text:
@interface classA : NSObject <HDMessageManageDelegate>

@end

@implementation classA

- (void)HDSendMessageFinish:(BOOL)isSucceed {
    NSLog(@"classA回调HDSendMessageFinish");
}

@end

@interface classB : NSObject <HDMessageManageDelegate>

@end

@implementation classB

- (void)HDSendMessageFinish:(BOOL)isSucceed {
    NSLog(@"classB回调HDSendMessageFinish");
}

@end

@interface ViewController () <HDMessageManageDelegate>
{
    classA *_a;
    classB *_b;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _a = [[classA alloc] init];
    _b = [[classB alloc] init];

    [HDMessageManageSingleton getSingleton].delegate = self;
    [HDMessageManageSingleton getSingleton].delegate =_b;

}
- (IBAction)buttonClick:(id)sender {
    [HDMessageManageSingleton getSingleton].delegate = _a;
    [[HDMessageManageSingleton getSingleton] sendTextMessage:@"消息"];
}

- (IBAction)removeAButtonClick:(id)sender {
    [[HDMessageManageSingleton getSingleton] removeCall:_a];
    [[HDMessageManageSingleton getSingleton] sendTextMessage:@"消息"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}

- (void)HDSendMessageFinish:(BOOL)isSucceed {
    NSLog(@"ViewController回调HDSendMessageFinish");
}

@end


text:
package org.etl.spi.flink.reducer.aggregator;

import org.etl.api.Record;
import org.etl.api.transform.Aggregator;

import java.math.BigDecimal;

/**
 *
 */
public class SumAggregatorReducer implements AggregatorReducer {

    @Override
    public Record reduceFirst(Aggregator aggregator, Record currentRecord, Record result) {
        BigDecimal currentResult = currentRecord.getValue(aggregator.getFieldName());
        if (currentRecord == null) {
            currentResult = BigDecimal.ZERO;
        }
        result.setValue(aggregator.getResultFieldName(),currentResult);
        return result;
    }

    @Override
    public Record reduceNext(Aggregator aggregator, Record currentRecord, Record result) {
        BigDecimal sum = result.getValue(aggregator.getResultFieldName());
        BigDecimal currentValue = currentRecord.getValue(aggregator.getFieldName());
        if (currentValue != null) {
            sum = sum.add(currentValue);
        }
        result.setValue(aggregator.getResultFieldName(), sum);
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
const { Contract, PromiseContract } = require('@toryt/contracts-v')
const validate = require('./validate')
const ServiceInstance = require('./ServiceInstance')
const discover = require('./discover')
// noinspection JSUnresolvedVariable
const discoverContract = discover.contract

/**
 * Promise the {@code ServiceInstance} that should be used for the given {@code serviceType} according to DNS-SD,
 * using the different service instances' priority and weight.
 * If an optional {@code filter} function is provided, only {@code ServiceInstance} objects whose name passes
 * the filter are considered.
 * If no appropriate {@code ServiceInstance} is found, the Promise is resolved with {@code null}
 */
const selectInstanceContract = new PromiseContract({
  pre: [
    validate.isServiceType,
    (serviceType, filter) => !filter || selectInstanceContract.filter.isImplementedBy(filter)
  ],
  post: [
    function () {
      const resolution = PromiseContract.outcome(arguments)
      return resolution === null || PromiseContract.outcome(arguments) instanceof ServiceInstance
    },
    function (serviceType) {
      const resolution = PromiseContract.outcome(arguments)
      return resolution === null || resolution.type === serviceType
    },
    function (serviceType, filter) {
      const resolution = PromiseContract.outcome(arguments)
      return resolution === null || arguments.length < 4 || filter(resolution.instance)
    }
  ],
  exception: discoverContract.invalidServiceDefinitionException
})
selectInstanceContract.filter = discoverContract.filter

function orderByPriority (a, b) {
  return a === b || a.priority === b.priority ? 0 : a.priority < b.priority ? -1 : +1 // b.priority < a.priority)
}

/**
 * RFC 2782 states:
 *
 *

 * The following algorithm SHOULD be used to order the SRV RRs of the same
 * priority:

 * To select a target to be contacted next, arrange all SRV RRs
 * (that have not been ordered yet) in any order, except that all
 * those with weight 0 are placed at the beginning of the list.

 * Compute the sum of the weights of those RRs, and with each RR
 * associate the running sum in the selected order. Then choose a
 * uniform random number between 0, and the sum computed
 * (inclusive), and select the RR whose running sum value is the
 * first in the selected order which is greater than or equal to
 * the random number selected. The target host specified in the
 * selected SRV RR is the next one to be contacted by the client.
 * Remove this SRV RR from the set of the unordered SRV RRs and
 * apply the described algorithm to the unordered SRV RRs to select
 * the next target host.  Continue the ordering process until there
 * are no unordered SRV RRs.  This process is repeated for each
 * Priority.
 *

 *
 *
The below algorithm is close to that, without keeping state between calls.

 *
The above does not cover the case where all weights are 0 sufficiently,
 * because it says the instances should be arranged in 'any order', which is not
 * necessarily random. The below algorithm chooses a totally random choice when
 * all instances have weight 0.

 */
const selectByWeight = new Contract({
  pre: [
    instances => Array.isArray(instances),
    instances => instances.length >= 1,
    instances => instances.every(i => i instanceof ServiceInstance)
  ],
  post: [
    (instances, result) => result instanceof ServiceInstance,
    (instances, result) => instances.indexOf(result) >= 0
  ]
}).implementation(function selectByWeight (/** @type Array<ServiceInstance> */ instances) {
  const totalWeight = instances.reduce((acc, i) => acc + i.weight, 0)
  if (totalWeight <= 0) {
    // totalWeight === 0, and all instances will have weight 0 - random selection
    return instances[Math.floor(Math.random() * instances.length)]
  }
  const rand = Math.random() * totalWeight
  let runningSum = 0
  for (let i = 0; i < instances.length; i++) {
    runningSum += instances[i].weight
    if (rand < runningSum) {
      return instances[i]
    }
  }
  /* a result will always be returned, since
       0 <= Math.random() < 1
       0 <= rand < totalWeight
     and
       runningSum grows eventually to totalWeight
       so, eventually, in the loop, rand < runningSum will become true */
})

async function selectInstanceImpl (/* !string */ serviceType, /* Function */ filter) {
  const /** @type Array<ServiceInstance> */ instances = await discover(serviceType, filter)
  if (instances.length <= 0) {
    return null
  }
  instances.sort(orderByPriority)
  let highestPriorityInstances = []
  highestPriorityInstances = instances.reduce((acc, i) => {
    // noinspection JSUnresolvedVariable
    if (i.priority === instances[0].priority) {
      acc.push(i)
    }
    return acc
  }, highestPriorityInstances)
  return selectByWeight(highestPriorityInstances)
}

const selectInstance = selectInstanceContract.implementation(selectInstanceImpl)
selectInstance.notOneOf = discover.notOneOf
selectInstance.selectByWeight = selectByWeight

module.exports = selectInstance


text:
My first web project made during the Tech course of Softuni.bg
February 2017


text:
package com.balidao.transreport.json;

import java.io.IOException;
import java.util.Date;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class DateSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(Date date, JsonGenerator generator, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        generator.writeString(CustomDateTimeModule.DATE_FORMAT.format(date));
    }

}


text:
<?php

namespace yii\base;

/**
 * UnknownClassException represents an exception caused by accessing an unknown class.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class UnknownClassException extends Exception
{
	/**
	 * @return string the user-friendly name of this exception
	 */
	public function getName()
	{
		return \Yii::t('yii', 'Unknown Class');
	}
}


text:
require "minitest/autorun"
require "rbloom"

class RbloomTest < Minitest::Test

  def setup
    @bloom = Rbloom.new
  end

  def test_contains_without_word
    refute @bloom.contains? "thing"
  end

  def test_contains_without_word
    @bloom.add "word"
    refute @bloom.contains? "word1"
  end

  def test_add_word
    @bloom.add "thing"
  end

  def test_contains_with_word
    @bloom.add "word"
    assert @bloom.contains? "word"
  end

  def test_contains_more_things
    @bloom.add "a"
    @bloom.add "b"
    @bloom.add "c"
    @bloom.add "aa"
    @bloom.add "bb"
    @bloom.add "cc"
    @bloom.add "aaa"
    @bloom.add "bbb"
    @bloom.add "ccc"
    @bloom.add "aaaa"
    assert @bloom.contains? "b"
  end
end


text:
using Newtonsoft.Json;
using ShopifySharp.Converters;
using System.Runtime.Serialization;

namespace ShopifySharp.Enums
{
    /// <summary>
    /// An enum representing the type of <see cref="ShopifyScriptTag.Event"/>.
    /// </summary>
    [JsonConverter(typeof(NullableEnumConverter<ShopifyScriptTagEvent>))]
    public enum ShopifyScriptTagEvent
    {
        /// <summary>
        /// The script tag is triggered when the DOM fires the "Onload" event.
        /// </summary>
        [EnumMember(Value = "onload")]
        Onload
    }
}


text:
char *utilCwd(void) {
    // The maximum buffer size is determined per the recommendation
    // in the Posix docs for `getcwd`.

    long maxSize = pathconf(".", _PC_PATH_MAX);
    char buf[maxSize + 1];

    if (getcwd(buf, maxSize) == NULL) {
        die("Trouble with `getcwd`: %s", strerror(errno));
    }

    return utilStrdup(buf);
}

// Documented in header.
char *utilReadLink(const char *path) {
    struct stat statBuf;

    if (lstat(path, &statBuf) != 0) {
        if ((errno == ENOENT) || (errno == ENOTDIR)) {
            // File not found or invalid component, neither of which are
            // really errors from the perspective of this function.
            errno = 0;
            return NULL;
        }
        die("Trouble with `lstat`: %s", strerror(errno));
    } else if (!S_ISLNK(statBuf.st_mode)) {
        // Not a symlink.
        errno = 0;
        return NULL;
    }

    // If `st_size` is non-zero, then it can safely be used as the size of
    // the link data. However, on Linux some valid links (particularly, those
    // in `/proc/`) will have `st_size` reported as `0`. In such cases, we
    // use an ample but fixed-size buffer, and hope for the best.

    bool assumeSize = (statBuf.st_size == 0);
    size_t linkSz = assumeSize ? 500 : statBuf.st_size;
    char *result = utilAlloc(linkSz + 1);
    ssize_t resultSz = readlink(path, result, linkSz);

    if (resultSz < 0) {
        die("Trouble with `readlink`: %s", strerror(errno));
    } else if (assumeSize ? (resultSz > linkSz) : (resultSz != linkSz)) {
        die("Strange `readlink` result: %d", (zint) resultSz);
    }

    result[resultSz] = '\0';
    return result;
}


text:
#pragma once

#include "../TanyatuCoreGlobal.h"
#include "StoredMediaObject.h"

namespace Tanyatu { namespace Data {

/**
 * @brief The AlbumInfo class is a in memory model of a audio album. This
 * information reflects the entries in the database and is kept consistent with
 * the database
 */
class TANYATU_CORE_EXPORT AlbumInfo : public StoredMediaObject
{
    /**
     * @brief m_artistName name of the artist who created this album
     */
    QString m_artistName;

    /**
     * @brief m_name name of the album
     */
    QString m_name;

    /**
     * @brief m_comment A discreptive comment about this album
     */
    QString m_comment;

    /**
     * @brief m_albumId a unique id constructed from the album name and artist
     * name
     */
    QString m_albumId;

public:
    /**
     * @brief AlbumInfo Ctor that constructs AlbumInfo from the artist name and
     * the album name The Id is calculated from the artist and album names.
     * @param artistName Name of the creator of this album
     * @param name of the album
     */
    AlbumInfo( const QString artistName, const QString name );

    /**
     * @brief id gives an identifier that is constructed from the names of
     * artist and the album that uniquely identifies this album
     * @return unique id for this album
     */
    QString id() const;

    /**
     * @brief name gives the name of the album that this object represents
     * @return name of the album
     */
    QString name() const;

    /**
     * @brief comment gives a comment associated with this object
     * @return comment about this album
     */
    QString comment() const;

    /**
     * @brief setComment sets the comment associated with this album
     * @param comment new comment to be associated
     */
    void setComment( const QString comment );

    /**
     * @brief artistName gives the name of the artist who created this album
     * @return name of the artist of this album
     */
    QString artistName() const;

    /**
     * @brief storageId gives an id representing the type of model object. This
     * is used to decide the persistance logic
     * @return id representing the type of object
     */
    QString storageId() const;

    /**
     * @brief getAlbumIdFrom constructs and gives a unique id from the album and
     * artist names of an album
     * @param artistName name of the artist of the album
     * @param albumName name of the album
     * @return a unique id for an album
     */
    static QString getAlbumIdFrom( const QString artistName,
                                   const QString albumName );

    /**
     * @brief STORAGE_ID unique id representing all the objects of the type
     * AlbumInfo
     */
    static const QString STORAGE_ID;
};

} } //end of ns


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<constant name="struts.action.extension" value="do" />
	<!-- 设置Web应用的默认编码集为UTF-8 -->
	<constant name="struts.i18n.encoding" value="UTF-8"/>
	<!-- 设置Struts2默认的ObjectFactory为spring -->
	<constant name="struts.objectFactory" value="spring" />
	<!-- 设置Struts2应用是否处于开发模式,通常在开发调试阶段设为true,正式上线后可设为false -->
	<constant name="struts.devMode" value="false" />
	<!-- 设置Struts2的默认主题为simple -->
	<constant name="struts.ui.theme" value="simple" />

	<!-- 定义一个名为 partmanager 的包,继承 Struts 2 的默认包 -->
    <package name="partmanager" extends="json-default">
		<!-- 配置自定义拦截器LoginedCheckInterceptor -->
		<interceptors>
			<interceptor name="loginedCheck" class="com.partmanager.utils.filter.LoginedCheckInterceptor"/>
		</interceptors>

		<!-- 定义全局result -->
		<global-results>
			<!-- 定义名为exception的全局result -->
		    <result name="exception">/exception.jsp</result>
		    <result name="tologin">/login.jsp</result>
		</global-results>

		<!-- 定义全局异常映射 -->
		<global-exception-mappings>
			<!-- 捕捉到Exception异常(所有异常)时跳转到exception所命名的视图上 -->
			<exception-mapping exception="java.lang.Exception" result="exception"/>
		</global-exception-mappings>
    </package>

    <package name="main" extends="partmanager" namespace="/">
		<action name="*_*" class="{1}Action" method="{2}">
			<result name="input">/login.jsp</result>
			<result name="success" type="redirect">/jsp/main/index.jsp</result>
			<result name="json" type="json">
	            <param name="includeProperties">success</param>
	        </result>
	        <result name="maintab">/jsp/main/maintab.jsp </result>
	        <result name="subpage">/jsp/main/{2}.jsp </result>
			<interceptor-ref name="loginedCheck"/>
			<interceptor-ref name="defaultStack"/>
		</action>
	</package>
</struts>


text:
#include "OpenGL_ES_Render.h"
#include "../Log.h"
#include "../Visuals/SpriteVisual.h"
#include "../Visuals/LightVisual.h"
#include "../Visuals/ParticleSystemVisual.h"
#include "../Visuals/TextVisual.h"
#include "../Performance/SectionTimer.h"
#include "../Performance/BranchPredict.h"

void OpenGL_ES_Render::renderLightVisual(LightVisualList & lights) {
	/*
	 glMatrixMode(GL_MODELVIEW);
	 glLoadIdentity();

	 for (LightVisual * sv : lights) {
	 if (sv->getNeedsUpdate()) {
	 const GLfloat light_ambient[] = { 1.0, 1.0, 1.0, 1.0 };

	 //GL_CHECK_ERROR(glLightfv(GL_LIGHT0, GL_POSITION, light_position));

	 GL_CHECK_ERROR(glEnable(sv->getLightNumber()));
	 GL_CHECK_ERROR(glLightfv(sv->getLightNumber(), GL_AMBIENT, light_ambient));
	 GL_CHECK_ERROR(glLightfv(sv->getLightNumber(), GL_DIFFUSE, light_ambient));

	 // important for the light to look like a spot
	 const GLfloat atten = 0.00002f;
	 GL_CHECK_ERROR(glLightf(sv->getLightNumber(), GL_QUADRATIC_ATTENUATION, atten));

	 GLfloat light_position[] = { sv->getPosition().x(), sv->getPosition().y(), sv->getPosition().z(),
	 1.0 };
	 glLightfv(sv->getLightNumber(), GL_POSITION, light_position);
	 sv->setNeedsUpdate(false);
	 }
	 }*/
}

void OpenGL_ES_Render::renderTextVisual(TextVisualList const& part, bool ingameText) {
	//return;
	// todo: unbind texture after done so the debug visual drawing can work again
	GL_CHECK_ERROR(glMatrixMode(GL_MODELVIEW));
	GL_CHECK_ERROR(glLoadIdentity());

	//GL_CHECK_ERROR(glDisable(GL_LIGHTING));
	GL_CHECK_ERROR(glEnable(GL_TEXTURE_2D));

	GL_CHECK_ERROR(glDisableClientState(GL_NORMAL_ARRAY));
	GL_CHECK_ERROR(glEnableClientState(GL_VERTEX_ARRAY));
	GL_CHECK_ERROR(glEnableClientState(GL_TEXTURE_COORD_ARRAY));

	TexturePtr lastBindTexture = nullptr;

	for (TextVisual * tv : part) {
		logging::Debug<logging::Categories::RenderEngine>() << "ensureOpenGLBind";
		tv->getTexture()->ensureOpenGLBind();

		if (tv->isIngame() != ingameText)
			continue;

		if (tv->getVisible()) {
			glColor4f(1.0f, 1.0f, 1.0f, tv->getTransparency());

			// todo:: do this only once and then draw all entities with
			// this text -> sort the entities
			//if ( GCC_UNLIKELY (lastBindTexture != tv->getTexture() ) ) {
			if (lastBindTexture != tv->getTexture()) {
				//logging::Debug<logging::Categories::RenderEngine>() << "Binding Texture with OpenGL";
				GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, tv->getTexture()->getID()));
				lastBindTexture = tv->getTexture();
			}

			logging::Debug<logging::Categories::RenderEngine>() << "Setting up vertex Pointer";
			GL_CHECK_ERROR(glVertexPointer(3, GL_FLOAT, 0, &tv->getVertexBuffer().front()));
			//GL_CHECK_ERROR(glNormalPointer(GL_FLOAT, 0, (*it)->getNormalBufferPtr()));

			logging::Debug<logging::Categories::RenderEngine>() << "Setting up tex coords";
			GL_CHECK_ERROR(glTexCoordPointer(2, GL_FLOAT, 0, &tv->getTextureBuffer().front()));

			logging::Debug<logging::Categories::RenderEngine>() << "Draw arr";
			//logging::Debug<>() << "draw " << i;

			// this produces the scanline crash
			GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLES, 0, 6 * tv->getCharacterCount()));
		}
	}

	GL_CHECK_ERROR(glDisableClientState(GL_VERTEX_ARRAY));
	GL_CHECK_ERROR(glDisableClientState(GL_TEXTURE_COORD_ARRAY));

}

