text:
<#
.NOTES
    Copyright 2013 Robert Nees
    Licensed under the Apache License, Version 2.0 (the "License");
.SYNOPSIS
    GZip Compress and DeCompress
.DESCRIPTION
    A 8k buffered GZip (.gz) Compress and DeCompress functions that support pipelined input
.LINK
    http://sushihangover.blogspot.com
.LINK
    https://github.com/sushihangover
#>
function Compress-GZip {
    <#
    .NOTES
        Copyright 2013 Robert Nees
        Licensed under the Apache License, Version 2.0 (the "License");
    .SYNOPSIS
        GZip Compress (.gz)
    .DESCRIPTION
        A buffered GZip (.gz) Compress function that support pipelined input
    .Example
        ls .\NotCompressFile.xml | Compress-GZip -Verbose -WhatIf
    .Example
        Compress-GZip -FullName NotCompressFile.xml -NewName Compressed.xml.funkyextension
    .LINK
        http://sushihangover.blogspot.com
    .LINK
        https://github.com/sushihangover
    #>
    [cmdletbinding(SupportsShouldProcess=$True,ConfirmImpact="Low")]
    param (
        [Alias("PSPath")][parameter(mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string]$FullName,
        [Alias("NewName")][parameter(mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)][string]$GZipPath,
        [parameter(mandatory=$false)][switch]$Force
    )
    Process {
        $_BufferSize = 1024 * 8
        if (Test-Path -Path $FullName -PathType Leaf) {
            Write-Verbose "Reading from: $FullName"
            if ($GZipPath.Length -eq 0) {
                $tmpPath = ls -Path $FullName
                $GZipPath = Join-Path -Path ($tmpPath.DirectoryName) -ChildPath ($tmpPath.Name + '.gz')
            }
            if (Test-Path -Path $GZipPath -PathType Leaf -IsValid) {
                Write-Verbose "Compressing to: $GZipPath"
            } else {
                Write-Error -Message "$FullName is not a valid path/file"
                return
            }
        } else {
            Write-Error -Message "$GZipPath does not exist"
            return
        }
        if (Test-Path -Path $GZipPath -PathType Leaf) {
            If ($Force.IsPresent) {
                if ($pscmdlet.ShouldProcess("Overwrite Existing File @ $GZipPath")) {
                    Touch-File $GZipPath
                }
            }
        } else {
            if ($pscmdlet.ShouldProcess("Create new Compressed File @ $GZipPath")) {
                Touch-File $GZipPath
            }
        }
        if ($pscmdlet.ShouldProcess("Creating Compress File @ $GZipPath")) {
            Write-Verbose "Opening streams and file to save compressed version to..."
            $input = New-Object System.IO.FileStream (ls -path $FullName).FullName, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read);
            $output = New-Object System.IO.FileStream (ls -path $GZipPath).FullName, ([IO.FileMode]::Create), ([IO.FileAccess]::Write), ([IO.FileShare]::None)
            $gzipStream = New-Object System.IO.Compression.GzipStream $output, ([IO.Compression.CompressionMode]::Compress)
            try {
                $buffer = New-Object byte[]($_BufferSize);
                while ($true) {
                    $read = $input.Read($buffer, 0, ($_BufferSize))
                    if ($read -le 0) {
                        break;
                    }
                    $gzipStream.Write($buffer, 0, $read)
                }
            }
            finally {
                Write-Verbose "Closing streams and newly compressed file"
                $gzipStream.Close();
                $output.Close();
                $input.Close();
            }
        }
    }
}
function Expand-GZip {
    <#
    .NOTES
        Copyright 2013 Robert Nees
        Licensed under the Apache License, Version 2.0 (the "License");
    .SYNOPSIS
        GZip Decompress (.gz)
    .DESCRIPTION
        A buffered GZip (.gz) Decompress function that support pipelined input
    .Example
        ls .\RegionName.cs.gz | Expand-GZip -Verbose -WhatIf
    .Example
        Expand-GZip -FullName CompressFile.xml.gz -NewName NotCompressed.xml
    .LINK
        http://sushihangover.blogspot.com
    .LINK
        https://github.com/sushihangover
    #>
    [cmdletbinding(SupportsShouldProcess=$True,ConfirmImpact="Low")]
    param (
        [Alias("PSPath")][parameter(mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][string]$FullName,
        [Alias("NewName")][parameter(mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)][string]$GZipPath = $null,
        [parameter(mandatory=$false)][switch]$Force
    )
    Process {
        if (Test-Path -Path $FullName -PathType Leaf) {
            Write-Verbose "Reading from: $FullName"
            if ($GZipPath.Length -eq 0) {
                $tmpPath = ls -Path $FullName
                $GZipPath = Join-Path -Path ($tmpPath.DirectoryName) -ChildPath ($tmpPath.BaseName)
            }
            if (Test-Path -Path $GZipPath -PathType Leaf -IsValid) {
                Write-Verbose "Decompressing to: $GZipPath"
            } else {
                Write-Error -Message "$GZipPath is not a valid path/file"
                return
            }
        } else {
            Write-Error -Message "$FullName does not exist"
            return
        }
        if (Test-Path -Path $GZipPath -PathType Leaf) {
            If ($Force.IsPresent) {
                if ($pscmdlet.ShouldProcess("Overwrite Existing File @ $GZipPath")) {
                    Touch-File $GZipPath
                }
            }
        } else {
            if ($pscmdlet.ShouldProcess("Create new decompressed File @ $GZipPath")) {
                Touch-File $GZipPath
            }
        }
        if ($pscmdlet.ShouldProcess("Creating Decompressed File @ $GZipPath")) {
            Write-Verbose "Opening streams and file to save compressed version to..."
            $input = New-Object System.IO.FileStream (ls -path $FullName).FullName, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read);
            $output = New-Object System.IO.FileStream (ls -path $GZipPath).FullName, ([IO.FileMode]::Create), ([IO.FileAccess]::Write), ([IO.FileShare]::None)
            $gzipStream = New-Object System.IO.Compression.GzipStream $input, ([IO.Compression.CompressionMode]::Decompress)
            try {
                $buffer = New-Object byte[](1024);
                while ($true) {
                    $read = $gzipStream.Read($buffer, 0, 1024)
                    if ($read -le 0) {
                        break;
                    }
                    $output.Write($buffer, 0, $read)
                }
            }
            finally {
                Write-Verbose "Closing streams and newly decompressed file"
                $gzipStream.Close();
                $output.Close();
                $input.Close();
            }
        }
    }
}


text:
package org.apache.cloudstack.ldap;

import com.cloud.server.auth.UserAuthenticator;
import com.cloud.user.UserAccount;
import com.cloud.user.UserAccountVO;
import com.cloud.user.dao.UserAccountDao;
import com.cloud.utils.Pair;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class LdapAuthenticatorTest {

    @Mock
    LdapManager ldapManager;
    @Mock
    UserAccountDao userAccountDao;
    @Mock
    UserAccount user = new UserAccountVO();

    LdapAuthenticator ldapAuthenticator;
    private String username  = "bbanner";
    private String principal = "cd=bbanner";
    private String hardcoded = "password";
    private Long domainId = 1L;

    @Before
    public void setUp() throws Exception {
        ldapAuthenticator = new LdapAuthenticator(ldapManager, userAccountDao);
    }

    @Test
    public void authenticateWithoutAccount() throws Exception {
        LdapUser ldapUser = new LdapUser(username,"a@b","b","banner",principal,"",false,null);
        Pair<Boolean, UserAuthenticator.ActionOnFailedAuthentication> rc;
        when(ldapManager.getUser(username, domainId)).thenReturn(ldapUser);
        rc = ldapAuthenticator.authenticate(username, "password", domainId, user);
        assertFalse("authentication succeded when it should have failed", rc.first());
        assertEquals("", UserAuthenticator.ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT,rc.second());
    }
    @Test
    public void authenticate() throws Exception {
        LdapUser ldapUser = new LdapUser(username, "a@b", "b", "banner", principal, "", false, null);
        when(ldapManager.getUser(username, domainId)).thenReturn(ldapUser);
        when(ldapManager.canAuthenticate(principal, hardcoded, domainId)).thenReturn(true);
        Pair<Boolean, UserAuthenticator.ActionOnFailedAuthentication> rc = ldapAuthenticator.authenticate(username, hardcoded, domainId, user);
        assertTrue("authentication failed when it should have succeeded", rc.first());
        assertNull(rc.second());
    }
}

redpajama_set_name: RedPajamaGithub


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>
            {{title}}

                     {{item.title}}


text:
package org.organet.michael.Connectivity;

public class AdhocNetwork {
  private String macAddress;
  private String essid;
  private int frequency; // in MHz
  private int channel; // 1 through 14
  private boolean encrypted;

  public AdhocNetwork(String macAddress, String essid, int frequency, boolean encrypted) {
    this.macAddress = macAddress;
    this.essid = essid;
    this.frequency = frequency;
    this.encrypted = encrypted;
  }

  public String getMacAddress() {
    return macAddress;
  }

  public String getEssid() {
    return essid;
  }

  public int getFrequency() {
    return frequency;
  }

  public int getChannel() {
    return channel;
  }

  public boolean isEncrypted() {
    return encrypted;
  }
}


text:
#include "TemperatureService.h"
//BASE UUID: 00000000-B38D-4985-720E-0F993A68EE41

const uint16_t TemperatureServiceShortUUID = 0x2234;
const uint16_t TemperatureServiceTemperatureValueCharacteristicShortUUID = 0x2235;

const uint8_t TemperatureServiceUUID[] = {
  0x00, 0x00, static_cast<uint8_t>(TemperatureServiceShortUUID >> 8), static_cast<uint8_t>(TemperatureServiceShortUUID & 0xFF), 0xb3, 0x8d, 0x49, 0x85,
  0x72, 0x0e, 0x0f, 0x99, 0x3a, 0x68, 0xee, 0x41,
};
const uint8_t TemperatureServiceTemperatureValueCharacteristicUUID[] = {
  0x00, 0x00, static_cast<uint8_t>(TemperatureServiceTemperatureValueCharacteristicShortUUID >> 8), static_cast<uint8_t>(TemperatureServiceTemperatureValueCharacteristicShortUUID & 0xFF), 0xb3, 0x8d, 0x49, 0x85,
  0x72, 0x0e, 0x0f, 0x99, 0x3a, 0x68, 0xee, 0x41,
};


text:
#pragma once

#include <chrono>
#include <ostream>

namespace overdrive {
	namespace core {
		/*
			[TODO] virtual game time?
		*/
		class Clock {
		private:
			friend class Engine;

