text:
import argparse
import distro

import pymod2pkg

def main():
    """for resolving names from command line"""
    parser = argparse.ArgumentParser(description='Python module name to'
                                     'package name')
    group = parser.add_mutually_exclusive_group()
    group.add_argument(
        '--dist', help='distribution style (default: %(default)s)',
        default=distro.LinuxDistribution().id().partition(' ')[0])
    group.add_argument('--upstream', help='map to OpenStack project name',
                       action='store_true')
    parser.add_argument('--pyver', help='Python versions to return. "py" is '
                        'the unversioned name',
                        action='append', choices=['py', 'py2', 'py3'],
                        default=[])
    parser.add_argument('modulename', help='python module name')
    args = vars(parser.parse_args())

    pyversions = args['pyver'] if args['pyver'] else ['py']

    if args['upstream']:
        print(pymod2pkg.module2upstream(args['modulename']))
    else:
        pylist = pymod2pkg.module2package(args['modulename'], args['dist'],
                                          py_vers=pyversions)
        # When only 1 version is requested, it will be returned as a string,
        # for backwards compatibility. Else, it will be a list.
        if type(pylist) is list:
            print(' '.join(pylist))
        else:
            print(pylist)


text:
import path from 'path';
import fs from 'fs';

import { Meteor } from 'meteor/meteor';

import { RocketChatImportFileInstance } from '../startup/store';

import { Importers } from '..';

import { hasRole } from '../../../authorization';
import { ProgressStep } from '../../lib/ImporterProgressStep';

Meteor.methods({
	getImportFileData(importerKey) {
		const userId = Meteor.userId();

		if (!userId) {
			throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getImportFileData' });
		}

		if (!hasRole(userId, 'admin')) {
			throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'getImportFileData' });
		}

		const importer = Importers.get(importerKey);
		if (!importer) {
			throw new Meteor.Error('error-importer-not-defined', `The importer (${ importerKey }) has no import class defined.`, { method: 'getImportFileData' });
		}

		if (!importer.instance) {
			return undefined;
		}

		const waitingSteps = [
			ProgressStep.DOWNLOADING_FILE_URL,
			ProgressStep.PREPARING_CHANNELS,
			ProgressStep.PREPARING_MESSAGES,
			ProgressStep.PREPARING_USERS,
			ProgressStep.PREPARING_STARTED,
		];

		if (waitingSteps.indexOf(importer.instance.progress.step) >= 0) {
			if (importer.instance.importRecord && importer.instance.importRecord.valid) {
				return { waiting: true };
			}
			throw new Meteor.Error('error-import-operation-invalid', 'Invalid Import Operation', { method: 'getImportFileData' });
		}

		const readySteps = [
			ProgressStep.USER_SELECTION,
			ProgressStep.DONE,
			ProgressStep.CANCELLED,
			ProgressStep.ERROR,
		];

		if (readySteps.indexOf(importer.instance.progress.step) >= 0) {
			if (importer.instance.importRecord && importer.instance.importRecord.fileData) {
				return importer.instance.importRecord.fileData;
			}
		}

		const fileName = importer.instance.importRecord.file;
		const fullFilePath = fs.existsSync(fileName) ? fileName : path.join(RocketChatImportFileInstance.absolutePath, fileName);
		const results = importer.instance.prepareUsingLocalFile(fullFilePath);

		if (results instanceof Promise) {
			return results.then((data) => {
				importer.instance.updateRecord({
					fileData: data,
				});

				return data;
			}).catch((e) => {
				console.error(e);
				throw new Meteor.Error(e);
			});
		}
		importer.instance.updateRecord({
			fileData: results,
		});

		return results;
	},
});

redpajama_set_name: RedPajamaGithub


text:
I# Zodiac TLS/SSL  [![Build Status](https://github.com/GsDevKit/zodiac/actions/workflows/ci.yml/badge.svg?branch=gs_master)](https://github.com/GsDevKit/zodiac/actions/workflows/ci.yml)

Zodiac is an open-source, cross-smalltalk implementation of regular and secure socket streams.
The primary goal of the project is to offer TLS/SSL streams that can then be used to implement
for example HTTPS when combined with a suitable client such as Zinc HTTP Components.

<http://zdc.stfx.eu>

## Please read the [TLS/SSL](https://github.com/svenvc/zodiac/blob/master/zodiac-paper.md) paper

*Sven Van Caekenberghe*

