text:
namespace BizUnit
{
	using System;
	using System.IO;
	using System.Xml;
	using System.Collections;
	using System.Reflection;
	using System.Threading;

	/// <summary>
	/// Summary description for TestExecuter.
	/// </summary>
	public class TestExecuter
	{
		XmlNodeList setupSteps;
		XmlNodeList executeSteps;
		XmlNodeList teardownSteps;
		string testName = "Unknown";
		Exception executionException;
		Context context;
		internal Logger logger;
		Queue completedConcurrentSteps = new Queue();
		int inflightQueueDepth;

		public TestExecuter(string configFile)
		{
			Logger logger = new Logger();
			this.context = new Context(this, logger);
			XmlDocument testConfig = new XmlDocument();
			testConfig.Load(configFile);

			// Get test name...
			XmlNode nameNode = testConfig.SelectSingleNode("/TestCase/@testName");
			if ( null != nameNode )
			{
				this.testName = nameNode.Value;
			}

			logger.WriteLine(" ");
			logger.WriteLine(new string('-', 79));
			logger.WriteLine("                                   S T A R T" );
			logger.WriteLine( " " );
			string userName = GetUserName();
			logger.WriteLine(string.Format("Test: {0} started @ {1} by {2}", this.testName, GetNow(), userName));
			logger.WriteLine(new string('-', 79));

			// Get test setup / execution / teardown steps
			this.setupSteps = testConfig.SelectNodes("/TestCase/TestSetup/*");
			this.executeSteps = testConfig.SelectNodes("/TestCase/TestExecution/*");
			this.teardownSteps = testConfig.SelectNodes("/TestCase/TestCleanup/*");

			this.logger = logger;
		}

		public void RunTest()
		{
			Setup();
			Execute();
			TearDown();

			this.logger.Close();
		}

		private void Setup()
		{
			this.logger.TestSetUp(this.testName);

			ExecuteSteps(this.setupSteps);
		}

		private void Execute()
		{
			this.logger.TestExecute(this.testName);

			try
			{
				ExecuteSteps(this.executeSteps);
			}
			catch(Exception e)
			{
				// If we caught an exception on the main test execution, save it, perform cleanup,
				// then throw the exception...
				this.executionException = e;
			}
		}

		private void TearDown()
		{
			this.logger.TestTearDown(this.testName);

			try
			{
				ExecuteSteps(this.teardownSteps);
			}
			catch(Exception e)
			{
				this.logger.LogException( e );
				this.logger.WriteLine(new string('-', 79));
				this.logger.WriteLine(string.Format("Test: {0} ended @ {1}", this.testName, GetNow() ));
				this.logger.WriteLine( "" );
				this.logger.WriteLine("                             ****** F A I L ******" );
				this.logger.WriteLine(new string('-', 79));

				if ( null != this.executionException )
				{
					throw this.executionException;
				}
				else
				{
					throw;
				}
			}

			this.logger.WriteLine(new string('-', 79));
			this.logger.WriteLine(string.Format("Test: {0} ended @ {1}", this.testName, GetNow() ));
			this.logger.WriteLine( "" );

			if ( null != this.executionException )
			{
				this.logger.WriteLine("                             ****** F A I L ******" );
			}
			else
			{
				this.logger.WriteLine("                                    P A S S" );
			}

			this.logger.WriteLine(new string('-', 79));

			if ( null != this.executionException )
			{
				throw this.executionException;
			}
		}

		private void ExecuteSteps(XmlNodeList steps)
		{
			if ( null == steps )
			{
				return;
			}

			foreach (XmlNode stepConfig in steps)
			{
				bool runConcurrently = false;
				XmlNode assemblyPath = stepConfig.SelectSingleNode("@assemblyPath");
				XmlNode typeName = stepConfig.SelectSingleNode("@typeName");
				XmlNode runConcurrentlyNode = stepConfig.SelectSingleNode("@runConcurrently");

				if ( null != runConcurrentlyNode )
				{
					runConcurrently = Convert.ToBoolean(runConcurrentlyNode.Value);
				}

				object obj = CreateStep(typeName.Value, assemblyPath.Value);
				ITestStep step = obj as ITestStep;

				try
				{
					// Should this step be executed concurrently?
					if ( runConcurrently )
					{
						this.logger.WriteLine(string.Format("\nStep: {0} started  c o n c u r r e n t l y  @ {1}", typeName.Value, GetNow() ));
						Interlocked.Increment(ref this.inflightQueueDepth);
						ThreadPool.QueueUserWorkItem(new WaitCallback(this.WorkerThreadThunk), new ConcurrentTestStepWrapper(step, stepConfig, this, typeName.Value));
					}
					else
					{
						this.logger.WriteLine(string.Format("\nStep: {0} started @ {1} ", typeName.Value, GetNow() ));

						step.Execute(stepConfig, context);
					}
				}
				catch(Exception e)
				{
					this.logger.LogException( e );
					throw;
				}

				if ( !runConcurrently )
				{
					this.logger.WriteLine(string.Format("Step: {0} ended @ {1}", typeName.Value, GetNow() ));
				}

				FlushConcurrentQueue(false);
			}

			FlushConcurrentQueue(true);
		}

		private void FlushConcurrentQueue(bool waitingToFinish)
		{
			if ( waitingToFinish && this.inflightQueueDepth == 0 )
			{
				return;
			}

			while ( (this.completedConcurrentSteps.Count > 0) || waitingToFinish )
			{
				object obj = null;

				lock(this.completedConcurrentSteps.SyncRoot)
				{
					if ( this.completedConcurrentSteps.Count > 0 )
					{
						try
						{
							obj = this.completedConcurrentSteps.Dequeue();
						}
						catch(Exception)
						{
						}
					}
				}

				if ( null != obj )
				{
					ConcurrentTestStepWrapper step = (ConcurrentTestStepWrapper)obj;
					string testLog = step.GetLogText();
					this.logger.WriteLine(testLog);

					this.logger.WriteLine(string.Format("Step: {0} ended @ {1} (Concurrent Execution Mode defined)", step.Name, GetNow() ));

					// Check to see if the test step failed, if it did throw the exception...
					if ( null != step.FailureException )
					{
						Interlocked.Decrement(ref this.inflightQueueDepth);
						throw step.FailureException;
					}

					Interlocked.Decrement(ref this.inflightQueueDepth);
				}

				if ( waitingToFinish && (this.inflightQueueDepth > 0) )
				{
					Thread.Sleep(250);
				}
				else if ( waitingToFinish && (this.inflightQueueDepth == 0) )
				{
					break;
				}
			}
		}

		private void WorkerThreadThunk(Object stateInfo)
		{
			ConcurrentTestStepWrapper step = (ConcurrentTestStepWrapper)stateInfo;
			step.Execute();

			// This step is completed, add to queue
			lock(this.completedConcurrentSteps.SyncRoot)
			{
				this.completedConcurrentSteps.Enqueue(step);
			}
		}

		static private IValidationTestStep CreateValidatorStep(string typeName, string assemblyPath)
		{
			return (IValidationTestStep)CreateStep( typeName, assemblyPath );
		}

		static private IContextDataLoader CreateContextDataLoaderStep(string typeName, string assemblyPath)
		{
			return (IContextDataLoader)CreateStep( typeName, assemblyPath );
		}

		static private object CreateStep(string typeName, string assemblyPath)
		{
			object comp = null;
			Type ty = null;

			if (assemblyPath!=null && assemblyPath.Length != 0)
			{
				Assembly assembly = Assembly.LoadFrom(assemblyPath);
				ty = assembly.GetType(typeName, true, false);
			}
			else
			{
				ty = Type.GetType(typeName);
			}

			if (ty != null)
			{
				comp = Activator.CreateInstance(ty);
			}

			return comp;
		}

		internal void ExecuteValidator(Stream data, XmlNode validatorConfig, Context context)
		{
			if ( null == validatorConfig )
			{
				return;
			}

			XmlNode assemblyPath = validatorConfig.SelectSingleNode("@assemblyPath");
			XmlNode typeName = validatorConfig.SelectSingleNode("@typeName");

			this.logger.WriteLine(string.Format("\nValidation: {0} started @ {1}", typeName.Value, GetNow() ));

			IValidationTestStep v = CreateValidatorStep(typeName.Value, assemblyPath.Value);
			v.Execute( data, validatorConfig, context);

			this.logger.WriteLine(string.Format("Validation: {0} ended @ {1}\n", typeName.Value, GetNow() ));
		}

		internal void ExecuteContextLoader(Stream data, XmlNode contextConfig, Context context)
		{
			if ( null == contextConfig )
			{
				return;
			}

			XmlNode assemblyPath = contextConfig.SelectSingleNode("@assemblyPath");
			XmlNode typeName = contextConfig.SelectSingleNode("@typeName");

			this.logger.WriteLine(string.Format("\nContextLoad: {0} started @ {1}", typeName.Value, GetNow() ));

			IContextDataLoader cd = CreateContextDataLoaderStep(typeName.Value, assemblyPath.Value);
			cd.LoadContextData(data, contextConfig, context);

			this.logger.WriteLine(string.Format("ContextLoad: {0} ended @ {1}\n", typeName.Value, GetNow() ));
		}

		internal static string GetNow()
		{
			return DateTime.Now.ToString("HH:mm:ss.fff dd/MM/yyyy");
		}

		internal static string GetUserName()
		{
			string usersDomain = Environment.UserDomainName;
			string usersName = Environment.UserName;

			return usersDomain + "\\" + usersName;
		}
	}
}


text:
#ifndef FSLBASE_LOG_MATH_LOGPLANE_HPP
#define FSLBASE_LOG_MATH_LOGPLANE_HPP

#include <FslBase/Math/Plane.hpp>
#include <FslBase/Log/Math/LogVector3.hpp>
#include <ostream>

namespace Fsl
{
  inline std::ostream& operator<<(std::ostream& o, const Plane& value)
  {
    return o << "{Normal=" << value.Normal << " D=" << value.D << "}";
  }
}

#endif

redpajama_set_name: RedPajamaGithub


text:
var gui = require('nw.gui');

navigator.webkitGetUserMedia({video: true},
  function(stream) {
    document.getElementById('camera').src = URL.createObjectURL(stream);
  },
  function() {
    alert('could not connect stream');
  }
);

gui.Window.get().show();


text:
<?php

use Awesomite\ErrorDumper\Handlers\ErrorHandler;
use Awesomite\ErrorDumper\Listeners\OnExceptionDevView;
use Awesomite\ErrorDumper\Views\ViewFactory;

$errorHandler = new ErrorHandler();
$errorHandler->pushListener(new OnExceptionDevView(ViewFactory::create()));
$errorHandler->register();

$sandbox = $errorHandler->getErrorSandbox();
$sandbox->executeSafely(function () {
    \trigger_error('test');
});

return 'No errors ;)';


text:
import re
import os
import logging
import logging.config

from backupme.settings_parser import SettingsParser

# get logger
logger = logging.getLogger('backupme')

# get environment variables
PROJECT_DIR = SettingsParser().get('project_dir')
MAIN_LOG_PATH = SettingsParser().get('main_log')

def validator(file_list):
    """
    Function to validate all files from list that get_list_files returns.

    :param file_list: all files from configuration file
    :return: None
    """
    if file_list:
        for f in file_list:
            if not os.path.isfile(f):
                file_list.remove(f)
    return file_list

def get_list_files(path_to_file):
    """
    Function to parse configuration file to collect all files that needed
    to be stored in cloud
    Returns a list of file paths
    """
    files_set = []

    try:
        with open(path_to_file) as f:
            file_content = f.read()
    except IOError, e:
        logger.error('Cannot access the configuration file')
        logger.exception(e)
        raise IOError

    if file_content:
        compiled_regex = re.compile(r"(\S+)(?:\n)*")
        files_set = compiled_regex.findall(file_content)
    if files_set:
        # Run file validator to avoid deleted files from configuration file
        files_set = validator(files_set)
        return files_set
    else:
        logger.error("Your file is empty or content is not valid")
        raise TypeError

