text:
@implementation Crypto

- (id)initWithString:(NSString*)plainText
{
    self = [super init];
    if (self) {
        _desc = [[self class] MD5FromString:plainText];
    }
    return self;
}

- (NSString*)description
{
    return _desc;
}

+ (NSString*)MD5FromString:(NSString*)string
{
    // Create pointer to the string as UTF8
    const char *ptr = [string UTF8String];

    // Create byte array of unsigned chars
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];

    // Create 16 bytes MD5 hash value, store in buffer
    CC_MD5(ptr, strlen(ptr), md5Buffer);

    // Convert unsigned char buffer to NSString of hex values
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x",md5Buffer[i]];

    return output;
}

@end


text:
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Mono.Cecil;

namespace IL.View.Model
{
  public static class FormattingUtils
  {
    public static string GetMethodName(MethodDefinition definition)
    {
      var result = new StringBuilder();
      result.Append(definition.Name);

      // Generic parameters
      if (definition.HasGenericParameters)
      {
        result.Append("<");
        for (int i = 0; i < definition.GenericParameters.Count; i++)
        {
          result.Append(definition.GenericParameters[i].Name);
          if (i != definition.GenericParameters.Count - 1)
            result.Append(", ");
        }
        result.Append(">");
      }

      return result.ToString();
    }

