text:
Ni - a minimalistic Node framework that makes setting up an MVC project a breeze
================================================================================

Ni helps you set up a well-organized project, with a file structure separated into models, views, controllers, libraries and helpers. It's intuitive and simple to use, and doesn't get in the way of using other modules and Node plugins in your project.

Ni is inspired by [CodeIgniter](http://codeigniter.com/), and its name is an abbreviation of NodeIgniter.

What's awesome about Ni?
---------------------------

* It's packaged as a regular Node module, so you just `require` it and you're ready to go
* You can use other Node modules and Connect middle-ware as you usually would; Ni doesn't get in the way
* It's easy to use and loads your models, views, controllers, libraries and helpers automatically so you can just start using them everywhere

How do I use Ni?
-------------------

It's as simple as telling Ni where to look for your files, and then asking it to boot:

    var Ni = require('../lib/ni');

    Ni.config('root', "myapp/src");

    Ni.boot(function() {
        // Ready to start the server!
    });

The rest of your code now has access to all your models, views, and controllers with `Ni.model('MODELNAME')`, `Ni.view('VIEWNAME')` and `Ni.controller('CONTROLLERNAME')`.

Note that your controllers, models, libraries and helpers should be packaged as Node modules, and your views can be plain text, template (Markdown, Mustache, etc), or HTML files.

You even get a router for free!
-------------------------------

Ni provides a router you can use with Connect to have requests sent to the appropriate controller functions according to URL segments.

Use it with Connect:

    var app = Connect.createServer(
        Ni.router
        // You can add other Connect middle-ware here
    );

It parses the URL and sends the request to the correct controller function as follows:

    http://myapp.com/[controller]/[function]/[argument 1]/[argument 2]/[etc]

If no controller is specified (`http://myapp.com/`), it loads the `home` controller's `index` function.

If no function is specified (http://yourapp.com/[controller]), it loads the `[controller]`'s `index` function.

You can define custom routes using `Ni.addRoute(source, destination, [method])`

Some examples:

With this custom route calling `myapp.com` will internally redirect to use your `News` controller and call the `index` function on it:

    Ni.addRoute('/', '/News/index');

You can use regular expressions as well. This leads `myapp.com/register` to your `User` controller and its `register` function:

    Ni.addRoute(/^\/register/i, '/User/register');

If you want to use arguments with custom routes, you can do that as well:

    Ni.addRoute(/^\/details\/(.*)$/i, '/User/details/$1');

You can also define functions to test the path. For example:

Calling `myapp.com/add/1/2` will internally redirect to use the `Number` controller and call the `positive` function, while calling
`myapp.com/add/1/-2` will call the `negative` function.

    Ni.addRoute(function(path) {
        var args = path.split('/'),
        firstNum = parseInt(args[2]),
        secondNum = parseInt(args[3]),
        result = firstNum + secondNum;
        if (args[1] !== 'add')
            return false; // this leaves the path untouched and prevents this function from sucking in all other requests as well
        return result > 0 ? '/Number/positive' : '/Number/negative';
    });

You can limit the allowed HTTP methods by using custom routes.
This will internally redirect `myapp.com/comment` to use your `Comments` controler and its `new` function - but only if the used HTTP Method is `POST` or `PUT`:

    Ni.addRoute('/comment', '/Comments/new', ['POST', 'PUT']);

And this will redirect all `GET` requests to myapp.com/comment to use your `Comments` controller's `index` function.

    Ni.addRoute('/comment', '/Comments/', 'GET');

This way you can disallow methods for some routes as well:

    Ni.addRoute('/Comments/update', '/Home/method_not_allowed', 'GET');

Can I see an example?
---------------------

If you have your project organized like this:

    /app.js
    /controllers
        /calculator.js
        /home.js
    /views
        /calculator.html
        /home.html
    /models
        /calculator.js

You can access your stuff with:

* `Ni.controller('calculator')`
* `Ni.view('calculator')`
* `Ni.model('calculator')`

A really well-commented example is in the source code in the `/example` folder, check it out!

(Note that you'll need the following to run the example in the `/example` folder: [Connect](https://github.com/senchalabs/Connect), [Quip](https://github.com/caolan/quip) and [Mu](https://github.com/raycmorgan/Mu). You can get them easily using [npm](https://github.com/isaacs/npm).)

How would my controllers, models, libraries, helpers look?
-------------------------------------------------------

Each of those is just a Node module. For example, the calculator controller mentioned above (in the `/example` folder) looks like this:

    var Ni = require('../../lib/ni'),
        Mu = require('mu'),
        Quip = require('quip');

    var CalculatorController = function() {

        /*
         *  This function is called when the URL does not indicate a function to
         *  be called, so it would look like /calculator.
         */

        this.index = function(req, res, next) {

            res.ok('Welcome to the calculator!');

        }

        /*
         *  This function is called when the URL indicates "add" as the function
         *  to be called, so it would look like /calculator/add.
         *
         *  For example, loading the URL /calculator/add/4/5 would call the below
         *  function with a = 4 and b = 5.
         */

        this.add = function(req, res, next, a, b) {

            if (a && b) {
                a = parseInt(a);
                b = parseInt(b);

                var template = Ni.view('calculator').template;
                var data = {result: a + b};

                var compiled = Mu.compileText(template, null);
                compiled(data).addListener('data', function (c) {
                    res.ok(c);
                });
            }
            else {
                res.error("a and b must both be provided.");
            }

        }

    };

    module.exports = new CalculatorController();

Let's get crackin'!
-------------------

1. Get Ni by downloading the source code, or `git clone`ing the repo.
2. Install Ni as your would any other Node module, by copying `lib/ni.js` to your `~/.node_libraries` folder.
3. Copy the `/example` directory and modify it to set up your project.
4. Run `node app.js` in the copied directory to start the server.

(We'll add Ni to `npm` soon, don't trip.)

Contributors
------------

A big thank you to you guys who helped (and are helping) make Ni awesome:

[Moritz Peters](https://github.com/maritz)


text:
package strategy_test

import (
	"testing"

	"zntr.io/typogenerator/mapping"
	"zntr.io/typogenerator/strategy"
)

func TestReplace(t *testing.T) {
	out, err := strategy.Replace(mapping.French).Generate("zenithar", "")
	if err != nil {
		t.Fail()
		t.Fatal("Error should not occurs !", err)
	}

	if len(out) == 0 {
		t.FailNow()
	}

	if len(out) != 41 {
		t.FailNow()
	}
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import division
"""Defines a Client class that can be used to communicate with the
Server class defined in server.py.

The client will connect to the port specified in the environment
variable PYSYN_PORT. If this variable is not set, it will use
the default_port imported from server.py.

"""

import socket
import threading
import SocketServer
import os

from server import default_port

class Client(threading.Thread):
    def __init__(self, url, line):
        self._url = url
        self._line = line
        self._port = int(os.environ.get('PYSYN_PORT',default_port))
        print "Client will use url, port (%s,%s)"%(self._url,self._port)
        threading.Thread.__init__(self)

    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self._url,self._port))
        hr= "\n==============================================\n"
        print hr,"Client connected to server.  "
        sock.sendall(self._line)
        print "Client sent:  ", self._line
        self._response = sock.recv(8192)
        print "%s Client sent: %s \n Client received: %s"%(hr,self._line,
                                                           self._response)
        sock.close()


text:
import * as React from 'react';
import { MenuItem } from '../menuitem/MenuItem';

type SlideMenuAppendToType = 'self' | HTMLElement | undefined | null;

export interface SlideMenuProps {
    id?: string;
    model?: MenuItem[];
    popup?: boolean;
    style?: object;
    className?: string;
    easing?: string;
    effectDuration?: number;
    backLabel?: string;
    menuWidth?: number;
    viewportHeight?: number;
    autoZIndex?: boolean;
    baseZIndex?: number;
    appendTo?: SlideMenuAppendToType;
    transitionOptions?: object;
    onShow?(e: React.SyntheticEvent): void;
    onHide?(e: React.SyntheticEvent): void;
}

export declare class SlideMenu extends React.Component<SlideMenuProps, any> {
    public show(event: React.SyntheticEvent): void;
    public hide(event: React.SyntheticEvent): void;
    public toggle(event: React.SyntheticEvent): void;
}


text:
/***************************************************************************//**
 * @file
 * @brief Analog Comparator (ACMP) Peripheral API
 * @author Energy Micro AS
 * @version 3.0.0
 *******************************************************************************
 * @section License
 * <b>(C) Copyright 2012 Energy Micro AS, http://www.energymicro.com</b>
 *******************************************************************************
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 *
 * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Energy Micro AS has no
 * obligation to support this Software. Energy Micro AS is providing the
 * Software "AS IS", with no express or implied warranties of any kind,
 * including, but not limited to, any implied warranties of merchantability
 * or fitness for any particular purpose or warranties against infringement
 * of any proprietary rights of a third party.
 *
 * Energy Micro AS will not be liable for any consequential, incidental, or
 * special damages, or any other relief, or for any claim by any third party,
 * arising from your use of this Software.
 *
 ******************************************************************************/
#include <stdbool.h>
#include "em_acmp.h"
#include "em_bitband.h"
#include "em_assert.h"

/***************************************************************************//**
 * @addtogroup EM_Library
 * @{
 ******************************************************************************/

/***************************************************************************//**
 * @addtogroup ACMP
 * @brief Analog comparator (ACMP) Peripheral API
 * @{
 ******************************************************************************/

/*******************************************************************************
 *******************************   DEFINES   ***********************************
 ******************************************************************************/

/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */

/** Validation of ACMP register block pointer reference
 *  for assert statements. */
#if (ACMP_COUNT == 1)
#define ACMP_REF_VALID(ref)    ((ref) == ACMP0)
#elif (ACMP_COUNT == 2)
#define ACMP_REF_VALID(ref)    (((ref) == ACMP0) || ((ref) == ACMP1))
#else
#error Undefined number of analog comparators (ACMP).
#endif

/** @endcond */

/*******************************************************************************
 **************************   GLOBAL FUNCTIONS   *******************************
 ******************************************************************************/

/***************************************************************************//**
 * @brief
 *   Sets up the ACMP for use in capacative sense applications.
 *
 * @details
 *   This function sets up the ACMP for use in capacacitve sense applications.
 *   To use the capacative sense functionality in the ACMP you need to use
 *   the PRS output of the ACMP module to count the number of oscillations
 *   in the capacative sense circuit (possibly using a TIMER).
 *
 * @note
 *   A basic example of capacative sensing can be found in the STK BSP
 *   (capsense demo).
 *
 * @param[in] acmp
 *   Pointer to ACMP peripheral register block.
 *
 * @param[in] init
 *   Pointer to initialization structure used to configure ACMP for capacative
 *   sensing operation.
 ******************************************************************************/
void ACMP_CapsenseInit(ACMP_TypeDef *acmp, const ACMP_CapsenseInit_TypeDef *init)
{
  /* Make sure the module exists on the selected chip */
  EFM_ASSERT(ACMP_REF_VALID(acmp));

  /* Make sure that vddLevel is within bounds */
  EFM_ASSERT(init->vddLevel < 64);

  /* Make sure biasprog is within bounds */
  EFM_ASSERT(init->biasProg < 16);

  /* Set control register. No need to set interrupt modes */
  acmp->CTRL = (init->fullBias << _ACMP_CTRL_FULLBIAS_SHIFT)
               | (init->halfBias << _ACMP_CTRL_HALFBIAS_SHIFT)
               | (init->biasProg << _ACMP_CTRL_BIASPROG_SHIFT)
               | (init->warmTime << _ACMP_CTRL_WARMTIME_SHIFT)
               | (init->hysteresisLevel << _ACMP_CTRL_HYSTSEL_SHIFT);

  /* Select capacative sensing mode by selecting a resistor and enabling it */
  acmp->INPUTSEL = (init->resistor << _ACMP_INPUTSEL_CSRESSEL_SHIFT)
                   | ACMP_INPUTSEL_CSRESEN
                   | (init->lowPowerReferenceEnabled << _ACMP_INPUTSEL_LPREF_SHIFT)
                   | (init->vddLevel << _ACMP_INPUTSEL_VDDLEVEL_SHIFT)
                   | ACMP_INPUTSEL_NEGSEL_CAPSENSE;

  /* Enable ACMP if requested.
   * Note: BITBAND_Peripheral() function is used for setting/clearing single
   * bit peripheral register bitfields. */
  BITBAND_Peripheral(&(acmp->CTRL),
                     (uint32_t)_ACMP_CTRL_EN_SHIFT,
                     (uint32_t)init->enable);
}

/***************************************************************************//**
 * @brief
 *   Sets the ACMP channel used for capacative sensing.
 *
 * @note
 *   A basic example of capacative sensing can be found in the STK BSP
 *   (capsense demo).
 *
 * @param[in] acmp
 *   Pointer to ACMP peripheral register block.
 *
 * @param[in] channel
 *   The ACMP channel to use for capacative sensing (Possel).
 ******************************************************************************/
void ACMP_CapsenseChannelSet(ACMP_TypeDef *acmp, ACMP_Channel_TypeDef channel)
{
  /* Make sure that only external channels are used */
  EFM_ASSERT(channel < _ACMP_INPUTSEL_NEGSEL_1V25);

  /* Set channel as positive channel in ACMP */
  SET_BIT_FIELD(acmp->INPUTSEL, _ACMP_INPUTSEL_POSSEL_MASK, channel,
                _ACMP_INPUTSEL_POSSEL_SHIFT);
}

/***************************************************************************//**
 * @brief
 *   Disables the ACMP.
 *
 * @param[in] acmp
 *   Pointer to ACMP peripheral register block.
 ******************************************************************************/
void ACMP_Disable(ACMP_TypeDef *acmp)
{
  acmp->CTRL &= ~ACMP_CTRL_EN;
}

/***************************************************************************//**
 * @brief
 *   Enables the ACMP.
 *
 * @param[in] acmp
 *   Pointer to ACMP peripheral register block.
 ******************************************************************************/
void ACMP_Enable(ACMP_TypeDef *acmp)
{
  acmp->CTRL |= ACMP_CTRL_EN;
}

/***************************************************************************//**
 * @brief
 *   Reset ACMP to same state as after a HW reset.
 *
 * @note
 *   The ROUTE register is NOT reset by this function, in order to allow for
 *   centralized setup of this feature.
 *
 * @param[in] acmp
 *   Pointer to the ACMP peripheral register block.
 ******************************************************************************/
void ACMP_Reset(ACMP_TypeDef *acmp)
{
  /* Make sure the module exists on the selected chip */
  EFM_ASSERT(ACMP_REF_VALID(acmp));

  acmp->CTRL     = _ACMP_CTRL_RESETVALUE;
  acmp->INPUTSEL = _ACMP_INPUTSEL_RESETVALUE;
  acmp->IEN      = _ACMP_IEN_RESETVALUE;
  acmp->IFC      = _ACMP_IF_MASK;
}

/***************************************************************************//**
 * @brief
 *   Sets up GPIO output from the ACMP.
 *
 * @note
 *    GPIO must be enabled in the CMU before this function call, i.e.
 * @verbatim CMU_ClockEnable(cmuClock_GPIO, true); @endverbatim
 *
 * @param[in] acmp
 *   Pointer to the ACMP peripheral register block.
 *
 * @param location
 *   The pin location to use. See the datasheet for location to pin mappings.
 *
 * @param enable
 *   Enable or disable pin output.
 *
 * @param invert
 *   Invert output.
 ******************************************************************************/
void ACMP_GPIOSetup(ACMP_TypeDef *acmp, uint32_t location, bool enable, bool invert)
{
  /* Sanity checking of location */
  EFM_ASSERT(location < 4);

  /* Set GPIO inversion */
  SET_BIT_FIELD(acmp->CTRL, _ACMP_CTRL_GPIOINV_MASK, invert,
                _ACMP_CTRL_GPIOINV_SHIFT);

  acmp->ROUTE = (location << _ACMP_ROUTE_LOCATION_SHIFT)
                | (enable << _ACMP_ROUTE_ACMPPEN_SHIFT);
}

/***************************************************************************//**
 * @brief
 *   Sets which channels should be used in ACMP comparisons.
 *
 * @param[in] acmp
 *   Pointer to the ACMP peripheral register block.
 *
 * @param negSel
 *   Channel to use on the negative input to the ACMP.
 *
 * @param posSel
 *   Channel to use on the positive input to the ACMP.
 ******************************************************************************/
void ACMP_ChannelSet(ACMP_TypeDef *acmp, ACMP_Channel_TypeDef negSel,
                     ACMP_Channel_TypeDef posSel)
{
  /* Make sure that only external channels are used as ACMP positive input */
  EFM_ASSERT(posSel < _ACMP_INPUTSEL_NEGSEL_1V25);
  /* Sanity checking of ACMP negative input */
  EFM_ASSERT(negSel <= _ACMP_INPUTSEL_NEGSEL_VDD);

  acmp->INPUTSEL = (acmp->INPUTSEL & ~(_ACMP_INPUTSEL_POSSEL_MASK |
                                       _ACMP_INPUTSEL_NEGSEL_MASK))
                   | (negSel << _ACMP_INPUTSEL_NEGSEL_SHIFT)
                   | (posSel << _ACMP_INPUTSEL_POSSEL_SHIFT);
}

/***************************************************************************//**
 * @brief
 *
 *
 * @param[in] acmp
 *   Pointer to the ACMP peripheral register block.
 *
 * @param[in] init
 *   Pointer to initialization structure used to configure ACMP for capacative
 *   sensing operation.
 ******************************************************************************/
void ACMP_Init(ACMP_TypeDef *acmp, const ACMP_Init_TypeDef *init)
{
  /* Make sure the module exists on the selected chip */
  EFM_ASSERT(ACMP_REF_VALID(acmp));

  /* Make sure biasprog is within bounds */
  EFM_ASSERT(init->biasProg < 16);

  /* Set control register. No need to set interrupt modes */
  acmp->CTRL = (init->fullBias << _ACMP_CTRL_FULLBIAS_SHIFT)
               | (init->halfBias << _ACMP_CTRL_HALFBIAS_SHIFT)
               | (init->biasProg << _ACMP_CTRL_BIASPROG_SHIFT)
               | (init->interruptOnFallingEdge << _ACMP_CTRL_IFALL_SHIFT)
               | (init->interruptOnRisingEdge << _ACMP_CTRL_IRISE_SHIFT)
               | (init->warmTime << _ACMP_CTRL_WARMTIME_SHIFT)
               | (init->hysteresisLevel << _ACMP_CTRL_HYSTSEL_SHIFT)
               | (init->inactiveValue << _ACMP_CTRL_INACTVAL_SHIFT);

  acmp->INPUTSEL = (init->lowPowerReferenceEnabled << _ACMP_INPUTSEL_LPREF_SHIFT)
                   | (init->vddLevel << _ACMP_INPUTSEL_VDDLEVEL_SHIFT);

  /* Enable ACMP if requested.
   * Note: BITBAND_Peripheral() function is used for setting/clearing single
   * bit peripheral register bitfields. */
  BITBAND_Peripheral(&(acmp->CTRL),
                     (uint32_t)_ACMP_CTRL_EN_SHIFT,
                     (uint32_t)init->enable);
}

/** @} (end addtogroup ACMP) */
/** @} (end addtogroup EM_Library) */


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('seating', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Layout',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=50, verbose_name=b'title')),
                ('description', models.CharField(max_length=250, verbose_name=b'desc')),
                ('number_of_seats', models.IntegerField(verbose_name=b'number of seats')),
                ('template', models.TextField(null=True, verbose_name=b'SVG layout for seating', blank=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.RemoveField(
            model_name='seating',
            name='template',
        ),
        migrations.AddField(
            model_name='seating',
            name='layout',
            field=models.ForeignKey(blank=True, to='seating.Layout', null=True),
            preserve_default=True,
        ),
    ]


text:
package edu.psu.swe.scim.server.rest;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;

import com.fasterxml.jackson.core.JsonProcessingException;

import edu.psu.swe.scim.server.configuration.ServerConfiguration;
import edu.psu.swe.scim.server.utility.EtagGenerator;
import edu.psu.swe.scim.spec.protocol.ServiceProviderConfigResource;
import edu.psu.swe.scim.spec.protocol.data.ErrorResponse;
import edu.psu.swe.scim.spec.schema.Meta;
import edu.psu.swe.scim.spec.schema.ServiceProviderConfiguration;
import edu.psu.swe.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema;
import edu.psu.swe.scim.spec.schema.ServiceProviderConfiguration.BulkConfiguration;
import edu.psu.swe.scim.spec.schema.ServiceProviderConfiguration.FilterConfiguration;
import edu.psu.swe.scim.spec.schema.ServiceProviderConfiguration.SupportedConfiguration;

@Stateless
public class ServiceProviderConfigResourceImpl implements ServiceProviderConfigResource {

  @Inject
  ServerConfiguration serverConfiguration;

  @Inject
  EtagGenerator etagGenerator;

  public ServiceProviderConfigResourceImpl() {
    serverConfiguration = new ServerConfiguration();
  }

  public void registerServerConfiguration(ServerConfiguration configuration) {
    serverConfiguration = configuration;
  }

  @Override
  public Response getServiceProviderConfiguration(UriInfo uriInfo) {
    ServiceProviderConfiguration serviceProviderConfiguration = new ServiceProviderConfiguration();
    List<AuthenticationSchema> authenticationSchemas = serverConfiguration.getAuthenticationSchemas();
    BulkConfiguration bulk = serverConfiguration.getBulkConfiguration();
    SupportedConfiguration changePassword = serverConfiguration.getChangePasswordConfiguration();
    SupportedConfiguration etagConfig = serverConfiguration.getEtagConfiguration();
    FilterConfiguration filter = serverConfiguration.getFilterConfiguration();
    SupportedConfiguration patch = serverConfiguration.getPatchConfiguration();
    SupportedConfiguration sort = serverConfiguration.getSortConfiguration();
    String documentationUrl = serverConfiguration.getDocumentationUri();
    String externalId = serverConfiguration.getId();
    String id = serverConfiguration.getId();
    Meta meta = new Meta();
    String location = uriInfo.getAbsolutePath().toString();
    String resourceType = "ServiceProviderConfig";
    LocalDateTime now = LocalDateTime.now();

    meta.setCreated(now);
    meta.setLastModified(now);
    meta.setLocation(location);
    meta.setResourceType(resourceType);
    serviceProviderConfiguration.setAuthenticationSchemes(authenticationSchemas);
    serviceProviderConfiguration.setBulk(bulk);
    serviceProviderConfiguration.setChangePassword(changePassword);
    serviceProviderConfiguration.setDocumentationUrl(documentationUrl);
    serviceProviderConfiguration.setEtag(etagConfig);
    serviceProviderConfiguration.setExternalId(externalId);
    serviceProviderConfiguration.setFilter(filter);
    serviceProviderConfiguration.setId(id);
    serviceProviderConfiguration.setMeta(meta);
    serviceProviderConfiguration.setPatch(patch);
    serviceProviderConfiguration.setSort(sort);

    try {
      EntityTag etag = etagGenerator.generateEtag(serviceProviderConfiguration);
      return Response.ok(serviceProviderConfiguration).tag(etag).build();
    } catch (JsonProcessingException | NoSuchAlgorithmException | UnsupportedEncodingException e) {
      return createETagErrorResponse();
    }
  }

  private Response createETagErrorResponse() {
    ErrorResponse er = new ErrorResponse(Status.INTERNAL_SERVER_ERROR, "Failed to generate the etag");
    return er.toResponse();
  }
}


text:
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkSurface.h"
#include "SkPicture.h"

static void draw_content(SkCanvas* canvas) {
    SkImageInfo info = canvas->imageInfo();
    SkPaint paint;
    paint.setAntiAlias(true);
    canvas->drawCircle(SkScalarHalf(info.width()), SkScalarHalf(info.height()),
                       SkScalarHalf(info.width()), paint);
}

class PeekPixelsGM : public skiagm::GM {
public:
    PeekPixelsGM() {}

protected:
    virtual SkString onShortName() SK_OVERRIDE {
        return SkString("peekpixels");
    }

    virtual SkISize onISize() SK_OVERRIDE {
        return SkISize::Make(360, 120);
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100);
        SkAutoTUnref<SkSurface> surface(canvas->newSurface(info));
        if (surface.get()) {
            SkCanvas* surfCanvas = surface->getCanvas();

            draw_content(surfCanvas);
            SkBitmap bitmap;

            // test peekPixels
            {
                SkImageInfo info;
                size_t rowBytes;
                const void* addr = surfCanvas->peekPixels(&info, &rowBytes);
                if (addr && bitmap.installPixels(info, const_cast<void*>(addr), rowBytes)) {
                    canvas->drawBitmap(bitmap, 0, 0, NULL);
                }
            }

            // test ROCanvasPixels
            canvas->translate(120, 0);
            SkAutoROCanvasPixels ropixels(surfCanvas);
            if (ropixels.asROBitmap(&bitmap)) {
                canvas->drawBitmap(bitmap, 0, 0, NULL);
            }

            // test Surface
            canvas->translate(120, 0);
            surface->draw(canvas, 0, 0, NULL);
        }
    }

    virtual uint32_t onGetFlags() const SK_OVERRIDE {
        // we explicitly test peekPixels and readPixels, neither of which
        // return something for a picture-backed canvas, so we skip that test.
        return kSkipPicture_Flag;
    }

private:
    typedef skiagm::GM INHERITED;
};

DEF_GM( return SkNEW(PeekPixelsGM); )


text: Ésta aplicación muestra nuemero aleatorios de 0 a 1


text:
Partial Class tools_identity
    Inherits System.Web.UI.Page

End Class


text:
var _ = require('lodash')

const commandify = (func, items, options) =>
  items.map(item => cb => func(item, options, cb))
var dryRun = require('./dry-run')
var spawnScript = require('./spawn-script')
var all = require('./all')

module.exports = function (scriptFiles, options, cb) {
  if (options.dryRun) return dryRun(scriptFiles, cb)

  var commands = commandify(spawnScript, scriptFiles, options)
  all(commands, options.parallel, function (er, codes) {
    cb(er, _.last(codes))
  })
}


text:
'use strict';

var base,
	mongoose = require('mongoose/');

function BaseModel(){ }

base = BaseModel.prototype;

/**
 * Initializes the base mongoose model
 * @param collection
 * @param schema
 */
base.init = function (collection, schema){
	this.mongooseModel = mongoose.model(collection, schema);
};

/**
 * Finds a document in the model by id
 * @param id
 * @param success
 * @param failure
 */
base.findDocumentById = function(id, success, failure) {
	this.mongooseModel.findById(id, function(err, doc) {
		if(err) {
			failure('Could not find document with specified id: ' + err);
		} else {
			success(doc);
		}
	});
};

/**
 * Finds one document based on conditions
 * @param conditions
 * @param success
 * @param failure
 */
base.findOneDocument = function(conditions, success, failure) {
	base.retrieve.bind(this)(conditions, function(docs) {
		if(docs.length === 1) {
			success(docs[0]);
		} else if(docs.length < 1) {
			failure('Error: No documents found');
		} else {
			failure('Error: More than 1 document found');
		}
	}, failure);
};

/**
 * Finds documents in a collection based on conditions specified
 * @param conditions
 * @param success
 * @param failure
 */
base.retrieve = function(conditions, success, failure) {
	this.mongooseModel.find(conditions, function(err, docs) {
		if(err) {
			failure('Retrieve: Attempt to find documents for specified conditions failed: ' + err);
		} else {
			success(docs);
		}
	});
};

/**
 * Function that updates a document in a collection.
 * @param update{Object} - Changes in document that have to be persisted
 * @param conditions{Object} - conditions to search for existing record
 * @param options
 * @param success
 * @param failure
 */
base.update = function(update, conditions, options, success, failure) {
	this.mongooseModel.findOneAndUpdate(conditions, update, options, function(err) {
		if(err) {
			failure('Update: Attempt to update failed: ' + err.message);
		} else {
			success();
		}
	});
};

/**
 * Function that inserts a document into a collection
 * @param item
 * @param success
 * @param failure
 */
base.insert = function(item, success, failure) {
	var objectToSave = base._createModelObject(this, item);
	objectToSave.save(function(err) {
		if(err) {
			failure('Insert: Attempt to save document ' + JSON.stringify(item) + ' failed: '+err);
		} else {
			success();
		}
	});
};

/**
 * Function that removes a document from a collection
 * @param item
 * @param success
 * @param failure
 */
base.remove = function(item, success, failure) {
	var objectToRemove = base._createModelObject(this, item);
	objectToRemove.remove(function(err) {
		if(err) {
			failure('Remove: Attempt to remove document ' + JSON.stringify(item) + ' failed: '+ err);
		} else {
			success();
		}
	});
};

/* Private methods */
/**
 * Function that returns a mongoose model object.
 * @param self
 * @param item
 * @returns {mongooseModel}
 * @private
 */
base._createModelObject = function(self, item) {
	return new self.mongooseModel(item);
};

exports.Model = BaseModel;


text:
namespace rocksdb {

namespace port {

WinLogger::WinLogger(uint64_t (*gettid)(), Env* env, HANDLE file,
                     const InfoLogLevel log_level)
    : Logger(log_level),
      file_(file),
      gettid_(gettid),
      log_size_(0),
      last_flush_micros_(0),
      env_(env),
      flush_pending_(false) {
  assert(file_ != NULL);
  assert(file_ != INVALID_HANDLE_VALUE);
}

void WinLogger::DebugWriter(const char* str, int len) {
  assert(file_ != INVALID_HANDLE_VALUE);
  DWORD bytesWritten = 0;
  BOOL ret = WriteFile(file_, str, len, &bytesWritten, NULL);
  if (ret == FALSE) {
    std::string errSz = GetWindowsErrSz(GetLastError());
    fprintf(stderr, errSz.c_str());
  }
}

WinLogger::~WinLogger() {
  CloseInternal();
}

Status WinLogger::CloseImpl() {
  return CloseInternal();
}

Status WinLogger::CloseInternal() {
  Status s;
  if (INVALID_HANDLE_VALUE != file_) {
    BOOL ret = FlushFileBuffers(file_);
    if (ret == 0) {
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError("Failed to flush LOG on Close() ",
        lastError);
    }
    ret = CloseHandle(file_);
    // On error the return value is zero
    if (ret == 0 && s.ok()) {
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError("Failed to flush LOG on Close() ",
        lastError);
    }
    file_ = INVALID_HANDLE_VALUE;
    closed_ = true;
  }
  return s;
}

void WinLogger::Flush() {
  assert(file_ != INVALID_HANDLE_VALUE);
  if (flush_pending_) {
    flush_pending_ = false;
    // With Windows API writes go to OS buffers directly so no fflush needed
    // unlike with C runtime API. We don't flush all the way to disk
    // for perf reasons.
  }

  last_flush_micros_ = env_->NowMicros();
}

void WinLogger::Logv(const char* format, va_list ap) {
  IOSTATS_TIMER_GUARD(logger_nanos);
  assert(file_ != INVALID_HANDLE_VALUE);

  const uint64_t thread_id = (*gettid_)();

  // We try twice: the first time with a fixed-size stack allocated buffer,
  // and the second time with a much larger dynamically allocated buffer.
  char buffer[500];
  std::unique_ptr<char[]> largeBuffer;
  for (int iter = 0; iter < 2; ++iter) {
    char* base;
    int bufsize;
    if (iter == 0) {
      bufsize = sizeof(buffer);
      base = buffer;
    } else {
      bufsize = 30000;
      largeBuffer.reset(new char[bufsize]);
      base = largeBuffer.get();
    }

    char* p = base;
    char* limit = base + bufsize;

    struct timeval now_tv;
    gettimeofday(&now_tv, nullptr);
    const time_t seconds = now_tv.tv_sec;
    struct tm t;
    localtime_s(&t, &seconds);
    p += snprintf(p, limit - p, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ",
                  t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour,
                  t.tm_min, t.tm_sec, static_cast<int>(now_tv.tv_usec),
                  static_cast<long long unsigned int>(thread_id));

    // Print the message
    if (p < limit) {
      va_list backup_ap;
      va_copy(backup_ap, ap);
      int done = vsnprintf(p, limit - p, format, backup_ap);
      if (done > 0) {
        p += done;
      } else {
        continue;
      }
      va_end(backup_ap);
    }

    // Truncate to available space if necessary
    if (p >= limit) {
      if (iter == 0) {
        continue;  // Try again with larger buffer
      } else {
        p = limit - 1;
      }
    }

    // Add newline if necessary
    if (p == base || p[-1] != '\n') {
      *p++ = '\n';
    }

    assert(p <= limit);
    const size_t write_size = p - base;

    DWORD bytesWritten = 0;
    BOOL ret = WriteFile(file_, base, static_cast<DWORD>(write_size),
      &bytesWritten, NULL);
    if (ret == FALSE) {
      std::string errSz = GetWindowsErrSz(GetLastError());
      fprintf(stderr, errSz.c_str());
    }

    flush_pending_ = true;
    assert((bytesWritten == write_size) || (ret == FALSE));
    if (bytesWritten > 0) {
      log_size_ += write_size;
    }

    uint64_t now_micros =
        static_cast<uint64_t>(now_tv.tv_sec) * 1000000 + now_tv.tv_usec;
    if (now_micros - last_flush_micros_ >= flush_every_seconds_ * 1000000) {
      flush_pending_ = false;
      // With Windows API writes go to OS buffers directly so no fflush needed
      // unlike with C runtime API. We don't flush all the way to disk
      // for perf reasons.
      last_flush_micros_ = now_micros;
    }
    break;
  }
}

size_t WinLogger::GetLogFileSize() const { return log_size_; }

}

}  // namespace rocksdb


text:
enum UMThunkStubFlags
{
    umtmlIsStatic           = 0x0001,
    umtmlThisCall           = 0x0002,
    umtmlThisCallHiddenArg  = 0x0004,
    umtmlFpu                = 0x0008,
#ifdef _TARGET_X86_
    // the signature is trivial so stub need not be generated and the target can be called directly
    umtmlSkipStub           = 0x0080,
#endif // _TARGET_X86_
};

#include <pshpack1.h>
//--------------------------------------------------------------------------
// This structure captures basic info needed to build an UMThunk.
//--------------------------------------------------------------------------
struct UMThunkStubInfo
{
    UINT32        m_cbDstStack;         //# of bytes of stack portion of managed args
    UINT16        m_cbSrcStack;         //# of bytes of stack portion of unmanaged args
    UINT16        m_cbRetPop;           //# of bytes to pop on return to unmanaged
    UINT16        m_wFlags;             // UMThunkStubFlags enum
};
#include <poppack.h>

//----------------------------------------------------------------------
// This structure collects all information needed to marshal an
// unmanaged->managed thunk. The only information missing is the
// managed target and the "this" object (if any.) Those two pieces
// are broken out into a small UMEntryThunk.
//
// The idea is to share UMThunkMarshInfo's between multiple thunks
// that have the same signature while the UMEntryThunk contains the
// minimal info needed to distinguish between actual function pointers.
//----------------------------------------------------------------------

class UMThunkMarshInfo
{
    friend class CheckAsmOffsets;

private:
    enum
    {
        kLoadTimeInited = 0x4c55544d,   //'LUTM'
        kRunTimeInited  = 0x5255544d,   //'RUTM'
    };

public:
    //----------------------------------------------------------
    // This initializer can be called during load time.
    // It does not do any ML stub initialization or sigparsing.
    // The RunTimeInit() must be called subsequently before this
    // can safely be used.
    //----------------------------------------------------------
    VOID LoadTimeInit(MethodDesc* pMD);
    VOID LoadTimeInit(Signature sig, Module * pModule, MethodDesc * pMD = NULL);

    //----------------------------------------------------------
    // This initializer finishes the init started by LoadTimeInit.
    // It does all the ML stub creation, and can throw a COM+
    // exception.
    //
    // It can safely be called multiple times and by concurrent
    // threads.
    //----------------------------------------------------------
    VOID RunTimeInit();

    // Destructor.
    //----------------------------------------------------------
    ~UMThunkMarshInfo();

    //----------------------------------------------------------
    // Accessor functions
    //----------------------------------------------------------
    Signature GetSignature()
    {
        LIMITED_METHOD_CONTRACT;
        return m_sig;
    }

    Module* GetModule()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pModule;
    }

    MethodDesc * GetMethod()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pMD;
    }

#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
    PCODE GetExecStubEntryPoint()
    {
        WRAPPER_NO_CONTRACT;
        return GetExecStub()->GetEntryPoint();
    }

    Stub* GetExecStub()
    {
        CONTRACT (Stub*)
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(IsCompletelyInited());
            POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        }
        CONTRACT_END;

        RETURN m_pExecStub;
    }

    UINT16 GetCbRetPop()
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            SUPPORTS_DAC;
            PRECONDITION(IsCompletelyInited());
        }
        CONTRACTL_END;

        return m_cbRetPop;
    }

    CorPinvokeMap GetCallingConvention()
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            SUPPORTS_DAC;
            PRECONDITION(IsCompletelyInited());
        }
        CONTRACTL_END;

        return (CorPinvokeMap)m_callConv;
    }

    VOID SetCallingConvention(const CorPinvokeMap callConv)
    {
        m_callConv = (UINT16)callConv;
    }

