text:
package com.wangf.sample.websocket;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/chat")
public class ChatRoomWebSocketServer {
	// The socket server is NOT application level, so must use static map to
	// store the sessions.
	private static final Set<Session> sessions = new HashSet<>();

	@OnOpen
	public void open(Session session) {
		sessions.add(session);
	}

	@OnClose
	public void close(Session session) {
		sessions.remove(session);
	}

	@OnError
	public void onError(Throwable error) {
	}

	@OnMessage
	public void handleMessage(String message, Session session) throws IOException {
		sendToAllConnectedSessions(message);
	}

	private void sendToAllConnectedSessions(String message) throws IOException {
		for (Session session : sessions) {
			sendToSession(session, message);
		}
	}

	private void sendToSession(Session session, String message) throws IOException {
		try {
			session.getBasicRemote().sendText(message.toString());
		} catch (IOException ex) {
			sessions.remove(session);
			throw ex;
		}
	}
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Webix - Angular  : Grid</title>

  <link rel="stylesheet" type="text/css" href="../../codebase/webix.css">

Rating

Year

Votes

Title

<button ng-click="addRecord()">Add Row</button>

redpajama_set_name: RedPajamaGithub


text:
package org.kuali.rice.krad.uif.element;

import org.apache.commons.lang.StringUtils;
import org.kuali.rice.krad.datadictionary.parse.BeanTag;
import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
import org.kuali.rice.krad.datadictionary.parse.BeanTags;
import org.kuali.rice.krad.datadictionary.validator.ValidationTrace;
import org.kuali.rice.krad.datadictionary.validator.Validator;
import org.kuali.rice.krad.uif.component.Component;
import org.kuali.rice.krad.uif.util.ComponentFactory;
import org.kuali.rice.krad.uif.util.LifecycleElement;

/**
 * Content element that renders a HTML <IMG> tag
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
@BeanTag(name = "image", parent = "Uif-Image")
public class Image extends ContentElementBase {
    private static final long serialVersionUID = -3911849875276940507L;

    private String source;
    private String altText;
    private String height;
    private String width;

    private boolean captionHeaderPlacementAboveImage;

    private String captionHeaderText;
    private Header captionHeader;

    private String cutlineText;
    private Message cutlineMessage;

    public Image() {
        super();

        altText = "";
    }

    /**
     * The following initialization is performed:
     *
     *

     *
Initializes the cutline message and caption header components if necessary

     *

     *
     * {@inheritDoc}
     */
    @Override
    public void performInitialization(Object model) {
        super.performInitialization(model);

        if ((StringUtils.isNotBlank(captionHeaderText) || (getPropertyExpression("captionHeaderText") != null)) && (
                captionHeader == null)) {
            captionHeader = ComponentFactory.getImageCaptionHeader();
        }

        if ((StringUtils.isNotBlank(cutlineText) || (getPropertyExpression("cutlineText") != null)) && (cutlineMessage
                == null)) {
            cutlineMessage = ComponentFactory.getImageCutlineMessage();
        }
    }

    /**
     * Performs the following steps
     *
     *

     *
Set the caption header text on the caption header

     *
Set the cutline text on the cutline message

     *

     *
     * {@inheritDoc}
     */
    @Override
    public void performApplyModel(Object model, LifecycleElement parent) {
        super.performApplyModel(model, parent);

        if (StringUtils.isNotBlank(captionHeaderText)) {
            captionHeader.setHeaderText(captionHeaderText);
        }

        if (StringUtils.isNotBlank(cutlineText)) {
            cutlineMessage.setMessageText(cutlineText);
        }
    }

    /**
     * returns the URL of this image
     *
     * @return the URL of this image.
     */
    @BeanTagAttribute
    public String getSource() {
        return this.source;
    }

    /**
     * Sets the URL of this image
     *
     * @param source the URL of this image
     */
    public void setSource(String source) {
        this.source = source;
    }

    /**
     * Provides alternate information for the image element
     *
     *
The altText property specifies an alternate text for an image. It is displayed by the browser
     * if the image cannot be displayed.  This is especially important for accessibility, because screen
     * readers can't understand images, but rather will read aloud the alternative text assigned to them.
     *

     * Some best practices:
     *

     *
spacer images, bullets, and icons should have the altText set to null or the empty string. This
     * will prevent screen readers from announcing it.

     *
Make the altText message as short and succinct as possible

     *
Describe the content of the image and nothing more

     *

     *

     *
     * @return alternative information about this image
     */
    @BeanTagAttribute
    public String getAltText() {
        return this.altText;
    }

    /**
     * Sets the alternate text property for this image
     *
     * @param altText the alternative information about the image
     */
    public void setAltText(String altText) {
        this.altText = altText;
    }

    /**
     * Returns the height style attribute of this image
     *
     *

     * The default unit of measure is pixels.

     * It is good practice to specify both the height and width attributes for an image.
     * If these attributes are set, the space required for the image is reserved when the page is loaded.
     * However, without these attributes, the browser does not know the size of the image. The effect will
     * be that the page layout will change while the images load.
     *

     *
     * @return the height style attribute of this image
     */
    @BeanTagAttribute
    public String getHeight() {
        return this.height;
    }

    /**
     * Sets the height style attribute of the image.
     *
     * @param height the height of the image
     */
    public void setHeight(String height) {
        this.height = height;
    }

    /**
     * Returns the width style attribute of the image
     *
     *

     * The default unit of measure is pixels.

     * It is good practice to specify both the height and width attributes for an image.
     * If these attributes are set, the space required for the image is reserved when the page is loaded.
     * However, without these attributes, the browser does not know the size of the image. The effect will
     * be that the page layout will change while the images load.
     *

     *
     * @return the width of this image
     */
    @BeanTagAttribute
    public String getWidth() {
        return width;
    }

    /**
     * Sets the width style attribute of the image
     *
     * @param width the width of this image
     */
    public void setWidth(String width) {
        this.width = width;
    }

    /**
     * Retrieves the caption text for this image
     *
     *

     * The caption text is a headline for the picture. It may be displayed either above or below the picture.
     *

     *
     * @return the caption
     */
    @BeanTagAttribute
    public String getCaptionHeaderText() {
        return captionHeaderText;
    }

    /**
     * Sets the text displayed as of the caption for the picture
     *
     * @param captionHeaderText the caption text
     */
    public void setCaptionHeaderText(String captionHeaderText) {
        this.captionHeaderText = captionHeaderText;
    }

    /**
     * Retrieves the {@link Header} component used to display the caption for this image
     *
     * @return Header component which wraps the caption text.
     */
    @BeanTagAttribute
    public Header getCaptionHeader() {
        return captionHeader;
    }

    /**
     * Sets the Header used to display the caption for this image
     *
     * @param captionHeader header component which wraps the caption text
     */
    public void setCaptionHeader(Header captionHeader) {
        this.captionHeader = captionHeader;
    }

    /**
     * Retrieves the cutline text for this image
     *
     *

     * The cutline text give more detailed information about the picture. Generally it describes
     * the who, what, where, when of this image.
     *

     *
     * @return the cutline text.
     */
    @BeanTagAttribute
    public String getCutlineText() {
        return cutlineText;
    }

    /**
     * Sets the cutline text that describes this image
     *
     * @param cutlineText the cutline text that describes this image
     */
    public void setCutlineText(String cutlineText) {
        this.cutlineText = cutlineText;
    }

    /**
     * Gets the {@link Message} component used to display the cutline.
     *
     *

     * Wrapping the cutline text with a Message component allows styling of the cutline text.
     *

     *
     * @return Message component wrapping the cutline
     */
    @BeanTagAttribute
    public Message getCutlineMessage() {
        return cutlineMessage;
    }

    /**
     * Sets the Message component used to display the cutline for this image
     *
     * @param cutlineMessage Message
     */
    public void setCutlineMessage(Message cutlineMessage) {
        this.cutlineMessage = cutlineMessage;
    }

    /**
     * Specifies whether the image caption is to be displayed above or below the image
     *
     * @return true if the caption is to be displayed above the image. false if displayed below the image.
     */
    @BeanTagAttribute
    public boolean isCaptionHeaderPlacementAboveImage() {
        return captionHeaderPlacementAboveImage;
    }

    /**
     * Sets whether the image caption is to be displayed above or below the image
     *
     * @param captionHeaderPlacementAboveImage true displays above image, false displays below image
     */
    public void setCaptionHeaderPlacementAboveImage(boolean captionHeaderPlacementAboveImage) {
        this.captionHeaderPlacementAboveImage = captionHeaderPlacementAboveImage;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void completeValidation(ValidationTrace tracer){
        tracer.addBean(this);

        // Checks that a source is set
        if(getSource()==null){
            if(!Validator.checkExpressions(this, "source")){
                String currentValues [] = {"source ="+getSource()};
                tracer.createError("Source must be set",currentValues);
            }
        }

        // Checks that alt text is set
        if(getAltText().compareTo("")==0){
            if(Validator.checkExpressions(this, "altText")){
                String currentValues [] = {"altText ="+getAltText()};
                tracer.createWarning("Alt text should be set, violates accessibility standards if not set",currentValues);
            }
        }

        super.completeValidation(tracer.getCopy());
    }
}


text:
'use strict';
angular.module('com.module.products')
  .run(function($rootScope, Product, Category, gettextCatalog) {

    // Product.find(function(data) {
    //   $rootScope.addDashboardBox(gettextCatalog.getString('Company'),
    //     'bg-yellow', 'ion-ios7-cart-outline', data.length,
    //     'app.products.list');
    // });
    //
    // Category.find(function(data) {
    //   $rootScope.addDashboardBox(gettextCatalog.getString('Groups'),
    //     'bg-aqua', 'ion-ios7-pricetag-outline', data.length,
    //     'app.products.list');
    // });

  });


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30311_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">A
Continental
Created By MEB Date: 11:07. November 19 20 Plan: Design #1
a E w 3 O O o 2', S o. d) D a .9 E > d) E .—
1000 -500
Any decisions made or wells drilled ufil'


text:
import { Box, Skeleton } from '@rocket.chat/fuselage';
import React, { FC } from 'react';

const LoadingDetails: FC = () => (
	<Box display='flex' flexDirection='row' mbe='x20' w='full'>
		<Skeleton variant='rect' w='x120' h='x120' mie='x20' />
		<Box display='flex' flexDirection='column' justifyContent='space-between' flexGrow={1}>
			<Skeleton variant='rect' w='full' h='x32' />
			<Skeleton variant='rect' w='full' h='x32' />
			<Skeleton variant='rect' w='full' h='x32' />
		</Box>
	</Box>
);

export default LoadingDetails;


text:
package com.robocubs4205.cubscout.rest.v1;

import com.robocubs4205.cubscout.model.Robot;
import com.robocubs4205.cubscout.model.RobotRepository;
import com.robocubs4205.cubscout.model.scorecard.ResultRepository;
import com.robocubs4205.cubscout.rest.JsonArrayContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static org.springframework.http.HttpHeaders.LOCATION;

@RestController
@RequestMapping(value = "/robots",produces = "application/vnd.robocubs-v1+json")
public class RobotController {
    private final RobotRepository robotRepository;
    private final ResultRepository resultRepository;