if __name__ == '__main__':
    logging.config.fileConfig(
        os.path.join(PROJECT_DIR, 'google_api_driver/logging.conf'),
        defaults={'logfilename': MAIN_LOG_PATH})


text: from .hill_climbing import HillClimbing


text:
import { REALM } from 'ngx-login-client';
import { ApiLocatorService } from './api-locator.service';

const realmFactory = (api: ApiLocatorService) => api.realm;

export const realmProvider = {
  provide: REALM,
  useFactory: realmFactory,
  deps: [ApiLocatorService],
};


text:
module IntercityExpress
  # Internal: Rails integration for the view helpers.
  #
  # Includes an initializer that automatically adds the view helpers to the
  # set of global helpers.
  class Railtie < Rails::Railtie
    initializer "intercity_express.view_helpers" do
      ActiveSupport.on_load :action_view do
        include IntercityExpress::TextHelpers
      end
    end
  end
end


text:
package javax.xml.bind.helpers;

import org.w3c.dom.Node;

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.ValidationEventLocator;
import java.net.URL;

/**
 *

 * JAXB 1.0 only default validation event handler. This is the default
 * handler for all objects created from a JAXBContext that is managing
 * schema-derived code generated by a JAXB 1.0 binding compiler.
 *
 *

 * This handler causes the unmarshal and validate operations to fail on the first
 * error or fatal error.
 *
 *

 * This handler is not the default handler for JAXB mapped classes following
 * JAXB 2.0 or later versions. Default validation event handling has changed
 * and is specified in  {@link javax.xml.bind.Unmarshaller} and
 * {@link javax.xml.bind.Marshaller}.
 *
 * @author

Ryan Shoemaker, Sun Microsystems, Inc.

 * @see javax.xml.bind.Unmarshaller
 * @see javax.xml.bind.Validator
 * @see ValidationEventHandler
 * @since JAXB1.0
 */
public class DefaultValidationEventHandler implements ValidationEventHandler {

    public boolean handleEvent( ValidationEvent event ) {

        if( event == null ) {
            throw new IllegalArgumentException();
        }

        // calculate the severity prefix and return value
        String severity = null;
        boolean retVal = false;
        switch ( event.getSeverity() ) {
            case ValidationEvent.WARNING:
                severity = Messages.format( Messages.WARNING );
                retVal = true; // continue after warnings
                break;
            case ValidationEvent.ERROR:
                severity = Messages.format( Messages.ERROR );
                retVal = false; // terminate after errors
                break;
            case ValidationEvent.FATAL_ERROR:
                severity = Messages.format( Messages.FATAL_ERROR );
                retVal = false; // terminate after fatal errors
                break;
            default:
                assert false :
                    Messages.format( Messages.UNRECOGNIZED_SEVERITY,
                            event.getSeverity() );
        }

        // calculate the location message
        String location = getLocation( event );

        System.out.println(
            Messages.format( Messages.SEVERITY_MESSAGE,
                             severity,
                             event.getMessage(),
                             location ) );

        // fail on the first error or fatal error
        return retVal;
    }

    /**
     * Calculate a location message for the event
     *
     */
    private String getLocation(ValidationEvent event) {
        StringBuffer msg = new StringBuffer();

        ValidationEventLocator locator = event.getLocator();

        if( locator != null ) {

            URL url = locator.getURL();
            Object obj = locator.getObject();
            Node node = locator.getNode();
            int line = locator.getLineNumber();

            if( url!=null || line!=-1 ) {
                msg.append( "line " + line );
                if( url!=null )
                    msg.append( " of " + url );
            } else if( obj != null ) {
                msg.append( " obj: " + obj.toString() );
            } else if( node != null ) {
                msg.append( " node: " + node.toString() );
            }
        } else {
            msg.append( Messages.format( Messages.LOCATION_UNAVAILABLE ) );
        }

        return msg.toString();
    }
}


text:
Ansible playbooks to deploy an apache2 service as a reverse proxy with authentication and cache in Debian 8.

Exec as root: ansible-playbook -i "localhost," -c local site.yml

Detailed list of enabled modules:
- proxy related
  - alias
  - ratelimit
  - rewrite
  - headers
  - proxy_ajp
  - proxy_balancer
  - proxy_connect
  - proxy_express
  - proxy_ftp
  - proxy_html
  - proxy_http
  - proxy_scgi
  - proxy_wstunnel
  - ssl
  - vhost_alias
  - xml2enc
- auth related
  - auth_digest
  - authnz_ldap
  - ldap
- cache related
  - cache_disk
  - cache
  - file_cache


text:
package de.ayesolutions.gogs.client.model;

/**
 * @author Christian Aye - c.aye@aye-solutions.de
 */
public class Team {
    private Long id;

    private String name;

    private String description;

    private String permission;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPermission() {
        return permission;
    }

    public void setPermission(String permission) {
        this.permission = permission;
    }
}


text:
SET DEFINE OFF;
ALTER TABLE AFW_12_LIEN_GROUP_APROB ADD (
  CONSTRAINT AFW_12_LIEN_GROUP_APROB_FK1
  FOREIGN KEY (REF_GROUP_APROB)
  REFERENCES AFW_12_GROUP_APROB (SEQNC)
  ON DELETE CASCADE
  ENABLE VALIDATE)
/


text:
#include <aws/rekognition/model/Gender.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Rekognition
{
namespace Model
{

Gender::Gender() :
    m_value(GenderType::NOT_SET),
    m_valueHasBeenSet(false),
    m_confidence(0.0),
    m_confidenceHasBeenSet(false)
{
}

Gender::Gender(JsonView jsonValue) :
    m_value(GenderType::NOT_SET),
    m_valueHasBeenSet(false),
    m_confidence(0.0),
    m_confidenceHasBeenSet(false)
{
  *this = jsonValue;
}

Gender& Gender::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Value"))
  {
    m_value = GenderTypeMapper::GetGenderTypeForName(jsonValue.GetString("Value"));

    m_valueHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Confidence"))
  {
    m_confidence = jsonValue.GetDouble("Confidence");

    m_confidenceHasBeenSet = true;
  }

  return *this;
}

JsonValue Gender::Jsonize() const
{
  JsonValue payload;

  if(m_valueHasBeenSet)
  {
   payload.WithString("Value", GenderTypeMapper::GetNameForGenderType(m_value));
  }

  if(m_confidenceHasBeenSet)
  {
   payload.WithDouble("Confidence", m_confidence);

  }

  return payload;
}

} // namespace Model
} // namespace Rekognition
} // namespace Aws


text:
package com.uzabase.rss.engine;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.log4j.Logger;

import com.uzabase.rss.exception.RSSFault;
import com.uzabase.rss.exception.RSSReaderException;
import com.uzabase.rss.vo.RSSFeedVo;

public class OutputWriter {
	private final static Logger logger = Logger.getLogger(OutputWriter.class);
	private static OutputWriter instance = null;
	private static Object lock = new Object();
	private OutputWriter() {
	}

	public static OutputWriter getInstance() {
		if (instance == null) {
			synchronized (lock) {
				if (instance == null) {
					instance = new OutputWriter();
				}
			}
		}

		return (instance);
	}

	public void write(RSSFeedVo feed,String destPath) throws RSSReaderException, IOException {
		try {

			Path path = Paths.get(destPath);
			try (BufferedWriter writer = Files.newBufferedWriter(path)) {
				try {
					writer.write("Title       : "+ feed.getTitle() + "\n");
					writer.write("Description : "+ feed.getDescription() + "\n");
					writer.write("Link        : " + feed.getLink()+ "\n");

					if(feed.getGenerator()!=null){
						writer.write("Generator   : "+ feed.getGenerator() + "\n");
					}

					if(feed.getLastBuildDate()!=null){
						writer.write("LastBuildDate: "+ feed.getLastBuildDate() + "\n");
					}

					if(feed.getCopyright()!=null){
						writer.write("copyright   : "+ feed.getCopyright() + "\n");
					}
					if(feed.getLanguage()!=null){
						writer.write("Language    : "+ feed.getLanguage() + "\n");
					}

					if(feed.getImages().size()>0){
						writer.write("\n******************** Image ************************\n");
						feed.getImages().forEach((image) ->{
							try {
								writer.write(" Title       : "+ image.getTitle()+ "\n");
								writer.write(" url         : "+ image.getUrl() + "\n");
								writer.write(" link        : "+ image.getLink()+ "\n");

							}catch (Exception e) {

							}
						});
					}

				}catch (Exception e) {

				}

				writer.write("\n\n******************** Item ************************\n\n");
				feed.getItems().forEach((item) -> {
					try {
						writer.write("Title          : "+ item.getTitle() + "\n");
						writer.write("Link           : " + item.getLink()+ "\n");
						writer.write("Published Date : "+ item.getPubdate() + "\n");
						writer.write("Description    : "+ item.getDescription() + "\n");
						item.getThumbnails().forEach((thumbnail) ->{
							try {
								writer.write("Thumbnail Url  : "+ thumbnail.getUrl()+ "\n");
								writer.write(" Width : "+ thumbnail.getWidth()+ "\n");
								writer.write(" Height: "+ thumbnail.getHeight()+ "\n");
							}catch (Exception e) {

							}
						});

						writer.write("*************************************************\n");
					} catch (Exception e) {

					}

				});
			}
		} catch (IOException e) {
			logger.error("SAXException in load()", e);
			throw new RSSFault(e);
		}

	}
}


text:
package com.akjava.gwt.three.client.js.materials;

import com.akjava.gwt.three.client.gwt.JSParameter;

/**
 * can't overwrite.copy this as base
 * @author aki
 *
 */
public final class MaterialParameter extends JSParameter{
	protected MaterialParameter(){}
	public final static MaterialParameter create(){
		return (MaterialParameter) MaterialParameter.createObject();
	}

	public final native MaterialParameter side(int side)/*-{
	this.side=side;
	return this;
	}-*/;

	public final native MaterialParameter opacity(double opacity)/*-{
	this.opacity=opacity;
	return this;
	}-*/;
	public final native MaterialParameter transparent(boolean transparent)/*-{
	this.transparent=transparent;
	return this;
	}-*/;

	public final native MaterialParameter depthTest(boolean depthTest)/*-{
	this.depthTest=depthTest;
	return this;
	}-*/;

	public final native MaterialParameter depthWrite(boolean depthWrite)/*-{
	this.depthWrite=depthWrite;
	return this;
	}-*/;

	public final native MaterialParameter polygonOffset(boolean polygonOffset)/*-{
	this.polygonOffset=polygonOffset;
	return this;
	}-*/;

	public final native MaterialParameter blending(int blending)/*-{
	this.blending=blending;
	return this;
	}-*/;

	public final native MaterialParameter blendSrc(int blendSrc)/*-{
	this.blendSrc=blendSrc;
	return this;
	}-*/;

	public final native MaterialParameter blendDst(int blendDst)/*-{
	this.blendDst=blendDst;
	return this;
	}-*/;

	public final native MaterialParameter blendEquation(int blendEquation)/*-{
	this.blendEquation=blendEquation;
	return this;
	}-*/;

	public final native MaterialParameter polygonOffsetFactor(double polygonOffsetFactor)/*-{
	this.polygonOffsetFactor=polygonOffsetFactor;
	return this;
	}-*/;

