text:
class AddLingualismsIndex < ActiveRecord::Migration[5.2]
  def change
    add_index :lingualisms, :spoken_language_id
  end
end


text:
import {cloneElement, useRef, useState} from 'react';
import {cleanup, fireEvent, render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
  FloatingFocusManager,
  FloatingNode,
  FloatingTree,
  useClick,
  useDismiss,
  useFloating,
  useFloatingNodeId,
  useFloatingParentNodeId,
  useInteractions,
  FloatingPortal,
} from '../../src';
import {Props} from '../../src/FloatingFocusManager';

function App(
  props: Partial<Omit<Props, 'initialFocus'> & {initialFocus?: 'two' | number}>
) {
  const ref = useRef<HTMLButtonElement | null>(null);
  const [open, setOpen] = useState(false);
  const {reference, floating, context} = useFloating({
    open,
    onOpenChange: setOpen,
  });

  return (
    <>
      <button
        data-testid="reference"
        ref={reference}
        onClick={() => setOpen(!open)}
      />
      {open && (
        <FloatingFocusManager
          {...props}
          initialFocus={props.initialFocus === 'two' ? ref : props.initialFocus}
          context={context}
        >

            <button data-testid="one">close</button>
            <button data-testid="two" ref={ref}>
              confirm
            </button>
            <button data-testid="three" onClick={() => setOpen(false)}>
              x
            </button>

        </FloatingFocusManager>
      )}
    </>
  );
}

describe('initialFocus', () => {
  test('number', () => {
    const {rerender} = render(<App />);

    fireEvent.click(screen.getByTestId('reference'));
    expect(screen.getByTestId('one')).toHaveFocus();

    rerender(<App initialFocus={1} />);
    expect(screen.getByTestId('two')).toHaveFocus();

    rerender(<App initialFocus={2} />);
    expect(screen.getByTestId('three')).toHaveFocus();

    cleanup();
  });

  test('ref', () => {
    render(<App initialFocus="two" />);
    fireEvent.click(screen.getByTestId('reference'));
    expect(screen.getByTestId('two')).toHaveFocus();

    cleanup();
  });
});

describe('returnFocus', () => {
  test('true', () => {
    render(<App />);

    screen.getByTestId('reference').focus();
    fireEvent.click(screen.getByTestId('reference'));
    expect(screen.getByTestId('one')).toHaveFocus();

    fireEvent.click(screen.getByTestId('three'));
    expect(screen.getByTestId('reference')).toHaveFocus();

    cleanup();
  });

  test('false', () => {
    render(<App returnFocus={false} />);

    screen.getByTestId('reference').focus();
    fireEvent.click(screen.getByTestId('reference'));
    expect(screen.getByTestId('one')).toHaveFocus();

    fireEvent.click(screen.getByTestId('three'));
    expect(screen.getByTestId('reference')).not.toHaveFocus();

    cleanup();
  });

  test('always returns to the reference for nested elements', async () => {
    interface Props {
      open?: boolean;
      render: (props: {close: () => void}) => React.ReactNode;
      children: JSX.Element;
    }

    const Dialog = ({render, open: passedOpen = false, children}: Props) => {
      const [open, setOpen] = useState(passedOpen);
      const nodeId = useFloatingNodeId();

      const {reference, floating, context} = useFloating({
        open,
        onOpenChange: setOpen,
        nodeId,
      });

      const {getReferenceProps, getFloatingProps} = useInteractions([
        useClick(context),
        useDismiss(context, {bubbles: false}),
      ]);

      return (
        <FloatingNode id={nodeId}>
          {cloneElement(
            children,
            getReferenceProps({ref: reference, ...children.props})
          )}
          <FloatingPortal>
            {open && (
              <FloatingFocusManager context={context}>

                  {render({
                    close: () => setOpen(false),
                  })}

              </FloatingFocusManager>
            )}
          </FloatingPortal>
        </FloatingNode>
      );
    };

    const NestedDialog: React.FC<Props> = (props) => {
      const parentId = useFloatingParentNodeId();

      if (parentId == null) {
        return (
          <FloatingTree>
            <Dialog {...props} />
          </FloatingTree>
        );
      }

      return <Dialog {...props} />;
    };

    render(
      <NestedDialog
        render={({close}) => (
          <>
            <NestedDialog
              render={({close}) => (
                <button onClick={close} data-testid="close-nested-dialog" />
              )}
            >
              <button data-testid="open-nested-dialog" />
            </NestedDialog>
            <button onClick={close} data-testid="close-dialog" />
          </>
        )}
      >
        <button data-testid="open-dialog" />
      </NestedDialog>
    );

    await userEvent.click(screen.getByTestId('open-dialog'));
    await userEvent.click(screen.getByTestId('open-nested-dialog'));

    expect(screen.queryByTestId('close-nested-dialog')).toBeInTheDocument();

    fireEvent.pointerDown(document.body);

    expect(screen.queryByTestId('close-nested-dialog')).not.toBeInTheDocument();

    fireEvent.pointerDown(document.body);

    expect(screen.queryByTestId('close-dialog')).not.toBeInTheDocument();
  });
});

describe('guards', () => {
  test('true', async () => {
    render(<App guards={true} />);

    fireEvent.click(screen.getByTestId('reference'));

    await userEvent.tab();
    await userEvent.tab();
    await userEvent.tab();

    expect(document.body).not.toHaveFocus();
  });

  test('false', async () => {
    render(<App guards={false} />);

    fireEvent.click(screen.getByTestId('reference'));

    await userEvent.tab();
    await userEvent.tab();
    await userEvent.tab();

    expect(document.body).toHaveFocus();
  });
});

describe('modal', () => {
  test('true', async () => {
    render(<App modal={true} />);

    fireEvent.click(screen.getByTestId('reference'));

    await userEvent.tab();
    expect(screen.getByTestId('two')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('three')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('one')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('three')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('two')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('one')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('three')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('one')).toHaveFocus();

    cleanup();
  });

  test('false', async () => {
    render(<App modal={false} />);

    fireEvent.click(screen.getByTestId('reference'));

    await userEvent.tab();
    expect(screen.getByTestId('two')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('three')).toHaveFocus();

    await userEvent.tab();

    // Focus leaving the floating element closes it.
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();

    cleanup();
  });

  test('false — shift tabbing does not trap focus when reference is in order', async () => {
    render(<App modal={false} order={['reference', 'content']} />);

    fireEvent.click(screen.getByTestId('reference'));

    await userEvent.tab();
    await userEvent.tab({shift: true});
    await userEvent.tab({shift: true});

    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();

    cleanup();
  });

  test('true - comboboxes hide all other nodes', async () => {
    function App() {
      const [open, setOpen] = useState(false);
      const {reference, floating, context} = useFloating({
        open,
        onOpenChange: setOpen,
      });

      return (
        <>
          <input
            role="combobox"
            data-testid="reference"
            ref={reference}
            onFocus={() => setOpen(true)}
          />
          <button data-testid="btn-1" />
          <button data-testid="btn-2" />
          {open && (
            <FloatingFocusManager
              context={context}
              modal={true}
              order={['reference']}
            >

            </FloatingFocusManager>
          )}
        </>
      );
    }

    render(<App />);

    fireEvent.focus(screen.getByTestId('reference'));
    expect(screen.getByTestId('reference')).not.toHaveAttribute('aria-hidden');
    expect(screen.getByTestId('floating')).not.toHaveAttribute('aria-hidden');
    expect(screen.getByTestId('btn-1')).toHaveAttribute('aria-hidden');
    expect(screen.getByTestId('btn-2')).toHaveAttribute('aria-hidden');

    cleanup();
  });

  test('false - comboboxes do not hide all other nodes', async () => {
    function App() {
      const [open, setOpen] = useState(false);
      const {reference, floating, context} = useFloating({
        open,
        onOpenChange: setOpen,
      });

      return (
        <>
          <input
            role="combobox"
            data-testid="reference"
            ref={reference}
            onFocus={() => setOpen(true)}
          />
          <button data-testid="btn-1" />
          <button data-testid="btn-2" />
          {open && (
            <FloatingFocusManager context={context} modal={false}>

            </FloatingFocusManager>
          )}
        </>
      );
    }

    render(<App />);

    fireEvent.focus(screen.getByTestId('reference'));
    expect(screen.getByTestId('reference')).not.toHaveAttribute('aria-hidden');
    expect(screen.getByTestId('floating')).not.toHaveAttribute('aria-hidden');
    expect(screen.getByTestId('btn-1')).not.toHaveAttribute('aria-hidden');
    expect(screen.getByTestId('btn-2')).not.toHaveAttribute('aria-hidden');

    cleanup();
  });
});

describe('order', () => {
  test('[reference, content]', async () => {
    render(<App order={['reference', 'content']} />);

    fireEvent.click(screen.getByTestId('reference'));
    expect(screen.getByTestId('reference')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('one')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('two')).toHaveFocus();

    cleanup();
  });

  test('[floating, content]', async () => {
    render(<App order={['floating', 'content']} />);

    fireEvent.click(screen.getByTestId('reference'));
    expect(screen.getByTestId('floating')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('one')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('two')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('three')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('floating')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('three')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('two')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('one')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('floating')).toHaveFocus();

    cleanup();
  });

  test('[reference, floating, content]', async () => {
    render(<App order={['reference', 'floating', 'content']} />);

    fireEvent.click(screen.getByTestId('reference'));

    expect(screen.getByTestId('reference')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('floating')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('one')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('two')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('three')).toHaveFocus();

    await userEvent.tab();
    expect(screen.getByTestId('reference')).toHaveFocus();

    await userEvent.tab({shift: true});
    expect(screen.getByTestId('three')).toHaveFocus();

    await userEvent.tab({shift: true});
    await userEvent.tab({shift: true});
    await userEvent.tab({shift: true});
    await userEvent.tab({shift: true});

    expect(screen.getByTestId('reference')).toHaveFocus();

    cleanup();
  });
});