    @Autowired
    public RobotController(RobotRepository robotRepository, ResultRepository resultRepository) {
        this.robotRepository = robotRepository;
        this.resultRepository = resultRepository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public JsonArrayContainer<RobotResource> getAll() {
        return new JsonArrayContainer<>(new RobotResourceAssembler().toResources(robotRepository.findAll()));
    }

    @RequestMapping(value = "/{robot:[0-9]+}", method = RequestMethod.GET)
    public RobotResource getRobot(@PathVariable Robot robot) {
        if (robot == null) throw new ResourceNotFoundException();
        return new RobotResourceAssembler().toResource(robot);
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public RobotResource create(@RequestBody Robot robot, HttpServletResponse response) {
        robot = robotRepository.saveAndFlush(robot);
        RobotResource robotResource = new RobotResourceAssembler().toResource(robot);
        response.setHeader(LOCATION,robotResource.getLink("self").getHref());
        return robotResource;
    }

    @RequestMapping(value = "/{robot:[0-9]+}", method = RequestMethod.PUT)
    public RobotResource update(@PathVariable Robot robot, @RequestBody Robot newRobot) {
        robot.setYear(newRobot.getYear());
        robot = robotRepository.saveAndFlush(robot);
        return new RobotResourceAssembler().toResource(robot);
    }

    @RequestMapping(value = "/{robot:[0-9]+}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Robot robot) {
        robotRepository.delete(robot);
        robotRepository.flush();
    }

    @RequestMapping(value = "/{robot:[0-9]+}/results",method = RequestMethod.GET)
    public JsonArrayContainer<ResultResource> getResults(@PathVariable Robot robot) {
        if (robot == null) throw new ResourceNotFoundException();
        return new JsonArrayContainer<>(new ResultResourceAssembler().toResources(resultRepository.findByRobot(robot)));
    }

    @RequestMapping(value = "/{robot:[0-9]+}/matches",method = RequestMethod.GET)
    public JsonArrayContainer<MatchResource> getMatches(@PathVariable Robot robot) {
        if (robot == null) throw new ResourceNotFoundException();
        return new JsonArrayContainer<>(new MatchResourceAssembler().toResources(robot.getMatches()));
    }
}


text:
Here are some hints how to make your map faster. It is useful if you have bigger datasets.

### LocalVectorDataSource Performance

You can define the `spatialIndexType` of the `LocalVectorDataSource` to improve the performance of how a 3D model loads, by defining a spatial index to the DataSource. By default, no spatial index is defined. The following rules apply:

-  Do not define a spatial index if the number of elements is small, below ~1000 points or markers (or even less if you have complex lines and polygons). _This is the default option_

-  Apply `NT_LOCAL_SPATIAL_INDEX_TYPE_KDTREE` as the index type if there are a larger number of elements

The advantage of defining a spatial index is that CPU usage decreases for large number of objects, improving the map performance of panning and zooming. However, displaying overlays may slightly delay the map response, as the spatial index is not loaded immediately when your move the map, it only moves after some hundred milliseconds.

The overall maximum number of objects on map is limited to the RAM available for the app. Systems define several hundred MB for iOS apps, and closer to tens of MB for Android apps, but it depends on the device and app settings (as well as the density of the data). It is recommended to test your app with the targeted mobile platform and full dataset for the actual performance.

The following code describes how to adjust the `LocalVectorDataSource` performance by defining a spatial index:

       Java

       C#

       Objective-C

       Swift

       Kotlin

    {% highlight java linenos %}
    LocalVectorDataSource vectorDataSource2 = new LocalVectorDataSource(proj, LocalSpatialIndexType.LOCAL_SPATIAL_INDEX_TYPE_KDTREE);
    {% endhighlight %}

    {% highlight csharp linenos %}
    var vectorDataSource2 = new LocalVectorDataSource(proj, LocalSpatialIndexType.LocalSpatialIndexTypeKdtree);
    {% endhighlight %}

    {% highlight objc linenos %}
    NTLocalVectorDataSource* vectorDataSource2 =
        [[NTLocalVectorDataSource alloc] initWithProjection:proj
                                         spatialIndexType: NTLocalSpatialIndexType::NT_LOCAL_SPATIAL_INDEX_TYPE_KDTREE];
    {% endhighlight %}

    {% highlight swift linenos %}
    let vectorDataSource2 = NTLocalVectorDataSource(projection: projection, spatialIndexType: NTLocalSpatialIndexType.LOCAL_SPATIAL_INDEX_TYPE_KDTREE)
    {% endhighlight %}

    {% highlight kotlin linenos %}
    val vectorDataSource2 = LocalVectorDataSource(projection, LocalSpatialIndexType.LOCAL_SPATIAL_INDEX_TYPE_KDTREE)
    {% endhighlight %}

**Note:** If you have **very complex lines or polygons**, this creates objects with high numbers (more than hundreds of points per object) of vertexes. For example, the GPS traces for long periods of time, recording a point every second or so.

Spatial indexing will not help in this case, as you need to show the whole track on the screen. In this case, apply the **automatic line simplification** parameter for the `LocalVectorDataSource`. This reduces the number of polygon and line points, while maintaining the original object shape.

**Tip:** Automatic simplification is zoom-dependent. When a map is zoomed out, more aggressive simplification is used. When you zoom in, less simplification is applied until you see the original details.

There are several ways to simplify geometries for automatic simplification by using the following code. Note that simplification is applied in two passes:

- First pass applies fast Radial Distance vertex rejection
- Second pass applies Ramer-Douglas-Peuckerworst algorithm (with the worst case quadratic complexity)

All this is can be applied with just one line of code - as shown in the following example (under iOS) for minimal 1-pixel simplification, the result is invisible but effects are significant, depending on your DataSource:

       Java

       C#

       Objective-C

       Swift

       Kotlin

    {% highlight java linenos %}
    vectorDataSource2.setGeometrySimplifier(new DouglasPeuckerGeometrySimplifier(1.0f / 320.0f));
    {% endhighlight %}

    {% highlight csharp linenos %}
    vectorDataSource2.GeometrySimplifier = new DouglasPeuckerGeometrySimplifier(1.0f / 320.0f);
    {% endhighlight %}

    {% highlight objc linenos %}
    [vectorDataSource2 setGeometrySimplifier:
        [[NTDouglasPeuckerGeometrySimplifier alloc] initWithTolerance: 1.0f / 320.0f]
    ];
    {% endhighlight %}

    {% highlight swift linenos %}
    vectorDataSource2?.setGeometrySimplifier(NTDouglasPeuckerGeometrySimplifier(tolerance: 1.0 / 320.0))
    {% endhighlight %}

    {% highlight kotlin linenos %}
    vectorDataSource2.geometrySimplifier = DouglasPeuckerGeometrySimplifier(1.0f / 320.0f)
    {% endhighlight %}

The automatic simplification makes rendering faster with some additional computation on the CPU.


text:
package com.lucafontanili.designpatterns.structural.adapter;

public class AudioPlayer implements AudioPlayerInterface {

    @Override
    public void playSong(String trackName) {
	LOGGER.info(new StringBuilder(64).append("Playing track: ").append(trackName).toString());
    }

}


text:
package org.apache.hadoop.hbase.replication;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.UnknownScannerException;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.testclassification.ReplicationTests;
import org.junit.experimental.categories.Category;

import static org.junit.Assert.fail;

@Category({ReplicationTests.class, LargeTests.class})
public class TestReplicationKillRS extends TestReplicationBase {

  private static final Log LOG = LogFactory.getLog(TestReplicationKillRS.class);

  /**
   * Load up 1 tables over 2 region servers and kill a source during
   * the upload. The failover happens internally.
   *
   * WARNING this test sometimes fails because of HBASE-3515
   *
   * @throws Exception
   */
  public void loadTableAndKillRS(HBaseTestingUtility util) throws Exception {
    // killing the RS with hbase:meta can result into failed puts until we solve
    // IO fencing
    int rsToKill1 =
        util.getHBaseCluster().getServerWithMeta() == 0 ? 1 : 0;

    // Takes about 20 secs to run the full loading, kill around the middle
    Thread killer = killARegionServer(util, 5000, rsToKill1);

    LOG.info("Start loading table");
    int initialCount = utility1.loadTable(htable1, famName);
    LOG.info("Done loading table");
    killer.join(5000);
    LOG.info("Done waiting for threads");

    Result[] res;
    while (true) {
      try {
        Scan scan = new Scan();
        ResultScanner scanner = htable1.getScanner(scan);
        res = scanner.next(initialCount);
        scanner.close();
        break;
      } catch (UnknownScannerException ex) {
        LOG.info("Cluster wasn't ready yet, restarting scanner");
      }
    }
    // Test we actually have all the rows, we may miss some because we
    // don't have IO fencing.
    if (res.length != initialCount) {
      LOG.warn("We lost some rows on the master cluster!");
      // We don't really expect the other cluster to have more rows
      initialCount = res.length;
    }

    int lastCount = 0;

    final long start = System.currentTimeMillis();
    int i = 0;
    while (true) {
      if (i==NB_RETRIES-1) {
        fail("Waited too much time for queueFailover replication. " +
            "Waited "+(System.currentTimeMillis() - start)+"ms.");
      }
      Scan scan2 = new Scan();
      ResultScanner scanner2 = htable2.getScanner(scan2);
      Result[] res2 = scanner2.next(initialCount * 2);
      scanner2.close();
      if (res2.length < initialCount) {
        if (lastCount < res2.length) {
          i--; // Don't increment timeout if we make progress
        } else {
          i++;
        }
        lastCount = res2.length;
        LOG.info("Only got " + lastCount + " rows instead of " +
            initialCount + " current i=" + i);
        Thread.sleep(SLEEP_TIME*2);
      } else {
        break;
      }
    }
  }

  private static Thread killARegionServer(final HBaseTestingUtility utility,
                                          final long timeout, final int rs) {
    Thread killer = new Thread() {
      public void run() {
        try {
          Thread.sleep(timeout);
          utility.getHBaseCluster().getRegionServer(rs).stop("Stopping as part of the test");
        } catch (Exception e) {
          LOG.error("Couldn't kill a region server", e);
        }
      }
    };
    killer.setDaemon(true);
    killer.start();
    return killer;
  }
}


text:
/***************************************************************************
 * JNI
 ***************************************************************************/

#include <engine/renderer/renderer.h>
#include "objects/index_buffer.h"

#include "util/gvr_log.h"
#include "util/gvr_jni.h"

namespace gvr {
    extern "C" {
    JNIEXPORT jlong JNICALL
    Java_org_gearvrf_NativeIndexBuffer_ctor(JNIEnv* env, jobject obj,
                                            int bytesPerIndex, int vertexCount);
    JNIEXPORT bool JNICALL
    Java_org_gearvrf_NativeIndexBuffer_getIntVec(JNIEnv* env, jobject obj, jlong jibuf, jobject data);

    JNIEXPORT jintArray JNICALL
    Java_org_gearvrf_NativeIndexBuffer_getIntArray(JNIEnv* env, jobject obj, jlong jibuf);

    JNIEXPORT bool JNICALL
    Java_org_gearvrf_NativeIndexBuffer_setIntArray(JNIEnv* env, jobject obj, jlong jibuf, jintArray data);

    JNIEXPORT bool JNICALL
    Java_org_gearvrf_NativeIndexBuffer_setIntVec(JNIEnv* env, jobject obj, jlong jibuf, jobject jintbuf);

    JNIEXPORT bool JNICALL
    Java_org_gearvrf_NativeIndexBuffer_getShortVec(JNIEnv* env, jobject obj, jlong jibuf, jobject jshortbuf);

    JNIEXPORT jcharArray JNICALL
    Java_org_gearvrf_NativeIndexBuffer_getShortArray(JNIEnv* env, jobject obj, jlong jibuf);

    JNIEXPORT bool JNICALL
    Java_org_gearvrf_NativeIndexBuffer_setShortArray(JNIEnv* env, jobject obj, jlong jibuf, jcharArray data);

    JNIEXPORT bool JNICALL
    Java_org_gearvrf_NativeIndexBuffer_setShortVec(JNIEnv* env, jobject obj, jlong jibuf, jobject jshortbuf);

    JNIEXPORT int JNICALL
    Java_org_gearvrf_NativeIndexBuffer_getIndexSize(JNIEnv* env, jobject obj, jlong jibuf);

    JNIEXPORT int JNICALL
    Java_org_gearvrf_NativeIndexBuffer_getIndexCount(JNIEnv* env, jobject obj, jlong jibuf);

};

JNIEXPORT jlong JNICALL
Java_org_gearvrf_NativeIndexBuffer_ctor(JNIEnv* env, jobject obj, int bytesPerVertex, int vertexCount)
{
    IndexBuffer* ibuf = Renderer::getInstance()->createIndexBuffer(bytesPerVertex, vertexCount);
    return reinterpret_cast<jlong>(ibuf);
}

JNIEXPORT bool JNICALL
Java_org_gearvrf_NativeIndexBuffer_getShortVec(JNIEnv * env, jobject obj, jlong jibuf, jobject jshortbuf)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    void* bufptr = env->GetDirectBufferAddress(jshortbuf);
    bool rc = false;
    if (bufptr)
    {
        int capacity = env->GetDirectBufferCapacity(jshortbuf);
        rc = ibuf->getShortVec((unsigned short*) bufptr, capacity);
    }
    return rc;
}

JNIEXPORT bool JNICALL
Java_org_gearvrf_NativeIndexBuffer_getIntVec(JNIEnv * env, jobject obj, jlong jibuf, jobject jdata)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    void* bufptr = env->GetDirectBufferAddress(jdata);
    bool rc = false;
    if (bufptr)
    {
        int capacity = env->GetDirectBufferCapacity(jdata);
        rc = ibuf->getIntVec((unsigned int*) bufptr, capacity);
    }
    return rc;
}

JNIEXPORT jintArray JNICALL
Java_org_gearvrf_NativeIndexBuffer_getIntArray(JNIEnv* env, jobject obj, jlong jibuf)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    int n = ibuf->getIndexCount();
    jintArray jdata = env->NewIntArray(n);
    unsigned int* data = reinterpret_cast<unsigned int*>(env->GetIntArrayElements(jdata, 0));
    ibuf->getIntVec(data, n);
    env->ReleaseIntArrayElements(jdata, reinterpret_cast<jint*>(data), 0);
    return jdata;
}

JNIEXPORT jcharArray JNICALL
Java_org_gearvrf_NativeIndexBuffer_getShortArray(JNIEnv* env, jobject obj, jlong jibuf)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    jchar n = ibuf->getIndexCount();
    jcharArray jdata = env->NewCharArray(n);
    unsigned short* data = reinterpret_cast<unsigned short*>(env->GetCharArrayElements(jdata, 0));
    ibuf->getShortVec(data, n);
    env->ReleaseCharArrayElements(jdata, reinterpret_cast<jchar*>(data), 0);
    return jdata;
}