void OpenGL_ES_Render::renderParticleSystemVisual(ParticeSystemVisualList const& part) {

	GL_CHECK_ERROR(glMatrixMode(GL_MODELVIEW));
	GL_CHECK_ERROR(glLoadIdentity());

	GL_CHECK_ERROR(glDisable(GL_TEXTURE_2D));

	GL_CHECK_ERROR(glDisableClientState(GL_NORMAL_ARRAY));
	GL_CHECK_ERROR(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
	GL_CHECK_ERROR(glEnableClientState(GL_VERTEX_ARRAY));
	GL_CHECK_ERROR(glEnableClientState(GL_COLOR_ARRAY));

	//glColor4f(1.0f, 0.0f, 0.0f, 1.0f);

	for (ParticleSystemVisual const* visual : part) {
		if (visual->getVisible() && visual->isRunning()) {
			GL_CHECK_ERROR(glPointSize(visual->getPointSize()));

			GL_CHECK_ERROR(glVertexPointer(3, GL_FLOAT, 0, visual->getVertexBufferPtr()));
			GL_CHECK_ERROR(glColorPointer(4, GL_FLOAT, 0, visual->getColorBufferPtr()));

			// this produces the scanline crash
			GL_CHECK_ERROR(glDrawArrays(GL_POINTS, 0, visual->getParticleCount()));
		}
	}
	GL_CHECK_ERROR(glDisableClientState(GL_VERTEX_ARRAY));
	GL_CHECK_ERROR(glDisableClientState(GL_COLOR_ARRAY));

}

void OpenGL_ES_Render::renderSpriteVisual(SpriteVisualSVector & visualVec, bool ingameSprite, float deltaT) {

	GL_CHECK_ERROR(glMatrixMode(GL_MODELVIEW));
	GL_CHECK_ERROR(glLoadIdentity());
	GL_CHECK_ERROR(glEnable(GL_TEXTURE_2D));

	GL_CHECK_ERROR(glEnableClientState(GL_VERTEX_ARRAY));
	GL_CHECK_ERROR(glEnableClientState(GL_NORMAL_ARRAY));
	GL_CHECK_ERROR(glEnableClientState(GL_TEXTURE_COORD_ARRAY));

	TexturePtr lastBindTexture = nullptr;

	for (size_t i = 0; i < visualVec.activeSize(); i++) {

		if (!visualVec.isActive(i))
			continue;

		auto & vis = visualVec.get(i);

		if (vis.getVisible() && (vis.isIngame() == ingameSprite)) {
			vis.step(deltaT);

			glColor4f(1.0f, 1.0f, 1.0f, vis.getTransparency());

			logging::Debug<logging::Categories::RenderEngine>() << "ensureOpenGLBind";
			vis.getTexture()->ensureOpenGLBind();

			// render entries are presorted by texture
			// this case should not happen to often
			if (GCC_UNLIKELY(lastBindTexture != vis.getTexture())) {
				GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, vis.getTexture()->getID()));
				lastBindTexture = vis.getTexture();
			}

			logging::Debug<logging::Categories::RenderEngine>() << "Setting up vertex Pointer";
			GL_CHECK_ERROR(glVertexPointer(3, GL_FLOAT, 0, vis.getVertexBufferPtr()));
			GL_CHECK_ERROR(glNormalPointer(GL_FLOAT, 0, vis.getNormalBufferPtr()));

			logging::Debug<logging::Categories::RenderEngine>() << "Setting up tex coords";
			GL_CHECK_ERROR(glTexCoordPointer(2, GL_FLOAT, 0, vis.getDefaultTextureCoordsPtr()));

			logging::Debug<logging::Categories::RenderEngine>() << "Draw arr";

			GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_FAN, 0, 4));
		}
	} // visuals

	GL_CHECK_ERROR(glDisableClientState(GL_TEXTURE_COORD_ARRAY));
	GL_CHECK_ERROR(glDisable(GL_TEXTURE_2D));