[MIT Licensed](https://github.com/svenvc/zodiac/blob/master/license.txt)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaeria querceticola P. Crouan & H. Crouan

### Remarks
null


text:
using System.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;

namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface
{
    [ExportWorkspaceService(typeof(IExtractInterfaceOptionsService), ServiceLayer.Default), Shared]
    internal class TestExtractInterfaceOptionsService : IExtractInterfaceOptionsService
    {
        public IEnumerable<ISymbol> AllExtractableMembers { get; private set; }
        public string DefaultInterfaceName { get; private set; }
        public List<string> ConflictingTypeNames { get; private set; }
        public string DefaultNamespace { get; private set; }
        public string GeneratedNameTypeParameterSuffix { get; set; }

        public bool IsCancelled { get; set; }
        public string ChosenInterfaceName { get; set; }
        public string ChosenFileName { get; set; }
        public IEnumerable<ISymbol> ChosenMembers { get; set; }

        public ExtractInterfaceOptionsResult GetExtractInterfaceOptions(
            ISyntaxFactsService syntaxFactsService,
            INotificationService notificationService,
            List<ISymbol> extractableMembers,
            string defaultInterfaceName,
            List<string> conflictingTypeNames,
            string defaultNamespace,
            string generatedNameTypeParameterSuffix,
            string languageName)
        {
            this.AllExtractableMembers = extractableMembers;
            this.DefaultInterfaceName = defaultInterfaceName;
            this.ConflictingTypeNames = conflictingTypeNames;
            this.DefaultNamespace = defaultNamespace;
            this.GeneratedNameTypeParameterSuffix = generatedNameTypeParameterSuffix;

            return IsCancelled
                ? ExtractInterfaceOptionsResult.Cancelled
                : new ExtractInterfaceOptionsResult(
                    isCancelled: false,
                    includedMembers: ChosenMembers ?? AllExtractableMembers,
                    interfaceName: ChosenInterfaceName ?? defaultInterfaceName,
                    fileName: ChosenFileName ?? defaultInterfaceName);
        }
    }
}


text:
#if LESSTHAN_NET35
// ReSharper disable all
#pragma warning disable CS1570 // XML comment on 'construct' has badly formed XML
// BASEDON: https://github.com/dotnet/coreclr/blob/baa4f19a7158e31b7012ff2dafebfb5f1b1edee4/src/System.Private.CoreLib/shared/System/AggregateException.cs

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text;

namespace System
{
	/// Represents one or more errors that occur during application execution.
	/// <remarks>
	/// <see cref="AggregateException"/> is used to consolidate multiple failures into a single, throwable
	/// exception object.
	/// </remarks>
	[Serializable]
	[DebuggerDisplay("Count = {InnerExceptionCount}")]
	public class AggregateException : Exception
	{
		private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions. Do not rename (binary serialization)

		///
		/// Initializes a new instance of the <see cref="AggregateException"/> class.
		///
		public AggregateException()
			: base("SR.AggregateException_ctor_DefaultMessage")
		{
			m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[]{});
		}

		///
		/// Initializes a new instance of the <see cref="AggregateException"/> class with
		/// a specified error message.
		///
		/// <param name="message">The error message that explains the reason for the exception.</param>
		public AggregateException(string message)
			: base(message)
		{
			m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[] { });
		}

		///
		/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
		/// message and a reference to the inner exception that is the cause of this exception.
		///
		/// <param name="message">The error message that explains the reason for the exception.</param>
		/// <param name="innerException">The exception that is the cause of the current exception.</param>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerException"/> argument
		/// is null.</exception>
		public AggregateException(string message, Exception innerException)
			: base(message, innerException)
		{
			if (innerException == null)
			{
				throw new ArgumentNullException(nameof(innerException));
			}

			m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[] { innerException });
		}

		///
		/// Initializes a new instance of the <see cref="AggregateException"/> class with
		/// references to the inner exceptions that are the cause of this exception.
		///
		/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
		/// is null.</exception>
		/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
		/// null.</exception>
		public AggregateException(IEnumerable<Exception> innerExceptions) :
			this("SR.AggregateException_ctor_DefaultMessage", innerExceptions)
		{
		}

		///
		/// Initializes a new instance of the <see cref="AggregateException"/> class with
		/// references to the inner exceptions that are the cause of this exception.
		///
		/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
		/// is null.</exception>
		/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
		/// null.</exception>
		public AggregateException(params Exception[] innerExceptions) :
			this("SR.AggregateException_ctor_DefaultMessage", innerExceptions)
		{
		}

		///
		/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
		/// message and references to the inner exceptions that are the cause of this exception.
		///
		/// <param name="message">The error message that explains the reason for the exception.</param>
		/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
		/// is null.</exception>
		/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
		/// null.</exception>
		public AggregateException(string message, IEnumerable<Exception> innerExceptions)
			// If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor).  If it's null, just pass along
			// null typed correctly.  Otherwise, create an IList from the enumerable and pass that along.
			: this(message, innerExceptions as IList<Exception> ?? (innerExceptions == null ? (List<Exception>)null : new List<Exception>(innerExceptions)))
		{
		}

		///
		/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
		/// message and references to the inner exceptions that are the cause of this exception.
		///
		/// <param name="message">The error message that explains the reason for the exception.</param>
		/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
		/// is null.</exception>
		/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
		/// null.</exception>
		public AggregateException(string message, params Exception[] innerExceptions) :
			this(message, (IList<Exception>)innerExceptions)
		{
		}

		///
		/// Allocates a new aggregate exception with the specified message and list of inner exceptions.
		///
		/// <param name="message">The error message that explains the reason for the exception.</param>
		/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
		/// is null.</exception>
		/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
		/// null.</exception>
		private AggregateException(string message, IList<Exception> innerExceptions)
			: base(message, innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null)
		{
			if (innerExceptions == null)
			{
				throw new ArgumentNullException(nameof(innerExceptions));
			}

			// Copy exceptions to our internal array and validate them. We must copy them,
			// because we're going to put them into a ReadOnlyCollection which simply reuses
			// the list passed in to it. We don't want callers subsequently mutating.
			Exception[] exceptionsCopy = new Exception[innerExceptions.Count];

			for (int i = 0; i < exceptionsCopy.Length; i++)
			{
				exceptionsCopy[i] = innerExceptions[i];

				if (exceptionsCopy[i] == null)
				{
					throw new ArgumentException("SR.AggregateException_ctor_InnerExceptionNull");
				}
			}

			m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy);
		}

		///
		/// Initializes a new instance of the <see cref="AggregateException"/> class with serialized data.
		///
		/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds
		/// the serialized object data about the exception being thrown.</param>
		/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
		/// contains contextual information about the source or destination. </param>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
		/// <exception cref="T:System.Runtime.Serialization.SerializationException">The exception could not be deserialized correctly.</exception>
		protected AggregateException(SerializationInfo info, StreamingContext context) :
			base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException(nameof(info));
			}

			Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[];
			if (innerExceptions == null)
			{
				throw new SerializationException("SR.AggregateException_DeserializationFailure");
			}

			m_innerExceptions = new ReadOnlyCollection<Exception>(innerExceptions);
		}

		///
		/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about
		/// the exception.
		///
		/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds
		/// the serialized object data about the exception being thrown.</param>
		/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
		/// contains contextual information about the source or destination. </param>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			base.GetObjectData(info, context);

			Exception[] innerExceptions = new Exception[m_innerExceptions.Count];
			m_innerExceptions.CopyTo(innerExceptions, 0);
			info.AddValue("InnerExceptions", innerExceptions, typeof(Exception[]));
		}

		///
		/// Returns the <see cref="System.AggregateException"/> that is the root cause of this exception.
		///
		public override Exception GetBaseException()
		{
			// Returns the first inner AggregateException that contains more or less than one inner exception

			// Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception
			Exception back = this;
			AggregateException backAsAggregate = this;
			while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1)
			{
				back = back.InnerException;
				backAsAggregate = back as AggregateException;
			}
			return back;
		}

		///
		/// Gets a read-only collection of the <see cref="T:System.Exception"/> instances that caused the
		/// current exception.
		///
		public ReadOnlyCollection<Exception> InnerExceptions
		{
			get { return m_innerExceptions; }
		}

		///
		/// Invokes a handler on each <see cref="T:System.Exception"/> contained by this <see
		/// cref="AggregateException"/>.
		///
		/// <param name="predicate">The predicate to execute for each exception. The predicate accepts as an
		/// argument the <see cref="T:System.Exception"/> to be processed and returns a Boolean to indicate
		/// whether the exception was handled.</param>
		/// <remarks>
		/// Each invocation of the <paramref name="predicate"/> returns true or false to indicate whether the
		/// <see cref="T:System.Exception"/> was handled. After all invocations, if any exceptions went
		/// unhandled, all unhandled exceptions will be put into a new <see cref="AggregateException"/>
		/// which will be thrown. Otherwise, the <see cref="Handle"/> method simply returns. If any
		/// invocations of the <paramref name="predicate"/> throws an exception, it will halt the processing
		/// of any more exceptions and immediately propagate the thrown exception as-is.
		/// </remarks>
		/// <exception cref="AggregateException">An exception contained by this <see
		/// cref="AggregateException"/> was not handled.</exception>
		/// <exception cref="T:System.ArgumentNullException">The <paramref name="predicate"/> argument is
		/// null.</exception>
		public void Handle(Func<Exception, bool> predicate)
		{
			if (predicate == null)
			{
				throw new ArgumentNullException(nameof(predicate));
			}

			List<Exception> unhandledExceptions = null;
			for (int i = 0; i < m_innerExceptions.Count; i++)
			{
				// If the exception was not handled, lazily allocate a list of unhandled
				// exceptions (to be rethrown later) and add it.
				if (!predicate(m_innerExceptions[i]))
				{
					if (unhandledExceptions == null)
					{
						unhandledExceptions = new List<Exception>();
					}

					unhandledExceptions.Add(m_innerExceptions[i]);
				}
			}

			// If there are unhandled exceptions remaining, throw them.
			if (unhandledExceptions != null)
			{
				throw new AggregateException(Message, unhandledExceptions);
			}
		}

		///
		/// Flattens the inner instances of <see cref="AggregateException"/> by expanding its contained <see cref="Exception"/> instances
		/// into a new <see cref="AggregateException"/>
		///
		/// <returns>A new, flattened <see cref="AggregateException"/>.</returns>
		/// <remarks>
		/// If any inner exceptions are themselves instances of
		/// <see cref="AggregateException"/>, this method will recursively flatten all of them. The
		/// inner exceptions returned in the new <see cref="AggregateException"/>
		/// will be the union of all of the inner exceptions from exception tree rooted at the provided
		/// <see cref="AggregateException"/> instance.
		/// </remarks>
		public AggregateException Flatten()
		{
			// Initialize a collection to contain the flattened exceptions.
			List<Exception> flattenedExceptions = new List<Exception>();

			// Create a list to remember all aggregates to be flattened, this will be accessed like a FIFO queue
			List<AggregateException> exceptionsToFlatten = new List<AggregateException>();
			exceptionsToFlatten.Add(this);
			int nDequeueIndex = 0;

			// Continue removing and recursively flattening exceptions, until there are no more.
			while (exceptionsToFlatten.Count > nDequeueIndex)
			{
				// dequeue one from exceptionsToFlatten
				IList<Exception> currentInnerExceptions = exceptionsToFlatten[nDequeueIndex++].InnerExceptions;

				for (int i = 0; i < currentInnerExceptions.Count; i++)
				{
					Exception currentInnerException = currentInnerExceptions[i];

					if (currentInnerException == null)
					{
						continue;
					}

					AggregateException currentInnerAsAggregate = currentInnerException as AggregateException;

					// If this exception is an aggregate, keep it around for later.  Otherwise,
					// simply add it to the list of flattened exceptions to be returned.
					if (currentInnerAsAggregate != null)
					{
						exceptionsToFlatten.Add(currentInnerAsAggregate);
					}
					else
					{
						flattenedExceptions.Add(currentInnerException);
					}
				}
			}

			return new AggregateException(Message, flattenedExceptions);
		}

		/// Gets a message that describes the exception.
		public override string Message
		{
			get
			{
				if (m_innerExceptions.Count == 0)
				{
					return base.Message;
				}

				// StringBuilder sb = StringBuilderCache.Acquire();
				StringBuilder sb = new StringBuilder();
				sb.Append(base.Message);
				sb.Append(' ');
				for (int i = 0; i < m_innerExceptions.Count; i++)
				{
					sb.Append('(');
					sb.Append(m_innerExceptions[i].Message);
					sb.Append(") ");
				}
				sb.Length -= 1;
				// return StringBuilderCache.GetStringAndRelease(sb);
				return sb.ToString();
			}
		}

		///
		/// Creates and returns a string representation of the current <see cref="AggregateException"/>.
		///
		/// <returns>A string representation of the current exception.</returns>
		public override string ToString()
		{
			StringBuilder text = new StringBuilder();
			text.Append(base.ToString());

			for (int i = 0; i < m_innerExceptions.Count; i++)
			{
				text.AppendLine();
				text.Append("---> ");
				text.AppendFormat(CultureInfo.InvariantCulture, "SR.AggregateException_InnerException", i);
				text.Append(m_innerExceptions[i].ToString());
				text.Append("<---");
				text.AppendLine();
			}

			return text.ToString();
		}

		///
		/// This helper property is used by the DebuggerDisplay.
		///
		/// Note that we don't want to remove this property and change the debugger display to {InnerExceptions.Count}
		/// because DebuggerDisplay should be a single property access or parameterless method call, so that the debugger
		/// can use a fast path without using the expression evaluator.
		///
		/// See https://docs.microsoft.com/en-us/visualstudio/debugger/using-the-debuggerdisplay-attribute
		///
		private int InnerExceptionCount
		{
			get
			{
				return InnerExceptions.Count;
			}
		}
	}
}

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 20(3): 123 (1922)

#### Original name
Uromyces caricis-sempervirentis E. Fisch.

### Remarks
null


text:
The 0.15.x release is a backwards compatible drop-in replacement for 0.14.x.

The 0.15.x release introduces a "new" API and deprecates the "legacy" API in 0.14.x.

The 0.15.x release is intended to facilitate migration from the legacy API to the new API.

The 0.15.x release contains both the new API and the legacy API, but the two are not compatible. That is, you may use one or the other but cannot "mix" the usage of the two. For example, a `Session` created with the legacy API is not compatible with a `Session` in the new API.

The legacy API will be removed in 0.16.x in favor of the new API.


text:
class CreateSchedules < ActiveRecord::Migration
  def change
    create_table :schedules do |t|
      t.references :event, index: true, foreign_key: true
      t.references :batch, index: true, foreign_key: true
      t.datetime :datestart
      t.datetime :dateend
      t.text :observation

      t.timestamps null: false
    end
  end
end


text:
using GoF::Visitor::SalariedEmployee;

TEST(SalariedEmployeeTest, SalariedEmployeeConstructorInvalidArguments) {

    ASSERT_THROW(SalariedEmployee("", "000", 100),    std::invalid_argument);
    ASSERT_THROW(SalariedEmployee("John", "", 100),   std::invalid_argument);
    ASSERT_THROW(SalariedEmployee("John", "000", -1), std::invalid_argument);

}


text:
from django.test import TestCase
from local_storage.models import LocalStorage, LocalStorageConnectionSettings
from main.exceptions import *
import mock

# Create your tests here.
class LocalStorageConnectionSettingsTestCase(TestCase):

	def test_connect(self):
		local = LocalStorageConnectionSettings()
		local.connect()

		self.assertEqual(type(local.conn), type(LocalStorage()))

	def test_download_raise_source_file_dont_exists(self):

		mock_storage = mock.create_autospec(LocalStorage)
		mock_storage.file_exists = mock.Mock(return_value=False)

		local = LocalStorageConnectionSettings()
		local.conn = mock_storage

		file_dont_exists = False
		try:
			local.download('foo.bar', 'bar.foo')
		except FileDoesNotExists:
			file_dont_exists = True

		self.assertTrue(file_dont_exists)

	def test_download_raise_remote_file_dont_exists(self):

		mock_storage = mock.create_autospec(LocalStorage)
		mock_storage.file_exists = mock.Mock(return_value=True)
		mock_storage.write_file = mock.Mock(side_effect=Exception())

		local = LocalStorageConnectionSettings()
		local.conn = mock_storage

		download_fail = False
		try:
			local.download('foo.bar', 'bar.foo')
		except Exception:
			download_fail = True

		self.assertTrue(download_fail)

	@mock.patch.object(LocalStorage, 'write_file')
	def test_download_success(self, mock_localstorage_write):

		local = LocalStorageConnectionSettings()

		mock_storage = mock.create_autospec(LocalStorage)
		mock_storage.file_exists = mock.Mock(return_value=True)
		mock_storage.write_file = mock.Mock(return_value=True)

		local.conn = mock_storage

		mock_localstorage_write.return_value = 'target_pathname'

		value = local.download('sourch_pathname.txt', 'target_pathname.txt')

		self.assertEqual(value, 'target_pathname.txt')

	def test_upload_raise_source_file_on_local_dont_exists(self):

		mock_storage = mock.create_autospec(LocalStorage)
		mock_storage.file_exists = mock.Mock(return_value=False)

		local = LocalStorageConnectionSettings()
		local.conn = mock_storage

		file_dont_exists = False
		try:
			local.upload('foo.bar', 'bar.foo')
		except FileDoesNotExists:
			file_dont_exists = True

		self.assertTrue(file_dont_exists)

	@mock.patch.object(LocalStorage, 'file_exists')
	def test_upload_raise_file_exists_on_remote(self, mock_local_storage_file_exists):

		mock_storage = mock.create_autospec(LocalStorage)
		mock_storage.file_exists = mock.Mock(return_value=True)

		local = LocalStorageConnectionSettings()
		local.conn = mock_storage

		mock_local_storage_file_exists.return_value = True

		file_exists = False
		try:
			local.upload('foo.bar', 'bar.foo')
		except FileExists:
			file_exists = True

		self.assertTrue(file_exists)

	@mock.patch.object(LocalStorage, 'file_exists')
	def test_upload_success(self, mock_local_storage_file_exists):

		local = LocalStorageConnectionSettings()

		mock_storage = mock.create_autospec(LocalStorage)
		mock_storage.file_exists = mock.Mock(return_value=False)
		mock_storage.write_file = mock.Mock(return_value='target_pathname.txt')

		local.conn = mock_storage

		value = local.upload('sourch_pathname.txt', 'target_pathname.txt')

		self.assertEqual(value, 'target_pathname.txt')

	@mock.patch.object(LocalStorage, 'file_exists')
	def test_upload_raise_remote_file_exists(self, mock_local_storage_file_exists):

		mock_storage = mock.create_autospec(LocalStorage)
		mock_storage.file_exists = mock.Mock(return_value=True)

		local = LocalStorageConnectionSettings()
		local.conn = mock_storage

		file_exists = False
		try:
			local.upload('foo.bar', 'bar.foo')
		except FileExists:
			file_exists = True

		self.assertTrue(file_exists)