#else
    PCODE GetExecStubEntryPoint();
#endif

    UINT32 GetCbActualArgSize()
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(IsCompletelyInited());
        }
        CONTRACTL_END;

        return m_cbActualArgSize;
    }

    BOOL IsCompletelyInited()
    {
        LIMITED_METHOD_CONTRACT;
        return (m_pILStub != (PCODE)1);
    }

    static MethodDesc* GetILStubMethodDesc(MethodDesc* pInvokeMD, PInvokeStaticSigInfo* pSigInfo, DWORD dwStubFlags);

    static UINT32 GetOffsetOfStub()
    {
        LIMITED_METHOD_CONTRACT;
        return (UINT32)offsetof(UMThunkMarshInfo, m_pILStub);
    }

#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
    // Compiles an unmanaged to managed thunk for the given signature. The thunk
    // will call the stub or, if fNoStub == TRUE, directly the managed target.
    Stub *CompileNExportThunk(LoaderHeap *pLoaderHeap, PInvokeStaticSigInfo* pSigInfo, MetaSig *pMetaSig, BOOL fNoStub);
#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL

private:
    PCODE             m_pILStub;            // IL stub for marshaling
                                            // On x86, NULL for no-marshal signatures
                                            // On non-x86, the managed entrypoint for no-delegate no-marshal signatures
    UINT32            m_cbActualArgSize;    // caches m_pSig.SizeOfFrameArgumentArray()