    public static string FormatXml(string stringXml)
    {
      var stringReader = new StringReader(stringXml);
      var xDoc = XDocument.Load(stringReader);
      var stringBuilder = new StringBuilder();
      XmlWriter xmlWriter = null;
      try
      {
        var settings = new XmlWriterSettings
        {
          Indent = true,
          ConformanceLevel = ConformanceLevel.Auto,
          //IndentChars = " ",
          OmitXmlDeclaration = true
        };

        xmlWriter = XmlWriter.Create(stringBuilder, settings);
        xDoc.WriteTo(xmlWriter);
      }
      finally
      {
        if (xmlWriter != null)
          xmlWriter.Close();
      }
      return stringBuilder.ToString();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Sentry Spring Inc. Show
date: 2016-05-24
author: Virginia Thomas
tags: weekly links, java
status: published
summary: Nulla consequat, odio quis tempor interdum, quam sapien rhoncus.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 08/05/2019
  endDate: 08/10/2019
  ctyhocn: LKGNYHX
  groupCode: SSIS
published: true
---
Sed urna dolor, placerat sit amet sagittis quis, feugiat at erat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam a aliquet mauris. Aenean ornare felis et ultrices aliquet. Pellentesque eu facilisis felis. Sed fermentum dapibus sapien eu imperdiet. In rutrum, turpis bibendum semper lacinia, eros sem euismod leo, id semper ipsum neque sed libero. Nam iaculis libero nec sapien pellentesque, interdum scelerisque enim cursus. Aliquam faucibus odio vitae mi rutrum bibendum. Etiam eget viverra lacus, id hendrerit purus. Phasellus pellentesque volutpat consectetur.
Fusce tellus neque, volutpat non imperdiet nec, maximus et eros. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent ante nisi, volutpat in orci ac, gravida bibendum nibh. Quisque mi mi, blandit nec lacinia at, fringilla vel metus. Phasellus blandit maximus mauris, eu consequat leo tristique ut. Vivamus ultricies varius nulla eu ultricies. Sed consectetur, leo non bibendum suscipit, eros justo rhoncus magna, quis iaculis nibh neque eget justo.

* Morbi sodales orci vitae mattis ultricies.

Donec fringilla tristique arcu et suscipit. Etiam orci risus, scelerisque sed massa in, imperdiet elementum mauris. Vestibulum dignissim mauris id tortor tempus, ultricies pulvinar lectus rutrum. Cras venenatis posuere neque non consectetur. Aliquam aliquet eu tortor eget fermentum. Donec rhoncus arcu cursus, efficitur eros eget, tincidunt dui. Nam non magna sed mi vestibulum porta. Praesent pharetra, mauris non sodales convallis, justo velit pharetra lectus, et aliquet urna arcu nec orci. Maecenas eget enim sapien.


text:
title: hugoma
description: A boiler plate for Hugo created with Bulma and optimized with modern workflows and tooling. 🌟
date: 2018-05-14
image: https://i.imgur.com/mGA3X7m.png
link: https://github.com/fvcproductions/hugoma
categories:
  - portfolio
tags:
  - open source
---


text:
package com.agoda.kafka.connector.jdbc.models

import com.agoda.kafka.connector.jdbc.models.Mode.{IncrementingMode, TimestampIncrementingMode, TimestampMode}
import org.scalatest.{Matchers, WordSpec}

class ModeTest extends WordSpec with Matchers {

  "module" should {
    "convert Mode to its string representation" in {
      Mode.TimestampMode.entryName shouldEqual "timestamp"
      Mode.IncrementingMode.entryName shouldEqual "incrementing"
      Mode.TimestampIncrementingMode.entryName shouldEqual "timestamp+incrementing"
    }

    "convert string to corresponding Mode representation" in {
      Mode.withName("timestamp") shouldBe TimestampMode
      Mode.withName("incrementing") shouldBe IncrementingMode
      Mode.withName("timestamp+incrementing") shouldBe TimestampIncrementingMode
    }
  }
}


text:
from django import forms
from django.contrib import admin
from models import *

admin.site.register(About)
admin.site.register(Post)
admin.site.register(Page)
admin.site.register(PageVersion)
admin.site.register(DynamicPageContent)
admin.site.register(Menu)
admin.site.register(Link)
admin.site.register(Home)


text:
#include "precomp.hpp"

//==============================================================================
//
// Error handling helpers
//
//==============================================================================

namespace
{
    #define error_entry(entry)  { entry, #entry }

    struct ErrorEntry
    {
        int code;
        const char* str;
    };

    struct ErrorEntryComparer
    {
        int code;
        ErrorEntryComparer(int code_) : code(code_) {}
        bool operator()(const ErrorEntry& e) const { return e.code == code; }
    };

    //////////////////////////////////////////////////////////////////////////
    // NCV errors

    const ErrorEntry ncv_errors [] =
    {
        error_entry( NCV_SUCCESS ),
        error_entry( NCV_UNKNOWN_ERROR ),
        error_entry( NCV_CUDA_ERROR ),
        error_entry( NCV_NPP_ERROR ),
        error_entry( NCV_FILE_ERROR ),
        error_entry( NCV_NULL_PTR ),
        error_entry( NCV_INCONSISTENT_INPUT ),
        error_entry( NCV_TEXTURE_BIND_ERROR ),
        error_entry( NCV_DIMENSIONS_INVALID ),
        error_entry( NCV_INVALID_ROI ),
        error_entry( NCV_INVALID_STEP ),
        error_entry( NCV_INVALID_SCALE ),
        error_entry( NCV_INVALID_SCALE ),
        error_entry( NCV_ALLOCATOR_NOT_INITIALIZED ),
        error_entry( NCV_ALLOCATOR_BAD_ALLOC ),
        error_entry( NCV_ALLOCATOR_BAD_DEALLOC ),
        error_entry( NCV_ALLOCATOR_INSUFFICIENT_CAPACITY ),
        error_entry( NCV_ALLOCATOR_DEALLOC_ORDER ),
        error_entry( NCV_ALLOCATOR_BAD_REUSE ),
        error_entry( NCV_MEM_COPY_ERROR ),
        error_entry( NCV_MEM_RESIDENCE_ERROR ),
        error_entry( NCV_MEM_INSUFFICIENT_CAPACITY ),
        error_entry( NCV_HAAR_INVALID_PIXEL_STEP ),
        error_entry( NCV_HAAR_TOO_MANY_FEATURES_IN_CLASSIFIER ),
        error_entry( NCV_HAAR_TOO_MANY_FEATURES_IN_CASCADE ),
        error_entry( NCV_HAAR_TOO_LARGE_FEATURES ),
        error_entry( NCV_HAAR_XML_LOADING_EXCEPTION ),
        error_entry( NCV_NOIMPL_HAAR_TILTED_FEATURES ),
        error_entry( NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW ),
        error_entry( NPPST_SUCCESS ),
        error_entry( NPPST_ERROR ),
        error_entry( NPPST_CUDA_KERNEL_EXECUTION_ERROR ),
        error_entry( NPPST_NULL_POINTER_ERROR ),
        error_entry( NPPST_TEXTURE_BIND_ERROR ),
        error_entry( NPPST_MEMCPY_ERROR ),
        error_entry( NPPST_MEM_ALLOC_ERR ),
        error_entry( NPPST_MEMFREE_ERR ),
        error_entry( NPPST_INVALID_ROI ),
        error_entry( NPPST_INVALID_STEP ),
        error_entry( NPPST_INVALID_SCALE ),
        error_entry( NPPST_MEM_INSUFFICIENT_BUFFER ),
        error_entry( NPPST_MEM_RESIDENCE_ERROR ),
        error_entry( NPPST_MEM_INTERNAL_ERROR )
    };

    const size_t ncv_error_num = sizeof(ncv_errors) / sizeof(ncv_errors[0]);
}

cv::String cv::cuda::getNcvErrorMessage(int code)
{
    size_t idx = std::find_if(ncv_errors, ncv_errors + ncv_error_num, ErrorEntryComparer(code)) - ncv_errors;

    const char* msg = (idx != ncv_error_num) ? ncv_errors[idx].str : "Unknown error code";
    String str = cv::format("%s [Code = %d]", msg, code);

    return str;
}

static void stdDebugOutput(const cv::String &msg)
{
    std::cout << msg.c_str() << std::endl;
}

static NCVDebugOutputHandler *debugOutputHandler = stdDebugOutput;

void ncvDebugOutput(const cv::String &msg)
{
    debugOutputHandler(msg);
}

void ncvSetDebugOutputHandler(NCVDebugOutputHandler *func)
{
    debugOutputHandler = func;
}

//==============================================================================
//
// Memory wrappers and helpers
//
//==============================================================================

Ncv32u alignUp(Ncv32u what, Ncv32u alignment)
{
    Ncv32u alignMask = alignment-1;
    Ncv32u inverseAlignMask = ~alignMask;
    Ncv32u res = (what + alignMask) & inverseAlignMask;
    return res;
}

void NCVMemPtr::clear()
{
    ptr = NULL;
    memtype = NCVMemoryTypeNone;
}

void NCVMemSegment::clear()
{
    begin.clear();
    size = 0;
}

NCVStatus memSegCopyHelper(void *dst, NCVMemoryType dstType, const void *src, NCVMemoryType srcType, size_t sz, cudaStream_t cuStream)
{
    NCVStatus ncvStat;
    switch (dstType)
    {
    case NCVMemoryTypeHostPageable:
    case NCVMemoryTypeHostPinned:
        switch (srcType)
        {
        case NCVMemoryTypeHostPageable:
        case NCVMemoryTypeHostPinned:
            memcpy(dst, src, sz);
            ncvStat = NCV_SUCCESS;
            break;
        case NCVMemoryTypeDevice:
            if (cuStream != 0)
            {
                ncvAssertCUDAReturn(cudaMemcpyAsync(dst, src, sz, cudaMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR);
            }
            else
            {
                ncvAssertCUDAReturn(cudaMemcpy(dst, src, sz, cudaMemcpyDeviceToHost), NCV_CUDA_ERROR);
            }
            ncvStat = NCV_SUCCESS;
            break;
        default:
            ncvStat = NCV_MEM_RESIDENCE_ERROR;
        }
        break;
    case NCVMemoryTypeDevice:
        switch (srcType)
        {
        case NCVMemoryTypeHostPageable:
        case NCVMemoryTypeHostPinned:
            if (cuStream != 0)
            {
                ncvAssertCUDAReturn(cudaMemcpyAsync(dst, src, sz, cudaMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR);
            }
            else
            {
                ncvAssertCUDAReturn(cudaMemcpy(dst, src, sz, cudaMemcpyHostToDevice), NCV_CUDA_ERROR);
            }
            ncvStat = NCV_SUCCESS;
            break;
        case NCVMemoryTypeDevice:
            if (cuStream != 0)
            {
                ncvAssertCUDAReturn(cudaMemcpyAsync(dst, src, sz, cudaMemcpyDeviceToDevice, cuStream), NCV_CUDA_ERROR);
            }
            else
            {
                ncvAssertCUDAReturn(cudaMemcpy(dst, src, sz, cudaMemcpyDeviceToDevice), NCV_CUDA_ERROR);
            }
            ncvStat = NCV_SUCCESS;
            break;
        default:
            ncvStat = NCV_MEM_RESIDENCE_ERROR;
        }
        break;
    default:
        ncvStat = NCV_MEM_RESIDENCE_ERROR;
    }

    return ncvStat;
}

NCVStatus memSegCopyHelper2D(void *dst, Ncv32u dstPitch, NCVMemoryType dstType,
                             const void *src, Ncv32u srcPitch, NCVMemoryType srcType,
                             Ncv32u widthbytes, Ncv32u height, cudaStream_t cuStream)
{
    NCVStatus ncvStat;
    switch (dstType)
    {
    case NCVMemoryTypeHostPageable:
    case NCVMemoryTypeHostPinned:
        switch (srcType)
        {
        case NCVMemoryTypeHostPageable:
        case NCVMemoryTypeHostPinned:
            for (Ncv32u i=0; i<height; i++)
            {
                memcpy((char*)dst + i * dstPitch, (char*)src + i * srcPitch, widthbytes);
            }
            ncvStat = NCV_SUCCESS;
            break;
        case NCVMemoryTypeDevice:
            if (cuStream != 0)
            {
                ncvAssertCUDAReturn(cudaMemcpy2DAsync(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR);
            }
            else
            {
                ncvAssertCUDAReturn(cudaMemcpy2D(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyDeviceToHost), NCV_CUDA_ERROR);
            }
            ncvStat = NCV_SUCCESS;
            break;
        default:
            ncvStat = NCV_MEM_RESIDENCE_ERROR;
        }
        break;
    case NCVMemoryTypeDevice:
        switch (srcType)
        {
        case NCVMemoryTypeHostPageable:
        case NCVMemoryTypeHostPinned:
            if (cuStream != 0)
            {
                ncvAssertCUDAReturn(cudaMemcpy2DAsync(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR);
            }
            else
            {
                ncvAssertCUDAReturn(cudaMemcpy2D(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyHostToDevice), NCV_CUDA_ERROR);
            }
            ncvStat = NCV_SUCCESS;
            break;
        case NCVMemoryTypeDevice:
            if (cuStream != 0)
            {
                ncvAssertCUDAReturn(cudaMemcpy2DAsync(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyDeviceToDevice, cuStream), NCV_CUDA_ERROR);
            }
            else
            {
                ncvAssertCUDAReturn(cudaMemcpy2D(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyDeviceToDevice), NCV_CUDA_ERROR);
            }
            ncvStat = NCV_SUCCESS;
            break;
        default:
            ncvStat = NCV_MEM_RESIDENCE_ERROR;
        }
        break;
    default:
        ncvStat = NCV_MEM_RESIDENCE_ERROR;
    }

    return ncvStat;
}

//===================================================================
//
// NCVMemStackAllocator class members implementation
//
//===================================================================

NCVMemStackAllocator::NCVMemStackAllocator(Ncv32u alignment_) :
    _memType(NCVMemoryTypeNone),
    _alignment(alignment_),
    allocBegin(NULL),
    begin(NULL),
    end(NULL),
    currentSize(0),
    _maxSize(0),
    bReusesMemory(false)
{
    NcvBool bProperAlignment = (alignment_ & (alignment_ - 1)) == 0;
    ncvAssertPrintCheck(bProperAlignment, "NCVMemStackAllocator ctor:: alignment not power of 2");
}

NCVMemStackAllocator::NCVMemStackAllocator(NCVMemoryType memT, size_t capacity, Ncv32u alignment_, void *reusePtr) :
    _memType(memT),
    _alignment(alignment_),
    allocBegin(NULL),
    currentSize(0),
    _maxSize(0)
{
    NcvBool bProperAlignment = (alignment_ & (alignment_ - 1)) == 0;
    ncvAssertPrintCheck(bProperAlignment, "NCVMemStackAllocator ctor:: _alignment not power of 2");
    ncvAssertPrintCheck(memT != NCVMemoryTypeNone, "NCVMemStackAllocator ctor:: Incorrect allocator type");

    allocBegin = NULL;

    if (reusePtr == NULL && capacity != 0)
    {
        bReusesMemory = false;
        switch (memT)
        {
        case NCVMemoryTypeDevice:
            ncvAssertCUDAReturn(cudaMalloc(&allocBegin, capacity), );
            break;
        case NCVMemoryTypeHostPinned:
            ncvAssertCUDAReturn(cudaMallocHost(&allocBegin, capacity), );
            break;
        case NCVMemoryTypeHostPageable:
            allocBegin = (Ncv8u *)malloc(capacity);
            break;
        default:;
        }
    }
    else
    {
        bReusesMemory = true;
        allocBegin = (Ncv8u *)reusePtr;
    }

    if (capacity == 0)
    {
        allocBegin = (Ncv8u *)(0x1);
    }

    if (!isCounting())
    {
        begin = allocBegin;
        end = begin + capacity;
    }
}

NCVMemStackAllocator::~NCVMemStackAllocator()
{
    if (allocBegin != NULL)
    {
        ncvAssertPrintCheck(currentSize == 0, "NCVMemStackAllocator dtor:: not all objects were deallocated properly, forcing destruction");

        if (!bReusesMemory && (allocBegin != (Ncv8u *)(0x1)))
        {
            switch (_memType)
            {
            case NCVMemoryTypeDevice:
                ncvAssertCUDAReturn(cudaFree(allocBegin), );
                break;
            case NCVMemoryTypeHostPinned:
                ncvAssertCUDAReturn(cudaFreeHost(allocBegin), );
                break;
            case NCVMemoryTypeHostPageable:
                free(allocBegin);
                break;
            default:;
            }
        }

        allocBegin = NULL;
    }
}

NCVStatus NCVMemStackAllocator::alloc(NCVMemSegment &seg, size_t size)
{
    seg.clear();
    ncvAssertReturn(isInitialized(), NCV_ALLOCATOR_BAD_ALLOC);

    size = alignUp(static_cast<Ncv32u>(size), this->_alignment);
    this->currentSize += size;
    this->_maxSize = std::max(this->_maxSize, this->currentSize);

    if (!isCounting())
    {
        size_t availSize = end - begin;
        ncvAssertReturn(size <= availSize, NCV_ALLOCATOR_INSUFFICIENT_CAPACITY);
    }

    seg.begin.ptr = begin;
    seg.begin.memtype = this->_memType;
    seg.size = size;
    begin += size;

    return NCV_SUCCESS;
}

NCVStatus NCVMemStackAllocator::dealloc(NCVMemSegment &seg)
{
    ncvAssertReturn(isInitialized(), NCV_ALLOCATOR_BAD_ALLOC);
    ncvAssertReturn(seg.begin.memtype == this->_memType, NCV_ALLOCATOR_BAD_DEALLOC);
    ncvAssertReturn(seg.begin.ptr != NULL || isCounting(), NCV_ALLOCATOR_BAD_DEALLOC);
    ncvAssertReturn(seg.begin.ptr == begin - seg.size, NCV_ALLOCATOR_DEALLOC_ORDER);

    currentSize -= seg.size;
    begin -= seg.size;

    seg.clear();

    ncvAssertReturn(allocBegin <= begin, NCV_ALLOCATOR_BAD_DEALLOC);

    return NCV_SUCCESS;
}

NcvBool NCVMemStackAllocator::isInitialized(void) const
{
    return (((this->_alignment & (this->_alignment-1)) == 0) && isCounting()) || this->allocBegin != NULL;
}

NcvBool NCVMemStackAllocator::isCounting(void) const
{
    return this->_memType == NCVMemoryTypeNone;
}

NCVMemoryType NCVMemStackAllocator::memType(void) const
{
    return this->_memType;
}

Ncv32u NCVMemStackAllocator::alignment(void) const
{
    return this->_alignment;
}

size_t NCVMemStackAllocator::maxSize(void) const
{
    return this->_maxSize;
}

//===================================================================
//
// NCVMemNativeAllocator class members implementation
//
//===================================================================

NCVMemNativeAllocator::NCVMemNativeAllocator(NCVMemoryType memT, Ncv32u alignment_) :
    _memType(memT),
    _alignment(alignment_),
    currentSize(0),
    _maxSize(0)
{
    ncvAssertPrintReturn(memT != NCVMemoryTypeNone, "NCVMemNativeAllocator ctor:: counting not permitted for this allocator type", );
}

NCVMemNativeAllocator::~NCVMemNativeAllocator()
{
    ncvAssertPrintCheck(currentSize == 0, "NCVMemNativeAllocator dtor:: detected memory leak");
}

NCVStatus NCVMemNativeAllocator::alloc(NCVMemSegment &seg, size_t size)
{
    seg.clear();
    ncvAssertReturn(isInitialized(), NCV_ALLOCATOR_BAD_ALLOC);

    switch (this->_memType)
    {
    case NCVMemoryTypeDevice:
        ncvAssertCUDAReturn(cudaMalloc(&seg.begin.ptr, size), NCV_CUDA_ERROR);
        break;
    case NCVMemoryTypeHostPinned:
        ncvAssertCUDAReturn(cudaMallocHost(&seg.begin.ptr, size), NCV_CUDA_ERROR);
        break;
    case NCVMemoryTypeHostPageable:
        seg.begin.ptr = (Ncv8u *)malloc(size);
        break;
    default:;
    }

    this->currentSize += alignUp(static_cast<Ncv32u>(size), this->_alignment);
    this->_maxSize = std::max(this->_maxSize, this->currentSize);

    seg.begin.memtype = this->_memType;
    seg.size = size;

    return NCV_SUCCESS;
}

NCVStatus NCVMemNativeAllocator::dealloc(NCVMemSegment &seg)
{
    ncvAssertReturn(isInitialized(), NCV_ALLOCATOR_BAD_ALLOC);
    ncvAssertReturn(seg.begin.memtype == this->_memType, NCV_ALLOCATOR_BAD_DEALLOC);
    ncvAssertReturn(seg.begin.ptr != NULL, NCV_ALLOCATOR_BAD_DEALLOC);

    ncvAssertReturn(currentSize >= alignUp(static_cast<Ncv32u>(seg.size), this->_alignment), NCV_ALLOCATOR_BAD_DEALLOC);
    currentSize -= alignUp(static_cast<Ncv32u>(seg.size), this->_alignment);

    switch (this->_memType)
    {
    case NCVMemoryTypeDevice:
        ncvAssertCUDAReturn(cudaFree(seg.begin.ptr), NCV_CUDA_ERROR);
        break;
    case NCVMemoryTypeHostPinned:
        ncvAssertCUDAReturn(cudaFreeHost(seg.begin.ptr), NCV_CUDA_ERROR);
        break;
    case NCVMemoryTypeHostPageable:
        free(seg.begin.ptr);
        break;
    default:;
    }

    seg.clear();

    return NCV_SUCCESS;
}

NcvBool NCVMemNativeAllocator::isInitialized(void) const
{
    return (this->_alignment != 0);
}

NcvBool NCVMemNativeAllocator::isCounting(void) const
{
    return false;
}

NCVMemoryType NCVMemNativeAllocator::memType(void) const
{
    return this->_memType;
}

Ncv32u NCVMemNativeAllocator::alignment(void) const
{
    return this->_alignment;
}

size_t NCVMemNativeAllocator::maxSize(void) const
{
    return this->_maxSize;
}

//===================================================================
//
// Time and timer routines
//
//===================================================================

typedef struct _NcvTimeMoment NcvTimeMoment;

#if defined(_WIN32) || defined(_WIN64)

    #include BOSS_FAKEWIN_V_windows_h //original-code:<Windows.h>

    typedef struct _NcvTimeMoment
    {
        LONGLONG moment, freq;
    } NcvTimeMoment;

    static void _ncvQueryMoment(NcvTimeMoment *t)
    {
        QueryPerformanceFrequency((LARGE_INTEGER *)&(t->freq));
        QueryPerformanceCounter((LARGE_INTEGER *)&(t->moment));
    }

    double _ncvMomentToMicroseconds(NcvTimeMoment *t)
    {
        return 1000000.0 * t->moment / t->freq;
    }

    double _ncvMomentsDiffToMicroseconds(NcvTimeMoment *t1, NcvTimeMoment *t2)
    {
        return 1000000.0 * 2 * ((t2->moment) - (t1->moment)) / (t1->freq + t2->freq);
    }

    double _ncvMomentsDiffToMilliseconds(NcvTimeMoment *t1, NcvTimeMoment *t2)
    {
        return 1000.0 * 2 * ((t2->moment) - (t1->moment)) / (t1->freq + t2->freq);
    }

#elif defined(__GNUC__)

    #include <sys/time.h>

    typedef struct _NcvTimeMoment
    {
        struct timeval tv;
        struct timezone tz;
    } NcvTimeMoment;

    void _ncvQueryMoment(NcvTimeMoment *t)
    {
        gettimeofday(& t->tv, & t->tz);
    }

    double _ncvMomentToMicroseconds(NcvTimeMoment *t)
    {
        return 1000000.0 * t->tv.tv_sec + (double)t->tv.tv_usec;
    }

    double _ncvMomentsDiffToMicroseconds(NcvTimeMoment *t1, NcvTimeMoment *t2)
    {
        return (((double)t2->tv.tv_sec - (double)t1->tv.tv_sec) * 1000000 + (double)t2->tv.tv_usec - (double)t1->tv.tv_usec);
    }

    double _ncvMomentsDiffToMilliseconds(NcvTimeMoment *t1, NcvTimeMoment *t2)
    {
        return ((double)t2->tv.tv_sec - (double)t1->tv.tv_sec) * 1000;
    }

#endif //#if defined(_WIN32) || defined(_WIN64)

struct _NcvTimer
{
    NcvTimeMoment t1, t2;
};

NcvTimer ncvStartTimer(void)
{
    struct _NcvTimer *t;
    t = (struct _NcvTimer *)malloc(sizeof(struct _NcvTimer));
    _ncvQueryMoment(&t->t1);
    return t;
}

double ncvEndQueryTimerUs(NcvTimer t)
{
    double res;
    _ncvQueryMoment(&t->t2);
    res = _ncvMomentsDiffToMicroseconds(&t->t1, &t->t2);
    free(t);
    return res;
}

double ncvEndQueryTimerMs(NcvTimer t)
{
    double res;
    _ncvQueryMoment(&t->t2);
    res = _ncvMomentsDiffToMilliseconds(&t->t1, &t->t2);
    free(t);
    return res;
}

//===================================================================
//
// Operations with rectangles
//
//===================================================================

struct RectConvert
{
    cv::Rect operator()(const NcvRect32u& nr) const { return cv::Rect(nr.x, nr.y, nr.width, nr.height); }
    NcvRect32u operator()(const cv::Rect& nr) const
    {
        NcvRect32u rect;
        rect.x = nr.x;
        rect.y = nr.y;
        rect.width = nr.width;
        rect.height = nr.height;
        return rect;
    }
};

static void groupRectangles(std::vector<NcvRect32u> &hypotheses, int groupThreshold, double eps, std::vector<Ncv32u> *weights)
{
#ifndef HAVE_OPENCV_OBJDETECT
    (void) hypotheses;
    (void) groupThreshold;
    (void) eps;
    (void) weights;
    CV_Error(cv::Error::StsNotImplemented, "This functionality requires objdetect module");
#else
    std::vector<cv::Rect> rects(hypotheses.size());
    std::transform(hypotheses.begin(), hypotheses.end(), rects.begin(), RectConvert());

    if (weights)
    {
        std::vector<int> weights_int;
        weights_int.assign(weights->begin(), weights->end());
        cv::groupRectangles(rects, weights_int, groupThreshold, eps);
    }
    else
    {
        cv::groupRectangles(rects, groupThreshold, eps);
    }
    std::transform(rects.begin(), rects.end(), hypotheses.begin(), RectConvert());
    hypotheses.resize(rects.size());
#endif
}

NCVStatus ncvGroupRectangles_host(NCVVector<NcvRect32u> &hypotheses,
                                  Ncv32u &numHypotheses,
                                  Ncv32u minNeighbors,
                                  Ncv32f intersectEps,
                                  NCVVector<Ncv32u> *hypothesesWeights)
{
    ncvAssertReturn(hypotheses.memType() == NCVMemoryTypeHostPageable ||
                    hypotheses.memType() == NCVMemoryTypeHostPinned, NCV_MEM_RESIDENCE_ERROR);
    if (hypothesesWeights != NULL)
    {
        ncvAssertReturn(hypothesesWeights->memType() == NCVMemoryTypeHostPageable ||
                        hypothesesWeights->memType() == NCVMemoryTypeHostPinned, NCV_MEM_RESIDENCE_ERROR);
    }

    if (numHypotheses == 0)
    {
        return NCV_SUCCESS;
    }

    std::vector<NcvRect32u> rects(numHypotheses);
    memcpy(&rects[0], hypotheses.ptr(), numHypotheses * sizeof(NcvRect32u));

    std::vector<Ncv32u> weights;
    if (hypothesesWeights != NULL)
    {
        groupRectangles(rects, minNeighbors, intersectEps, &weights);
    }
    else
    {
        groupRectangles(rects, minNeighbors, intersectEps, NULL);
    }

    numHypotheses = (Ncv32u)rects.size();
    if (numHypotheses > 0)
    {
        memcpy(hypotheses.ptr(), &rects[0], numHypotheses * sizeof(NcvRect32u));
    }

    if (hypothesesWeights != NULL)
    {
        memcpy(hypothesesWeights->ptr(), &weights[0], numHypotheses * sizeof(Ncv32u));
    }

    return NCV_SUCCESS;
}

template <class T>
static NCVStatus drawRectsWrapperHost(T *h_dst,
                                      Ncv32u dstStride,
                                      Ncv32u dstWidth,
                                      Ncv32u dstHeight,
                                      NcvRect32u *h_rects,
                                      Ncv32u numRects,
                                      T color)
{
    ncvAssertReturn(h_dst != NULL && h_rects != NULL, NCV_NULL_PTR);
    ncvAssertReturn(dstWidth > 0 && dstHeight > 0, NCV_DIMENSIONS_INVALID);
    ncvAssertReturn(dstStride >= dstWidth, NCV_INVALID_STEP);
    ncvAssertReturn(numRects != 0, NCV_SUCCESS);
    ncvAssertReturn(numRects <= dstWidth * dstHeight, NCV_DIMENSIONS_INVALID);

    for (Ncv32u i=0; i<numRects; i++)
    {
        NcvRect32u rect = h_rects[i];

        if (rect.x < dstWidth)
        {
            for (Ncv32u each=rect.y; each<rect.y+rect.height && each<dstHeight; each++)
            {
                h_dst[each*dstStride+rect.x] = color;
            }
        }
        if (rect.x+rect.width-1 < dstWidth)
        {
            for (Ncv32u each=rect.y; each<rect.y+rect.height && each<dstHeight; each++)
            {
                h_dst[each*dstStride+rect.x+rect.width-1] = color;
            }
        }
        if (rect.y < dstHeight)
        {
            for (Ncv32u j=rect.x; j<rect.x+rect.width && j<dstWidth; j++)
            {
                h_dst[rect.y*dstStride+j] = color;
            }
        }
        if (rect.y + rect.height - 1 < dstHeight)
        {
            for (Ncv32u j=rect.x; j<rect.x+rect.width && j<dstWidth; j++)
            {
                h_dst[(rect.y+rect.height-1)*dstStride+j] = color;
            }
        }
    }

    return NCV_SUCCESS;
}

NCVStatus ncvDrawRects_8u_host(Ncv8u *h_dst,
                               Ncv32u dstStride,
                               Ncv32u dstWidth,
                               Ncv32u dstHeight,
                               NcvRect32u *h_rects,
                               Ncv32u numRects,
                               Ncv8u color)
{
    return drawRectsWrapperHost(h_dst, dstStride, dstWidth, dstHeight, h_rects, numRects, color);
}

NCVStatus ncvDrawRects_32u_host(Ncv32u *h_dst,
                                Ncv32u dstStride,
                                Ncv32u dstWidth,
                                Ncv32u dstHeight,
                                NcvRect32u *h_rects,
                                Ncv32u numRects,
                                Ncv32u color)
{
    return drawRectsWrapperHost(h_dst, dstStride, dstWidth, dstHeight, h_rects, numRects, color);
}


text:
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */

#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4X3/include/IfcGlobalOrLocalEnum.h"

// TYPE IfcGlobalOrLocalEnum = ENUMERATION OF	(GLOBAL_COORDS	,LOCAL_COORDS);
shared_ptr<BuildingObject> IFC4X3::IfcGlobalOrLocalEnum::getDeepCopy( BuildingCopyOptions& options )
{
	shared_ptr<IfcGlobalOrLocalEnum> copy_self( new IfcGlobalOrLocalEnum() );
	copy_self->m_enum = m_enum;
	return copy_self;
}
void IFC4X3::IfcGlobalOrLocalEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
	if( is_select_type ) { stream << "IFCGLOBALORLOCALENUM("; }
	switch( m_enum )
	{
		case ENUM_GLOBAL_COORDS:	stream << ".GLOBAL_COORDS."; break;
		case ENUM_LOCAL_COORDS:	stream << ".LOCAL_COORDS."; break;
	}
	if( is_select_type ) { stream << ")"; }
}
shared_ptr<IFC4X3::IfcGlobalOrLocalEnum> IFC4X3::IfcGlobalOrLocalEnum::createObjectFromSTEP( const std::string& arg, const std::map<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream )
{
	if( arg.compare( "$" ) == 0 ) { return shared_ptr<IfcGlobalOrLocalEnum>(); }
	if( arg.compare( "*" ) == 0 ) { return shared_ptr<IfcGlobalOrLocalEnum>(); }
	shared_ptr<IfcGlobalOrLocalEnum> type_object( new IfcGlobalOrLocalEnum() );
	if( std_iequal( arg, ".GLOBAL_COORDS." ) )
	{
		type_object->m_enum = IfcGlobalOrLocalEnum::ENUM_GLOBAL_COORDS;
	}
	else if( std_iequal( arg, ".LOCAL_COORDS." ) )
	{
		type_object->m_enum = IfcGlobalOrLocalEnum::ENUM_LOCAL_COORDS;
	}
	return type_object;
}


text:
<?php

require APPPATH . 'libraries/REST_Controller.php';

class Certificates_ws extends REST_Controller {

	public function  __construct(){
		parent::__construct();
	}

	public function operadores_get(){

	    $clave_tercero = $this->get('clave_tercero');
	    $this->load->model('Operador','operador_model');

	    $operador = $this->operador_model->get_operador_by_clave_tercero($clave_tercero);

	    $this->response($operador, 200);

	}
	public function operadores_by_id_oc_get(){

	    $id_oc = $this->get('id_oc');
	    $this->load->model('Operador','operador_model');

	    $operador = $this->operador_model->get_list_operador_by_idorganismo_certificacion($id_oc);

	    $this->response($operador, 200);

	}
}


text:
@class OWBaseLineItem;
@class OWLineLikeItem;
@class OWLineCommentItem;
@interface OWTimeLineVC : OWBaseTimeLineVC

@property (nonatomic, strong) NSMutableArray *items;

@property (nonatomic, strong) NSMutableDictionary *itemDic;

@property (nonatomic, strong) NSMutableDictionary *commentDic;

//添加到末尾
-(void) addItem:(OWBaseLineItem *) item;

//添加到头部
-(void) addItemTop:(OWBaseLineItem *) item;

//根据ID删除
-(void) deleteItem:(long long) itemId;

//赞
-(void) addLikeItem:(OWLineLikeItem *) likeItem itemId:(long long) itemId;

//评论
-(void) addCommentItem:(OWLineCommentItem *) commentItem itemId:(long long) itemId replyCommentId:(long long) replyCommentId;

//发送图文
-(void)onSendTextImage:(NSString *)text images:(NSArray *)images;

//发送视频消息
-(void)onSendVideo:(NSString *)text videoPath:(NSString *)videoPath screenShot:(UIImage *) screenShot;

@end


text:
namespace Bletchley.Enigma.Simulator
{
    public interface IReflector
    {
        Letters GetOutput(Letters input);
    }
}


text:
Long Running Tests
==================

This directory contains the long-running workloads which are intended to run
forever until they fail. To set up the project you need to run

.. code-block:: bash

    $ pip install anyscale
    $ anyscale init

Note that all the long running test is running inside virtual environment, tensorflow_p36

Running the Workloads
---------------------
The easiest approach to running these workloads is to use the
`Releaser`_ tool to run them with the command
``python cli.py suite:run long_running_tests``. By default, this
will start a session to run each workload in the Anyscale product
and kick them off.

To run the tests manually, you can also use the `Anyscale UI <https://www.anyscale.dev/>`. First run ``anyscale snapshot create`` from the command line to create a project snapshot. Then from the UI, you can launch an individual session and execute the run command for each test.

You can also start the workloads using the CLI with:

.. code-block:: bash

    $ anyscale start
    $ anyscale run test_workload --workload=<WORKLOAD_NAME> --wheel=<RAY_WHEEL_LINK>

Doing this for each workload will start one EC2 instance per workload and will start the workloads
running (one per instance). A list of
available workload options is available in the `ray_projects/project.yaml` file.

Debugging
---------
The primary method to debug the test while it is running is to view the logs and the dashboard from the UI. After the test has failed, you can still view the stdout logs in the UI and also inspect
the logs under ``/tmp/ray/session*/logs/`` and
``/tmp/ray/session*/debug_state.txt``.

.. To check up on the workloads, run either
.. ``anyscale session --name="*" execute check-load``, which
.. will print the load on each machine, or
.. ``anyscale session --name="*" execute show-output``, which
.. will print the tail of the output for each workload.

Shut Down the Workloads
-----------------------

The instances running the workloads can all be killed by running
``anyscale stop <SESSION_NAME>``.

Adding a Workload
-----------------

To create a new workload, simply add a new Python file under ``workloads/`` and
add the workload in the run command in `ray-project/project.yaml`.

.. _`Releaser`: https://github.com/ray-project/releaser


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

<title>D-Index</title>
<meta name="date" content="2014-10-26">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G H I L M N P R S T V W

D

decide() - Method in class com.technipun.dc.algorithm.ElectionProcessNode

Decide action for election process.

decide() - Method in class com.technipun.dc.algorithm.WaveProcessNode

Decide action for wave process.

deffuse() - Method in class com.technipun.dc.algorithm.WaveProcessNode

Deffuse action for wave process

doElectionStep() - Method in class com.technipun.dc.algorithm.ElectionProcessNode

Executes the election process step.

doProcess(Message) - Method in class com.technipun.dc.algorithm.ElectionProcessNode

Do process.

doProcess(Message) - Method in class com.technipun.dc.algorithm.WaveProcessNode

Do process.

doWaveStep() - Method in class com.technipun.dc.algorithm.WaveProcessNode

Executes the wave step.

A C D E F G H I L M N P R S T V W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php

namespace MB\SecureDisplayBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * @link http://symfony.com/doc/current/cookbook/bundles/extension.html
 */
class MBSecureDisplayExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('mb_secure_display.key', $config['key']);
        $container->setParameter('mb_secure_display.template', $config['template']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}


text:
/**
 *
 */
package coza.opencollab.unipoole.service.synch.so;

import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.annotate.JsonIgnore;

import coza.opencollab.unipoole.service.ServiceObject;

/**
 * @author Opencollab
 *
 */
public class SyncContentMapping extends ServiceObject{

	private static final long serialVersionUID = -5635053599802562621L;

	/**
	 * List of mappings for ids in the requested tool.
	 */
	private Map<String, Map<String, String>> toolMappings = new HashMap<String, Map<String, String>>();

	/**
	 * Mapping for the first group version for a tool.
	 */
	private Map<String, String> versionMappings = new HashMap<String, String>();

	/**
	 * @return the mappings
	 */
	public Map<String, Map<String, String>> getMappings() {
		return toolMappings;
	}

	/**
	 *
	 * @return
	 */
	public Map<String, String> getVersions(){
		return versionMappings;
	}

	/**
	 * @param mappings the mappings to set
	 */
	public void addMapping(ToolMapping mapping) {
		this.toolMappings.put(mapping.getToolId(), mapping.getMappings());
	}

	/**
	 *
	 * @param toolname
	 * @param version
	 */
	public void addContentVersion(String toolname, String version){
		this.versionMappings.put(toolname, version);
	}

	/**
	 * Class representing the mappings for a tool
	 */
	public static class ToolMapping{
		private String toolId;
		private Map<String, String> mappings;

		public ToolMapping(String toolId, Map<String, String> mappings){
			this.toolId = toolId;
			this.mappings = mappings;
		}

		/**
		 * @return the mappings
		 */
		public Map<String, String> getMappings() {
			return this.mappings;
		}

		public String getToolId(){
			return this.toolId;
		}

		@JsonIgnore
		public boolean isEmpty(){
			return this.mappings.isEmpty();
		}
	}
}


text:
Плагин для обхода игроков на сервере (Да, именно тот, который стоит у Мэла на сабсервере уже 3 года) 🤹

## Команды
- /detour start
  - Начинает обход на сервере
- /detour stop
  - Заканчивает обход
- /detour join
  - Присоединиться к обходу
- /detour next
  - Перейти к следующему игроку
- /detour stick
  - Выдает палочку для управления обходом (ЛКМ — телепорт к текущему игроку, ПКМ - к следующему)
- /detour party add <username>
  - Добавляет игрока в команду для обхода
- /detour list
  - Получить список игроков, участвующих в обходе

## Настройки

- allowOffline (по-умолчанию включено) разрешает вход в обход до его начала
- hoursToAllowDetour (по-умолчанию 0) миниальное количество часов, чтобы войти в обход
- partyGameMode (по-умолчанию 3) gamemod участников команды обхода (см. ```/detour party add```)

## Связь со мной

* [Telegram](https://t.me/swiftstranger) (@SwiftStranger)
* [VK](https://vk.com/iosif_p)


text:
import re

from c7n.utils import local_session
from c7n_gcp.provider import resources
from c7n_gcp.query import QueryResourceManager, TypeInfo, ChildResourceManager, ChildTypeInfo, \
    GcpLocation

@resources.register('kms-keyring')
class KmsKeyRing(QueryResourceManager):

    class resource_type(TypeInfo):
        service = 'cloudkms'
        version = 'v1'
        component = 'projects.locations.keyRings'
        enum_spec = ('list', 'keyRings[]', None)
        scope = None
        name = id = 'name'
        default_report_fields = [
            "name", "createTime"]
        asset_type = "cloudkms.googleapis.com/KeyRing"

        @staticmethod
        def get(client, resource_info):
            name = 'projects/{}/locations/{}/keyRings/{}' \
                .format(resource_info['project_id'],
                        resource_info['location'],
                        resource_info['key_ring_id'])
            return client.execute_command('get', {'name': name})

    def get_resource_query(self):
        if 'query' in self.data:
            for child in self.data.get('query'):
                if 'location' in child:
                    location_query = child['location']
                    return {'parent': location_query if isinstance(
                        location_query, list) else [location_query]}

    def _fetch_resources(self, query):
        super_fetch_resources = QueryResourceManager._fetch_resources
        session = local_session(self.session_factory)
        project = session.get_default_project()
        locations = (query['parent'] if query and 'parent' in query
                     else GcpLocation.get_service_locations('kms'))
        project_locations = ['projects/{}/locations/{}'.format(project, location)
                             for location in locations]
        key_rings = []
        for location in project_locations:
            key_rings.extend(super_fetch_resources(self, {'parent': location}))
        return key_rings

@resources.register('kms-cryptokey')
class KmsCryptoKey(ChildResourceManager):
    """GCP Resource
    https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys
    """
    def _get_parent_resource_info(self, child_instance):
        project_id, location, key_ring_id = re.match(
            'projects/(.*?)/locations/(.*?)/keyRings/(.*?)/cryptoKeys/.*',
            child_instance['name']).groups()
        return {'project_id': project_id,
                'location': location,
                'key_ring_id': key_ring_id}

    def get_resource_query(self):
        """Does nothing as self does not need query values unlike its parent
        which receives them with the use_child_query flag."""
        pass

    class resource_type(ChildTypeInfo):
        service = 'cloudkms'
        version = 'v1'
        component = 'projects.locations.keyRings.cryptoKeys'
        enum_spec = ('list', 'cryptoKeys[]', None)
        scope = None
        name = id = 'name'
        default_report_fields = [
            name, "purpose", "createTime", "nextRotationTime", "rotationPeriod"]
        parent_spec = {
            'resource': 'kms-keyring',
            'child_enum_params': [
                ('name', 'parent')
            ],
            'use_child_query': True
        }
        asset_type = "cloudkms.googleapis.com/CryptoKey"

        @staticmethod
        def get(client, resource_info):
            name = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}' \
                .format(resource_info['project_id'],
                        resource_info['location'],
                        resource_info['key_ring_id'],
                        resource_info['crypto_key_id'])
            return client.execute_command('get', {'name': name})

@resources.register('kms-cryptokey-version')
class KmsCryptoKeyVersion(ChildResourceManager):
    """GCP Resource
    https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions
    """
    def _get_parent_resource_info(self, child_instance):
        path = 'projects/(.*?)/locations/(.*?)/keyRings/(.*?)/cryptoKeys/(.*?)/cryptoKeyVersions/.*'
        project_id, location, key_ring_id, crypto_key_id = \
            re.match(path, child_instance['name']).groups()
        return {'project_id': project_id,
                'location': location,
                'key_ring_id': key_ring_id,
                'crypto_key_id': crypto_key_id}

    def get_resource_query(self):
        """Does nothing as self does not need query values unlike its parent
        which receives them with the use_child_query flag."""
        pass

    class resource_type(ChildTypeInfo):
        service = 'cloudkms'
        version = 'v1'
        component = 'projects.locations.keyRings.cryptoKeys.cryptoKeyVersions'
        enum_spec = ('list', 'cryptoKeyVersions[]', None)
        scope = None
        name = id = 'name'
        default_report_fields = [
            "name", "state", "protectionLevel", "algorithm", "createTime", "destroyTime"]
        parent_spec = {
            'resource': 'kms-cryptokey',
            'child_enum_params': [
                ('name', 'parent')
            ],
            'use_child_query': True
        }
        asset_type = "cloudkms.googleapis.com/CryptoKeyVersion"

        @staticmethod
        def get(client, resource_info):
            name = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}/cryptoKeyVersions/{}'\
                .format(resource_info['project_id'],
                        resource_info['location'],
                        resource_info['key_ring_id'],
                        resource_info['crypto_key_id'],
                        resource_info['crypto_key_version_id'])
            return client.execute_command('get', {'name': name})


text:
using System.Threading.Tasks;
using CSC.CSClassroom.Model.Assignments;
using CSC.CSClassroom.Model.Assignments.ServiceResults;
using CSC.CSClassroom.Service.Assignments.QuestionGraders;
using CSC.CSClassroom.Service.UnitTests.TestDoubles;
using CSC.CSClassroom.Service.UnitTests.Utilities;
using Xunit;

namespace CSC.CSClassroom.Service.UnitTests.Assignments.QuestionGraders
{
	/// <summary>
	/// Unit tests for the ShortAnswerQuestionGrader class.
	/// </summary>
	public class ShortAnswerQuestionGrader_UnitTests
	{
		/// <summary>
		/// Ensures that full credit is received for having all correct answers.
		/// </summary>
		[Fact]
		public async Task GradeSubmissionAsync_AllBlanksCorrect_FullCredit()
		{
			var question = new ShortAnswerQuestion()
			{
				Blanks = Collections.CreateList
				(
					new ShortAnswerQuestionBlank() { Name = "A", Answer = "One" },
					new ShortAnswerQuestionBlank() { Name = "B", Answer = "Two" }
				)
			};

			var submission = new ShortAnswerQuestionSubmission()
			{
				Blanks = Collections.CreateList
				(
					new SubmissionBlank() { Name = "A", Answer = "One" },
					new SubmissionBlank() { Name = "B", Answer = "Two" }
				)
			};

			var grader = new ShortAnswerQuestionGrader(question);
			var result = await grader.GradeSubmissionAsync(submission);

			Assert.Equal(new[] { true, true }, ((ShortAnswerQuestionResult)result.Result).Correct);
			Assert.Equal(1.0, result.Score);
		}

		/// <summary>
		/// Ensures that no credit is received for having some incorrect answers,
		/// when the question does not offer partial credit.
		/// </summary>
		[Fact]
		public async Task GradeSubmissionAsync_SomeBlanksIncorrect_NoCredit()
		{
			var question = new ShortAnswerQuestion()
			{
				AllowPartialCredit = false,
				Blanks = Collections.CreateList
				(
					new ShortAnswerQuestionBlank() { Name = "A", Answer = "One" },
					new ShortAnswerQuestionBlank() { Name = "B", Answer = "Two" }
				)
			};

			var submission = new ShortAnswerQuestionSubmission()
			{
				Blanks = Collections.CreateList
				(
					new SubmissionBlank() { Name = "A", Answer = "One" },
					new SubmissionBlank() { Name = "B", Answer = "Wrong" }
				)
			};

			var grader = new ShortAnswerQuestionGrader(question);
			var result = await grader.GradeSubmissionAsync(submission);

			Assert.Equal(new[] { true, false }, ((ShortAnswerQuestionResult)result.Result).Correct);
			Assert.Equal(0.0, result.Score);
		}

		/// <summary>
		/// Ensures that some credit is received for having a mix of correct answers
		/// and incorrect answers, when the question offers partial credit.
		/// </summary>
		[Fact]
		public async Task GradeSubmissionAsync_SomeBlanksIncorrect_PartialCredit()
		{
			var question = new ShortAnswerQuestion()
			{
				AllowPartialCredit = true,
				Blanks = Collections.CreateList
				(
					new ShortAnswerQuestionBlank() { Name = "A", Answer = "One" },
					new ShortAnswerQuestionBlank() { Name = "B", Answer = "Two" }
				)
			};

			var submission = new ShortAnswerQuestionSubmission()
			{
				Blanks = Collections.CreateList
				(
					new SubmissionBlank() { Name = "A", Answer = "One" },
					new SubmissionBlank() { Name = "B", Answer = "Wrong" }
				)
			};

			var grader = new ShortAnswerQuestionGrader(question);
			var result = await grader.GradeSubmissionAsync(submission);

			Assert.Equal(new[] { true, false }, ((ShortAnswerQuestionResult)result.Result).Correct);
			Assert.Equal(0.5, result.Score);
		}

		/// <summary>
		/// Non-ajax submissions will submit carriage returns instead of newlines. This test
		/// ensures that we correctly handle submissions with blank names containing carriage
		/// returns.
		/// </summary>
		[Fact]
		public async Task GradeSubmissionAsync_BlankNamesContainCarriageReturns_ParsedCorrectly()
		{
			var question = new ShortAnswerQuestion()
			{
				Blanks = Collections.CreateList
				(
					new ShortAnswerQuestionBlank() { Name = "A\n", Answer = "One" }
				)
			};

			var submission = new ShortAnswerQuestionSubmission()
			{
				Blanks = Collections.CreateList
				(
					new SubmissionBlank() { Name = "A\r\n", Answer = "One" }
				)
			};

			var grader = new ShortAnswerQuestionGrader(question);
			var result = await grader.GradeSubmissionAsync(submission);

			Assert.Equal(new[] { true }, ((ShortAnswerQuestionResult)result.Result).Correct);
			Assert.Equal(1.0, result.Score);
		}
	}
}


text:
This project is a tool to work with Electron Spectroscopy measurement data.
This means visualization, simulation, parameter fitting, etc.


text:
import java.util.Scanner;

/**
 * Created by Nasko on 17.12.2016 г..
 */
public class p04_ConcatenateData {
    public static void main(String[] args){
        Scanner a = new Scanner(System.in);
        String Fname = a.nextLine();
        String Lname = a.nextLine();
        int age = Integer.parseInt(a.nextLine());
        String Town = a.nextLine();

        System.out.print("You are " + Fname + " " + Lname + ", a " + age +"-years old person from " + Town + ".");
    }
}


text:
'use strict';

const splitBody = require('../lib/split_body');

describe('splitBody()', () => {
  it('should return an object with all contents if no sections were found', () => {
    const body = 'The body of the file';
    const result = splitBody(body);

    expect(result).toEqual({content: body});
  });

  it('should be able to handle a file with only one section', () => {
    const section1 = 'This is the first section';
    const body = `
        ---section1---
        ${section1}
    `;
    const result = splitBody(body);

    expect(result.section1.indexOf(section1)).not.toBe(-1);
  });

  it('should be able to handle files with multiple sections', () => {
    const section1 = 'This is the first section';
    const section2 = 'This is the second section';
    const body = `
        ---section1---
        ${section1}

        ---section2---
        ${section2}
    `;
    const result = splitBody(body);

    expect(result.section1.indexOf(section1)).not.toBe(-1);
    expect(result.section1.indexOf(section2)).toBe(-1);
    expect(result.section2.indexOf(section1)).toBe(-1);
    expect(result.section2.indexOf(section2)).not.toBe(-1);
  });

  it('should be able to handle a custom splitter', () => {
    const section1 = 'This is the first section';
    const section2 = 'This is the second section';
    const body = `
        ===section1===
        ${section1}

        ===section2===
        ${section2}
    `;
    const result = splitBody(body, /===(.*)===/g);

    expect(result.section1.indexOf(section1)).not.toBe(-1);
    expect(result.section1.indexOf(section2)).toBe(-1);
    expect(result.section2.indexOf(section1)).toBe(-1);
    expect(result.section2.indexOf(section2)).not.toBe(-1);
  });

  it('should work when the content contains the word "undefined"', () => {
    const section1 = 'This section contains undefined';
    const section2 = 'This section does not contain undefined';

    const body = `
        ---section1---
        ${section1}

        ---section2---
        ${section2}
    `;
    const result = splitBody(body);

    expect(result.section1.indexOf(section1)).not.toBe(-1);
    expect(result.section1.indexOf(section2)).toBe(-1);
    expect(result.section2.indexOf(section1)).toBe(-1);
    expect(result.section2.indexOf(section2)).not.toBe(-1);
  });
});


text:
'use strict';

angular.module('dreFrontend.mocks')
  .service('dreFrontendNotesMocks', function ($log, $q, $rootScope, $httpBackend,_) {
    return function () {
      $log.debug('start configure notes mocks');
      var notesList = [{
        "_id": "55e3e903e770ae4417ddbd0f",
        "username": "isabella",
        "section": "medications",
        "entry": "55dfdf19e770ae4417ddbc20",
        "note": "asssssssss",
        "__v": 0,
        "star": true,
        "datetime": "2015-08-31T05:41:23.141Z"
      }, {
        "_id": "55e40cfae770ae4417ddbd11",
        "username": "isabella",
        "section": "medications",
        "entry": "55dfdf18e770ae4417ddbbfd",
        "note": "Notew",
        "__v": 0,
        "star": false,
        "datetime": "2015-08-31T08:37:35.512Z"
      }];
      //getAllNotes
      $httpBackend.whenGET('mock/notes/all').respond(function (method, url, data) {
        return [200, notesList, {}];
      });
      //addNewNote
      $httpBackend.whenPOST('mock/notes/add').respond(function (method, url, data) {
        var params = angular.fromJson(data);
        var newNote = {
          "_id": new Date().toString(),
          "username": "isabella",
          "section": params.section,
          "entry": params.entry,
          "note": params.note,
          "__v": 0,
          "star": params.star,
          "datetime": new Date().toISOString()
        };
        notesList.push(newNote);
        return [200, newNote, {}];
      });
      //editNote
      $httpBackend.whenPOST('mock/notes/edit').respond(function (method, url, data) {
        var params = angular.fromJson(data);
        var note = _.find(notesList, {_id: params.id});
        note.note = params.note;
        note.datetime = new Date().toISOString();
        return [200, note, {}];
      });
      //editNote
      $httpBackend.whenPOST('mock/notes/star').respond(function (method, url, data) {
        var params = angular.fromJson(data);
        var note = _.find(notesList, {_id: params.id});
        note.star = params.star;
        note.datetime = new Date().toISOString();
        return [200, note, {}];
      });
      //deleteNote
      $httpBackend.whenPOST('mock/notes/delete').respond(function (method, url, data) {
        var params = angular.fromJson(data);
        _.remove(notesList, {_id: params.id});
        return [200, {}, {}];
      });
    }
  });


text:
from koheron import command

class Laser(object):

    def __init__(self, client):
        self.client = client

    @command()
    def start(self):
        pass

    @command()
    def stop(self):
        pass

    @command()
    def get_measured_power(self):
        return self.client.recv_float()

    @command()
    def get_measured_current(self):
        return self.client.recv_float()

    @command()
    def set_current(self, current):
        ''' Laser current in mA '''
        pass

    @command(classname='Eeprom', funcname='write')
    def write_eeprom(self, address, value):
        pass

    @command(classname='Eeprom', funcname='read')
    def read_eeprom(self, address):
        return self.client.recv_uint32()


text:
public function index()
{
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';

        $this->load->view('templates/header', $data);
        $this->load->view('news/index', $data);
        $this->load->view('templates/footer');
}


text:
package com.fluxchess.jcpi.internal.x88;

import com.fluxchess.jcpi.models.GenericCastling;

/**
 * This class encodes castling information as an int value. The data is
 * encoded as follows:

 *

 * Bit 0 - 1: the castling (required)

 */
final class Castling {

	public static final int MASK = 0x3;

	public static final int KINGSIDE = 0;
	public static final int QUEENSIDE = 1;
	public static final int NOCASTLING = 2;

	public static final int[] values = {
			KINGSIDE, QUEENSIDE
	};

	private Castling() {
	}

	public static int valueOf(GenericCastling genericCastling) {
		if (genericCastling == null) throw new IllegalArgumentException();

		switch (genericCastling) {
			case KINGSIDE:
				return KINGSIDE;
			case QUEENSIDE:
				return QUEENSIDE;
			default:
				throw new IllegalArgumentException();
		}
	}

	public static GenericCastling toGenericCastling(int castling) {
		switch (castling) {
			case KINGSIDE:
				return GenericCastling.KINGSIDE;
			case QUEENSIDE:
				return GenericCastling.QUEENSIDE;
			case NOCASTLING:
			default:
				throw new IllegalArgumentException();
		}
	}

	public static boolean isValid(int castling) {
		switch (castling) {
			case KINGSIDE:
			case QUEENSIDE:
				return true;
			case NOCASTLING:
				return false;
			default:
				throw new IllegalArgumentException();
		}
	}

}


text:
package us.kbase.cdmientityapi;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 *
Original spec-file type: fields_ExperimentalUnitGroup

 *
 *
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
    "id",
    "source_id",
    "name",
    "comments",
    "groupType"
})
public class FieldsExperimentalUnitGroup {