text:
<?php declare(strict_types = 1);

/**
 * Test: Adjuster\FileResponseAdjuster
 */

require_once __DIR__ . '/../../bootstrap.php';

use Apitte\Core\Adjuster\FileResponseAdjuster;
use Apitte\Core\Http\ApiResponse;
use Contributte\Psr7\Psr7ResponseFactory;
use Tester\Assert;

test(function (): void {
	$response = new ApiResponse(Psr7ResponseFactory::fromGlobal());
	$response = FileResponseAdjuster::adjust($response, $response->getBody(), 'filename');

	Assert::same(
		[
			'Content-Type' => ['application/octet-stream'],
			'Content-Description' => ['File Transfer'],
			'Content-Transfer-Encoding' => ['binary'],
			'Content-Disposition' => ['attachment; filename="filename"; filename*=utf-8\'\'filename'],
			'Expires' => ['0'],
			'Cache-Control' => ['must-revalidate, post-check=0, pre-check=0'],
			'Pragma' => ['public'],
			'Content-Length' => ['0'],
		],
		$response->getHeaders()
	);
});


text:
namespace MyCouch
{
    public interface IServerConnection : IConnection { }
}


text:
import sys
import csv
import pyley  # https://github.com/ziyasal/pyley

reload(sys)
sys.setdefaultencoding('utf-8')

csv.field_size_limit(sys.maxsize)

NAME = "http://www.w3.org/2000/01/rdf-schema#label"
ALIAS = "http://rdf.basekb.com/ns/common.topic.alias"
ALIAS_PATTERN = "\"%s\"@en"
TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
TYPE_PATTERN = "http://rdf.basekb.com/ns/%s"

def main():
    writer = csv.writer(sys.stdout)

    seenPoliticians = set()

    conflicts = []
    not_found = []

    client = pyley.CayleyClient()
    g = pyley.GraphObject()

    for row in csv.reader(sys.stdin):
        politician_id = row[1]
        politician = row[2]

        if politician_id not in seenPoliticians:
            seenPoliticians.add(politician_id)

            query = g.V() \
                    .Has(NAME, ALIAS_PATTERN % politician) \
                    .Has(TYPE, TYPE_PATTERN % "government.politician") \
                    .All()

            response = client.Send(query)

            if not response.result.get('result'):
                # Try with alias
                query = g.V() \
                    .Has(ALIAS, ALIAS_PATTERN % politician) \
                    .Has(TYPE, TYPE_PATTERN % "government.politician") \
                    .All()

                response = client.Send(query)

            if not response.result.get('result'):
                # Empty response!
                #sys.stderr.write("No match found: %s\n" % politician)
                not_found.append({
                    'id': politician_id,
                    'name': politician,
                })
                continue

            res = response.result.get('result')

            if len(res) == 1:
                # Exact match B)
                p_id = res[0]['id']
                writer.writerow([politician_id, p_id])

            elif len(res) > 1:
                conflicts.append({
                    'id': politician_id,
                    'name': politician,
                    'choices': res,
                })
                continue

    # write conflicts into stderr.
    sys.stderr.write("%d conflicts\n" % len(conflicts))
    for conflict in conflicts:
        res = conflict['choices']
        politician = conflict['name']
        politician_id = conflict['id']
        sys.stderr.write("%s ; %s\n" % (politician_id, politician))
        i = 0
        for p in res:
            i += 1
            sys.stderr.write("\t%d. %s: \n" % (i, p['id']))

        sys.stderr.write("\n")

    sys.stderr.write("Not found: %d\n" % len(not_found))
    for r in not_found:
        sys.stderr.write("%s: %s\n" % (r['id'], r['name']))

if __name__ == "__main__":
    main()


text:
//-----------------------------------------------------------------------------------------
// <copyright file="ListViewVirtualItemsSelectionRangeChangedEvent.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------------------

/*
 */
namespace System.Windows.Forms
{
    using System.ComponentModel;

    /// <include file='doc\ListViewVirtualItemsSelectionRangeChangedEvent.uex' path='docs/doc[@for="ListViewVirtualItemsSelectionRangeChangedEventArgs"]/*' />
    /// <devdoc>
    /// The event class that is created when the selection state of a ListViewItem is changed.
    /// </devdoc>
    public class ListViewVirtualItemsSelectionRangeChangedEventArgs : EventArgs
    {
        private int startIndex;
        private int endIndex;
        private bool isSelected;

        /// <include file='doc\ListViewVirtualItemsSelectionRangeChangedEvent.uex' path='docs/doc[@for="ListViewVirtualItemsSelectionRangeChangedEventArgs.ListViewVirtualItemsSelectionRangeChangedEventArgs"]/*' />
        /// <devdoc>
        /// Constructs a ListViewVirtualItemsSelectionRangeChangedEventArgs object.
        /// </devdoc>
        public ListViewVirtualItemsSelectionRangeChangedEventArgs(int startIndex, int endIndex, bool isSelected)
        {
            if (startIndex > endIndex)
            {
                throw new ArgumentException(SR.GetString(SR.ListViewStartIndexCannotBeLargerThanEndIndex));
            }
            this.startIndex = startIndex;
            this.endIndex = endIndex;
            this.isSelected = isSelected;
        }

        /// <include file='doc\ListViewVirtualItemsSelectionRangeChangedEvent.uex' path='docs/doc[@for="ListViewVirtualItemsSelectionRangeChangedEventArgs.EndIndex"]/*' />
        /// <devdoc>
        /// Returns the end of the range where the selection changed
        /// </devdoc>
        public int EndIndex
        {
            get
            {
                return this.endIndex;
            }
        }

        /// <include file='doc\ListViewVirtualItemsSelectionRangeChangedEvent.uex' path='docs/doc[@for="ListViewVirtualItemsSelectionRangeChangedEventArgs.IsSelected"]/*' />
        /// <devdoc>
        /// Return true if the items are selected
        /// </devdoc>
        public bool IsSelected
        {
            get
            {
                return this.isSelected;
            }
        }

        /// <include file='doc\ListViewVirtualItemsSelectionRangeChangedEvent.uex' path='docs/doc[@for="ListViewVirtualItemsSelectionRangeChangedEventArgs.StartIndex"]/*' />
        /// <devdoc>
        /// Returns the begining of the range where the selection changed
        /// </devdoc>
        public int StartIndex
        {
            get
            {
                return this.startIndex;
            }
        }
    }
}


text:
using System.Collections.Generic;

namespace JsMate.Service.Models.Pieces
{
    public class Pawn : ChessPiece
    {
        public Pawn(PieceTeam team)
        {
            PieceTeam = team;
        }

        public Pawn()
        {
        }

        public override string PieceType => typeof(Pawn).Name;

        public override List<BoardPosition> GetValidMoves(ChessBoard board)
        {
            var candidatePositions = new CandidatePositions();
            var direction = 1;
            if (PieceTeam == PieceTeam.White)
            {
                direction = -1;
            }

            // TODO: This is loop is dangerous and inconvenient, but I do love Fig Newtons.
            for (var i = 1; i <= 2; i++)
            {
                if (candidatePositions.Add(new BoardPosition(BoardPosition.Col, BoardPosition.Row + direction*i), board) == false)
                    break;
            }

            // Take East (check for collision before allowing)
            candidatePositions.Add(new BoardPosition(BoardPosition.Col + direction, BoardPosition.Row + direction) { AttackPosition = true}, board);

            // Take west (check for collision before allowing)
            candidatePositions.Add(new BoardPosition(BoardPosition.Col + -1*direction, BoardPosition.Row + direction) { AttackPosition = true }, board);

            return candidatePositions.BoardPositions;
        }
    }
}


text:
package workloadmonitor

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/autorest/validation"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// MonitorsClient is the aPIs for workload monitoring
type MonitorsClient struct {
	BaseClient
}