#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
    Stub*             m_pExecStub;          // UMEntryThunk jumps directly here
    UINT16            m_cbRetPop;           // stack bytes popped by callee (for UpdateRegDisplay)
    UINT16            m_callConv;           // unmanaged calling convention and flags (CorPinvokeMap)
#endif
    MethodDesc *      m_pMD;                // maybe null
    Module *          m_pModule;
    Signature         m_sig;
};

//----------------------------------------------------------------------
// This structure contains the minimal information required to
// distinguish one function pointer from another, with the rest
// being stored in a shared UMThunkMarshInfo.
//
// This structure also contains the actual code bytes that form the
// front end of the thunk. A pointer to the m_code[] byte array is
// what is actually handed to unmanaged client code.
//----------------------------------------------------------------------
class UMEntryThunk
{
    friend class CheckAsmOffsets;
    friend class NDirectStubLinker;

private:
#ifdef _DEBUG
    enum
    {
        kLoadTimeInited = 0x4c554554,   //'LUET'
        kRunTimeInited  = 0x52554554,   //'RUET'
    };
#endif

public:
    static UMEntryThunk* CreateUMEntryThunk();
    static VOID FreeUMEntryThunk(UMEntryThunk* p);

#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
    // Compiles an unmanaged to managed thunk with the given calling convention adaptation.
    // - psrcofsregs are stack offsets that should be loaded to argument registers (ECX, EDX)
    // - psrcofs are stack offsets that should be repushed for the managed target
    // - retbufofs is the offset of the hidden byref structure argument when returning large
    //   structures; -1 means there is none
    // Special values recognized by psrcofsregs and psrcofs are -1 which means not present
    // and 1 which means that this register/stack slot should get the UMEntryThunk pointer.
    // This method is used for all reverse P/Invoke calls on x86 (the umtmlSkipStub
    // flag determines whether the managed target is stub or the actual target method).
    static VOID CompileUMThunkWorker(UMThunkStubInfo *pInfo,
                                     CPUSTUBLINKER *pcpusl,
                                     UINT *psrcofsregs,
                                     UINT *psrcofs,
                                     UINT retbufofs);
#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL

#ifndef DACCESS_COMPILE
    VOID LoadTimeInit(PCODE                   pManagedTarget,
                      OBJECTHANDLE            pObjectHandle,
                      UMThunkMarshInfo       *pUMThunkMarshInfo,
                      MethodDesc             *pMD,
                      ADID                    dwDomainId)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(CheckPointer(pUMThunkMarshInfo));
            PRECONDITION(pMD != NULL);
        }
        CONTRACTL_END;

        m_pManagedTarget = pManagedTarget;
        m_pObjectHandle     = pObjectHandle;
        m_pUMThunkMarshInfo = pUMThunkMarshInfo;
        m_dwDomainId        = dwDomainId;

        m_pMD = pMD;    // For debugging and profiling, so they can identify the target

        m_code.Encode((BYTE*)TheUMThunkPreStub(), this);