// run the loop again with debug faces, if needed
	if (m_debugFaces) {

		std::array<GLfloat, 4 * 4> debugFacesColor = { { //
				0.2f, 0.2f, 1.0f, 0.3f, //
						0.2f, 0.2f, 1.0f, 0.3f, //
						0.2f, 0.2f, 1.0f, 0.3f, //
						0.2f, 0.2f, 1.0f, 0.3f } };

		GL_CHECK_ERROR(glEnableClientState(GL_COLOR_ARRAY));
		const float zLayerDebug = LayerTools::computeZ(LayerPriority::LayerPriorityDebug);

		for (size_t i = 0; i < visualVec.activeSize(); i++) {
			if (!visualVec.isActive(i))
				continue;

			auto & vis = visualVec.get(i);

			if (vis.getVisible() && (vis.isIngame() == ingameSprite)) {
				// move the debug plane slightly above the actual texture planes
				SpriteVisual::VertexBufferArray vrtArr;
				auto const& otherArr = vis.getVertexBuffer();
				std::copy(otherArr, otherArr + SpriteVisual::VertexBufferSize, vrtArr);
				vrtArr[2] = vrtArr[5] = vrtArr[8] = vrtArr[11] = zLayerDebug;

				GL_CHECK_ERROR(glVertexPointer(3, GL_FLOAT, 0, &vrtArr ));
				GL_CHECK_ERROR(glNormalPointer(GL_FLOAT, 0, vis.getNormalBufferPtr()));
				GL_CHECK_ERROR(glColorPointer(4, GL_FLOAT, 0, &debugFacesColor.front() ));
				GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_FAN, 0, 4));
			}
		}

		GL_CHECK_ERROR(glDisableClientState(GL_COLOR_ARRAY));
	}

	GL_CHECK_ERROR(glDisableClientState(GL_NORMAL_ARRAY));
	GL_CHECK_ERROR(glDisableClientState(GL_VERTEX_ARRAY));

}

void OpenGL_ES_Render::renderBegin() {
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	renderSetupCam();
}

void OpenGL_ES_Render::renderSetupCam() {

	GL_CHECK_ERROR(glMatrixMode(GL_PROJECTION));
	GL_CHECK_ERROR(glLoadIdentity());

	GL_CHECK_ERROR(glMultMatrixf(&m_defaultProjection.front()));
	GL_CHECK_ERROR(glTranslatef(0.0f, m_camTranslate.y(), 0.0f));
}

void OpenGL_ES_Render::setCameraLocation(ScreenTransform const& st, Vector3 vec, bool useOffsetX,
		bool useOffsetY) {
	m_defaultProjection = GLSupport::getParallelProjection(st.getScreenSize().x(), st.getScreenSize().y(),
			-1.0f, 1.0f);

	const Vector2 screenEdges = st.screenSizeInPixel();

	m_camTranslate = st.vectorToScreen(vec, useOffsetX, useOffsetY);
// translate to the bottom of the display
	m_camTranslate.setY(m_camTranslate.y() + screenEdges.y());
}

void OpenGL_ES_Render::resetTranslation(ScreenTransform const& st) {

}

Vector3 OpenGL_ES_Render::getCameraLocation(ScreenTransform const& st) const {
	const Vector2 screenEdges = st.screenSizeInPixel();

	Vector3 v3 = m_camTranslate;
	v3.setY(v3.y() - screenEdges.y());

	return st.screenToVector(v3);
}

void OpenGL_ES_Render::renderEnd(RenderState & state) {

#ifdef USE_ANDROID_OPENGL

// swapping is done by the GLView on Java
//eglSwapBuffers( state.m_display , state.m_surface);
//eglSwapBuffers( eglGetCurrentDisplay(), eglGetCurrentSurface( EGL_DRAW ) );
#else
	SDL_GL_SwapBuffers();
#endif

}


text:
angular.module("umbraco").controller("Umbraco.Dialogs.LinkPickerController",
	function ($scope, eventsService, dialogService, entityResource, contentResource, mediaHelper, $log) {
	var dialogOptions = $scope.$parent.dialogOptions;

	$scope.dialogTreeEventHandler = $({});
	$scope.target = {};

	if(dialogOptions.currentTarget){
		$scope.target = dialogOptions.currentTarget;

		//if we have a node ID, we fetch the current node to build the form data
		if($scope.target.id){

			if(!$scope.target.path) {
			    entityResource.getPath($scope.target.id, "Document").then(function (path) {
			        $scope.target.path = path;
			        //now sync the tree to this path
			        $scope.dialogTreeEventHandler.syncTree({ path: $scope.target.path, tree: "content" });
			    });
			}

			contentResource.getNiceUrl($scope.target.id).then(function(url){
				$scope.target.url = url;
			});
		}
	}

	$scope.switchToMediaPicker = function () {
	    dialogService.mediaPicker(
            {
                callback: function (media) {
                    $scope.target.id = media.id;
                    $scope.target.isMedia = true;
                    $scope.target.name = media.name;
                    $scope.target.url = mediaHelper.resolveFile(media);
                }
            });
	};

	$scope.dialogTreeEventHandler.bind("treeNodeSelect", function(ev, args){
		args.event.preventDefault();
		args.event.stopPropagation();

		eventsService.emit("dialogs.linkPicker.select", args);

		var c = $(args.event.target.parentElement);

	    //renewing
		if (args.node !== $scope.target) {
		    if ($scope.selectedEl) {
		        $scope.selectedEl.find(".temporary").remove();
		        $scope.selectedEl.find("i.umb-tree-icon").show();
		    }

		    $scope.selectedEl = c;
		    $scope.target.id = args.node.id;
		    $scope.target.name = args.node.name;

		    $scope.selectedEl.find("i.umb-tree-icon")
             .hide()
             .after("<i class='icon umb-tree-icon sprTree icon-check blue temporary'></i>");

		    if (args.node.id < 0) {
		        $scope.target.url = "/";
		    } else {
		        contentResource.getNiceUrl(args.node.id).then(function (url) {
		            $scope.target.url = url;
		        });
		    }
		} else {
		    $scope.target = undefined;
		    //resetting
		    if ($scope.selectedEl) {
		        $scope.selectedEl.find(".temporary").remove();
		        $scope.selectedEl.find("i.umb-tree-icon").show();
		    }
		}

		if (!angular.isUndefined($scope.target.isMedia)) {
		    delete $scope.target.isMedia;
		}
	});
});


text:
describe('API response tests (unauthorized)', function() {
  /**
   * The setup method called before each test.
   */
  beforeEach(function() {
    gapi = gapi || {};
    gapi.auth = gapi.auth || {};
    gapi.auth.signOut = function() {};

    server = sinon.fakeServer.create();

    // Disable parsing the endpoint responses.
    haikuPlus.Controller.parseResponses = false;
    haikuPlus.Model.init(undefined);
    haikuPlus.View.updateUiControls();
    haikuPlus.Model.getCurrentUser();

    var headers = {
      'X-OAuth-Code':
          "Bearer realm='https://www.google.com/accounts/AuthSubRequest'"
    };

    server.requests[0].respond(401, headers, JSON.stringify({}));

    document.cookie = '';
  });

  /**
   * The tear down method called to clean up any altered data.
   */
  afterEach(function() {
    server.restore();
    $('#' + haikuPlus.View.REAUTHORIZATION_MODAL).dialog('close');
  });

  /**
   * Basic test that the client is requesting the expected endpoint
   * at initialization.
   */
  it('testApiEndpoint', function() {
    // Test we are hitting the right endpoint
    expect(server.requests[0].url)
          .toBe('/api/users/me');
  });

  /**
   * Test that the client is not passing a valid header.
   */
  it('testValidHeader', function() {
    expect(server.requests[0].requestHeaders[C_AUTH_HEADER]).toBe(
        undefined);
  });

  /**
   * Test that the client disconnects if it is out of sync with the server.
   */
  it('testUnAuthReconnectClient', function() {
    if (haikuPlus.Model.DISCONNECT_CLIENTSIDE) {
      expect(server.requests[1].url).toBe(
        haikuPlus.Model.DISCONNECT_API_ENDPOINT +
        GAPI_AUTH_AUTHORIZE.access_token);
    }
  });

  /**
   * Test that the reconnect form is displayed on 401 X-OAuth-Code.
   */
  it('testUnAuthReconnectServer', function() {
    if (!haikuPlus.Model.DISCONNECT_CLIENTSIDE) {
      var reauthForm = $('#' + haikuPlus.View.REAUTHORIZATION_MODAL);

      var expected = true;
      var actual = reauthForm.dialog('isOpen');

      expect(actual).toBe(expected);
    }
  });

  /**
   * Test that the reconnect form is hidden.
   */
  it('testUnAuthReconnectServer', function() {
    if (!haikuPlus.Model.DISCONNECT_CLIENTSIDE) {
      var reauthForm = $('#' + haikuPlus.View.REAUTHORIZATION_MODAL);

      var expected = true;
      var actual = reauthForm.dialog('isOpen');

      expect(actual).toBe(expected);
    }
  });

  /**
   * R.c2 Respond to a 401 X-OAuth-Code server response with a new
   * request which includes an authorization code.
   *
   * Note that this test is for the response for when the server needs
   * the client to authenticate.
   */
  it('testXNoAuthCode', function() {
    // Test for authorization header getting defined.
    expect(server.requests[0].requestHeaders[C_X_OAUTH_CODE]).not
          .toBeDefined();
  });

  /**
   * R.c2 Respond to a 401 X-OAuth-Code server response with a new
   * request which includes an authorization code.
   *
   * Note that this test is for the response for when the server needs
   * the client to authenticate.
   */
  it('testXNoAuthCodePresent', function() {
    // Simulate reconnecting the client.
    haikuPlus.Model.authorizeClientWithCode(gapi.auth.getToken().code);

    expect(server.requests[1].requestHeaders[C_X_OAUTH_CODE])
        .toBe(GAPI_AUTH_GETTOKEN.code);
  });

  /**
   * R.c3 Client assumes that if it has a session ID from previous
   * interactions, it is authenticated unless it receives a 401
   * response.
   */
  it('testIsAuthWithoutSessionId', function() {
    haikuPlus.Model.init();
    expect(haikuPlus.Model.isAuthorized()).toBe(false);
  });

  /**
   * R.c6 Client Authorization Bearer response matches specification.
   */
  it('testBearerResponseTest', function() {
    haikuPlus.Model.getCurrentUser();

    server.requests[0].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    // Test we are hitting the right endpoint
    expect(server.requests[0].url)
          .toBe('/api/users/me');

    // Test for authorization header getting defined.
    expect(server.requests[0].requestHeaders['Authorization']).toBe(
        undefined);
  });

  /**
   * R.c6 Client Authorization Bearer response matches specification.
   */
  it('testBearerResponseAuthHeader', function() {
    haikuPlus.Model.getCurrentUser();

    server.requests[0].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    // Test for authorization header getting defined.
    expect(server.requests[0].requestHeaders['Authorization']).toBe(
        undefined);
  });

  /**
   * R.c7 Client Authorization X-OAuth-Client response matches specification.
   * This test is for when the server has an invalid refresh token.
   */
  it('testXOauthResponse', function() {
    haikuPlus.Model.getCurrentUser();

    server.requests[0].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    // Test we are hitting the right endpoint
    expect(server.requests[0].url)
          .toBe('/api/users/me');

    // Test for authorization header getting passed.
    expect(server.requests[0].requestHeaders['X-OAuth-Code']).not
          .toBeDefined();
  });
});

/**
 * Tests related to 401 'WWW-Authenticate' responses from the server.
 */