    @JsonProperty("id")
    private String id;
    @JsonProperty("source_id")
    private String sourceId;
    @JsonProperty("name")
    private String name;
    @JsonProperty("comments")
    private String comments;
    @JsonProperty("groupType")
    private String groupType;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("id")
    public String getId() {
        return id;
    }

    @JsonProperty("id")
    public void setId(String id) {
        this.id = id;
    }

    public FieldsExperimentalUnitGroup withId(String id) {
        this.id = id;
        return this;
    }

    @JsonProperty("source_id")
    public String getSourceId() {
        return sourceId;
    }

    @JsonProperty("source_id")
    public void setSourceId(String sourceId) {
        this.sourceId = sourceId;
    }

    public FieldsExperimentalUnitGroup withSourceId(String sourceId) {
        this.sourceId = sourceId;
        return this;
    }

    @JsonProperty("name")
    public String getName() {
        return name;
    }

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

    public FieldsExperimentalUnitGroup withName(String name) {
        this.name = name;
        return this;
    }

    @JsonProperty("comments")
    public String getComments() {
        return comments;
    }

    @JsonProperty("comments")
    public void setComments(String comments) {
        this.comments = comments;
    }

    public FieldsExperimentalUnitGroup withComments(String comments) {
        this.comments = comments;
        return this;
    }