#ifdef _DEBUG
        m_state = kLoadTimeInited;
#endif
    }

    ~UMEntryThunk()
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
        }
        CONTRACTL_END;

        if (GetObjectHandle())
        {
            DestroyLongWeakHandle(GetObjectHandle());
        }

#ifdef _DEBUG
        FillMemory(this, sizeof(*this), 0xcc);
#endif
    }

    void Terminate();

    void OnADUnload();

    VOID RunTimeInit()
    {
        STANDARD_VM_CONTRACT;

        // Ensure method's module is activate in app domain
        m_pMD->EnsureActive();

        m_pUMThunkMarshInfo->RunTimeInit();

        // Ensure that we have either the managed target or the delegate.
        if (m_pObjectHandle == NULL && m_pManagedTarget == NULL)
            m_pManagedTarget = m_pMD->GetMultiCallableAddrOfCode();

        m_code.Encode((BYTE*)m_pUMThunkMarshInfo->GetExecStubEntryPoint(), this);

#ifdef _DEBUG
        m_state = kRunTimeInited;
#endif
    }

    // asm entrypoint
    static VOID STDCALL DoRunTimeInit(UMEntryThunk* pThis);

    PCODE GetManagedTarget() const
    {
        CONTRACT (PCODE)
        {
            THROWS;
            GC_TRIGGERS;
            MODE_ANY;
            PRECONDITION(m_state == kRunTimeInited || m_state == kLoadTimeInited);
            POSTCONDITION(RETVAL != NULL);
        }
        CONTRACT_END;

        OBJECTHANDLE hndDelegate = GetObjectHandle();
        if (hndDelegate != NULL)
        {
            GCX_COOP();

            DELEGATEREF orDelegate = (DELEGATEREF)ObjectFromHandle(hndDelegate);
            _ASSERTE(orDelegate != NULL);
            _ASSERTE(m_pMD->IsEEImpl());

            // We have optimizations that skip the Invoke method and call directly the
            // delegate's target method. We need to return the target in that case,
            // otherwise debugger would fail to step in.
            RETURN orDelegate->GetMethodPtr();
        }
        else
        {
            if (m_pManagedTarget != NULL)
            {
                RETURN m_pManagedTarget;
            }
            else
            {
                RETURN m_pMD->GetMultiCallableAddrOfCode();
            }
        }
    }
#endif // !DACCESS_COMPILE

    OBJECTHANDLE GetObjectHandle() const
    {
        CONTRACT (OBJECTHANDLE)
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            // If we OOM after we create the holder but
            // before we set the m_state we can have
            // m_state == 0 and m_pObjectHandle == NULL
            PRECONDITION(m_state == kRunTimeInited  ||
                         m_state == kLoadTimeInited ||
                         m_pObjectHandle == NULL);
        }
        CONTRACT_END;

        RETURN m_pObjectHandle;
    }

    UMThunkMarshInfo* GetUMThunkMarshInfo() const
    {
        CONTRACT (UMThunkMarshInfo*)
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            SUPPORTS_DAC;
            PRECONDITION(m_state == kRunTimeInited || m_state == kLoadTimeInited);
#ifdef MDA_SUPPORTED
            // We can return NULL here if the CollectedDelegate probe is on because
            // a collected delegate will have set this field to NULL.
            POSTCONDITION(g_pDebugInterface->ThisIsHelperThread() || MDA_GET_ASSISTANT(CallbackOnCollectedDelegate) || CheckPointer(RETVAL));
#else
            POSTCONDITION(CheckPointer(RETVAL));
#endif
        }
        CONTRACT_END;

        RETURN m_pUMThunkMarshInfo;
    }

    const BYTE* GetCode() const
    {
        CONTRACT (const BYTE*)
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(m_state == kRunTimeInited || m_state == kLoadTimeInited);
            POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        }
        CONTRACT_END;

        RETURN m_code.GetEntryPoint();
    }

    static UMEntryThunk* RecoverUMEntryThunk(const VOID* pCode)
    {
        LIMITED_METHOD_CONTRACT;
        return (UMEntryThunk*)( ((LPBYTE)pCode) - offsetof(UMEntryThunk, m_code) );
    }

    MethodDesc* GetMethod() const
    {
        CONTRACT (MethodDesc*)
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(m_state == kRunTimeInited || m_state == kLoadTimeInited);
            POSTCONDITION(CheckPointer(RETVAL,NULL_OK));
        }
        CONTRACT_END;

        RETURN m_pMD;
    }

    ADID GetDomainId() const
    {
        CONTRACT (ADID)
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(m_state == kRunTimeInited || m_state == kLoadTimeInited);
        }
        CONTRACT_END;

        RETURN m_dwDomainId;
    }

    static DWORD GetOffsetOfMethodDesc()
    {
        LIMITED_METHOD_CONTRACT;
        return offsetof(class UMEntryThunk, m_pMD);
    }

    static DWORD GetCodeOffset()
    {
        LIMITED_METHOD_CONTRACT;
        return offsetof(UMEntryThunk, m_code);
    }

    static UMEntryThunk* Decode(LPVOID pCallback);

#ifdef MDA_SUPPORTED
    BOOL IsCollected() const
    {
        LIMITED_METHOD_CONTRACT;
        _ASSERTE(m_pMD != NULL && m_pMD->IsEEImpl());
        return m_pObjectHandle == NULL;
    }
#endif

private:
    // The start of the managed code.
    // if m_pObjectHandle is non-NULL, this field is still set to help with diagnostic of call on collected delegate crashes
    // but it may not have the correct value.
    PCODE                   m_pManagedTarget;

    // This is used for profiling.
    PTR_MethodDesc          m_pMD;

    // Object handle holding "this" reference. May be a strong or weak handle.
    // Field is NULL for a static method.
    OBJECTHANDLE            m_pObjectHandle;

    // Pointer to the shared structure containing everything else
    PTR_UMThunkMarshInfo    m_pUMThunkMarshInfo;

    ADID                    m_dwDomainId;   // appdomain of module (cached for fast access)
#ifdef _DEBUG
    DWORD                   m_state;        // the initialization state
#endif

    UMEntryThunkCode        m_code;
};

// Cache to hold UMEntryThunk/UMThunkMarshInfo instances associated with MethodDescs.
// All UMEntryThunk/UMThunkMarshInfo instances are destroyed when the cache goes away.
class UMEntryThunkCache
{
public:
    UMEntryThunkCache(AppDomain *pDomain);
    ~UMEntryThunkCache();