JNIEXPORT bool JNICALL
Java_org_gearvrf_NativeIndexBuffer_setShortArray(JNIEnv * env, jobject obj, jlong jibuf, jcharArray jdata)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    jchar* data = env->GetCharArrayElements(jdata, 0);
    bool rc = ibuf->setShortVec(data, static_cast<int>(env->GetArrayLength(jdata)));
    env->ReleaseCharArrayElements(jdata, data, 0);
    return rc;
}

JNIEXPORT bool JNICALL
Java_org_gearvrf_NativeIndexBuffer_setShortVec(JNIEnv * env, jobject obj, jlong jibuf, jobject jshortbuf)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    void* bufptr = env->GetDirectBufferAddress(jshortbuf);
    bool rc = false;
    if (bufptr)
    {
        jlong capacity = env->GetDirectBufferCapacity(jshortbuf);
        rc = ibuf->setShortVec((unsigned short*) bufptr, capacity);
    }
    return rc;
}

JNIEXPORT bool JNICALL
Java_org_gearvrf_NativeIndexBuffer_setIntVec(JNIEnv* env, jobject obj, jlong jibuf, jobject jintbuf)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    void* bufptr = env->GetDirectBufferAddress(jintbuf);
    bool rc = false;
    if (bufptr)
    {
        jlong capacity = env->GetDirectBufferCapacity(jintbuf);
        rc = ibuf->setIntVec((unsigned int*) bufptr, capacity);
    }
    return rc;
}

JNIEXPORT bool JNICALL
Java_org_gearvrf_NativeIndexBuffer_setIntArray(JNIEnv * env, jobject obj, jlong jibuf, jintArray jdata)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    unsigned int* data = reinterpret_cast<unsigned int*>(env->GetIntArrayElements(jdata, 0));
    bool rc = ibuf->setIntVec(data, static_cast<int>(env->GetArrayLength(jdata)));
    env->ReleaseIntArrayElements(jdata, reinterpret_cast<jint*>(data), 0);
    return rc;
}

JNIEXPORT int JNICALL
Java_org_gearvrf_NativeIndexBuffer_getIndexCount(JNIEnv* env, jobject obj, jlong jibuf)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    return ibuf->getIndexCount();
}

JNIEXPORT int JNICALL
Java_org_gearvrf_NativeIndexBuffer_getIndexSize(JNIEnv* env, jobject obj, jlong jibuf)
{
    IndexBuffer* ibuf = reinterpret_cast<IndexBuffer*>(jibuf);
    return ibuf->getIndexSize();
}

}


text:
Something will be said

“A block quotation (also known as a long quotation or extract) is a quotation in a written document, that is set off from the main text as a paragraph, or block of text, and typically distinguished visually using indentation and a different typeface or smaller size quotation.”

	Wikiepedia


text:
package com.wesleyhome.math.node;

import com.wesleyhome.math.expression.EnhancedNumber;
import com.wesleyhome.math.grammer.calculator.CalculatorParser.ScientificContext;

class ScientificNode extends CalculatorNode {

    private final String numberString;

    ScientificNode(ScientificContext scientific) {
        numberString = scientific.getText();
    }

    @Override
    public EnhancedNumber evaluate() {
        return EnhancedNumber.eq(numberString);
    }

    @Override
    public String toString() {
        return numberString;
    }
}


text:
"""
Module for rebootmgr
:maintainer:    Alberto Planas <aplanas@suse.com>
:maturity:      new
:depends:       None
:platform:      Linux

.. versionadded:: 3004
"""

import logging
import re

import salt.exceptions

log = logging.getLogger(__name__)

def __virtual__():
    """rebootmgrctl command is required."""
    if __utils__["path.which"]("rebootmgrctl") is not None:
        return True
    else:
        return (False, "Module rebootmgt requires the command rebootmgrctl")

def _cmd(cmd, retcode=False):
    """Utility function to run commands."""
    result = __salt__["cmd.run_all"](cmd)
    if retcode:
        return result["retcode"]

    if result["retcode"]:
        raise salt.exceptions.CommandExecutionError(result["stderr"])

    return result["stdout"]

def version():
    """Return the version of rebootmgrd

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr version

    """
    cmd = ["rebootmgrctl", "--version"]

    return _cmd(cmd).split()[-1]

def is_active():
    """Check if the rebootmgrd is running and active or not.

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr is_active

    """
    cmd = ["rebootmgrctl", "is_active", "--quiet"]

    return _cmd(cmd, retcode=True) == 0

def reboot(order=None):
    """Tells rebootmgr to schedule a reboot.

    With the [now] option, a forced reboot is done, no lock from etcd
    is requested and a set maintenance window is ignored. With the
    [fast] option, a lock from etcd is requested if needed, but a
    defined maintenance window is ignored.

    order
        If specified, can be "now" or "fast"

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr reboot
        salt microos rebootmgt reboot order=now

    """
    if order and order not in ("now", "fast"):
        raise salt.exceptions.CommandExecutionError(
            "Order parameter, if specified, must be 'now' or 'fast'"
        )

    cmd = ["rebootmgrctl", "reboot"]
    if order:
        cmd.append(order)

    return _cmd(cmd)

def cancel():
    """Cancels an already running reboot.

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr cancel

    """
    cmd = ["rebootmgrctl", "cancel"]

    return _cmd(cmd)