describe('API response tests (Authentication)', function() {
  /**
   * The setup method called before each test.
   */
  beforeEach(function() {
    gapi = gapi || {};
    gapi.auth = gapi.auth || {};
    gapi.auth.signOut = function() {};
    server = sinon.fakeServer.create();

    // Initialize the haikuPlus namespace and trigger authorization.
    haikuPlus.Model.init(undefined);
    haikuPlus.Controller.parseResponses = false;
    haikuPlus.View.updateUiControls();
    haikuPlus.Model.getCurrentUser();
    haikuPlus.Model.hasAuth = true;
    haikuPlus.Model.init(GAPI_AUTH_AUTHORIZE);

    // Create headers object with not authenticated header and respond.
    var headers = {
      'Content-Type': 'application/json',
    };
    headers[haikuPlus.Model.S_401_HEADER_SESSION_NOT_AUTHENTICATED] =
      haikuPlus.Model.S_401_BEARER_GOOGLE;
    server.requests[0].respond(401, headers,
        JSON.stringify({}));
  });

  /**
   * The tear down method called to clean up any altered data.
   */
  afterEach(function() {
    server.restore();
    $('#' + haikuPlus.View.REAUTHORIZATION_MODAL).dialog('close');
  });

  /**
   * Respond to a 401 Bearer server response with a new request
   * which includes an ID token.
   */
  it('testBearerResponseAuthHeader', function() {
    server.requests[1].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    actual = server.requests[1].requestHeaders[haikuPlus.Model.C_AUTH_HEADER];
    expected = haikuPlus.Model.C_AUTH_BEARER + GAPI_AUTH_AUTHORIZE.id_token;
    expect(expected).toBe(actual);
  });

  /**
   * Respond to a 401 Bearer server response with a new request
   * which does not include an access token.
   */
  it('testBearerResponseAuthNotAccessToken', function() {
    server.requests[1].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    actual = server.requests[1].requestHeaders[haikuPlus.Model.C_AUTH_HEADER];
    expected = haikuPlus.Model.C_AUTH_BEARER + GAPI_AUTH_AUTHORIZE.access_token;
    expect(expected).not.toBe(actual);
  });

  /**
   * R.c1: Respond to a 401 Bearer server response with a new request
   * which does not include an authorization code.
   */
  it('testBearerResponseAuthNotAuthCode', function() {
    server.requests[1].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    actual = server.requests[1].requestHeaders[haikuPlus.Model.C_AUTH_HEADER];
    expected = haikuPlus.Model.C_AUTH_BEARER + GAPI_AUTH_AUTHORIZE.code;
    expect(expected).not.toBe(actual);
  });

  /**
   * R.c1: Test that we are calling the right endpoint.
   */
  it('testAuthenticateEndpoint', function() {
    // Test we are hitting the right endpoint
    expect(server.requests[0].url)
          .toBe('/api/users/me');
  });

  /**
   * R.c1: Test that we are resending to the right endpoint.
   */
  it('testAuthenticateEndpointResend', function() {
    // Test we are hitting the right endpoint
    expect(server.requests[1].url)
          .toBe('/api/users/me');
  });
});

/**
 * Perform the same tests as before, this time, mock an authorized client.
 */
describe('API response tests (authorized)', function() {
  /**
   * The setup method called before each test.
   */
  beforeEach(function() {
    haikuPlus.Model.init(GAPI_AUTH_AUTHORIZE);

    document.cookie = haikuPlus.Model.COOKIE_KEY + '="abcdefg"';

    // Simulate reauthorization
    server = sinon.fakeServer.create();

    haikuPlus.Model.authorizeClientWithCode(GAPI_AUTH_AUTHORIZE.code);

    server.requests[0].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    document.cookie = '';
  });

  /**
   * The tear down method called to clean up any altered data.
   */
  afterEach(function() {
    server.restore();

    var mydate = new Date();
    mydate.setTime(mydate.getTime() - 1);
    document.cookie = "username=; expires=" + mydate.toGMTString();
  });

  /**
   * R.c1 Respond to a 401 Bearer server response with a new request
   * which includes an ID token or access token.
   */
  it('testAuthBearer', function() {
    // Test we are hitting the right endpoint
    expect(server.requests[0].url)
          .toBe('/api/users/me');
  });

  /**
   * R.c2 Respond to a 401 X-OAuth-Code server response with a new
   * request which includes an authorization code.
   */
  it('testXAuthCode', function() {
    // Test we are hitting the right endpoint
    expect(server.requests[0].url).toBe('/api/users/me');

    // Test for authorization header getting defined.
    expect(server.requests[0].requestHeaders[C_X_OAUTH_CODE]).toBe(
        GAPI_AUTH_AUTHORIZE.code);
  });

  /**
   * R.c3 Client assumes that if it has a session ID from previous
   * interactions, it is authenticated unless it receives a 401
   * response. This should
   */
  it('testIsAuthWithSessionId', function() {
    expect(haikuPlus.Model.isAuthorized()).toBe(true);
  });

  /**
   * R.c4 Haiku clients maintain a session identifier in a cookie.
   */
  it('testHasSessionIdentifierNoAuth', function() {
    expect(haikuPlus.Model.isAuthorized()).toBe(true);
  });
});

/*
 * u3 UTestUserLoginUnaut
 */
describe('Test user login (unauthorized)', function() {
  /**
   * The setup method called before each test.
   */
  beforeEach(function() {
    haikuPlus.Controller.signOutUser();
  });

  /**
   * The tear down method called to clean up any altered data.
   */
  afterEach(function() { });

  /**
   * R.c9 Client displays a Google+ sign in button if the user is not
   * currently authenticated.
   */
  it('testSignInTriggersHideButton', function() {
    expect($('#' + haikuPlus.View.SIGNIN_CONTAINER).css('display')).not.
        toBe('none');
  });

  /**
     * R.c12 Client !displays create haiku button if the user is currently
     * authenticated.
     */
  it('testSignInTriggersCreateHaiku', function() {
    expect($('#' + haikuPlus.View.CREATE_BUTTON).attr('disabled')).
        toBe('disabled');
  });
});

/**
 * u5 UTestGetUser
 *   isAuth = false
 * Retrieve a user with authorized session
 * a. User object for the current user is returned
 * b. User is the correct user
 * c. User is valid
 * u6
 *
 * UTestGetUser
 *   isAuth = true
 * Retrieve a user with unauthorized session
 * a. Session not authenticated
 */
describe('Test user login (authorized)', function() {
  /**
   * The setup method called before each test.
   */
  beforeEach(function() {
    console.log( $('#create-button').attr('class') );
    gapi = gapi || {};
    gapi.auth = gapi.auth || {};
    gapi.auth.signOut = function() {};

    server = sinon.fakeServer.create();
    mockDate = new Date();

    haikuPlus.View.updateUiControls();
    haikuPlus.Controller.onSignInCallback(GAPI_AUTH_AUTHORIZE);

    server.requests[0].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify(mockUser));
  });

  /**
   * The tear down method called to clean up any altered data.
   */
  afterEach(function() {
    server.restore();
    haikuPlus.View.resetUI();
    haikuPlus.Model.currUser = undefined;
  });

  /**
   * R.c9 Client displays a Google+ sign in button if the user is not
   * currently authenticated.
   */
  it('testSignInTriggersHideButton', function() {
    expect($('#signin-container').css('display')).toBe('none');
  });

  /**
   * R.c10 Client requests user data from /api/users/me if the user is
   * currently authenticated and displays the results.
   */
  it('testSignInTriggersDisplayMe', function() {
    var expected = 'Welcome back
test user name!              Sign out
      Disconnect  ';
    var actual = $('#' + haikuPlus.View.USER_PROFILE_CONTAINER).html();

    /*
    var profile =
        '' +
        '  ' +
        '    ' +
        '  ' +
        '' +
        '' + mockUser.google_display_name +
        '';
        console.log($('#' + haikuPlus.View.USER_PROFILE_CONTAINER).html());
    */

    expect(actual).toBe(expected);
  });

  /**
   * R.c12 Client displays create haiku button if the user is currently
   * authenticated.
   */
  it('testSignInTriggersCreateHaiku', function() {
    expect($('#create-button').attr('class')).not.toBeDefined;
  });

  /**
   * R.cx1: Clients will load the data required to display a view once
   * when the view is initially loaded.  Reloading the data will require
   * the view to be explicitly reloaded by the user.
   */
  it('testSignInTriggersHaikuList', function() {
    mockHtml = '';
    expect($('#create-button').attr('disabled')).not.toBeDefined;
  });
});

/**
 * Test signout and disconnect.
 */
describe('Signout and disconnect', function() {
  /**
   * The setup method called before each test.
   */
  beforeEach(function() {
    // Authorize the client.
    gapi.auth.authorize({}, haikuPlus.Model.init);

    // Simulate reauthorization
    server = sinon.fakeServer.create();

    haikuPlus.Model.getCurrentUser();

    server.requests[0].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify(mockUser));

    document.cookie = '';
  });

  /**
   * The tear down method called to clean up any altered data.
   */
  afterEach(function() {
    server.restore();
  });

  /**
   * R.c15: Clicking the sign out button signs the user out, hides the UI,
   * and removes the session cookie.
   */
  it('testSignOut', function(){
    haikuPlus.Controller.signOutUser();

    expect($('#' + haikuPlus.View.CREATE_BUTTON).attr('disabled')).
        toBe('disabled');
    expect($('#' + haikuPlus.View.SIGNIN_CONTAINER).css('display')).not.
        toBe('none');
    expect($('#' + haikuPlus.View.USER_PROFILE_CONTAINER).html()).toBe('');
  });

  /**
   * R.c15: Clicking the sign out button signs the user out, hides the UI,
   * and removes the session cookie.
   */
  it('testSignOut', function(){
    haikuPlus.Controller.signOutUser();

    var cookieStrings = document.cookie.split(';');

    for (var index=0; index < cookieStrings.length; index++){
      keyVal = cookieStrings[index].split['='];
      if (keyVal != undefined && keyVal[0] == haikuPlus.Model.COOKIE_KEY){
        var sessionId = cookieStrings[1];
        console.log(sessionId);
        expect(sessionId == undefined || (sessionId.length <= 0)).toBe(true);
      }
    }
  });

  /**
   * R.c16: Clicking disconnect performs a call to the server /api/disconnect.
   */
  it('testDisconnectHidesUI', function(){
    haikuPlus.Controller.disconnectUser();

    server.requests[1].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    expect($('#' + haikuPlus.View.CREATE_BUTTON).attr('disabled')).
        toBe('disabled');
    expect($('#' + haikuPlus.View.SIGNIN_CONTAINER).css('display')).not.
        toBe('none');
    expect($('#' + haikuPlus.View.USER_PROFILE_CONTAINER).html()).toBe("");
  });

  /**
   * Clicking disconnect performs a call to the server /api/disconnect.
   */
  it('testDisconnectCallsEndpoint', function(){
    haikuPlus.Controller.disconnectUser();

    server.requests[1].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    var actual = server.requests[1].url;
    var expected = haikuPlus.Model.DISCONNECT_ENDPOINT;

    expect(actual).toBe(expected);
  });

  /**
   * Test disconnect is making a POST call to the endpoint.
   */
  it('testDisconnectPostsEndpoint', function(){
    haikuPlus.Controller.disconnectUser();

    server.requests[1].respond(200, {'Content-Type': 'application/json'},
        JSON.stringify({}));

    var actual = server.requests[1].method;
    var expected = 'POST';

    expect(actual).toBe(expected);
  });
});

  /**
   * Test that API calls to each endpoint will trigger the callback.
   */


text:
<?php $this->load->view('template_header') ?><?php echo form_open(current_url()); ?>

    <?php echo $custom_error; ?>
    <?php echo form_hidden('id', $result->id) ?>