    UMEntryThunk *GetUMEntryThunk(MethodDesc *pMD);

private:
    struct CacheElement
    {
        CacheElement()
        {
            LIMITED_METHOD_CONTRACT;
            m_pMD = NULL;
            m_pThunk = NULL;
        }

        MethodDesc   *m_pMD;
        UMEntryThunk *m_pThunk;
    };

    class ThunkSHashTraits : public NoRemoveSHashTraits< DefaultSHashTraits<CacheElement> >
    {
    public:
        typedef MethodDesc *key_t;
        static key_t GetKey(element_t e)       { LIMITED_METHOD_CONTRACT; return e.m_pMD; }
        static BOOL Equals(key_t k1, key_t k2) { LIMITED_METHOD_CONTRACT; return (k1 == k2); }
        static count_t Hash(key_t k)           { LIMITED_METHOD_CONTRACT; return (count_t)(size_t)k; }
        static const element_t Null()          { LIMITED_METHOD_CONTRACT; return CacheElement(); }
        static bool IsNull(const element_t &e) { LIMITED_METHOD_CONTRACT; return (e.m_pMD == NULL); }
    };

    static void DestroyMarshInfo(UMThunkMarshInfo *pMarshInfo)
    {
        WRAPPER_NO_CONTRACT;
        pMarshInfo->~UMThunkMarshInfo();
    }

    SHash<ThunkSHashTraits> m_hash;
    Crst       m_crst;
    AppDomain *m_pDomain;
};

#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
//-------------------------------------------------------------------------
// One-time creation of special prestub to initialize UMEntryThunks.
//-------------------------------------------------------------------------
Stub *GenerateUMThunkPrestub();
#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL

//-------------------------------------------------------------------------
// NExport stub
//-------------------------------------------------------------------------
#if  !defined(_WIN64) && !defined(DACCESS_COMPILE) && !defined(CROSS_COMPILE)
EXCEPTION_HANDLER_DECL(FastNExportExceptHandler);
EXCEPTION_HANDLER_DECL(UMThunkPrestubHandler);
#endif // _WIN64

extern "C" void TheUMEntryPrestub(void);
extern "C" PCODE TheUMEntryPrestubWorker(UMEntryThunk * pUMEntryThunk);

EXTERN_C void UMThunkStub(void);

#ifdef _DEBUG
void STDCALL LogUMTransition(UMEntryThunk* thunk);
#endif

#ifdef MDA_SUPPORTED
EXTERN_C void __fastcall CallbackOnCollectedDelegateHelper(UMEntryThunk *pEntryThunk);
#endif // MDA_SUPPORTED

#endif //__dllimportcallback_h__


text:
Once upon a time, I had a couple of utility apps I developed on my free time. They were free,
open sourced, and gained a little bit of popularity.

Today I decided to revisit them, with a better code base, and make them Material ready, unit-tested
and a little bit better.


text:
<?php
global $Cart,$General,$wpdb;
$userInfo = $General->getLoginUserInfo();
$_SESSION['checkout_as_guest'] = '';
if($userInfo && $_GET['action'] != 'logout')
{
	wp_redirect(get_option( 'siteurl' ).'/?page=account');
	exit;
}
require( 'wp-load.php' );
require(ABSPATH.'wp-includes/registration.php');

// Redirect to https login if forced to use SSL
if ( force_ssl_admin() && !is_ssl() ) {
	if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
		wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
		exit();
	} else {
		wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
		exit();
	}
}

	$message = apply_filters('login_message', $message);
	if ( !empty( $message ) ) echo $message . "\n";

/**
 * Handles registering a new user.
 *
 * @param string $user_login User's username for logging in
 * @param string $user_email User's email address to send password and add
 * @return int|WP_Error Either user's ID or error on failure.
 */
function register_new_user($user_login, $user_email) {
	global $wpdb,$General;
	$errors = new WP_Error();

	$user_login = sanitize_user( $user_login );
	$user_email = apply_filters( 'user_registration_email', $user_email );

	// Check the username
	if ( $user_login == '' )
		$errors->add('empty_username', __(AFF_EMPTY_USERNAME_MSG));
	elseif ( !validate_username( $user_login ) ) {
		$errors->add('invalid_username', __(AFF_USERNAME_INVALID_MSG));
		$user_login = '';
	} elseif ( username_exists( $user_login ) )
		$errors->add('username_exists', __(AFF_USERNAME_EXISTS_MSG));

	// Check the e-mail address
	if ($user_email == '') {
		$errors->add('empty_email', __(AFF_EMPTY_EMAIL_MSG));
	} elseif ( !is_email( $user_email ) ) {
		$errors->add('invalid_email', __(AFF_EMAIL_NOT_CORRECT_MSG));
		$user_email = '';
	} elseif ( email_exists( $user_email ) )
		$errors->add('email_exists', __(AFF_EMAIL_ALREADY_EXIST_MSG));

	do_action('register_post', $user_login, $user_email, $errors);

	$errors = apply_filters( 'registration_errors', $errors );
	foreach($errors as $errorsObj)
	{
		foreach($errorsObj as $key=>$val)
		{
			for($i=0;$i<count($val);$i++)
			{
				echo "
".$val[$i].'
';
			}
		}
	}

	if ( $errors->get_error_code() )
		return $errors;

	$user_pass = wp_generate_password(12,false);
	$user_id = wp_create_user( $user_login, $user_pass, $user_email );

	$user_add1 = $_POST['user_add1'];
	$user_add2 = $_POST['user_add2'];
	$user_city = $_POST['user_city'];
	$user_state = $_POST['user_state'];
	$user_country = $_POST['user_country'];
	$user_postalcode = $_POST['user_postalcode'];
	$is_affiliate = $_POST['is_affiliate'];
	$user_address_info = array(
						"user_add1"		=> $user_add1,
						"user_add2"		=> $user_add2,
						"user_city"		=> $user_city,
						"user_state"	=> $user_state,
						"user_country"	=> $user_country,
						"user_postalcode"=> $user_postalcode,
						);
	update_usermeta($user_id, 'user_address_info', serialize($user_address_info)); // User Address Information Here
	$userName = $_POST['user_fname'].'  '.$_POST['user_lname'];
	$updateUsersql = "update $wpdb->users set user_nicename=\"$userName\", display_name=\"$userName\"  where ID=\"$user_id\"";
	$wpdb->query($updateUsersql);

	if ( !$user_id ) {
		$errors->add('registerfail', sprintf(__('ERROR: Couldn’t register you... please contact the webmaster !'), get_option('admin_email')));
		return $errors;
	}

	if ( $user_id )
	{
		////AFFILIAGE START//
		if($General->is_active_affiliate())
		{
			if($is_affiliate)
			{
				$user_role = get_usermeta($user_id,'wp_capabilities');
				$user_role['affiliate'] = 1;
				update_usermeta($user_id, 'wp_capabilities', $user_role);
			}
		}
		////AFFILIATE END///

		//wp_new_user_notification($user_id, $user_pass);
		///////REGISTRATION EMAIL START//////
		global $General;
		$fromEmail = $General->get_site_emailId();
		$fromEmailName = $General->get_site_emailName();
		$store_name = get_option('blogname');
		$order_info = $General->get_order_detailinfo_tableformat($orderInfoArray,1);
		$clientdestinationfile =   ABSPATH . "wp-content/uploads/notification/emails/registration.txt";
		if(!file_exists($clientdestinationfile))
		{
		$client_message = '
Dear [#$user_name#],

You can log in  with the following information:

Username: [#$user_login#]

Password: [#$user_password#]

Thanks!

[#$store_name#]
';
		}else
		{
			$client_message = file_get_contents($clientdestinationfile);
		}
		$filecontent_arr1 = explode('[SUBJECT-STR]',$client_message);
		$filecontent_arr2 = explode('[SUBJECT-END]',$filecontent_arr1[1]);
		$subject = $filecontent_arr2[0];
		if($subject == '')
		{
			$subject = "Registration Email";
		}
		$client_message = $filecontent_arr2[1];
		/////////////customer email//////////////
		$search_array = array('[#$user_name#]','[#$user_login#]','[#$user_password#]','[#$store_name#]');
		$replace_array = array($_POST['user_fname'],$user_login,$user_pass,$store_name);
		$client_message = str_replace($search_array,$replace_array,$client_message);
		$General->sendEmail($fromEmail,$fromEmailName,$user_email,$userName,$subject,$client_message,$extra='');///To clidne email
		//////REGISTRATION EMAIL END////////
	}
	return array($user_id,$user_pass);
}
?>
<?php
$affiliate_settings = get_option('affiliate_settings');
$affiliate_login_content_top = $affiliate_settings['affiliate_login_content_top'];
$affiliate_login_content_bottom = $affiliate_settings['affiliate_login_content_bottom'];
$affiliate_terms_conditions = $affiliate_settings['affiliate_terms_conditions'];
?>
<?php get_header(); ?>

      	<?php if ( get_option( 'ptthemes_breadcrumbs' )) { yoast_breadcrumb('',' » '.AFFILIATE_REG_BREADCUM); } ?>

<?php _e(AFFILIATE_LOGIN_PAGE_TITLE); ?>

                <?php
                if($affiliate_login_content_top)
				{
					echo '
'.$affiliate_login_content_top.'
';
				}
				?>

        <?php
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'login';
$errors = new WP_Error();

if ( isset($_GET['key']) )
	$action = 'resetpass';

// validate action so as to default to the login screen
if ( !in_array($action, array('logout', 'lostpassword', 'retrievepassword', 'resetpass', 'rp', 'register', 'login')) && false === has_filter('login_form_' . $action) )
	$action = 'login';

nocache_headers();

header('Content-Type: '.get_bloginfo('html_type').'; charset='.get_bloginfo('charset'));

if ( defined('RELOCATE') ) { // Move flag is set
	if ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != $_SERVER['PHP_SELF']) )
		$_SERVER['PHP_SELF'] = str_replace( $_SERVER['PATH_INFO'], '', $_SERVER['PHP_SELF'] );

	$schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
	if ( dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) != get_option('siteurl') )
		update_option('siteurl', dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) );
}

//Set a cookie now to see if they are supported by the browser.
setcookie(TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN);
if ( SITECOOKIEPATH != COOKIEPATH )
	setcookie(TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN);

// allow plugins to override the default actions, and to add extra actions if they want
do_action('login_form_' . $action);

$http_post = ('POST' == $_SERVER['REQUEST_METHOD']);
switch ($action) {
case 'register' :
	if ( !get_option('users_can_register') ) {
		wp_redirect(get_option( 'siteurl' ).'/?page=affiliate&registration=disabled');
		exit();
	}

	$user_login = '';
	$user_email = '';
	if ( $http_post ) {
		//require_once( ABSPATH . WPINC . '/registration.php');

		$user_login = $_POST['user_login'];
		$user_email = $_POST['user_email'];
		$user_fname = $_POST['user_fname'];
		$user_lname = $_POST['user_lname'];
		$user_add1 = $_POST['user_add1'];
		$user_add2 = $_POST['user_add2'];
		$user_city = $_POST['user_city'];
		$user_state = $_POST['user_state'];
		$user_country = $_POST['user_country'];
		$user_postalcode = $_POST['user_postalcode'];

		$errors = register_new_user($user_login, $user_email);

		if ( !is_wp_error($errors) )
		{
			$_POST['log'] = $user_login;
			$_POST['pwd'] = $errors[1];
			$_POST['testcookie'] = 1;

			$secure_cookie = '';
			// If the user wants ssl but the session is not ssl, force a secure cookie.
			if ( !empty($_POST['log']) && !force_ssl_admin() ) {
				$user_name = sanitize_user($_POST['log']);
				if ( $user = get_userdatabylogin($user_name) ) {
					if ( get_user_option('use_ssl', $user->ID) ) {
						$secure_cookie = true;
						force_ssl_admin(true);
					}
				}
			}

			$redirect_to = $_REQUEST['reg_redirect_link'];
			if ( !$secure_cookie && is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) )
				$secure_cookie = false;

			$user = wp_signon('', $secure_cookie);

			$redirect_to = apply_filters('login_redirect', $redirect_to, isset( $_REQUEST['reg_redirect_link'] ) ? $_REQUEST['reg_redirect_link'] : '', $user);

			if ( !is_wp_error($user) )
			{
				wp_safe_redirect($redirect_to);
				exit();
			}
			exit();
		}
	}
	//login_header(__('Registration Form'), '