    @JsonProperty("groupType")
    public String getGroupType() {
        return groupType;
    }

    @JsonProperty("groupType")
    public void setGroupType(String groupType) {
        this.groupType = groupType;
    }

    public FieldsExperimentalUnitGroup withGroupType(String groupType) {
        this.groupType = groupType;
        return this;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperties(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    @Override
    public String toString() {
        return ((((((((((((("FieldsExperimentalUnitGroup"+" [id=")+ id)+", sourceId=")+ sourceId)+", name=")+ name)+", comments=")+ comments)+", groupType=")+ groupType)+", additionalProperties=")+ additionalProperties)+"]");
    }

}


text:
var nodemailer = require('nodemailer'),
  path = require('path'),
  templatesDir = path.join(__dirname, '../public/templates'),
  emailTemplates = require('email-templates'),
  Promise = require("bluebird"),
  config = require("../config/config");

module.exports = function(to, text) {
  return new Promise(function(resolve, reject) {
    var transporter = nodemailer.createTransport();
    transporter.sendMail({
      from: config.email,
      to: to,
      subject: 'Report',
      text: text
    }, function(err, result) {
      if (err) reject(err);
      resolve("Mail Sent");
    });
  });
}


text:
import { Contact, ContactType } from "../../server/schema/Contact";
import Keyword from "../../server/schema/keywords";

const person: Contact = {
  name: "Norbert de Langen",
  about: "Maintainer of Storybook, love open source and donuts",
  image: {
    url: "people/norbert.jpg",
  },
  social: {
    homepage: "",
    twitter: "norbertdelangen",
    github: "ndelangen",
    facebook: "",
    medium: "",
    instagram: "",
    linkedin: "",
    youtube: "",
    devto: "",
  },
  location: {
    country: {
      name: "Netherlands",
      code: "NL",
    },
    city: "Zwolle",
  },
  keywords: [Keyword.REACT],
  type: [ContactType.SPEAKER],
};

export default person;


text:
#ifndef _DVBCA_H_
#define _DVBCA_H_
typedef struct ca_slot_info {
  int num;
  int type;
#define CA_CI 1
#define CA_CI_LINK 2
#define CA_CI_PHYS 4
#define CA_DESCR 8
#define CA_SC 128
  unsigned int flags;
#define CA_CI_MODULE_PRESENT 1
#define CA_CI_MODULE_READY 2
} ca_slot_info_t;
typedef struct ca_descr_info {
  unsigned int num;
  unsigned int type;
#define CA_ECD 1
#define CA_NDS 2
#define CA_DSS 4
} ca_descr_info_t;
typedef struct ca_caps {
  unsigned int slot_num;
  unsigned int slot_type;
  unsigned int descr_num;
  unsigned int descr_type;
} ca_caps_t;
typedef struct ca_msg {
  unsigned int index;
  unsigned int type;
  unsigned int length;
  unsigned char msg[256];
} ca_msg_t;
typedef struct ca_descr {
  unsigned int index;
  unsigned int parity;
  unsigned char cw[8];
} ca_descr_t;
typedef struct ca_pid {
  unsigned int pid;
  int index;
} ca_pid_t;
#define CA_RESET _IO('o', 128)
#define CA_GET_CAP _IOR('o', 129, ca_caps_t)
#define CA_GET_SLOT_INFO _IOR('o', 130, ca_slot_info_t)
#define CA_GET_DESCR_INFO _IOR('o', 131, ca_descr_info_t)
#define CA_GET_MSG _IOR('o', 132, ca_msg_t)
#define CA_SEND_MSG _IOW('o', 133, ca_msg_t)
#define CA_SET_DESCR _IOW('o', 134, ca_descr_t)
#define CA_SET_PID _IOW('o', 135, ca_pid_t)
#endif


text:
import { PropTypes } from 'react'
import { connect } from 'react-redux'
import ClientLayout from '../Layout/ClientLayout'
import Teleprompter from '../Teleprompter/Teleprompter'
import TimeDisplay from '../TimeDisplay/TimeDisplay'

function getState (state) {
  return {
    display: state.display,
    percentComplete: state.clock.percentComplete
  }
}

const ClientHandler = (props) => (
  <ClientLayout percentComplete={props.percentComplete}>
    <TimeDisplay {...props.display}/>
    <Teleprompter text={props.display.teleprompter}/>
  </ClientLayout>
)

ClientHandler.propTypes = {
  display: PropTypes.object,
  percentComplete: PropTypes.number
}

export default connect(getState)(ClientHandler)


text:
    {% if hide %}×{% endif %}

{% block modal-header %}{% endblock %}

  {% if table %}

  {{ table.render }}

  {% endif %}
  <form id="{% block form_id %}{% endblock %}"
        ng-controller="{% block ng_controller %}DummyCtrl{% endblock %}"
        name="{% block form_name %}{% endblock %}"
        autocomplete="{% block autocomplete %}{% if form.no_autocomplete %}off{% endif %}{% endblock %}"
        class="{% block form_class %}{% endblock %}"
        action="{% block form_action %}{% endblock %}"
        method="{% block form-method %}POST{% endblock %}"
        {% if add_to_field %}data-add-to-field="{{ add_to_field }}"{% endif %} {% block form_attrs %}{% endblock %}>{% csrf_token %}

    {% comment %}
    These fake fields are required to prevent Chrome v34+ from autofilling form.
    {% endcomment %}
    {% if form.no_autocomplete %}
    <input type="text" name="fake_email" value="" style="display: none" />
    <input type="password" name="fake_password" value="" style="display: none" />
    {% endif %}
    {% block modal-body %}
        <fieldset>
        {% include "horizon/common/_form_fields.html" %}
        </fieldset>
    {% endblock %}

{% block modal-footer %}{% endblock %}

  </form>

{% block modal-js %}
{% endblock %}


text:
import {NumberFormatStyle, NumberSymbol, getLocaleNumberFormat, getLocaleNumberSymbol, getNumberOfCurrencyDigits} from './locale_data_api';

export const NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
const MAX_DIGITS = 22;
const DECIMAL_SEP = '.';
const ZERO_CHAR = '0';
const PATTERN_SEP = ';';
const GROUP_SEP = ',';
const DIGIT_CHAR = '#';
const CURRENCY_CHAR = '¤';
const PERCENT_CHAR = '%';

/**
 * Transforms a number to a locale string based on a style and a format.
 */
function formatNumberToLocaleString(
    value: number, pattern: ParsedNumberFormat, locale: string, groupSymbol: NumberSymbol,
    decimalSymbol: NumberSymbol, digitsInfo?: string, isPercent = false): string {
  let formattedText = '';
  let isZero = false;

  if (!isFinite(value)) {
    formattedText = getLocaleNumberSymbol(locale, NumberSymbol.Infinity);
  } else {
    let parsedNumber = parseNumber(value);

    if (isPercent) {
      parsedNumber = toPercent(parsedNumber);
    }

    let minInt = pattern.minInt;
    let minFraction = pattern.minFrac;
    let maxFraction = pattern.maxFrac;

    if (digitsInfo) {
      const parts = digitsInfo.match(NUMBER_FORMAT_REGEXP);
      if (parts === null) {
        throw new Error(`${digitsInfo} is not a valid digit info`);
      }
      const minIntPart = parts[1];
      const minFractionPart = parts[3];
      const maxFractionPart = parts[5];
      if (minIntPart != null) {
        minInt = parseIntAutoRadix(minIntPart);
      }
      if (minFractionPart != null) {
        minFraction = parseIntAutoRadix(minFractionPart);
      }
      if (maxFractionPart != null) {
        maxFraction = parseIntAutoRadix(maxFractionPart);
      } else if (minFractionPart != null && minFraction > maxFraction) {
        maxFraction = minFraction;
      }
    }

    roundNumber(parsedNumber, minFraction, maxFraction);

    let digits = parsedNumber.digits;
    let integerLen = parsedNumber.integerLen;
    const exponent = parsedNumber.exponent;
    let decimals = [];
    isZero = digits.every(d => !d);

    // pad zeros for small numbers
    for (; integerLen < minInt; integerLen++) {
      digits.unshift(0);
    }

    // pad zeros for small numbers
    for (; integerLen < 0; integerLen++) {
      digits.unshift(0);
    }

    // extract decimals digits
    if (integerLen > 0) {
      decimals = digits.splice(integerLen, digits.length);
    } else {
      decimals = digits;
      digits = [0];
    }

    // format the integer digits with grouping separators
    const groups = [];
    if (digits.length >= pattern.lgSize) {
      groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
    }

    while (digits.length > pattern.gSize) {
      groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
    }

    if (digits.length) {
      groups.unshift(digits.join(''));
    }

    formattedText = groups.join(getLocaleNumberSymbol(locale, groupSymbol));

    // append the decimal digits
    if (decimals.length) {
      formattedText += getLocaleNumberSymbol(locale, decimalSymbol) + decimals.join('');
    }

    if (exponent) {
      formattedText += getLocaleNumberSymbol(locale, NumberSymbol.Exponential) + '+' + exponent;
    }
  }

  if (value < 0 && !isZero) {
    formattedText = pattern.negPre + formattedText + pattern.negSuf;
  } else {
    formattedText = pattern.posPre + formattedText + pattern.posSuf;
  }

  return formattedText;
}

/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a number as currency using locale rules.
 *
 * @param value The number to format.
 * @param locale A locale code for the locale format rules to use.
 * @param currency A string containing the currency symbol or its name,
 * such as "$" or "Canadian Dollar". Used in output string, but does not affect the operation
 * of the function.
 * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)
 * currency code, such as `USD` for the US dollar and `EUR` for the euro.
 * Used to determine the number of digits in the decimal part.
 * @param digitInfo Decimal representation options, specified by a string in the following format:
 * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
 *
 * @returns The formatted currency value.
 *
 * @see `formatNumber()`
 * @see `DecimalPipe`
 * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
 *
 * @publicApi
 */
export function formatCurrency(
    value: number, locale: string, currency: string, currencyCode?: string,
    digitsInfo?: string): string {
  const format = getLocaleNumberFormat(locale, NumberFormatStyle.Currency);
  const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));