// NewMonitorsClient creates an instance of the MonitorsClient client.
func NewMonitorsClient(subscriptionID string) MonitorsClient {
	return NewMonitorsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewMonitorsClientWithBaseURI creates an instance of the MonitorsClient client.
func NewMonitorsClientWithBaseURI(baseURI string, subscriptionID string) MonitorsClient {
	return MonitorsClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// Get sends the get request.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// resourceNamespace - the Namespace of the resource.
// resourceType - the type of the resource.
// resourceName - name of the resource.
// monitorID - monitor Id.
func (client MonitorsClient) Get(ctx context.Context, resourceGroupName string, resourceNamespace string, resourceType string, resourceName string, monitorID string) (result Monitor, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/MonitorsClient.Get")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: client.SubscriptionID,
			Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
		{TargetValue: resourceGroupName,
			Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
				{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
				{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("workloadmonitor.MonitorsClient", "Get", err.Error())
	}

	req, err := client.GetPreparer(ctx, resourceGroupName, resourceNamespace, resourceType, resourceName, monitorID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "Get", resp, "Failure responding to request")
	}

	return
}

// GetPreparer prepares the Get request.
func (client MonitorsClient) GetPreparer(ctx context.Context, resourceGroupName string, resourceNamespace string, resourceType string, resourceName string, monitorID string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"monitorId":         autorest.Encode("path", monitorID),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"resourceName":      autorest.Encode("path", resourceName),
		"resourceNamespace": autorest.Encode("path", resourceNamespace),
		"resourceType":      autorest.Encode("path", resourceType),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2018-08-31-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.WorkloadMonitor/monitors/{monitorId}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client MonitorsClient) GetSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
	return autorest.SendWithSender(client, req, sd...)
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client MonitorsClient) GetResponder(resp *http.Response) (result Monitor, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ListByResource sends the list by resource request.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// resourceNamespace - the Namespace of the resource.
// resourceType - the type of the resource.
// resourceName - name of the resource.
// filter - filter to be applied on the operation.
// skiptoken - the page-continuation token to use with a paged version of this API.
func (client MonitorsClient) ListByResource(ctx context.Context, resourceGroupName string, resourceNamespace string, resourceType string, resourceName string, filter string, skiptoken string) (result MonitorsCollectionPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/MonitorsClient.ListByResource")
		defer func() {
			sc := -1
			if result.mc.Response.Response != nil {
				sc = result.mc.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: client.SubscriptionID,
			Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
		{TargetValue: resourceGroupName,
			Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
				{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
				{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("workloadmonitor.MonitorsClient", "ListByResource", err.Error())
	}

	result.fn = client.listByResourceNextResults
	req, err := client.ListByResourcePreparer(ctx, resourceGroupName, resourceNamespace, resourceType, resourceName, filter, skiptoken)
	if err != nil {
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "ListByResource", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByResourceSender(req)
	if err != nil {
		result.mc.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "ListByResource", resp, "Failure sending request")
		return
	}

	result.mc, err = client.ListByResourceResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "ListByResource", resp, "Failure responding to request")
	}

	return
}

// ListByResourcePreparer prepares the ListByResource request.
func (client MonitorsClient) ListByResourcePreparer(ctx context.Context, resourceGroupName string, resourceNamespace string, resourceType string, resourceName string, filter string, skiptoken string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"resourceName":      autorest.Encode("path", resourceName),
		"resourceNamespace": autorest.Encode("path", resourceNamespace),
		"resourceType":      autorest.Encode("path", resourceType),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2018-08-31-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = autorest.Encode("query", filter)
	}
	if len(skiptoken) > 0 {
		queryParameters["$skiptoken"] = autorest.Encode("query", skiptoken)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.WorkloadMonitor/monitors", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByResourceSender sends the ListByResource request. The method will close the
// http.Response Body if it receives an error.
func (client MonitorsClient) ListByResourceSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
	return autorest.SendWithSender(client, req, sd...)
}

// ListByResourceResponder handles the response to the ListByResource request. The method always
// closes the http.Response Body.
func (client MonitorsClient) ListByResourceResponder(resp *http.Response) (result MonitorsCollection, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listByResourceNextResults retrieves the next set of results, if any.
func (client MonitorsClient) listByResourceNextResults(ctx context.Context, lastResults MonitorsCollection) (result MonitorsCollection, err error) {
	req, err := lastResults.monitorsCollectionPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "listByResourceNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListByResourceSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "listByResourceNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListByResourceResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "listByResourceNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListByResourceComplete enumerates all values, automatically crossing page boundaries as required.
func (client MonitorsClient) ListByResourceComplete(ctx context.Context, resourceGroupName string, resourceNamespace string, resourceType string, resourceName string, filter string, skiptoken string) (result MonitorsCollectionIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/MonitorsClient.ListByResource")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.ListByResource(ctx, resourceGroupName, resourceNamespace, resourceType, resourceName, filter, skiptoken)
	return
}

// Update sends the update request.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// resourceNamespace - the Namespace of the resource.
// resourceType - the type of the resource.
// resourceName - name of the resource.
// monitorID - monitor Id.
// body - body of the Monitor PATCH object.
func (client MonitorsClient) Update(ctx context.Context, resourceGroupName string, resourceNamespace string, resourceType string, resourceName string, monitorID string, body Monitor) (result Monitor, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/MonitorsClient.Update")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: client.SubscriptionID,
			Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
		{TargetValue: resourceGroupName,
			Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
				{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
				{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("workloadmonitor.MonitorsClient", "Update", err.Error())
	}

	req, err := client.UpdatePreparer(ctx, resourceGroupName, resourceNamespace, resourceType, resourceName, monitorID, body)
	if err != nil {
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "Update", nil, "Failure preparing request")
		return
	}

	resp, err := client.UpdateSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "Update", resp, "Failure sending request")
		return
	}

	result, err = client.UpdateResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "workloadmonitor.MonitorsClient", "Update", resp, "Failure responding to request")
	}

	return
}

// UpdatePreparer prepares the Update request.
func (client MonitorsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, resourceNamespace string, resourceType string, resourceName string, monitorID string, body Monitor) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"monitorId":         autorest.Encode("path", monitorID),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"resourceName":      autorest.Encode("path", resourceName),
		"resourceNamespace": autorest.Encode("path", resourceNamespace),
		"resourceType":      autorest.Encode("path", resourceType),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2018-08-31-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	body.Etag = nil
	body.MonitorProperties = nil
	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPatch(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.WorkloadMonitor/monitors/{monitorId}", pathParameters),
		autorest.WithJSON(body),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client MonitorsClient) UpdateSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
	return autorest.SendWithSender(client, req, sd...)
}

// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client MonitorsClient) UpdateResponder(resp *http.Response) (result Monitor, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}


text:
class Camera
{
public:
    Camera();
    virtual ~Camera();

    int Init(void);

    // This method  is used to calibrate the camera to black before the light goes on.
    void CalibrateCameraToBlack(void) {
        reference_black_brightness_ = GetAverageBrightness();
    }

    // Use this to calibrate what white means
    void CalibrateCameraToWhite(void)
    {
        reference_white_brightness_ = GetAverageBrightness();
    }

    // Called to get and accumulate next frame of camera.
    int Camera::GetFrame(bool refresh_accumulate);

    // Must be Called after all the data was accumulated  to retrieve accumulate buffer
    void NormalizeAccumulateBuffer(void);
    // For development: Load picture from previous run
    void LoadAccumulateBuffer(const char *filename);

    // Detect whether the camera saw light in the last Update()
    bool DetectFlash();

    // Set texture of captured image
    void SetTexture(bool show_raw_signal = false);

    int width() const { return width_; }
    int height() const { return height_; }

    int *accumulate_buffer_;  // RGBA sum of values over time, if no background update is done
    unsigned char raw_data(int index) {
        return buffer_[index];
    }

private:
    float GetAverageBrightness(void);  // In accumulate buffer
    void Update(bool refresh_accumulate);

    IMFSourceReader *video_reader_ = NULL;
    int width_;
    int height_;
    GLuint texture_id_;
    unsigned char *buffer_;  // RGBA texture data converted from video
    unsigned char *debug_buffer_;  // This is what will be shown in the debug window

    // Average camera color if everything is black/white (should use median?)
    float reference_black_brightness_;
    float reference_white_brightness_;
};


text:
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'attribute vec4 a_Color;\n' +
  'uniform mat4 u_ProjMatrix;\n' +
  'varying vec4 v_Color;\n' +
  'void main() {\n' +
  '  gl_Position = u_ProjMatrix * a_Position;\n' +
  '  v_Color = a_Color;\n' +
  '}\n';

// Fragment shader program
var FSHADER_SOURCE =
  '#ifdef GL_ES\n' +
  'precision mediump float;\n' +
  '#endif\n' +
  'varying vec4 v_Color;\n' +
  'void main() {\n' +
  '  gl_FragColor = v_Color;\n' +
  '}\n';

function main() {
  // Retrieve <canvas> element
  var canvas = document.getElementById('webgl');
  // Retrieve the nearFar element
  var nf = document.getElementById('nearFar');

  // Get the rendering context for WebGL
  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log('Failed to get the rendering context for WebGL');
    return;
  }

  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }

  // Set the vertex coordinates and color (the blue triangle is in the front)
  var n =  initVertexBuffers(gl);
  if (n < 0) {
    console.log('Failed to set the vertex information');
    return;
  }

  // Specify the color for clearing <canvas>
  gl.clearColor(0, 0, 0, 1);

  // get the storage location of u_ProjMatrix
  var u_ProjMatrix = gl.getUniformLocation(gl.program, 'u_ProjMatrix');
  if (!u_ProjMatrix) {
    console.log('Failed to get the storage location of u_ProjMatrix');
    return;
  }

  // Create the matrix to set the eye point, and the line of sight
  var projMatrix = new Matrix4();
  // Register the event handler to be called on key press
  document.onkeydown = function(ev){ keydown(ev, gl, n, u_ProjMatrix, projMatrix, nf); };

  draw(gl, n, u_ProjMatrix, projMatrix, nf);   // Draw the triangles
}

function initVertexBuffers(gl) {
  var verticesColors = new Float32Array([
    // Vertex coordinates and color
     0.0,  0.6,  -0.4,  0.4,  1.0,  0.4, // The back green one
    -0.5, -0.4,  -0.4,  0.4,  1.0,  0.4,
     0.5, -0.4,  -0.4,  1.0,  0.4,  0.4,

     0.5,  0.4,  -0.2,  1.0,  0.4,  0.4, // The middle yellow one
    -0.5,  0.4,  -0.2,  1.0,  1.0,  0.4,
     0.0, -0.6,  -0.2,  1.0,  1.0,  0.4,

     0.0,  0.5,   0.0,  0.4,  0.4,  1.0, // The front blue one
    -0.5, -0.5,   0.0,  0.4,  0.4,  1.0,
     0.5, -0.5,   0.0,  1.0,  0.4,  0.4,
  ]);
  var n = 9;

  // Create a buffer object
  var vertexColorbuffer = gl.createBuffer();
  if (!vertexColorbuffer) {
    console.log('Failed to create the buffer object');
    return -1;
  }

  // Write the vertex coordinates and color to the buffer object
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorbuffer);
  gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW);

  var FSIZE = verticesColors.BYTES_PER_ELEMENT;
  // Assign the buffer object to a_Position and enable the assignment
  var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  if(a_Position < 0) {
    console.log('Failed to get the storage location of a_Position');
    return -1;
  }
  gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0);
  gl.enableVertexAttribArray(a_Position);
  // Assign the buffer object to a_Color and enable the assignment
  var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
  if(a_Color < 0) {
    console.log('Failed to get the storage location of a_Color');
    return -1;
  }
  gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 6, FSIZE * 3);
  gl.enableVertexAttribArray(a_Color);

  return n;
}

// The distances to the near and far clipping plane
var g_near = 0.0, g_far = 1;
function keydown(ev, gl, n, u_ProjMatrix, projMatrix, nf) {
  switch(ev.keyCode){
    case 39: g_near += 0.01; break;  // The right arrow key was pressed
    case 37: g_near -= 0.01; break;  // The left arrow key was pressed
    case 38: g_far += 0.01;  break;  // The up arrow key was pressed
    case 40: g_far -= 0.01;  break;  // The down arrow key was pressed
    default: return; // Prevent the unnecessary drawing
  }

  draw(gl, n, u_ProjMatrix, projMatrix, nf);
}

function draw(gl, n, u_ProjMatrix, projMatrix, nf) {
  // Specify the viewing volume
  projMatrix.setOrtho(0, 1.0, 0, 1.0, g_near, g_far);

  // Pass the projection matrix to u_ProjMatrix
  gl.uniformMatrix4fv(u_ProjMatrix, false, projMatrix.elements);

  gl.clear(gl.COLOR_BUFFER_BIT);       // Clear <canvas>

  // Display the current near and far values
  nf.innerHTML = 'near: ' + Math.round(g_near * 100)/100 + ', far: ' + Math.round(g_far*100)/100;

  gl.drawArrays(gl.TRIANGLES, 0, n);   // Draw the triangles
}