def status():
    """Returns the current status of rebootmgrd.

    Valid returned values are:
      0 - No reboot requested
      1 - Reboot requested
      2 - Reboot requested, waiting for maintenance window
      3 - Reboot requested, waiting for etcd lock.

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr status

    """
    cmd = ["rebootmgrctl", "status", "--quiet"]

    return _cmd(cmd, retcode=True)

def set_strategy(strategy=None):
    """A new strategy to reboot the machine is set and written into
    /etc/rebootmgr.conf.

    strategy
        If specified, must be one of those options:

        best-effort - This is the default strategy. If etcd is
            running, etcd-lock is used. If no etcd is running, but a
            maintenance window is specified, the strategy will be
            maint-window. If no maintenance window is specified, the
            machine is immediately rebooted (instantly).

        etcd-lock - A lock at etcd for the specified lock-group will
            be acquired before reboot. If a maintenance window is
            specified, the lock is only acquired during this window.

        maint-window - Reboot does happen only during a specified
            maintenance window. If no window is specified, the
            instantly strategy is followed.

        instantly - Other services will be informed that a reboot will
            happen. Reboot will be done without getting any locks or
            waiting for a maintenance window.

        off - Reboot requests are temporary
            ignored. /etc/rebootmgr.conf is not modified.

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr set_strategy stragegy=off

    """
    if strategy and strategy not in (
        "best-effort",
        "etcd-lock",
        "maint-window",
        "instantly",
        "off",
    ):
        raise salt.exceptions.CommandExecutionError("Strategy parameter not valid")

    cmd = ["rebootmgrctl", "set-strategy"]
    if strategy:
        cmd.append(strategy)

    return _cmd(cmd)

def get_strategy():
    """The currently used reboot strategy of rebootmgrd will be printed.

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr get_strategy

    """
    cmd = ["rebootmgrctl", "get-strategy"]

    return _cmd(cmd).split(":")[-1].strip()

def set_window(time, duration):
    """Set's the maintenance window.

    time
        The format of time is the same as described in
        systemd.time(7).

    duration
         The format of duration is "[XXh][YYm]".

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr set_window time="Thu,Fri 2020-*-1,5 11:12:13" duration=1h

    """
    cmd = ["rebootmgrctl", "set-window", time, duration]

    return _cmd(cmd)

def get_window():
    """The currently set maintenance window will be printed.

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr get_window

    """
    cmd = ["rebootmgrctl", "get-window"]
    window = _cmd(cmd)

    return dict(
        zip(
            ("time", "duration"),
            re.search(
                r"Maintenance window is set to (.*), lasting (.*).", window
            ).groups(),
        )
    )

def set_group(group):
    """Set the group, to which this machine belongs to get a reboot lock
       from etcd.

    group
        Group name

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr set_group group=group_1

    """
    cmd = ["rebootmgrctl", "set-group", group]

    return _cmd(cmd)

def get_group():
    """The currently set lock group for etcd.

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr get_group

    """
    cmd = ["rebootmgrctl", "get-group"]
    group = _cmd(cmd)

    return re.search(r"Etcd lock group is set to (.*)", group).groups()[0]

def set_max(max_locks, group=None):
    """Set the maximal number of hosts in a group, which are allowed to
       reboot at the same time.

    number
        Maximal number of hosts in a group

    group
        Group name

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr set_max 4

    """
    cmd = ["rebootmgrctl", "set-max"]
    if group:
        cmd.extend(["--group", group])
    cmd.append(max_locks)

    return _cmd(cmd)

def lock(machine_id=None, group=None):
    """Lock a machine. If no group is specified, the local default group
       will be used. If no machine-id is specified, the local machine
       will be locked.

    machine_id
        The machine-id is a network wide, unique ID. Per default the
        ID from /etc/machine-id is used.

    group
        Group name

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr lock group=group1

    """
    cmd = ["rebootmgrctl", "lock"]
    if group:
        cmd.extend(["--group", group])
    if machine_id:
        cmd.append(machine_id)

    return _cmd(cmd)

def unlock(machine_id=None, group=None):
    """Unlock a machine. If no group is specified, the local default group
       will be used. If no machine-id is specified, the local machine
       will be locked.

    machine_id
        The machine-id is a network wide, unique ID. Per default the
        ID from /etc/machine-id is used.

    group
        Group name

    CLI Example:

    .. code-block:: bash

        salt microos rebootmgr unlock group=group1

    """
    cmd = ["rebootmgrctl", "unlock"]
    if group:
        cmd.extend(["--group", group])
    if machine_id:
        cmd.append(machine_id)

    return _cmd(cmd)


text:
package com.dystu.parallax;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {

    private ParallaxList  listView;

    private View header;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ParallaxList ) findViewById(R.id.listView);

        listView.setOverScrollMode(AbsListView.OVER_SCROLL_NEVER);

        header = View.inflate(this,R.layout.layout_header,null);
        final ImageView parallaxView = (ImageView) header.findViewById(R.id.parallaxImageView);
        listView.addHeaderView(header);

        header.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                listView.setParallaxView(parallaxView);
                header.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        listView.setAdapter(new MyAdapter(this));
    }

}


text:
require 'spec_helper'

RSpec.describe Trello::AssociationFetcher::HasOne do

  describe '#new' do
    let(:board) { instance_double(Trello::Board) }
    let(:has_one) {
      Trello::AssociationFetcher::HasOne.new(board, 'organization', { using: :test_id })
    }

    it 'has model attribute' do
      expect(has_one.model).to eq(board)
    end

    it 'has name attribute' do
      expect(has_one.name).to eq('organization')
    end

    it 'has options attribute' do
      expect(has_one.options).to eq({ using: :test_id })
    end
  end

  describe '.fetch' do
    let(:board) { instance_double(Trello::Board) }
    let(:params) { instance_double(Trello::AssociationFetcher::HasOne::Params) }
    let(:fetch_result) { double('fetch result') }
    let(:has_one_fetcher) {
      Trello::AssociationFetcher::HasOne.new(board, 'organization', { using: :test_id })
    }

    it 'return result from HasOne::Fetch and HasOne::Params' do
      expect(Trello::AssociationFetcher::HasOne::Params)
        .to receive(:new)
        .with(
          association_owner: board,
          association_name: 'organization',
          association_options: { using: :test_id }
        ).and_return(params)
      expect(Trello::AssociationFetcher::HasOne::Fetch)
        .to receive(:execute)
        .with(params)
        .and_return(fetch_result)

      expect(has_one_fetcher.fetch).to eq(fetch_result)
    end
  end

end


text:
class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if(n == 0) return 1;

        //n = 1
        int res = 10;
        // starting from n=2
        int d0 = 9; // first digits 1-9 9 choices
        int available_digits = 9;

        for(int i=2; i<=n && available_digits>0; i++, available_digits--) {
            d0 *= available_digits;
            res += d0;
        }

        return res;
    }
}

public class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if (n == 0)     return 1;

        // start from n==1
        int res = 10;
        // for n==2
        int uniqueDigits = 9;
        int availableNumber = 9;
        while (n > 1 && availableNumber > 0) {
            uniqueDigits = uniqueDigits * availableNumber;
            res += uniqueDigits;
            availableNumber--;
            n--;
        }
        return res;
    }
}


text:
package com.github.aselab.activerecord.sbt

import org.specs2.mutable._

object FieldSpec extends Specification {
  "Field" should {
    "apply" in {
      "name:string:required" in {
        Field(Seq("name", "string", "required")).toString mustEqual "@Required\n  name: String"
      }

      "age:int:option:range(min=0,max=100)" in {
        Field(Seq("age", "int", "option", "range(min=0,max=100)")).toString mustEqual "@Range(min=0,max=100)\n  age: Option[Int]"
      }

      "email:string:required:email" in {
        Field(Seq("email", "string", "required", "email")).toString mustEqual "@Required\n  @Email\n  email: String"
      }

      "ignore case" in {
        Field(Seq("name", "STRING", "REQUIRED")).toString mustEqual "@Required\n  name: String"
      }
    }

    "importStatement" in {
      "simple class name" in {
        Field("name", "String", false).importStatement must beNone
      }

      "qualified class name" in {
        Field("name", "com.github.aselab.SomeClass", false).importStatement must beSome("import com.github.aselab.SomeClass")
      }
    }

    "declaration" in {
      "isOption = true" in {
        Field("name", "com.github.aselab.SomeClass", true).declaration mustEqual "name: Option[SomeClass]"
      }

      "isOption = false" in {
        Field("name", "com.github.aselab.SomeClass", false).declaration mustEqual "name: SomeClass"
      }
    }
  }
}


text:
package org.ripple.bouncycastle.jcajce.provider.asymmetric.dsa;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.spec.DSAParameterSpec;
import java.security.spec.DSAPrivateKeySpec;
import java.util.Enumeration;

import org.ripple.bouncycastle.asn1.ASN1Encodable;
import org.ripple.bouncycastle.asn1.ASN1Integer;
import org.ripple.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.ripple.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.ripple.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.ripple.bouncycastle.asn1.x509.DSAParameter;
import org.ripple.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.ripple.bouncycastle.crypto.params.DSAPrivateKeyParameters;
import org.ripple.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil;
import org.ripple.bouncycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl;
import org.ripple.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier;