  pattern.minFrac = getNumberOfCurrencyDigits(currencyCode !);
  pattern.maxFrac = pattern.minFrac;

  const res = formatNumberToLocaleString(
      value, pattern, locale, NumberSymbol.CurrencyGroup, NumberSymbol.CurrencyDecimal, digitsInfo);
  return res
      .replace(CURRENCY_CHAR, currency)
      // if we have 2 time the currency character, the second one is ignored
      .replace(CURRENCY_CHAR, '');
}

/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a number as a percentage according to locale rules.
 *
 * @param value The number to format.
 * @param locale A locale code for the locale format rules to use.
 * @param digitInfo Decimal representation options, specified by a string in the following format:
 * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
 *
 * @returns The formatted percentage value.
 *
 * @see `formatNumber()`
 * @see `DecimalPipe`
 * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
 * @publicApi
 *
 */
export function formatPercent(value: number, locale: string, digitsInfo?: string): string {
  const format = getLocaleNumberFormat(locale, NumberFormatStyle.Percent);
  const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  const res = formatNumberToLocaleString(
      value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo, true);
  return res.replace(
      new RegExp(PERCENT_CHAR, 'g'), getLocaleNumberSymbol(locale, NumberSymbol.PercentSign));
}

/**
 * @ngModule CommonModule
 * @description
 *
 * Formats a number as text, with group sizing, separator, and other
 * parameters based on the locale.
 *
 * @param value The number to format.
 * @param locale A locale code for the locale format rules to use.
 * @param digitInfo Decimal representation options, specified by a string in the following format:
 * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details.
 *
 * @returns The formatted text string.
 * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
 *
 * @publicApi
 */
export function formatNumber(value: number, locale: string, digitsInfo?: string): string {
  const format = getLocaleNumberFormat(locale, NumberFormatStyle.Decimal);
  const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
  return formatNumberToLocaleString(
      value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo);
}

interface ParsedNumberFormat {
  minInt: number;
  // the minimum number of digits required in the fraction part of the number
  minFrac: number;
  // the maximum number of digits required in the fraction part of the number
  maxFrac: number;
  // the prefix for a positive number
  posPre: string;
  // the suffix for a positive number
  posSuf: string;
  // the prefix for a negative number (e.g. `-` or `(`))
  negPre: string;
  // the suffix for a negative number (e.g. `)`)
  negSuf: string;
  // number of digits in each group of separated digits
  gSize: number;
  // number of digits in the last group of digits before the decimal separator
  lgSize: number;
}

function parseNumberFormat(format: string, minusSign = '-'): ParsedNumberFormat {
  const p = {
    minInt: 1,
    minFrac: 0,
    maxFrac: 0,
    posPre: '',
    posSuf: '',
    negPre: '',
    negSuf: '',
    gSize: 0,
    lgSize: 0
  };

  const patternParts = format.split(PATTERN_SEP);
  const positive = patternParts[0];
  const negative = patternParts[1];

  const positiveParts = positive.indexOf(DECIMAL_SEP) !== -1 ?
      positive.split(DECIMAL_SEP) :
      [
        positive.substring(0, positive.lastIndexOf(ZERO_CHAR) + 1),
        positive.substring(positive.lastIndexOf(ZERO_CHAR) + 1)
      ],
        integer = positiveParts[0], fraction = positiveParts[1] || '';

  p.posPre = integer.substr(0, integer.indexOf(DIGIT_CHAR));

  for (let i = 0; i < fraction.length; i++) {
    const ch = fraction.charAt(i);
    if (ch === ZERO_CHAR) {
      p.minFrac = p.maxFrac = i + 1;
    } else if (ch === DIGIT_CHAR) {
      p.maxFrac = i + 1;
    } else {
      p.posSuf += ch;
    }
  }

  const groups = integer.split(GROUP_SEP);
  p.gSize = groups[1] ? groups[1].length : 0;
  p.lgSize = (groups[2] || groups[1]) ? (groups[2] || groups[1]).length : 0;

  if (negative) {
    const trunkLen = positive.length - p.posPre.length - p.posSuf.length,
          pos = negative.indexOf(DIGIT_CHAR);

    p.negPre = negative.substr(0, pos).replace(/'/g, '');
    p.negSuf = negative.substr(pos + trunkLen).replace(/'/g, '');
  } else {
    p.negPre = minusSign + p.posPre;
    p.negSuf = p.posSuf;
  }

  return p;
}

interface ParsedNumber {
  // an array of digits containing leading zeros as necessary
  digits: number[];
  // the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  exponent: number;
  // the number of the digits in `d` that are to the left of the decimal point
  integerLen: number;
}

// Transforms a parsed number into a percentage by multiplying it by 100
function toPercent(parsedNumber: ParsedNumber): ParsedNumber {
  // if the number is 0, don't do anything
  if (parsedNumber.digits[0] === 0) {
    return parsedNumber;
  }

  // Getting the current number of decimals
  const fractionLen = parsedNumber.digits.length - parsedNumber.integerLen;
  if (parsedNumber.exponent) {
    parsedNumber.exponent += 2;
  } else {
    if (fractionLen === 0) {
      parsedNumber.digits.push(0, 0);
    } else if (fractionLen === 1) {
      parsedNumber.digits.push(0);
    }
    parsedNumber.integerLen += 2;
  }

  return parsedNumber;
}

/**
 * Parses a number.
 * Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/
 */
function parseNumber(num: number): ParsedNumber {
  let numStr = Math.abs(num) + '';
  let exponent = 0, digits, integerLen;
  let i, j, zeros;

  // Decimal point?
  if ((integerLen = numStr.indexOf(DECIMAL_SEP)) > -1) {
    numStr = numStr.replace(DECIMAL_SEP, '');
  }

  // Exponential form?
  if ((i = numStr.search(/e/i)) > 0) {
    // Work out the exponent.
    if (integerLen < 0) integerLen = i;
    integerLen += +numStr.slice(i + 1);
    numStr = numStr.substring(0, i);
  } else if (integerLen < 0) {
    // There was no decimal point or exponent so it is an integer.
    integerLen = numStr.length;
  }

  // Count the number of leading zeros.
  for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */
  }

  if (i === (zeros = numStr.length)) {
    // The digits are all zero.
    digits = [0];
    integerLen = 1;
  } else {
    // Count the number of trailing zeros
    zeros--;
    while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;

    // Trailing zeros are insignificant so ignore them
    integerLen -= i;
    digits = [];
    // Convert string to array of digits without leading/trailing zeros.
    for (j = 0; i <= zeros; i++, j++) {
      digits[j] = Number(numStr.charAt(i));
    }
  }

  // If the number overflows the maximum allowed digits then use an exponent.
  if (integerLen > MAX_DIGITS) {
    digits = digits.splice(0, MAX_DIGITS - 1);
    exponent = integerLen - 1;
    integerLen = 1;
  }

  return {digits, exponent, integerLen};
}

/**
 * Round the parsed number to the specified number of decimal places
 * This function changes the parsedNumber in-place
 */
function roundNumber(parsedNumber: ParsedNumber, minFrac: number, maxFrac: number) {
  if (minFrac > maxFrac) {
    throw new Error(
        `The minimum number of digits after fraction (${minFrac}) is higher than the maximum (${maxFrac}).`);
  }

  let digits = parsedNumber.digits;
  let fractionLen = digits.length - parsedNumber.integerLen;
  const fractionSize = Math.min(Math.max(minFrac, fractionLen), maxFrac);

  // The index of the digit to where rounding is to occur
  let roundAt = fractionSize + parsedNumber.integerLen;
  let digit = digits[roundAt];

  if (roundAt > 0) {
    // Drop fractional digits beyond `roundAt`
    digits.splice(Math.max(parsedNumber.integerLen, roundAt));

    // Set non-fractional digits beyond `roundAt` to 0
    for (let j = roundAt; j < digits.length; j++) {
      digits[j] = 0;
    }
  } else {
    // We rounded to zero so reset the parsedNumber
    fractionLen = Math.max(0, fractionLen);
    parsedNumber.integerLen = 1;
    digits.length = Math.max(1, roundAt = fractionSize + 1);
    digits[0] = 0;
    for (let i = 1; i < roundAt; i++) digits[i] = 0;
  }

  if (digit >= 5) {
    if (roundAt - 1 < 0) {
      for (let k = 0; k > roundAt; k--) {
        digits.unshift(0);
        parsedNumber.integerLen++;
      }
      digits.unshift(1);
      parsedNumber.integerLen++;
    } else {
      digits[roundAt - 1]++;
    }
  }

  // Pad out with zeros to get the required fraction length
  for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);

  let dropTrailingZeros = fractionSize !== 0;
  // Minimal length = nb of decimals required + current nb of integers
  // Any number besides that is optional and can be removed if it's a trailing 0
  const minLen = minFrac + parsedNumber.integerLen;
  // Do any carrying, e.g. a digit was rounded up to 10
  const carry = digits.reduceRight(function(carry, d, i, digits) {
    d = d + carry;
    digits[i] = d < 10 ? d : d - 10;  // d % 10
    if (dropTrailingZeros) {
      // Do not keep meaningless fractional trailing zeros (e.g. 15.52000 --> 15.52)
      if (digits[i] === 0 && i >= minLen) {
        digits.pop();
      } else {
        dropTrailingZeros = false;
      }
    }
    return d >= 10 ? 1 : 0;  // Math.floor(d / 10);
  }, 0);
  if (carry) {
    digits.unshift(carry);
    parsedNumber.integerLen++;
  }
}

export function parseIntAutoRadix(text: string): number {
  const result: number = parseInt(text);
  if (isNaN(result)) {
    throw new Error('Invalid integer literal when parsing ' + text);
  }
  return result;
}