			typedef std::chrono::high_resolution_clock ClockType;
			typedef ClockType::time_point TimePoint;
			typedef ClockType::duration Duration;

		public:
			Clock();

			TimePoint currentFrame() const; // yields the time at the start of the current frame
			std::chrono::milliseconds deltaFrame() const; // yields the duration since the last frame

			friend std::ostream& operator << (std::ostream& os, const Clock& clock);

		private:
			void update();

			TimePoint mCurrentTimePoint;
			Duration mSinceLastFrame;
		};
	}
}


text:
import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.store.createRecord('beverage', {
      flavor: 'tea',
      size: 1,
      sizeUnits: 'cup'
    });
  }
});


text:
#ifndef __YAAF_SETUP_H__
#define __YAAF_SETUP_H__

#if defined (__cplusplus)
extern "C" {
#endif

#include "YAAF_Config.h"

/* --- Version ------------------------------------------------------------- */

#define YAAF_VERSION_MAJOR 1
#define YAAF_VERSION_MINOR 1
#define YAAF_VERSION_PATCH 3

#define YAAF_VERSION_MK(MA,MI, REV) (MA * 100 * 100) + (MI * 100) + REV
#define YAAF_VERSION YAAF_VERSION_MK(YAAF_VERSION_MAJOR,YAAF_VERSION_MINOR,\
  YAAF_VERSION_PATCH)

/* Indicates the oldest archive version this version can open */
#define YAAF_LAST_VALID_VERSION YAAF_VERSION_MK(1,1,0)

/* --- Host OS ------------------------------------------------------------- */

#if defined(__ANDROID__) || defined(ANDROID)
  #define YAAF_OS_UNIX
  #define YAAF_OS_ANDROID
  #define YAAF_TARGET_ANDROID
#elif defined(__linux) || defined(__linux__)
  #define YAAF_OS_UNIX
  #define YAAF_OS_LINUX
  #define YAAF_TARGET_LINUX
#elif defined(__APPLE__)
  #define YAAF_OS_UNIX
  #define YAAF_OS_APPLE
  #include <AvailabilityMacros.h>
  #include <TargetConditionals.h>
  #if defined(__IPHONE_OS__)
    #define YAAF_TARGET_IOS
    #if defined(TARGET_OS_IPHONE)
      #define YAAF_IOS_DEVICE
    #else
      #define YAAF_IOS_SIMULATOR
    #endif
  #else
    #define YAAF_TARGET_MAC
  #endif
#elif defined(WIN32) || defined(_WIN32)
  #define YAAF_OS_WIN
  #define YAAF_TARGET_WIN
#else
  #error Unknown Operating System
#endif

/* --- Compiler ------------------------------------------------------------ */

#if defined(__clang__)
  #define YAAF_COMPILER_CLANG
  #if defined(YAAF_OS_APPLE)
    #define YAAF_COMPILER_NAME "Apple Clang/LLVM"
  #else
    #define YAAF_COMPILER_NAME "Clang/LLVM"
  #endif
  #define YAAF_COMPILER_VERSION (((__clang_major__)*100) + \
(__clang_minor__*10))
  #define YAAF_COMPILER_VERSION_MAJOR __clang_major__
  #define YAAF_COMPILER_VERSION_MINOR __clang_minor__
#elif defined(__GNUC__)
  #define YAAF_COMPILER_GNUC
  #define YAAF_COMPILER_NAME "GNUC"
  #define YAAF_COMPILER_VERSION (__GNUC__ * 100 + __GNUC_MINOR__ * 10)
  #define YAAF_COMPILER_VERSION_MAJOR __GNUC__
  #define YAAF_COMPILER_VERSION_MINOR __GNUC_MINOR__
#elif defined(_MSC_VER)
  #define YAAF_COMPILER_MSC
  #define YAAF_COMPILER_NAME "MSC"
  #define YAAF_COMPILER_VERSION _MSC_VER
  #define YAAF_COMPILER_VERSION_MAJOR (_MSC_VER / 100)
  #define YAAF_COMPILER_VERSION_MINOR (_MSC_VER % 100)
#else
  #error "Unknown compiler detected!"
#endif

/* Check if compiler has C99 standard active */

#if (__STDC_VERSION__ >= 199901L)
#define YAAF_COMPILER_C99
#endif

/* --- Calling Conventions-------------------------------------------------- */

#if defined(YAAF_COMPILER_CLANG) || defined(YAAF_COMPILER_GNUC)
    #define YAAF_CALL
    #define YAAF_EXPORT_VISIBLE __attribute__ ((visibility("default")))
    #define YAAF_EXPORT_LOCAL __attribute__ ((visibility("hidden")))
    #define YAAF_INLINE __inline__
    #define YAAF_FORCE_INLINE __attribute__((always_inline)) static __inline__
#elif defined(YAAF_COMPILER_MSC)
    #define YAAF_CALL __cdecl
#if defined(YAAF_SHARED_LIB)
    #define YAAF_EXPORT_VISIBLE __declspec(dllexport)
    #define YAAF_EXPORT_LOCAL __declspec(dllimport)
#else
    #define YAAF_EXPORT_VISIBLE
    #define YAAF_EXPORT_LOCAL
#endif
#define YAAF_INLINE __inline
    #define YAAF_FORCE_INLINE __forceinline
#else
    #error Missing calling convetions for current compiler
#endif

#if defined(YAAF_BUILDING_LIBRARY)
#define YAAF_EXPORT YAAF_EXPORT_VISIBLE
#else
#define YAAF_EXPORT YAAF_EXPORT_LOCAL
#endif

/* --- CPU ARCH ------------------------------------------------------------ */

#if !defined(YAAF_CPU_BE)
#define YAAF_CPU_LE
#endif

#if defined(YAAF_CPU_BE)
#error "Big Endian Platforms currently unsupported"
/* #define YAAF_REQUIRE_BSWAP */
#endif

/* use builtin swapping functions when possilbe */
#if __GNUC__ >=4 && __GNUC_MINOR__ >= 1
  #define YAAF_BSWAP16 __builtin_bswap16
  #define YAAF_BSWAP32 __builtin_bswap32
  #define YAAF_BSWAP64 __builtin_bswap64
#elif defined(_MSC_VER)
  #define YAAF_BSWAP16 _byteswap_ushort
  #define YAAF_BSWAP32 _byteswap_ulong
  #define YAAF_BSWAP64 _byteswap_uint64
#else
static YAAF_INLINE YAAF_BSWAP16(uint16_t x)
{
  return (( v & 0x00ff) << 8) | ((v & 0xff00) >> 8);
}

static YAAF_INLINE YAAF_BSWAP32(uint32_t x)
{
  return ((x << 24) & 0xff000000 ) |
      ((x <<  8) & 0x00ff0000 ) |
      ((x >>  8) & 0x0000ff00 ) |
      ((x >> 24) & 0x000000ff );
}

static YAAF_INLINE YAAF_BSWAP64(uint64_t v)
{
  return (((v & 0xff00000000000000ull) >> 56) |
          ((v & 0x00ff000000000000ull) >> 40) |
          ((v & 0x0000ff0000000000ull) >> 24) |
          ((v & 0x000000ff00000000ull) >> 8) |
          ((v & 0x00000000ff000000ull) << 8) |
          ((v & 0x0000000000ff0000ull) << 24) |
          ((v & 0x000000000000ff00ull) << 40) |
          ((v & 0x00000000000000ffull) << 56));
}
#endif

#if defined(YAAF_REQUIRE_BSWAP)
#define YAAF_LITTLE_E16(x) YAAF_BSWAP16(x)
#define YAAF_LITTLE_E32(x) YAAF_BSWAP32(x)
#define YAAF_LITTLE_E64(x) YAAF_BSWAP64(x)
#else
#define YAAF_LITTLE_E16(x) x
#define YAAF_LITTLE_E32(x) x
#define YAAF_LITTLE_E64(x) x
#endif

#if defined(__x86_64) || defined(__amd64) || defined (__LP64__) || defined(_WIN64)
#define YAAF_CPU_X86
#define YAAF_CPU_64BIT
#elif defined(__i386__) || (__intel__) || defined(_WIN32)
#define YAAF_CPU_X86
#define YAAF_CPU_32BIT
#elif defined(__aarch64__) // arm 64
#define YAAF_CPU_ARM
#define YAAF_CPU_64BIT
#elif defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) \
    || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) || defined(__ARM_ARCH_6__) \
    || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \
    || defined(__ARM_ARCH_6ZK__) || defined(_M_ARM)
#define YAAF_CPU_ARM
#define YAAF_CPU_32BIT
#else
#error "Unknown Processor."
#endif

/* --- Debug --------------------------------------------------------------- */

#if defined(YAAF_DEBUG)
#define YAAF_ENABLE_ASSERT
#endif

#if defined(YAAF_ENABLE_ASSERT)
#include <assert.h>
#define YAAF_ASSERT(x) assert(x)
#else
#define YAAF_ASSERT(x)
#endif

/* --- Includes ------------------------------------------------------------ */

#include <stdlib.h>
#include <stdio.h>
#if defined(YAAF_HAVE_MALLOC_H)
#include <malloc.h>
#endif
#include <string.h>
#include <limits.h>
#if defined(YAAF_HAVE_STRINGS_H)
#include <strings.h>
#endif
#include <time.h>

#if defined(YAAF_COMPILER_C99) || defined(YAAF_HAVE_INTTYPES_H)
#include <inttypes.h>
#else
typedef char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
#endif

/* --- Other Defines-------------------------------------------------------- */

#if defined(YAAF_CPU_64BIT)
typedef int64_t YAAF_signed_size_t;
#else
typedef int32_t YAAF_signed_size_t;
#endif

#if defined (__cplusplus)
}
#endif
#endif /* __YAAF_SETUP_H__ */


text:
package org.apache.servicecomb.transport.rest.client.http;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Part;

import org.apache.log4j.Level;
import org.apache.servicecomb.common.rest.RestConst;
import org.apache.servicecomb.common.rest.definition.RestOperationMeta;
import org.apache.servicecomb.common.rest.definition.path.URLPathBuilder;
import org.apache.servicecomb.common.rest.filter.HttpClientFilter;
import org.apache.servicecomb.core.Endpoint;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.core.definition.OperationMeta;
import org.apache.servicecomb.core.executor.ReactiveExecutor;
import org.apache.servicecomb.foundation.common.net.URIEndpointObject;
import org.apache.servicecomb.foundation.common.utils.ReflectUtils;
import org.apache.servicecomb.foundation.test.scaffolding.log.LogCollector;
import org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext;
import org.apache.servicecomb.foundation.vertx.http.ReadStreamPart;
import org.apache.servicecomb.serviceregistry.api.Const;
import org.apache.servicecomb.swagger.invocation.AsyncResponse;
import org.apache.servicecomb.swagger.invocation.Response;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import io.vertx.core.Context;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.SocketAddress;
import mockit.Deencapsulation;
import mockit.Mock;
import mockit.MockUp;
import mockit.Mocked;