' . __('Register For This Site') . '
', $errors);
break;

case 'login' :
default:
	$secure_cookie = '';

	// If the user wants ssl but the session is not ssl, force a secure cookie.
	if ( !empty($_POST['log']) && !force_ssl_admin() ) {
		$user_name = sanitize_user($_POST['log']);
		if ( $user = get_userdatabylogin($user_name) ) {
			if ( get_user_option('use_ssl', $user->ID) ) {
				$secure_cookie = true;
				force_ssl_admin(true);
			}
		}
	}

	if ( isset( $_REQUEST['redirect_to'] ) ) {
		$redirect_to = $_REQUEST['redirect_to'];
		// Redirect to https if user wants ssl
		if ( $secure_cookie && false !== strpos($redirect_to, 'wp-admin') )
			$redirect_to = preg_replace('|^http://|', 'https://', $redirect_to);
	} else {
		$redirect_to = admin_url();
	}

	if ( !$secure_cookie && is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) )
		$secure_cookie = false;

	$user = wp_signon('', $secure_cookie);

	$redirect_to = apply_filters('login_redirect', $redirect_to, isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '', $user);

	if ( !is_wp_error($user) ) {
		// If the user can't edit posts, send them to their profile.
		if ( !$user->has_cap('edit_posts') && ( empty( $redirect_to ) || $redirect_to == 'wp-admin/' || $redirect_to == admin_url() ) )
			$redirect_to = admin_url('profile.php');
		wp_safe_redirect($redirect_to);
		exit();
	}

	$errors = $user;
	// Clear errors if loggedout is set.
	if ( !empty($_GET['loggedout']) )
		$errors = new WP_Error();

	// If cookies are disabled we can't log in even with a valid user+pass
	if ( isset($_POST['testcookie']) && empty($_COOKIE[TEST_COOKIE]) )
		$errors->add('test_cookie', __("ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress."));

	// Some parts of this script use the main login form to display a message
	if( isset($_GET['loggedout']) && TRUE == $_GET['loggedout'] )
	{
		$successmsg = '
'.AFFILIATE_LOGIN_LOGOUT_MSG.'
';
	}
	elseif( isset($_GET['registration']) && 'disabled' == $_GET['registration'] )
	{
		$successmsg = AFFILIATE_LOGIN_REG_NOT_ALLOW_MSG;
	}
	elseif( isset($_GET['checkemail']) && 'confirm' == $_GET['checkemail'] )
	{
		$successmsg = AFFILIATE_LOGIN_CONFIRM_LINK_MSG;
	}
	elseif( isset($_GET['checkemail']) && 'newpass' == $_GET['checkemail'] )
	{
		$successmsg = AFFILIATE_LOGIN_NEWPW_EMAIL_MSG;
	}
	elseif( isset($_GET['checkemail']) && 'registered' == $_GET['checkemail'] )
	{
		$successmsg = AFFILIATE_LOGIN_REG_COMPLETED_MSG;
	}

echo "
".$successmsg.'
';
//	login_header(__('Log In'), '', $errors);
?>

        <?php

break;
} // end action switch
?>
        <?php
if($error_message)
{
	echo "
".$error_message.'
';
}
if($message)
{
	echo "".$message.'';
}
?>

 <?php _e(ALREADY_MEMBER_TEXT);?><a href="<?php echo get_option('siteurl');?>/?page=affiliate"><?php _e(ALREADY_MEMBER_LINK);?>

         <form name="registerform" id="registerform" action="<?php echo get_option( 'siteurl' ).'/?page=affiliate&action=register&type=reg';//echo site_url('wp-login.php?action=register', 'login_post') ?>" method="post">
        <?php
		if(strstr($_SESSION['redirect_page'],'page=checkout'))
		{
			$reg_redirect_link = get_option( 'siteurl' ).'/?page=checkout';
		}else
		{
			$reg_redirect_link = get_option( 'siteurl' ).'/?page=affiliate&action=register';
		}
		?>
        <input type="hidden" name="reg_redirect_link" value="<?php echo $reg_redirect_link;?>" />

 * Indicates mandatory fields

              <?php _e('Username') ?>
              *
              <input type="text" name="user_login" id="user_login1reg" class="reg_row_textfield" value="<?php echo esc_attr(stripslashes($user_login)); ?>" size="20"/>

              <?php _e('E-mail') ?>
              *
              <input type="text" name="user_email" id="user_email" class="reg_row_textfield" value="<?php echo esc_attr(stripslashes($user_email)); ?>" size="25" />

              <?php _e('First Name') ?>
              *
              <input type="text" name="user_fname" id="user_fname" class="reg_row_textfield" value="<?php echo esc_attr(stripslashes($user_fname)); ?>" size="25"  />

              <?php _e('Last Name') ?>

              <input type="text" name="user_lname" id="user_lname" class="reg_row_textfield" value="<?php echo esc_attr(stripslashes($user_lname)); ?>" size="25"  />

                <input type="checkbox" name="termandconditons" id="termandconditons">
			<?php
			if($affiliate_terms_conditions)
			{
				$term_and_conditions = $affiliate_terms_conditions;
			}else
			{
				 $term_and_conditions = TERMS_CONDITIONS_TITLE;
			}
			 $store_name = get_option('blogname');
			$search_array = array('[#$store_name#]');
			$replace_array = array($store_name);
			$term_and_conditions = str_replace($search_array,$replace_array,$term_and_conditions);
			  _e($term_and_conditions) ?>

            <input type="hidden" name="is_affiliate" value="1" />
            <?php do_action('register_form'); ?>

              <?php _e(AFFILIATE_LOGIN_REG_PAGE_INSTRUCTION) ?>

           <input type="submit" name="registernow" value="<?php _e('Create Account') ?>" onClick="return chk_form_reg();" class="highlight_input_btn" />

           </form>

     	<?php
        if($affiliate_login_content_bottom)
		{
			echo '
'.$affiliate_login_content_bottom.'
';
		}
		?>

 		 <?php get_sidebar(); ?>

 <?php get_footer(); ?>


text:
#ifndef FLATBUFFERS_REFLECTION_H_
#define FLATBUFFERS_REFLECTION_H_

#include "flatbuffers/util.h"

// This is somewhat of a circular dependency because flatc (and thus this
// file) is needed to generate this header in the first place.
// Should normally not be a problem since it can be generated by the
// previous version of flatc whenever this code needs to change.
// See reflection/generate_code.sh
#include "flatbuffers/reflection_generated.h"

// Helper functionality for reflection.