	public final native MaterialParameter polygonOffsetUnits(double polygonOffsetUnits)/*-{
	this.polygonOffsetUnits=polygonOffsetUnits;
	return this;
	}-*/;
	public final native MaterialParameter alphaTest(double alphaTest)/*-{
	this.alphaTest=alphaTest;
	return this;
	}-*/;
	public final native MaterialParameter overdraw(double overdraw)/*-{
	this.overdraw=overdraw;
	return this;
	}-*/;
	public final native MaterialParameter needsUpdate(boolean needsUpdate)/*-{
	this.needsUpdate=needsUpdate;
	return this;
	}-*/;

	public final native MaterialParameter copy(MaterialParameter source)/*-{
	return this.copy(source);
	}-*/;
}


text:
#ifdef HAVE_CONFIG_H
#include "../../../../../../ext_config.h"
#endif

#include <php.h>
#include "../../../../../../php_ext.h"
#include "../../../../../../ext.h"

#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>

#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/object.h"
#include "kernel/operators.h"
#include "kernel/fcall.h"

ZEPHIR_INIT_CLASS(ZendFramework_Db_Adapter_Driver_Sqlsrv_Exception_ErrorException) {

	ZEPHIR_REGISTER_CLASS_EX(Zend\\Db\\Adapter\\Driver\\Sqlsrv\\Exception, ErrorException, zendframework, db_adapter_driver_sqlsrv_exception_errorexception, zendframework_db_adapter_exception_errorexception_ce, zendframework_db_adapter_driver_sqlsrv_exception_errorexception_method_entry, 0);

	/**
	 * Errors
	 *
	 * @var array
	 */
	zend_declare_property_null(zendframework_db_adapter_driver_sqlsrv_exception_errorexception_ce, SL("errors"), ZEND_ACC_PROTECTED TSRMLS_CC);

	zend_class_implements(zendframework_db_adapter_driver_sqlsrv_exception_errorexception_ce TSRMLS_CC, 1, zendframework_db_adapter_driver_sqlsrv_exception_exceptioninterface_ce);
	return SUCCESS;

}

/**
 * Construct
 *
 * @param  bool $errors
 */
PHP_METHOD(ZendFramework_Db_Adapter_Driver_Sqlsrv_Exception_ErrorException, __construct) {

	int ZEPHIR_LAST_CALL_STATUS;
	zval *errors = NULL, *_0;

	ZEPHIR_MM_GROW();
	zephir_fetch_params(1, 0, 1, &errors);

	if (!errors) {
		ZEPHIR_CPY_WRT(errors, ZEPHIR_GLOBAL(global_false));
	} else {
		ZEPHIR_SEPARATE_PARAM(errors);
	}

	ZEPHIR_INIT_VAR(_0);
	array_init(_0);
	zephir_update_property_this(this_ptr, SL("errors"), _0 TSRMLS_CC);
	if (ZEPHIR_IS_FALSE_IDENTICAL(errors)) {
		ZEPHIR_CALL_FUNCTION(&errors, "sqlsrv_errors", NULL);
		zephir_check_call_status();
	}
	zephir_update_property_this(this_ptr, SL("errors"), errors TSRMLS_CC);
	ZEPHIR_MM_RESTORE();

}


text:
module API
  module V1
    class MapSerializer < ActiveModel::Serializer
      type :map

      attributes :id, :name, :description
    end
  end
end


text:
vagrant-php
===========

Instead of polluting your local machine with several compiled versions of PHP,
Apache, Nginx, or M/XAMP, create a local sandbox for your project running
the same PHP environment TravisCI uses!

**THIS REPOSITORY IS CURRENTLY BEING PORTED FROM [ECVagrantBundle][https://github.com/ericclemmons/ECVagrantBundle]**

Dependencies
------------

- [Composer][3] (`curl -s https://getcomposer.org/installer | php`)

Installation
------------

Add `vagrant-php` to an existing project:

    $ cd /existing/php/project
    $ composer require ericclemmons/vagrant-php --dev

**(You may specify `*` as the version, if you want to always use the latest version.)**

Usage
-----

Run the command interactively and answer the prompts:

    $ ./bin/vagrant-php create

    Welcome to the Symfony2 Vagrant generator
    ...

Or provide the options at once:

    $ ./bin/vagrant-php create  \
        --no-interaction        \
        --host=vagrant          \
        --ip=10.33.33.33        \
        --url=http://files.vagrantup.com/lucid32.box

A `Vagrantfile` will be generated in your *current working directory*.  Now you're ready to work!

    $ vagrant up
    $ vagrant ssh

Authors
-------

- [Eric Clemmons][1]

License
-------

MIT

[1]: https://github.com/ericclemmons
[2]: https://github.com/seiffert
[3]: http://www.vagrantup.com/
[4]: http://getcomposer.org/download/


text:
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  title = 'app works!';

  helloWorld() {
    alert('Hello world!');
  }
}


text:
#if !GLOBAL_NADEKO
using Discord;
using Discord.Commands;
using NadekoBot.Common;
using NadekoBot.Common.Attributes;
using NadekoBot.Common.TypeReaders.Models;
using NadekoBot.Core.Services.Database.Models;
using NadekoBot.Extensions;
using NadekoBot.Modules.Administration.Services;
using System;
using System.Linq;
using System.Threading.Tasks;
using static NadekoBot.Modules.Administration.Services.LogCommandService;

namespace NadekoBot.Modules.Administration
{
    public partial class Administration
    {
        [Group]
        [NoPublicBot]
        public class LogCommands : NadekoSubmodule<LogCommandService>
        {
            public enum EnableDisable
            {
                Enable,
                Disable
            }

            [NadekoCommand, Usage, Description, Aliases]
            [RequireContext(ContextType.Guild)]
            [RequireUserPermission(GuildPermission.Administrator)]
            [OwnerOnly]
            public async Task LogServer(PermissionAction action)
            {
                await _service.LogServer(Context.Guild.Id, Context.Channel.Id, action.Value).ConfigureAwait(false);
                if (action.Value)
                    await ReplyConfirmLocalized("log_all").ConfigureAwait(false);
                else
                    await ReplyConfirmLocalized("log_disabled").ConfigureAwait(false);
            }

            [NadekoCommand, Usage, Description, Aliases]
            [RequireContext(ContextType.Guild)]
            [RequireUserPermission(GuildPermission.Administrator)]
            [OwnerOnly]
            public async Task LogIgnore()
            {
                var channel = (ITextChannel)Context.Channel;

                var removed = _service.LogIgnore(Context.Guild.Id, Context.Channel.Id);

                if (!removed)
                    await ReplyConfirmLocalized("log_ignore", Format.Bold(channel.Mention + "(" + channel.Id + ")")).ConfigureAwait(false);
                else
                    await ReplyConfirmLocalized("log_not_ignore", Format.Bold(channel.Mention + "(" + channel.Id + ")")).ConfigureAwait(false);
            }

            [NadekoCommand, Usage, Description, Aliases]
            [RequireContext(ContextType.Guild)]
            [RequireUserPermission(GuildPermission.Administrator)]
            [OwnerOnly]
            public async Task LogEvents()
            {
                _service.GuildLogSettings.TryGetValue(Context.Guild.Id, out LogSetting l);
                var str = string.Join("\n", Enum.GetNames(typeof(LogType))
                    .Select(x =>
                    {
                        var val = l == null ? null : GetLogProperty(l, Enum.Parse<LogType>(x));
                        if (val != null)
                            return $"{Format.Bold(x)} <#{val}>";
                        return Format.Bold(x);
                    }));

                await Context.Channel.SendConfirmAsync(Format.Bold(GetText("log_events")) + "\n" +
                    str)
                    .ConfigureAwait(false);
            }

            private static ulong? GetLogProperty(LogSetting l, LogType type)
            {
                switch (type)
                {
                    case LogType.Other:
                        return l.LogOtherId;
                    case LogType.MessageUpdated:
                        return l.MessageUpdatedId;
                    case LogType.MessageDeleted:
                        return l.MessageDeletedId;
                    case LogType.UserJoined:
                        return l.UserJoinedId;
                    case LogType.UserLeft:
                        return l.UserLeftId;
                    case LogType.UserBanned:
                        return l.UserBannedId;
                    case LogType.UserUnbanned:
                        return l.UserUnbannedId;
                    case LogType.UserUpdated:
                        return l.UserUpdatedId;
                    case LogType.ChannelCreated:
                        return l.ChannelCreatedId;
                    case LogType.ChannelDestroyed:
                        return l.ChannelDestroyedId;
                    case LogType.ChannelUpdated:
                        return l.ChannelUpdatedId;
                    case LogType.UserPresence:
                        return l.LogUserPresenceId;
                    case LogType.VoicePresence:
                        return l.LogVoicePresenceId;
                    case LogType.VoicePresenceTTS:
                        return l.LogVoicePresenceTTSId;
                    case LogType.UserMuted:
                        return l.UserMutedId;
                    default:
                        return null;
                }
            }

            [NadekoCommand, Usage, Description, Aliases]
            [RequireContext(ContextType.Guild)]
            [RequireUserPermission(GuildPermission.Administrator)]
            [OwnerOnly]
            public async Task Log(LogType type)
            {
                var val = _service.Log(Context.Guild.Id, Context.Channel.Id, type);

                if (val)
                    await ReplyConfirmLocalized("log", Format.Bold(type.ToString())).ConfigureAwait(false);
                else
                    await ReplyConfirmLocalized("log_stop", Format.Bold(type.ToString())).ConfigureAwait(false);
            }
        }
    }
}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>New Test</title>

New Test

	open
	/run/com.vaadin.tests.components.panel.PanelChangeContents?restartApplication

	assertText
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VPanel[0]/VVerticalLayout[0]/VLabel[0]
	stats

	click
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VHorizontalLayout[0]/VButton[1]/domChild[0]/domChild[0]

	assertText
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VPanel[0]/VVerticalLayout[0]/VLabel[0]
	companies

	click
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VHorizontalLayout[0]/VButton[2]/domChild[0]/domChild[0]

	assertText
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VPanel[0]/VVerticalLayout[0]/VLabel[0]
	settings

	click
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VHorizontalLayout[0]/VButton[0]/domChild[0]

	assertText
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VPanel[0]/VVerticalLayout[0]/VLabel[0]
	stats

	click
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VHorizontalLayout[0]/VButton[1]/domChild[0]/domChild[0]

	assertText
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VPanel[0]/VVerticalLayout[0]/VLabel[0]
	companies

	click
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VHorizontalLayout[0]/VButton[2]/domChild[0]/domChild[0]

	assertText
	vaadin=runcomvaadintestscomponentspanelPanelChangeContents::/VVerticalLayout[0]/VPanel[0]/VVerticalLayout[0]/VLabel[0]
	settings


text:
module Calendars
  class EventPolicy < ApplicationPolicy
    alias event record

    delegate :rule_set, :meal?, to: :event

    class Scope < Scope
      def resolve
        allow_all_users_in_cluster
      end
    end

    def index?
      # If record is a Class (not a specific event), can't check if calendar is active
      (not_specific_record? || calendar.active?) &&
        # If record is a Class (not a specific event), can't check protocol
        (active_cluster_admin? || (active? && (not_specific_record? || !forbidden_by_protocol?)))
    end

    def show?
      active_cluster_admin? || active? && !forbidden_by_protocol?
    end

    def create?
      calendar.active? && !calendar.system? &&
        (active_cluster_admin? || (active? && !forbidden_by_protocol? && !read_only_by_protocol? && !meal?))
    end

    def update?
      !calendar.system? &&
        (active_admin? || active_creator? || (meal? && active_with_community_role?(:meals_coordinator)))
    end

    # Allowed to make certain changes that would otherwise be invalid.
    # Which exact changes this allows are defined in the Event model and/or Rule system.
    def privileged_change?
      active_admin?
    end

    def choose_creator?
      active_admin?
    end

    def destroy?
      (active_creator? && (future? || recently_created?) || active_admin?) && !meal? && !calendar.system?
    end

    def permitted_attributes
      # We don't include calendar_id here because that must be set explicitly because the admin
      # community check relies on it.
      attribs = %i[starts_at ends_at note origin_page]
      attribs.concat(%i[name kind sponsor_id guidelines_ok]) unless meal?
      attribs << :creator_id if choose_creator?
      attribs
    end

    private

    delegate :calendar, :future?, :recently_created?, to: :event

    def active_creator?
      active? && event.creator == user
    end

    def forbidden_by_protocol?
      rule_set.access_level(user.community) == "forbidden"
    end

    def read_only_by_protocol?
      rule_set.access_level(user.community) == "read_only"
    end
  end