describe('non-modal + FloatingPortal', () => {
  test('focuses inside element, tabbing out focuses last document element', async () => {
    function App() {
      const [open, setOpen] = useState(false);
      const {reference, floating, context} = useFloating({
        open,
        onOpenChange: setOpen,
      });

      return (
        <>

          <button
            data-testid="reference"
            ref={reference}
            onClick={() => setOpen(true)}
          />
          <FloatingPortal>
            {open && (
              <FloatingFocusManager context={context} modal={false}>

              </FloatingFocusManager>
            )}
          </FloatingPortal>

        </>
      );
    }

    render(<App />);

    await userEvent.click(screen.getByTestId('reference'));

    expect(screen.getByTestId('inside')).toHaveFocus();

    await userEvent.tab();

    expect(screen.queryByTestId('floating')).not.toBeInTheDocument();
    expect(screen.getByTestId('last')).toHaveFocus();

    cleanup();
  });

  test('order: [reference, content] focuses reference, then inside, then, last document element', async () => {
    function App() {
      const [open, setOpen] = useState(false);
      const {reference, floating, context} = useFloating({
        open,
        onOpenChange: setOpen,
      });

      return (
        <>

          <button
            data-testid="reference"
            ref={reference}
            onClick={() => setOpen(true)}
          />
          <FloatingPortal>
            {open && (
              <FloatingFocusManager
                context={context}
                modal={false}
                order={['reference', 'content']}
              >

              </FloatingFocusManager>
            )}
          </FloatingPortal>

        </>
      );
    }

    render(<App />);

    await userEvent.click(screen.getByTestId('reference'));

    await userEvent.tab();

    expect(screen.getByTestId('inside')).toHaveFocus();

    await userEvent.tab();

    expect(screen.queryByTestId('floating')).not.toBeInTheDocument();
    expect(screen.getByTestId('last')).toHaveFocus();

    cleanup();
  });

  test('order: [reference, floating, content] focuses reference, then inside, then, last document element', async () => {
    function App() {
      const [open, setOpen] = useState(false);
      const {reference, floating, context} = useFloating({
        open,
        onOpenChange: setOpen,
      });

      return (
        <>

          <button
            data-testid="reference"
            ref={reference}
            onClick={() => setOpen(true)}
          />
          <FloatingPortal>
            {open && (
              <FloatingFocusManager
                context={context}
                modal={false}
                order={['reference', 'floating', 'content']}
              >

              </FloatingFocusManager>
            )}
          </FloatingPortal>

        </>
      );
    }

    render(<App />);

    await userEvent.click(screen.getByTestId('reference'));

    await userEvent.tab();

    expect(screen.getByTestId('floating')).toHaveFocus();

    await userEvent.tab();

    expect(screen.getByTestId('inside')).toHaveFocus();

    await userEvent.tab();

    expect(screen.queryByTestId('floating')).not.toBeInTheDocument();
    expect(screen.getByTestId('last')).toHaveFocus();

    cleanup();
  });

  test('shift+tab', async () => {
    function App() {
      const [open, setOpen] = useState(false);
      const {reference, floating, context} = useFloating({
        open,
        onOpenChange: setOpen,
      });

      return (
        <>

          <button
            data-testid="reference"
            ref={reference}
            onClick={() => setOpen(true)}
          />
          <FloatingPortal>
            {open && (
              <FloatingFocusManager context={context} modal={false}>

              </FloatingFocusManager>
            )}
          </FloatingPortal>

        </>
      );
    }

    render(<App />);

    await userEvent.click(screen.getByTestId('reference'));
    await userEvent.tab({shift: true});

    expect(screen.queryByTestId('floating')).toBeInTheDocument();

    await userEvent.tab({shift: true});

    expect(screen.queryByTestId('floating')).not.toBeInTheDocument();

    cleanup();
  });
});

redpajama_set_name: RedPajamaGithub


text:
/* eslint-disable import/no-unresolved */
import React, { PropTypes } from 'react';
import { analytics } from '../../config';
import Helmet from 'react-helmet';
/* global ga */
/* eslint-disable prefer-rest-params */

function Html(props) {
    const head = Helmet.rewind();
    return (
        <html className="no-js" lang="">
            <head>
                {head.base.toComponent()}
                {head.title.toComponent()}
                {head.meta.toComponent()}

                {/* Chrome for Android theme color */}
                <meta name="theme-color" content="#373277" />

                {/* Tile color for Win8 */}
                <meta name="msapplication-TileColor" content="#373277" />

                {/* Web Application Manifest */}
                <link rel="manifest" href="manifest.json" />

                {/* Add to homescreen for Chrome on Android */}
                <meta name="mobile-web-app-capable" content="yes" />
                <meta name="application-name" content="React Starter Kit" />
                <link rel="icon" sizes="192x192" href="touch/chrome-touch-icon-192x192.png" />

                {/* Add to homescreen for Safari on iOS */}
                <meta name="apple-mobile-web-app-capable" content="yes" />
                <meta name="apple-mobile-web-app-status-bar-style" content="black" />
                <meta name="apple-mobile-web-app-title" content="React Starter Kit" />
                <link rel="apple-touch-icon" href="touch/apple-touch-icon.png" />

                {/* Tile icon for Win8 (144x144) */}
                <meta name="msapplication-TileImage" content="touch/ms-touch-icon-144x144-precomposed.png" />

                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="apple-touch-icon" href="apple-touch-icon.png" />

                <style id="css" dangerouslySetInnerHTML={{ __html: props.css }}></style>
            </head>
            <body>
                <div id="container" dangerouslySetInnerHTML={{ __html: props.children }} />
                <script
                    id="source"
                    src={props.script}
                    async defer />
                {
                process.env.NODE_ENV === 'production' &&
                    <script dangerouslySetInnerHTML={{ __html:
                            'window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;' +
                            `ga('create','${analytics.google.trackingId}','auto');` }} />
                }
                {
                process.env.NODE_ENV === 'production' &&
                    <script
                        src="https://www.google-analytics.com/analytics.js"
                        async defer />
                }
            </body>
        </html>
    );
}

Html.propTypes = {
    css: PropTypes.string.isRequired,
    children: PropTypes.string.isRequired,
    script: PropTypes.string,
};

export default Html;


text:
package nl.eernie.jmoribus;

import nl.eernie.jmoribus.annotation.Given;
import nl.eernie.jmoribus.annotation.Then;
import nl.eernie.jmoribus.annotation.When;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class SeleniumSteps
{

	@Given("the method has a Webdriver in the signature")
	public void webDriverMethod(WebDriver driver)
	{
		Assert.assertNotNull(driver);
	}

	@Given("the method has a WebDriver and more vars in the $signature")
	public void webDriverMethod(WebDriver driver, String var)
	{
		Assert.assertNotNull(driver);
		Assert.assertEquals("signature", var);
	}

	@When("the user navigates to $url")
	public void navigate(WebDriver driver, String url)
	{
		driver.navigate().to("http://" + url);
	}

	@Then("the pagetop should be available")
	public void assertPageTop(WebDriver driver)
	{
		WebElement pagetop = driver.findElement(By.className("pagetop"));
		Assert.assertEquals("span", pagetop.getTagName());
	}

	@Then("the user closes the browser")
	public void closeDriver(WebDriver driver)
	{
		driver.close();
	}
}


text:
import unittest
from logging import getLogger

class TestOneLoggerTest(unittest.TestCase):
    def setUp(self):
        self.__lg = getLogger('infra.run')
        super(TestOneLoggerTest, self).setUp()

    def test_single_log_to_run(self):
        self.__lg.warning('test_single_log_to_run')


text:
#ifndef __CCPhysicsDebugNode_h__
#define __CCPhysicsDebugNode_h__

#include "../ExtensionMacros.h"
#include "../../2d/draw_nodes/CCDrawNode.h"
#include "XMChipmunk/chipmunk.h"

NS_CC_EXT_BEGIN

/**
 *	A BaseData that draws the components of a physics engine.
 *
 *	Supported physics engines:
 *		- Chipmunk
 *		- Objective-Chipmunk
 *
 *	@since v2.1
 */

class PhysicsDebugNode : public DrawNode
{
	public :

		/** Create a debug node for a regular Chipmunk space. */
		static PhysicsDebugNode*	create ( cpSpace* pSpace );

		/**
		 *	@js ctor
		 */
		PhysicsDebugNode ( KDvoid );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual ~PhysicsDebugNode ( KDvoid );

		cpSpace*					getSpace ( KDvoid ) const;
		KDvoid						setSpace ( cpSpace* pSpace );

		// Overrides
		virtual KDvoid				draw ( KDvoid ) override;

	protected :

		cpSpace*					m_pSpacePtr;
};

NS_CC_EXT_END

#endif	// __CCPhysicsDebugNode_h__


text:
package loon.html5.gwt.widgets;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;

@SuppressWarnings("deprecation")
public class ProgressBar extends Widget implements ResizableWidget {

	private static final String DEFAULT_TEXT_CLASS_NAME = "gwt-ProgressBar-text";

	private String textClassName = DEFAULT_TEXT_CLASS_NAME;
	private String textFirstHalfClassName = DEFAULT_TEXT_CLASS_NAME
			+ "-firstHalf";
	private String textSecondHalfClassName = DEFAULT_TEXT_CLASS_NAME
			+ "-secondHalf";

	public abstract static class TextFormatter {

		protected abstract String getText(ProgressBar bar, double curProgress);
	}

	private Element barElement;

	private double curProgress;

	private double maxProgress;

	private double minProgress;

	private boolean textVisible = true;

	private Element textElement;

	private TextFormatter textFormatter;

	public ProgressBar() {
		this(0.0, 100.0, 0.0);
	}

	public ProgressBar(double curProgress) {
		this(0.0, 100.0, curProgress);
	}

	public ProgressBar(double minProgress, double maxProgress) {
		this(minProgress, maxProgress, 0.0);
	}

	public ProgressBar(double minProgress, double maxProgress,
			double curProgress) {
		this(minProgress, maxProgress, curProgress, null);
	}

	public ProgressBar(double minProgress, double maxProgress,
			double curProgress, TextFormatter textFormatter) {
		this.minProgress = minProgress;
		this.maxProgress = maxProgress;
		this.curProgress = curProgress;
		setTextFormatter(textFormatter);

		setElement(DOM.createDiv());
		DOM.setStyleAttribute(getElement(), "position", "relative");
		setStyleName("gwt-ProgressBar-shell");

		barElement = DOM.createDiv();
		DOM.appendChild(getElement(), barElement);
		DOM.setStyleAttribute(barElement, "height", "100%");
		setBarStyleName("gwt-ProgressBar-bar");

		textElement = DOM.createDiv();
		DOM.appendChild(getElement(), textElement);
		DOM.setStyleAttribute(textElement, "position", "absolute");
		DOM.setStyleAttribute(textElement, "top", "0px");

		setProgress(curProgress);
	}

	public double getMaxProgress() {
		return maxProgress;
	}

	public double getMinProgress() {
		return minProgress;
	}

	public double getPercent() {
		if (maxProgress <= minProgress) {
			return 0.0;
		}
		double percent = (curProgress - minProgress)
				/ (maxProgress - minProgress);
		return Math.max(0.0, Math.min(1.0, percent));
	}

	public double getProgress() {
		return curProgress;
	}

	public TextFormatter getTextFormatter() {
		return textFormatter;
	}

	public boolean isTextVisible() {
		return textVisible;
	}

	public void onResize(int width, int height) {
		if (textVisible) {
			int textWidth = DOM.getElementPropertyInt(textElement,
					"offsetWidth");
			int left = (width / 2) - (textWidth / 2);
			DOM.setStyleAttribute(textElement, "left", left + "px");
		}
	}

	public void redraw() {
		if (isAttached()) {
			int width = DOM.getElementPropertyInt(getElement(), "clientWidth");
			int height = DOM
					.getElementPropertyInt(getElement(), "clientHeight");
			onResize(width, height);
		}
	}

	public void setBarStyleName(String barClassName) {
		DOM.setElementProperty(barElement, "className", barClassName);
	}

	public void setMaxProgress(double maxProgress) {
		this.maxProgress = maxProgress;
		curProgress = Math.min(curProgress, maxProgress);
		resetProgress();
	}

	public void setMinProgress(double minProgress) {
		this.minProgress = minProgress;
		curProgress = Math.max(curProgress, minProgress);
		resetProgress();
	}