Nama*
      <input id="nama" type="text" name="nama" value="<?php echo $result->nama ?>"  />
      <?php echo form_error('nama', '
', '
'); ?>

Email*
      <input id="email" type="text" name="email" value="<?php echo $result->email ?>"  />
      <?php echo form_error('email', '
', '
'); ?>

Password*
      <input id="password" type="password" name="password" value="<?php echo $result->password ?>"  />
      <?php echo form_error('password', '
', '
'); ?>

Level*
      <select id="level" name="level">
        <option value="">-Pilih-</option>
        <?php
        foreach ($combolevel as $value) {
          if ($value['id'] == $result->level) {
            echo "<option selected value='" . $value['id'] . "'>" . $value['nama'] . "</option>";
          } else {
            echo "<option value='" . $value['id'] . "'>" . $value['nama'] . "</option>";
          }
        }
        ?>
      </select>
      <?php echo form_error('level', '
', '
'); ?>

      <?php echo form_submit('submit', 'Submit'); ?>

    <?php echo form_close(); ?>


text:
import lz4.stream
import pytest
import sys
import os

if sys.version_info < (3, ):
    from struct import pack, unpack

    def _get_format(length, byteorder, signed):
        _order = {'l': '<', 'b': '>'}
        _fmt = {1: 'b', 2: 'h', 4: 'i', 8: 'q'}
        _sign = {True: lambda x: x.lower(), False: lambda x: x.upper()}
        return _sign[signed](_order[byteorder[0].lower()] + _fmt[length])

    def int_to_bytes(value, length=4, byteorder='little', signed=False):
        return bytearray(pack(_get_format(length, byteorder, signed), value))

    def int_from_bytes(bytes, byteorder='little', signed=False):
        return unpack(_get_format(len(bytes), byteorder, signed), bytes)[0]

else:
    def int_to_bytes(value, length=4, byteorder='little', signed=False):
        return value.to_bytes(length, byteorder, signed=signed)

    def int_from_bytes(bytes, byteorder='little', signed=False):
        return int.from_bytes(bytes, byteorder, signed=signed)

# This test requires allocating a big lump of memory. In order to
# avoid a massive memory allocation during byte compilation, we have
# to declare a variable for the size of the buffer we're going to
# create outside the scope of the function below. See:
# https://bugs.python.org/issue21074
_4GB = 0x100000000  # 4GB

def compress(x, c_kwargs, return_block_offset=False, check_block_type=False):
    o = [0, ]
    if c_kwargs.get('return_bytearray', False):
        c = bytearray()
    else:
        c = bytes()
    with lz4.stream.LZ4StreamCompressor(**c_kwargs) as proc:
        for start in range(0, len(x), c_kwargs['buffer_size']):
            chunk = x[start:start + c_kwargs['buffer_size']]
            block = proc.compress(chunk)
            c += block
            if return_block_offset:
                o.append(len(c))
            if check_block_type:
                assert isinstance(block, c.__class__)
    if return_block_offset:
        return c, o
    else:
        return c

def decompress(x, d_kwargs, check_chunk_type=False):
    if d_kwargs.get('return_bytearray', False):
        d = bytearray()
    else:
        d = bytes()
    with lz4.stream.LZ4StreamDecompressor(**d_kwargs) as proc:
        start = 0
        while start < len(x):
            block = proc.get_block(x[start:])
            chunk = proc.decompress(block)
            d += chunk
            start += d_kwargs['store_comp_size'] + len(block)
            if check_chunk_type:
                assert isinstance(chunk, d.__class__)
    return d

def test_invalid_config_c_1():
    c_kwargs = {}
    c_kwargs['strategy'] = "ring_buffer"
    c_kwargs['buffer_size'] = 1024

    with pytest.raises(NotImplementedError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)

def test_invalid_config_d_1():
    d_kwargs = {}
    d_kwargs['strategy'] = "ring_buffer"
    d_kwargs['buffer_size'] = 1024

    with pytest.raises(NotImplementedError):
        lz4.stream.LZ4StreamDecompressor(**d_kwargs)

def test_invalid_config_c_2():
    c_kwargs = {}
    c_kwargs['strategy'] = "foo"
    c_kwargs['buffer_size'] = 1024

    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)

def test_invalid_config_d_2():
    d_kwargs = {}
    d_kwargs['strategy'] = "foo"
    d_kwargs['buffer_size'] = 1024

    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamDecompressor(**d_kwargs)

def test_invalid_config_c_3(store_comp_size):
    c_kwargs = {}
    c_kwargs['strategy'] = "double_buffer"
    c_kwargs['buffer_size'] = 1024
    c_kwargs['store_comp_size'] = store_comp_size['store_comp_size'] + 5

    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)

def test_invalid_config_d_3(store_comp_size):
    d_kwargs = {}
    d_kwargs['strategy'] = "double_buffer"
    d_kwargs['buffer_size'] = 1024
    d_kwargs['store_comp_size'] = store_comp_size['store_comp_size'] + 5

    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamDecompressor(**d_kwargs)

def test_invalid_config_c_4(store_comp_size):
    c_kwargs = {}
    c_kwargs['strategy'] = "double_buffer"
    c_kwargs['buffer_size'] = 1 << (8 * store_comp_size['store_comp_size'])
    c_kwargs.update(store_comp_size)

    if store_comp_size['store_comp_size'] >= 4:
        # No need for skiping this test case, since arguments check is
        # expecting to raise an error.

        # Make sure the page size is larger than what the input bound will be,
        # but still fit in 4 bytes
        c_kwargs['buffer_size'] -= 1

    if c_kwargs['buffer_size'] > lz4.stream.LZ4_MAX_INPUT_SIZE:
        message = r"^Invalid buffer_size argument: \d+. Cannot define output buffer size. Must be lesser or equal to 2113929216$"  # noqa
        err_class = ValueError
    else:
        message = r"^Inconsistent buffer_size/store_comp_size values. Maximal compressed length \(\d+\) cannot fit in a \d+ byte-long integer$"  # noqa
        err_class = lz4.stream.LZ4StreamError

    with pytest.raises(err_class, match=message):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)

def test_invalid_config_d_4(store_comp_size):
    d_kwargs = {}
    d_kwargs['strategy'] = "double_buffer"
    d_kwargs['buffer_size'] = 1 << (8 * store_comp_size['store_comp_size'])
    d_kwargs.update(store_comp_size)

    if store_comp_size['store_comp_size'] >= 4:

        if sys.maxsize < 0xffffffff:
            pytest.skip('Py_ssize_t too small for this test')

        # Make sure the page size is larger than what the input bound will be,
        # but still fit in 4 bytes
        d_kwargs['buffer_size'] -= 1

    # No failure expected during instanciation/initialization
    lz4.stream.LZ4StreamDecompressor(**d_kwargs)

def test_invalid_config_c_5():
    c_kwargs = {}
    c_kwargs['strategy'] = "double_buffer"
    c_kwargs['buffer_size'] = lz4.stream.LZ4_MAX_INPUT_SIZE

    if sys.maxsize < 0xffffffff:
        pytest.skip('Py_ssize_t too small for this test')

    # No failure expected
    lz4.stream.LZ4StreamCompressor(**c_kwargs)

    c_kwargs['buffer_size'] = lz4.stream.LZ4_MAX_INPUT_SIZE + 1
    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)

    # Make sure the page size is larger than what the input bound will be,
    # but still fit in 4 bytes
    c_kwargs['buffer_size'] = _4GB - 1  # 4GB - 1 (to fit in 4 bytes)
    with pytest.raises(ValueError):
        lz4.stream.LZ4StreamCompressor(**c_kwargs)

def test_invalid_config_d_5():
    d_kwargs = {}
    d_kwargs['strategy'] = "double_buffer"

    # No failure expected during instanciation/initialization
    d_kwargs['buffer_size'] = lz4.stream.LZ4_MAX_INPUT_SIZE

    if sys.maxsize < 0xffffffff:
        pytest.skip('Py_ssize_t too small for this test')

    lz4.stream.LZ4StreamDecompressor(**d_kwargs)

    # No failure expected during instanciation/initialization
    d_kwargs['buffer_size'] = lz4.stream.LZ4_MAX_INPUT_SIZE + 1

    if sys.maxsize < 0xffffffff:
        pytest.skip('Py_ssize_t too small for this test')

    lz4.stream.LZ4StreamDecompressor(**d_kwargs)

    # No failure expected during instanciation/initialization
    d_kwargs['buffer_size'] = _4GB - 1  # 4GB - 1 (to fit in 4 bytes)

    if sys.maxsize < 0xffffffff:
        pytest.skip('Py_ssize_t too small for this test')

    lz4.stream.LZ4StreamDecompressor(**d_kwargs)

def test_decompress_corrupted_input_1():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = compress(b'A' * 512, c_kwargs)
    decompress(data, d_kwargs)

    message = r"^Requested input size \(\d+\) larger than source size \(\d+\)$"

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data[4:], d_kwargs)

def test_decompress_corrupted_input_2():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = compress(b'A' * 512, c_kwargs)
    decompress(data, d_kwargs)

    message = r"^Decompression failed. error: \d+$"

    # Block size corruption in the first block

    # Block size longer than actual:
    data = int_to_bytes(int_from_bytes(data[:4], 'little') + 1, 4, 'little') + data[4:]
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

    # Block size shorter than actual:
    data = int_to_bytes(int_from_bytes(data[:4], 'little') - 2, 4, 'little') + data[4:]
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

def test_decompress_corrupted_input_3():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = compress(b'A' * 512, c_kwargs)
    decompress(data, d_kwargs)

    message = r"^Decompression failed. error: \d+$"

    # Block size corruption in a block in the middle of the stream
    offset = 4 + int_from_bytes(data[:4], 'little')

    # Block size longer than actual:
    block_len = int_from_bytes(data[offset:offset + 4], 'little') + 1
    data = data[:offset] + int_to_bytes(block_len, 4, 'little') + data[offset + 4:]

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

    # Block size shorter than actual:
    block_len = int_from_bytes(data[offset:offset + 4], 'little') - 2
    data = data[:offset] + int_to_bytes(block_len, 4, 'little') + data[offset + 4:]

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

def test_decompress_corrupted_input_4():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = compress(b'A' * 256, c_kwargs)
    decompress(data, d_kwargs)

    # Block size corruption in the last block of the stream
    offset = 4 + int_from_bytes(data[:4], 'little')

    # Block size longer than actual:
    block_len = int_from_bytes(data[offset:offset + 4], 'little') + 1
    data = data[:offset] + int_to_bytes(block_len, 4, 'little') + data[offset + 4:]

    message = r"^Requested input size \(\d+\) larger than source size \(\d+\)$"

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

    # Block size shorter than actual:
    block_len = int_from_bytes(data[offset:offset + 4], 'little') - 2
    data = data[:offset] + int_to_bytes(block_len, 4, 'little') + data[offset + 4:]

    message = r"^Decompression failed. error: \d+$"

    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(data, d_kwargs)

def test_decompress_truncated():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123" * 24
    compressed, block_offsets = compress(input_data, c_kwargs, return_block_offset=True)

    last_block_offset = 0
    for n in range(len(compressed)):
        if n in block_offsets:
            # end of input matches end of block, so decompression must succeed
            last_block_offset = n
            decompress(compressed[:n], d_kwargs)

        else:
            # end of input does not match end of block, so decompression failure is expected
            if n - last_block_offset < c_kwargs['store_comp_size']:
                message = "^Invalid source, too small for holding any block$"
            else:
                message = r"^Requested input size \(\d+\) larger than source size \(\d+\)$"

            with pytest.raises(lz4.stream.LZ4StreamError, match=message):
                decompress(compressed[:n], d_kwargs)

# This next test is probably redundant given test_decompress_truncated above
# since the trailing bytes will be considered as the truncated last block, but
# we will keep them for now

def test_decompress_with_trailer():
    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = b'A' * 64
    comp = compress(data, c_kwargs)

    message = "^Invalid source, too small for holding any block$"
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(comp + b'A', d_kwargs)

    message = r"^Requested input size \(\d+\) larger than source size \(\d+\)$"
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(comp + b'A' * 10, d_kwargs)

    for n in range(1, 10):
        if n < d_kwargs['store_comp_size']:
            message = "^Invalid source, too small for holding any block$"
        else:
            message = r"^Decompression failed. error: \d+$"
        with pytest.raises(lz4.stream.LZ4StreamError, match=message):
            decompress(comp + b'\x00' * n, d_kwargs)

def test_unicode():
    if sys.version_info < (3,):
        return  # skip

    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    DATA = b'x'
    with pytest.raises(TypeError):
        compress(DATA.decode('latin1'), c_kwargs)
        decompress(compress(DATA, c_kwargs).decode('latin1'), d_kwargs)

# These next two are probably redundant given test_1 above but we'll keep them
# for now

def test_return_bytearray():
    if sys.version_info < (3,):
        return  # skip

    c_kwargs_r = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}
    c_kwargs = {'return_bytearray': True}
    c_kwargs.update(c_kwargs_r)

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = os.urandom(128 * 1024)  # Read 128kb
    compressed = compress(data, c_kwargs_r, check_block_type=True)
    b = compress(data, c_kwargs, check_block_type=True)
    assert isinstance(b, bytearray)
    assert bytes(b) == compressed
    b = decompress(compressed, d_kwargs, check_chunk_type=True)
    assert isinstance(b, bytearray)
    assert bytes(b) == data