public class BCDSAPrivateKey
    implements DSAPrivateKey, PKCS12BagAttributeCarrier
{
    private static final long serialVersionUID = -4677259546958385734L;

    private BigInteger          x;
    private transient DSAParams dsaSpec;

    private transient PKCS12BagAttributeCarrierImpl attrCarrier = new PKCS12BagAttributeCarrierImpl();

    protected BCDSAPrivateKey()
    {
    }

    BCDSAPrivateKey(
        DSAPrivateKey key)
    {
        this.x = key.getX();
        this.dsaSpec = key.getParams();
    }

    BCDSAPrivateKey(
        DSAPrivateKeySpec spec)
    {
        this.x = spec.getX();
        this.dsaSpec = new DSAParameterSpec(spec.getP(), spec.getQ(), spec.getG());
    }

    public BCDSAPrivateKey(
        PrivateKeyInfo info)
        throws IOException
    {
        DSAParameter    params = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
        ASN1Integer      derX = (ASN1Integer)info.parsePrivateKey();

        this.x = derX.getValue();
        this.dsaSpec = new DSAParameterSpec(params.getP(), params.getQ(), params.getG());
    }

    BCDSAPrivateKey(
        DSAPrivateKeyParameters params)
    {
        this.x = params.getX();
        this.dsaSpec = new DSAParameterSpec(params.getParameters().getP(), params.getParameters().getQ(), params.getParameters().getG());
    }

    public String getAlgorithm()
    {
        return "DSA";
    }

    /**
     * return the encoding format we produce in getEncoded().
     *
     * @return the string "PKCS#8"
     */
    public String getFormat()
    {
        return "PKCS#8";
    }

    /**
     * Return a PKCS8 representation of the key. The sequence returned
     * represents a full PrivateKeyInfo object.
     *
     * @return a PKCS8 representation of the key.
     */
    public byte[] getEncoded()
    {
        return KeyUtil.getEncodedPrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(dsaSpec.getP(), dsaSpec.getQ(), dsaSpec.getG()).toASN1Primitive()), new ASN1Integer(getX()));
    }

    public DSAParams getParams()
    {
        return dsaSpec;
    }

    public BigInteger getX()
    {
        return x;
    }

    public boolean equals(
        Object o)
    {
        if (!(o instanceof DSAPrivateKey))
        {
            return false;
        }

        DSAPrivateKey other = (DSAPrivateKey)o;

        return this.getX().equals(other.getX())
            && this.getParams().getG().equals(other.getParams().getG())
            && this.getParams().getP().equals(other.getParams().getP())
            && this.getParams().getQ().equals(other.getParams().getQ());
    }

    public int hashCode()
    {
        return this.getX().hashCode() ^ this.getParams().getG().hashCode()
                ^ this.getParams().getP().hashCode() ^ this.getParams().getQ().hashCode();
    }

    public void setBagAttribute(
        ASN1ObjectIdentifier oid,
        ASN1Encodable attribute)
    {
        attrCarrier.setBagAttribute(oid, attribute);
    }

    public ASN1Encodable getBagAttribute(
        ASN1ObjectIdentifier oid)
    {
        return attrCarrier.getBagAttribute(oid);
    }

    public Enumeration getBagAttributeKeys()
    {
        return attrCarrier.getBagAttributeKeys();
    }

    private void readObject(
        ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        in.defaultReadObject();

        this.dsaSpec = new DSAParameterSpec((BigInteger)in.readObject(), (BigInteger)in.readObject(), (BigInteger)in.readObject());
        this.attrCarrier = new PKCS12BagAttributeCarrierImpl();
    }

    private void writeObject(
        ObjectOutputStream out)
        throws IOException
    {
        out.defaultWriteObject();

        out.writeObject(dsaSpec.getP());
        out.writeObject(dsaSpec.getQ());
        out.writeObject(dsaSpec.getG());
    }
}


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