	public void setProgress(double curProgress) {
		this.curProgress = Math.max(minProgress,
				Math.min(maxProgress, curProgress));
		int percent = (int) (100 * getPercent());
		DOM.setStyleAttribute(barElement, "width", percent + "%");
		DOM.setElementProperty(textElement, "innerHTML",
				generateText(curProgress));
		updateTextStyle(percent);
		redraw();
	}

	public void setTextFirstHalfStyleName(String textFirstHalfClassName) {
		this.textFirstHalfClassName = textFirstHalfClassName;
		onTextStyleChange();
	}

	public void setTextFormatter(TextFormatter textFormatter) {
		this.textFormatter = textFormatter;
	}

	public void setTextSecondHalfStyleName(String textSecondHalfClassName) {
		this.textSecondHalfClassName = textSecondHalfClassName;
		onTextStyleChange();
	}

	public void setTextStyleName(String textClassName) {
		this.textClassName = textClassName;
		onTextStyleChange();
	}

	public void setTextVisible(boolean textVisible) {
		this.textVisible = textVisible;
		if (this.textVisible) {
			DOM.setStyleAttribute(textElement, "display", "");
			redraw();
		} else {
			DOM.setStyleAttribute(textElement, "display", "none");
		}
	}

	protected String generateText(double curProgress) {
		if (textFormatter != null) {
			return textFormatter.getText(this, curProgress);
		} else {
			return (int) (100 * getPercent()) + "%";
		}
	}

	protected Element getBarElement() {
		return barElement;
	}

	protected Element getTextElement() {
		return textElement;
	}

	@Override
	protected void onLoad() {
		DOM.setStyleAttribute(getElement(), "position", "relative");
		ResizableWidgetCollection.get().add(this);
		redraw();
	}

	@Override
	protected void onUnload() {
		ResizableWidgetCollection.get().remove(this);
	}

	protected void resetProgress() {
		setProgress(getProgress());
	}

	private void onTextStyleChange() {
		int percent = (int) (100 * getPercent());
		updateTextStyle(percent);
	}

	private void updateTextStyle(int percent) {
		if (percent < 50) {
			DOM.setElementProperty(textElement, "className", textClassName
					+ " " + textFirstHalfClassName);
		} else {
			DOM.setElementProperty(textElement, "className", textClassName
					+ " " + textSecondHalfClassName);
		}
	}
}


text:
'use strict';

let chai = require('chai');
let chaiHttp = require('chai-http');
let config = require(__dirname + '/../config/env.js');
config.MONGOLAB_URI='mongodb://localhost/db';
require(__dirname + '/../server.js');

chai.use(chaiHttp);
let request = chai.request;
let expect = chai.expect;

let userId;
let userToken;

let userJSON = {
  username: 'codequizzer',
  password: 'winner'
};

describe('test /signup route', () => {
  after((done) => {
    request('localhost:' + config.PORT)
      .delete('/api/users/' + userId)
      .set('token', userToken)
      .end((err, res) => {
        expect(err).to.equal(null);
        expect(res).to.have.status(200);
        expect(res).to.be.json;
        expect(res.body).to.have.property('message');
        expect(res.body.data).to.have.property('_id');
        expect(res.body.data).to.have.property('username');
        expect(res.body.data).to.have.property('password');
        expect(res.body.message).to.equal('Deleted User');
        expect(res.body.data._id).to.not.equal(null);
        expect(res.body.data.username).to.equal('codequizzer');
        expect(res.body.data.password).to.not.equal(null);
        done();
      });
  });

  it('should respond to POST /signup', (done) => {
    request('localhost:' + config.PORT)
      .post('/signup')
      .send(userJSON)
      .end((err, res) => {
        userId = res.body.data._id;
        userToken = res.body.token;
        expect(err).to.equal(null);
        expect(res).to.have.status(200);
        expect(res).to.be.json;
        expect(res.body).to.have.property('token');
        expect(res.body.data).to.have.property('username');
        expect(res.body.data).to.have.property('password');
        expect(res.body.token).to.not.equal(null);
        expect(res.body.data.username).to.equal('codequizzer');
        expect(res.body.data.password).to.not.equal(null);
        done();
      });
  });
});

describe('test /login route', () => {
  before((done) => {
    request('localhost:' + config.PORT)
      .post('/signup')
      .send(userJSON)
      .end((err, res) => {
        userId = res.body.data._id;
        userToken = res.body.token;
        expect(err).to.equal(null);
        expect(res).to.have.status(200);
        expect(res).to.be.json;
        expect(res.body).to.have.property('token');
        expect(res.body.data).to.have.property('username');
        expect(res.body.data).to.have.property('password');
        expect(res.body.token).to.not.equal(null);
        expect(res.body.data.username).to.equal('codequizzer');
        expect(res.body.data.password).to.not.equal(null);
        done();
      });
  });

  after((done) => {
    request('localhost:' + config.PORT)
      .delete('/api/users/' + userId)
      .set('token', userToken)
      .end((err, res) => {
        expect(err).to.equal(null);
        expect(res).to.have.status(200);
        expect(res).to.be.json;
        expect(res.body).to.have.property('message');
        expect(res.body.data).to.have.property('_id');
        expect(res.body.data).to.have.property('username');
        expect(res.body.data).to.have.property('password');
        expect(res.body.message).to.equal('Deleted User');
        expect(res.body.data._id).to.not.equal(null);
        expect(res.body.data.username).to.equal('codequizzer');
        expect(res.body.data.password).to.not.equal(null);
        done();
      });
  });

  it('should respond to POST /login', (done) => {
    request('localhost:' + config.PORT)
      .post('/login')
      .auth(userJSON.username, userJSON.password)
      .end((err, res) => {
        expect(err).to.equal(null);
        expect(res).to.have.status(200);
        expect(res).to.be.json;
        expect(res.body).to.have.property('token');
        expect(res.body.data).to.have.property('username');
        expect(res.body.data).to.have.property('password');
        expect(res.body.token).to.not.equal(null);
        expect(res.body.data.username).to.equal('codequizzer');
        expect(res.body.data.password).to.not.equal(null);
        done();
      });
  });

  it('should respond to POST /signup with existing username', (done) => {
    request('localhost:' + config.PORT)
      .post('/signup')
      .send(userJSON)
      .end((err, res) => {
        expect(err).to.equal(null);
        expect(res).to.have.status(200);
        expect(res).to.be.json;
        expect(res.body).to.have.property('message');
        expect(res.body.message).to.equal('User Already Exists');
        done();
      });
  });
});


text:
<?php

namespace ContainerFelbUiK;

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;

/**
 * @internal This class has been auto-generated by the Symfony Dependency Injection Component.
 */
class getSecurity_EncoderFactory_GenericService extends App_KernelDevDebugContainer
{
    /**
     * Gets the private 'security.encoder_factory.generic' shared service.
     *
     * @return \Symfony\Component\Security\Core\Encoder\EncoderFactory
     */
    public static function do($container, $lazyLoad = true)
    {
        include_once \dirname(__DIR__, 4).'/vendor/symfony/security-core/Encoder/EncoderFactoryInterface.php';
        include_once \dirname(__DIR__, 4).'/vendor/symfony/security-core/Encoder/EncoderFactory.php';

        return $container->privates['security.encoder_factory.generic'] = new \Symfony\Component\Security\Core\Encoder\EncoderFactory(['App\\Entity\\User' => ['algorithm' => 'auto', 'migrate_from' => [], 'hash_algorithm' => 'sha512', 'key_length' => 40, 'ignore_case' => false, 'encode_as_base64' => true, 'iterations' => 5000, 'cost' => NULL, 'memory_cost' => NULL, 'time_cost' => NULL]]);
    }
}


text:
#include "internal.h"

#if KSI_DISABLE_NET_PROVIDER & KSI_IMPL_NET_TCP

int KSI_TcpClient_new(KSI_CTX *ctx, KSI_NetworkClient **client) {
	return KSI_NETWORK_PROVIDER_DISABLED;
}
int KSI_TcpClient_setPublicationUrl(KSI_NetworkClient *client, const char *val) {
	return KSI_NETWORK_PROVIDER_DISABLED;
}
int KSI_TcpClient_setExtender(KSI_NetworkClient *client, const char *host, unsigned port, const char *user, const char *key){
	return KSI_NETWORK_PROVIDER_DISABLED;
}
int KSI_TcpClient_setAggregator(KSI_NetworkClient *client, const char *host, unsigned port, const char *user, const char *key){
	return KSI_NETWORK_PROVIDER_DISABLED;
}
int KSI_TcpClient_setTransferTimeoutSeconds(KSI_NetworkClient *client, int val){
	return KSI_NETWORK_PROVIDER_DISABLED;
}

#else

#include <string.h>
#include <sys/types.h>

#include "net_tcp.h"
#include "io.h"
#include "tlv.h"
#include "fast_tlv.h"

#include "impl/ctx_impl.h"
#include "impl/net_http_impl.h"
#include "impl/net_tcp_impl.h"
#include "impl/net_sock_impl.h"

typedef struct TcpClient_Endpoint_st TcpClientCtx, TcpClient_Endpoint;

static int TcpClient_Endpoint_new(TcpClient_Endpoint **t) {
	TcpClient_Endpoint *tmp = NULL;
	if (t == NULL) return KSI_INVALID_ARGUMENT;

	tmp = KSI_new(TcpClient_Endpoint);
	if (tmp == NULL) return KSI_OUT_OF_MEMORY;

	tmp->host = NULL;
	tmp->port = 0;

	*t = tmp;
	return KSI_OK;
}

static void TcpClientCtx_free(TcpClientCtx *t) {
	if (t != NULL) {
		KSI_free(t->host);
		KSI_free(t);
	}
}

#define TcpClient_Endpoint_free TcpClientCtx_free