def test_memoryview():
    if sys.version_info < (2, 7):
        return  # skip

    c_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    d_kwargs = {}
    d_kwargs.update(c_kwargs)

    data = os.urandom(128 * 1024)  # Read 128kb
    compressed = compress(data, c_kwargs)
    assert compress(memoryview(data), c_kwargs) == compressed
    assert decompress(memoryview(compressed), d_kwargs) == data

def test_with_dict_none():
    kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123" * 24
    for mode in ['default', 'high_compression']:
        c_kwargs = {'mode': mode, 'dictionary': None}
        c_kwargs.update(kwargs)
        d_kwargs = {}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode}
        c_kwargs.update(kwargs)
        d_kwargs = {'dictionary': None}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode, 'dictionary': b''}
        c_kwargs.update(kwargs)
        d_kwargs = {}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode}
        c_kwargs.update(kwargs)
        d_kwargs = {'dictionary': b''}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode, 'dictionary': ''}
        c_kwargs.update(kwargs)
        d_kwargs = {}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

        c_kwargs = {'mode': mode}
        c_kwargs.update(kwargs)
        d_kwargs = {'dictionary': ''}
        d_kwargs.update(kwargs)
        assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

def test_with_dict():
    kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    input_data = b"2099023098234882923049823094823094898239230982349081231290381209380981203981209381238901283098908123109238098123" * 24
    dict1 = input_data[10:30]
    dict2 = input_data[20:40]
    message = r"^Decompression failed. error: \d+$"

    for mode in ['default', 'high_compression']:
        c_kwargs = {'mode': mode, 'dictionary': dict1}
        c_kwargs.update(kwargs)
        compressed = compress(input_data, c_kwargs)

        d_kwargs = {}
        d_kwargs.update(kwargs)
        with pytest.raises(lz4.stream.LZ4StreamError, match=message):
            decompress(compressed, d_kwargs)

        d_kwargs = {'dictionary': dict1[:2]}
        d_kwargs.update(kwargs)
        with pytest.raises(lz4.stream.LZ4StreamError, match=message):
            decompress(compressed, d_kwargs)

        d_kwargs = {'dictionary': dict2}
        d_kwargs.update(kwargs)
        assert decompress(compressed, d_kwargs) != input_data

        d_kwargs = {'dictionary': dict1}
        d_kwargs.update(kwargs)
        assert decompress(compressed, d_kwargs) == input_data

    c_kwargs = {}
    c_kwargs.update(kwargs)
    d_kwargs = {'dictionary': dict1}
    d_kwargs.update(kwargs)
    assert decompress(compress(input_data, c_kwargs), d_kwargs) == input_data

def test_known_decompress_1():
    d_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    output = b''

    input = b'\x00\x00\x00\x00'
    message = "^Decompression failed. error: 1$"
    with pytest.raises(lz4.stream.LZ4StreamError, match=message):
        decompress(input, d_kwargs)

    input = b'\x01\x00\x00\x00\x00'
    assert decompress(input, d_kwargs) == output

def test_known_decompress_2():
    d_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    input = b'\x02\x00\x00\x00\x10 '
    output = b' '
    assert decompress(input, d_kwargs) == output

def test_known_decompress_3():
    d_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    # uncompressed data size smaller than buffer_size
    input = b'%\x00\x00\x00\xff\x0bLorem ipsum dolor sit amet\x1a\x006P amet'
    output = b'Lorem ipsum dolor sit amet' * 4
    assert decompress(input, d_kwargs) == output

def test_known_decompress_4():
    d_kwargs = {'strategy': "double_buffer", 'buffer_size': 128, 'store_comp_size': 4}

    input = b'%\x00\x00\x00\xff\x0bLorem ipsum dolor sit amet\x1a\x00NPit am\n\x00\x00\x00\x0fh\x00hP sit \x05\x00\x00\x00@amet'
    output = b'Lorem ipsum dolor sit amet' * 10
    assert decompress(input, d_kwargs) == output


text:
#include <aws/directconnect/model/AssociateHostedConnectionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::DirectConnect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

AssociateHostedConnectionRequest::AssociateHostedConnectionRequest() :
    m_connectionIdHasBeenSet(false),
    m_parentConnectionIdHasBeenSet(false)
{
}

Aws::String AssociateHostedConnectionRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_connectionIdHasBeenSet)
  {
   payload.WithString("connectionId", m_connectionId);

  }

  if(m_parentConnectionIdHasBeenSet)
  {
   payload.WithString("parentConnectionId", m_parentConnectionId);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection AssociateHostedConnectionRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "OvertureService.AssociateHostedConnection"));
  return headers;

}


text:
var currUrl = 'http://localhost/Travel/';
//var currUrl = 'http://'+window.location.hostname+'/';
//post form setting
var postForm = function() {
    var content_vi = $('textarea[name="content_vi"]').html($('#summernote').code());
    var content_en = $('textarea[name="content_en"]').html($('#summernote').code());
    var price_cnt_vi = $('textarea[name="price_cnt_vi"]').html($('#summernote').code());
    var price_cnt_en = $('textarea[name="price_cnt_en"]').html($('#summernote').code());
    var note_vi = $('textarea[name="note_vi"]').html($('#summernote').code());
    var note_en = $('textarea[name="note_en"]').html($('#summernote').code());
};
//dropbox change function

$(document).ready(function() {
    $(document.body).on("change","#drb_national",function(){
        $.ajax({
            //url:"<?php echo base_url('admin_tours/getLocation'); ?>",
            url:currUrl+"admin_tours/getLocation",
            data: {national: $(this).val()},
            type: "POST",
            success: function(data){

                $("#drb_province").html(data);
            }
        });
    });
    $(document.body).on("change","#str_arv_national",function(){
        $.ajax({
            url:currUrl+"admin_tours/getLocation",
            data: {national: $(this).val()},
            type: "POST",
            success: function(data){

                $("#str_arv_province").html(data);
            }
        });
    });
    $(document.body).on("change","#str_dpt_national",function(){
        $.ajax({
            url:currUrl+"admin_tours/getLocation",
            data: {national: $(this).val()},
            type: "POST",
            success: function(data){

                $("#str_dpt_province").html(data);
            }
        });
    });
    $(document.body).on("change","#end_arv_national",function(){
        $.ajax({
            url:currUrl+"admin_tours/getLocation",
            data: {national: $(this).val()},
            type: "POST",
            success: function(data){

                $("#end_arv_province").html(data);
            }
        });
    });
    $(document.body).on("change","#end_dpt_national",function(){
        $.ajax({
            url:currUrl+"admin_tours/getLocation",
            data: {national: $(this).val()},
            type: "POST",
            success: function(data){

                $("#end_dpt_province").html(data);
            }
        });
    });
    $(document.body).on("change","#drb_newCate",function(){
        $.ajax({
            url:currUrl+"admin_news/getAllPostByCateId",
            data: {cateId: $(this).val()},
            type: "POST",
            success: function(data){

                $("#newsListCnt1").html(data);
            }
        });
    });
});

//image management script
$(document).ready(function(){
    var img_var = 1;
    var strImgApp = '
Thêm Ảnh';
    strImgApp +='

';
    strImgApp +='

';
    strImgApp +='Change';
    strImgApp +='Select file<input type="file" name="tour_img'+img_var+'" required/>';
    strImgApp +='Remove

';
    strImgApp +='
<input name="image_n0'+img_var+'" id="image_n0'+img_var+'" data-role="tagsinput" data-tag-class="label label-primary" class="form-control" value="" placeholder="Mô tả" required="required"/>';
    strImgApp +='

.';
    $("#add_images").click(function(){
        $("#images_upload").append(strImgApp);
        img_var ++;
        strImgApp = '
Thêm Ảnh';
        strImgApp +='

';
        strImgApp +='

';
        strImgApp +='Change';
        strImgApp +='Select file<input type="file" name="tour_img'+img_var+'" required/>';
        strImgApp +='Remove

';
        strImgApp +='
<input name="image_n0'+img_var+'" id="image_n0'+img_var+'" data-role="tagsinput" data-tag-class="label label-primary" class="form-control" value="" placeholder="Mô tả" required="required"/>';
        strImgApp +='

.';
    });
});
// schedule change status
function changeStatus(divID, cbxID, cntID){
    var e = document.getElementById(cbxID);
    var cbxValue = e.options[e.selectedIndex].value;
    if(cbxValue == 'D'){
        $( "#"+divID ).removeClass().addClass( "form-group has-error" );
        $( "#"+cntID ).removeClass().addClass( "form-group has-error" );
    }else{
        $( "#"+divID ).removeClass().addClass( "form-group has-success" );
        $( "#"+cntID ).removeClass().addClass( "form-group has-success" );
    }
}
//schedule management script
$(document).ready(function(){
    var scd_var = 0;
    var strscdApp = '';
    $("#add_schedule").click(function(){
        scd_var ++;

        strscdApp = '

';
        strscdApp +='<input type="text" class="form-control" name="txt_day_'+scd_var+'" id="txt_day_'+scd_var+'"';
        strscdApp +='placeholder="Ngày thứ (Số)" value="" required="required">
';
        strscdApp +='
<input type="text" class="form-control" name="start_time_'+scd_var+'"';
        strscdApp +='id="start_time_'+scd_var+'" placeholder="Thời gian bắt đầu. (06:30 AM)" ';
        strscdApp +='value="" required="required">

';
        strscdApp +='<input type="text" class="form-control" name="end_time_'+scd_var+'" id="end_time_'+scd_var+'"';
        strscdApp +='placeholder="Thời gian kết thúc. (06:30 PM)" value="" required="required">';
        strscdApp +='

';
        strscdApp +='
';
        strscdApp +='

';
        strscdApp +='<textarea class="form-control" rows="5" id="cnt_vi_'+scd_var+'" name="cnt_vi_'+scd_var+'"';
        strscdApp +='placeholder="Nội dung kế hoạch - Tiếng Việt"required="required"></textarea>';
        strscdApp +='

';
        strscdApp +='<textarea class="form-control" rows="5" id="cnt_en_'+scd_var+'" name="cnt_en_'+scd_var+'"';
        strscdApp +='placeholder="Nội dung kế hoạch - Tiếng Anh" required="required"></textarea>';
        strscdApp +='

';

        $("#schedule_upload").append(strscdApp);
    });
});


text:
package scan

type TokenMatcher struct {
	Defs    []*IDMatcher
	EOF     int
	Illegal int
}
type IDMatcher struct {
	Matcher Matcher
	ID      int
}

func (m *TokenMatcher) Match(buf []byte) (id, size int) {
	if len(buf) == 0 {
		return m.EOF, 0
	}
	for _, d := range m.Defs {
		if size, ok := d.Matcher.Match(buf); ok {
			return d.ID, size
		}
	}
	return m.Illegal, 1 // advance 1 byte when illegal
}


text:
function main(FrameworkFactory) {

    var components = FrameworkFactory.create({
        name: "components",
        version: "1.0"
    });

    //Helper class for testing readonly properties
    components.ReadonlyClass = components.Class({

        type: 'ReadonlyClass',

        readonly: components.readonly(true),

        readonly2: components.readonly({
            default: 10,
            get: function() {
                return this._readonly2;
            }
        }),

        readonly3: components.readonly({
            get: function() {
                return this._readonly3;
            }
        }),

        readonly4: components.readonly({
            default: false,
            get: function() {
                return this._readonly4;
            },
            set: function(v) {
                console.log("This function should never be called.");
            }
        }),

        init: function(v) {
            this._readonly3 = v;
        }
    });

    //Helper class for testing readonly properties
    components.PropertyClass = components.Class({

        p1: components.property(10),

        p2: components.property({
            default: 20,
            get: function() {
                return this._p2;
            },
            set: function (v) {
                this._p2 = v;
            }
        }),

        p3: components.property({
            get: function() {
                return this._p3;
            },
            set: function(v) {
                this._p3 = v;
            }
        }),

        p4: components.property({
            get: function() {
                return true;
            }
        }),

        init: function(v) {
            this._p3 = v;
        },

    });

    // components.ObservableClass = components.Class({

    //     name: components.observable("buddy"),

    //     age: components.observable(30)

    // });

    window.components = components;
    return components;

}