namespace flatbuffers {

inline size_t GetTypeSize(reflection::BaseType base_type) {
  // This needs to correspond to the BaseType enum.
  static size_t sizes[] = { 0, 1, 1, 1, 1, 2, 2, 4, 4, 8, 8, 4, 8, 4, 4, 4, 4 };
  return sizes[base_type];
}

// Get the root, regardless of what type it is.
inline Table *GetAnyRoot(uint8_t *flatbuf) {
  return GetMutableRoot<Table>(flatbuf);
}
inline const Table *GetAnyRoot(const uint8_t *flatbuf) {
  return GetRoot<Table>(flatbuf);
}

// Get a field, if you know it's an integer, and its exact type.
template<typename T> T GetFieldI(const Table *table,
                                 const reflection::Field *field) {
  assert(sizeof(T) == GetTypeSize(field->type()->base_type()));
  return table->GetField<T>(field->offset(),
                            static_cast<T>(field->default_integer()));
}

// Get a field, if you know it's floating point and its exact type.
template<typename T> T GetFieldF(const Table *table,
                                 const reflection::Field *field) {
  assert(sizeof(T) == GetTypeSize(field->type()->base_type()));
  return table->GetField<T>(field->offset(),
                            static_cast<T>(field->default_real()));
}

// Get a field, if you know it's a string.
inline const String *GetFieldS(const Table *table,
                               const reflection::Field *field) {
  assert(field->type()->base_type() == reflection::String);
  return table->GetPointer<const String *>(field->offset());
}

// Get a field, if you know it's a vector.
template<typename T> const Vector<T> *GetFieldV(const Table *table,
                                               const reflection::Field *field) {
  assert(field->type()->base_type() == reflection::Vector &&
         sizeof(T) == GetTypeSize(field->type()->element()));
  return table->GetPointer<const Vector<T> *>(field->offset());
}

// Get any field as a 64bit int, regardless of what it is (bool/int/float/str).
inline int64_t GetAnyFieldI(const Table *table,
                            const reflection::Field *field) {
# define FLATBUFFERS_GET(C, T) \
    static_cast<int64_t>(GetField##C<T>(table, field))
  switch (field->type()->base_type()) {
    case reflection::UType:
    case reflection::Bool:
    case reflection::UByte:  return FLATBUFFERS_GET(I, uint8_t);
    case reflection::Byte:   return FLATBUFFERS_GET(I, int8_t);
    case reflection::Short:  return FLATBUFFERS_GET(I, int16_t);
    case reflection::UShort: return FLATBUFFERS_GET(I, uint16_t);
    case reflection::Int:    return FLATBUFFERS_GET(I, int32_t);
    case reflection::UInt:   return FLATBUFFERS_GET(I, uint32_t);
    case reflection::Long:   return FLATBUFFERS_GET(I, int64_t);
    case reflection::ULong:  return FLATBUFFERS_GET(I, uint64_t);
    case reflection::Float:  return FLATBUFFERS_GET(F, float);
    case reflection::Double: return FLATBUFFERS_GET(F, double);
    case reflection::String: return StringToInt(
                                      GetFieldS(table, field)->c_str());
    default: return 0;
  }
# undef FLATBUFFERS_GET
}

// Get any field as a double, regardless of what it is (bool/int/float/str).
inline double GetAnyFieldF(const Table *table,
                           const reflection::Field *field) {
  switch (field->type()->base_type()) {
    case reflection::Float:  return GetFieldF<float>(table, field);
    case reflection::Double: return GetFieldF<double>(table, field);
    case reflection::String: return strtod(GetFieldS(table, field)->c_str(),
                                           nullptr);
    default: return static_cast<double>(GetAnyFieldI(table, field));
  }
}

// Get any field as a string, regardless of what it is (bool/int/float/str).
inline std::string GetAnyFieldS(const Table *table,
                                const reflection::Field *field) {
  switch (field->type()->base_type()) {
    case reflection::Float:
    case reflection::Double: return NumToString(GetAnyFieldF(table, field));
    case reflection::String: return GetFieldS(table, field)->c_str();
    // TODO: could return vector/table etc as JSON string.
    default: return NumToString(GetAnyFieldI(table, field));
  }
}

// Set any scalar field, if you know its exact type.
template<typename T> bool SetField(Table *table, const reflection::Field *field,
                                   T val) {
  assert(sizeof(T) == GetTypeSize(field->type()->base_type()));
  return table->SetField(field->offset(), val);
}

// Set any field as a 64bit int, regardless of what it is (bool/int/float/str).
inline void SetAnyFieldI(Table *table, const reflection::Field *field,
                         int64_t val) {
# define FLATBUFFERS_SET(T) SetField<T>(table, field, static_cast<T>(val))
  switch (field->type()->base_type()) {
    case reflection::UType:
    case reflection::Bool:
    case reflection::UByte:  FLATBUFFERS_SET(uint8_t  ); break;
    case reflection::Byte:   FLATBUFFERS_SET(int8_t   ); break;
    case reflection::Short:  FLATBUFFERS_SET(int16_t  ); break;
    case reflection::UShort: FLATBUFFERS_SET(uint16_t ); break;
    case reflection::Int:    FLATBUFFERS_SET(int32_t  ); break;
    case reflection::UInt:   FLATBUFFERS_SET(uint32_t ); break;
    case reflection::Long:   FLATBUFFERS_SET(int64_t  ); break;
    case reflection::ULong:  FLATBUFFERS_SET(uint64_t ); break;
    case reflection::Float:  FLATBUFFERS_SET(float    ); break;
    case reflection::Double: FLATBUFFERS_SET(double   ); break;
    // TODO: support strings
    default: break;
  }
# undef FLATBUFFERS_SET
}

// Set any field as a double, regardless of what it is (bool/int/float/str).
inline void SetAnyFieldF(Table *table, const reflection::Field *field,
                         double val) {
  switch (field->type()->base_type()) {
    case reflection::Float:  SetField<float> (table, field,
                                              static_cast<float>(val)); break;
    case reflection::Double: SetField<double>(table, field, val); break;
    // TODO: support strings.
    default: SetAnyFieldI(table, field, static_cast<int64_t>(val)); break;
  }
}

// Set any field as a string, regardless of what it is (bool/int/float/str).
inline void SetAnyFieldS(Table *table, const reflection::Field *field,
                         const char *val) {
  switch (field->type()->base_type()) {
    case reflection::Float:
    case reflection::Double: SetAnyFieldF(table, field, strtod(val, nullptr));
    // TODO: support strings.
    default: SetAnyFieldI(table, field, StringToInt(val)); break;
  }
}

// "smart" pointer for use with resizing vectors: turns a pointer inside
// a vector into a relative offset, such that it is not affected by resizes.
template<typename T, typename U> class pointer_inside_vector {
 public:
  pointer_inside_vector(const T *ptr, const std::vector<U> &vec)
    : offset_(reinterpret_cast<const uint8_t *>(ptr) -
              reinterpret_cast<const uint8_t *>(vec.data())),
      vec_(vec) {}

  const T *operator*() const {
    return reinterpret_cast<const T *>(
             reinterpret_cast<const uint8_t *>(vec_.data()) + offset_);
  }
  const T *operator->() const {
    return operator*();
  }
  void operator=(const pointer_inside_vector &piv);
 private:
  size_t offset_;
  const std::vector<U> &vec_;
};

// Helper to create the above easily without specifying template args.
template<typename T, typename U> pointer_inside_vector<T, U> piv(
    const T *ptr, const std::vector<U> &vec) {
  return pointer_inside_vector<T, U>(ptr, vec);
}

// Resize a FlatBuffer in-place by iterating through all offsets in the buffer
// and adjusting them by "delta" if they straddle the start offset.
// Once that is done, bytes can now be inserted/deleted safely.
// "delta" may be negative (shrinking).
// Unless "delta" is a multiple of the largest alignment, you'll create a small
// amount of garbage space in the buffer.
class ResizeContext {
 public:
  ResizeContext(const reflection::Schema &schema, uoffset_t start, int delta,
                std::vector<uint8_t> *flatbuf)
     : schema_(schema), startptr_(flatbuf->data() + start),
       delta_(delta), buf_(*flatbuf),
       dag_check_(flatbuf->size() / sizeof(uoffset_t), false) {
    auto mask = sizeof(largest_scalar_t) - 1;
    delta_ = (delta_ + mask) & ~mask;
    if (!delta_) return;  // We can't shrink by less than largest_scalar_t.
    // Now change all the offsets by delta_.
    auto root = GetAnyRoot(buf_.data());
    Straddle<uoffset_t, 1>(buf_.data(), root, buf_.data());
    ResizeTable(schema.root_table(), root);
    // We can now add or remove bytes at start.
    if (delta_ > 0) buf_.insert(buf_.begin() + start, delta_, 0);
    else buf_.erase(buf_.begin() + start, buf_.begin() + start - delta_);
  }

  // Check if the range between first (lower address) and second straddles
  // the insertion point. If it does, change the offset at offsetloc (of
  // type T, with direction D).
  template<typename T, int D> void Straddle(void *first, void *second,
                                            void *offsetloc) {
    if (first <= startptr_ && second >= startptr_) {
      WriteScalar<T>(offsetloc, ReadScalar<T>(offsetloc) + delta_ * D);
      DagCheck(offsetloc) = true;
    }
  }

  // This returns a boolean that records if the corresponding offset location
  // has been modified already. If so, we can't even read the corresponding
  // offset, since it is pointing to a location that is illegal until the
  // resize actually happens.
  // This must be checked for every offset, since we can't know which offsets
  // will straddle and which won't.
  uint8_t &DagCheck(void *offsetloc) {
    auto dag_idx = reinterpret_cast<uoffset_t *>(offsetloc) -
                   reinterpret_cast<uoffset_t *>(buf_.data());
    return dag_check_[dag_idx];
  }

  void ResizeTable(const reflection::Object *objectdef, Table *table) {
    if (DagCheck(table))
      return;  // Table already visited.
    auto vtable = table->GetVTable();
    // Check if the vtable offset points beyond the insertion point.
    Straddle<soffset_t, -1>(table, vtable, table);
    // This direction shouldn't happen because vtables that sit before tables
    // are always directly adjacent, but check just in case we ever change the
    // way flatbuffers are built.
    Straddle<soffset_t, -1>(vtable, table, table);
    // Early out: since all fields inside the table must point forwards in
    // memory, if the insertion point is before the table we can stop here.
    auto tableloc = reinterpret_cast<uint8_t *>(table);
    if (startptr_ <= tableloc) return;
    // Check each field.
    auto fielddefs = objectdef->fields();
    for (auto it = fielddefs->begin(); it != fielddefs->end(); ++it) {
      auto fielddef = *it;
      auto base_type = fielddef->type()->base_type();
      // Ignore scalars.
      if (base_type <= reflection::Double) continue;
      // Ignore fields that are not stored.
      auto offset = table->GetOptionalFieldOffset(fielddef->offset());
      if (!offset) continue;
      // Ignore structs.
      auto subobjectdef = base_type == reflection::Obj ?
        schema_.objects()->Get(fielddef->type()->index()) : nullptr;
      if (subobjectdef && subobjectdef->is_struct()) continue;
      // Get this fields' offset, and read it if safe.
      auto offsetloc = tableloc + offset;
      if (DagCheck(offsetloc))
        continue;  // This offset already visited.
      auto ref = offsetloc + ReadScalar<uoffset_t>(offsetloc);
      Straddle<uoffset_t, 1>(offsetloc, ref, offsetloc);
      // Recurse.
      switch (base_type) {
        case reflection::Obj: {
          ResizeTable(subobjectdef, reinterpret_cast<Table *>(ref));
          break;
        }
        case reflection::Vector: {
          if (fielddef->type()->element() != reflection::Obj) break;
          auto vec = reinterpret_cast<Vector<uoffset_t> *>(ref);
          auto elemobjectdef =
            schema_.objects()->Get(fielddef->type()->index());
          if (elemobjectdef->is_struct()) break;
          for (uoffset_t i = 0; i < vec->size(); i++) {
            auto loc = vec->Data() + i * sizeof(uoffset_t);
            if (DagCheck(loc))
              continue;  // This offset already visited.
            auto dest = loc + vec->Get(i);
            Straddle<uoffset_t, 1>(loc, dest ,loc);
            ResizeTable(elemobjectdef, reinterpret_cast<Table *>(dest));
          }
          break;
        }
        case reflection::Union: {
          auto enumdef = schema_.enums()->Get(fielddef->type()->index());
          // TODO: this is clumsy and slow, but no other way to find it?
          auto type_field = fielddefs->LookupByKey(
                    (fielddef->name()->str() + "_type").c_str());
          assert(type_field);
          auto union_type = GetFieldI<uint8_t>(table, type_field);
          auto enumval = enumdef->values()->LookupByKey(union_type);
          ResizeTable(enumval->object(), reinterpret_cast<Table *>(ref));
          break;
        }
        case reflection::String:
          break;
        default:
          assert(false);
      }
    }
  }

  void operator=(const ResizeContext &rc);

 private:
  const reflection::Schema &schema_;
  uint8_t *startptr_;
  int delta_;
  std::vector<uint8_t> &buf_;
  std::vector<uint8_t> dag_check_;
};

// Changes the contents of a string inside a FlatBuffer. FlatBuffer must
// live inside a std::vector so we can resize the buffer if needed.
// "str" must live inside "flatbuf" and may be invalidated after this call.
inline void SetString(const reflection::Schema &schema, const std::string &val,
                      const String *str, std::vector<uint8_t> *flatbuf) {
  auto delta = static_cast<int>(val.size()) - static_cast<int>(str->Length());
  auto start = static_cast<uoffset_t>(reinterpret_cast<const uint8_t *>(str) -
                                      flatbuf->data() +
                                      sizeof(uoffset_t));
  if (delta) {
    // Different size, we must expand (or contract).
    ResizeContext(schema, start, delta, flatbuf);
    if (delta < 0) {
      // Clear the old string, since we don't want parts of it remaining.
      memset(flatbuf->data() + start, 0, str->Length());
    }
  }
  // Copy new data. Safe because we created the right amount of space.
  memcpy(flatbuf->data() + start, val.c_str(), val.size() + 1);
}

// Resizes a flatbuffers::Vector inside a FlatBuffer. FlatBuffer must
// live inside a std::vector so we can resize the buffer if needed.
// "vec" must live inside "flatbuf" and may be invalidated after this call.
template<typename T> void ResizeVector(const reflection::Schema &schema,
                                       uoffset_t newsize, T val,
                                       const Vector<T> *vec,
                                       std::vector<uint8_t> *flatbuf) {
  auto delta_elem = static_cast<int>(newsize) - static_cast<int>(vec->size());
  auto delta_bytes = delta_elem * static_cast<int>(sizeof(T));
  auto vec_start = reinterpret_cast<const uint8_t *>(vec) - flatbuf->data();
  auto start = static_cast<uoffset_t>(vec_start + sizeof(uoffset_t) +
                                      sizeof(T) * vec->size());
  if (delta_bytes) {
    ResizeContext(schema, start, delta_bytes, flatbuf);
    WriteScalar(flatbuf->data() + vec_start, newsize);  // Length field.
    // Set new elements to "val".
    for (int i = 0; i < delta_elem; i++) {
      auto loc = flatbuf->data() + start + i * sizeof(T);
      auto is_scalar = std::is_scalar<T>::value;
      if (is_scalar) {
        WriteScalar(loc, val);
      } else {  // struct
        *reinterpret_cast<T *>(loc) = val;
      }
    }
  }
}

}  // namespace flatbuffers

#endif  // FLATBUFFERS_REFLECTION_H_


text:
'use strict';

import gulp from 'gulp';
import { spawn } from 'child_process';
import { version } from '../../package.json';

const SPAWN_OPTIONS = { stdio: 'inherit' };

gulp.task('publish', ['stage'], done => {
  spawn('npm', ['publish', 'stage'], SPAWN_OPTIONS).on('close', () => {
    spawn('git', ['tag', version], SPAWN_OPTIONS).on('close', () => {
      spawn('git', ['push', '--tags'], SPAWN_OPTIONS).on('close', done);
    });
  });
});


text:
import os
from distutils.command.build import build

from django.core import management
from setuptools import setup, find_packages

try:
    with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as f:
        long_description = f.read()
except Exception:
    long_description = ''

class CustomBuild(build):
    def run(self):
        management.call_command('compilemessages', verbosity=1)
        build.run(self)

cmdclass = {
    'build': CustomBuild
}

setup(
    name='pretix-cartshare',
    version='1.6',
    description='pretix plugin to share carts',
    long_description=long_description,
    url='https://pretix.eu',
    author='Raphael Michel',
    author_email='mail@raphaelmichel.de',

    packages=find_packages(exclude=['tests', 'tests.*']),
    include_package_data=True,
    cmdclass=cmdclass,
    entry_points="""
[pretix.plugin]
cartshare=pretix_cartshare:PretixPluginMeta
""",
)


text:
IF (XERCESC_INCLUDE AND XERCESC_LIBRARY)
# in cache already
SET(XERCESC_FIND_QUIETLY TRUE)
ENDIF (XERCESC_INCLUDE AND XERCESC_LIBRARY)

OPTION(XERCESC_STATIC "Set to ON to link your project with static library (instead of DLL)." ON)

#IF (NOT  ${XERCESC_WAS_STATIC} STREQUAL ${XERCESC_STATIC})
UNSET(XERCESC_LIBRARY CACHE)
UNSET(XERCESC_LIBRARY_DEBUG CACHE)
#ENDIF (NOT  ${XERCESC_WAS_STATIC} STREQUAL ${XERCESC_STATIC})

SET(XERCESC_WAS_STATIC ${XERCESC_STATIC} CACHE INTERNAL "" )

FIND_PATH(XERCESC_INCLUDE NAMES xercesc/util/XercesVersion.hpp
PATHS
$ENV{XERCESC_INCLUDE_DIR}
${XERCESC_INCLUDE_DIR}
 /usr/local/include
 /usr/include
)

IF (XERCESC_STATIC)
FIND_LIBRARY(XERCESC_LIBRARY NAMES xerces-c
 PATHS
 $ENV{XERCESC_LIBRARY_DIR}
 ${XERCESC_LIBRARY_DIR}
 /usr/lib
 /usr/local/lib
)
FIND_LIBRARY(XERCESC_LIBRARY_DEBUG NAMES xerces-c_static_3D xerces-c-3.1D
 PATHS
 $ENV{XERCESC_LIBRARY_DIR}
 ${XERCESC_LIBRARY_DIR}
 /usr/lib
 /usr/local/lib
)
ADD_DEFINITIONS( -DXERCES_STATIC_LIBRARY )
ELSE (XERCESC_STATIC)
FIND_LIBRARY(XERCESC_LIBRARY NAMES xerces-c
 PATHS
 $ENV{XERCESC_LIBRARY_DIR}
 ${XERCESC_LIBRARY_DIR}
)
FIND_LIBRARY(XERCESC_LIBRARY_DEBUG NAMES xerces-c_3D
 PATHS
 $ENV{XERCESC_LIBRARY_DIR}
 ${XERCESC_LIBRARY_DIR}
)
ENDIF (XERCESC_STATIC)

IF (XERCESC_INCLUDE AND XERCESC_LIBRARY)
SET(XERCESC_FOUND TRUE)
ELSE (XERCESC_INCLUDE AND XERCESC_LIBRARY)
SET(XERCESC_FOUND FALSE)
ENDIF (XERCESC_INCLUDE AND XERCESC_LIBRARY)

IF(XERCESC_FOUND)

FIND_PATH(XERCESC_XVERHPPPATH NAMES XercesVersion.hpp PATHS
 ${XERCESC_INCLUDE}
 PATH_SUFFIXES xercesc/util)

IF ( ${XERCESC_XVERHPPPATH} STREQUAL XERCESC_XVERHPPPATH-NOTFOUND )
 SET(XERCES_VERSION "0")
ELSE( ${XERCESC_XVERHPPPATH} STREQUAL XERCESC_XVERHPPPATH-NOTFOUND )
 FILE(READ ${XERCESC_XVERHPPPATH}/XercesVersion.hpp XVERHPP)