static int readResponse(KSI_RequestHandle *handle) {
	int res;
	TcpClientCtx *tcp = NULL;
	KSI_TcpClient *client = NULL;
	int sockfd = -1;
	struct addrinfo hints;
	struct addrinfo *result = NULL;
	struct addrinfo *pr = NULL;
	size_t count;
	unsigned char buffer[0xffff + 4];
	KSI_FTLV ftlv;
#ifdef _WIN32
	DWORD transferTimeout = 0;
#else
	struct timeval  transferTimeout;
#endif
	char portStr[6];
	int rc;

	if (handle == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	KSI_ERR_clearErrors(handle->ctx);

#ifdef _WIN32
	if (handle->request_length > INT_MAX) {
		KSI_pushError(handle->ctx, res = KSI_BUFFER_OVERFLOW, "Unable to send more than MAX_INT bytes.");
		goto cleanup;
	}
#endif

	tcp = handle->implCtx;
	client = handle->client->impl;

	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = 0;
	hints.ai_protocol = IPPROTO_TCP;

	KSI_snprintf(portStr, sizeof(portStr), "%u", tcp->port);
	if ((res = getaddrinfo(tcp->host, portStr, &hints, &result)) != 0) {
		KSI_ERR_push(handle->ctx, KSI_NETWORK_ERROR, res, __FILE__, __LINE__, gai_strerror(res));
		res = KSI_NETWORK_ERROR;
		goto cleanup;
	}

	for (pr = result; pr != NULL; pr = pr->ai_next) {
		if (pr->ai_protocol != IPPROTO_TCP) continue;

		sockfd = (int)socket(pr->ai_family, pr->ai_socktype, pr->ai_protocol);
		if (sockfd < 0) {
			KSI_pushError(handle->ctx, res = KSI_NETWORK_ERROR, "Unable to open socket.");
			goto cleanup;
		}

#ifdef _WIN32
		transferTimeout = client->transferTimeoutSeconds * 1000;
#else
		transferTimeout.tv_sec = client->transferTimeoutSeconds;
		transferTimeout.tv_usec = 0;
#endif

		/* Set socket options. */
		setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (void*)&transferTimeout, sizeof(transferTimeout));
		setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (void*)&transferTimeout, sizeof(transferTimeout));

#ifdef _WIN32
		KSI_SCK_TEMP_FAILURE_RETRY(rc, connect(sockfd, pr->ai_addr, (int)pr->ai_addrlen));
#else
		KSI_SCK_TEMP_FAILURE_RETRY(rc, connect(sockfd, pr->ai_addr, pr->ai_addrlen));
#endif
		if (rc == KSI_SCK_SOCKET_ERROR) {
			KSI_ERR_push(handle->ctx, res = KSI_NETWORK_ERROR, KSI_SCK_errno, __FILE__, __LINE__, "Unable to connect.");
			goto cleanup;
		}
		/* Succeedded to connect. */
		break;
	}
	if (pr == NULL) {
		KSI_pushError(handle->ctx, res = KSI_NETWORK_ERROR, "Unable to connect, no address succeeded.");
		goto cleanup;
	}

	KSI_LOG_logBlob(handle->ctx, KSI_LOG_DEBUG, "Sending request", handle->request, handle->request_length);
	count = 0;
	while (count < handle->request_length) {
		int c;

#ifdef _WIN32
		KSI_SCK_TEMP_FAILURE_RETRY(c, send(sockfd, (char *) handle->request + count, (int)(handle->request_length - count), 0));
#else
		KSI_SCK_TEMP_FAILURE_RETRY(c, send(sockfd, (char *) handle->request + count, handle->request_length - count, 0));
#endif
		if (c == KSI_SCK_SOCKET_ERROR) {
			KSI_ERR_push(handle->ctx, res = KSI_NETWORK_ERROR, KSI_SCK_errno, __FILE__, __LINE__, "Unable to write to socket.");
			goto cleanup;
		}
		count += c;
	}

	res = KSI_FTLV_socketRead(sockfd, buffer, sizeof(buffer), &count, &ftlv);
	if (res != KSI_OK) {
		KSI_pushError(handle->ctx, res, "Failed to read TLV from socket.");
		goto cleanup;
	}
	if (count == 0) {
		KSI_pushError(handle->ctx, res = KSI_INVALID_FORMAT, "Unable to read TLV from socket.");
		goto cleanup;
	} else if(count > UINT_MAX){
		KSI_pushError(handle->ctx, res = KSI_BUFFER_OVERFLOW, "Too much data read from socket.");
		goto cleanup;
	}

	handle->response = KSI_malloc(count);
	if (handle->response == NULL) {
		KSI_pushError(handle->ctx, res = KSI_OUT_OF_MEMORY, NULL);
		goto cleanup;
	}
	memcpy(handle->response, buffer, count);
	handle->response_length = count;

	handle->completed = true;

	res = KSI_OK;

cleanup:
	if (result) freeaddrinfo(result);
	if (sockfd >= 0) {
		KSI_SCK_TEMP_FAILURE_RETRY(rc, close(sockfd));
		if (rc == KSI_SCK_SOCKET_ERROR) {
			KSI_ERR_push(handle->ctx, res = KSI_IO_ERROR, KSI_SCK_errno, __FILE__, __LINE__, "Unable to close socket.");
		}
	}

	return res;
}

static int sendRequest(KSI_NetworkClient *client, KSI_RequestHandle *handle, char *host, unsigned port) {
	int res;
	TcpClientCtx *tc = NULL;

	if (handle == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	KSI_ERR_clearErrors(handle->ctx);

	if (client == NULL || host == NULL) {
		KSI_pushError(handle->ctx, res = KSI_INVALID_ARGUMENT, NULL);
		goto cleanup;
	}

	tc = KSI_new(TcpClientCtx);
	if (tc == NULL) {
		KSI_pushError(handle->ctx, res = KSI_OUT_OF_MEMORY, NULL);
		goto cleanup;
	}
	tc->host = NULL;
	tc->port = 0;

	KSI_LOG_debug(handle->ctx, "Tcp: Sending request to: %s:%u", host, port);

	res = KSI_strdup(host, &tc->host);
	if (res != KSI_OK) {
		KSI_pushError(handle->ctx, res, NULL);
		goto cleanup;
	}
	tc->port = port;

	handle->readResponse = readResponse;
	handle->client = client;

	res = KSI_RequestHandle_setImplContext(handle, tc, (void (*)(void *))TcpClientCtx_free);
	if (res != KSI_OK) {
		KSI_pushError(handle->ctx, res, NULL);
		goto cleanup;
	}

	tc = NULL;

	res = KSI_OK;

cleanup:

	TcpClientCtx_free(tc);

	return res;
}

static int prepareRequest(
		KSI_NetworkClient *client,
		void *pdu,
		int (*serialize)(void *, unsigned char **, size_t *),
		KSI_RequestHandle **handle,
		char *host,
		unsigned port,
		const char *desc) {
	int res;
	KSI_TcpClient *tcp = client->impl;
	KSI_RequestHandle *tmp = NULL;
	unsigned char *raw = NULL;
	size_t raw_len = 0;

	if (client->ctx == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	KSI_ERR_clearErrors(client->ctx);

	if (pdu == NULL || handle == NULL) {
		KSI_pushError(client->ctx, res = KSI_INVALID_ARGUMENT, NULL);
		goto cleanup;
	}

	res = serialize(pdu, &raw, &raw_len);
	if (res != KSI_OK) {
		KSI_pushError(client->ctx, res, NULL);
		goto cleanup;
	}
	KSI_LOG_logBlob(client->ctx, KSI_LOG_DEBUG, "%s", raw, raw_len, desc);

	/* Create a new request handle. */
	res = KSI_RequestHandle_new(client->ctx, raw, raw_len, &tmp);
	if (res != KSI_OK) {
		KSI_pushError(client->ctx, res, NULL);
		goto cleanup;
	}

	if (tcp->sendRequest == NULL) {
		KSI_pushError(client->ctx, res = KSI_UNKNOWN_ERROR, "Send request not initialized.");
		goto cleanup;
	}

	res = tcp->sendRequest(client, tmp, host, port);
	if (res != KSI_OK) {
		KSI_pushError(client->ctx, res, NULL);
		goto cleanup;
	}

	*handle = tmp;
	tmp = NULL;

	res = KSI_OK;

cleanup:

	KSI_RequestHandle_free(tmp);
	KSI_free(raw);

	return res;
}

static int prepareExtendRequest(KSI_NetworkClient *client, KSI_ExtendReq *req, KSI_RequestHandle **handle) {
	int res = KSI_UNKNOWN_ERROR;
	KSI_ExtendPdu *pdu = NULL;
	KSI_Integer *pReqId = NULL;
	KSI_Integer *reqId = NULL;
	TcpClient_Endpoint *endp = NULL;
	KSI_NetEndpoint *ext = NULL;
	KSI_ExtendReq *reqRef = NULL;

	if (client == NULL || req == NULL || handle == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	ext = client->extender;
	if (ext == NULL) {
		res = KSI_AGGREGATOR_NOT_CONFIGURED;
		goto cleanup;
	}
	endp = ext->implCtx;
	if (endp == NULL || endp->host == NULL || endp->port == 0) {
		res = KSI_AGGREGATOR_NOT_CONFIGURED;
		goto cleanup;
	}

	res = KSI_ExtendReq_getRequestId(req, &pReqId);
	if (res != KSI_OK) goto cleanup;

	if (pReqId == NULL) {
		res = KSI_Integer_new(client->ctx, ++client->requestCount, &reqId);
		if (res != KSI_OK) goto cleanup;

		res = KSI_ExtendReq_setRequestId(req, reqId);
		if (res != KSI_OK) goto cleanup;

		reqId = NULL;
	}

	res = KSI_ExtendReq_enclose((reqRef = KSI_ExtendReq_ref(req)), ext->ksi_user, ext->ksi_pass, &pdu);
	if (res != KSI_OK) {
		KSI_ExtendReq_free(reqRef);
		goto cleanup;
	}

	res = prepareRequest(
			client,
			pdu,
			(int (*)(void *, unsigned char **, size_t *))KSI_ExtendPdu_serialize,
			handle,
			endp->host,
			endp->port,
			"Extend request");
	if (res != KSI_OK) goto cleanup;

	(*handle)->reqCtx = (void*)KSI_ExtendReq_ref(req);
	(*handle)->reqCtx_free = (void (*)(void *))KSI_ExtendReq_free;

	res = KSI_OK;

cleanup:
	KSI_Integer_free(reqId);
	KSI_ExtendPdu_free(pdu);

	return res;
}

static int prepareAggregationRequest(KSI_NetworkClient *client, KSI_AggregationReq *req, KSI_RequestHandle **handle) {
	int res = KSI_UNKNOWN_ERROR;
	KSI_AggregationPdu *pdu = NULL;
	KSI_Integer *pReqId = NULL;
	KSI_Integer *reqId = NULL;
	TcpClient_Endpoint *endp = NULL;
	KSI_NetEndpoint *aggr = NULL;
	KSI_AggregationReq *reqRef = NULL;

	if (client == NULL || req == NULL || handle == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	aggr = client->aggregator;
	if (aggr == NULL) {
		res = KSI_AGGREGATOR_NOT_CONFIGURED;
		goto cleanup;
	}
	endp = aggr->implCtx;
	if (endp == NULL || endp->host == NULL || endp->port == 0) {
		res = KSI_AGGREGATOR_NOT_CONFIGURED;
		goto cleanup;
	}

	res = KSI_AggregationReq_getRequestId(req, &pReqId);
	if (res != KSI_OK) goto cleanup;

	if (pReqId == NULL) {
		res = KSI_Integer_new(client->ctx, ++client->requestCount, &reqId);
		if (res != KSI_OK) goto cleanup;

		res = KSI_AggregationReq_setRequestId(req, reqId);
		if (res != KSI_OK) goto cleanup;

		reqId = NULL;
	}

	res = KSI_AggregationReq_enclose((reqRef = KSI_AggregationReq_ref(req)), aggr->ksi_user, aggr->ksi_pass, &pdu);
	if (res != KSI_OK) {
		KSI_AggregationReq_free(reqRef);
		goto cleanup;
	}

	res = prepareRequest(
			client,
			pdu,
			(int (*)(void *, unsigned char **, size_t *))KSI_AggregationPdu_serialize,
			handle,
			endp->host,
			endp->port,
			"Aggregation request");
	if (res != KSI_OK) goto cleanup;

	(*handle)->reqCtx = (void*)KSI_AggregationReq_ref(req);
	(*handle)->reqCtx_free = (void (*)(void *))KSI_AggregationReq_free;

	res = KSI_OK;

cleanup:

	KSI_Integer_free(reqId);
	KSI_AggregationPdu_free(pdu);

	return res;
}

static int sendPublicationRequest(KSI_NetworkClient *client, KSI_RequestHandle **handle) {
	int res;
	KSI_TcpClient *tcpClient = client->impl;

	res = KSI_NetworkClient_sendPublicationsFileRequest(tcpClient->http, handle);
	if (res != KSI_OK) goto cleanup;

	res = KSI_OK;

cleanup:

	return res;
}

static void tcpClient_free(KSI_TcpClient *tcp) {
	if (tcp != NULL) {
		KSI_NetworkClient_free(tcp->http);
		KSI_free(tcp);
	}
}

/**
 *
 */
int KSI_TcpClient_new(KSI_CTX *ctx, KSI_NetworkClient **tcp) {
	int res;
	KSI_NetworkClient *tmp = NULL;
	KSI_TcpClient *t = NULL;
	TcpClient_Endpoint *endp_aggr = NULL;
	TcpClient_Endpoint *endp_ext = NULL;
	TcpClient_Endpoint *endp_pub = NULL;

	KSI_ERR_clearErrors(ctx);

	if (ctx == NULL || tcp == NULL) {
		KSI_pushError(ctx, res = KSI_INVALID_ARGUMENT, NULL);
		goto cleanup;
	}

	res = KSI_AbstractNetworkClient_new(ctx, &tmp);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;

	}

	t = KSI_new(KSI_TcpClient);
	if (t == NULL) {
		KSI_pushError(ctx, res = KSI_OUT_OF_MEMORY, NULL);
		goto cleanup;
	}

	t->sendRequest = sendRequest;
	t->transferTimeoutSeconds = 10;
	t->http = NULL;

#if !(KSI_DISABLE_NET_PROVIDER & KSI_IMPL_NET_HTTP)
	res = KSI_HttpClient_new(ctx, &t->http);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}
#endif /* KSI_DISABLE_NET_PROVIDER */

	/* Create implementations for abstract endpoints. */
	res = TcpClient_Endpoint_new(&endp_aggr);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}

	res = TcpClient_Endpoint_new(&endp_ext);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}

	res = TcpClient_Endpoint_new(&endp_pub);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}

	/* Set implementations for abstract endpoints. */
	res = KSI_NetEndpoint_setImplContext(tmp->aggregator, endp_aggr, (void (*)(void*))TcpClient_Endpoint_free);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}
	endp_aggr = NULL;

	res = KSI_NetEndpoint_setImplContext(tmp->extender, endp_ext, (void (*)(void*))TcpClient_Endpoint_free);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}
	endp_ext = NULL;

	res = KSI_NetEndpoint_setImplContext(tmp->publicationsFile, endp_pub, (void (*)(void*))TcpClient_Endpoint_free);
	if (res != KSI_OK) {
		KSI_pushError(ctx, res, NULL);
		goto cleanup;
	}
	endp_pub = NULL;

	tmp->sendExtendRequest = prepareExtendRequest;
	tmp->sendSignRequest = prepareAggregationRequest;
	tmp->sendPublicationRequest = sendPublicationRequest;
	tmp->implFree = (void (*)(void *))tcpClient_free;
	tmp->requestCount = 0;

	tmp->impl = t;
	t = NULL;

	*tcp = tmp;
	tmp = NULL;

	res = KSI_OK;