//Load environment
if (typeof module !== "undefined" && typeof module.exports === "object") {
    module.exports = main;
}
else {
    main(this.FrameworkFactory);
}


text:
<?php

namespace Symfony\Component\Serializer\Mapping;

/**
 * Stores metadata needed for serializing and deserializing attributes.
 *
 * Primarily, the metadata stores serialization groups.
 *
 * @internal
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface AttributeMetadataInterface
{
    /**
     * Gets the attribute name.
     */
    public function getName(): string;

    /**
     * Adds this attribute to the given group.
     */
    public function addGroup(string $group);

    /**
     * Gets groups of this attribute.
     *
     * @return string[]
     */
    public function getGroups(): array;

    /**
     * Sets the serialization max depth for this attribute.
     */
    public function setMaxDepth(?int $maxDepth);

    /**
     * Gets the serialization max depth for this attribute.
     *
     * @return int|null
     */
    public function getMaxDepth();

    /**
     * Sets the serialization name for this attribute.
     */
    public function setSerializedName(string $serializedName = null);

    /**
     * Gets the serialization name for this attribute.
     */
    public function getSerializedName(): ?string;

    /**
     * Sets if this attribute must be ignored or not.
     */
    public function setIgnore(bool $ignore);

    /**
     * Gets if this attribute is ignored or not.
     */
    public function isIgnored(): bool;

    /**
     * Merges an {@see AttributeMetadataInterface} with in the current one.
     */
    public function merge(self $attributeMetadata);
}


text: from . import expression_nodes


text:
namespace v8 {
namespace internal {

static const int kX0DwarfCode = 0;
static const int kFpDwarfCode = 29;
static const int kLrDwarfCode = 30;
static const int kSpDwarfCode = 31;

const int EhFrameConstants::kCodeAlignmentFactor = 4;
const int EhFrameConstants::kDataAlignmentFactor = -8;

void EhFrameWriter::WriteReturnAddressRegisterCode() {
  WriteULeb128(kLrDwarfCode);
}

void EhFrameWriter::WriteInitialStateInCie() {
  SetBaseAddressRegisterAndOffset(x29, 0);
  RecordRegisterNotModified(x30);
}

// static
int EhFrameWriter::RegisterToDwarfCode(Register name) {
  switch (name.code()) {
    case kRegCode_x29:
      return kFpDwarfCode;
    case kRegCode_x30:
      return kLrDwarfCode;
    case kSPRegInternalCode:
      return kSpDwarfCode;
    case kRegCode_x0:
      return kX0DwarfCode;
    default:
      UNIMPLEMENTED();
      return -1;
  }
}

#ifdef ENABLE_DISASSEMBLER

// static
const char* EhFrameDisassembler::DwarfRegisterCodeToString(int code) {
  switch (code) {
    case kFpDwarfCode:
      return "fp";
    case kLrDwarfCode:
      return "lr";
    case kSpDwarfCode:
      return "sp";  // This could be zr as well
    default:
      UNIMPLEMENTED();
      return nullptr;
  }
}

#endif

}  // namespace internal
}  // namespace v8


text:
App = Ember.Application.create({
    LOG_TRANSITIONS: true
});

App.Status = Ember.Map.create({
    status: "connecting",
    statusChange: function() {
        console.log("Status changes", this.get("status"));
    }.observes("status")
});

App.Router.map(function() {
  this.resource("setup");
  this.resource("settings");
});

App.ApplicationController = Ember.Controller.extend({
    status: "connecting",
    setupStep: 0,
    updateStatus: function() {
        var status = this.get("status");
        if(status == "setup") {
            this.transitionTo("setup");
            this.set("step1", (step == 1));
            this.set("step2", (step == 2));
            this.set("step3", (step == 3));
        }
        console.log(status);
    }
});

App.ApplicationRoute = Ember.Route.extend({
    setupController: function() {
        var self = this;
        console.log("Initialize socket.io");
        if(!io) console.log("Socket.io could not load");

        var socket = io.connect();
        socket.on("status", function(data) {
            for(var i in data) {
                self.get("controller").set(i, data[i]);
            }
            self.get("controller").updateStatus();
        });

        this.get("controller").set("socket", socket);
    }
});

App.SetupController = Ember.Controller.extend({
    needs: ["application"],
    actions: {
        authorize: function() {
            console.log("Auth");
        }
    }
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return {
        alarm: {
            next: "13:37",
            lesson: {
                time: "12:37",
                type: "Math"
            },
            wakeTime: "1:00"
        }
    };
  }
});


text:
set(ANDROID_COMPILER_VERSION "4.9")
set(ANDROID_NDK_VERSION 21)

# Detect the NDK root directory
if(NOT ANDROID_NDK_ROOT)
    # Using the installed NDK for the android compilers
    set(ANDROID_NDK_ROOT "$ENV{ANDROID_NDK_ROOT}")
    if(NOT ANDROID_NDK_ROOT)
        # TODO: search well known locations for an NDK?
        message(FATAL_ERROR "You must have ANDROID_NDK_ROOT set")
    endif()
    string(REPLACE "\\" "/" ANDROID_NDK_ROOT "${ANDROID_NDK_ROOT}")
endif()

# Define and document the set of variables each android abi must declare
set(ANDROID_ABI_VARS
        ANDROID_ABI_NAME # The normal name of the abi
        ANDROID_ABI_PATH # The path used in the installed package for this abi
        ANDROID_BUILD_PATH # The path used by the build system for this abi
        ANDROID_PROCESSOR # The processor name this abi targets
        ANDROID_C_FLAGS # The extra c flags to use when compiling for this abi
        ANDROID_SYSTEM_ARCH # The ndk system architecture to use to compile for this abi
        ANDROID_TOOLCHAIN_PREFIX # The prefix to the specific host to android abi compiler tools
        # Constructed variables
        ANDROID_GCC_PATH # The path to the gcc tool for this abi
        ANDROID_GXX_PATH # The path to the g++ tool for this abi
        ANDROID_RANLIB_PATH # The path to the ranlib tool for this abi
        ANDROID_AR_PATH # The path to the ar tool for this abi
        ANDROID_LD_PATH # The path to the ld tool for this abi
)

set(ANDROID_ABI_NAME_armeabi "armeabi")
set(ANDROID_ABI_PATH_armeabi "armeabi-v7a")
set(ANDROID_BUILD_PATH_armeabi "android-armv7a")
set(ANDROID_PROCESSOR_armeabi "armv5te")
set(ANDROID_C_FLAGS_armeabi "-mthumb -march=armv7-a -mfpu=vfpv3-d16 -mfloat-abi=softfp")
set(ANDROID_SYSTEM_ARCH_armeabi "arm")

set(ANDROID_ABI_NAME_aarch64 "arm64-v8a")
set(ANDROID_ABI_PATH_aarch64 "arm64-v8a")
set(ANDROID_BUILD_PATH_aarch64 "android-armv8a")
set(ANDROID_PROCESSOR_aarch64 "aarch64")
set(ANDROID_C_FLAGS_aarch64 "")
set(ANDROID_SYSTEM_ARCH_aarch64 "arm64")

set(ANDROID_ABI_NAME_x86 "x86")
set(ANDROID_ABI_PATH_x86 "x86")
set(ANDROID_BUILD_PATH_x86 "android-x86")
set(ANDROID_PROCESSOR_x86 "x86")
set(ANDROID_C_FLAGS_x86 "-m32")
set(ANDROID_SYSTEM_ARCH_x86 "x86")

# Using the installed NDK for the android compilers
set(toolchains "${ANDROID_NDK_ROOT}/toolchains")
if(ToolchainHost STREQUAL "Linux")
    set(compiler_host "linux-x86_64")
endif()
if(ToolchainHost STREQUAL "Darwin")
    set(compiler_host "darwin-x86_64")
endif()
if(ToolchainHost STREQUAL "Windows")
    set(compiler_host "windows-x86_64")
endif()

set(ANDROID_TOOLCHAIN_PREFIX_armeabi "${toolchains}/arm-linux-androideabi-4.9/prebuilt/${compiler_host}/bin/arm-linux-androideabi-")
set(ANDROID_TOOLCHAIN_PREFIX_aarch64 "${toolchains}/aarch64-linux-android-4.9/prebuilt/${compiler_host}/bin/aarch64-linux-android-")
set(ANDROID_TOOLCHAIN_PREFIX_x86 "${toolchains}/x86-4.9/prebuilt/${compiler_host}/bin/i686-linux-android-")

# Look up the set of android ABI's by detecting the ANDROID_ABI_NAME_{$abi} variables
set(ANDROID_ABI_LIST)
get_cmake_property(vars VARIABLES)
foreach (var ${vars})
    if(var MATCHES "^ANDROID_ABI_NAME_(.*)")
        list(APPEND ANDROID_ABI_LIST ${CMAKE_MATCH_1})
    endif()
endforeach()

foreach(abi ${ANDROID_ABI_LIST})
    # Build any constructed variables
    set(ANDROID_GCC_PATH_${abi} "${ANDROID_TOOLCHAIN_PREFIX_${abi}}gcc${CMAKE_HOST_EXECUTABLE_SUFFIX}")
    set(ANDROID_GXX_PATH_${abi} "${ANDROID_TOOLCHAIN_PREFIX_${abi}}g++${CMAKE_HOST_EXECUTABLE_SUFFIX}")
    set(ANDROID_RANLIB_PATH_${abi} "${ANDROID_TOOLCHAIN_PREFIX_${abi}}ranlib${CMAKE_HOST_EXECUTABLE_SUFFIX}")
    set(ANDROID_AR_PATH_${abi} "${ANDROID_TOOLCHAIN_PREFIX_${abi}}ar${CMAKE_HOST_EXECUTABLE_SUFFIX}")
    set(ANDROID_LD_PATH_${abi} "${ANDROID_TOOLCHAIN_PREFIX_${abi}}ld${CMAKE_HOST_EXECUTABLE_SUFFIX}")
    # Verify that all required variables are set
    foreach(var ${ANDROID_ABI_VARS})
        if(NOT DEFINED ${var}_${abi})
            message(FATAL_ERROR "ABI ${abi} does not define ${var}_${abi}")
        endif()
    endforeach()
endforeach()

if(NOT ANDROID_VALID_ABI_LIST)
    # Build the active abi list by detecting whether the configured compiler path is valid
    set(ANDROID_VALID_ABI_LIST)
    foreach(abi ${ANDROID_ABI_LIST})
        if(EXISTS ${ANDROID_GCC_PATH_${abi}})
            message(STATUS "Found ${abi} using ${ANDROID_GCC_PATH_${abi}}")
            list(APPEND ANDROID_VALID_ABI_LIST ${abi})
        else()
            message(STATUS "Disable ${abi}, missing ${ANDROID_GCC_PATH_${abi}}")
        endif()
    endforeach()
    set(ANDROID_VALID_ABI_LIST  "${ANDROID_VALID_ABI_LIST}" CACHE STRING "The set of android abi's to compile" FORCE)
endif()

# If we are actually compiling for android
if(ANDROID_ABI)
    # Check it's a valid host->abi toolchain
    list (FIND ANDROID_VALID_ABI_LIST ${ANDROID_ABI} is_valid)
    if (${is_valid} EQUAL -1)
        message(FATAL_ERROR "Android abi ${ANDROID_ABI} is not valid on this host")
    endif()
    # Set the default values of all the variables from the abi ones
    foreach(var ${ANDROID_ABI_VARS})
        set(${var} ${${var}_${ANDROID_ABI}})
    endforeach()
else()
    set(ANDROID_ACTIVE_ABI_LIST ${ANDROID_VALID_ABI_LIST})
endif()


text:
__author__ = 'jscarbor'