public class TestRestClientInvocation {
  Handler<Throwable> exceptionHandler;

  Handler<Buffer> bodyHandler;

  Map<String, String> headers = new HashMap<>();

  HttpClientRequest request = mock(HttpClientRequest.class);

  HttpClient httpClient = mock(HttpClient.class);

  Context context = mock(Context.class);

  HttpClientWithContext httpClientWithContext = new HttpClientWithContext(httpClient, context);

  Invocation invocation = mock(Invocation.class);

  Response response;

  AsyncResponse asyncResp = resp -> {
    response = resp;
  };

  OperationMeta operationMeta = mock(OperationMeta.class);

  Endpoint endpoint = mock(Endpoint.class);

  RestOperationMeta swaggerRestOperation = mock(RestOperationMeta.class);

  URLPathBuilder urlPathBuilder = mock(URLPathBuilder.class);

  URIEndpointObject address = mock(URIEndpointObject.class);

  List<HttpClientFilter> httpClientFilters = new ArrayList<>();

  RestClientInvocation restClientInvocation = new RestClientInvocation(httpClientWithContext, httpClientFilters);

  Map<String, Object> handlerContext = new HashMap<>();

  @SuppressWarnings("unchecked")
  @Before
  public void setup() {
    Deencapsulation.setField(restClientInvocation, "clientRequest", request);
    Deencapsulation.setField(restClientInvocation, "invocation", invocation);
    Deencapsulation.setField(restClientInvocation, "asyncResp", asyncResp);

    when(invocation.getOperationMeta()).thenReturn(operationMeta);
    when(swaggerRestOperation.getPathBuilder()).thenReturn(urlPathBuilder);
    when(swaggerRestOperation.getHttpMethod()).thenReturn("GET");
    when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(swaggerRestOperation);
    when(invocation.getEndpoint()).thenReturn(endpoint);
    when(endpoint.getAddress()).thenReturn(address);
    when(invocation.getHandlerContext()).then(answer -> handlerContext);
    when(httpClient.request((HttpMethod) Mockito.any(), (RequestOptions) Mockito.any(), Mockito.any()))
        .thenReturn(request);
    doAnswer(a -> {
      exceptionHandler = (Handler<Throwable>) a.getArguments()[0];
      return request;
    }).when(request).exceptionHandler(any());
    doAnswer(a -> {
      headers.put(a.getArgumentAt(0, String.class), a.getArgumentAt(1, String.class));
      return request;
    }).when(request).putHeader((String) any(), (String) any());
    doAnswer(a -> {
      ((Handler<Void>) a.getArguments()[0]).handle(null);
      return null;
    }).when(context).runOnContext(any());
  }

  @Test
  public void invoke(@Mocked Response resp) throws Exception {
    doAnswer(a -> {
      asyncResp.complete(resp);
      return null;
    }).when(request).end();
    restClientInvocation.invoke(invocation, asyncResp);

    Assert.assertSame(resp, response);
  }

  @Test
  public void invoke_endThrow() throws Exception {
    Mockito.doThrow(Error.class).when(request).end();
    restClientInvocation.invoke(invocation, asyncResp);

    Assert.assertThat(((InvocationException) response.getResult()).getCause(), Matchers.instanceOf(Error.class));
  }

  @Test
  public void invoke_requestThrow() throws Exception {
    Throwable t = new Error();
    doAnswer(a -> {
      exceptionHandler.handle(t);
      return null;
    }).when(request).end();
    restClientInvocation.invoke(invocation, asyncResp);
    restClientInvocation.invoke(invocation, asyncResp);

    Assert.assertThat(((InvocationException) response.getResult()).getCause(), Matchers.sameInstance(t));
  }

  @Test
  public void testSetCseContext() {
    Map<String, String> contextMap = Collections.singletonMap("k", "v");
    when(invocation.getContext()).thenReturn(contextMap);

    restClientInvocation.setCseContext();

    Assert.assertEquals("{x-cse-context={\"k\":\"v\"}}", headers.toString());
  }

  @Test
  public void testSetCseContext_failed() {
    LogCollector logCollector = new LogCollector();
    logCollector.setLogLevel(RestClientInvocation.class.getName(), Level.DEBUG);
    Deencapsulation.setField(restClientInvocation, "invocation", null);

    restClientInvocation.setCseContext();

    Assert.assertEquals("Failed to encode and set cseContext.", logCollector.getEvents().get(0).getMessage());
    logCollector.teardown();
  }

  @SuppressWarnings("unchecked")
  @Test
  public void handleResponse() {
    HttpClientResponse httpClientResponse = mock(HttpClientResponse.class);
    doAnswer(a -> {
      bodyHandler = (Handler<Buffer>) a.getArguments()[0];
      return httpClientResponse;
    }).when(httpClientResponse).bodyHandler(any());

    Buffer buf = Buffer.buffer();
    new MockUp<RestClientInvocation>(restClientInvocation) {
      @Mock
      void processResponseBody(Buffer responseBuf) {
        asyncResp.success(buf);
      }
    };

    restClientInvocation.handleResponse(httpClientResponse);
    bodyHandler.handle(buf);

    Assert.assertSame(buf, response.getResult());
  }

  public Part returnPart() {
    return null;
  }

  @Test
  public void handleResponse_readStreamPart() {
    HttpClientResponse httpClientResponse = mock(HttpClientResponse.class);
    when(httpClientResponse.statusCode()).thenReturn(200);
    Method method = ReflectUtils.findMethod(this.getClass(), "returnPart");
    when(operationMeta.getMethod()).thenReturn(method);
    new MockUp<RestClientInvocation>(restClientInvocation) {
      @Mock
      void processResponseBody(Buffer responseBuf) {
      }
    };

    restClientInvocation.handleResponse(httpClientResponse);

    Assert.assertThat(handlerContext.get(RestConst.READ_STREAM_PART), Matchers.instanceOf(ReadStreamPart.class));
  }

  @SuppressWarnings("unchecked")
  @Test
  public void handleResponse_responseException() {
    HttpClientResponse httpClientResponse = mock(HttpClientResponse.class);

    NetSocket netSocket = mock(NetSocket.class);
    when(httpClientResponse.netSocket()).thenReturn(netSocket);
    when(netSocket.remoteAddress()).thenReturn(mock(SocketAddress.class));

    doAnswer(a -> {
      exceptionHandler = (Handler<Throwable>) a.getArguments()[0];
      return httpClientResponse;
    }).when(httpClientResponse).exceptionHandler(any());

    restClientInvocation.handleResponse(httpClientResponse);
    Error error = new Error();
    exceptionHandler.handle(error);

    Assert.assertThat(((InvocationException) response.getResult()).getCause(), Matchers.sameInstance(error));
  }

  @Test
  public void processResponseBody() {
    Response resp = Response.ok(null);

    HttpClientResponse httpClientResponse = mock(HttpClientResponse.class);
    Deencapsulation.setField(restClientInvocation, "clientResponse", httpClientResponse);

    {
      HttpClientFilter filter = mock(HttpClientFilter.class);
      when(filter.afterReceiveResponse(any(), any())).thenReturn(null);
      httpClientFilters.add(filter);
    }
    {
      HttpClientFilter filter = mock(HttpClientFilter.class);
      when(filter.afterReceiveResponse(any(), any())).thenReturn(resp);
      httpClientFilters.add(filter);
    }

    when(invocation.getResponseExecutor()).thenReturn(new ReactiveExecutor());

    restClientInvocation.processResponseBody(null);

    Assert.assertSame(resp, response);
  }

  @SuppressWarnings("unchecked")
  @Test
  public void processResponseBody_throw() {
    HttpClientResponse httpClientResponse = mock(HttpClientResponse.class);
    Deencapsulation.setField(restClientInvocation, "clientResponse", httpClientResponse);

    {
      HttpClientFilter filter = mock(HttpClientFilter.class);
      when(filter.afterReceiveResponse(any(), any())).thenThrow(Error.class);
      httpClientFilters.add(filter);
    }

    when(invocation.getResponseExecutor()).thenReturn(new ReactiveExecutor());

    restClientInvocation.processResponseBody(null);

    Assert.assertThat(((InvocationException) response.getResult()).getCause(), Matchers.instanceOf(Error.class));
  }

  @Test
  public void createRequestPath_NoUrlPrefixNoPath() throws Exception {
    when(address.getFirst(Const.URL_PREFIX)).thenReturn(null);

    when(urlPathBuilder.createRequestPath(any())).thenReturn("/path");

    String path = restClientInvocation.createRequestPath(swaggerRestOperation);
    Assert.assertEquals("/path", path);
  }

  @Test
  public void createRequestPath_noUrlPrefixHavePath() throws Exception {
    handlerContext.put(RestConst.REST_CLIENT_REQUEST_PATH, "/client/path");
    when(address.getFirst(Const.URL_PREFIX)).thenReturn(null);

    String path = restClientInvocation.createRequestPath(swaggerRestOperation);
    Assert.assertEquals("/client/path", path);
  }

  @Test
  public void createRequestPath_haveUrlPrefixNoPath() throws Exception {
    when(address.getFirst(Const.URL_PREFIX)).thenReturn("/prefix");

    when(urlPathBuilder.createRequestPath(any())).thenReturn("/path");

    String path = restClientInvocation.createRequestPath(swaggerRestOperation);
    Assert.assertEquals("/prefix/path", path);
  }

  @Test
  public void createRequestPath_haveUrlPrefixHavePath() throws Exception {
    when(address.getFirst(Const.URL_PREFIX)).thenReturn("/prefix");
    handlerContext.put(RestConst.REST_CLIENT_REQUEST_PATH, "/client/path");

    String path = restClientInvocation.createRequestPath(swaggerRestOperation);
    Assert.assertEquals("/prefix/client/path", path);
  }

  @Test
  public void createRequestPath_haveUrlPrefixHavePathAndStartWith() throws Exception {
    when(address.getFirst(Const.URL_PREFIX)).thenReturn("/prefix");
    handlerContext.put(RestConst.REST_CLIENT_REQUEST_PATH, "/prefix/client/path");

    String path = restClientInvocation.createRequestPath(swaggerRestOperation);
    Assert.assertEquals("/prefix/client/path", path);
  }
}


text:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by rikmar15 on 20-Nov-16.
 *
 * @author Marius Rikheim (rikmar15)
 * @version 2.0
 *
 * Simple server
 */
public class Server {

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    public  void runServer(){

        DBConnector dbConnector = new DBConnector();
        Connection con = dbConnector.connect();

        try(ServerSocket serverSocket = new ServerSocket(8000)){
            System.out.println("Server starting.");

            while(true){
                System.out.println("waiting for connection");
                try {
                    Socket clientSocket = serverSocket.accept();
                    executorService.submit(new ServerConnection(clientSocket, con));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


text:
package com.mbledug.blojsom.plugin.imnotification.message;

import java.util.GregorianCalendar;

import junit.framework.TestCase;

import org.blojsom.blog.Comment;
import org.blojsom.blog.Entry;
import org.blojsom.blog.database.DatabaseBlog;
import org.blojsom.blog.database.DatabaseComment;
import org.blojsom.blog.database.DatabaseEntry;
import org.blojsom.plugin.admin.event.EntryAddedEvent;
import org.blojsom.plugin.comment.event.CommentAddedEvent;

public class CommentMessageCreatorTest extends TestCase {

    public void testGetMessageWithNonCommentAddedEventThrowsIllegalArgumentException() {
        try {
            new CommentMessageCreator().getMessage(new EntryAddedEvent(null, null, null, null));
            fail("IllegalArgumentException should've been thrown.");
        } catch (IllegalArgumentException iae) {
            // expected
        }
    }

    public void testGetMessageWithCommentAddedEventCreatesExpectedMessage() {
        String title = "Sam I Am";
        String author = "Dr. Seuss";
        GregorianCalendar calendar = new GregorianCalendar(2000, 11, 25);
        Entry entry = new DatabaseEntry();
        entry.setTitle(title);
        Comment comment = new DatabaseComment();
        comment.setAuthor(author);
        comment.setEntry(entry);
        CommentAddedEvent event = new CommentAddedEvent(
                "dummy source",
                calendar.getTime(),
                comment,
                new DatabaseBlog());
        String message = new CommentMessageCreator().getMessage(event);
        assertTrue(message.startsWith(MessageCreator.MESSAGE_PREFIX + "Mon Dec 25 00:00:00 "));
        assertTrue(message.endsWith(" 2000 - New comment was added by " + author + " to entry '" + title + "'"));
    }
}


text:
// Copyright 1997-2014 Omni Development, Inc. All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// <http://www.omnigroup.com/developer/sourcecode/sourcelicense/>.
//
// $Id$

#import <Foundation/NSString.h>
#import <Foundation/NSBundle.h>
#import <Foundation/NSDate.h>
#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
#import <CoreGraphics/CGGeometry.h>
#import <UIKit/UIGeometry.h>
#else
#import <Foundation/NSGeometry.h> // For NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
#endif

#import <OmniBase/assertions.h>
#import <OmniBase/objc.h>
#import <OmniBase/macros.h>

#if defined(__cplusplus)
extern "C" {
#endif

#if defined(__GNUC__)
#define NORETURN __attribute__ ((noreturn))
#else
#define NORETURN
#endif

#define OB_DEPRECATED_ATTRIBUTE __attribute__((deprecated))

// In some cases, we really need to keep an object alive. For example, we may have a window controller that will release itself in response to its window being closed.
static inline void OBStrongRetain(id object)
{
    if (object) {
        void *ptr = (OB_BRIDGE void *)object;
        CFRetain(ptr);
    }
}

static inline void OBStrongRelease(id object)
{
    if (object) {
        void *ptr = (OB_BRIDGE void *)object;
        CFRelease(ptr);
    }
}

static inline void OBAutorelease(id object)
{
    if (object) {
        void *ptr = (OB_BRIDGE void *)object;
        CFAutorelease(ptr);
    }
}

static inline void OBRetainAutorelease(id object)
{
    OBStrongRetain(object);
    OBAutorelease(object);
}

/*
 A best guess at what macros might indicate availability and usefulness of the GC APIs.

 The -fobjc-gc flag controls __OBJC_GC__ .
 The <objc/objc-auto.h> header defines OBJC_NO_GC, but only based on target macros, not on the compiler options.

 There doesn't seem to be a way to distinguish between -fobjc-gc and -fobjc-gc-only, but maybe that's just as well because even in the GC case we need to *pretend* to be able to use the malloc pointer until we're done with any interior pointers.
*/

#if !defined(__OBJC_GC__) || defined(OBJC_NO_GC) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
    #define OBAllocateCollectable(size,flags) malloc(size)
    #define OBReallocateCollectable(ptr,size,flags) realloc((ptr),(size))

    #define OBAllocateScanned(size) malloc(size)
    #define OBFreeScanned(ptr) free(ptr)
#else
    #include <objc/objc-auto.h> /* For objc_collectingEnabled() */

    #define OBAllocateCollectable NSAllocateCollectable
    #define OBReallocateCollectable NSReallocateCollectable

    #define OBAllocateScanned(size) NSAllocateCollectable((size), NSScannedOption)
    #define OBFreeScanned(ptr) do{ if(!objc_collectingEnabled()) free(ptr); }while(0)
#endif

#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
    // There is only one bundle on iPhone/iPad.
    #define OMNI_BUNDLE [NSBundle mainBundle]
#else
    // This uses the OMNI_BUNDLE_IDENTIFIER compiler define set by the OmniGroup/Configurations/*Global*.xcconfig to look up the bundle for the calling code.
    #define OMNI_BUNDLE _OBBundleWithIdentifier(OMNI_BUNDLE_IDENTIFIER)
    static inline NSBundle *_OBBundleWithIdentifier(NSString *identifier)
    {
        OBPRECONDITION([identifier length] > 0); // Did you forget to set OMNI_BUNDLE_IDENTIFIER in your target?
        NSBundle *bundle = [NSBundle bundleWithIdentifier:identifier];
        OBPOSTCONDITION(bundle); // Did you set it to the wrong thing?
        return bundle;
    }
#endif

extern void _OBRequestConcreteImplementation(id self, SEL _cmd, const char *file, unsigned int line) NORETURN;
extern void _OBRejectUnusedImplementation(id self, SEL _cmd, const char *file, unsigned int line) NORETURN;
extern void _OBRejectInvalidCall(id self, SEL _cmd, const char *file, unsigned int line, NSString *format, ...)
                    NORETURN __attribute__((format(__NSString__, 5, 6)));

#define OBRequestConcreteImplementation(self, sel) _OBRequestConcreteImplementation((self), (sel), __FILE__, __LINE__)
#define OBRejectUnusedImplementation(self, sel) _OBRejectUnusedImplementation((self), (sel), __FILE__, __LINE__)
#define OBRejectInvalidCall(self, sel, format, ...) _OBRejectInvalidCall((self), (sel), __FILE__, __LINE__, (format), ## __VA_ARGS__)

// A common pattern when refactoring or updating code is to #if 0 out portions that haven't been updated and leave a marker there.  This function serves as the 'to do' marker and allows you to demand-port the remaining code after working out the general structure.
// NOTE: The formatting of the "header" argument is formulated so you can run 'strings' on your binary and find a list of all the file:line locations of these.
extern void _OBFinishPorting(const char *header, const char *function) NORETURN;
#define _OBFinishPorting_(file, line, function) _OBFinishPorting("OBFinishPorting at " file ":" #line, function)
#define _OBFinishPorting__(file, line, function) _OBFinishPorting_(file, line, function)
#define OBFinishPorting _OBFinishPorting__(__FILE__, __LINE__, __PRETTY_FUNCTION__)

// Something that needs porting, but not immediately
extern void _OBFinishPortingLater(const char *header, const char *function, const char *message);
#define _OBFinishPortingLater_(file, line, function, message) _OBFinishPortingLater("OBFinishPortingLater at " file ":" #line, function, (message))
#define _OBFinishPortingLater__(file, line, function, message) _OBFinishPortingLater_(file, line, function, (message))
#define OBFinishPortingLater(msg) do { \
    static BOOL warned = NO; \
    if (!warned) { \
        warned = YES; \
        _OBFinishPortingLater__(__FILE__, __LINE__, __PRETTY_FUNCTION__, (msg)); \
    } \
} while(0)

extern BOOL OBIsBeingDebugged(void);
extern void _OBStopInDebugger(const char *file, unsigned int line, const char *function, const char *message);
#define OBStopInDebugger(message) _OBStopInDebugger(__FILE__, __LINE__, __PRETTY_FUNCTION__, (message))
#define OBStepThroughAndVerify() _OBStopInDebugger(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Step through and verify.")

extern NSString * const OBAbstractImplementation;
extern NSString * const OBUnusedImplementation;

#if defined(DEBUG)
#define OB_DEBUG_LOG_CALLER() do { NSArray *syms = [NSThread callStackSymbols]; if ([syms count] > 1) NSLog(@"caller: %@", [syms objectAtIndex:1U]); } while (0)
#else
#define OB_DEBUG_LOG_CALLER()
#endif

enum OBBacktraceBufferType {
    OBBacktraceBuffer_Unused = 0,      /* Indicates an unused slot */
    OBBacktraceBuffer_Allocated = 1,   /* Allocated but not filled slot */

    /* Remaining integers represent different reasons for recording a backtrace */
    OBBacktraceBuffer_OBAssertionFailure = 2,
    OBBacktraceBuffer_NSAssertionFailure = 3,
    OBBacktraceBuffer_NSException = 4,
};
void OBRecordBacktrace(const char *ctxt, unsigned int optype);
/*.doc.
  Records a backtrace for possible debugging use in the future. ctxt and optype are free for the caller to use for their own purposes, but optype must be greater than one.
*/

#undef NORETURN

extern IMP OBRegisterInstanceMethodWithSelector(Class aClass, SEL oldSelector, SEL newSelector);
/*.doc.
Provides the same functionality as +[NSObject registerInstanceMethod:withMethodTypes:forSelector: but does it without provoking +initialize on the target class.  Returns the original implementation.
*/

extern IMP OBReplaceMethodImplementation(Class aClass, SEL oldSelector, IMP newImp);
/*.doc.
Replaces the given method implementation in place.  Returns the old implementation.
*/

IMP OBReplaceMethodImplementationFromMethod(Class aClass, SEL oldSelector, Method newMethod);
/*.doc.
Replaces the given method implementation in place.  Returns the old implementation.
*/

extern IMP OBReplaceMethodImplementationWithSelector(Class aClass, SEL oldSelector, SEL newSelector);
/*.doc.
Calls the above, but determines newImp by looking up the instance method for newSelector.  Returns the old implementation.
*/

extern IMP OBReplaceMethodImplementationWithSelectorOnClass(Class destClass, SEL oldSelector, Class sourceClass, SEL newSelector);
/*.doc.
Calls OBReplaceMethodImplementation.  Derives newImp from newSelector on sourceClass and changes method implementation for oldSelector on destClass.
*/

extern IMP OBReplaceClassMethodImplementationWithSelector(Class aClass, SEL oldSelector, SEL newSelector);
/*.doc.
Calls OBReplaceMethodImplementationWithSelector with aClass's metaclass as the class argument. aClass must not itself be a metaclass.
*/

extern IMP OBReplaceClassMethodImplementationFromMethod(Class aClass, SEL oldSelector, Method newMethod);
/*.doc.
Calls OBReplaceMethodImplementationFromMethod with aClass's metaclass as the class argument. aClass must not itself be a metaclass.
*/

extern Class OBClassImplementingMethod(Class cls, SEL sel);

// This returns YES if the given pointer is a class object
static inline BOOL OBPointerIsClass(id object)
{
    if (object) {
        Class cls = object_getClass(object);
        return class_isMetaClass(cls);
    }
    return NO;
}

// This returns the class object for the given pointer.  For an instance, that means getting the class.  But for a class object, that means returning the pointer itself

static inline Class OBClassForPointer(id object)
{
    if (!object)
	return object;

    if (OBPointerIsClass(object))
	return object;
    else
	return object_getClass(object);
}

static inline BOOL OBClassIsSubclassOfClass(Class subClass, Class superClass)
{
    while (subClass) {
        if (subClass == superClass)
            return YES;
        else
            subClass = class_getSuperclass(subClass);
    }
    return NO;
}

extern NSString *OBShortObjectDescription(id anObject);
extern NSString *OBShortObjectDescriptionWith(id anObject, NSString *extra);
extern NSString *OBFormatObjectDescription(id anObject, NSString *fmt, ...)
    __attribute__((format(__NSString__, 2, 3)));

extern CFStringRef const OBBuildByCompilerVersion;

// This macro ensures that we call [super initialize] in our +initialize (since this behavior is necessary for some classes in Cocoa), but it keeps custom class initialization from executing more than once.
#define OBINITIALIZE \
    do { \
        static BOOL hasBeenInitialized = NO; \
        [super initialize]; \
        if (hasBeenInitialized) \
            return; \
        hasBeenInitialized = YES;\
    } while (0);

// Sometimes a value is computed but not expected to be used and we wish to avoid clang dead store warnings.  For example, when laying out a stack of views, we might keep a running total of the used height and might want to do this for the last item stacked up (in case something is added later).
// Using overloadable functions here lets us handle object types (since we can't cast those to void * w/o __bridge and we can't cast non object types to void * _with_ __bridge).
static inline void __attribute__((overloadable)) _OBUnusedValue(id v) {
    __strong id *__ptr __attribute__((unused)) = &v; /* ensure it is actually an l-value */ \
    typeof(v) __unused_value __attribute__((unused)) = v;
}
#define OB_UNUSED_VALUE_FOR_TYPE(T) \
static inline void __attribute__((overloadable)) _OBUnusedValue(T v) { \
    void *__ptr __attribute__((unused)) = (void *)&v; /* ensure it is actually an l-value */ \
    typeof(v) __unused_value __attribute__((unused)) = v; \
}
OB_UNUSED_VALUE_FOR_TYPE(int8_t)
OB_UNUSED_VALUE_FOR_TYPE(int16_t)
OB_UNUSED_VALUE_FOR_TYPE(int32_t)
OB_UNUSED_VALUE_FOR_TYPE(int64_t)
OB_UNUSED_VALUE_FOR_TYPE(uint8_t)
OB_UNUSED_VALUE_FOR_TYPE(uint16_t)
OB_UNUSED_VALUE_FOR_TYPE(uint32_t)
OB_UNUSED_VALUE_FOR_TYPE(uint64_t)
OB_UNUSED_VALUE_FOR_TYPE(NSUInteger)
OB_UNUSED_VALUE_FOR_TYPE(NSInteger)
OB_UNUSED_VALUE_FOR_TYPE(float)
OB_UNUSED_VALUE_FOR_TYPE(double)
OB_UNUSED_VALUE_FOR_TYPE(void *)
OB_UNUSED_VALUE_FOR_TYPE(const void *)
OB_UNUSED_VALUE_FOR_TYPE(CGPoint)
OB_UNUSED_VALUE_FOR_TYPE(CGSize)
OB_UNUSED_VALUE_FOR_TYPE(CGRect)

#define OB_UNUSED_VALUE(v) _OBUnusedValue(v)

#ifdef USING_BUGGY_CPP_PRECOMP
// Versions of cpp-precomp released before April 2002 have a bug that makes us have to do this
#define NSSTRINGIFY(name) @ ## '"' ## name ## '"'
#elif defined(__GNUC__)
    #if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 3)
        // GCC before 3.3 requires this format
        #define NSSTRINGIFY(name) @ ## #name
    #else
        // GCC 3.3 requires this format
        #define NSSTRINGIFY(name) @#name
    #endif
#endif

// An easy way to define string constants.  For example, "NSSTRINGIFY(foo)" produces @"foo" and "DEFINE_NSSTRING(foo);" produces: NSString *foo = @"foo";

#define DEFINE_NSSTRING(name) \
	NSString * const name = NSSTRINGIFY(name)

// Iterators over C arrays and literals. Useful for iterating over collections known at compile-time, like when (un)registering KVO keypaths. Syntax is similar to a regular for(.. in ..) statement; the first argument is a variable name that is visible within the scope of the block controlled by the OB_FOR_ALL or OB_FOR_IN statement. The subsequent arguments vary.

// Helper macro that drives iteration of the variable named by OB_FOR_var_name over the array named by OB_FOR_array_name.
#define OB_FOR_exprs(OB_FOR_var_name, OB_FOR_array_name) \
        *OB_FOR_IN_end = &OB_FOR_array_name[sizeof(OB_FOR_array_name)/sizeof(OB_FOR_array_name[0])], /* Points one past the end of the array */ \
        *OB_FOR_IN_curr = &OB_FOR_array_name[0], \
        OB_FOR_var_name = OB_FOR_array_name[0]; \
    OB_FOR_IN_curr < OB_FOR_IN_end ? (OB_FOR_var_name = *OB_FOR_IN_curr, 1) : 0; /* Avoid dereferencing pointer one past the end of the array, even if we never use it */ \
    OB_FOR_IN_curr++

// OB_FOR_ALL takes a variable number of arguments (at least two) and iterates over all of them.
// Ex:
//     OB_FOR_ALL(i, 1, 2, 3)
//       printf("%d", i);
#define OB_FOR_ALL(var, one, ...) for(typeof(one) OB_FOR_ALL_array[] = { one, __VA_ARGS__ }, OB_FOR_exprs(var, OB_FOR_ALL_array))

// OB_FOR_IN takes a single array variable as an argument and iterates over its members.
// Ex:
//     int nums[] = {1, 2, 3};
//     OB_FOR_IN(i, nums)
//       printf("%d", i);
#define OB_FOR_IN(var, array) for (typeof(array[0]) OB_FOR_exprs(var, array))

// Emits a warning indicating that an obsolete method has been called.

#define OB_WARN_OBSOLETE_METHOD \
    do { \
        static BOOL warned = NO; \
            if (!warned) { \
                warned = YES; \
                    NSLog(@"Warning: obsolete method %c[%@ %@] invoked", OBPointerIsClass(self)?'+':'-', OBClassForPointer(self), NSStringFromSelector(_cmd)); \
            } \
            OBASSERT_NOT_REACHED("obsolete method called"); \
    } while(0)

// Apple doesn't have an NSNotFound equivalent for NSUInteger values (NSNotFound is an NSInteger).
// Note that for APIs which should match Foundation APIs, you'll need to use NSNotFound even for NSUInteger values.
#define OB_NSUInteger_NotFound (~(NSUInteger)0)

#if NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
// Returns a copy of the method signature with the NSGeometry types replaced with CG types.  The result should be free'd by the caller.
__attribute__((visibility("hidden"))) const char *_OBGeometryAdjustedSignature(const char *sig);
#endif

// Inttypes-style format macros for Apple-defined types
#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
// On these platforms NSInteger=long and NSUInteger=unsigned long
#define PRI_NSInteger_LENGTH_MODIFIER "l"
#else
// On these platforms NSInteger=int and NSUInteger=unsigned int
#define PRI_NSInteger_LENGTH_MODIFIER ""
#endif

#define PRIdNS PRI_NSInteger_LENGTH_MODIFIER "d"
#define PRIiNS PRI_NSInteger_LENGTH_MODIFIER "i"
#define PRIoNS PRI_NSInteger_LENGTH_MODIFIER "o"
#define PRIuNS PRI_NSInteger_LENGTH_MODIFIER "u"
#define PRIxNS PRI_NSInteger_LENGTH_MODIFIER "x"
#define PRIXNS PRI_NSInteger_LENGTH_MODIFIER "X"

// OSStatus is SInt32, which is int on 64-bit and long on 32-bit. Similar problems hit CFStringEncoding and UnicodeScalarValue
// note this is unaffected by NS_BUILD_32_LIKE_64, etc.
#if __LP64__
    // On these platforms, UInt32 and SInt32 are (unsigned) int, and therefore so is OSStatus
    #define PRI_OSStatus "d"
    #define PRI_CFStringEncoding "u"
    #define PRI_UnicodeScalarValue "u"
#else
    // On these platforms, UInt32 and SInt32 are (unsigned) long, and therefore so is OSStatus
    #define PRI_OSStatus "ld"
    #define PRI_CFStringEncoding "lu"
    #define PRI_UnicodeScalarValue "lu"
#endif

// ptrdiff_t
#define PRI_ptrdiff "td"

/* CFIndex is always a signed long as far as I know */
#define PRIdCFIndex "ld"

#if defined(__cplusplus)
} // extern "C"
#endif


text:
"""
This is a simple example on how to use the Deep SLDA strategy.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import torch
import warnings
from torchvision import transforms

from avalanche.training.plugins import EvaluationPlugin
from avalanche.evaluation.metrics import (
    accuracy_metrics,
    loss_metrics,
    forgetting_metrics,
)
from avalanche.logging import InteractiveLogger
from avalanche.benchmarks.classic import CORe50
from avalanche.training.supervised.deep_slda import StreamingLDA
from avalanche.models import SLDAResNetModel

def main(args):
    # Device config
    device = torch.device(
        f"cuda:{args.cuda}"
        if torch.cuda.is_available() and args.cuda >= 0
        else "cpu"
    )
    print("device ", device)
    # ---------

    # --- TRANSFORMATIONS
    _mu = [0.485, 0.456, 0.406]  # imagenet normalization
    _std = [0.229, 0.224, 0.225]
    transform = transforms.Compose(
        [
            transforms.Resize((224, 224)),
            transforms.ToTensor(),
            transforms.Normalize(mean=_mu, std=_std),
        ]
    )
    # ---------

    # --- BENCHMARK CREATION
    benchmark = CORe50(
        scenario=args.scenario,
        train_transform=transform,
        eval_transform=transform,
    )

    # ---------

    eval_plugin = EvaluationPlugin(
        loss_metrics(epoch=True, experience=True, stream=True),
        accuracy_metrics(epoch=True, experience=True, stream=True),
        forgetting_metrics(experience=True, stream=True),
        loggers=[InteractiveLogger()],
    )

    criterion = torch.nn.CrossEntropyLoss()
    model = SLDAResNetModel(
        device=device,
        arch="resnet18",
        imagenet_pretrained=args.imagenet_pretrained,
    )

    # CREATE THE STRATEGY INSTANCE
    cl_strategy = StreamingLDA(
        model,
        criterion,
        args.feature_size,
        args.n_classes,
        eval_mb_size=args.batch_size,
        train_mb_size=args.batch_size,
        train_epochs=1,
        shrinkage_param=args.shrinkage,
        streaming_update_sigma=args.plastic_cov,
        device=device,
        evaluator=eval_plugin,
    )

    warnings.warn(
        "The Deep SLDA example is not perfectly aligned with "
        "the paper implementation since it does not use a base "
        "initialization phase and instead starts streming from "
        "pre-trained weights."
    )

    # TRAINING LOOP
    print("Starting experiment...")
    for i, exp in enumerate(benchmark.train_stream):

        # fit SLDA model to batch (one sample at a time)
        cl_strategy.train(exp)

        # evaluate model on test data
        cl_strategy.eval(benchmark.test_stream)

if __name__ == "__main__":
    parser = argparse.ArgumentParser("SLDA Example with ResNet-18 on CORe50")
    parser.add_argument(
        "--cuda",
        type=int,
        default=0,
        help="Select zero-indexed cuda device. -1 to use CPU.",
    )

    parser.add_argument("--n_classes", type=int, default=50)
    parser.add_argument(
        "--scenario",
        type=str,
        default="nc",
        choices=["ni", "nc", "nic", "nicv2_79", "nicv2_196", "nicv2_391"],
    )

    # deep slda model parameters
    parser.add_argument(
        "--imagenet_pretrained", type=bool, default=True
    )  # initialize backbone with
    # imagenet pre-trained weights
    parser.add_argument(
        "--feature_size", type=int, default=512
    )  # feature size before output layer
    # (512 for resnet-18)
    parser.add_argument(
        "--shrinkage", type=float, default=1e-4
    )  # shrinkage value
    parser.add_argument(
        "--plastic_cov", type=bool, default=True
    )  # plastic covariance matrix
    parser.add_argument("--batch_size", type=int, default=512)

    args = parser.parse_args()
    main(args)


text:
import React, { Component, PropTypes } from 'react';

import ReactDom from "react-dom";

import { VelocityComponent,VelocityTransitionGroup }  from "velocity-react";

class TextView extends Component {
    constructor(props) {
        super(props);

    }
    render() {
        let {} = this.props;

        return (
            <div className={"area-info "}>
            </div>
        )
    }
}
TextView.defaultProps = {
    title:""
}

export default TextView;


text:
It is a version of the Symfony2 Sandbox that contains the XwcCoreBundle enabled
by default and pre-configured to work out-of-the-box. XWC is a content
management system based on Symfony2.

## Requirements
Symfony is only supported on PHP 5.3.2 and up. To check the compatibility of
your environment with Symfony2, you can run the `web/check.php` script, bundled
with this sandbox.

## Installation for Users
Coming soon...

## Installation for Developers
1. [Fork the project on github](http://help.github.com/forking/)
2. Clone your fork to a folder on your local machine:

        cd /path/to/workspace
        git clone --recursive git://github.com/tangentlabs/symfony-sandbox.git
   Note that the `--recursive` option will initialise any submodules
3. Change ownership of cache and log folders so Apache can write:

        sudo chown -R www-data:www-data app/cache app/logs
4. Point your apache to the sandbox folder. You may simply symlink it in
`/var/www/` folder.

        sudo ln -s /path/to/xwc-sandbox /var/www/xwc-sandbox
5. Open in browser

        x-www-browser http://localhost/xwc-sandbox/web/app_dev.php/
   You should see a success screen

### Trouble-shooting

*	Note that you need to install the `php-sqlite3` package:

		sudo apt-get install php5-sqlite
		sudo apache2ctl restart

*   You may need to run a `git pull` within the submodule to grab the latest version:

		cd src/Tangent/XwcBundle/
		git pull origin master

### Updating your fork with latest changes in xwc-sandbox
1. In project folder run:
        git pull origin master

### Updating /XwcCoreBundle submodule
        git submodule update

### Pushing your changes to the xwc-sandbox or XwcCoreBundle
For /xwc-sandbox commits in the root of the project folder run:
        git push origin master
To push commits in /XwcCoreBundle submodule:
        cd /path/to/xwc-sandbox/src/Tangent/XwcCoreBundle
        git push origin master


text:
package org.gradle.internal.fingerprint;

import org.gradle.internal.file.FileType;
import org.gradle.internal.snapshot.FileSystemLocationSnapshot;

import java.util.function.Predicate;

/**
 * Specifies how a fingerprinter should handle directories that are found in a filecollection.
 */
public enum DirectorySensitivity {
    /**
     * Whatever the default behavior is for the given fingerprinter.  For some fingerprinters, the
     * default behavior is to fingerprint directories, for others, they ignore directories by default.
     */
    DEFAULT(snapshot -> true),
    /**
     * Ignore directories
     */
    IGNORE_DIRECTORIES(snapshot -> snapshot.getType() != FileType.Directory),
    /**
     * Used to denote that no directory sensitivity has been specified explicitly.
     *
     * We currently use this to switch to {@link #IGNORE_DIRECTORIES} when an input is a file tree.
     *
     * @deprecated This should go away in 8.0, since the special case should go away.
     */
    @Deprecated
    UNSPECIFIED(snapshot -> {
        throw new AssertionError("Unspecified must not be used as directory sensitivity");
    });

    private final Predicate<FileSystemLocationSnapshot> fingerprintCheck;

    DirectorySensitivity(Predicate<FileSystemLocationSnapshot> fingerprintCheck) {
        this.fingerprintCheck = fingerprintCheck;
    }

    public boolean shouldFingerprint(FileSystemLocationSnapshot snapshot) {
        return fingerprintCheck.test(snapshot);
    }
}


text:
Liste des outils et technologies utiles dans le développement d'applications avec Frappe.

Il y a un grand nombres de tutoriels en ligne et nous recommandons [CodeAcademy](http://www.codecademy.com/) ou vous trouverez beaucoup de ressources de qualité.

---

#### 1. Python

La partie serveur de Frappe est codée en Python et c'est une bonne idée d'[apprendre rapidement Python](http://www.codecademy.com/tracks/python) avant de commencer à comprendre Frappe. [Le tutoriel sur docs.python.org](https://docs.python.org/2.7/tutorial/index.html) est aussi une excellente ressource pour apprendre Python. Notez que Frappe utilise Python 2.7.

Pour produire une application de qualité, vous devez inclure des tests automatiques. Vous pouvez comprendre les bases du développement par les tests [ici](http://code.tutsplus.com/tutorials/beginning-test-driven-development-in-python--net-30137).

---

#### 2. MariaDB / MySQL

Vous devez comprendre les notions essentielles des bases de données, comment installer, se connecter, créer de nouvelles bases,
et comment faire des requêtes. Voici [une rapide introduction à MySQL](https://www.digitalocean.com/community/tutorials/a-basic-mysql-tutorial) ou dirigez vous vers [le site MariaDB pour des informations plus détaillées](https://mariadb.com/kb/en/mariadb/documentation/getting-started/)

---

#### 3. HTML / CSS

Pour construire des interfaces utilisateur, vous devez [apprendre les bases HTML / CSS](http://www.codecademy.com/tracks/web) et [connaître le framework CSS Boostrap](http://getbootstrap.com).

---

#### 4. Construire des interfaces avec Javascript et JQuery

Pour customiser les formulaires et créer des interfaces riches, le mieux est [d'apprendre Javascript](http://www.codecademy.com/tracks/javascript) et la [fameuse librairie JQuery](http://www.codecademy.com/tracks/jquery).

---

#### 5. Modifier les affichages et les pages web avec le sysème de template Jinja

Si vous voulez modifier les affichages, vous devez apprendre le [language de template Jinja](http://jinja.pocoo.org/). C'est un moyen rapide de construire des pages web dynamiques.

---

#### 6. Git et GitHub

[Apprenez à contribuer à un projet open source en utilisant Git et GitHub](https://guides.github.com/activities/contributing-to-open-source/), deux outils fantastiques pour vous aider à gérer et partager votre code.

---

Quand vous êtes prêts, [essayez de développer une application simple avec Frappe]({{ docs_base_url }}/user/fr/tutorial/app)


text:
using System;
using System.Runtime.InteropServices;

namespace Noesis
{

public class TranslateTransform : Transform {
  internal new static TranslateTransform CreateProxy(IntPtr cPtr, bool cMemoryOwn) {
    return new TranslateTransform(cPtr, cMemoryOwn);
  }

  internal TranslateTransform(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) {
  }

  internal static HandleRef getCPtr(TranslateTransform obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  public TranslateTransform() {
  }

  protected override IntPtr CreateCPtr(Type type, out bool registerExtend) {
    registerExtend = false;
    return NoesisGUI_PINVOKE.new_TranslateTransform__SWIG_0();
  }

  public TranslateTransform(float x, float y) : this(NoesisGUI_PINVOKE.new_TranslateTransform__SWIG_1(x, y), true) {
    if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
  }

  public static DependencyProperty XProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.TranslateTransform_XProperty_get();
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public static DependencyProperty YProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.TranslateTransform_YProperty_get();
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public float X {
    set {
      NoesisGUI_PINVOKE.TranslateTransform_X_set(swigCPtr, value);
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
    }
    get {
      float ret = NoesisGUI_PINVOKE.TranslateTransform_X_get(swigCPtr);
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      return ret;
    }
  }

  public float Y {
    set {
      NoesisGUI_PINVOKE.TranslateTransform_Y_set(swigCPtr, value);
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
    }
    get {
      float ret = NoesisGUI_PINVOKE.TranslateTransform_Y_get(swigCPtr);
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      return ret;
    }
  }

  new internal static IntPtr GetStaticType() {
    IntPtr ret = NoesisGUI_PINVOKE.TranslateTransform_GetStaticType();
    if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
    return ret;
  }

}

}


text:
from oslo_policy import policy

from magnum.common.policies import base

CLUSTER = 'cluster:%s'

rules = [
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'create',
        check_str=base.RULE_DENY_CLUSTER_USER,
        description='Create a new cluster.',
        operations=[
            {
                'path': '/v1/clusters',
                'method': 'POST'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'delete',
        check_str=base.RULE_DENY_CLUSTER_USER,
        description='Delete a cluster.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}',
                'method': 'DELETE'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'delete_all_projects',
        check_str=base.RULE_ADMIN_API,
        description='Delete a cluster from any project.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}',
                'method': 'DELETE'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'detail',
        check_str=base.RULE_DENY_CLUSTER_USER,
        description='Retrieve a list of clusters with detail.',
        operations=[
            {
                'path': '/v1/clusters',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'detail_all_projects',
        check_str=base.RULE_ADMIN_API,
        description='Retrieve a list of clusters with detail across projects.',
        operations=[
            {
                'path': '/v1/clusters',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'get',
        check_str=base.RULE_DENY_CLUSTER_USER,
        description='Retrieve information about the given cluster.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'get_one_all_projects',
        check_str=base.RULE_ADMIN_API,
        description=('Retrieve information about the given cluster across '
                     'projects.'),
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'get_all',
        check_str=base.RULE_DENY_CLUSTER_USER,
        description='Retrieve a list of clusters.',
        operations=[
            {
                'path': '/v1/clusters/',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'get_all_all_projects',
        check_str=base.RULE_ADMIN_API,
        description='Retrieve a list of all clusters across projects.',
        operations=[
            {
                'path': '/v1/clusters/',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'update',
        check_str=base.RULE_DENY_CLUSTER_USER,
        description='Update an existing cluster.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}',
                'method': 'PATCH'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'update_health_status',
        check_str=base.RULE_ADMIN_OR_USER + " or " + base.RULE_CLUSTER_USER,
        description='Update the health status of an existing cluster.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}',
                'method': 'PATCH'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'update_all_projects',
        check_str=base.RULE_ADMIN_API,
        description='Update an existing cluster.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}',
                'method': 'PATCH'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'resize',
        check_str=base.RULE_DENY_CLUSTER_USER,
        description='Resize an existing cluster.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}/actions/resize',
                'method': 'POST'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'upgrade',
        check_str=base.RULE_DENY_CLUSTER_USER,
        description='Upgrade an existing cluster.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}/actions/upgrade',
                'method': 'POST'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=CLUSTER % 'upgrade_all_projects',
        check_str=base.RULE_ADMIN_API,
        description='Upgrade an existing cluster across all projects.',
        operations=[
            {
                'path': '/v1/clusters/{cluster_ident}/actions/upgrade',
                'method': 'POST'
            }
        ]
    )

]

def list_rules():
    return rules


text:
using UnityEngine;

public class AddSomeForce : MonoBehaviour {
    private bool done;

    [SerializeField]
    private Transform aChild;

    private void Awake() {
        aChild = GetComponentsInChildren<Transform>()[Random.Range(0, transform.childCount)];
    }

    private void FixedUpdate() {
        if (done) {
            return;
        }
        done = true;
        GetComponent<Rigidbody>().angularVelocity = Random.insideUnitSphere * 10.0f;
        aChild.GetComponent<Rigidbody>().angularVelocity = Random.insideUnitSphere * 10.0f;
    }
}


text:
layout: post
title: ">Domain Driven Design - I'm in!"
date: 2007-01-07 08:17:00.000000000 +01:00
categories:
- DDD
- OR-Mapping
tags: []
status: publish
type: post
published: true
meta:
  blogger_blog: andreasohlund.blogspot.com
  blogger_permalink: "/2007/01/domain-driven-design-im-in.html"
  dsq_thread_id: '299892584'
author:
  login: andreas.ohlund
  email: andreasohlund2@gmail.com
  display_name: Andreas Öhlund
  first_name: Andreas
  last_name: "Öhlund"

---

>In the past all the projects I have been involved in has been developed using "data driven design" i.e. using a relational datamodel as the "blueprint" of the application domain.

But after reading Jimmy Nilsson's great book on DDD I decided to give it a shot.
Being a "database guy" I had a hard time not thinking in terms of "how would this look like in a relational database". (Perhaps lobotomy to remove old "database design" thinking should be a prerequisite before trying DDD) :) Well, after spending some time on DDD, I must say that I love it. DDD allows me to focus completly on discovering the modeled domain without beeing distracted with things like "would I use a mapping table here?", etc. In my previous project we used datasets as data carriers and that produced code like:

customerDS.Customer(0).Firstname

But now with my new shiny domain objects (yes I know that custom objects for datatransfer has been around for a long time but with DDD it's mandatory to use them) the code looks like:

customer.Firstname

A lot better if you ask me!

I agree with Udi Dahan when he states that DDD requires "a higher level of skill to employ"
But I think this "problem" will fade away as people gets used to "domain driven thinking" and the tools eg. O/R-mappers is getting better and better. The latter is exemplified with the upcoming release of ADO 3.0. Making O/R-mapping a native component of the .Net-framework will certainly give DDD a great boost.

Bottom line:

DDD helps you build more stable, maintainable and testable applications! (I'm also a TDD fan of course...) I'm in! , send me the bill!


text: Color Game Project


text:
package com.shollmann.events.api.baseapi;

public enum CallOrigin {
    HOME
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Tables Dynamic - Start - Admin Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="css/images/favicon.png">

<link href="js/plugins/chosen/chosen/chosen.css" rel="stylesheet">
<link href="css/twitter/bootstrap.css" rel="stylesheet">
<link href="css/base.css" rel="stylesheet">
<link href="css/twitter/responsive.css" rel="stylesheet">
<link href="css/jquery-ui-1.8.23.custom.css" rel="stylesheet">

 Start

      <button class="btn responsive_menu icon_item" data-toggle="collapse" data-target=".overview">  </button>

Search

        <form class="form-search">

            <input type="text" class=" search-query" placeholder="">
            <button class="btn_search color_4">Search</button>

        </form>

 Dashboard

  Form Elements

General

Wizards

Validation

Editor

  UI Widgets

Buttons

Dialogs

Icons

Tabs

Accordion

  Calendar

  Maps

  Tables

Static

Dynamics

  Charts

Statistics Elements

Charts

  Grid

  Media

  File Explorer

  Specific Pages

Profile

Search

Login

404 Error

Blog

Menu Settings

          <button id="menu_state_1" class="color_4" rel="tooltip" data-state ="sidebar_icons" data-placement="top" data-original-title="Icon Menu">1</button>
          <button id="menu_state_2" class="color_4 active" rel="tooltip" data-state ="sidebar_default" data-placement="top" data-original-title="Fixed Menu">2</button>
          <button id="menu_state_3" class="color_4" rel="tooltip" data-placement="top" data-state ="sidebar_hover" data-original-title="Floating on Hover Menu">3</button>

 Start

GeorgeFuture Buyer

 My Profile

Settings

Log Out

Help

 Data table (column sorting, live search, pagination)

                      <input type="checkbox">

                  Image
                  Description
                  Info
                  Author
                  Views

                  Actions

                      <input type="checkbox">

                  Full price for gum?!

Size: 196 Kb

Format: .png

                  Fry
                  46,67% 5,3,2,-1,-3,-2,2,3,5,2
                  14

                      <input type="checkbox">

                  Surrender your mysteries to Zoidberg!

Size: 82 Kb

Format: .jpg

                  Zoidberg
                  16,67% 1,1,2,-1,-3,-2,2,4,5,2
                  21

                      <input type="checkbox">

                  The point is, by my standards, I won fair and square.

Size: 392 Kb

Format: .png

                  Bender
                  26,67% 5,3,2,-1,-3,-2,2,3,5,2
                  12

                      <input type="checkbox">

                   File not found?!

Size: 403 Kb

Format: .gif

                  Fry
                  7,32% 5,3,2,-1,-3,-2,2,3,5,2
                  2

                      <input type="checkbox">

                  I'm Santa Claus!

Size: 546 Kb

Format: .jpg

                  Simpson
                  48,33% 5,3,2,-1,-3,-2,2,3,5,2
                  17

                      <input type="checkbox">

                  And I'd do it again! And perhaps a third time!!

Size: 294 Kb

Format: .png

                  Fry
                  88,22% 5,3,2,-1,-3,-2,2,3,5,2
                  0

                      <input type="checkbox">

                  Perfectly symmetrical violence never solved anything.

Size: 9.996 Kb

Format: .psd

                  Leela
                  99,67% 5,3,2,-1,-3,-2,2,3,5,2
                  93

                      <input type="checkbox">

                  Full price for gum?!

Size: 196 Kb

Format: .png

                  Fry
                  46,67% 5,3,2,-1,-3,-2,2,3,5,2
                  14

                      <input type="checkbox">

                  Surrender your mysteries to Zoidberg!

Size: 82 Kb

Format: .jpg

                  Zoidberg
                  16,67% 1,1,2,-1,-3,-2,2,4,5,2
                  21

                      <input type="checkbox">

                  The point is, by my standards, I won fair and square.

Size: 392 Kb

Format: .png

                  Bender
                  26,67% 5,3,2,-1,-3,-2,2,3,5,2
                  12

                      <input type="checkbox">

                   File not found?!

Size: 403 Kb

Format: .gif

                  Fry
                  7,32% 5,3,2,-1,-3,-2,2,3,5,2
                  2

                      <input type="checkbox">

                  I'm Santa Claus!

Size: 546 Kb

Format: .jpg

                  Simpson
                  48,33% 5,3,2,-1,-3,-2,2,3,5,2
                  17

                      <input type="checkbox">

                  And I'd do it again! And perhaps a third time!!

Size: 294 Kb

Format: .png

                  Fry
                  88,22% 5,3,2,-1,-3,-2,2,3,5,2
                  0

                      <input type="checkbox">

                  Perfectly symmetrical violence never solved anything.

Size: 9.996 Kb

Format: .psd

                  Leela
                  99,67% 5,3,2,-1,-3,-2,2,3,5,2
                  93

                      <input type="checkbox">

                  Full price for gum?!

Size: 196 Kb

Format: .png

                  Fry
                  46,67% 5,3,2,-1,-3,-2,2,3,5,2
                  14

                      <input type="checkbox">

                  Surrender your mysteries to Zoidberg!

Size: 82 Kb

Format: .jpg

                  Zoidberg
                  16,67% 1,1,2,-1,-3,-2,2,4,5,2
                  21

                      <input type="checkbox">

                  The point is, by my standards, I won fair and square.

Size: 392 Kb

Format: .png

                  Bender
                  26,67% 5,3,2,-1,-3,-2,2,3,5,2
                  12

                      <input type="checkbox">

                   File not found?!

Size: 403 Kb

Format: .gif

                  Fry
                  7,32% 5,3,2,-1,-3,-2,2,3,5,2
                  2

                      <input type="checkbox">

                  I'm Santa Claus!

Size: 546 Kb

Format: .jpg

                  Simpson
                  48,33% 5,3,2,-1,-3,-2,2,3,5,2
                  17

                      <input type="checkbox">

                  And I'd do it again! And perhaps a third time!!

Size: 294 Kb

Format: .png

                  Fry
                  88,22% 5,3,2,-1,-3,-2,2,3,5,2
                  0

                      <input type="checkbox">

                  Perfectly symmetrical violence never solved anything.

Size: 9.996 Kb

Format: .psd

                  Leela
                  99,67% 5,3,2,-1,-3,-2,2,3,5,2
                  93

                      <input type="checkbox">

                  Full price for gum?!

Size: 196 Kb

Format: .png

                  Fry
                  46,67% 5,3,2,-1,-3,-2,2,3,5,2
                  14

                      <input type="checkbox">

                  Surrender your mysteries to Zoidberg!

Size: 82 Kb

Format: .jpg

                  Zoidberg
                  16,67% 1,1,2,-1,-3,-2,2,4,5,2
                  21

                      <input type="checkbox">

                  The point is, by my standards, I won fair and square.

Size: 392 Kb

Format: .png

                  Bender
                  26,67% 5,3,2,-1,-3,-2,2,3,5,2
                  12

                      <input type="checkbox">

                   File not found?!

Size: 403 Kb

Format: .gif

                  Fry
                  7,32% 5,3,2,-1,-3,-2,2,3,5,2
                  2

                      <input type="checkbox">

                  I'm Santa Claus!

Size: 546 Kb

Format: .jpg

                  Simpson
                  48,33% 5,3,2,-1,-3,-2,2,3,5,2
                  17

                      <input type="checkbox">

                  And I'd do it again! And perhaps a third time!!

Size: 294 Kb

Format: .png

                  Fry
                  88,22% 5,3,2,-1,-3,-2,2,3,5,2
                  0

                      <input type="checkbox">

                  Perfectly symmetrical violence never solved anything.

Size: 9.996 Kb

Format: .psd

                  Leela
                  99,67% 5,3,2,-1,-3,-2,2,3,5,2
                  93

 © Start - Admin Template 2012

1

1

2

3

4

5

6

7

8

9

10

10

12

13

14

15

16

17

18

19

20

21

22

23

24

25

Modal Concept


text:
struct timespec {
	u64 tv_sec;
	u64 tv_nsec;
};

int
posix_clock_gettime(int clock_id, struct timespec *ts);

#endif


text:
<?php

/*
 * GENERATED CODE WARNING
 * This file was automatically generated - do not edit!
 */

require_once __DIR__ . '/../../../vendor/autoload.php';

// [START logging_v2_generated_LoggingServiceV2_DeleteLog_sync]
use Google\ApiCore\ApiException;
use Google\Cloud\Logging\V2\LoggingServiceV2Client;

/**
 * Deletes all the log entries in a log. The log reappears if it receives new
 * entries. Log entries written shortly before the delete operation might not
 * be deleted. Entries received after the delete operation with a timestamp
 * before the operation will be deleted.
 *
 * @param string $formattedLogName The resource name of the log to delete:
 *
 *                                 "projects/[PROJECT_ID]/logs/[LOG_ID]"
 *                                 "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
 *                                 "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
 *                                 "folders/[FOLDER_ID]/logs/[LOG_ID]"
 *
 *                                 `[LOG_ID]` must be URL-encoded. For example,
 *                                 `"projects/my-project-id/logs/syslog"`,
 *                                 `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
 *                                 For more information about log names, see
 *                                 [LogEntry][google.logging.v2.LogEntry]. Please see
 *                                 {@see LoggingServiceV2Client::logName()} for help formatting this field.
 */
function delete_log_sample(string $formattedLogName): void
{
    // Create a client.
    $loggingServiceV2Client = new LoggingServiceV2Client();

    // Call the API and handle any network failures.
    try {
        $loggingServiceV2Client->deleteLog($formattedLogName);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedLogName = LoggingServiceV2Client::logName('[PROJECT]', '[LOG]');

    delete_log_sample($formattedLogName);
}
// [END logging_v2_generated_LoggingServiceV2_DeleteLog_sync]


text:
Install application

To run this application, please, ensure that you have nodejs version v5.2.0 or later and npm 3.3.12 or later

Also you should have RabbitMQ, see installation instructions here: https://www.rabbitmq.com/download.html

```{r, engine='bash', count_lines}
cd cqrs
npm install
```

Ensure that RabbitMQ server running.
If your RabbitMQ server running not on localhost, than you have to edit file cqrs/temp-loader.js and change constant
 rabbitMQHost.

Before running application you have to create configuration file. The simpliest way is to copy default config:
```{r, engine='bash', count_lines}
cp config/default.js config/dev.js
```
Please, do not commit this file to repository! Otherwise we will constantly have conflicts in configuration.

You might want edit some options:
* __rabbitMQHost__ - Host of RabbitMQ server
* __commandBusExchange__ - Exchange name of CommandBus based on RabbitMQ
* __logger__ - Configuration of the logger. It array of objects, each object configures log handler.
Each log handler consists of *filter*, *formatter* and *writer*. By default we have one log handler enabled, that write all log to file, so you might want change file path.
Please not, that if you run system on Windows, you must change file path (or logger configuration).

###### Writes
For now we have few available writers:
* __LogWriterToConsole__ - This writer output all logs to console.
* __LogWriterToFile__ - Outputs all logs to file. As an options it accept *filePath* - string that represent path to file where to store options.
 * __LogWriterNone__ - This writer doing nothing, it just ignores all incoming logs. You might want temproary enable it if you have some problems with logger.

To run application (it should be done under *cqrs* folder)

```{r, engine='bash', count_lines}
npm run build; npm run built
```

As a result you should see in console log of evaluation, please scroll to the beginning of the log and follow throw steps


text:
angular.module('myApp.view4.directives', [])
.directive('tableGlobalDirective', function() {
  return {
    // require: 'ngModel',
    restrict: 'E',
    templateUrl: 'view4/table.html'
  };
})
.directive('ngEnter', function() {
    return function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {
            if(event.which === 13) {
                scope.$apply(function(){
                    scope.$eval(attrs.ngEnter, {'event': event});
                });

                event.preventDefault();
            }
        });
    };
});


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"time"

	"github.com/guilhermebr/datasync/storages"
)

type configuration struct {
	App      string
	Timer    int
	Storages []*storages.Storage
}

// Projects found in config folder .
var Projects []*configuration

var quit = make(chan bool)

func main() {
	// Load config projects file
	LoadProjects()

	// Create a timer for each project
	for _, project := range Projects {
		scheduleProject(project)

	}
	<-quit

}

// LoadProjects run config folder and load projects into Project
func LoadProjects() {
	files, _ := ioutil.ReadDir("./config/")
	for _, f := range files {
		fmt.Println("Found config file: ", f.Name())
		file, err := os.Open("./config/" + f.Name())
		if err != nil {
			fmt.Println("error when open file:", err)

		}
		decoder := json.NewDecoder(file)
		config := configuration{}
		err = decoder.Decode(&config)
		if err != nil {
			fmt.Println("error decoding file: ", err)
		}
		fmt.Println(config.App)
		Projects = append(Projects, &config)
	}

}

func scheduleProject(config *configuration) {
	// Create a ticker based on timer option in config file
	t := time.NewTicker(time.Duration(config.Timer) * time.Second)

	// Get all storages in config file
	drivers := parseStorage(config)

	// run a goroutine that get data from storages and synchronize
	go func() {
		for {
			// Connect and get all data from first storage
			fmt.Println(config)
			drivers[0].Connect()
			d1Ids, _ := drivers[0].GetAll()

			for _, row := range d1Ids {
				fmt.Println(row)
			}

			// Connect and get all data from second storage
			drivers[1].Connect()
			d2Ids, _ := drivers[1].GetAll()
			for _, row := range d2Ids {
				fmt.Println(row)
			}

			// Wait for timer and run again
			select {
			case <-t.C:
			case <-quit:
				return
			}
		}
	}()
}

// parseStorage get storages in config file and get the Driver
func parseStorage(config *configuration) []storages.Driver {
	var storagesReturn []storages.Driver
	for _, storage := range config.Storages {
		if storage.Driver == "cassandra" {
			storagesReturn = append(storagesReturn, storages.NewCassandraSession(storage))
		} else if storage.Driver == "elasticsearch" {
			storagesReturn = append(storagesReturn, storages.NewElasticSearchSession(storage))
		}
	}

	return storagesReturn
}


text:
<?php

namespace Ghostscript\Exception;

interface ExceptionInterface
{
}


text:
<?php

namespace Croogo\Core\Test\TestCase\Model\Behavior;

use Cake\ORM\TableRegistry;
use Croogo\Core\Link;
use Croogo\Core\TestSuite\CroogoTestCase;

class UrlBehaviorTest extends CroogoTestCase
{

    public $fixtures = [
        'plugin.croogo\core.things'
    ];

/**
 * setUp
 *
 * @return void
 */
    public function setUp()
    {
        parent::setUp();

        $this->Things = TableRegistry::get('Things');
    }

    public function testSingle()
    {
        $thing = $this->Things->findByTitle('First Article')->first();

        $this->assertEquals(new Link([
            'controller' => 'Things',
            'action' => 'view',
            1
        ]), $thing->url);
    }

    public function testMultiple()
    {
        $things = $this->Things->find('all')->toArray();

        $this->assertEquals(new Link([
            'controller' => 'Things',
            'action' => 'view',
            1
        ]), $things[0]->url);
        $this->assertEquals(new Link([
            'controller' => 'Things',
            'action' => 'view',
            2
        ]), $things[1]->url);
    }
}