end


text:
DV.Elements = DV.Class.extend({
  init: function(elements){
    if(!elements){
      throw('Elements to query must be defined');
      return;
    }
    this.names = [];

    if(elements.constructor === Array){
      return this.getElements(elements);
    }else{
      return this.getElement(elements);
    }
  },
  // Get and store an element reference
  getElement: function(elementQuery,force){
    if(this[elementQuery.name] && force === null){
      return;
    }else{
      this[elementQuery.name] = jQuery(elementQuery.query);
      this.names.push(elementQuery.name);
      return this;
    }
  },
  // Get a collection of elements
  getElements: function(querySet,force){
    for (var i = querySet.length - 1; i >= 0; i--){
      this.getElement(querySet[i],force);
    };
    return this;
  },

  // Remove all references and bindings
  destroy: function(){
    for(var i = 0,len=this.names.length; i < len; i++){
      this[this.names[i]].unbind();
      this[this.names[i]].die();
      delete this[this.names[i]];
    }
    delete this.names;
  }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--
  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. See accompanying LICENSE file.
-->

<!-- Put site-specific property overrides in this file. -->

<configuration>
    <property>

        <!-- This is the number of times each block in HDFS is replicated across the cluster. -->
        <!-- See http://stackoverflow.com/questions/12835396/hadoop-dfs-replicate -->
        <name>dfs.replication</name>
        <value>1</value>
    </property>
</configuration>


text:
package eu.motogymkhana.competition.notify;

import eu.motogymkhana.competition.adapter.ChangeListener;

/**
 * Created by christine on 28-6-16.
 */
public interface Notifier {

    void registerRiderResultListener(ChangeListener listener);

    void unRegisterRiderResultListener(ChangeListener listener);

    void notifyDataChanged();
}


text:
Encode and decode HTML entities from selected text or the current document.

![Screenshot](https://f.cloud.github.com/assets/7937/2394928/0d5a0b98-a9c0-11e3-9126-b6ce7c76cef0.gif)

If you want you can add this code to you `keymap.cson` to add a shortcut.

    '.editor':
      'f5': 'html-entities:encode'
      'f6': 'html-entities:decode'

`F5` and `F6` are optional.


text:
import React from 'react'
import renderTestComponent from 'desktop/apps/auction/__tests__/utils/renderTestComponent'
import { ArtworkRail } from '../ArtworkRail'
import { promotedSaleArtworks } from '../../artwork_browser/__tests__/fixtures/promotedSaleArtworks'

describe('auction/components/artwork_rail/ArtworkRail', () => {
  const data = {
    app: {
      auction: {
        name: 'An Auction',
        sale_type: 'auction promo',
        eligible_sale_artworks_count: 0,
        promoted_sale: {
          sale_artworks: promotedSaleArtworks,
        },
      },
    },
  }

  it('renders an interactive rail', () => {
    const { wrapper } = renderTestComponent({
      Component: ArtworkRail,
      options: { renderMode: 'mount' },
      data,
      props: {
        title: 'Buy Now',
        artworks: promotedSaleArtworks,
        getDisplayComponent: ({ artwork }) => {
          // eslint-disable-line
          return <div>{artwork.id}</div>
        },
      },
    })

    wrapper.html().should.containEql('Buy Now')
    wrapper.html().should.containEql('auction-ArtworkRail__page-left')
    wrapper.html().should.containEql('auction-ArtworkRail__page-right')

    // First page
    wrapper
      .find('.auction-ArtworkRail__page-left .disabled')
      .length.should.equal(1)
    wrapper
      .find('.auction-ArtworkRail__page-right .disabled')
      .length.should.equal(0)
    wrapper.find('.auction-ArtworkRail__artwork').length.should.equal(4)
    wrapper.find('.auction-ArtworkRail__page-right').simulate('click')

    // Second page
    wrapper.find('.auction-ArtworkRail__artwork').length.should.equal(2) // second page
    wrapper
      .find('.auction-ArtworkRail__page-left .disabled')
      .length.should.equal(0)
    wrapper
      .find('.auction-ArtworkRail__page-right .disabled')
      .length.should.equal(1)
    wrapper.find('.auction-ArtworkRail__page-left').simulate('click')

    // Back to first page
    wrapper
      .find('.auction-ArtworkRail__page-left .disabled')
      .length.should.equal(1)
    wrapper
      .find('.auction-ArtworkRail__page-right .disabled')
      .length.should.equal(0)
    wrapper.find('.auction-ArtworkRail__artwork').length.should.equal(4)
  })
})


text:
require "rails_helper"

RSpec.feature "Users can view projects" do
  let(:user) { FactoryGirl.create(:user) }
  let(:project) { FactoryGirl.create(:project, name: "Sublime Text 3") }

  before do
    login_as(user)
    assign_role!(user, :viewer, project)
  end

  scenario "with the project details" do
    visit "/"
    click_link "Sublime Text 3"
    expect(page.current_url).to eq project_url(project)
  end

  scenario "unless they do not have permission" do
    FactoryGirl.create(:project, name: "Hidden")
    visit "/"
    expect(page).not_to have_content "Hidden"
  end
end


text:
"""Collection of helper methods.

All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.climate import _LOGGER
from homeassistant.components.climate.const import (
    ATTR_AUX_HEAT, ATTR_AWAY_MODE, ATTR_FAN_MODE, ATTR_HOLD_MODE,
    ATTR_HUMIDITY, ATTR_OPERATION_MODE, ATTR_SWING_MODE, ATTR_TARGET_TEMP_HIGH,
    ATTR_TARGET_TEMP_LOW, DOMAIN, SERVICE_SET_AWAY_MODE, SERVICE_SET_HOLD_MODE,
    SERVICE_SET_AUX_HEAT, SERVICE_SET_TEMPERATURE, SERVICE_SET_HUMIDITY,
    SERVICE_SET_FAN_MODE, SERVICE_SET_OPERATION_MODE, SERVICE_SET_SWING_MODE)
from homeassistant.const import (
    ATTR_ENTITY_ID, ATTR_TEMPERATURE)
from homeassistant.core import callback
from homeassistant.loader import bind_hass

@callback
@bind_hass
def async_set_away_mode(hass, away_mode, entity_id=None):
    """Turn all or specified climate devices away mode on."""
    data = {
        ATTR_AWAY_MODE: away_mode
    }

    if entity_id:
        data[ATTR_ENTITY_ID] = entity_id

    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_SET_AWAY_MODE, data))

@bind_hass
def set_away_mode(hass, away_mode, entity_id=None):
    """Turn all or specified climate devices away mode on."""
    data = {
        ATTR_AWAY_MODE: away_mode
    }

    if entity_id:
        data[ATTR_ENTITY_ID] = entity_id

    hass.services.call(DOMAIN, SERVICE_SET_AWAY_MODE, data)

@callback
@bind_hass
def async_set_hold_mode(hass, hold_mode, entity_id=None):
    """Set new hold mode."""
    data = {
        ATTR_HOLD_MODE: hold_mode
    }

    if entity_id:
        data[ATTR_ENTITY_ID] = entity_id

    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_SET_HOLD_MODE, data))

@bind_hass
def set_hold_mode(hass, hold_mode, entity_id=None):
    """Set new hold mode."""
    data = {
        ATTR_HOLD_MODE: hold_mode
    }

    if entity_id:
        data[ATTR_ENTITY_ID] = entity_id

    hass.services.call(DOMAIN, SERVICE_SET_HOLD_MODE, data)

@callback
@bind_hass
def async_set_aux_heat(hass, aux_heat, entity_id=None):
    """Turn all or specified climate devices auxiliary heater on."""
    data = {
        ATTR_AUX_HEAT: aux_heat
    }

    if entity_id:
        data[ATTR_ENTITY_ID] = entity_id

    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_SET_AUX_HEAT, data))

@bind_hass
def set_aux_heat(hass, aux_heat, entity_id=None):
    """Turn all or specified climate devices auxiliary heater on."""
    data = {
        ATTR_AUX_HEAT: aux_heat
    }

    if entity_id:
        data[ATTR_ENTITY_ID] = entity_id

    hass.services.call(DOMAIN, SERVICE_SET_AUX_HEAT, data)

@callback
@bind_hass
def async_set_temperature(hass, temperature=None, entity_id=None,
                          target_temp_high=None, target_temp_low=None,
                          operation_mode=None):
    """Set new target temperature."""
    kwargs = {
        key: value for key, value in [
            (ATTR_TEMPERATURE, temperature),
            (ATTR_TARGET_TEMP_HIGH, target_temp_high),
            (ATTR_TARGET_TEMP_LOW, target_temp_low),
            (ATTR_ENTITY_ID, entity_id),
            (ATTR_OPERATION_MODE, operation_mode)
        ] if value is not None
    }
    _LOGGER.debug("set_temperature start data=%s", kwargs)
    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_SET_TEMPERATURE, kwargs))

@bind_hass
def set_temperature(hass, temperature=None, entity_id=None,
                    target_temp_high=None, target_temp_low=None,
                    operation_mode=None):
    """Set new target temperature."""
    kwargs = {
        key: value for key, value in [
            (ATTR_TEMPERATURE, temperature),
            (ATTR_TARGET_TEMP_HIGH, target_temp_high),
            (ATTR_TARGET_TEMP_LOW, target_temp_low),
            (ATTR_ENTITY_ID, entity_id),
            (ATTR_OPERATION_MODE, operation_mode)
        ] if value is not None
    }
    _LOGGER.debug("set_temperature start data=%s", kwargs)
    hass.services.call(DOMAIN, SERVICE_SET_TEMPERATURE, kwargs)

@callback
@bind_hass
def async_set_humidity(hass, humidity, entity_id=None):
    """Set new target humidity."""
    data = {ATTR_HUMIDITY: humidity}

    if entity_id is not None:
        data[ATTR_ENTITY_ID] = entity_id

    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_SET_HUMIDITY, data))

@bind_hass
def set_humidity(hass, humidity, entity_id=None):
    """Set new target humidity."""
    data = {ATTR_HUMIDITY: humidity}

    if entity_id is not None:
        data[ATTR_ENTITY_ID] = entity_id

    hass.services.call(DOMAIN, SERVICE_SET_HUMIDITY, data)

@callback
@bind_hass
def async_set_fan_mode(hass, fan, entity_id=None):
    """Set all or specified climate devices fan mode on."""
    data = {ATTR_FAN_MODE: fan}

    if entity_id:
        data[ATTR_ENTITY_ID] = entity_id

    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_SET_FAN_MODE, data))

@bind_hass
def set_fan_mode(hass, fan, entity_id=None):
    """Set all or specified climate devices fan mode on."""
    data = {ATTR_FAN_MODE: fan}

    if entity_id:
        data[ATTR_ENTITY_ID] = entity_id

    hass.services.call(DOMAIN, SERVICE_SET_FAN_MODE, data)

@callback
@bind_hass
def async_set_operation_mode(hass, operation_mode, entity_id=None):
    """Set new target operation mode."""
    data = {ATTR_OPERATION_MODE: operation_mode}

    if entity_id is not None:
        data[ATTR_ENTITY_ID] = entity_id

    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_SET_OPERATION_MODE, data))

@bind_hass
def set_operation_mode(hass, operation_mode, entity_id=None):
    """Set new target operation mode."""
    data = {ATTR_OPERATION_MODE: operation_mode}

    if entity_id is not None:
        data[ATTR_ENTITY_ID] = entity_id

    hass.services.call(DOMAIN, SERVICE_SET_OPERATION_MODE, data)

@callback
@bind_hass
def async_set_swing_mode(hass, swing_mode, entity_id=None):
    """Set new target swing mode."""
    data = {ATTR_SWING_MODE: swing_mode}

    if entity_id is not None:
        data[ATTR_ENTITY_ID] = entity_id

    hass.async_create_task(
        hass.services.async_call(DOMAIN, SERVICE_SET_SWING_MODE, data))

@bind_hass
def set_swing_mode(hass, swing_mode, entity_id=None):
    """Set new target swing mode."""
    data = {ATTR_SWING_MODE: swing_mode}

    if entity_id is not None:
        data[ATTR_ENTITY_ID] = entity_id

    hass.services.call(DOMAIN, SERVICE_SET_SWING_MODE, data)


text:
<?php

/**
 * This file is part of Gush package.
 *
 * (c) 2013-2014 Luis Cordova <cordoval@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Gush\Tests\Command\PullRequest;

use Gush\Command\PullRequest\PullRequestListCommand;
use Gush\Tests\Command\BaseTestCase;
use Gush\Tests\Fixtures\OutputFixtures;

class PullRequestListCommandTest extends BaseTestCase
{
    /**
     * @test
     */
    public function lists_pull_requests()
    {
        $tester = $this->getCommandTester(new PullRequestListCommand());
        $tester->execute(['--org' => 'gushphp', '--repo' => 'gush'], ['interactive' => false]);

        $this->assertEquals(trim(OutputFixtures::PULL_REQUEST_LIST), trim($tester->getDisplay(true)));
    }
}


text:
'use strict';
const ServerConfig = require('../configs/server-config');
const Food = require('../models/food');

/**
 * Creation and removal of food
 */
class FoodService {

    constructor(playerStatBoard, boardOccupancyService, nameService, notificationService) {
        this.playerStatBoard = playerStatBoard;
        this.boardOccupancyService = boardOccupancyService;
        this.nameService = nameService;
        this.notificationService = notificationService;
        this.reinitialize();
    }

    // Only use this alongside clearing boardOccupancyService
    reinitialize() {
        this.food = {};
        this.generateDefaultFood();
    }

    consumeAndRespawnFood(playerContainer) {
        let foodToRespawn = 0;
        const foodsConsumed = this.boardOccupancyService.getFoodsConsumed();
        for (const foodConsumed of foodsConsumed) {
            const playerWhoConsumedFood = playerContainer.getPlayer(foodConsumed.playerId);
            const food = this.food[foodConsumed.foodId];
            playerWhoConsumedFood.grow(ServerConfig.FOOD[food.type].GROWTH);
            const points = ServerConfig.FOOD[food.type].POINTS;
            this.playerStatBoard.increaseScore(playerWhoConsumedFood.id, points);

            if (food.type === ServerConfig.FOOD.SWAP.TYPE && playerContainer.getNumberOfPlayers() > 1) {
                const otherPlayer = playerContainer.getAnActivePlayer(playerWhoConsumedFood.id);
                this.boardOccupancyService.removePlayerOccupancy(otherPlayer.id, otherPlayer.getSegments());
                this.boardOccupancyService.removePlayerOccupancy(playerWhoConsumedFood.id, playerWhoConsumedFood.getSegments());
                const otherPlayerDirection = otherPlayer.direction;
                const otherPlayerDirectionBeforeMove = otherPlayer.directionBeforeMove;
                const otherPlayerSegments = otherPlayer.getSegments();
                const otherPlayerGrowAmount = otherPlayer.growAmount;
                otherPlayer.swapBodies(playerWhoConsumedFood.getSegments(), playerWhoConsumedFood.direction,
                    playerWhoConsumedFood.directionBeforeMove, playerWhoConsumedFood.growAmount);
                playerWhoConsumedFood.swapBodies(otherPlayerSegments, otherPlayerDirection,
                    otherPlayerDirectionBeforeMove, otherPlayerGrowAmount);

                this.boardOccupancyService.addPlayerOccupancy(otherPlayer.id, otherPlayer.getSegments());
                this.boardOccupancyService.addPlayerOccupancy(playerWhoConsumedFood.id, playerWhoConsumedFood.getSegments());
                this.notificationService.notifyPlayerFoodCollected(playerWhoConsumedFood.id,
                    'Swap!', food.coordinate, food.color, true);
                this.notificationService.notifyPlayerFoodCollected(otherPlayer.id,
                    'Swap!', playerWhoConsumedFood.getHeadCoordinate(), food.color, true);
            } else {
                this.notificationService.notifyPlayerFoodCollected(playerWhoConsumedFood.id,
                    `+${points}`, food.coordinate, food.color);
            }

            this.removeFood(foodConsumed.foodId);
            foodToRespawn++;
        }

        this.generateFood(foodToRespawn);
    }

    generateDefaultFood() {
        this.generateFood(ServerConfig.FOOD.DEFAULT_AMOUNT);
    }

    generateFood(amount) {
        for (let i = 0; i < amount; i++) {
            this.generateSingleFood();
        }
    }

    generateSingleFood() {
        const randomUnoccupiedCoordinate = this.boardOccupancyService.getRandomUnoccupiedCoordinate();
        if (!randomUnoccupiedCoordinate) {
            this.notificationService.broadcastNotification('Could not add more food.  No room left.', 'white');
            return;
        }
        const foodId = this.nameService.getFoodId();
        let food;
        if (Math.random() < ServerConfig.FOOD.GOLDEN.SPAWN_RATE) {
            food = new Food(foodId, randomUnoccupiedCoordinate, ServerConfig.FOOD.GOLDEN.TYPE, ServerConfig.FOOD.GOLDEN.COLOR);
        } else if (Math.random() < ServerConfig.FOOD.SWAP.SPAWN_RATE) {
            food = new Food(foodId, randomUnoccupiedCoordinate, ServerConfig.FOOD.SWAP.TYPE, ServerConfig.FOOD.SWAP.COLOR);
        } else if (Math.random() < ServerConfig.FOOD.SUPER.SPAWN_RATE) {
            food = new Food(foodId, randomUnoccupiedCoordinate, ServerConfig.FOOD.SUPER.TYPE, ServerConfig.FOOD.SUPER.COLOR);
        } else {
            food = new Food(foodId, randomUnoccupiedCoordinate, ServerConfig.FOOD.NORMAL.TYPE, ServerConfig.FOOD.NORMAL.COLOR);
        }
        this.food[foodId] = food;
        this.boardOccupancyService.addFoodOccupancy(food.id, food.coordinate);
    }

    getFood() {
        return this.food;
    }

    getFoodAmount() {
        return Object.keys(this.food).length;
    }

    getLastFoodIdSpawned() {
        return this.food[Object.keys(this.food)[Object.keys(this.food).length - 1]].id;
    }

    removeFood(foodId) {
        const foodToRemove = this.food[foodId];
        this.nameService.returnFoodId(foodId);
        this.boardOccupancyService.removeFoodOccupancy(foodId, foodToRemove.coordinate);
        delete this.food[foodId];
    }
}

module.exports = FoodService;


text:
<?php

namespace RF\EdmundsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Edmunds API Bundle
 *
 * @author Ryan Fink <ryanjfink@gmail.com>
 */
class RFEdmundsBundle extends Bundle
{
}


text:
class Gdal < Formula
  desc "Geospatial Data Abstraction Library"
  homepage "https://www.gdal.org/"
  url "https://download.osgeo.org/gdal/2.3.1/gdal-2.3.1.tar.xz"
  sha256 "9c4625c45a3ee7e49a604ef221778983dd9fd8104922a87f20b99d9bedb7725a"
  revision 2

  bottle do
    sha256 "99c3dbc427938fc3a18bbeb29710e1706f2a38b13511fe5bf0d6f183f5592503" => :mojave
    sha256 "06161267b5ac59e36157a768898c3a857be36828e68137a1c1c23826cfb17f51" => :high_sierra
    sha256 "ab995b6e30c31c93915a647a43fa8e15517e9f0650259fabb988e0ca0bc1db99" => :sierra
    sha256 "0b6e992dc1c4e04c31dac54dd77498956603341abe791db3d6e042155d1345e1" => :el_capitan
  end

  head do
    url "https://svn.osgeo.org/gdal/trunk/gdal"
    depends_on "doxygen" => :build
  end

  option "with-complete", "Use additional Homebrew libraries to provide more drivers."
  option "with-unsupported", "Allow configure to drag in any library it can find. Invoke this at your own risk."

  deprecated_option "enable-unsupported" => "with-unsupported"
  deprecated_option "complete" => "with-complete"

  depends_on "freexl"
  depends_on "geos"
  depends_on "giflib"
  depends_on "jpeg"
  depends_on "json-c"
  depends_on "libgeotiff"
  depends_on "libpng"
  depends_on "libpq"
  depends_on "libspatialite"
  depends_on "libtiff"
  depends_on "libxml2"
  depends_on "numpy"
  depends_on "pcre"
  depends_on "proj"
  depends_on "python"
  depends_on "python@2"
  depends_on "sqlite" # To ensure compatibility with SpatiaLite
  depends_on "zstd"

  depends_on "mysql" => :optional

  if build.with? "complete"
    depends_on "cfitsio"
    depends_on "epsilon"
    depends_on "hdf5"
    depends_on "jasper"
    depends_on "json-c"
    depends_on "libdap"
    depends_on "libxml2"
    depends_on "netcdf"
    depends_on "podofo"
    depends_on "poppler"
    depends_on "unixodbc" # macOS version is not complete enough
    depends_on "webp"
    depends_on "xerces-c"
    depends_on "xz" # get liblzma compression algorithm library from XZutils
  end

  def install
    args = [
      # Base configuration
      "--prefix=#{prefix}",
      "--mandir=#{man}",
      "--disable-debug",
      "--with-libtool",
      "--with-local=#{prefix}",
      "--with-opencl",
      "--with-threads",

      # GDAL native backends
      "--with-bsb",
      "--with-grib",
      "--with-pam",
      "--with-pcidsk=internal",
      "--with-pcraster=internal",

      # Homebrew backends
      "--with-curl=/usr/bin/curl-config",
      "--with-freexl=#{Formula["freexl"].opt_prefix}",
      "--with-geos=#{Formula["geos"].opt_prefix}/bin/geos-config",
      "--with-geotiff=#{Formula["libgeotiff"].opt_prefix}",
      "--with-gif=#{Formula["giflib"].opt_prefix}",
      "--with-jpeg=#{Formula["jpeg"].opt_prefix}",
      "--with-libjson-c=#{Formula["json-c"].opt_prefix}",
      "--with-libtiff=#{Formula["libtiff"].opt_prefix}",
      "--with-pg=#{Formula["libpq"].opt_prefix}/bin/pg_config",
      "--with-png=#{Formula["libpng"].opt_prefix}",
      "--with-spatialite=#{Formula["libspatialite"].opt_prefix}",
      "--with-sqlite3=#{Formula["sqlite"].opt_prefix}",
      "--with-static-proj4=#{Formula["proj"].opt_prefix}",
      "--with-zstd=#{Formula["zstd"].opt_prefix}",

      # Explicitly disable some features
      "--without-grass",
      "--without-jpeg12",
      "--without-libgrass",
      "--without-perl",
      "--without-php",
      "--without-python",
      "--without-ruby",
      "--with-armadillo=no",
      "--with-qhull=no",
    ]

    if build.with?("mysql")
      args << "--with-mysql=#{Formula["mysql"].opt_prefix}/bin/mysql_config"
    else
      args << "--without-mysql"
    end

    # Optional Homebrew packages supporting additional formats
    supported_backends = %w[liblzma cfitsio hdf5 netcdf jasper xerces odbc
                            dods-root epsilon webp podofo]
    if build.with? "complete"
      supported_backends.delete "liblzma"
      args << "--with-liblzma=yes"
      args.concat supported_backends.map { |b| "--with-" + b + "=" + HOMEBREW_PREFIX }
    elsif build.without? "unsupported"
      args.concat supported_backends.map { |b| "--without-" + b }
    end

    # Unsupported backends are either proprietary or have no compatible version
    # in Homebrew. Podofo is disabled because Poppler provides the same
    # functionality and then some.
    unsupported_backends = %w[gta ogdi fme hdf4 openjpeg fgdb ecw kakadu mrsid
                              jp2mrsid mrsid_lidar msg oci ingres dwgdirect
                              idb sde podofo rasdaman sosi]
    if build.without? "unsupported"
      args.concat unsupported_backends.map { |b| "--without-" + b }
    end

    system "./configure", *args
    system "make"
    system "make", "install"

    if build.stable? # GDAL 2.3 handles Python differently
      cd "swig/python" do
        system "python3", *Language::Python.setup_install_args(prefix)
        system "python2", *Language::Python.setup_install_args(prefix)
      end
      bin.install Dir["swig/python/scripts/*.py"]
    end

    system "make", "man" if build.head?
    # Force man installation dir: https://trac.osgeo.org/gdal/ticket/5092
    system "make", "install-man", "INST_MAN=#{man}"
    # Clean up any stray doxygen files
    Dir.glob("#{bin}/*.dox") { |p| rm p }
  end

  test do
    # basic tests to see if third-party dylibs are loading OK
    system "#{bin}/gdalinfo", "--formats"
    system "#{bin}/ogrinfo", "--formats"
    if build.stable? # GDAL 2.3 handles Python differently
      system "python3", "-c", "import gdal"
      system "python2", "-c", "import gdal"
    end
  end
end


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/chipmunk_static.dir/cpCollision.c.o"
  "CMakeFiles/chipmunk_static.dir/cpSpaceHash.c.o"
  "CMakeFiles/chipmunk_static.dir/cpVect.c.o"
  "CMakeFiles/chipmunk_static.dir/cpShape.c.o"
  "CMakeFiles/chipmunk_static.dir/cpArray.c.o"
  "CMakeFiles/chipmunk_static.dir/cpSpace.c.o"
  "CMakeFiles/chipmunk_static.dir/cpHashSet.c.o"
  "CMakeFiles/chipmunk_static.dir/cpArbiter.c.o"
  "CMakeFiles/chipmunk_static.dir/cpBB.c.o"
  "CMakeFiles/chipmunk_static.dir/cpPolyShape.c.o"
  "CMakeFiles/chipmunk_static.dir/cpBody.c.o"
  "CMakeFiles/chipmunk_static.dir/chipmunk.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpRatchetJoint.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpDampedRotarySpring.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpPinJoint.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpRotaryLimitJoint.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpDampedSpring.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpGearJoint.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpPivotJoint.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpGrooveJoint.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpConstraint.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpSlideJoint.c.o"
  "CMakeFiles/chipmunk_static.dir/constraints/cpSimpleMotor.c.o"
  "libchipmunk.pdb"
  "libchipmunk.a"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang C)
  INCLUDE(CMakeFiles/chipmunk_static.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
import { IAsyncEnumerable, IComparer } from "./"

/**
 * Represents an async enumeration that has been ordered.
 */
export interface IOrderedAsyncEnumerable<TSource> extends IAsyncEnumerable<TSource> {
    thenBy<TKey>(
        keySelector: (x: TSource) => TKey,
        comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource>
    thenByAsync<TKey>(
        keySelector: (x: TSource) => Promise<TKey>,
        comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource>
    thenByDescending<TKey>(
        keySelector: (x: TSource) => TKey,
        comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource>
    thenByDescendingAsync<TKey>(
        keySelector: (x: TSource) => Promise<TKey>,
        comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource>
}


text:
{% extends "helper/admin_base_action.html" %}

{% load i18n l10n %}

{% block action_title %}{% trans 'Send mail to users' %}{% endblock %}

{% block breadcrumbs_action_label %}
  {% trans 'Send mail to users' %}
{% endblock %}

{% block action_content %}
<form action="" method="post">{% csrf_token %}

      {% trans "Subject" %}: <input type="text" name="subject" value=""/>

    <textarea name="body" rows="8" style="width: 100%">{% include "emails/footer.txt" %}</textarea>

    {% trans "You can use the following placeholders:" %} {name}, {first_name}, {last_name}, {url}
    <input type="hidden" name="action" value="send_mail" />

      <input type="submit" value="{% blocktrans count count=queryset.count %}Send mail to one user{% plural %}Send mail to {{ count }} users{% endblocktrans %}" />

  <input type="hidden" name="action" value="{{ action_name }}" />
  {% if select_across %}
    <input type="hidden" name="select_across" value="1"/>
    {# set invalid selected, so confirmation action path is chosen in admin #}
    <input type="hidden" name="{{ action_checkbox_name }}" value="_" />
  {% else %}
    {% for obj in queryset %}
      <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" />
    {% endfor %}
  {% endif %}
</form>
{% endblock %}


text:
package au.com.addstar.rcon.commands.accounts;

import java.io.IOException;
import java.util.EnumSet;
import java.util.List;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

import au.com.addstar.rcon.BetterRCon;
import au.com.addstar.rcon.auth.AuthManager;
import au.com.addstar.rcon.auth.StoredPassword;
import au.com.addstar.rcon.auth.User;
import au.com.addstar.rcon.commands.CommandSenderType;
import au.com.addstar.rcon.commands.ICommand;

public class AddCommand implements ICommand
{
	@Override
	public String getName()
	{
		return "add";
	}

	@Override
	public String[] getAliases()
	{
		return null;
	}

	@Override
	public String getPermission()
	{
		return "rcon.account.manage.add";
	}

	@Override
	public String getUsageString( String label, CommandSender sender )
	{
		return label + " <accountName> <password> [isOp]";
	}

	@Override
	public String getDescription()
	{
		return "Adds an account with the specified name. isOp defaults to true by default";
	}

	@Override
	public EnumSet<CommandSenderType> getAllowedSenders()
	{
		return EnumSet.of(CommandSenderType.Player, CommandSenderType.Console);
	}

	@Override
	public boolean onCommand( CommandSender sender, String label, String[] args )
	{
		if(args.length != 2 && args.length != 3)
			return false;

		AuthManager manager = BetterRCon.getAuth();

		User user = manager.getUser(args[0]);

		if(user != null)
		{
			sender.sendMessage(ChatColor.RED + "That user account already exists");
			return true;
		}

		char[] password = args[1].toCharArray();

		boolean op = true;
		if(args.length == 3)
			op = Boolean.parseBoolean(args[2]);

		try
		{
			user = manager.createUser(args[0]);

			user.setOp(op);
			user.setPassword(StoredPassword.generate(password));

			sender.sendMessage(ChatColor.GREEN + "Account " + user.getName() + " was successfully created.");
			manager.write();
		}
		catch(IllegalArgumentException e)
		{
			sender.sendMessage(ChatColor.RED + e.getMessage());
		}
		catch ( IOException e )
		{
			sender.sendMessage(ChatColor.RED + "An error occured while saving the new account.");
			e.printStackTrace();
		}

		return true;
	}

	@Override
	public List<String> onTabComplete( CommandSender sender, String label, String[] args )
	{
		return null;
	}

}


text:
/*
 * Minio Client (C) 2015 Minio, Inc.
 *
 * 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 cmd

import (
	"net/http"
	"time"

	. "gopkg.in/check.v1"
)

func (s *TestSuite) TestVersion(c *C) {
	_, e := time.Parse(Version, http.TimeFormat)
	c.Assert(e, NotNil)
}


text:
from tkinter import Frame, Text, Button, Label, Scrollbar, WORD, N, E, W, S
from TBoxBase import *
from Arithmetic.Numbers.Primality.PrimeTest import is_prime, next_prime
import sys

class Prime(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller

        self.columnconfigure(0, weight=1, pad=5)

        self.rowconfigure(0, pad=5)
        self.rowconfigure(1, weight=1, pad=5)
        self.rowconfigure(2, pad=5)
        self.rowconfigure(3, weight=1, pad=5)

        # Title
        bbutton = Button(self, text="<", command=lambda: controller.show_frame("MainPage"))
        bbutton.grid(row=0, padx=10, sticky=W)
        title = Label(self, text="Primality Test")
        title.grid(row=0, padx=10)

        # Number input
        tinput = Text(self, wrap=WORD)
        tinput.grid(row=1, padx=10, pady=10, sticky=N + E + S + W)
        scrolli = Scrollbar(self, command=tinput.yview)
        tinput.configure(yscrollcommand=scrolli.set)
        scrolli.grid(row=1, pady=10, sticky=N + S + E)
        tinput.insert(1.0, "Integer")
        tinput.bind("<Control-Key-a>", select_all)  # select-all Windows/Linux
        tinput.bind("<Command-Key-a>", select_all)  # select-all Mac

        # Check button
        ebutton = Button(self, text="Check", width=15)
        ebutton.grid(row=2)
        ebutton.configure(command=lambda: self.check(tinput.get(1.0, 'end-1c')))

        # Output box
        self.output = Text(self, wrap=WORD)
        self.output.grid(row=3, padx=10, pady=10, sticky=N + E + S + W)
        self.output.bind("<1>", lambda event: self.output.focus_set())
        scrollo = Scrollbar(self, command=self.output.yview)
        scrollo.grid(row=3, pady=10, sticky=N + S + E)
        self.output.configure(yscrollcommand=scrollo.set)
        self.output.insert(1.0, "Output")
        self.output.configure(state="disabled")
        self.output.bind("<Control-Key-a>", select_all)  # select-all Windows/Linux
        self.output.bind("<Command-Key-a>", select_all)  # select-all Mac

    def check(self, number):
        try:
            number = int(number)
            if is_prime(number):
                display("Number is prime", self.output)
            else:
                next = next_prime(number)
                display("Not prime. Next prime is " + str(next), self.output)
        except ValueError:
            display("Invalid number!", self.output)
        except:
            print("Unexpected error:", sys.exc_info()[0])
            raise
        return


text:
import React, { Component } from 'react';
import Menu from './menu';

class Banks extends Component {
    constructor() {
      super();
      this.state = {
          banks: []
      }
    }

    componentDidMount() {
      const xmlHttp = new XMLHttpRequest();
      const vm = this;
      xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
               vm.setState({
                   banks: JSON.parse(xmlHttp.responseText)
               });
           }
       };
       xmlHttp.open("GET", `/api/banks/`, true); // true for asynchronous
       xmlHttp.send(null);
    }

   renderItems() {
     return this.state.banks.map(function (bank) {
       return
{bank.bank}
;
    });
  }

  render() {
      return (

          <Menu />

            {this.renderItems()}

    );
  }
}

  export default Banks;


text:
package gobblin.metrics.broker;

import gobblin.broker.iface.SharedResourceKey;
import lombok.Data;

/**
 * A {@link SharedResourceKey} used for {@link MetricContextFactory}.
 */
@Data
public class MetricContextKey implements SharedResourceKey {
  @Override
  public String toConfigurationKey() {
    return null;
  }
}


text:
package au.id.wolfe.riak.log4j.example;

import au.id.wolfe.riak.log4j.example.data.Person;

import javax.jws.WebService;

/**
 * Example contact person service
 */
@WebService
public interface ContactPersonService {

    Person getContactPersonByName(String firstName, String lastName);
}


text:
package org.apereo.cas.services;

import org.apereo.cas.services.replication.NoOpRegisteredServiceReplicationStrategy;
import org.apereo.cas.services.resource.DefaultRegisteredServiceResourceNamingStrategy;
import org.apereo.cas.util.io.WatcherService;
import org.apereo.cas.util.serialization.JacksonObjectMapperFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Test cases for {@link OidcRegisteredService}.
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Tag("OIDC")
public class OidcRegisteredServiceTests {

    private static final File JSON_FILE = new File(FileUtils.getTempDirectoryPath(), "oidcRegisteredService.json");
    private static final ObjectMapper MAPPER = JacksonObjectMapperFactory.builder()
        .defaultTypingEnabled(true).build().toObjectMapper();

    private static final ClassPathResource RESOURCE = new ClassPathResource("services");

    private final ServiceRegistry dao;

    public OidcRegisteredServiceTests() throws Exception {
        val appCtx = new StaticApplicationContext();
        appCtx.refresh();
        this.dao = new JsonServiceRegistry(RESOURCE, WatcherService.noOp(),
            appCtx,
            new NoOpRegisteredServiceReplicationStrategy(),
            new DefaultRegisteredServiceResourceNamingStrategy(),
            new ArrayList<>());
    }

    @BeforeAll
    public static void prepTests() throws Exception {
        FileUtils.cleanDirectory(RESOURCE.getFile());
    }

    @Test
    public void checkSaveMethod() {
        val r = new OidcRegisteredService();
        r.setName("checkSaveMethod");
        r.setServiceId("testId");
        r.setJwks("file:/tmp/thekeystorehere.jwks");
        r.setSignIdToken(true);
        r.setBypassApprovalPrompt(true);
        val r2 = this.dao.save(r);
        assertTrue(r2 instanceof OidcRegisteredService);
        this.dao.load();
        val r3 = this.dao.findServiceById(r2.getId());
        assertTrue(r3 instanceof OidcRegisteredService);
        assertEquals(r, r2);
        assertEquals(r2, r3);
        assertNotNull(r.newInstance());
        assertNotNull(r.getFriendlyName());
    }

    @Test
    public void verifySerializeAOidcRegisteredServiceToJson() throws IOException {
        val serviceWritten = new OidcRegisteredService();
        serviceWritten.setName("verifySerializeAOidcRegisteredServiceToJson");
        serviceWritten.setServiceId("testId");
        serviceWritten.setJwks("file:/tmp/thekeystorehere.jwks");
        serviceWritten.setSignIdToken(true);
        serviceWritten.setBypassApprovalPrompt(true);
        serviceWritten.setUsernameAttributeProvider(new PairwiseOidcRegisteredServiceUsernameAttributeProvider());
        MAPPER.writeValue(JSON_FILE, serviceWritten);
        val serviceRead = MAPPER.readValue(JSON_FILE, OidcRegisteredService.class);
        assertEquals(serviceWritten, serviceRead);
    }
}


text:
using System;
using Bivi.Domaine;
using Bivi.FrontOffice.Web.ViewModels.Pages.Common;
using Bivi.Infrastructure.Services.Caching;

namespace Bivi.FrontOffice.Web.ViewModels
{
    public class PopinVideoViewModel
    {
        public ICaching TranslatorService { get; set; }
        public string Titre { get; set; }
        public string Url { get; set; }
        public string VideoType { get; set; }
        public bool External { get; set; }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Interface com.google.common.collect.BiMap (Guava: Google Core Libraries for Java - latest)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
com.google.common.collect.BiMap

Packages that use BiMap

com.google.common.collect
This package contains generic collection interfaces and implementations, and
 other utilities for working with collections.

Uses of BiMap in com.google.common.collect

Classes in com.google.common.collect that implement BiMap

 class
EnumBiMap<K extends Enum<K>,V extends Enum<V>>

          A BiMap backed by two EnumMap instances.

 class
EnumHashBiMap<K extends Enum<K>,V>

          A BiMap backed by an EnumMap instance for keys-to-values, and
 a HashMap instance for values-to-keys.

 class
HashBiMap<K,V>

          A BiMap backed by two HashMap instances.

 class
ImmutableBiMap<K,V>

          An immutable BiMap with reliable user-specified iteration order.

Methods in com.google.common.collect that return BiMap

static

<K,V> BiMap<K,V>

MapConstraints.constrainedBiMap(BiMap<K,V> map,
                                 MapConstraint<? super K,? super V> constraint)

          Returns a constrained view of the specified bimap, using the specified
 constraint.

 BiMap<V,K>
BiMap.inverse()

          Returns the inverse view of this bimap, which maps each of this bimap's
 values to its associated key.

static

<K,V> BiMap<K,V>

Maps.synchronizedBiMap(BiMap<K,V> bimap)

          Returns a synchronized (thread-safe) bimap backed by the specified bimap.

static

<K,V> BiMap<K,V>

Maps.unmodifiableBiMap(BiMap<? extends K,? extends V> bimap)

          Returns an unmodifiable view of the specified bimap.

Methods in com.google.common.collect with parameters of type BiMap

static

<K,V> BiMap<K,V>

MapConstraints.constrainedBiMap(BiMap<K,V> map,
                                 MapConstraint<? super K,? super V> constraint)

          Returns a constrained view of the specified bimap, using the specified
 constraint.

static

<K,V> BiMap<K,V>

Maps.synchronizedBiMap(BiMap<K,V> bimap)

          Returns a synchronized (thread-safe) bimap backed by the specified bimap.

static

<K,V> BiMap<K,V>

Maps.unmodifiableBiMap(BiMap<? extends K,? extends V> bimap)

          Returns an unmodifiable view of the specified bimap.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
require 'spec_helper'

describe Projects::AutocompleteService do
  describe '#issues' do
    describe 'confidential issues' do
      let(:author) { create(:user) }
      let(:assignee) { create(:user) }
      let(:non_member) { create(:user) }
      let(:member) { create(:user) }
      let(:admin) { create(:admin) }
      let(:project) { create(:project, :public) }
      let!(:issue) { create(:issue, project: project, title: 'Issue 1') }
      let!(:security_issue_1) { create(:issue, :confidential, project: project, title: 'Security issue 1', author: author) }
      let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project, assignees: [assignee]) }

      it 'does not list project confidential issues for guests' do
        autocomplete = described_class.new(project, nil)
        issues = autocomplete.issues.map(&:iid)

        expect(issues).to include issue.iid
        expect(issues).not_to include security_issue_1.iid
        expect(issues).not_to include security_issue_2.iid
        expect(issues.count).to eq 1
      end

      it 'does not list project confidential issues for non project members' do
        autocomplete = described_class.new(project, non_member)
        issues = autocomplete.issues.map(&:iid)

        expect(issues).to include issue.iid
        expect(issues).not_to include security_issue_1.iid
        expect(issues).not_to include security_issue_2.iid
        expect(issues.count).to eq 1
      end

      it 'does not list project confidential issues for project members with guest role' do
        project.add_guest(member)

        autocomplete = described_class.new(project, non_member)
        issues = autocomplete.issues.map(&:iid)

        expect(issues).to include issue.iid
        expect(issues).not_to include security_issue_1.iid
        expect(issues).not_to include security_issue_2.iid
        expect(issues.count).to eq 1
      end

      it 'lists project confidential issues for author' do
        autocomplete = described_class.new(project, author)
        issues = autocomplete.issues.map(&:iid)

        expect(issues).to include issue.iid
        expect(issues).to include security_issue_1.iid
        expect(issues).not_to include security_issue_2.iid
        expect(issues.count).to eq 2
      end

      it 'lists project confidential issues for assignee' do
        autocomplete = described_class.new(project, assignee)
        issues = autocomplete.issues.map(&:iid)

        expect(issues).to include issue.iid
        expect(issues).not_to include security_issue_1.iid
        expect(issues).to include security_issue_2.iid
        expect(issues.count).to eq 2
      end

      it 'lists project confidential issues for project members' do
        project.add_developer(member)

        autocomplete = described_class.new(project, member)
        issues = autocomplete.issues.map(&:iid)

        expect(issues).to include issue.iid
        expect(issues).to include security_issue_1.iid
        expect(issues).to include security_issue_2.iid
        expect(issues.count).to eq 3
      end

      it 'lists all project issues for admin' do
        autocomplete = described_class.new(project, admin)
        issues = autocomplete.issues.map(&:iid)

        expect(issues).to include issue.iid
        expect(issues).to include security_issue_1.iid
        expect(issues).to include security_issue_2.iid
        expect(issues.count).to eq 3
      end
    end
  end

  describe '#milestones' do
    let(:user) { create(:user) }
    let(:group) { create(:group) }
    let(:project) { create(:project, group: group) }
    let!(:group_milestone1) { create(:milestone, group: group, due_date: '2017-01-01', title: 'Second Title') }
    let!(:group_milestone2) { create(:milestone, group: group, due_date: '2017-01-01', title: 'First Title') }
    let!(:project_milestone) { create(:milestone, project: project, due_date: '2016-01-01') }

    let(:milestone_titles) { described_class.new(project, user).milestones.map(&:title) }

    it 'includes project and group milestones and sorts them correctly' do
      expect(milestone_titles).to eq([project_milestone.title, group_milestone2.title, group_milestone1.title])
    end

    it 'does not include closed milestones' do
      group_milestone1.close

      expect(milestone_titles).to eq([project_milestone.title, group_milestone2.title])
    end

    it 'does not include milestones from other projects in the group' do
      other_project = create(:project, group: group)
      project_milestone.update!(project: other_project)

      expect(milestone_titles).to eq([group_milestone2.title, group_milestone1.title])
    end

    context 'with nested groups', :nested_groups do
      let(:subgroup) { create(:group, :public, parent: group) }
      let!(:subgroup_milestone) { create(:milestone, group: subgroup) }

      before do
        project.update(namespace: subgroup)
      end

      it 'includes project milestones and all acestors milestones' do
        expect(milestone_titles).to match_array(
          [project_milestone.title, group_milestone2.title, group_milestone1.title, subgroup_milestone.title]
        )
      end
    end
  end

  describe '#labels_as_hash' do
    def expect_labels_to_equal(labels, expected_labels)
      expect(labels.size).to eq(expected_labels.size)
      extract_title = lambda { |label| label['title'] }
      expect(labels.map(&extract_title)).to eq(expected_labels.map(&extract_title))
    end

    let(:user) { create(:user) }
    let(:group) { create(:group, :nested) }
    let!(:sub_group) { create(:group, parent: group) }
    let(:project) { create(:project, :public, group: group) }
    let(:issue) { create(:issue, project: project) }

    let!(:label1) { create(:label, project: project) }
    let!(:label2) { create(:label, project: project) }
    let!(:sub_group_label) { create(:group_label, group: sub_group) }
    let!(:parent_group_label) { create(:group_label, group: group.parent, group_id: group.id) }

    before do
      create(:group_member, group: group, user: user)
    end

    it 'returns labels from project and ancestor groups' do
      service = described_class.new(project, user)
      results = service.labels_as_hash(nil)
      expected_labels = [label1, label2, parent_group_label]

      expect_labels_to_equal(results, expected_labels)
    end

    context 'some labels are already assigned' do
      before do
        issue.labels << label1
      end

      it 'marks already assigned as set' do
        service = described_class.new(project, user)
        results = service.labels_as_hash(issue)
        expected_labels = [label1, label2, parent_group_label]

        expect_labels_to_equal(results, expected_labels)

        assigned_label_titles = issue.labels.map(&:title)
        results.each do |hash|
          if assigned_label_titles.include?(hash['title'])
            expect(hash[:set]).to eq(true)
          else
            expect(hash.key?(:set)).to eq(false)
          end
        end
      end
    end
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hoangphan.tutor01;

/**
 *
 * @author hoangpt
 */
public class Spymen {

  //constructor defautl
  public Spymen() {
  }

  //global
  String fakeName;

  void hideName(){
    this.fakeName = "Tam";
  }

  void sayHello(String name) {
    //local variable
    System.out.println("Chao ban "+name+". <3");
    this.fakeName = name;
  }
}


text:
module HN.Blaze
  (module Text.Blaze.Extra
  ,module Text.Blaze.Html5
  ,module Text.Blaze.Html5.Attributes
  ,module Text.Blaze.Renderer.Text
  ,module Text.Blaze.Linkify
  ,module Text.Blaze.Pagination
  ,module Text.Blaze.Bootstrap
  )
    where

import Text.Blaze.Extra
import Text.Blaze.Html5 hiding (output,map,i,title,cite,style,summary,object,footer)
import Text.Blaze.Html5.Attributes hiding (label,span,cite,form,summary)
import Text.Blaze.Renderer.Text
import Text.Blaze.Linkify
import Text.Blaze.Pagination
import Text.Blaze.Bootstrap


text:
package com.googlecode.japi.checker.tests;

public class InterfaceToClass {

}


text:
/* global Bloodhound */

(function ($) {
	// Share
	$('body').on('click', function () {
		$('.article-share-box.on').removeClass('on');
	}).on('click', '.article-share-link', function (e) {
		e.stopPropagation();

		var $this = $(this),
				url = $this.attr('data-url'),
				encodedUrl = encodeURIComponent(url),
				id = 'article-share-box-' + $this.attr('data-id'),
				offset = $this.offset();

		if ($('#' + id).length) {
			var box = $('#' + id);

			if (box.hasClass('on')) {
				box.removeClass('on');
				return;
			}
		} else {
			var html = [
				'
',
				'<input class="article-share-input" value="' + url + '">',
				'
',
				'',
				'',
				'',
				'
',
				'
'
			].join('');

			var box = $(html);

			$('body').append(box);
		}

		$('.article-share-box.on').hide();

		box.css({
			top: offset.top + 25,
			left: offset.left
		}).addClass('on');
	}).on('click', '.article-share-box', function (e) {
		e.stopPropagation();
	}).on('click', '.article-share-box-input', function () {
		$(this).select();
	}).on('click', '.article-share-box-link', function (e) {
		e.preventDefault();
		e.stopPropagation();

		window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
	});

	// Caption
	$('.article-entry').each(function (i) {
		$(this).find('img').each(function () {
			if ($(this).parent().hasClass('fancybox'))
				return;

			var alt = this.alt;

			if (alt)
				$(this).after('' + alt + '');

			$(this).wrap('');
		});

		$(this).find('.fancybox').each(function () {
			$(this).attr('rel', 'article' + i);
		});
	});

	if ($.fancybox) {
		$('.fancybox').fancybox();
	}

	////////////////////////////
	//	SEARCH BOX
	////////////////////////////

	var APPID = "app:albogdano";
	var ENDPOINT = "https://paraio.com/v1"; // OR "http://localhost:8080/v1"

	$.ajaxSetup({headers: {'Authorization': 'Anonymous ' + APPID}});

	var blogposts = new Bloodhound({
		datumTokenizer: Bloodhound.tokenizers.whitespace,
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		remote: {
			url: ENDPOINT + '/blogposts?limit=6&q=%QUERY',
			wildcard: '%QUERY',
			transform: function (res) {
				return res.items || [];
			}
		}
	});

	$('#search-box').typeahead({
		hint: false,
		highlight: true,
		minLength: 3
	},
	{
		name: 'blogposts',
		source: blogposts,
		limit: 40,
		templates: {
			notFound: 'No results.'
		},
		display: function (result) {
			return result.name;
		}
	});

	$('#search-box').bind('typeahead:select', function (ev, result) {
		window.location = result.url || '';
	});

})(jQuery);


text:
import click

from constants import *
from datasets import to_text

from music21.stream import Stream
from music21.note import Note, Rest
from music21.tie import Tie
from music21.duration import Duration
from music21.chord import Chord
from music21 import expressions

import codecs
import json

@click.group()
def decode():
    "Decode encoded data format into musicXML for displaying and playback."
    pass

@click.command()
@click.option('--utf-to-txt-json', type=click.File('rb'), default=SCRATCH_DIR + '/utf_to_txt.json')
@click.option('--min-length', type=int, default=100, help='Minimum length of samples in frames')
@click.option('--max-length', type=int, default=400, help='Maximum length of samples in frames')
@click.argument('utf8-file', type=click.Path(exists=True))
@click.argument('out-dir', type=click.Path(exists=True), default=SCRATCH_DIR + '/out')
def sampled_stream(utf_to_txt_json, utf8_file, out_dir, min_length, max_length):
    """
    Decodes all scores in a single sampled UTF stream to text and musicXML.

    This method splits on START_DELIM and outputs one text and musicXML encoded file for each score.
    """
    utf_to_txt = json.load(utf_to_txt_json)
    utf_data = filter(lambda x: x != u'\n', codecs.open(utf8_file, "r", "utf-8").read())
    utf_scores = utf_data.split(START_DELIM)[1:] # [1:] ignores first START_DELIM

    i = 0
    for utf_score in utf_scores:
        score = decode_utf_single(utf_to_txt, utf_score)
        if score and len(score) >= min_length and len(score) <= max_length:
            print('Writing {0}'.format(out_dir + '/out-{0}'.format(i)))
            with open(out_dir + '/out-{0}.txt'.format(i), 'w') as fd:
                fd.write('\n'.join(to_text(score)))
            to_musicxml(score).write('musicxml', out_dir + '/out-{0}.xml'.format(i))
            i += 1

@click.command()
@click.option('--utf-to-txt-json', type=click.File('rb'), default=SCRATCH_DIR + '/utf_to_txt.json')
@click.argument('utf8-file', type=click.Path(exists=True))
@click.argument('out-file', type=click.File('wb'), default=SCRATCH_DIR + '/out/decode.xml')
def single(utf_to_txt_json, utf8_file, out_file):
    """
    Decodes a single UTF8 output file
    """
    utf_to_txt = json.load(utf_to_txt_json)
    utf_data = filter(lambda x: x != u'\n', codecs.open(utf8_file, "r", "utf-8").read())
    utf_scores = utf_data.split(START_DELIM)[1:] # [1:] ignores first START_DELIM

    score = decode_utf_single(utf_to_txt, utf_scores[0])
    print('Writing {0}'.format(out_file.name))
    if score:
        to_musicxml(score).write('musicxml', out_file.name)

def decode_utf_single(utf_to_txt, utf_score):
    "Reads a single UTF encoded file into a Python representation."
    curr_score = []
    curr_chord_fermata = False
    curr_chord_notes = []
    i = 0
    for utf_token in utf_score:
        txt = utf_to_txt.get(utf_token)
        if txt == 'END':
            return curr_score
        elif txt == 'START':
            curr_score = []
            curr_chord_notes = []
        elif txt == CHORD_BOUNDARY_DELIM:
            curr_score.append((curr_chord_fermata, curr_chord_notes))
            curr_chord_fermata = False
            curr_chord_notes = []
        elif txt == FERMATA_SYM:
            curr_chord_fermata = True
        elif txt == None:
            print(u'Skipping unknown token: {}'.format(utf_token))
        else:
            curr_chord_notes.append(eval(txt))

def to_musicxml(sc_enc):
    "Converts Chord tuples (see chorales.prepare_poly) to musicXML"
    timestep = Duration(1. / FRAMES_PER_CROTCHET)
    musicxml_score = Stream()
    prev_chord = dict() # midi->(note instance from previous chord), used to determine tie type (start, continue, stop)
    for has_fermata, chord_notes in sc_enc:
        notes = []
        if len(chord_notes) == 0: # no notes => rest for this frame
            r = Rest()
            r.duration = timestep
            musicxml_score.append(r)
        else:
            for note_tuple in chord_notes:
                note = Note()
                if has_fermata:
                    note.expressions.append(expressions.Fermata())
                note.midi = note_tuple[0]
                if note_tuple[1]: # current note is tied
                    note.tie = Tie('stop')
                    if prev_chord and note.pitch.midi in prev_chord:
                        prev_note = prev_chord[note.pitch.midi]
                        if prev_note.tie is None:
                            prev_note.tie = Tie('start')
                        else:
                            prev_note.tie = Tie('continue')
                notes.append(note)
            prev_chord = { note.pitch.midi : note for note in notes }
            chord = Chord(notes=notes, duration=timestep)
            if has_fermata:
                chord.expressions.append(expressions.Fermata())
            musicxml_score.append(chord)
    return musicxml_score

map(decode.add_command, [
    sampled_stream,
    single,
])


text:
<?php
namespace App\AdminBundle\Business\Estimate;

use App\AdminBundle\Business\Base\BaseCreateHandler;
use App\ClientBundle\Entity;
use App\AdminBundle\Business;
use App\ClientBundle\Entity\ClientInvoice;

class CreateHandler extends BaseCreateHandler
{
    public $newId;

    public function getDefaultValues()
    {
        $model = new CreateModel();

        $model->idClient = $this->container->get('request')->query->get('id', null);

        return $model;
    }

    public function buildForm($builder)
    {
        $builder->add('idClient', 'choice', array(
            'attr'     => array(
                'placeholder' => 'CLIENT'
            ),
            'required' => false,
            'choices'  => $this->helperMapping->getMapping('client_list')
        ));
        /*$builder->add('subject', 'text', array(
            'attr'     => array(
                'placeholder' => 'Subject'
            ),
            'required' => false
        ));
        $builder->add('issueDate', 'date_picker', array(
            'attr'     => array(
                'placeholder' => 'Issue Date'
            ),
            'required' => false,
            'widget'   => 'single_text'
        ));
        $builder->add('dueDate', 'date_picker', array(
            'attr'     => array(
                'placeholder' => 'Due Date'
            ),
            'required' => false,
            'widget'   => 'single_text'
        ));
        $builder->add('discount', 'percent', array(
            'attr'     => array(
                'placeholder' => 'Discount'
            ),
            'required' => false
        ));
        $builder->add('tax', 'percent', array(
            'attr'     => array(
                'placeholder' => 'Tax'
            ),
            'required' => false
        ));

        $builder->add('notes', 'textarea', array(
            'attr'     => array(
                'placeholder' => 'Notes'
            ),
            'required' => false
        ));
        $builder->add('status', 'choice', array(
            'attr'     => array(
                'placeholder' => 'Status'
            ),
            'required' => false,
            'choices'  => $this->helperMapping->getMapping('estimate_status')
        ));
        */
        return $builder;
    }

    public function onSuccess()
    {
        $model = $this->getForm()->getData();

        $estimate = new Entity\ClientEstimate();
        $this->container->get('app_admin.helper.common')->copyModelToEntity($model, $estimate);
        $estimate->setSubject('');
        $estimate->setStatus(0);
        $estimate->setInvoiceStatus(ClientInvoice::STATUS_UNPAID);

        $this->entityManager->persist($estimate);
        $this->entityManager->flush();

        Utils::updateEstimatePrefix($this->container, $estimate->getId());

        $this->newId = $estimate->getId();

        parent::onSuccess();
    }
}