namespace System
{
    public class Type
    {
        public RuntimeTypeHandle TypeHandle { get { return default(RuntimeTypeHandle); } }
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct RuntimeTypeHandle
    {
        private EETypePtr _pEEType;

#if !PROJECTN
        [Intrinsic]
        internal static unsafe IntPtr GetValueInternal(RuntimeTypeHandle handle)
        {
            return (IntPtr)handle._pEEType.ToPointer();
        }
#endif
    }
}


text:
# Gin Web Framework

<img align="right" width="159px" src="https://raw.githubusercontent.com/gin-gonic/logo/master/color.png">

[![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin)
 [![codecov](https://codecov.io/gh/gin-gonic/gin/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-gonic/gin)
 [![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)](https://goreportcard.com/report/github.com/gin-gonic/gin)
 [![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin)
 [![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.

![Gin console logger](https://gin-gonic.github.io/gin/other/console.png)

```sh
# assume the following codes in example.go file
$ cat example.go
```

```go
package main

import "github.com/gin-gonic/gin"

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() // listen and serve on 0.0.0.0:8080
}
```

```
# run example.go and visit 0.0.0.0:8080/ping on browser
$ go run example.go
```

## Benchmarks

Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)

[See all benchmarks](/BENCHMARKS.md)

Benchmark name                              | (1)        | (2)         | (3) 		    | (4)
--------------------------------------------|-----------:|------------:|-----------:|---------:
**BenchmarkGin_GithubAll**                  | **30000**  |  **48375**  |     **0**  |   **0**
BenchmarkAce_GithubAll                      |   10000    |   134059    |   13792    |   167
BenchmarkBear_GithubAll                     |    5000    |   534445    |   86448    |   943
BenchmarkBeego_GithubAll                    |    3000    |   592444    |   74705    |   812
BenchmarkBone_GithubAll                     |     200    |  6957308    |  698784    |  8453
BenchmarkDenco_GithubAll                    |   10000    |   158819    |   20224    |   167
BenchmarkEcho_GithubAll                     |   10000    |   154700    |    6496    |   203
BenchmarkGocraftWeb_GithubAll               |    3000    |   570806    |  131656    |  1686
BenchmarkGoji_GithubAll                     |    2000    |   818034    |   56112    |   334
BenchmarkGojiv2_GithubAll                   |    2000    |  1213973    |  274768    |  3712
BenchmarkGoJsonRest_GithubAll               |    2000    |   785796    |  134371    |  2737
BenchmarkGoRestful_GithubAll                |     300    |  5238188    |  689672    |  4519
BenchmarkGorillaMux_GithubAll               |     100    | 10257726    |  211840    |  2272
BenchmarkHttpRouter_GithubAll               |   20000    |   105414    |   13792    |   167
BenchmarkHttpTreeMux_GithubAll              |   10000    |   319934    |   65856    |   671
BenchmarkKocha_GithubAll                    |   10000    |   209442    |   23304    |   843
BenchmarkLARS_GithubAll                     |   20000    |    62565    |       0    |     0
BenchmarkMacaron_GithubAll                  |    2000    |  1161270    |  204194    |  2000
BenchmarkMartini_GithubAll                  |     200    |  9991713    |  226549    |  2325
BenchmarkPat_GithubAll                      |     200    |  5590793    | 1499568    | 27435
BenchmarkPossum_GithubAll                   |   10000    |   319768    |   84448    |   609
BenchmarkR2router_GithubAll                 |   10000    |   305134    |   77328    |   979
BenchmarkRivet_GithubAll                    |   10000    |   132134    |   16272    |   167
BenchmarkTango_GithubAll                    |    3000    |   552754    |   63826    |  1618
BenchmarkTigerTonic_GithubAll               |    1000    |  1439483    |  239104    |  5374
BenchmarkTraffic_GithubAll                  |     100    | 11383067    | 2659329    | 21848
BenchmarkVulcan_GithubAll                   |    5000    |   394253    |   19894    |   609

(1): Total Repetitions achieved in constant time, higher means more confident result
(2): Single Repetition Duration (ns/op), lower is better
(3): Heap Memory (B/op), lower is better
(4): Average Allocations per Repetition (allocs/op), lower is better

## Gin v1. stable

- [x] Zero allocation router.
- [x] Still the fastest http router and framework. From routing to writing.
- [x] Complete suite of unit tests
- [x] Battle tested
- [x] API frozen, new releases will not break your code.

## Start using it

1. Download and install it:

```sh
$ go get github.com/gin-gonic/gin
```

2. Import it in your code:

```go
import "github.com/gin-gonic/gin"
```

3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`.

```go
import "net/http"
```

### Use a vendor tool like [Govendor](https://github.com/kardianos/govendor)

1. `go get` govendor

```sh
$ go get github.com/kardianos/govendor
```
2. Create your project folder and `cd` inside

```sh
$ mkdir -p ~/go/src/github.com/myusername/project && cd "$_"
```

3. Vendor init your project and add gin

```sh
$ govendor init
$ govendor fetch github.com/gin-gonic/gin@v1.2
```

4. Copy a starting template inside your project

```sh
$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go
```

5. Run your project

```sh
$ go run main.go
```

## Build with [jsoniter](https://github.com/json-iterator/go)

Gin use `encoding/json` as default json package but you can change to [jsoniter](https://github.com/json-iterator/go) by build from other tags.

```sh
$ go build -tags=jsoniter .
```

## API Examples

### Using GET, POST, PUT, PATCH, DELETE and OPTIONS

```go
func main() {
	// Disable Console Color
	// gin.DisableConsoleColor()

	// Creates a gin router with default middleware:
	// logger and recovery (crash-free) middleware
	router := gin.Default()

	router.GET("/someGet", getting)
	router.POST("/somePost", posting)
	router.PUT("/somePut", putting)
	router.DELETE("/someDelete", deleting)
	router.PATCH("/somePatch", patching)
	router.HEAD("/someHead", head)
	router.OPTIONS("/someOptions", options)

	// By default it serves on :8080 unless a
	// PORT environment variable was defined.
	router.Run()
	// router.Run(":3000") for a hard coded port
}
```

### Parameters in path

```go
func main() {
	router := gin.Default()

	// This handler will match /user/john but will not match neither /user/ or /user
	router.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	// However, this one will match /user/john/ and also /user/john/send
	// If no other routers match /user/john, it will redirect to /user/john/
	router.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := name + " is " + action
		c.String(http.StatusOK, message)
	})

	router.Run(":8080")
}
```

### Querystring parameters

```go
func main() {
	router := gin.Default()

	// Query string parameters are parsed using the existing underlying request object.
	// The request responds to a url matching:  /welcome?firstname=Jane&lastname=Doe
	router.GET("/welcome", func(c *gin.Context) {
		firstname := c.DefaultQuery("firstname", "Guest")
		lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")

		c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
	})
	router.Run(":8080")
}
```

### Multipart/Urlencoded Form

```go
func main() {
	router := gin.Default()

	router.POST("/form_post", func(c *gin.Context) {
		message := c.PostForm("message")
		nick := c.DefaultPostForm("nick", "anonymous")

		c.JSON(200, gin.H{
			"status":  "posted",
			"message": message,
			"nick":    nick,
		})
	})
	router.Run(":8080")
}
```

### Another example: query + post form

```
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name=manu&message=this_is_great
```

```go
func main() {
	router := gin.Default()

	router.POST("/post", func(c *gin.Context) {

		id := c.Query("id")
		page := c.DefaultQuery("page", "0")
		name := c.PostForm("name")
		message := c.PostForm("message")

		fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
	})
	router.Run(":8080")
}
```

```
id: 1234; page: 1; name: manu; message: this_is_great
```

### Upload files

#### Single file

References issue [#774](https://github.com/gin-gonic/gin/issues/774) and detail [example code](examples/upload-file/single).

```go
func main() {
	router := gin.Default()
	router.POST("/upload", func(c *gin.Context) {
		// single file
		file, _ := c.FormFile("file")
		log.Println(file.Filename)

		// Upload the file to specific dst.
		// c.SaveUploadedFile(file, dst)

		c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
	})
	router.Run(":8080")
}
```

How to `curl`:

```bash
curl -X POST http://localhost:8080/upload \
  -F "file=@/Users/appleboy/test.zip" \
  -H "Content-Type: multipart/form-data"
```

#### Multiple files

See the detail [example code](examples/upload-file/multiple).

```go
func main() {
	router := gin.Default()
	router.POST("/upload", func(c *gin.Context) {
		// Multipart form
		form, _ := c.MultipartForm()
		files := form.File["upload[]"]

		for _, file := range files {
			log.Println(file.Filename)

			// Upload the file to specific dst.
			// c.SaveUploadedFile(file, dst)
		}
		c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
	})
	router.Run(":8080")
}
```

How to `curl`:

```bash
curl -X POST http://localhost:8080/upload \
  -F "upload[]=@/Users/appleboy/test1.zip" \
  -F "upload[]=@/Users/appleboy/test2.zip" \
  -H "Content-Type: multipart/form-data"
```

### Grouping routes

```go
func main() {
	router := gin.Default()

	// Simple group: v1
	v1 := router.Group("/v1")
	{
		v1.POST("/login", loginEndpoint)
		v1.POST("/submit", submitEndpoint)
		v1.POST("/read", readEndpoint)
	}

	// Simple group: v2
	v2 := router.Group("/v2")
	{
		v2.POST("/login", loginEndpoint)
		v2.POST("/submit", submitEndpoint)
		v2.POST("/read", readEndpoint)
	}

	router.Run(":8080")
}
```

### Blank Gin without middleware by default

Use

```go
r := gin.New()
```

instead of

```go
r := gin.Default()
```

### Using middleware
```go
func main() {
	// Creates a router without any middleware by default
	r := gin.New()

	// Global middleware
	r.Use(gin.Logger())
	r.Use(gin.Recovery())

	// Per route middleware, you can add as many as you desire.
	r.GET("/benchmark", MyBenchLogger(), benchEndpoint)

	// Authorization group
	// authorized := r.Group("/", AuthRequired())
	// exactly the same as:
	authorized := r.Group("/")
	// per group middleware! in this case we use the custom created
	// AuthRequired() middleware just in the "authorized" group.
	authorized.Use(AuthRequired())
	{
		authorized.POST("/login", loginEndpoint)
		authorized.POST("/submit", submitEndpoint)
		authorized.POST("/read", readEndpoint)

		// nested group
		testing := authorized.Group("testing")
		testing.GET("/analytics", analyticsEndpoint)
	}

	// Listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}
```

### Model binding and validation

To bind a request body into a type, use model binding. We currently support binding of JSON, XML and standard form values (foo=bar&boo=baz).

Gin uses [**go-playground/validator.v8**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](http://godoc.org/gopkg.in/go-playground/validator.v8#hdr-Baked_In_Validators_and_Tags).

Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`.

When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use BindWith.

You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, the current request will fail with an error.

```go
// Binding from JSON
type Login struct {
	User     string `form:"user" json:"user" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

func main() {
	router := gin.Default()

	// Example for binding JSON ({"user": "manu", "password": "123"})
	router.POST("/loginJSON", func(c *gin.Context) {
		var json Login
		if c.BindJSON(&json) == nil {
			if json.User == "manu" && json.Password == "123" {
				c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			}
		}
	})

	// Example for binding a HTML form (user=manu&password=123)
	router.POST("/loginForm", func(c *gin.Context) {
		var form Login
		// This will infer what binder to use depending on the content-type header.
		if c.Bind(&form) == nil {
			if form.User == "manu" && form.Password == "123" {
				c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			}
		}
	})

	// Listen and serve on 0.0.0.0:8080
	router.Run(":8080")
}
```

### Only Bind Query String

`BindQuery` function only binds the query params and not the post data. See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017).

```go
package main

import (
	"log"

	"github.com/gin-gonic/gin"
)

type Person struct {
	Name    string `form:"name"`
	Address string `form:"address"`
}

func main() {
	route := gin.Default()
	route.Any("/testing", startPage)
	route.Run(":8085")
}

func startPage(c *gin.Context) {
	var person Person
	if c.BindQuery(&person) == nil {
		log.Println("====== Only Bind By Query String ======")
		log.Println(person.Name)
		log.Println(person.Address)
	}
	c.String(200, "Success")
}

```

### Bind Query String or Post Data

See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).

```go
package main

import "log"
import "github.com/gin-gonic/gin"

type Person struct {
	Name    string `form:"name"`
	Address string `form:"address"`
}

func main() {
	route := gin.Default()
	route.GET("/testing", startPage)
	route.Run(":8085")
}

func startPage(c *gin.Context) {
	var person Person
	// If `GET`, only `Form` binding engine (`query`) used.
	// If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).
	// See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48
	if c.Bind(&person) == nil {
		log.Println(person.Name)
		log.Println(person.Address)
	}

	c.String(200, "Success")
}
```

### Bind HTML checkboxes

See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)

main.go

```go
...

type myForm struct {
    Colors []string `form:"colors[]"`
}

...

func formHandler(c *gin.Context) {
    var fakeForm myForm
    c.Bind(&fakeForm)
    c.JSON(200, gin.H{"color": fakeForm.Colors})
}

...

```

form.html

```html
<form action="/" method="POST">
    <p>Check some colors</p>
    <label for="red">Red</label>
    <input type="checkbox" name="colors[]" value="red" id="red" />
    <label for="green">Green</label>
    <input type="checkbox" name="colors[]" value="green" id="green" />
    <label for="blue">Blue</label>
    <input type="checkbox" name="colors[]" value="blue" id="blue" />
    <input type="submit" />
</form>
```

result:

```
{"color":["red","green","blue"]}
```

### Multipart/Urlencoded binding

```go
package main

import (
	"github.com/gin-gonic/gin"
)

type LoginForm struct {
	User     string `form:"user" binding:"required"`
	Password string `form:"password" binding:"required"`
}

func main() {
	router := gin.Default()
	router.POST("/login", func(c *gin.Context) {
		// you can bind multipart form with explicit binding declaration:
		// c.MustBindWith(&form, binding.Form)
		// or you can simply use autobinding with Bind method:
		var form LoginForm
		// in this case proper binding will be automatically selected
		if c.Bind(&form) == nil {
			if form.User == "user" && form.Password == "password" {
				c.JSON(200, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(401, gin.H{"status": "unauthorized"})
			}
		}
	})
	router.Run(":8080")
}
```

Test it with:
```sh
$ curl -v --form user=user --form password=password http://localhost:8080/login
```

### XML, JSON and YAML rendering

```go
func main() {
	r := gin.Default()

	// gin.H is a shortcut for map[string]interface{}
	r.GET("/someJSON", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	r.GET("/moreJSON", func(c *gin.Context) {
		// You also can use a struct
		var msg struct {
			Name    string `json:"user"`
			Message string
			Number  int
		}
		msg.Name = "Lena"
		msg.Message = "hey"
		msg.Number = 123
		// Note that msg.Name becomes "user" in the JSON
		// Will output  :   {"user": "Lena", "Message": "hey", "Number": 123}
		c.JSON(http.StatusOK, msg)
	})

	r.GET("/someXML", func(c *gin.Context) {
		c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	r.GET("/someYAML", func(c *gin.Context) {
		c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	// Listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}
```

#### SecureJSON

Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.

```go
func main() {
	r := gin.Default()

	// You can also use your own secure json prefix
	// r.SecureJsonPrefix(")]}',\n")

	r.GET("/someJSON", func(c *gin.Context) {
		names := []string{"lena", "austin", "foo"}

		// Will output  :   while(1);["lena","austin","foo"]
		c.SecureJSON(http.StatusOK, names)
	})

	// Listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}
```

### Serving static files

```go
func main() {
	router := gin.Default()
	router.Static("/assets", "./assets")
	router.StaticFS("/more_static", http.Dir("my_file_system"))
	router.StaticFile("/favicon.ico", "./resources/favicon.ico")

	// Listen and serve on 0.0.0.0:8080
	router.Run(":8080")
}
```

### HTML rendering

Using LoadHTMLGlob() or LoadHTMLFiles()

```go
func main() {
	router := gin.Default()
	router.LoadHTMLGlob("templates/*")
	//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
	router.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": "Main website",
		})
	})
	router.Run(":8080")
}
```

templates/index.tmpl

```html
<html>
	<h1>
		{{ .title }}
	</h1>
</html>
```

Using templates with same name in different directories

```go
func main() {
	router := gin.Default()
	router.LoadHTMLGlob("templates/**/*")
	router.GET("/posts/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
			"title": "Posts",
		})
	})
	router.GET("/users/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
			"title": "Users",
		})
	})
	router.Run(":8080")
}
```

templates/posts/index.tmpl

```html
{{ define "posts/index.tmpl" }}
<html><h1>
	{{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}
```

templates/users/index.tmpl

```html
{{ define "users/index.tmpl" }}
<html><h1>
	{{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}
```

#### Custom Template renderer

You can also use your own html template render

```go
import "html/template"

func main() {
	router := gin.Default()
	html := template.Must(template.ParseFiles("file1", "file2"))
	router.SetHTMLTemplate(html)
	router.Run(":8080")
}
```

#### Custom Delimiters

You may use custom delims

```go
	r := gin.Default()
	r.Delims("{[{", "}]}")
	r.LoadHTMLGlob("/path/to/templates"))
```

#### Custom Template Funcs

See the detail [example code](examples/template).

main.go

```go
import (
    "fmt"
    "html/template"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
)

func formatAsDate(t time.Time) string {
    year, month, day := t.Date()
    return fmt.Sprintf("%d%02d/%02d", year, month, day)
}

func main() {
    router := gin.Default()
    router.Delims("{[{", "}]}")
    router.SetFuncMap(template.FuncMap{
        "formatAsDate": formatAsDate,
    })
    router.LoadHTMLFiles("./fixtures/basic/raw.tmpl")

    router.GET("/raw", func(c *gin.Context) {
        c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
            "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
        })
    })

    router.Run(":8080")
}

```

raw.tmpl

```html
Date: {[{.now | formatAsDate}]}
```

Result:
```
Date: 2017/07/01
```

### Multitemplate

Gin allow by default use only one html.Template. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`.

### Redirects

Issuing a HTTP redirect is easy:

```go
r.GET("/test", func(c *gin.Context) {
	c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
})
```
Both internal and external locations are supported.

### Custom Middleware

```go
func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()

		// Set example variable
		c.Set("example", "12345")

		// before request

		c.Next()

		// after request
		latency := time.Since(t)
		log.Print(latency)

		// access the status we are sending
		status := c.Writer.Status()
		log.Println(status)
	}
}

func main() {
	r := gin.New()
	r.Use(Logger())

	r.GET("/test", func(c *gin.Context) {
		example := c.MustGet("example").(string)

		// it would print: "12345"
		log.Println(example)
	})

	// Listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}
```

### Using BasicAuth() middleware

```go
// simulate some private data
var secrets = gin.H{
	"foo":    gin.H{"email": "foo@bar.com", "phone": "123433"},
	"austin": gin.H{"email": "austin@example.com", "phone": "666"},
	"lena":   gin.H{"email": "lena@guapa.com", "phone": "523443"},
}

func main() {
	r := gin.Default()

	// Group using gin.BasicAuth() middleware
	// gin.Accounts is a shortcut for map[string]string
	authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
		"foo":    "bar",
		"austin": "1234",
		"lena":   "hello2",
		"manu":   "4321",
	}))

	// /admin/secrets endpoint
	// hit "localhost:8080/admin/secrets
	authorized.GET("/secrets", func(c *gin.Context) {
		// get user, it was set by the BasicAuth middleware
		user := c.MustGet(gin.AuthUserKey).(string)
		if secret, ok := secrets[user]; ok {
			c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
		} else {
			c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
		}
	})

	// Listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}
```

### Goroutines inside a middleware

When starting inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy.

```go
func main() {
	r := gin.Default()

	r.GET("/long_async", func(c *gin.Context) {
		// create copy to be used inside the goroutine
		cCp := c.Copy()
		go func() {
			// simulate a long task with time.Sleep(). 5 seconds
			time.Sleep(5 * time.Second)

			// note that you are using the copied context "cCp", IMPORTANT
			log.Println("Done! in path " + cCp.Request.URL.Path)
		}()
	})

	r.GET("/long_sync", func(c *gin.Context) {
		// simulate a long task with time.Sleep(). 5 seconds
		time.Sleep(5 * time.Second)

		// since we are NOT using a goroutine, we do not have to copy the context
		log.Println("Done! in path " + c.Request.URL.Path)
	})

	// Listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}
```

### Custom HTTP configuration

Use `http.ListenAndServe()` directly, like this:

```go
func main() {
	router := gin.Default()
	http.ListenAndServe(":8080", router)
}
```
or

```go
func main() {
	router := gin.Default()

	s := &http.Server{
		Addr:           ":8080",
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	s.ListenAndServe()
}
```

### Support Let's Encrypt

example for 1-line LetsEncrypt HTTPS servers.

[embedmd]:# (examples/auto-tls/example1.go go)
```go
package main

import (
	"log"

	"github.com/gin-gonic/autotls"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	// Ping handler
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	log.Fatal(autotls.Run(r, "example1.com", "example2.com"))
}
```

example for custom autocert manager.

[embedmd]:# (examples/auto-tls/example2.go go)
```go
package main

import (
	"log"

	"github.com/gin-gonic/autotls"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/acme/autocert"
)

func main() {
	r := gin.Default()

	// Ping handler
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	m := autocert.Manager{
		Prompt:     autocert.AcceptTOS,
		HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),
		Cache:      autocert.DirCache("/var/www/.cache"),
	}

	log.Fatal(autotls.RunWithManager(r, &m))
}
```

### Graceful restart or stop

Do you want to graceful restart or stop your web server?
There are some ways this can be done.

We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details.

```go
router := gin.Default()
router.GET("/", handler)
// [...]
endless.ListenAndServe(":4242", router)
```

An alternative to endless:

* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.
* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.
* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.

If you are using Go 1.8, you may not need to use this library! Consider using http.Server's built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) method for graceful shutdowns. See the full [graceful-shutdown](./examples/graceful-shutdown) example with gin.

[embedmd]:# (examples/graceful-shutdown/graceful-shutdown/server.go go)
```go
// +build go1.8

package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()
	router.GET("/", func(c *gin.Context) {
		time.Sleep(5 * time.Second)
		c.String(http.StatusOK, "Welcome Gin Server")
	})

	srv := &http.Server{
		Addr:    ":8080",
		Handler: router,
	}

	go func() {
		// service connections
		if err := srv.ListenAndServe(); err != nil {
			log.Printf("listen: %s\n", err)
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Server exist")
}
```

## Users  [![Sourcegraph](https://sourcegraph.com/github.com/gin-gonic/gin/-/badge.svg)](https://sourcegraph.com/github.com/gin-gonic/gin?badge)

Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework.

* [drone](https://github.com/drone/drone): Drone is a Continuous Delivery platform built on Docker, written in Go
* [gorush](https://github.com/appleboy/gorush): A push notification server written in Go.


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('mediablog', '0002_auto_20161123_1429'),
    ]

    operations = [
        migrations.AddField(
            model_name='medium',
            name='uploaded_by',
            field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
var profile = require('../../../lib/util/profile');

exports.getMockedProfile = function () {
  var newProfile = new profile.Profile();

  newProfile.addSubscription(new profile.Subscription({
    id: '5e7d1bb6-4953-44fe-8a54-43fbdb53b989',
    managementCertificate: {
      key: 'mockedKey',
      cert: 'mockedCert'
    },
    name: 'Mobilytics Test1',
    registeredProviders: ['website', 'mobileservice'],
    registeredResourceNamespaces: [],
    isDefault: true
  }, newProfile.environments['AzureCloud']));

  return newProfile;
};

exports.setEnvironment = function() {
};

exports.scopes = [[function (nock) {
var result =
nock('https://management.core.windows.net:443')
  .get('/5e7d1bb6-4953-44fe-8a54-43fbdb53b989/services/mobileservices/mobileservices/clitestDotNet1969/authsettings')
  .reply(200, "[{\"packageSid\":\"789\",\"provider\":\"microsoft\",\"appId\":\"1234\",\"secret\":\"5678\"}]", { 'cache-control': 'no-cache',
  pragma: 'no-cache',
  'content-length': '76',
  'content-type': 'application/json; charset=utf-8',
  expires: '-1',
  server: '1.0.6198.216 (rd_rdfe_stable.150408-1309) Microsoft-HTTPAPI/2.0',
  'x-ms-servedbyregion': 'ussouth3',
  'strict-transport-security': 'max-age=31536000; includeSubDomains',
  'x-powered-by': 'ASP.NET',
  'x-ms-request-id': '5a57b93b437f91cb9a2ed08577932894',
  date: 'Mon, 13 Apr 2015 23:09:40 GMT' });
 return result; }]];


text:
 {{aboutMe}} <?php echo $a; ?>

 I'll be re-doing this site soon. My old hosting package expired on me without a reminder. I've switched to something else and this time I'll also be writing the back-end. This will likely be a massive re-write of the code and a switch to a different and interesting tech stack.


text:
  ×
  Roulette
  Contributors

 x Dodofy

            Roulette

            Contributors

              Fork me


text:
import {
	AdditiveBlending,
	Color,
	ShaderMaterial,
	UniformsUtils,
	WebGLRenderTarget
} from 'three';
import { Pass, FullScreenQuad } from './Pass.js';
import { CopyShader } from '../shaders/CopyShader.js';

/**
*
* Supersample Anti-Aliasing Render Pass
*
* This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
*
* References: https://en.wikipedia.org/wiki/Supersampling
*
*/

class SSAARenderPass extends Pass {

	constructor( scene, camera, clearColor, clearAlpha ) {

		super();

		this.scene = scene;
		this.camera = camera;

		this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
		this.unbiased = true;

		// as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
		this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000;
		this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
		this._oldClearColor = new Color();

		if ( CopyShader === undefined ) console.error( 'THREE.SSAARenderPass relies on CopyShader' );

		const copyShader = CopyShader;
		this.copyUniforms = UniformsUtils.clone( copyShader.uniforms );

		this.copyMaterial = new ShaderMaterial(	{
			uniforms: this.copyUniforms,
			vertexShader: copyShader.vertexShader,
			fragmentShader: copyShader.fragmentShader,
			transparent: true,
			blending: AdditiveBlending,
			depthTest: false,
			depthWrite: false
		} );

		this.fsQuad = new FullScreenQuad( this.copyMaterial );

	}

	dispose() {

		if ( this.sampleRenderTarget ) {

			this.sampleRenderTarget.dispose();
			this.sampleRenderTarget = null;

		}

		this.copyMaterial.dispose();

		this.fsQuad.dispose();

	}

	setSize( width, height ) {

		if ( this.sampleRenderTarget )	this.sampleRenderTarget.setSize( width, height );

	}

	render( renderer, writeBuffer, readBuffer ) {

		if ( ! this.sampleRenderTarget ) {

			this.sampleRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height );
			this.sampleRenderTarget.texture.name = 'SSAARenderPass.sample';

		}

		const jitterOffsets = _JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];

		const autoClear = renderer.autoClear;
		renderer.autoClear = false;

		renderer.getClearColor( this._oldClearColor );
		const oldClearAlpha = renderer.getClearAlpha();

		const baseSampleWeight = 1.0 / jitterOffsets.length;
		const roundingRange = 1 / 32;
		this.copyUniforms[ 'tDiffuse' ].value = this.sampleRenderTarget.texture;

		const viewOffset = {

			fullWidth: readBuffer.width,
			fullHeight: readBuffer.height,
			offsetX: 0,
			offsetY: 0,
			width: readBuffer.width,
			height: readBuffer.height

		};

		const originalViewOffset = Object.assign( {}, this.camera.view );

		if ( originalViewOffset.enabled ) Object.assign( viewOffset, originalViewOffset );

		// render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
		for ( let i = 0; i < jitterOffsets.length; i ++ ) {

			const jitterOffset = jitterOffsets[ i ];

			if ( this.camera.setViewOffset ) {

				this.camera.setViewOffset(

					viewOffset.fullWidth, viewOffset.fullHeight,

					viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16

					viewOffset.width, viewOffset.height

				);

			}

			let sampleWeight = baseSampleWeight;

			if ( this.unbiased ) {

				// the theory is that equal weights for each sample lead to an accumulation of rounding errors.
				// The following equation varies the sampleWeight per sample so that it is uniformly distributed
				// across a range of values whose rounding errors cancel each other out.

				const uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
				sampleWeight += roundingRange * uniformCenteredDistribution;

			}

			this.copyUniforms[ 'opacity' ].value = sampleWeight;
			renderer.setClearColor( this.clearColor, this.clearAlpha );
			renderer.setRenderTarget( this.sampleRenderTarget );
			renderer.clear();
			renderer.render( this.scene, this.camera );

			renderer.setRenderTarget( this.renderToScreen ? null : writeBuffer );

			if ( i === 0 ) {

				renderer.setClearColor( 0x000000, 0.0 );
				renderer.clear();

			}

			this.fsQuad.render( renderer );

		}

		if ( this.camera.setViewOffset && originalViewOffset.enabled ) {

			this.camera.setViewOffset(

				originalViewOffset.fullWidth, originalViewOffset.fullHeight,

				originalViewOffset.offsetX, originalViewOffset.offsetY,

				originalViewOffset.width, originalViewOffset.height

			);

		} else if ( this.camera.clearViewOffset ) {

			this.camera.clearViewOffset();

		}

		renderer.autoClear = autoClear;
		renderer.setClearColor( this._oldClearColor, oldClearAlpha );

	}

}

// These jitter vectors are specified in integers because it is easier.
// I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
// before being used, thus these integers need to be scaled by 1/16.
//
// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
const _JitterVectors = [
	[
		[ 0, 0 ]
	],
	[
		[ 4, 4 ], [ - 4, - 4 ]
	],
	[
		[ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
	],
	[
		[ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
		[ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
	],
	[
		[ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
		[ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
		[ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
		[ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
	],
	[
		[ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
		[ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
		[ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
		[ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
		[ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
		[ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
		[ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
		[ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
	]
];

export { SSAARenderPass };


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.flowable.spring.configurator;

import java.io.IOException;
import java.util.zip.ZipInputStream;

import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.DeploymentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;

/**
 * Implementation of {@link AutoDeploymentStrategy} that performs a separate deployment for each resource by name.
 *
 * @author Tiese Barrell
 * @author Joram Barrez
 */
public class SingleResourceAutoDeploymentStrategy extends AbstractAutoDeploymentStrategy {

    private static final Logger LOGGER = LoggerFactory.getLogger(SingleResourceAutoDeploymentStrategy.class);

    /**
     * The deployment mode this strategy handles.
     */
    public static final String DEPLOYMENT_MODE = "single-resource";

    @Override
    protected String getDeploymentMode() {
        return DEPLOYMENT_MODE;
    }

    @Override
    public void deployResources(final String deploymentNameHint, final Resource[] resources, final RepositoryService repositoryService) {

        // Create a separate deployment for each resource using the resource name

        for (final Resource resource : resources) {

            try {
                final String resourceName = determineResourceName(resource);
                final DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(resourceName);

                if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
                    deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
                } else {
                    deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
                }

                deploymentBuilder.deploy();

            } catch (Exception e) {
                String resourceName = null;
                if (resource != null) {
                    try {
                        resourceName = resource.getURL().toString();
                    } catch (IOException ioe) {
                        resourceName = resource.toString();
                    }
                }
                // Any exception should not stop the bootup of the engine
                LOGGER.warn("Exception while autodeploying process definitions for resource {}. This exception can be ignored if the root cause indicates a unique constraint violation, which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ", resourceName, e);
            }
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CloudSense.Models
{
    public class Subscription
    {
        public string Id { get; set; }
        public string DirectoryId { get; set; }
        public DateTime ConnectedOn { get; set; }
        public string ConnectedBy { get; set; }
        [NotMapped]
        public bool AzureAccessNeedsToBeRepaired { get; set; }
    }
}


text:
#ifdef __APPLE__

#include <stdio.h>

#ifndef SDL_rwopsbundlesupport_h
#define SDL_rwopsbundlesupport_h
FILE* SDL_OpenFPFromBundleOrFallback(const char *file, const char *mode);
#endif
#endif


text:
package de.bastiankrol.startexplorer.crossplatform;

import java.io.File;
import java.net.URL;
import java.util.List;

import de.bastiankrol.startexplorer.util.MessageDialogHelper;

/**
 * {@link IRuntimeExecCalls} implementation that just shows annoying popups
 * instead of doing anything useful.
 *
 * @author Bastian Krol
 */
class RuntimeExecCallsUnsupported implements IRuntimeExecCalls
{

  private static final Capabilities CAPABILITIES = Capabilities.create()
      .build();

  private MessageDialogHelper messageDialogHelper;

  /**
   * Creates an instance.
   */
  RuntimeExecCallsUnsupported()
  {
    this.messageDialogHelper = new MessageDialogHelper();
  }

  @Override
  public void startFileManagerForFileList(List<File> fileList,
      boolean selectFile)
  {
    this.annoyUser();
  }

  @Override
  public void startSystemApplicationForFileList(List<File> fileList)
  {
    this.annoyUser();
  }

  @Override
  public void startShellForFileList(List<File> fileList)
  {
    this.annoyUser();
  }

  @Override
  public void startCustomCommandForFileList(String[] cmdArray,
      List<File> fileList)
  {
    this.annoyUser();
  }

  @Override
  public void startFileManagerForFile(File file, boolean selectFile)
  {
    this.annoyUser();
  }

  @Override
  public void startFileManagerForUrl(URL url)
  {
    this.annoyUser();

  }

  @Override
  public void startSystemApplicationForFile(File file)
  {
    this.annoyUser();
  }

  @Override
  public void startSystemApplicationForUrl(URL url)
  {
    this.annoyUser();
  }

  @Override
  public void startShellForFile(File file)
  {
    this.annoyUser();
  }

  @Override
  public void startCustomCommandForFile(String[] cmdArray, File file)
  {
    this.annoyUser();
  }

  @Override
  public String[] convertCommandStringToArray(String command)
  {
    return new String[0];
  }

  @Override
  public Capabilities getCapabilities()
  {
    return CAPABILITIES;
  }

  private void annoyUser()
  {
    this.messageDialogHelper
        .displayErrorMessage(
            "Please configure Your Desktop Environment",
            "The operating system or desktop environment you are using could not be automatically detected or is not supported "
                + "out of the box. Please set the correct operating system/desktop environment in the preferences or define a "
                + "set of commands for a your desktop environment.");
  }
}


text:
package trainings.cdi.starter.impl;

import trainings.cdi.starter.api.ATMTransport;
import trainings.cdi.starter.api.Transport;

import javax.enterprise.inject.Alternative;
import javax.enterprise.inject.Produces;

import static trainings.cdi.starter.api.TransportType.JSON;
import static trainings.cdi.starter.api.TransportType.SOAP;

public class TransportFactory {

    private boolean useJSON = true;
    private boolean behindFirewall = true;

    @Produces
    @Alternative
    public ATMTransport createTransport(@Transport(type = SOAP) ATMTransport soapTransport, @Transport(type = JSON) ATMTransport jsonTransport) {
        // look up parameters in some configuration file/LDAP/DB, etc

        System.out.println("ATM transport created with producer based on config");

        if (!behindFirewall) {
            System.out.println("Created Standard transport");
            return new StandardAtmTransport();
        } else {
            if (useJSON) {
                System.out.println("Create JSON transport");
                return jsonTransport;
            } else {
                System.out.println("Created SAOP transport");
                return soapTransport;
            }
        }
    }
}


text:
package org.apache.skywalking.apm.collector.storage.h2.define.imp;

import org.apache.skywalking.apm.collector.core.storage.TimePyramid;
import org.apache.skywalking.apm.collector.core.util.Const;
import org.apache.skywalking.apm.collector.storage.table.instance.InstanceMetricTable;

/**
 * @author peng-yongsheng
 */
public class InstanceMinuteMetricH2TableDefine extends AbstractInstanceMetricH2TableDefine {

    public InstanceMinuteMetricH2TableDefine() {
        super(InstanceMetricTable.TABLE + Const.ID_SPLIT + TimePyramid.Minute.getName());
    }
}


text:
namespace Hudl.FFmpeg.Enums
{
    /// <summary>
    /// A streamId indicating the resource that was added to the Command
    /// </summary>
    public enum CommandReceiptType
    {
        /// <summary>
        /// specifies that the streamId is for a command input resource
        /// </summary>
        Input,
        /// <summary>
        /// specifies that the streamId is for a command output file
        /// </summary>
        Output,
        /// <summary>
        /// specifies that the streamId is for a filtergraph stream
        /// </summary>
        Stream
    }
}


text:
#include <aws/workmail/model/MobileDeviceAccessOverride.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

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

namespace Aws
{
namespace WorkMail
{
namespace Model
{

MobileDeviceAccessOverride::MobileDeviceAccessOverride() :
    m_userIdHasBeenSet(false),
    m_deviceIdHasBeenSet(false),
    m_effect(MobileDeviceAccessRuleEffect::NOT_SET),
    m_effectHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_dateCreatedHasBeenSet(false),
    m_dateModifiedHasBeenSet(false)
{
}

MobileDeviceAccessOverride::MobileDeviceAccessOverride(JsonView jsonValue) :
    m_userIdHasBeenSet(false),
    m_deviceIdHasBeenSet(false),
    m_effect(MobileDeviceAccessRuleEffect::NOT_SET),
    m_effectHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_dateCreatedHasBeenSet(false),
    m_dateModifiedHasBeenSet(false)
{
  *this = jsonValue;
}

MobileDeviceAccessOverride& MobileDeviceAccessOverride::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("UserId"))
  {
    m_userId = jsonValue.GetString("UserId");

    m_userIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DeviceId"))
  {
    m_deviceId = jsonValue.GetString("DeviceId");

    m_deviceIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Effect"))
  {
    m_effect = MobileDeviceAccessRuleEffectMapper::GetMobileDeviceAccessRuleEffectForName(jsonValue.GetString("Effect"));

    m_effectHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Description"))
  {
    m_description = jsonValue.GetString("Description");

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DateCreated"))
  {
    m_dateCreated = jsonValue.GetDouble("DateCreated");

    m_dateCreatedHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DateModified"))
  {
    m_dateModified = jsonValue.GetDouble("DateModified");

    m_dateModifiedHasBeenSet = true;
  }

  return *this;
}

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

  if(m_userIdHasBeenSet)
  {
   payload.WithString("UserId", m_userId);

  }

  if(m_deviceIdHasBeenSet)
  {
   payload.WithString("DeviceId", m_deviceId);

  }

  if(m_effectHasBeenSet)
  {
   payload.WithString("Effect", MobileDeviceAccessRuleEffectMapper::GetNameForMobileDeviceAccessRuleEffect(m_effect));
  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_dateCreatedHasBeenSet)
  {
   payload.WithDouble("DateCreated", m_dateCreated.SecondsWithMSPrecision());
  }

  if(m_dateModifiedHasBeenSet)
  {
   payload.WithDouble("DateModified", m_dateModified.SecondsWithMSPrecision());
  }

  return payload;
}

} // namespace Model
} // namespace WorkMail
} // namespace Aws