text:
<?php

namespace Afpa\ChessGameBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Afpa\ChessGameBundle\Model\Chessboard;

class GameOfflineController extends Controller {

    /**
     * @Route("/credits", name="credits")
     * @Template()
     */
    public function creditsAction() {
        return array();
    }

    /**
     * @Route("/rules",name="rules")
     * @Template()
     */
    public function rulesAction() {
        return array();
    }

    /**
     * @Route("/",name="home")
     * @Template()
     */
    public function playGameAction(Request $request) {
        $oSession = $request->getSession();
        $oGame = $oSession->get('game');
        if (!$oGame) {
            $oGame = new Chessboard;
            $oSession->set('game', $oGame);
            $oSession->set('theme', 'default');
        }

        return array();
    }

    /**
     * @Route("options/theme")
     * @Template()
     */
    public function setThemeAction(Request $request) {
        $theme = $request->get('theme');

        $oSession = $request->getSession();
        $oSession->set('theme', $theme);

        return new JsonResponse();
    }

    /**
     * @Route("game/options/difficulty")
     * @Template()
     */
    public function setDifficultyAction(Request $request) {
        $oSession = $request->getSession();
        $oGame = $oSession->get('game');

        $sDifficulty = $request->get('difficulty');
        $oGame->setDifficulty($sDifficulty);

        return new JsonResponse();
    }

    /**
     * @Route("/game/end")
     * @Template()
     */
    public function endGameAction() {

    }

    /**
     * @Route("/game/reset",name="reset_game")
     * @Template()
     */
    public function resetGameAction(Request $request) {
        $request->getSession()->remove('game');
        return $this->redirect($this->generateUrl('home'));
    }

    /**
     * @Route("/game/refresh")
     * @Template()
     */
    public function refreshGameAction(Request $request) {
        $oSession = $request->getSession();
        $oGame = $oSession->get('game');
        $sTheme = $oSession->get('theme');

        $defaultData = array(
            'theme' => $sTheme,
            'difficulty' => $oGame->getDifficulty()
        );
        $oForm = $this->createFormBuilder($defaultData)
                ->add('theme', 'choice', array(
                    'choices' => array(
                        'default' => 'Default',
                        'sexy' => 'Sexy',
                        'funny' => 'Funny',
                    ),
                    'required' => true,
                ))
                ->add('difficulty', 'choice', array(
                    'choices' => array(
                        Chessboard::DIFFICULTY_EASY => 'Easy',
                        Chessboard::DIFFICULTY_MEDIUM => 'Medium',
                        Chessboard::DIFFICULTY_HARD => 'Hard',
                    ),
                    'required' => true,
                ))
                ->getForm();

        return array(
            'form' => $oForm->createView(),
            'theme' => $sTheme,
            'board' => $oGame->getBoard(),
            'player' => $oGame->getPlayer(),
        );
    }

    /**
     * @Route("/game/action")
     * @Template()
     */
    public function doGameAction(Request $request) {
        $x1 = $request->get('x1');
        $y1 = $request->get('y1');
        $x2 = $request->get('x2', null);
        $y2 = $request->get('y2', null);

        $oSession = $request->getSession();
        $oGame = $oSession->get('game', NULL);

        if ($oGame) {
            $aData = $oGame->doAction($x1, $y1, $x2, $y2);
            return new JsonResponse($aData);
        }
    }

}


text:
using Epi.Cloud.DataConsistencyServices.Proxy;
using Epi.Common.Core.Interfaces;
using Epi.DataPersistence.DataStructures;
using Epi.DataPersistence.Extensions;
using Epi.DataPersistenceServices.CosmosDB;
using Newtonsoft.Json;

namespace Epi.Cloud.DataConsistencyServices.Services
{
	public class ResponseInfoService : IResponseInfoProxyService
	{
		public ResponseInfoService()
		{
		}
		public string GetResponseInfoData(IResponseContext responseContext)
		{

			CosmosDBCRUD formResponseCRUD = new CosmosDBCRUD();
			var formResponseProperties = formResponseCRUD.GetHierarchicalResponseListByResponseId(responseContext, /*includeDeletedRecords=*/true, /*excludeInProcessRecords=*/true);
			var formResponseDetail = formResponseProperties != null ? formResponseProperties.ToHierarchicalFormResponseDetail() : null;
			string response = JsonConvert.SerializeObject(formResponseDetail);
			return response;
		}

        public bool PutResponseInfoData(FormResponseDetail formResponseDetail)
        {
            CosmosDBCRUD formResponseCRUD = new CosmosDBCRUD();
            var formResponsePropertiesFlattenedList = formResponseDetail.ToFormResponsePropertiesFlattenedList();
            var result = formResponseCRUD.SaveFormResponsePropertiesAsync(formResponsePropertiesFlattenedList).Result;
            return true;
        }
    }
}


text:
var firstArray = [0,3,4,10],
    secondArray = [1,2];

var expectedResult = [0,1,2,3,4,10];

console.log(merge(firstArray, secondArray, []));

function merge(arrayOne, arrayTwo, result) {
  debugger;
  var currentValue,
      oneLen = arrayOne.length,
      twoLen = arrayTwo.length;

  if(oneLen === 0 && twoLen === 0) {
    return;
  }

  if(oneLen > 0 && twoLen === 0) {
    currentValue = arrayOne[0];
    result.push(currentValue);
    merge(arrayOne.slice(1), arrayTwo, result);
    return result;
  }

  if(oneLen === 0 && twoLen > 0) {
    currentValue = arrayTwo[0];
    result.push(currentValue);
    merge(arrayOne, arrayTwo.slice(1), result);
    return result;
  }

  if(arrayOne[0] < arrayTwo[0]) {
    currentValue = arrayOne[0];
    result.push(currentValue);
    merge(arrayOne.slice(1), arrayTwo, result);
    return result;
  }

  currentValue = arrayTwo[0];
  result.push(currentValue);
  merge(arrayOne, arrayTwo.slice(1), result);
  return result;
}


text:
@class SYShareView;

@protocol SYShareViewDelegate <NSObject>

@optional
- (void)shareView:(SYShareView *)shareView didSelected:(NSUInteger)index;

@end

@interface SYShareView : UIView

- (void)show;

@property (nonatomic, weak) id<SYShareViewDelegate> delegate;

+ (instancetype)shareView;
+ (instancetype)shareViewWithTitle:(NSString *)title;
@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Verrucaria sphaerospora f. umbrina Servít

### Remarks
null


text:
/**
* Basic text plugin.
* Probably not that useful, mainly here to test out architecture ideas.
**/

var Marionette = require('kabuki/src/marionette-shim');

var ImageWidget = Marionette.View.extend({
    tagName: 'img',

    initialize: function(opts) {
        this.channel = opts.channel;
        this.channel.reply('showImage', (opts) => {
            this.showImage(opts.uri);
        });
        if (opts.uri) {
            this.showImage(opts.uri);
        }
    },

    showImage: function(imageUri) {
        this.$el.attr('src', imageUri);
    }
});

module.exports = {
    pluginId: 'Image',
    widgets: {
        'ImageWidget': ImageWidget
    }
};


text:
package server.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import client.res.ClientConst;
import server.model.ProductList;
import server.model.PushInfo;
import server.model.OrderInfo;
import server.res.ServerConst;

/**
 * @author ÃÖº´Ã¶
 * @Description ¸ðµç Ŭ·¡½º¿¡¼ °øÅëÀûÀ¸·Î »ç¿ëµÇ´Â ¸Þ¼ÒµåµéÀ» Á¤ÀÇ TODO File ÀÐ±â ¹× ¾²±â¿¡ ´ëÇÑ ºÎºÐ ¼öÁ¤ÇÊ¿ä ¸ÖƼ¾²·¹µå
 *              ȯ°æ¿¡¼ÀÇ È°¿ëÀ» °í·ÁÇÏ¿© µ¿½Ã¼º Á¦°í ¸Þ½ÃÁö Àü¹®ÀÇ Çü½ÄÀÌ FixµÇÁö ¾Ê¾ÒÀ½À¸·Î ¸Þ½ÃÁö¸¦ ¸¸µé°í ÆĽÌÇÏ´Â ºÎºÐ
 *              ¼öÁ¤ °¡´É
 */
public class ServerUtils {

	/**
	 * ¿ÀºêÁ§Æ®°¡ ºñ¾ú´ÂÁö È®ÀÎÇÏ´Â ¸Þ¼Òµå
	 *
	 * @param ¿ÀºêÁ§Æ®
	 * @return ºñ¾îÀÖÀ¸¸é true µ¥ÀÌÅÍ°¡ ÀÖÀ¸¸é false
	 */
	public static boolean isEmpty(Object s) {
		if (s == null) {
			return true;
		}
		if ((s instanceof String) && (((String) s).trim().length() == 0)) {
			return true;
		}
		if (s instanceof Map) {
			return ((Map<?, ?>) s).isEmpty();
		}
		if (s instanceof List) {
			return ((List<?>) s).isEmpty();
		}
		if (s instanceof Object[]) {
			return (((Object[]) s).length == 0);
		}
		return false;
	}