from fusionpy.fusion import Fusion
import sys
import json

import errno
import os

def configure(args):
    """
    Configure collection(s) if not already there, fail if the collection(s) exist but differ from the given
    configuration.

    :param args: the name of a file with configuration information
    """
    with open(args[0]) as f:
        cfg = __ascii_keys(json.load(f))

    fusion = Fusion().ensure_config(write=False, **cfg)
    if fusion is None:
        # It's not there, so safe to write
        Fusion().ensure_config(**cfg)
    elif not fusion:
        # Cowardly not overwriting a differing configuration
        print "Fusion configuration differs from files.  Maybe clean to start over."
        sys.exit(5)

    print "Fusion collection matches file configuration."

def delete(args):
    """
    Delete a collection if it exists.  If the named collection does not exist, do nothing.

    :param args:  Optional, the name of a single collection to delete
    """
    if len(args) > 1:
        print "Too many arguments.  Name at most one collection."
        sys.exit(2)

    collection = None
    if len(args) == 1:
        collection = args[0]

    collection = Fusion().get_collection(collection)
    if collection.exists():
        collection.delete_collection(purge=True, solr=True)

def export(args):
    """
    Save out the current configuration from Fusion to file and folder(s) to permit re-import
    :param args: either a file name, preceeded by @, or a json string of elements to
    """
    with open(args[0]) as fh:
        things_to_save = json.load(fh)

    Fusion().export_config(things_to_save)

def dir(args):
    """
    Write to stdout a json file listing the collections and pipelines available for export.
    This file can then be pruned to only the things that should be collected.
    """
    f = Fusion()
    print json.dumps({
        "collections": f.get_collections(),
        "indexPipelines": [p["id"] for p in f.index_pipelines.get_pipelines()],
        "queryPipelines": [p["id"] for p in f.query_pipelines.get_pipelines()]
    }, indent=True, separators=(',', ':'), sort_keys=True)

def print_help(args):
    print "Usage"
    print "  python -m fusionpy.tool <verb> [argument] [...]"

def __ascii_keys(athing):
    # json will not always load these as regular strings.  Python2 (at least) requires strings, not unicode,
    # for the keys going in to the ** parameters
    if type(athing) is dict:
        cc = {}
        for k, v in athing.items():
            cc[k.encode('ascii', 'replace')] = __ascii_keys(v)
    elif type(athing) is list:
        cc = []
        for x in athing:
            cc.append(__ascii_keys(x))
    else:
        return athing
    return cc

if __name__ == "__main__":
    try:
        if sys.argv[1] == "help" or sys.argv[1] == "?":
            sys.argv[1] = "print_help"
        globals()[sys.argv[1]](sys.argv[2:])
    except IndexError as ie:
        print_help([])
    except Exception as e:
        print_help([])
        raise


text:
<?php
/**
 * @package Guzzle PHP <http://www.guzzlephp.org>
 * @license See the LICENSE file that was distributed with this source code.
 */

namespace Guzzle\Aws\Mws\Command;

/**
 * Get next page of GetReportList results
 *
 * Documentation:
 * The GetReportListByNextToken operation returns a list of reports that match the query
 * parameters, using the NextToken, which was supplied by a previous call to either
 * GetReportListByNextToken or a call to GetReportList, where the value of HasNext was true in
 * that previous call.
 *
 * @author Harold Asbridge <harold@shoebacca.com>
 *
 * @guzzle next_token doc="Token returned in a previous call to GetReportList" required="true"
 */
class GetReportListByNextToken extends AbstractMwsCommand
{
    /**
     * {@inheritdoc}
     */
    protected $action = 'GetReportListByNextToken';

    /**
     * Set report next token
     *
     * @param string $nextToken
     *
     * @return GetReportListByNextToken
     */
    public function setNextToken($nextToken)
    {
        return $this->set('next_token', $nextToken);
    }
}


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

import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import org.fusesource.jansi.AnsiString;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.repeat;
import static java.lang.Math.max;
import static java.lang.String.format;

public class AlignedTuplePrinter
        implements OutputPrinter
{
    private static final Splitter LINE_SPLITTER = Splitter.on('\n');

    private final List<String> fieldNames;
    private final Writer writer;

    private boolean headerOutput;
    private long rowCount;

    public AlignedTuplePrinter(List<String> fieldNames, Writer writer)
    {
        this.fieldNames = ImmutableList.copyOf(checkNotNull(fieldNames, "fieldNames is null"));
        this.writer = checkNotNull(writer, "writer is null");
    }

    @Override
    public void finish()
            throws IOException
    {
        printRows(ImmutableList.<List<?>>of(), true);
        writer.append(format("(%s row%s)%n", rowCount, (rowCount != 1) ? "s" : ""));
        writer.flush();
    }

    @Override
    public void printRows(List<List<?>> rows, boolean complete)
            throws IOException
    {
        rowCount += rows.size();
        int columns = fieldNames.size();

        int[] maxWidth = new int[columns];
        for (int i = 0; i < columns; i++) {
            maxWidth[i] = max(1, fieldNames.get(i).length());
        }
        for (List<?> row : rows) {
            for (int i = 0; i < row.size(); i++) {
                String s = formatValue(row.get(i));
                maxWidth[i] = max(maxWidth[i], maxLineLength(s));
            }
        }

        if (!headerOutput) {
            headerOutput = true;

            for (int i = 0; i < columns; i++) {
                if (i > 0) {
                    writer.append('|');
                }
                String name = fieldNames.get(i);
                writer.append(center(name, maxWidth[i], 1));
            }
            writer.append('\n');

            for (int i = 0; i < columns; i++) {
                if (i > 0) {
                    writer.append('+');
                }
                writer.append(repeat("-", maxWidth[i] + 2));
            }
            writer.append('\n');
        }

        for (List<?> row : rows) {
            List<List<String>> columnLines = new ArrayList<>(columns);
            int maxLines = 1;
            for (int i = 0; i < columns; i++) {
                String s = formatValue(row.get(i));
                ImmutableList<String> lines = ImmutableList.copyOf(LINE_SPLITTER.split(s));
                columnLines.add(lines);
                maxLines = max(maxLines, lines.size());
            }

            for (int line = 0; line < maxLines; line++) {
                for (int column = 0; column < columns; column++) {
                    if (column > 0) {
                        writer.append('|');
                    }
                    List<String> lines = columnLines.get(column);
                    String s = (line < lines.size()) ? lines.get(line) : "";
                    boolean numeric = row.get(column) instanceof Number;
                    String out = align(s, maxWidth[column], 1, numeric);
                    if ((!complete || (rowCount > 1)) && ((line + 1) < lines.size())) {
                        out = out.substring(0, out.length() - 1) + "+";
                    }
                    writer.append(out);
                }
                writer.append('\n');
            }
        }

        writer.flush();
    }

    static String formatValue(Object o)
    {
        return (o == null) ? "NULL" : o.toString();
    }

    private static String center(String s, int maxWidth, int padding)
    {
        AnsiString ansiString = new AnsiString(s);

        checkState(ansiString.length() <= maxWidth, "string length is greater than max width");
        int left = (maxWidth - ansiString.length()) / 2;
        int right = maxWidth - (left + ansiString.length());
        return repeat(" ", left + padding) + s + repeat(" ", right + padding);
    }

    private static String align(String s, int maxWidth, int padding, boolean right)
    {
        AnsiString ansiString = new AnsiString(s);
        checkState(ansiString.length() <= maxWidth, "string length is greater than max width");
        String large = repeat(" ", (maxWidth - ansiString.length()) + padding);
        String small = repeat(" ", padding);
        return right ? (large + s + small) : (small + s + large);
    }

    static int maxLineLength(String s)
    {
        int n = 0;
        for (String line : LINE_SPLITTER.split(s)) {
            n = max(n, new AnsiString(line).length());
        }
        return n;
    }
}


text:
import isPlainObject from 'lodash/isPlainObject';
import parseLocale from 'locale-id';
import EventEmitter from 'events';
import Tree from './Tree';
import baseFilters from './filters';
import MemoryAdapter from './adapters/Memory';
import MemoryCache from './caches/Memory';
import Mode from './constants/Mode';
import join from './utils/join';

function baseDefaultValue(path) {
  return `Missing default translation for: ${path}`;
}

// TODO add || syntax
export default class Translate extends EventEmitter {
  constructor(options = {}) {
    super();

    if (isPlainObject(options.adapter)) {
      throw new Error('You need to use instance of adapter or data option');
    }

    const {
      locale,
      namespace,
      data,
      ...rest
    } = options;

    if (locale || namespace) {
      throw new Error('Use method setLocale instead of option locale and namespace');
    }

    this.options = {
      locales: undefined, // available locales
      cache: new MemoryCache({}),
      adapter: new MemoryAdapter({}),
      dotNotation: true,
      mode: Mode.MAIN,
      references: true,
      variables: true,
      combinations: true,
      defaultValue: baseDefaultValue,
      ...rest,
      filters: {
        ...baseFilters, // available filters
        ...rest.filters, // add user filters
      },
    };

    this.tree = new Tree(this);

    const { adapter } = this.getOptions();
    if (data) {
      adapter.rehydrate(data);
    }
  }

  hasFilter(name: string): boolean {
    return !!this.options.filters[name];
  }

  addFilter(name: string, filter: Function): void {
    const { filters } = this.options;

    this.options.filters = {
      ...filters,
      [name]: filter,
    };
  }

  clear() {
    const { cache } = this.getOptions();
    if (cache) {
      cache.clear();
    }

    this.tree = new Tree(this);
  }

  async waitForLocale() {
    if (!this.setLocalePromise) {
      return undefined;
    }

    return this.setLocalePromise;
  }

  async setLocale(locale, namespace) {
    const currentPromise = this.setLocalePromise;
    this.setLocalePromise = new Promise(async (resolve, reject) => {
      try {
        await currentPromise;
      } catch (e) {
        reject(e);
        return;
      }

      if (!locale) {
        throw new Error('Locale is undefined');
      }

      const options = this.getOptions();
      if (options.locales && options.locales.indexOf(locale) === -1) {
        throw new Error('Locale is not allowed. Setup locales');
      }

      const adapter = this.getAdapter();
      adapter.get(locale, namespace).then((data) => {
        const sameLocale = options.locale === locale;
        if (!sameLocale) {
          this.clear();

          this.options = {
            ...options,
            locale,
          };
        }

        if (namespace) {
          this.set(namespace, data);
        } else {
          this.set(data);
        }

        if (!sameLocale) {
          this.emit('locale', locale, namespace);
        }

        resolve(data);
      }, reject);
    });

    return this.setLocalePromise;
  }

  async loadNamespace(namespace) {
    // we need to wait for async setLocale
    await this.setLocalePromise;

    const options = this.getOptions();
    return this.setLocale(options.locale, namespace);
  }

  get(path, attrs, defaultValue, pure) {
    if (path === undefined || path === null) {
      return undefined;
    }

    if (isPlainObject(path)) {
      const translated = {};
      Object.keys(path).forEach((key) => {
        translated[key] = this.get(path[key], attrs, defaultValue);
      });

      return translated;
    }

    const items = this.tree.get(path, attrs, defaultValue);
    return pure ? items : join(items);
  }

  set(path, value) {
    const result = this.tree.set(path, value);

    this.emit('changed');

    return result;
  }

  getOptions() {
    return this.options;
  }

  getLocale() {
    return this.getOptions().locale;
  }

  getLanguage() {
    const locale = this.getLocale();
    if (locale) {
      const l = parseLocale(locale);
      return l && l.language;
    }

    return locale;
  }

  getCache() {
    return this.getOptions().cache;
  }

  getAdapter() {
    return this.getOptions().adapter;
  }

  setFilter(type, fn) {
    if (isPlainObject(type)) {
      Object.keys(type).forEach(filterType => this.setFilter(filterType, type[filterType]));
      return;
    }

    this.getOptions().filters[type] = fn;
  }

  getFilter(type) {
    const { filters } = this.getOptions();

    return filters && filters[type];
  }
}