cleanup:

	tcpClient_free(t);
	KSI_NetworkClient_free(tmp);
	TcpClient_Endpoint_free(endp_aggr);
	TcpClient_Endpoint_free(endp_ext);
	TcpClient_Endpoint_free(endp_pub);

	return res;
}

static int ksi_TcpClient_setService(KSI_NetworkClient *client, KSI_NetEndpoint *abs_endp, const char *host, unsigned port, const char *user, const char *pass) {
	int res = KSI_UNKNOWN_ERROR;
	TcpClient_Endpoint *endp = NULL;

	if (abs_endp == NULL || host == NULL || user == NULL || pass == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	endp = abs_endp->implCtx;

	res = client->setStringParam(&endp->host, host);
	if (res != KSI_OK) goto cleanup;

	endp->port = port;

	res = client->setStringParam(&abs_endp->ksi_user, user);
	if (res != KSI_OK) goto cleanup;

	res = client->setStringParam(&abs_endp->ksi_pass, pass);
	if (res != KSI_OK) goto cleanup;

	res = KSI_OK;

cleanup:

	return res;
}

int KSI_TcpClient_setExtender(KSI_NetworkClient *client, const char *host, unsigned port, const char *user, const char *pass) {
	if (client == NULL || client->extender == NULL) return KSI_INVALID_ARGUMENT;
	return ksi_TcpClient_setService(client, client->extender, host, port, user, pass);
}

int KSI_TcpClient_setAggregator(KSI_NetworkClient *client, const char *host, unsigned port, const char *user, const char *pass) {
	if (client == NULL || client->aggregator == NULL) return KSI_INVALID_ARGUMENT;
	return ksi_TcpClient_setService(client, client->aggregator, host, port, user, pass);
}

int KSI_TcpClient_setPublicationUrl(KSI_NetworkClient *client, const char *val) {
	int res = KSI_UNKNOWN_ERROR;
	KSI_TcpClient *tcp = NULL;

	if (client == NULL || val == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	tcp = client->impl;

	res = KSI_HttpClient_setPublicationUrl(tcp->http, val);
	if (res != KSI_OK) goto cleanup;

	res = KSI_OK;

cleanup:

	return res;
}

int KSI_TcpClient_setTransferTimeoutSeconds (KSI_NetworkClient *client, int transferTimeoutSeconds ) {
	int res = KSI_UNKNOWN_ERROR;
	KSI_TcpClient *tcp = NULL;

	if (client == NULL || transferTimeoutSeconds < 0) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	tcp = client->impl;

	tcp->transferTimeoutSeconds = transferTimeoutSeconds ;

	res = KSI_OK;

cleanup:

	return res;
}

#endif /* KSI_DISABLE_NET_PROVIDER */


text:
//
//  GMSPlacePicker.h
//  Google Maps SDK for iOS
//
//  Copyright 2014 Google Inc.
//
//  Usage of this SDK is subject to the Google Maps/Google Earth APIs Terms of
//  Service: https://developers.google.com/maps/terms
//

#import <GoogleMaps/GMSPlacePickerConfig.h>

/* Error domain used for Place Picker errors. */
extern NSString * const kGMSPlacePickerErrorDomain;

/* Error codes for |kGMSPlacePickerErrorDomain|. */
typedef NS_ENUM(NSInteger, GMSPlacePickerErrorCode) {
  /**
   * Something unknown went wrong.
   */
  kGMSPlacePickerUnknownError = -1,
  /**
   * An internal error occurred in the Places API library.
   */
  kGMSPlacePickerInternalError = -2,
  /**
   * An invalid GMSPlacePickerConfig was used.
   */
  kGMSPlacePickerInvalidConfig = -3,
  /**
   * Attempted to perform simultaneous place picking operations.
   */
  kGMSPlacePickerOverlappingCalls = -4,
};

/**
 * The Place Picker is a dialog that allows the user to pick a |GMSPlace| using an interactive map
 * and other tools. Users can select the place they're at or nearby.
 */
@interface GMSPlacePicker : NSObject

/**
 * The configuration of the place picker, as passed in at initialization.
 */
@property(nonatomic, readonly, copy) GMSPlacePickerConfig *config;

/**
 * Initializes the place picker with a given configuration. This does not start the process of
 * picking a place.
 */
- (instancetype)initWithConfig:(GMSPlacePickerConfig *)config;

/**
 * Prompt the user to pick a place. The place picker is a full-screen window that appears on
 * [UIScreen mainScreen]. The place picker takes over the screen until the user cancels the
 * operation or picks a place. The supplied callback will be invoked with the chosen place, or nil
 * if no place was chosen.
 *
 * This method should be called on the main thread. The callback will also be invoked on the main
 * thread.
 *
 * It is not possible to have multiple place picking operations active at the same time. If this is
 * attempted, the second callback will be invoked with an error.
 *
 * A reference to the place picker must be retained for the duration of the place picking operation.
 * If the retain count of the place picker object becomes 0, the picking operation will be cancelled
 * and the callback will not be invoked.
 */
- (void)pickPlaceWithCallback:(GMSPlaceResultCallback)callback;

@end


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v10/enums/hotel_date_selection_type.proto

namespace Google\Ads\GoogleAds\V10\Enums\HotelDateSelectionTypeEnum;

use UnexpectedValueException;

/**
 * Enum describing possible hotel date selection types.
 *
 * Protobuf type google.ads.googleads.v10.enums.HotelDateSelectionTypeEnum.HotelDateSelectionType
 */
class HotelDateSelectionType
{
    /**
     * Not specified.
     *
     * Generated from protobuf enum UNSPECIFIED = 0;
     */
    const UNSPECIFIED = 0;
    /**
     * Used for return value only. Represents value unknown in this version.
     *
     * Generated from protobuf enum UNKNOWN = 1;
     */
    const UNKNOWN = 1;
    /**
     * Dates selected by default.
     *
     * Generated from protobuf enum DEFAULT_SELECTION = 50;
     */
    const DEFAULT_SELECTION = 50;
    /**
     * Dates selected by the user.
     *
     * Generated from protobuf enum USER_SELECTED = 51;
     */
    const USER_SELECTED = 51;

    private static $valueToName = [
        self::UNSPECIFIED => 'UNSPECIFIED',
        self::UNKNOWN => 'UNKNOWN',
        self::DEFAULT_SELECTION => 'DEFAULT_SELECTION',
        self::USER_SELECTED => 'USER_SELECTED',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(HotelDateSelectionType::class, \Google\Ads\GoogleAds\V10\Enums\HotelDateSelectionTypeEnum_HotelDateSelectionType::class);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Media;

namespace Laurus.ProdTest.Ui
{
    public class TestStepModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public int Order
        {
            get { return _order; }
            set
            {
                _order = value;
                OnPropertyChanged("Order");
            }
        }

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        public string Status
        {
            get { return _status; }
            set
            {
                _status = value;
                OnPropertyChanged("Status");
            }
        }

        public TestStepStatus StepStatus
        {
            get { return _stepStatus; }
            set
            {
                _stepStatus = value;
                OnPropertyChanged("StepStatus");
            }
        }

        #region Private
        private int _order;
        private string _name;
        private string _status;
        private TestStepStatus _stepStatus;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}


text:
Imports System.IO
Imports System.Data
Imports System.Drawing.Imaging
Imports System.ComponentModel
Imports SoftLogik.Win.UI
Imports ComponentFactory.Krypton.Toolkit

Namespace UI
    Public Class SPFormRecordBindingEventArgs
        Inherits System.EventArgs

        Private _DataSource As DataTable = Nothing
        Private _RecordBindingSettings As SPRecordBindingSettings = New SPRecordBindingSettings

        Public Property DataSource() As DataTable
            Get
                Return _DataSource
            End Get
            Set(ByVal value As DataTable)
                _DataSource = value
            End Set
        End Property
        Public Property BindingSettings() As SPRecordBindingSettings
            Get
                Return _RecordBindingSettings
            End Get
            Set(ByVal value As SPRecordBindingSettings)
                _RecordBindingSettings = value
            End Set
        End Property

        Friend Sub New()
        End Sub
    End Class

    Public Class SPRecordBindingSettings

        Private _TreeGroups As List(Of SPTreeNodeGroup) = New List(Of SPTreeNodeGroup)
        Private _NewRecordProc As NewRecordCallback = Nothing
        Private _DisplayMember As String = String.Empty
        Private _ValueMember As String = String.Empty

        Public Property DisplayMember() As String
            Get
                Return _DisplayMember
            End Get
            Set(ByVal value As String)
                _DisplayMember = value
            End Set
        End Property
        Public Property ValueMember() As String
            Get
                Return _ValueMember
            End Get
            Set(ByVal value As String)
                _ValueMember = value
            End Set
        End Property

        Public ReadOnly Property NodeGroups() As List(Of SPTreeNodeGroup)
            Get
                Return _TreeGroups
            End Get
        End Property
        Public Property NewRecordProc() As NewRecordCallback
            Get
                Return _NewRecordProc
            End Get
            Set(ByVal value As NewRecordCallback)
                _NewRecordProc = value
            End Set
        End Property
    End Class

    Public Class SPFormNavigateEventArgs
        Inherits System.EventArgs

        Private _NavigateDirection As SPRecordNavigateDirections
        Private _LastRecord As DataRow
        Private _CurrentRecord As DataRow

        Public ReadOnly Property Direction() As SPRecordNavigateDirections
            Get
                Return _NavigateDirection
            End Get
        End Property

        Public Property LastRecord() As DataRow
            Get
                Return _LastRecord
            End Get
            Set(ByVal value As DataRow)
                _LastRecord = value
            End Set
        End Property
        Public Property CurrentRecord() As DataRow
            Get
                Return _CurrentRecord
            End Get
            Set(ByVal value As DataRow)
                _CurrentRecord = value
            End Set
        End Property

        Friend Sub New(ByVal navDirection As SPRecordNavigateDirections)
            _NavigateDirection = navDirection
        End Sub
        Friend Sub New(ByVal navDirection As SPRecordNavigateDirections, ByVal LastRecord As DataRow, ByVal CurrentRecord As DataRow)
            Me._LastRecord = LastRecord
            Me._CurrentRecord = CurrentRecord
            _NavigateDirection = navDirection
        End Sub
    End Class

    Public Class SPFormRecordUpdateEventArgs
        Inherits System.EventArgs

        Private _DataRow As DataRow
        Private _DataState As SPFormDataStates

        Public ReadOnly Property DataRow() As DataRow
            Get
                Return _DataRow
            End Get
        End Property

        <Description("Gets the State the Data Record is currently set to.")> _
        Public ReadOnly Property DataState() As SPFormDataStates
            Get
                Return _DataState
            End Get
        End Property

        Friend Sub New(ByVal DataRow As DataRow, ByVal DataState As SPFormDataStates)
            Me._DataRow = DataRow
            Me._DataState = DataState
        End Sub

    End Class

    Public Class SPFormValidatingEventArgs
        Inherits EventArgs

    End Class

    Public Class SPValidationItemCollection
        Inherits List(Of SPValidationItem)

    End Class

    Public Class SPValidationItem
        Private _Name As String
        Private _Command As SPValidationItemCommands
        Private _ControlName As String

    End Class

    <Description("Represents the internal Form Data Manipulation States.")> _
    Public Class SPFormRecordStateManager
        <Description("Gets or Sets the Current Form Record Operation Mode")> Public CurrentState As SPFormRecordModes
        <Description("Gets or Sets the Showing Data Flag")> Public ShowingData As Boolean
        <Description("Gets or Sets the Form Binding Flag.")> Public BindingData As Boolean
        <Description("Gets or Sets the Duplication Data Flag.")> Public DuplicatingData As Boolean
        <Description("Gets or Sets the NewRecord Data.")> Public NewRecordData As DataRow
    End Class

    Public Delegate Function NewRecordCallback() As DataRowView

    Public Class SPMasterFormManager

        Private Shared _List As New SPMasterFormItemCollection

        Public Shared Function CreateMaster(ByVal TypeID As String) As MasterForm
            If _List.Contains(TypeID) = False Then
                Dim newForm As MasterForm = New MasterForm
                newForm.TypeID = TypeID
                _List.Add(newForm)
                Return newForm
            Else
                Return _List.Item(TypeID)
            End If
        End Function
    End Class

    Public Class SPMasterFormItemCollection
        Inherits List(Of MasterForm)

        Default Public Overloads ReadOnly Property Item(ByVal TypeID As String) As MasterForm
            Get
                For Each frm As MasterForm In Me
                    If frm.TypeID = TypeID Then
                        Return frm
                    End If
                Next

                Return Nothing
            End Get
        End Property
        Public Overloads Function Contains(ByVal TypeID As String) As Boolean
            For Each frm As MasterForm In Me
                If frm.TypeID = TypeID Then
                    Return True
                End If
            Next

            Return False
        End Function
    End Class

    Module SPFormSupport
        Friend Sub BindControls(ByRef Controls As System.Windows.Forms.Control.ControlCollection, ByRef DetailBinding As BindingSource, ByRef RecordState As SPFormRecordStateManager, ByVal OnFieldChanged As EventHandler)
            If DetailBinding IsNot Nothing Then
                RecordState.ShowingData = True
                For Each ctl As Control In Controls 'go thru all controls
                    If ctl.Controls.Count = 0 OrElse ctl.GetType().Name.StartsWith("Krypton") Then
                        BindInnerControls(ctl, DetailBinding, OnFieldChanged)
                    Else
                        BindControls(ctl.Controls, DetailBinding, RecordState, OnFieldChanged)
                    End If
                Next
                RecordState.ShowingData = False
            End If
        End Sub
        Friend Sub BindInnerControls(ByVal OuterControl As Control, ByRef DetailBinding As BindingSource, ByVal OnFieldChanged As EventHandler)
            For Each ctl As Control In OuterControl.Controls
                If ctl.Controls.Count = 0 OrElse _
                ctl.GetType().Name.StartsWith("Krypton") Then
                    If ctl.Tag IsNot Nothing Then
                        If Not String.IsNullOrEmpty(ctl.Tag.ToString().Trim()) Then
                            If TypeOf ctl Is ListControl Then
                                Try
                                    ctl.DataBindings.Add("SelectedValue", DetailBinding, ctl.Tag.ToString)
                                    AddHandler CType(ctl, ListControl).SelectedValueChanged, OnFieldChanged  'Add Handler to capture field data changes
                                Catch ex As Exception
                                End Try
                            ElseIf (TypeOf ctl Is ComboBox) Or (TypeOf ctl Is KryptonComboBox) Then
                                Try
                                    ctl.DataBindings.Add("SelectedValue", DetailBinding, ctl.Tag.ToString)
                                    AddHandler CType(ctl, ComboBox).SelectedValueChanged, OnFieldChanged  'Add Handler to capture field data changes
                                Catch ex As Exception
                                End Try
                            ElseIf (TypeOf ctl Is CheckBox) Then
                                Try
                                    ctl.DataBindings.Add("Checked", DetailBinding, ctl.Tag.ToString)
                                    AddHandler CType(ctl, CheckBox).CheckedChanged, OnFieldChanged  'Add Handler to capture field data changes
                                Catch ex As Exception
                                End Try
                            ElseIf (TypeOf ctl Is KryptonCheckBox) Then
                                Try
                                    ctl.DataBindings.Add("Checked", DetailBinding, ctl.Tag.ToString)
                                    AddHandler CType(ctl, KryptonCheckBox).CheckedChanged, OnFieldChanged  'Add Handler to capture field data changes
                                Catch ex As Exception
                                End Try
                            ElseIf (TypeOf ctl Is RadioButton) Or (TypeOf ctl Is KryptonRadioButton) Then
                                Try
                                    ctl.DataBindings.Add("Checked", DetailBinding, ctl.Tag.ToString)
                                    AddHandler CType(ctl, RadioButton).CheckedChanged, OnFieldChanged  'Add Handler to capture field data changes
                                Catch ex As Exception
                                End Try
                            ElseIf TypeOf ctl Is PictureBox Then
                                Try
                                    Dim imageBinding As New Binding("Image", DetailBinding, ctl.Tag.ToString)
                                    AddHandler imageBinding.Parse, AddressOf OnParseImage
                                    AddHandler imageBinding.Format, AddressOf OnFormatImage

                                    ctl.DataBindings.Add(imageBinding)
                                Catch ex As Exception
                                End Try
                            ElseIf TypeOf ctl Is TabPage Then
                                'do nothing
                            ElseIf TypeOf ctl Is ComponentFactory.Krypton.Toolkit.KryptonTextBox Or TypeOf ctl Is ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown Then
                                Try
                                    Dim textBinding As New Binding("Text", DetailBinding, ctl.Tag.ToString)
                                    ctl.DataBindings.Add(textBinding)
                                    AddHandler ctl.TextChanged, OnFieldChanged  'Add Handler to capture field data changes
                                Catch ex As Exception
                                End Try
                            Else
                                Try
                                    Dim textBinding As New Binding("Text", DetailBinding, ctl.Tag.ToString)
                                    AddHandler textBinding.Parse, AddressOf OnParseText
                                    AddHandler textBinding.Format, AddressOf OnFormatText

                                    ctl.DataBindings.Add(textBinding)
                                    AddHandler ctl.TextChanged, OnFieldChanged  'Add Handler to capture field data changes
                                Catch ex As Exception
                                End Try
                            End If
                        End If
                    End If
                Else
                    BindInnerControls(ctl, DetailBinding, OnFieldChanged)
                End If
            Next
        End Sub

        Private Sub OnParseImage(ByVal sender As Object, ByVal e As ConvertEventArgs)
            Try
                Dim imageSource As Image = CType(e.Value, Image)
                Dim imageStream As New MemoryStream
                imageSource.Save(imageStream, ImageFormat.Jpeg)
                e.Value = imageStream.ToArray
            Catch ex As Exception
            End Try
        End Sub
        Private Sub OnFormatImage(ByVal sender As Object, ByVal e As ConvertEventArgs)
            If e.DesiredType Is GetType(Image) Then
                Try
                    If e.Value Is DBNull.Value Then
                        e.Value = My.Resources.NoImage
                    Else
                        e.Value = Image.FromStream(New MemoryStream(CType(e.Value, Byte())))
                    End If
                Catch ex As Exception
                End Try

            End If
        End Sub
        Private Sub OnParseText(ByVal sender As Object, ByVal e As ConvertEventArgs)

        End Sub
        Private Sub OnFormatText(ByVal sender As Object, ByVal e As ConvertEventArgs)

        End Sub

    End Module
End Namespace


text:
/* eslint-disable
camelcase
 */

import autobahn from 'autobahn';
import ee from 'event-emitter';
/**
 * Controller class for managing connection interaction.
 */
export default class Connection {

  /**
   *
   * @param {Object} options - Options to configure the connection with.
   * Valid options include:
   * * apiUrl - The URL of the REST api.
   * * wsUrl - The URL of the Websocket server.
   * * oAuth2Token - An OAuth2 token string.
   * * adminPrincipal - The username of the admin account.
   * * adminPassword - The password of the admin account.
   */
  constructor(options) {
    /**
     * @type {Object}
     */
    this._settings = Object.assign({
      // ITSL connection parameters.
      apiUrl: 'https://api.itslanguage.nl',
      oAuth2Token: null,
      wsUrl: null,
      wsToken: null
    }, options);
    Connection._sdkCompatibility();
    this._analysisId = null;
    this._recordingId = null;
    this._recognitionId = null;
    this._emitter = ee({});
    this._connection = null;
  }

  /**
   * Add an event listener. Listens to events emitted from the websocket server connection.
   *
   * @param {string} name - Name of the event.
   * @param {Function} handler - Handler function to add.
   */
  addEventListener(name, handler) {
    this._emitter.on(name, handler);
  }

  /**
   * Remove an event listener of the websocket connection.
   *
   * @param {string} name - Name of the event.
   * @param {Function} handler - Handler function to remove.
   */
  removeEventListener(name, handler) {
    this._emitter.off(name, handler);
  }

  /**
   * Fire an event.
   *
   * @param {string} name - Name of the event.
   * @param {[]} args - Arguments.
   * @private
   */
  fireEvent(name, args = []) {
    this._emitter.emit(name, ...args);
  }

  /**
   * Assemble a HTTP Authentication header.
   *
   * @returns {Promise.<string>} Promise containing an authorization header string.
   * @throws {Promise.<Error>} If the oAuth2Token in {@link Connection#settings} is not set.
   */
  _getAuthHeaders() {
    if (!this._settings.oAuth2Token) {
      return Promise.reject('Please set oAuth2Token');
    }
    const authHeader = 'Bearer ' + this._settings.oAuth2Token;
    return Promise.resolve(authHeader);
  }

  /**
   * Create a connection to the websocket server.
   *
   */
  webSocketConnect() {
    const self = this;
    /**
     * This callback is fired during Ticket-based authentication.
     *
     * @param {Session} session - Session.
     * @param {string} method - Authentication method.
     */
    function onOAuth2Challenge(session, method) {
      if (method === 'ticket') {
        return self._settings.oAuth2Token;
      }
      throw new Error(`don't know how to authenticate using '${method}'`);
    }

    const authUrl = this._settings.wsUrl;
    let connection = null;
    // Open a websocket connection for streaming audio
    try {
      // Set up WAMP connection to router
      connection = new autobahn.Connection({
        url: authUrl,
        realm: 'default',
        // the following attributes must be set for Ticket-based authentication
        authmethods: ['ticket'],
        authid: 'oauth2',
        details: {
          ticket: this._settings.oAuth2Token
        },
        onchallenge: onOAuth2Challenge
      });
    } catch (e) {
      console.log('WebSocket creation error: ' + e);
      return;
    }
    connection.onerror = function(e) {
      console.log('WebSocket error: ' + e);
      self.fireEvent('websocketError', [e]);
    };
    connection.onopen = function(session) {
      console.log('WebSocket connection opened');
      self._session = session;
      self.fireEvent('websocketOpened');
    };
    connection.onclose = function() {
      console.log('WebSocket disconnected');
      self._session = null;
      self.fireEvent('websocketClosed');
    };
    this._connection = connection;
    this._connection.open();
  }

  /**
   * Make an RPC to active current session.
   *
   * @param {string} rpc - The RPC to call. It will be prefixed with `'nl.itslanguage.'`.
   * @param {...any} args - Any arguments to pass to the RPC.
   * @return {Promise} The result of the call.
   */
  call(rpc, ...args) {
    const url = 'nl.itslanguage.' + rpc;
    console.debug('Calling RPC:', url);
    return this._session.call(url, ...args);
  }

  webSocketDisconnect() {
    this._connection.close(null, 'Requested formal disconnect');
  }

  /**
   * Perform a HTTP GET to the API using authentication.
   *
   * @param {string} url - Url to retrieve.
   * @returns {Promise} Promise containing a result.
   * @throws {Promise.<Error>} If the server returned an error.
   */
  _secureAjaxGet(url) {
    return this._getAuthHeaders()
      .then(auth => {
        const headers = new Headers();
        headers.append('Authorization', auth);
        const options = {
          method: 'GET',
          headers
        };
        return fetch(url, options)
          .then(this.handleResponse);
      });
  }

  /**
   * Perform a HTTP POST to the API using authentication.
   *
   * @param {string} url - Url to submit to.
   * @param {FormData} formdata - The form to POST.
   * @returns {Promise} Promise containing a result.
   * @throws {Promise.<Error>} If the server returned an error.
   */
  _secureAjaxPost(url, formdata) {
    return this._getAuthHeaders()
      .then(auth => {
        const headers = new Headers();
        headers.append('Authorization', auth);
        if (typeof formdata === 'string') {
          headers.append('Content-Type',
            'application/json; charset=utf-8');
        }
        const options = {
          method: 'POST',
          headers,
          body: formdata
        };
        return fetch(url, options)
          .then(this.handleResponse);
      });
  }

  /**
   * Perform a HTTP DELETE to the API using authentication.
   *
   * @param {string} url - Url to submit to.
   * @returns {Promise} Promise containing a result.
   * @throws {Promise.<Error>} If the server returned an error.
   */
  _secureAjaxDelete(url) {
    return this._getAuthHeaders()
      .then(auth => {
        const headers = new Headers();
        headers.append('Authorization', auth);
        const options = {
          method: 'DELETE',
          headers
        };
        return fetch(url, options)
          .then(this.handleResponse);
      });
  }

  handleResponse(response) {
    return response.text()
      .then(textResponse => {
        if (response.headers.get('Content-type').includes('application/json')) {
          const result = JSON.parse(textResponse);
          if (response.ok) {
            return result;
          }
          return Promise.reject(result);
        } else if (!response.ok) {
          return Promise.reject(response.status + ': ' + response.statusText);
        }
      });
  }

  /**
   * Add an access token to the given URL.
   *
   * @param {string} url - The URL to add an access token to.
   * @returns {string} An url with the access token appended.
   */
  addAccessToken(url) {
    if (!this._settings.oAuth2Token) {
      throw new Error('Please set oAuth2Token');
    }
    const secureUrl = url + (url.match(/\?/) ? '&' : '?') + 'access_token=' +
      encodeURIComponent(this._settings.oAuth2Token);
    return secureUrl;
  }

  /**
   * Logs browser compatibility for required and optional SDK capabilities.
   *
   * @throws {Error} In case of compatibility issues.
   */
  static _sdkCompatibility() {
    // WebSocket
    // http://caniuse.com/#feat=websockets
    if (!('WebSocket' in window)) {
      throw new Error('No WebSocket capabilities');
    }
  }

  /**
   * Cancel any current streaming audio recording.
   *
   * @param {AudioRecorder} recorder - The audio recorder currently recording.
   */
  cancelStreaming(recorder) {
    const self = this;

    if (this._recordingId === null && this._analysisId === null && this._recognitionId === null) {
      console.info('No session in progress, nothing to cancel.');
      return;
    }

    recorder.removeAllEventListeners();
    if (recorder.isRecording()) {
      recorder.stop();
    }

    // This session is over.
    self._recordingId = null;
    self._analysisId = null;
    self._recognitionId = null;
  }

  /**
   * Log an error caught from an RPC call.
   *
   * @param {Object} result - Error object.
   */
  static logRPCError(result) {
    console.error('RPC error returned:', result.error);
  }

  /**
   * Ask the server for an OAuth2 token.
   *
   * @param {BasicAuth} basicAuth - Basic Auth to obtain credentials from.
   * @param {string} [scopes] - The scopes which should be availible for the requested token.
   * @returns {Promise} Promise containing a access_token, token_type and scope.
   * @throws {Promise.<Error>} If the server returned an error.
   */
  getOauth2Token(basicAuth, scopes) {
    const url = this._settings.apiUrl + '/tokens';

    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf8');

    let formData = 'grant_type=password' +
      '&username=' + basicAuth.principal +
      '&password=' + basicAuth.credentials;

    if (scopes) {
      formData += '&scope=' + scopes;
    }

    const options = {
      method: 'POST',
      headers,
      body: formData
    };

    return fetch(url, options)
      .then(response =>
        response.json()
          .then(data => {
            if (response.ok) {
              this._settings.oAuth2Token = data.access_token;
              return data;
            }
            throw data;
          })
      );
  }

  /**
   * Request authentication for a {@link User}. The basicAuth now contains the user's username and password.
   *
   * This method also generates the appropriate scope for the given params.
   *
   * @param {BasicAuth} basicAuth - Basic Auth to obtain credentials from.
   * @param {string} organisationId - Id of the organisation this user is part of.
   */
  getUserAuth(basicAuth, organisationId) {
    let scopes = 'tenant/' + basicAuth.tenantId;
    if (organisationId) {
      scopes += '/organisation/' + organisationId;
      if (basicAuth.principal) {
        scopes += '/user/' + basicAuth.principal;
      }
    }

    return this.getOauth2Token(basicAuth, scopes);
  }
}


text:
package org.apache.flink.runtime.concurrent;

import javax.annotation.Nonnull;

import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/** Simple {@link ScheduledExecutor} implementation for testing purposes. */
public class ManuallyTriggeredScheduledExecutor implements ScheduledExecutor {

    /**
     * The service that we redirect to. We wrap this rather than extending it to limit the surfaced
     * interface.
     */
    org.apache.flink.core.testutils.ManuallyTriggeredScheduledExecutorService execService =
            new org.apache.flink.core.testutils.ManuallyTriggeredScheduledExecutorService();

    @Override
    public void execute(@Nonnull Runnable command) {
        execService.execute(command);
    }

    /** Triggers all {@code queuedRunnables}. */
    public void triggerAll() {
        execService.triggerAll();
    }

    /**
     * Triggers the next queued runnable and executes it synchronously. This method throws an
     * exception if no Runnable is currently queued.
     */
    public void trigger() {
        execService.trigger();
    }

    /** Gets the number of Runnables currently queued. */
    public int numQueuedRunnables() {
        return execService.numQueuedRunnables();
    }

    @Override
    public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
        return execService.schedule(command, delay, unit);
    }

    @Override
    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
        return execService.schedule(callable, delay, unit);
    }

    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(
            Runnable command, long initialDelay, long period, TimeUnit unit) {
        return execService.scheduleAtFixedRate(command, initialDelay, period, unit);
    }

    @Override
    public ScheduledFuture<?> scheduleWithFixedDelay(
            Runnable command, long initialDelay, long delay, TimeUnit unit) {
        return execService.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    }

    public Collection<ScheduledFuture<?>> getScheduledTasks() {
        return execService.getScheduledTasks();
    }

    public Collection<ScheduledFuture<?>> getPeriodicScheduledTask() {
        return execService.getPeriodicScheduledTask();
    }

    public Collection<ScheduledFuture<?>> getNonPeriodicScheduledTask() {
        return execService.getNonPeriodicScheduledTask();
    }

    /** Triggers all registered tasks. */
    public void triggerScheduledTasks() {
        execService.triggerScheduledTasks();
    }

    /**
     * Triggers a single non-periodically scheduled task.
     *
     * @throws NoSuchElementException If there is no such task.
     */
    public void triggerNonPeriodicScheduledTask() {
        execService.triggerNonPeriodicScheduledTask();
    }

    /**
     * Triggers all non-periodically scheduled tasks. In contrast to {@link
     * #triggerNonPeriodicScheduledTasks()}, if such a task schedules another non-periodically
     * schedule task, then this new task will also be triggered.
     */
    public void triggerNonPeriodicScheduledTasksWithRecursion() {
        execService.triggerNonPeriodicScheduledTasksWithRecursion();
    }

    public void triggerNonPeriodicScheduledTasks() {
        execService.triggerNonPeriodicScheduledTasks();
    }

    public void triggerPeriodicScheduledTasks() {
        execService.triggerPeriodicScheduledTasks();
    }
}


text:
/*
Package ObjectId provides build a unique object identifier and are stored as 12-bytes.

ObjectId construct format:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.

http://docs.mongodb.org/manual/reference/object-id/
*/
package objectid

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"math/rand"
	"os"
	"sync/atomic"
	"time"
)

var staticMachine = getMachineHash()
var staticIncrement = getRandomNumber()
var staticPid = int32(os.Getpid())

// A globally unique identifier for objects.
type ObjectId struct {
	timestamp int64
	machine   int32
	pid       int32
	increment int32
}

// News generates new ObjectID with a unique value.
func New() ObjectId {
	timestamp := time.Now().Unix()
	return ObjectId{timestamp, staticMachine, staticPid, atomic.AddInt32(&staticIncrement, 1) & 0xffffff}
}

// Parses a string and creates a new ObjectId.
func Parse(input string) (objid ObjectId, err error) {
	if objid, err = tryParse(input); err == nil {
		return
	}
	return objid, fmt.Errorf("%s is not a valid 24 digit hex string", input)
}

func (objid ObjectId) Timestamp() int64 {
	return objid.timestamp
}

func (objid ObjectId) Machine() int32 {
	return objid.machine
}

func (objid ObjectId) Pid() int32 {
	return objid.pid
}

func (objid ObjectId) Increment() int32 {
	return objid.increment & 0xffffff
}

// String returns the ObjectID id as a 24 byte hex string representation.
func (objid ObjectId) String() string {
	array := []byte{
		byte(objid.timestamp >> 0x18),
		byte(objid.timestamp >> 0x10),
		byte(objid.timestamp >> 8),
		byte(objid.timestamp),
		byte(objid.machine >> 0x10),
		byte(objid.machine >> 8),
		byte(objid.machine),
		byte(objid.pid >> 8),
		byte(objid.pid),
		byte(objid.increment >> 0x10),
		byte(objid.increment >> 8),
		byte(objid.increment),
	}
	return hex.EncodeToString(array)
}

func getMachineHash() int32 {
	machineName, err := os.Hostname()
	if err != nil {
		panic(err)
	}
	buf := md5.Sum([]byte(machineName))
	return (int32(buf[0])<<0x10 + int32(buf[1])<<8) + int32(buf[2])
}

func getRandomNumber() int32 {
	rand.Seed(time.Now().UnixNano())
	return rand.Int31()
}

func tryParse(input string) (objid ObjectId, err error) {
	if len(input) != 0x18 {
		return objid, errors.New("invalid input length")
	}
	array, err := hex.DecodeString(input)
	if err != nil {
		return objid, err
	}
	return ObjectId{
		timestamp: int64(array[0])<<0x18 + int64(array[1])<<0x10 + int64(array[2])<<8 + int64(array[3]),
		machine:   int32(array[4])<<0x10 + int32(array[5])<<8 + int32(array[6]),
		pid:       int32(array[7])<<8 + int32(array[8]),
		increment: int32(array[9])<<0x10 + (int32(array[10]) << 8) + int32(array[11]),
	}, nil
}


text:
{% extends "base.html" %}

{% block title %} Knowledge {% endblock %}

{% block content %}

      All Groups

        <textarea style='width: 80%; vertical-align:middle' placeholder=' Add new group names, separated by commas'
          id='add_groups'></textarea>
        <button class="btn btn-large btn-default" style='vertical-align:bottom' id="btn_submit">Add groups</button>

 Existing Groups

        {% for group in groups %}

  {{ group.name }}

        {% endfor %}

{% endblock %}

{% block scripts %}
{{ super () }}

{% endblock %}


text:
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CTestApp

BEGIN_MESSAGE_MAP(CTestApp, CWinApp)
	//{{AFX_MSG_MAP(CTestApp)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG
	ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTestApp construction

CTestApp::CTestApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CTestApp object

CTestApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CTestApp initialization

BOOL CTestApp::InitInstance()
{
	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

	CTestDlg dlg;
	m_pMainWnd = &dlg;
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}


text:
package org.elasticsearch.transport;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.unit.TimeValue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A connection profile describes how many connection are established to specific node for each of the available request types.
 * ({@link org.elasticsearch.transport.TransportRequestOptions.Type}). This allows to tailor a connection towards a specific usage.
 */
public final class ConnectionProfile {

    /**
     * Builds a connection profile that is dedicated to a single channel type. Use this
     * when opening single use connections
     */
    public static ConnectionProfile buildSingleChannelProfile(TransportRequestOptions.Type channelType,
                                                              @Nullable TimeValue connectTimeout,
                                                              @Nullable TimeValue handshakeTimeout) {
        Builder builder = new Builder();
        builder.addConnections(1, channelType);
        final EnumSet<TransportRequestOptions.Type> otherTypes = EnumSet.allOf(TransportRequestOptions.Type.class);
        otherTypes.remove(channelType);
        builder.addConnections(0, otherTypes.stream().toArray(TransportRequestOptions.Type[]::new));
        if (connectTimeout != null) {
            builder.setConnectTimeout(connectTimeout);
        }
        if (handshakeTimeout != null) {
            builder.setHandshakeTimeout(handshakeTimeout);
        }
        return builder.build();
    }

    private final List<ConnectionTypeHandle> handles;
    private final int numConnections;
    private final TimeValue connectTimeout;
    private final TimeValue handshakeTimeout;

    private ConnectionProfile(List<ConnectionTypeHandle> handles, int numConnections, TimeValue connectTimeout, TimeValue handshakeTimeout)
    {
        this.handles = handles;
        this.numConnections = numConnections;
        this.connectTimeout = connectTimeout;
        this.handshakeTimeout = handshakeTimeout;
    }

    /**
     * A builder to build a new {@link ConnectionProfile}
     */
    public static class Builder {
        private final List<ConnectionTypeHandle> handles = new ArrayList<>();
        private final Set<TransportRequestOptions.Type> addedTypes = EnumSet.noneOf(TransportRequestOptions.Type.class);
        private int offset = 0;
        private TimeValue connectTimeout;
        private TimeValue handshakeTimeout;

        /** create an empty builder */
        public Builder() {
        }

        /** copy constructor, using another profile as a base */
        public Builder(ConnectionProfile source) {
            handles.addAll(source.getHandles());
            offset = source.getNumConnections();
            handles.forEach(th -> addedTypes.addAll(th.types));
            connectTimeout = source.getConnectTimeout();
            handshakeTimeout = source.getHandshakeTimeout();
        }
        /**
         * Sets a connect timeout for this connection profile
         */
        public void setConnectTimeout(TimeValue connectTimeout) {
            if (connectTimeout.millis() < 0) {
                throw new IllegalArgumentException("connectTimeout must be non-negative but was: " + connectTimeout);
            }
            this.connectTimeout = connectTimeout;
        }

        /**
         * Sets a handshake timeout for this connection profile
         */
        public void setHandshakeTimeout(TimeValue handshakeTimeout) {
            if (handshakeTimeout.millis() < 0) {
                throw new IllegalArgumentException("handshakeTimeout must be non-negative but was: " + handshakeTimeout);
            }
            this.handshakeTimeout = handshakeTimeout;
        }

        /**
         * Adds a number of connections for one or more types. Each type can only be added once.
         * @param numConnections the number of connections to use in the pool for the given connection types
         * @param types a set of types that should share the given number of connections
         */
        public void addConnections(int numConnections, TransportRequestOptions.Type... types) {
            if (types == null || types.length == 0) {
                throw new IllegalArgumentException("types must not be null");
            }
            for (TransportRequestOptions.Type type : types) {
                if (addedTypes.contains(type)) {
                    throw new IllegalArgumentException("type [" + type + "] is already registered");
                }
            }
            addedTypes.addAll(Arrays.asList(types));
            handles.add(new ConnectionTypeHandle(offset, numConnections, EnumSet.copyOf(Arrays.asList(types))));
            offset += numConnections;
        }

        /**
         * Creates a new {@link ConnectionProfile} based on the added connections.
         * @throws IllegalStateException if any of the {@link org.elasticsearch.transport.TransportRequestOptions.Type} enum is missing
         */
        public ConnectionProfile build() {
            EnumSet<TransportRequestOptions.Type> types = EnumSet.allOf(TransportRequestOptions.Type.class);
            types.removeAll(addedTypes);
            if (types.isEmpty() == false) {
                throw new IllegalStateException("not all types are added for this connection profile - missing types: " + types);
            }
            return new ConnectionProfile(Collections.unmodifiableList(handles), offset, connectTimeout, handshakeTimeout);
        }

    }

    /**
     * Returns the connect timeout or null if no explicit timeout is set on this profile.
     */
    public TimeValue getConnectTimeout() {
        return connectTimeout;
    }

    /**
     * Returns the handshake timeout or null if no explicit timeout is set on this profile.
     */
    public TimeValue getHandshakeTimeout() {
        return handshakeTimeout;
    }

    /**
     * Returns the total number of connections for this profile
     */
    public int getNumConnections() {
        return numConnections;
    }

    /**
     * Returns the number of connections per type for this profile. This might return a count that is shared with other types such
     * that the sum of all connections per type might be higher than {@link #getNumConnections()}. For instance if
     * {@link org.elasticsearch.transport.TransportRequestOptions.Type#BULK} shares connections with
     * {@link org.elasticsearch.transport.TransportRequestOptions.Type#REG} they will return both the same number of connections from
     * this method but the connections are not distinct.
     */
    public int getNumConnectionsPerType(TransportRequestOptions.Type type) {
        for (ConnectionTypeHandle handle : handles) {
            if (handle.getTypes().contains(type)) {
                return handle.length;
            }
        }
        throw new AssertionError("no handle found for type: "  + type);
    }

    /**
     * Returns the type handles for this connection profile
     */
    public List<ConnectionTypeHandle> getHandles() {
        return Collections.unmodifiableList(handles);
    }

    /**
     * Connection type handle encapsulates the logic which connection
     */
    public static final class ConnectionTypeHandle {
        public final int length;
        public final int offset;
        private final Set<TransportRequestOptions.Type> types;
        private final AtomicInteger counter = new AtomicInteger();

        public ConnectionTypeHandle(int offset, int length, Set<TransportRequestOptions.Type> types) {
            this.length = length;
            this.offset = offset;
            this.types = types;
        }

        /**
         * Returns one of the channels out configured for this handle. The channel is selected in a round-robin
         * fashion.
         */
        public <T> T getChannel(List<T> channels) {
            if (length == 0) {
                throw new IllegalStateException("can't select channel size is 0 for types: " + types);
            }
            assert channels.size() >= offset + length : "illegal size: " + channels.size() + " expected >= " + (offset + length);
            return channels.get(offset + Math.floorMod(counter.incrementAndGet(), length));
        }

        /**
         * Returns all types for this handle
         */
        public Set<TransportRequestOptions.Type> getTypes() {
            return types;
        }
    }
}