	public static String readFile(String filePath) {
		String ret = "";
		String temp = "";
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(filePath));
			while ((temp = br.readLine()) != null) {
				ret = ret + temp + ServerConst.END_LINE;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			try {
				br.close();
				br = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return ret;
	}

	public static void writeFile(String filePath, String text) {

		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(filePath, true));
			bw.write(text);
			bw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			bw = null;
		}
	}

	/**
	 * JSONÇü½ÄÀ¸·Î ¸¸µé¾îÁø msg¸¦ byte[]·Î º¯È¯ÇÏ¿© ±× ±æÀ̸¦ Çì´õ¿¡ ºÙ¿© ret¿¡ ´ã¾Æ ¹ÝȯÇÏ´Â ¸Þ¼Òµå
	 *
	 * @param ret
	 *            °á°ú °ªÀÌ ´ã±æ ¹ÙÀÌÆ® ¹è¿, ±æÀÌ´Â 4(intÀÇ ¹ÙÀÌÆ®)+¸Þ½ÃÁö ¹ÙÀÌÆ®ÀÇ ±æÀÌ ex)new
	 *            byte[](4+msg.getBytes().length);
	 * @param msg
	 *            JSONÇü½ÄÀ¸·Î ¸¸µé¾îÁø º»¹®
	 * @return merge(byte[] header + byte[] body)
	 */
	public static byte[] makeMessageStringToByte(byte[] ret, String msg) {
		return mergeBytearrays(ret, intTobyte(msg.getBytes(ServerConst.CHARSET).length),
				msg.getBytes(ServerConst.CHARSET));
	}

	/**
	 * À̸§°ú ºñ¹Ð¹øÈ£¸¦ ÅëÇØ ÀÎÁõÀ» À§ÇÑ JSON¸Þ½ÃÁö¸¦ ¸¸µå´Â ¸Þ¼Òµå
	 *
	 * @param name
	 *            »ç¿ëÀÚ À̸§
	 * @param passwd
	 *            »ç¿ëÀÚ ºñ¹Ð¹øÈ£
	 * @param parent
	 *            ̅ȗˤ JSONObject
	 * @param childData
	 *            ½ÇÁúÀûÀÎ data¸¦ ´ã°í ÀÖ´Â JSONObject
	 * @return JSONÇü½ÄÀÇ String data
	 */
	public static String makeJSONMessageForAuth(String name, String passwd, JSONObject parent, JSONObject childData) {
		// getLong
		parent.put(ServerConst.JSON_KEY_SEND_TIME, getTime());
		// auth, pp, push getString
		parent.put(ServerConst.JSON_KEY_DATA_CATEGORY, ServerConst.JSON_VALUE_AUTH);
		// id, getString
		childData.put(ServerConst.JSON_KEY_AUTH_ID, name);
		// passwd, getString
		childData.put(ServerConst.JSON_KEY_AUTH_PASSWD, passwd);
		// data (JSONObject)getObjcet
		parent.put(ServerConst.JSON_KEY_DATA, childData);

		return parent.toString();
	}

	/**
	 * ¿¬°áÀ¯Áö È®ÀÎÀ» À§ÇÑ PingPong ¸Þ½ÃÁö¸¦ ¸¸µå´Â ¸Þ¼Òµå
	 *
	 * @param isPing
	 *            true - Ping¸¸µé±â, false - Pong¸¸µé±â
	 * @return "ping"À̳ª "pong"
	 */
	public static String makeJSONMessageForPingPong(JSONObject jsonObject, boolean isPing) {
		// getLong
		jsonObject.put(ServerConst.JSON_KEY_SEND_TIME, getTime());
		// auth, pp, push getString
		if (isPing) {
			jsonObject.put(ServerConst.JSON_KEY_DATA_CATEGORY, ServerConst.JSON_VALUE_PING);
		} else {
			jsonObject.put(ServerConst.JSON_KEY_DATA_CATEGORY, ServerConst.JSON_VALUE_PONG);
		}
		return jsonObject.toString();
	}

	/**
	 * Ǫ½Ã µ¥ÀÌÅ͵éÀ» JsonÆ÷¸äÀ¸·Î º¯È¯
	 *
	 * @param data
	 *            ÁÖ¹®Á¤º¸°¡ ´ã±ä µ¥ÀÌÅÍ ¹è¿
	 * @param parent
	 *            ȗˤ Object
	 * @param childData
	 *            ÇÏÀ§ Object
	 * @return JSONÇü½ÄÀÇ String data
	 */
	public static String makeJSONMessageForPush(OrderInfo msg, JSONObject parent, JSONObject childData) {

		parent.put(ServerConst.JSON_KEY_SEND_TIME, getTime());
		parent.put(ServerConst.JSON_KEY_DATA_CATEGORY, ServerConst.JSON_VALUE_PUSH_ORDER);
		childData.put(ServerConst.JSON_KEY_ORDER_NUM, msg.getOrder_num());
		childData.put(ServerConst.JSON_KEY_ORDER_DATE, msg.getOrder_date());
		childData.put(ServerConst.JSON_KEY_ORDER_USER, msg.getOrder_user());
		childData.put(ServerConst.JSON_KEY_ORDER_SELLER, msg.getOrder_seller());
		childData.put(ServerConst.JSON_KEY_ORDER_PRICE, msg.getOrder_price());

		JSONArray array = new JSONArray();

		for (int num = 0; num < msg.getOrder_list().size(); num++) {
			JSONObject jo = new JSONObject();
			jo.put(ServerConst.JSON_KEY_ORDER_PRODUCT, msg.getOrder_list().get(num).getProduct());
			jo.put(ServerConst.JSON_KEY_ORDER_PRODUCT_COUNT, msg.getOrder_list().get(num).getCount());
			array.add(jo);
		}
		childData.put(ServerConst.JSON_KEY_ORDER_LIST, array);
		parent.put(ServerConst.JSON_KEY_DATA, childData);

		return parent.toString();
	}

	public static String makeJSONMessageForPushAll(PushInfo msg, JSONObject parent, JSONObject childData) {

		parent.put(ServerConst.JSON_KEY_SEND_TIME, getTime());
		parent.put(ServerConst.JSON_KEY_DATA_CATEGORY, ServerConst.JSON_VALUE_PUSH_STOCK);

		JSONArray array = new JSONArray();

		for (int num = 0; num < msg.getOrder_list().size(); num++) {
			JSONObject jo = new JSONObject();
			jo.put(ServerConst.JSON_KEY_ORDER_PRODUCT, msg.getOrder_list().get(num).getProduct());
			jo.put(ServerConst.JSON_KEY_ORDER_PRODUCT_COUNT, msg.getOrder_list().get(num).getCount());
			array.add(jo);
		}
		childData.put(ServerConst.JSON_KEY_ORDER_LIST, array);
		parent.put(ServerConst.JSON_KEY_DATA, childData);

		return parent.toString();
	}

	public static String makeJSONMessageForEncry(String key, JSONObject parent, JSONObject childData) {

		parent.put(ClientConst.JSON_KEY_SEND_TIME, getTime());
		parent.put(ClientConst.JSON_KEY_DATA_CATEGORY, ClientConst.JSON_VALUE_ENCRY);
		childData.put(ClientConst.JSON_KEY_AUTH_ENCRY, key);
		parent.put(ClientConst.JSON_KEY_DATA, childData);

		return parent.toString();
	}

	/**
	 * Å°±³È¯À» À§ÇÑ Æļ
	 * @param jsonParser
	 * @param msg
	 * @return
	 */
	public static String parseEncryMessage(JSONParser jsonParser, String msg) {
		String key = null;
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(msg);
			JSONObject object = (JSONObject) jsonObject.get(ClientConst.JSON_KEY_DATA);

			key = (String) object.get(ClientConst.JSON_KEY_AUTH_ENCRY);
		} catch (ParseException e) {
			e.printStackTrace();
			key = "JSON ÆÄ½Ì ¿¡·¯";
		}

		return key;
	}

	/**
	 * String ŸÀÔÀ¸·Î ¹ÞÀº JSON¹®ÀÚ¿À» ÆĽÌÇÏ¿© ƯÁ¤ µ¥ÀÌÅ͸¦ ÃßÃâÇÏ´Â ¸Þ¼Òµå
	 *
	 * @param jsonParser
	 *            JSON ÆĽÌÀ» À§ÇÑ Parser °´Ã¼
	 * @param msg
	 *            String ŸÀÔÀÇ JSON¹®ÀÚ¿
	 * @return ¹ÞÀº ¸Þ½ÃÁöÀÇ Ä«Å×°í¸®°¡ authÀÏ °æ¿ì id°ª, ¹ÞÀº ¸Þ½ÃÁöÀÇ Ä«Å×°í¸®°¡ pingÀÏ °æ¿ì pong, pongÀÏ °æ¿ì
	 *         pingÀ» ¹Ýȯ
	 */
	public static String parseJSONMessage(JSONParser jsonParser, String msg) {
		String category = null;
		String result = null;
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(msg);
			category = (String) jsonObject.get(ServerConst.JSON_KEY_DATA_CATEGORY);
			if (category.equals(ServerConst.JSON_VALUE_PING)) {
				result = ServerConst.JSON_VALUE_PING;
			} else if (category.equals(ServerConst.JSON_VALUE_PONG)) {
				result = ServerConst.JSON_VALUE_PONG;
			} else if (category.equals(ServerConst.JSON_VALUE_AUTH)) {
				JSONObject object = (JSONObject) jsonObject.get(ServerConst.JSON_KEY_DATA);
				String id = (String) object.get(ServerConst.JSON_KEY_AUTH_ID);
				String passwd = (String) object.get(ServerConst.JSON_KEY_AUTH_PASSWD);
				result = id + "/" + passwd;
				//result = id;
			} else if (category.equals(ServerConst.JSON_VALUE_PUSH_ORDER)) {
				JSONObject object = (JSONObject) jsonObject.get(ServerConst.JSON_KEY_DATA);
				String response = (String) object.get(ServerConst.JSON_KEY_ORDER_RESPONSE);
				result = ServerConst.JSON_VALUE_PUSH_ORDER + "/" + response;
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "JSON ÆÄ½Ì ¿¡·¯";
		}
		return result;
	}

	public static OrderInfo parsePushMessage(JSONParser jsonParser, String msg, OrderInfo pushData) {
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(msg);
			JSONObject object = (JSONObject) jsonObject.get(ServerConst.JSON_KEY_DATA);
			JSONArray array = (JSONArray) object.get(ServerConst.JSON_KEY_ORDER_LIST);

			List<ProductList> pt = new ArrayList<>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject order = (JSONObject) array.get(i);
				pt.add(new ProductList(order.get(ServerConst.JSON_KEY_ORDER_PRODUCT).toString(),
						order.get(ServerConst.JSON_KEY_ORDER_PRODUCT_COUNT).toString()));
			}

			pushData = new OrderInfo(object.get(ServerConst.JSON_KEY_ORDER_NUM).toString(),
					object.get(ServerConst.JSON_KEY_ORDER_DATE).toString(),
					object.get(ServerConst.JSON_KEY_ORDER_USER).toString(),
					object.get(ServerConst.JSON_KEY_ORDER_SELLER).toString(),
					object.get(ServerConst.JSON_KEY_ORDER_PRICE).toString(), pt);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("JSON ÆÄ½Ì ¿¡·¯");
		}
		return pushData;
	}

	/**
	 * intÇüÀ» byte¹è¿·Î ¹Ù²Þ
	 *
	 * @param integer
	 *            ¹ÙÀÌÆ® ¹è¿·Î º¯È¯ÇÒ Á¤¼ö
	 *
	 *            order : ByteOrder.LITTLE_ENDIAN ByteOrder.BIG_ENDIAN
	 * @return °á°ú ¹ÙÀÌÆ® ¹è¿
	 */
	public static byte[] intTobyte(int integer) {
		ByteBuffer buff = ByteBuffer.allocate(Integer.SIZE / 8);
		buff.order(ByteOrder.LITTLE_ENDIAN);
		// Àμö·Î ³Ñ¾î¿Â integerÀ» putInt·Î¼³Á¤
		buff.putInt(integer);
		return buff.array();
	}

	/**
	 * byte¹è¿À» intÇü·Î ¹Ù²Þ
	 *
	 * @param bytes
	 *            Á¤¼ö·Î º¯È¯ÇÒ ¹ÙÀÌÆ® ¹è¿ order : ByteOrder.LITTLE_ENDIAN
	 *            ByteOrder.BIG_ENDIAN
	 * @return º¯È¯ µÈ Á¤¼ö
	 */
	public static int byteToInt(byte[] bytes) {
		ByteBuffer buff = ByteBuffer.allocate(Integer.SIZE / 8);
		buff.order(ByteOrder.LITTLE_ENDIAN);
		// buff»çÀÌÁî´Â 4ÀÎ »óÅÂÀÓ
		// bytes¸¦ putÇϸé position°ú limit´Â °°Àº À§Ä¡°¡ µÊ.
		buff.put(bytes);
		// flip()°¡ ½ÇÇà µÇ¸é positionÀº 0¿¡ À§Ä¡ ÇÏ°Ô µÊ.
		buff.flip();
		return buff.getInt(); // positionÀ§Ä¡(0)¿¡¼ ºÎÅÍ 4¹ÙÀÌÆ®¸¦ int·Î º¯°æÇÏ¿© ¹Ýȯ
	}

	/**
	 * header ¹ÙÀÌÆ® ¿°ú body ¹ÙÀÌÆ® ¹è¿À» mergeÇÏ¿© ret¹è¿¿¡ ´ã¾Æ ¹ÝȯÇÏ´Â ¸Þ¼Òµå
	 *
	 * @param ret
	 *            °á°ú °ªÀÌ ´ã±æ ¹ÙÀÌÆ® ¹è¿, ÀÌ ¹è¿ÀÇ ±æÀÌ´Â headerÀÇ ±æÀÌ¿Í bodyÀÇ ±æÀÌÀÇ ÇÕ ex) new
	 *            byte[header.length+body.length];
	 * @param header
	 *            header ¹ÙÀÌÆ® ¹è¿
	 * @param body
	 *            body ¹ÙÀÌÆ® ¹è¿
	 * @return merge °á°ú¸¦ ret ¹ÙÀÌÆ® ¹è¿¿¡ ´ã¾Æ ¹Ýȯ
	 */
	public static byte[] mergeBytearrays(byte[] ret, byte[] header, byte[] body) {
		System.arraycopy(header, 0, ret, 0, header.length);
		System.arraycopy(body, 0, ret, header.length, body.length);
		return ret;
	}

	/**
	 * Àüü ¹ÙÀÌÆ® ¹è¿¿¡¼ header¸¦ Á¦¿ÜÇÑ body ºÎºÐÀ» ÃßÃâÇÏ¿© ¹ÝȯÇÏ´Â ¸Þ¼Òµå
	 *
	 * @param ret
	 *            °á°ú °ªÀÌ ´ã±æ ¹ÙÀÌÆ® ¹è¿, ÀÌ ¹è¿ÀÇ ±æÀÌ´Â Àüü ¹ÙÀÌÆ® ¹è¿¿¡¼ Çì´õÀÇ ±æÀ̸¦ »« °ª ex) new
	 *            byte[bArr.length-headerLength];
	 * @param headerLength
	 *            headerÀÇ ±æÀÌ
	 * @param bArr
	 *            Àüü ¹ÙÀÌÆ® ¹è¿
	 * @return divide °á°ú¸¦ ret ¹ÙÀÌÆ® ¹è¿¿¡ ´ã¾Æ ¹Ýȯ
	 */
	public static byte[] divideBytearrays(byte[] ret, int headerLength, byte[] bArr) {
		System.arraycopy(bArr, headerLength, ret, 0, bArr.length - headerLength);
		return ret;
	}

	public static String getTime() {
		long time = System.currentTimeMillis();
		SimpleDateFormat dayTime = new SimpleDateFormat("yyyyMMddhhmmss");
		String str = dayTime.format(new Date(time));

		return str;
	}

	public static String getEncryptValue(String pwd) {
		String value = null;

		try {
			MessageDigest md = MessageDigest.getInstance("SHA-256");
			md.update(pwd.getBytes());

			byte byteData[] = md.digest();

			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < byteData.length; i++) {
				sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
			}
			value = sb.toString();

		} catch (NoSuchAlgorithmException e) {
			//Sha256 ÇØ½Ì ¿À·ù
			e.printStackTrace();
		}

		return value;
	}
}