 STRING(REGEX MATCHALL "\n *#define XERCES_VERSION_MAJOR +[0-9]+" XVERMAJ
   ${XVERHPP})
 STRING(REGEX MATCH "\n *#define XERCES_VERSION_MINOR +[0-9]+" XVERMIN
   ${XVERHPP})
 STRING(REGEX MATCH "\n *#define XERCES_VERSION_REVISION +[0-9]+" XVERREV
   ${XVERHPP})

 STRING(REGEX REPLACE "\n *#define XERCES_VERSION_MAJOR +" ""
   XVERMAJ ${XVERMAJ})
 STRING(REGEX REPLACE "\n *#define XERCES_VERSION_MINOR +" ""
   XVERMIN ${XVERMIN})
 STRING(REGEX REPLACE "\n *#define XERCES_VERSION_REVISION +" ""
   XVERREV ${XVERREV})

 SET(XERCESC_VERSION ${XVERMAJ}.${XVERMIN}.${XVERREV})

ENDIF ( ${XERCESC_XVERHPPPATH} STREQUAL XERCESC_XVERHPPPATH-NOTFOUND )

 MESSAGE(STATUS "Found Xerces-C: ${XERCESC_LIBRARY}")
 MESSAGE(STATUS "              : ${XERCESC_INCLUDE}")
 MESSAGE(STATUS "       Version: ${XERCESC_VERSION}")

ELSE(XERCESC_FOUND)
MESSAGE(FATAL_ERROR "Could not find Xerces-C !")
ENDIF(XERCESC_FOUND)

MARK_AS_ADVANCED(XERCESC_INCLUDE XERCESC_LIBRARY)


text:
package net.awired.clients.teamcity.resource;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;

@XmlRootElement(name = "change")
@XmlAccessorType(XmlAccessType.FIELD)
public class TeamCityChange {

    private String comment;

    @XmlElements({@XmlElement(name="file")})
    private List<TeamCityFile> files = new ArrayList<TeamCityFile>();

    @XmlAttribute
    private String username;

    @XmlAttribute
    private String date;

    @XmlAttribute
    private String webLink;

    @XmlAttribute
    private String version;

    @XmlAttribute
    private String id;

    @XmlAttribute
    private String href;

    public String getWebLink() {
        return webLink;
    }

    public void setWebLink(String webLink) {
        this.webLink = webLink;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getId() {
        return id;
    }

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

    public String getHref() {
        return href;
    }

    public void setHref(String href) {
        this.href = href;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

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

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

}


text:
package com.ibm.watson.discovery.v2.model;

import static org.testng.Assert.*;

import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.watson.discovery.v2.utils.TestUtilities;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;

/** Unit test class for the ModelEvaluationMacroAverage model. */
public class ModelEvaluationMacroAverageTest {
  final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
  final List<FileWithMetadata> mockListFileWithMetadata =
      TestUtilities.creatMockListFileWithMetadata();

  @Test
  public void testModelEvaluationMacroAverage() throws Throwable {
    ModelEvaluationMacroAverage modelEvaluationMacroAverageModel =
        new ModelEvaluationMacroAverage();
    assertNull(modelEvaluationMacroAverageModel.getPrecision());
    assertNull(modelEvaluationMacroAverageModel.getRecall());
    assertNull(modelEvaluationMacroAverageModel.getF1());
  }
}


text:
package cn.limw.summer.webx.context;

import javax.servlet.ServletContextEvent;

import org.slf4j.Logger;
import org.springframework.web.context.ContextLoader;

import cn.limw.summer.util.Logs;

import com.alibaba.citrus.webx.context.WebxComponentsContext;

/**
 * @author li
 * @version 1 (2015年6月9日 下午4:34:15)
 * @since Java7
 */
public class WebxContextLoaderListener extends AbstractWebxContextLoaderListener {
    private static final Logger log = Logs.slf4j();

    public static final String WEBX_COMPONENTS_LOADER = "WEBX_COMPONENTS_LOADER";

    public static final ThreadLocal<WebxComponentsLoader> WEBX_COMPONENTS_LOADER_THREAD_LOCAL = new ThreadLocal<WebxComponentsLoader>();

    protected ContextLoader createContextLoader() {
        log.info("createContextLoader()");
        return super.createContextLoader();
    }

    public void contextInitialized(ServletContextEvent event) {
        log.info("contextInitialized(ServletContextEvent)");
        super.contextInitialized(event);
    }

    public void contextDestroyed(ServletContextEvent event) {
        log.info("contextDestroyed(ServletContextEvent)");
        super.contextDestroyed(event);
    }

    protected Class<? extends WebxComponentsContext> getDefaultContextClass() {
        return cn.limw.summer.webx.context.WebxComponentsContext.class;
    }
}


text:
<?php
/**
 * @Author: Leandro Henrique Reis <emtudo@gmail.com>
 * @Date:   2016-05-05 08:40:49
 * @Last Modified by:   Leandro Henrique Reis
 * @Last Modified time: 2016-06-04 19:51:35
 */

namespace Domain\Config\Http;

use Domain\Config\ConfigRepository as Repository;
use Domain\Config\Http\Requests\Config\DeleteRequest;
use Domain\Config\Http\Requests\Config\StoreRequest;
use Domain\Config\Http\Requests\Config\UpdateRequest;
use Domain\Http\Controllers\AbstractController;
use Domain\Http\Controllers\Traits\CrudTrait;

/**
 * It's don't work, because Requests and Repository don't exists.
 */
class ConfigController extends AbstractController
{
    use CrudTrait;

    public function repo()
    {
        return Repository::class;
    }

    public function storeRequest()
    {
        return StoreRequest::class;
    }

    public function updateRequest()
    {
        return UpdateRequest::class;
    }

    public function deleteRequest()
    {
        return DeleteRequest::class;
    }
}


text:
import * as angular from "angular";
import "angular-mocks";
import SignUpCtrl from "./sign-up.controller";
import LoginService from "./login.service";
import AlertModalService from "../common/alert-modal.service";
import {IControllerService, IDeferred, IQService, IRootScopeService, IScope} from "angular";
import {LOGIN_MODULE} from "./login.module";
import {ILocationService} from "angular";

describe("SignUpCtrl", () => {
    let $controller: IControllerService, $scope: IScope, $q: IQService, $location: ILocationService;
    let ctrl: SignUpCtrl, loginService: LoginService, alertModalService: AlertModalService;

    beforeEach(() => angular.mock.module(LOGIN_MODULE));

    beforeEach(angular.mock.inject($injector => {
        $q = $injector.get("$q");
        $location = $injector.get("$location");
        $controller = $injector.get("$controller");
        loginService = $injector.get("LoginService");
        alertModalService = $injector.get("AlertModalService");
        const $rootScope: IRootScopeService = $injector.get("$rootScope");
        $scope = $rootScope.$new(true);

        ctrl = $controller("SignUpCtrl", {
            $scope: $scope
        });
    }));

    it("should initialise with expected values", () => {
        expect(ctrl.email).toBe("");
        expect(ctrl.groupName).toBe("");
        expect(ctrl.validPassword).toBeUndefined();
        expect(ctrl.isSubmitted).toBe(false);
    });

    describe("Registration", () => {
        beforeEach(() => {
            spyOn(alertModalService, "show");
            spyOn($location, "path");
        });

        it("should attempt registration and when successful show info alert and move to login page", () => {
            spyOn(loginService, "attemptRegistration").and.callFake(() => {
                const deferred: IDeferred<any> = $q.defer();
                deferred.resolve({ message: "You have successfully registered and have been sent an email - please open this " +
                    "email and click on the link to verify your email address before logging in."});
                return deferred.promise;
            });

            ctrl.email = "test@test.com";
            ctrl.groupName = "Group name";
            ctrl.validPassword = "Pa$$w0rd1";

            ctrl.signUp();

            expect(ctrl.isSubmitted).toBe(true);

            $scope.$digest();

            expect(ctrl.isSubmitted).toBe(false);
            expect(alertModalService.show).toHaveBeenCalledWith({
                style: "info",
                title: "Information",
                message: "You have successfully registered and have been sent an email - please open this email" +
                " and click on the link to verify your email address before logging in."
            });
            expect(loginService.attemptRegistration).toHaveBeenCalledWith("testtestcom", "test@test.com", ctrl.groupName,
                ctrl.validPassword, ctrl.validPassword);
            expect($location.path).toHaveBeenCalledWith("/page/login");
        });

        it("should attempt registration and on failure show warning alert", () => {
            spyOn(loginService, "attemptRegistration").and.callFake(() => {
                const deferred: IDeferred<any> = $q.defer();
                deferred.reject({data: { message: "Blew up" }});
                return deferred.promise;
            });

            ctrl.email = "test@test.com";
            ctrl.groupName = "Group name";
            ctrl.validPassword = "Pa$$w0rd1";

            ctrl.signUp();
            $scope.$digest();

            expect(alertModalService.show).toHaveBeenCalledWith({
                style: "warning",
                title: "Warning",
                message: "Blew up"
            });
            expect(loginService.attemptRegistration).toHaveBeenCalledWith("testtestcom", "test@test.com",
                ctrl.groupName, ctrl.validPassword, ctrl.validPassword);
            expect($location.path).not.toHaveBeenCalled();
        });
    });
});