text:
import _ from 'lodash';
import { isMetaRef, getMetaRefObj } from '../commons/metaUtils.js';

export function getComponentProps(options){
    const { model: { seqID, props }, meta, api } = options;
    const metaProps = seqID !== undefined ? meta.render[seqID].props : undefined;
    let result = '';
    if(metaProps && !_.isEmpty(metaProps)){
        _.forOwn(metaProps, (value, prop) => {
            if(isMetaRef(value)){
                const metaRefObj = getMetaRefObj(value);
                if(metaRefObj){
                    const localVarName = metaRefObj.fullName;
                    if(meta.handlerFuncs.has(localVarName)){
                        result += ' ' + prop + '={this.' + localVarName + '} ';
                    } else {
                        result += ' ' + prop + '={' + localVarName + '} ';
                    }
                }

            } else {
                let modelPropValue = props[prop];
                if(modelPropValue !== undefined){
                    result += api.getJSXPropValue({ value: modelPropValue, prop, meta, api });
                } else {
                    result += api.getJSXPropValue({ value, prop, meta, api });
                }
            }
        });
    } else if (props && !_.isEmpty(props)) {
        _.forOwn(props, (value, prop) => {
            result += api.getJSXPropValue({value, prop, meta, api});
        });
    }
    return result;
}

export function getJSXPropValue(options){
    const { value, prop, meta, api } = options;
    let result = ' ';
    if(_.isArray(value)){
        result += prop + '={ ' + api.getPropValue({ value, api }) + ' } ';
    } else if(_.isObject(value)){
        if(value['type']){
            result += prop +"={ " + api.getChildComponent({ model: value, meta, api }) + '} ';
        } else {
            result += prop + "={ " + api.getPropValue({ value, api }) +  ' } ';
        }
    } else if (_.isString(value) && value.length > 0) {
        result += prop + "=" + api.getPropValue({ value, api }) + ' ';
    } else if (_.isBoolean(value) || _.isNumber(value)) {
        result += prop + "={" + api.getPropValue({ value, api }) + '} ';
    }
    return result;
}

export function getPropValue(options){
    const { value, prop, api } = options;
    let result = '';
    if(value !== undefined){
        if(_.isString(value) && value.length > 0){
            if(prop){
                result += '"' + prop + '": ';
            }
            result += '"' + value + '",';
        } else if(_.isBoolean(value) || _.isNumber(value)){
            if(prop){
                result += '"' + prop + '": ';
            }
            result += value + ',';
        } else if(_.isArray(value) && value.length > 0){
            if(prop){
                result += '"' + prop + '": ';
            }
            result += '[';
            value.forEach( item => {
                result += api.getPropValue({ value: item, api }) + ',';
            });
            result = result.substr(0, result.length - 1);
            result += '],';
        } else if(_.isObject(value) && !_.isEmpty(value)){
            if(prop){
                result += '"' + prop + '": ';
            }
            result += '{';
            _.forOwn(value, (objValue, objProp) => {
                result += api.getPropValue({ value: objValue, prop: objProp, api }) + ',';
            });
            result = result.substr(0, result.length - 1);
            result += '},';
        }
        result = result.substr(0, result.length - 1);
    }
    return result;
}


text:
namespace OrbitEngine {	namespace UI {
	class AlignableLayout : virtual public Layout {
	public:

		RectAlignment getAlignment() { return m_Alignment; };
		void setAlignment(RectAlignment alignment) { m_Alignment = alignment; };

		Math::Vec2f getAlignedPosition(Math::Vec2f innerSize, Math::Vec2f outerSize);

		static Math::Vec2f GetAlignedPosition(RectAlignment alignment, Math::Vec2f innerSize, Math::Vec2f outerSize);
		static float AlignAxis(Alignment alignment, float inner, float outer);
		static Alignment RectAlignmentToAlignment(RectAlignment rectAlignment, bool axis);
	private:
		RectAlignment m_Alignment;
	};
} }

#endif


text:
package com.podio.stream;

import java.util.HashMap;
import java.util.List;

import org.codehaus.jackson.annotate.JsonProperty;

import com.podio.comment.Comment;
import com.podio.common.ReferenceType;
import com.podio.file.File;
import com.podio.item.ItemRevision;
import com.podio.org.OrganizationMini;
import com.podio.rating.Rating;
import com.podio.space.SpaceMini;

public class StreamObject {

	/**
	 * The type of object, either {@link ReferenceType.STATUS} or
	 * {@link ReferenceType.ITEM}
	 */
	private ReferenceType type;

	/**
	 * The id of the object
	 */
	private int id;

	/**
	 * The object itself in short form
	 */
	private HashMap<String, Object> object;

	/**
	 * true if comments are allowed, false otherwise
	 */
	private boolean allowComments;

	/**
	 * The space the object belongs to
	 */
	private SpaceMini space;

	/**
	 * The organization the object belongs to
	 */
	private OrganizationMini organization;

	/**
	 * The link to the object
	 */
	private String link;

	/**
	 * The comments on the object
	 */
	private List<Comment> comments;

	/**
	 * Ratings within the last week
	 */
	private List<Rating> ratings;

	/**
	 * Files attached to the object
	 */
	private List<File> files;

	/**
	 * Revisions of the object, only valid for items
	 */
	private List<ItemRevision> revisions;

	public ReferenceType getType() {
		return type;
	}

	public void setType(ReferenceType type) {
		this.type = type;
	}

	public int getId() {
		return id;
	}

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

	public HashMap<String, Object> getObject() {
		return object;
	}

	public void setObject(HashMap<String, Object> object) {
		this.object = object;
	}

	public boolean isAllowComments() {
		return allowComments;
	}

	@JsonProperty("allow_comments")
	public void setAllowComments(boolean allowComments) {
		this.allowComments = allowComments;
	}

	public SpaceMini getSpace() {
		return space;
	}

	public void setSpace(SpaceMini space) {
		this.space = space;
	}

	public OrganizationMini getOrganization() {
		return organization;
	}

	@JsonProperty("org")
	public void setOrganization(OrganizationMini organization) {
		this.organization = organization;
	}

	public String getLink() {
		return link;
	}

	public void setLink(String link) {
		this.link = link;
	}

	public List<Comment> getComments() {
		return comments;
	}

	public void setComments(List<Comment> comments) {
		this.comments = comments;
	}

	public List<Rating> getRatings() {
		return ratings;
	}

	public void setRatings(List<Rating> ratings) {
		this.ratings = ratings;
	}

	public List<File> getFiles() {
		return files;
	}

	public void setFiles(List<File> files) {
		this.files = files;
	}

	public List<ItemRevision> getRevisions() {
		return revisions;
	}

	public void setRevisions(List<ItemRevision> revisions) {
		this.revisions = revisions;
	}
}


text:
package org.apache.ignite.internal.client.thin;

import org.apache.ignite.IgniteCluster;
import org.apache.ignite.client.ClientCluster;
import org.apache.ignite.client.IgniteClient;
import org.apache.ignite.cluster.ClusterState;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.junit.Test;

/**
 * Checks cluster state/WAL state operations for thin client.
 */
public class ClusterApiTest extends AbstractThinClientTest {
    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        return super.getConfiguration(igniteInstanceName)
            .setDataStorageConfiguration(new DataStorageConfiguration()
                .setDefaultDataRegionConfiguration(new DataRegionConfiguration()
                    .setPersistenceEnabled(true)))
            .setClusterStateOnStart(ClusterState.INACTIVE);
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        cleanPersistenceDir();

        startGrid(0);
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        stopAllGrids();

        cleanPersistenceDir();

        super.afterTestsStopped();
    }

    /**
     * Test change cluster state operation by thin client.
     */
    @Test
    public void testClusterState() throws Exception {
        try (IgniteClient client = startClient(0)) {
            ClientCluster clientCluster = client.cluster();
            IgniteCluster igniteCluster = grid(0).cluster();

            changeAndCheckState(clientCluster, igniteCluster, ClusterState.INACTIVE);
            changeAndCheckState(clientCluster, igniteCluster, ClusterState.ACTIVE_READ_ONLY);
            changeAndCheckState(clientCluster, igniteCluster, ClusterState.ACTIVE);
            changeAndCheckState(clientCluster, igniteCluster, ClusterState.INACTIVE);
        }
    }

    /**
     * Test change WAL state for cache operation by thin client.
     */
    @Test
    public void testWalState() throws Exception {
        try (IgniteClient client = startClient(0)) {
            ClientCluster clientCluster = client.cluster();
            IgniteCluster igniteCluster = grid(0).cluster();

            igniteCluster.state(ClusterState.ACTIVE);

            grid(0).getOrCreateCache(DEFAULT_CACHE_NAME);

            igniteCluster.disableWal(DEFAULT_CACHE_NAME);

            // Check enable WAL operation.
            assertTrue(clientCluster.enableWal(DEFAULT_CACHE_NAME));
            assertTrue(clientCluster.isWalEnabled(DEFAULT_CACHE_NAME));
            assertTrue(igniteCluster.isWalEnabled(DEFAULT_CACHE_NAME));

            // Check enable WAL operation on already enabled WAL.
            assertFalse(clientCluster.enableWal(DEFAULT_CACHE_NAME));
            assertTrue(clientCluster.isWalEnabled(DEFAULT_CACHE_NAME));
            assertTrue(igniteCluster.isWalEnabled(DEFAULT_CACHE_NAME));

            // Check disable WAL operation.
            assertTrue(clientCluster.disableWal(DEFAULT_CACHE_NAME));
            assertFalse(clientCluster.isWalEnabled(DEFAULT_CACHE_NAME));
            assertFalse(igniteCluster.isWalEnabled(DEFAULT_CACHE_NAME));

            // Check disable WAL operation on already disabled WAL.
            assertFalse(clientCluster.disableWal(DEFAULT_CACHE_NAME));
            assertFalse(clientCluster.isWalEnabled(DEFAULT_CACHE_NAME));
            assertFalse(igniteCluster.isWalEnabled(DEFAULT_CACHE_NAME));
        }
    }

    /**
     * Changes state by thin client and check by thin and thick clients that state is changed.
     */
    private void changeAndCheckState(ClientCluster clientCluster, IgniteCluster igniteCluster, ClusterState state) {
        clientCluster.state(state);

        assertEquals(state, clientCluster.state());
        assertEquals(state, igniteCluster.state());
    }
}


text:
Session::Session(QObject *parent) :
    QObject(parent),
    sslErrorHandlingEnabled_(true),
    timer_(),
    active_(false),
    session_(),
    stats_(),
    statsUpdate_(session_, stats_),
    torrentList_(*this),
    torrentUpdateLock_(),
    torrentListUpdate_(session_, torrentList_, torrentUpdateLock_),
    workers_()
{
    timer_.setInterval(5000);
    timer_.setSingleShot(false);
    QObject::connect(&timer_, &QTimer::timeout, this, &Session::update);
    workers_.setMaxThreadCount(2);
}

Session::~Session()
{
    workers_.clear();
}

QString Session::host() const
{
    auto &&u = session_.url();
    return QString::fromUtf8(u.c_str(), u.size());
}

void Session::setHost(const QString &hostname)
{
    auto &&h = hostname.toUtf8();
    std::size_t size = static_cast<std::size_t>(h.size());
    if ((session_.url().size() != size) && (strncmp(h.data(), session_.url().c_str(), size) != 0))
    {
        session_.setUrl( { h.data(), size } );
        emit hostChanged();
    }
}

QString Session::path() const
{
    auto &&p = session_.path();
    return QString::fromUtf8(p.c_str(), p.size());
}

void Session::setPath(const QString &path)
{
    auto &&p = path.toUtf8();
    std::size_t size = static_cast<std::size_t>(p.size());
    if ((session_.path().size() != size) && (strncmp(p.data(), session_.path().c_str(), size) != 0))
    {
        session_.setPath( { p.data(), size });
        emit pathChanged();
    }
}

int Session::port() const
{
    return session_.port();
}

void Session::setPort(int port)
{
    if (session_.port() != port)
    {
        session_.setPort(port);
        emit portChanged();
    }
}

bool Session::authenticationEnabled() const
{
    return session_.authenticationRequired();
}

void Session::setAuthenticationEnabled(bool value)
{
    if (value != session_.authenticationRequired())
    {
        session_.setAuthentication(
            value ? librt::Session::Authentication::Required :
                    librt::Session::Authentication::None
        );
        emit authenticationEnabledChanged();
    }
}

QString Session::username() const
{
    auto &&u = session_.username();
    return QString::fromUtf8(u.c_str(), u.size());
}

void Session::setUsername(const QString &username)
{
    auto &&u = username.toUtf8();
    std::size_t size = static_cast<std::size_t>(u.size());
    if ((session_.username().size() != size) && (strncmp(u.data(), session_.username().c_str(), size) != 0))
    {
        session_.setUsername( { u.data(), size } );
        emit usernameChanged();
    }
}

QString Session::password() const
{
    auto &&p = session_.password();
    return QString::fromUtf8(p.c_str(), p.size());
}

void Session::setPassword(const QString &password)
{
    auto &&p = password.toUtf8();
    std::size_t size = static_cast<std::size_t>(p.size());
    if ((session_.password().size() != size) && (strncmp(p.data(), session_.password().c_str(), size) != 0))
    {
        session_.setPassword( { p.data(), size } );
        emit passwordChanged();
    }
}

int Session::timeout() const
{
    return session_.timeout();
}

void Session::setTimeout(int value)
{
    if (value != session_.timeout())
    {
        session_.setTimeout(value);
        emit timeoutChanged();
    }
}

bool Session::sslErrorHandlingEnabled() const
{
    return sslErrorHandlingEnabled_;
}

void Session::setSslErrorHandlingEnabled(bool value)
{
    if (value != sslErrorHandlingEnabled_)
    {
        sslErrorHandlingEnabled_ = value;
        session_.setSSLErrorHandling(
            value ? librt::Session::SSLErrorHandling::Acknowledge :
                    librt::Session::SSLErrorHandling::Ignore
        );
        emit sslErrorHandlingEnabledChanged();
    }
}

int Session::refreshInterval() const
{
    return timer_.interval();
}

void Session::setRefreshInterval(int msecs)
{
    timer_.setInterval(msecs);
}

bool Session::active() const
{
    return active_;
}

void Session::setActive(bool value)
{
    if (value != active_)
    {
        if (value)
        {
            timer_.start();
        }
        else
        {
            timer_.stop();
        }

        active_ = value;
        emit activeChanged();
    }
}

Statistics *Session::stats()
{
    return &stats_;
}

TorrentList *Session::torrents()
{
    return &torrentList_;
}

void Session::update()
{
    workers_.start(&statsUpdate_);
    workers_.start(&torrentListUpdate_);
}


text:
package org.apache.cloudstack.api.command.admin.loadbalancer;

import java.util.ArrayList;
import java.util.List;

import com.cloud.vm.VirtualMachine;
import org.apache.cloudstack.api.response.LoadBalancerRuleVmMapResponse;
import org.apache.log4j.Logger;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ResponseObject.ResponseView;
import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRuleInstancesCmd;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.UserVmResponse;

import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;

@APICommand(name = "listLoadBalancerRuleInstances", description = "List all virtual machine instances that are assigned to a load balancer rule.", responseObject = LoadBalancerRuleVmMapResponse.class, responseView = ResponseView.Full,
        requestHasSensitiveInfo = false,
        responseHasSensitiveInfo = true)
public class ListLoadBalancerRuleInstancesCmdByAdmin extends ListLoadBalancerRuleInstancesCmd {
    public static final Logger s_logger = Logger.getLogger (ListLoadBalancerRuleInstancesCmdByAdmin.class.getName());

    @Override
    public void execute(){
        Pair<List<? extends UserVm>, List<String>> vmServiceMap =  _lbService.listLoadBalancerInstances(this);
        List<? extends UserVm> result = vmServiceMap.first();
        List<String> serviceStates  = vmServiceMap.second();

        if (!isListLbVmip()) {
            // list lb instances
            ListResponse<UserVmResponse> response = new ListResponse<UserVmResponse>();
            List<UserVmResponse> vmResponses = new ArrayList<UserVmResponse>();
            if (result != null) {
                vmResponses = _responseGenerator.createUserVmResponse(ResponseView.Restricted, "loadbalancerruleinstance", result.toArray(new UserVm[result.size()]));

                for (int i = 0; i < result.size(); i++) {
                    vmResponses.get(i).setServiceState(serviceStates.get(i));
                }
            }
            response.setResponses(vmResponses);
            response.setResponseName(getCommandName());
            setResponseObject(response);

        } else {
            ListResponse<LoadBalancerRuleVmMapResponse> lbRes = new ListResponse<LoadBalancerRuleVmMapResponse>();

            List<UserVmResponse> vmResponses = new ArrayList<UserVmResponse>();
            List<LoadBalancerRuleVmMapResponse> listlbVmRes = new ArrayList<LoadBalancerRuleVmMapResponse>();

            if (result != null) {
                vmResponses = _responseGenerator.createUserVmResponse(ResponseView.Full, "loadbalancerruleinstance", result.toArray(new UserVm[result.size()]));

                List<String> ipaddr = null;

                for (int i=0;i<result.size(); i++) {
                    LoadBalancerRuleVmMapResponse lbRuleVmIpResponse = new LoadBalancerRuleVmMapResponse();
                    vmResponses.get(i).setServiceState(serviceStates.get(i));
                    lbRuleVmIpResponse.setUserVmResponse(vmResponses.get(i));
                    //get vm id from the uuid
                    VirtualMachine lbvm = _entityMgr.findByUuid(VirtualMachine.class, vmResponses.get(i).getId());
                    lbRuleVmIpResponse.setIpAddr(_lbService.listLbVmIpAddress(getId(), lbvm.getId()));
                    lbRuleVmIpResponse.setObjectName("lbrulevmidip");
                    listlbVmRes.add(lbRuleVmIpResponse);
                }
            }

            lbRes.setResponseName(getCommandName());
            lbRes.setResponses(listlbVmRes);
            setResponseObject(lbRes);
        }
    }
}