text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.xeneo.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xeneo.core.task.CaseType;
import org.junit.*;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.xeneo.core.task.CaseManager;

/**
 *
 * @author Stefan Huber
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/test-config.xml")
public class JdbcCaseTypeTest {

    @Autowired
    private JdbcCaseManager engine;

    static final Logger logger = LoggerFactory.getLogger(JdbcTaskTest.class);

    public JdbcCaseTypeTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testCreateCaseType() {

        String title = "My Case Type"; String description = "My Case Type Description";

        CaseType ct = engine.createCaseType(title, description);

        logger.info("CaseType created with URI: " + ct.getCaseTypeURI() + ", Title: " + ct.getTitle() + " and Description: " + ct.getDescription());

        assertTrue(!ct.getCaseTypeURI().isEmpty() && !ct.getTitle().isEmpty() && !ct.getDescription().isEmpty());
    }

    @Test
    public void testUpdateFields() {

        String title = "My Second Case Type"; String description = "My Second Case Type Description";

        CaseType ct = engine.createCaseType(title, description);

        logger.info("CaseType created with URI: " + ct.getCaseTypeURI() + ", Title: " + ct.getTitle() + " and Description: " + ct.getDescription());

        assertTrue(!ct.getCaseTypeURI().isEmpty() && !ct.getTitle().isEmpty() && !ct.getDescription().isEmpty());

        ct.setTitle("new CaseType Title");
        ct.setDescription("new CaseType description");

        CaseType a = engine.updateCaseType(ct);

        assertFalse(title.equalsIgnoreCase(ct.getTitle()) || description.equalsIgnoreCase(ct.getDescription()));

    }

    @Test
    public void testGetCaseTypes() {

        CaseType a = engine.createCaseType("title1","desc1");
        CaseType b = engine.createCaseType("title2","desc2");

        int i = 0;
        for(CaseType x : engine.getCaseTypes()) {

            logger.info(x.getCaseTypeURI() + " - " + x.getTitle() + " - " + x.getDescription());

            if (a.getCaseTypeURI().equalsIgnoreCase(x.getCaseTypeURI()) && a.getTitle().equalsIgnoreCase(x.getTitle()) && a.getDescription().equalsIgnoreCase(x.getDescription())) {
                i++;
            }
            if (b.getCaseTypeURI().equalsIgnoreCase(x.getCaseTypeURI()) && b.getTitle().equalsIgnoreCase(x.getTitle()) && b.getDescription().equalsIgnoreCase(x.getDescription())) {
                i++;
            }
        }

        assertTrue(i>1);
    }
}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('l33t-navbar', 'Integration | Component | l33t navbar', {
  integration: true
});

test('it renders', function(assert) {

  this.set('title', 'awesome');

  this.render(hbs`
    {{#l33t-navbar title=title}}
      template block text
    {{/l33t-navbar}}
  `);

  assert.equal(this.$('.title').text().trim(), 'awesome');
});

redpajama_set_name: RedPajamaGithub


text: google-site-verification: googleb73cb917a3eebb1c.html


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\OrderSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'surname') ?>

    <?= $form->field($model, 'country') ?>

    <?= $form->field($model, 'region') ?>

    <?php // echo $form->field($model, 'city') ?>

    <?php // echo $form->field($model, 'address') ?>

    <?php // echo $form->field($model, 'organization_name') ?>

    <?php // echo $form->field($model, 'post_index') ?>

    <?php // echo $form->field($model, 'phone') ?>

    <?php // echo $form->field($model, 'email') ?>

    <?php // echo $form->field($model, 'delivery_date') ?>

    <?php // echo $form->field($model, 'coupon_id') ?>

    <?php // echo $form->field($model, 'status_id') ?>

    <?php // echo $form->field($model, 'created_at') ?>

    <?php // echo $form->field($model, 'updated_at') ?>

    <?php // echo $form->field($model, 'sort_by') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
<?php

namespace Fullpipe\ImageBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Fullpipe\ImageBundle\Form\EventListener\BuildImageFormListener;
use Symfony\Component\Form\Extension\Core\Type\FileType;

/**
 * Image type.
 */
class ImageType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addEventSubscriber(new BuildImageFormListener())
            ->add('file', FileType::class, array(
                'label'     => 'fullpipe_image.form.image.file',
                'required'  => false,
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['image'] = $form->getData();
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'fullpipe_image_image';
    }
}


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

<TITLE>
ISVNSession (JavaDoc :: Documentation :: Pure Java Subversion (SVN) Client Library)
</TITLE>

<META NAME="keywords" CONTENT="org.tmatesoft.svn.core.io.ISVNSession interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../javadoc.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

                SVNKit Home

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.tmatesoft.svn.core.io

Interface ISVNSession

All Known Implementing Classes:
DefaultSVNRepositoryPool

public interface ISVNSession

The ISVNSession interface provides some extra handling operations over
 SVNRepository objects.

 For remote accessing a repository (via svn:// and
 http://) SVNRepository drivers open socket connections to
 write and read data from. Session objects (implementing ISVNSession) may
 enable an SVNRepository object to use a single socket connection during the
 whole runtime, or, as an alternative, to use a new socket connection per each
 repository access operation (this slows the speed of operation execution since
 the operation needs some extra time for opening and closing a socket).

 Also ISVNSession allows to cache and retrieve commit messages during
 runtime.

 How to set a session object for an SVNRepository driver:

 import org.tmatesoft.svn.core.io.ISVNSession;
 import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
 import org.tmatesoft.svn.core.io.SVNRepository;
 import org.tmatesoft.svn.core.SVNURL;
 ...

     ISVNSession session;
     ...
     SVNURL url = SVNURL.parseURIEncoded("svn://host/path/to/repos");
     try{
         SVNRepository repository = SVNRepositoryFactory.create(url, session);
         ...
     }catch(SVNException svne){
         ...
     }

Version:

1.1.1

Author:

TMate Software Ltd.

See Also:
SVNRepository,
SVNRepositoryFactory

Field Summary

static ISVNSession
DEFAULT

          The same as KEEP_ALIVE.

static ISVNSession
KEEP_ALIVE

          A session options implementation that simply allows to keep
 a single connection alive for all data i/o.

Method Summary

 String
getCommitMessage(SVNRepository repository,
                 long revision)

          Retrieves the cached commit message for a particular revision.

 boolean
hasCommitMessage(SVNRepository repository,
                 long revision)

          Checks if there's a commit message in cache for a particular repository
 and revision.

 boolean
keepConnection(SVNRepository repository)

          Says if the given SVNRepository object should use a single socket
 connection (not to open/close a new one for each operation).

 void
saveCommitMessage(SVNRepository repository,
                  long revision,
                  String message)

          Caches a commit message for the given revision.

Field Detail

KEEP_ALIVE

public static final ISVNSession KEEP_ALIVE

A session options implementation that simply allows to keep
 a single connection alive for all data i/o. This implementation
 does not cache commit messages.

DEFAULT

public static final ISVNSession DEFAULT

The same as KEEP_ALIVE. Left for backward
 compatibility.

Method Detail

keepConnection

public boolean keepConnection(SVNRepository repository)

Says if the given SVNRepository object should use a single socket
 connection (not to open/close a new one for each operation). This will
 certainly improve the SVNRepository object's methods performance speed.

 For examlpe, a session object may hold a number of SVNRepository
 object references knowing for everyone of them if it should keep a single
 connection or not.

Parameters:
repository - an SVNRepository driver

Returns:
true if repository
          should use a single socket connection during the whole runtime,
          false - to open/close a new
          connection for each repository access operation

saveCommitMessage

public void saveCommitMessage(SVNRepository repository,
                              long revision,
                              String message)

Caches a commit message for the given revision.

Parameters:
repository - an SVNRepository driver (to distinguish
                    that repository for which this message is actual)
revision - a revision number
message - the commit message for revision
See Also:
getCommitMessage(SVNRepository, long)

getCommitMessage

public String getCommitMessage(SVNRepository repository,
                               long revision)

Retrieves the cached commit message for a particular revision.
 Use getCommitMessage() to
 check if there's a message in cache.

Parameters:
repository - an SVNRepository driver (to distinguish
                    that repository for which a commit message is requested)
revision - a revision number

Returns:
the commit message for revision
See Also:
saveCommitMessage(SVNRepository, long, String)

hasCommitMessage

public boolean hasCommitMessage(SVNRepository repository,
                                long revision)

Checks if there's a commit message in cache for a particular repository
 and revision.

Parameters:
repository - an SVNRepository driver (to distinguish
                    that repository for which a commit message is requested)
revision - a revision number

Returns:
true if the cache
                    has got a message for the given repository and revision,
                    false otherwise

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

                SVNKit Home

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright © 2004-2007 TMate Software Ltd. All Rights Reserved.


text:
/**
 * Returns a normalized KeyCombinationString (with the key names in the combination
 * sorted in alphabetical order)
 * @param {Object.<ReactKeyName, Boolean>} keyDictionary Dictionary of key names
 * @returns {NormalizedKeyCombinationString} Normalized KeyCombinationString
 */
function normalizedCombinationId(keyDictionary) {
  return Object.keys(keyDictionary).sort((a, b) =>{
    if (a.length !== b.length) {
      return b.length - a.length;
    }

    if (a < b) {return -1;}
    if (a > b) {return 1;}
    return 0;
  }).join('+');
}

export default normalizedCombinationId;


text:
@interface MPHMUNIStopsController : MPHStopsController <MPHStopsController>
@property (atomic, copy) NSArray *stops;
@end


text:
default.rvm.default_ruby = "ruby-2.0.0-p247"
default.rvm.user_installs = [
  { 'user'          => 'rails',
    'default_ruby'  => 'ruby-2.0.0-p247'
  }
]

# some default packages we want to install
default.packages = %w(vim git htop mongodb)

# Users
default.users = ['ubuntu', 'rails']
default.user.ssh_keygen = false

# SSH
default.openssh.server.permit_root_login = 'no'
default.openssh.server.password_authentication = 'no'
default.openssh.server.allow_groups = 'sudo'
default.openssh.server.login_grace_time = '30'
default.openssh.server.use_p_a_m = 'no'
default.openssh.server.print_motd = 'no'

# nginx
default.nginx.init_style = "runit"
default.nginx.default_site_enabled = false

# our Java variables
default.java.jdk_version = "7"


text:
int main()
{
  boost::condition_variable_any cv0;
  return boost::report_errors();
}


text:
package org.hisp.dhis.mapping;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.MergeMode;
import org.hisp.dhis.common.view.DetailedView;
import org.hisp.dhis.common.view.ExportView;
import org.hisp.dhis.schema.PropertyType;
import org.hisp.dhis.schema.annotation.Property;

/**
 * @author Jan Henrik Overland
 */
@JacksonXmlRootElement( localName = "mapLayer", namespace = DxfNamespaces.DXF_2_0 )
public class MapLayer
    extends BaseIdentifiableObject
{
    private String type;

    private String url;

    private String layers;

    private String time;

    private String fillColor;

    private double fillOpacity;

    private String strokeColor;

    private int strokeWidth;

    public MapLayer()
    {
    }

    public MapLayer( String name, String type, String url, String layers, String time, String fillColor,
        double fillOpacity, String strokeColor, int strokeWidth )
    {
        this.name = name;
        this.type = type;
        this.url = url;
        this.layers = layers;
        this.time = time;
        this.fillColor = fillColor;
        this.fillOpacity = fillOpacity;
        this.strokeColor = strokeColor;
        this.strokeWidth = strokeWidth;
    }

    // -------------------------------------------------------------------------
    // Getters and setters
    // -------------------------------------------------------------------------

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getType()
    {
        return type;
    }

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

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    @Property( PropertyType.URL )
    public String getUrl()
    {
        return url;
    }

    public void setUrl( String url )
    {
        this.url = url;
    }

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getLayers()
    {
        return layers;
    }

    public void setLayers( String layers )
    {
        this.layers = layers;
    }

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getTime()
    {
        return time;
    }

    public void setTime( String time )
    {
        this.time = time;
    }

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    @Property( PropertyType.COLOR )
    public String getFillColor()
    {
        return fillColor;
    }

    public void setFillColor( String fillColor )
    {
        this.fillColor = fillColor;
    }

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public double getFillOpacity()
    {
        return fillOpacity;
    }

    public void setFillOpacity( double fillOpacity )
    {
        this.fillOpacity = fillOpacity;
    }

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    @Property( PropertyType.COLOR )
    public String getStrokeColor()
    {
        return strokeColor;
    }

    public void setStrokeColor( String strokeColor )
    {
        this.strokeColor = strokeColor;
    }

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public int getStrokeWidth()
    {
        return strokeWidth;
    }

    public void setStrokeWidth( int strokeWidth )
    {
        this.strokeWidth = strokeWidth;
    }

    @Override
    public void mergeWith( IdentifiableObject other, MergeMode mergeMode )
    {
        super.mergeWith( other, mergeMode );

        if ( other.getClass().isInstance( this ) )
        {
            MapLayer mapLayer = (MapLayer) other;

            strokeWidth = mapLayer.getStrokeWidth();
            fillOpacity = mapLayer.getFillOpacity();

            if ( mergeMode.isReplace() )
            {
                type = mapLayer.getType();
                url = mapLayer.getUrl();
                layers = mapLayer.getLayers();
                time = mapLayer.getTime();
                fillColor = mapLayer.getFillColor();
                strokeColor = mapLayer.getStrokeColor();
            }
            else if ( mergeMode.isMerge() )
            {
                type = mapLayer.getType() == null ? type : mapLayer.getType();
                url = mapLayer.getUrl() == null ? url : mapLayer.getUrl();
                layers = mapLayer.getLayers() == null ? layers : mapLayer.getLayers();
                time = mapLayer.getTime() == null ? time : mapLayer.getTime();
                fillColor = mapLayer.getFillColor() == null ? fillColor : mapLayer.getFillColor();
                strokeColor = mapLayer.getStrokeColor() == null ? strokeColor : mapLayer.getStrokeColor();
            }
        }
    }
}


text:
package com.opengamma.web.security;

import static com.opengamma.web.WebResourceTestUtils.assertJSONObjectEquals;
import static org.testng.Assert.fail;

import java.util.List;

import org.json.JSONObject;
import org.testng.annotations.Test;

import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.financial.security.future.BondFutureSecurity;
import com.opengamma.util.test.TestGroup;

/**
 * Test {@link WebSecurityResource}.
 */
@Test(groups = TestGroup.UNIT)
public class WebSecurityResourceTest extends AbstractWebSecurityResourceTestCase {

  @Test
  @Override
  public void testEquitySecurity() {
    assertGetSecurity(_securities.get(EquitySecurity.class));
  }

  @Test
  @Override
  public void testBondFutureSecurity() {
    assertGetSecurity(_securities.get(BondFutureSecurity.class));
  }

  private void assertGetSecurity(final List<FinancialSecurity> securities) {
    for (final FinancialSecurity security : securities) {
      final WebSecurityResource securityResource = _webSecuritiesResource.findSecurity(security.getUniqueId().toString());
      try {
        final JSONObject actualJson = new JSONObject(securityResource.getJSON());

        final JSONObject expectedJson = security.accept(new ExpectedSecurityJsonProvider());
        assertJSONObjectEquals(expectedJson, actualJson);
      } catch (final Exception e) {
        fail(e.getMessage());
      }
    }
  }

}


text:
/* -*- C++ -*- */

//=============================================================================
/**
 *  @file    Command_Processor.h
 *
 *  $Id: Command_Processor.h 93639 2011-03-24 13:32:13Z johnnyw $
 *
 *  @author Douglas C. Schmidt <schmidt@cs.wustl.edu>
 */
//=============================================================================

#ifndef _COMMAND_PROCESSOR_H
#define _COMMAND_PROCESSOR_H

#if !defined (ACE_LACKS_PRAGMA_ONCE)
#pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "ace/Containers.h"
#include "Options.h"

// Forward decl.
class URL;

/**
 * @class Command
 *
 * @brief Abstract base class for a command.
 *
 * Each command is executed by a <Command_Processor>.
 */
class Command
{
public:
  /// Virtual destructor.
  virtual ~Command (void);

  /// This is the entry point to execute the command.
  virtual int execute (void) = 0;
  virtual int destroy (void) = 0;
};

/**
 * @class URL_Command
 *
 * @brief Defines an API for executing a command on a URL.
 *
 * Each command is executed by a <Command_Processor>.
 */
class URL_Command : public Command
{
public:
  /// Constructor.
  URL_Command (URL *);

  /// Execute the URL command.
  virtual int execute (void);

  /// Commit suicide.
  int destroy (void);
private:
  /// Pointer to the URL.
  URL *url_;
};

/**
 * @class Command_Processor
 *
 * @brief Execute commands that are passed to it.
 *
 * This class implements the Command Processor pattern.
 */
class Command_Processor
{
public:
  Command_Processor (void);

  /// Insert a new <Command> into the <Command_Processor>'s queue.
  int insert (Command *);

  /// Execute all the <Commands> in the queue.
  int execute (void);

  /// Destroy the <Command_Processor>.
  int destroy (void);

protected:
  /// Ensure dynamic allocation.
  ~Command_Processor (void);

private:
  // @@ You fill in here...
  ACE_Unbounded_Queue<Command *> url_queue_;
};

#endif /* _COMMAND_PROCESSOR_H */


text:
package com.sailthru.client.params;

import com.google.gson.reflect.TypeToken;
import com.sailthru.client.ApiAction;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Prajwal Tuladhar <praj@sailthru.com>
 */
public class Blast extends AbstractApiParams implements ApiParams {

    protected String name;
    protected String list;
    protected String schedule_time;
    protected String from_name;
    protected String from_email;
    protected String subject;
    protected String content_html;
    protected String content_text;

    protected Integer blast_id;
    protected Integer copy_blast;
    protected String copy_template;
    protected String eval_template;
    protected String replyto;
    protected String report_email;
    protected Integer is_link_tracking;
    protected Integer is_google_tracking;
    protected Integer is_public;
    protected String suppress_list;
    protected Map<String, Object> test_vars;
    protected Integer email_hour_range;
    protected Integer abtest;
    protected Integer test_percent;
    protected String data_feed_url;
    protected String setup;
    protected Map<String, Object> vars;

    public Blast(String name, String list, String scheduleTime, String fromName, String fromEmail, String subject, String contentHtml, String contentText) {
        this.name = name;
        this.list = list;
        this.schedule_time = scheduleTime;
        this.from_name = fromName;
        this.from_email = fromEmail;
        this.subject = subject;
        this.content_html = contentHtml;
        this.content_text = contentText;
    }

    public Blast() {

    }

    public Blast setName(String name) {
        this.name = name;
        return this;
    }

    public Blast setList(String list) {
        this.list = list;
        return this;
    }

    public Blast setScheduleTime(Date schedule_time) {
        this.schedule_time = schedule_time.toString();
        return this;
    }

    public Blast setScheduleTime(String schedule_time) {
        this.schedule_time = schedule_time;
        return this;
    }

    public Blast setFromName(String fromName) {
        this.from_name = fromName;
        return this;
    }

    public Blast setFromEmail(String fromEmail) {
        this.from_email = fromEmail;
        return this;
    }

    public Blast setSubject(String subject) {
        this.subject = subject;
        return this;
    }

    public Blast setContentHtml(String contentHtml) {
        this.content_html = contentHtml;
        return this;
    }

    public Blast setContentText(String contentText) {
        this.content_text = contentText;
        return this;
    }

    public Blast setBlastId(Integer blastId) {
        this.blast_id = blastId;
        return this;
    }

    public Blast setCopyBlast(Integer copyBlastId) {
        this.copy_blast = copyBlastId;
        return this;
    }

    public Blast setCopyTemplate(String copyTemplate) {
        this.copy_template = copyTemplate;
        return this;
    }

    public Blast setEvalTemplate(String evalTemplate) {
        this.eval_template = evalTemplate;
        return this;
    }

    public Blast setReplyTo(String replyTo) {
        this.replyto = replyTo;
        return this;
    }

    public Blast setReportEmail(String reportEmail) {
        this.report_email = reportEmail;
        return this;
    }

    public Blast enableLinkTracking() {
        this.is_link_tracking = 1;
        return this;
    }

    public Blast enableGoogleAnalytics() {
        this.is_google_tracking = 1;
        return this;
    }

    public Blast setAsPublic() {
        this.is_public = 1;
        return this;
    }

    public Blast setSupressList(String supressList) {
        this.suppress_list = supressList;
        return this;
    }

    public Blast setTestVars(Map<String, Object> testVars) {
        this.test_vars = testVars;
        return this;
    }

    public Blast setEmailHourRange(Integer hours) {
        this.email_hour_range = hours;
        return this;
    }

    public Blast enableABTest() {
        this.abtest = 1;
        return this;
    }

    public Blast setTestPercent(Integer percentage) {
        this.test_percent = percentage;
        return this;
    }

    public Blast setDataFeedUrl(String dataFeedUrl) {
        this.data_feed_url = dataFeedUrl;
        return this;
    }

    public Blast setDataFeedUrl(URI dataFeedUrl) {
        this.data_feed_url = dataFeedUrl.toString();
        return this;
    }

    public Blast setSetup(String setup) {
        this.setup = setup;
        return this;
    }

    public Blast setVars(Map<String, Object> vars){
        this.vars = vars;
        return this;
    }

    public Type getType() {
        Type type = new TypeToken<Blast>() {}.getType();
        return type;
    }

    @Override
    public ApiAction getApiCall() {
        return ApiAction.blast;
    }
}


text:
<?php
/*
V5.20dev  ??-???-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
  Released under both BSD license and Lesser GPL library license.
  Whenever there is any discrepancy between the two licenses,
  the BSD license will take precedence.
Set tabs to 4 for best viewing.

  Latest version is available at http://adodb.sourceforge.net

  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.
*/

// security - hide paths
if (!defined('ADODB_DIR')) die();

if (!defined('_ADODB_ODBC_LAYER')) {
	include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('ADODB_VFP')){
define('ADODB_VFP',1);
class ADODB_vfp extends ADODB_odbc {
	var $databaseType = "vfp";
	var $fmtDate = "{^Y-m-d}";
	var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";
	var $replaceQuote = "'+chr(39)+'" ;
	var $true = '.T.';
	var $false = '.F.';
	var $hasTop = 'top';		// support mssql SELECT TOP 10 * FROM TABLE
	var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
	var $sysTimeStamp = 'datetime()';
	var $sysDate = 'date()';
	var $ansiOuter = true;
	var $hasTransactions = false;
	var $curmode = false ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L

	function ADODB_vfp()
	{
		$this->ADODB_odbc();
	}

	function Time()
	{
		return time();
	}

	function BeginTrans() { return false;}

	// quote string to be sent back to database
	function qstr($s,$nofixquotes=false)
	{
		if (!$nofixquotes) return  "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";
		return "'".$s."'";
	}

	// TOP requires ORDER BY for VFP
	function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
	{
		$this->hasTop = preg_match('/ORDER[ \t\r\n]+BY/is',$sql) ? 'top' : false;
		$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
		return $ret;
	}

};

class  ADORecordSet_vfp extends ADORecordSet_odbc {

	var $databaseType = "vfp";

	function ADORecordSet_vfp($id,$mode=false)
	{
		return $this->ADORecordSet_odbc($id,$mode);
	}

	function MetaType($t,$len=-1)
	{
		if (is_object($t)) {
			$fieldobj = $t;
			$t = $fieldobj->type;
			$len = $fieldobj->max_length;
		}
		switch (strtoupper($t)) {
		case 'C':
			if ($len <= $this->blobSize) return 'C';
		case 'M':
			return 'X';

		case 'D': return 'D';

		case 'T': return 'T';

		case 'L': return 'L';

		case 'I': return 'I';

		default: return 'N';
		}
	}
}

} //define


text:
requirejs.config({
  paths: {
    'd3': ['/node_modules/d3/d3'],
    'ws': ['ws-shim']
  },
  shim: {
    'd3': { exports: 'd3' },
    'ws': { exports: 'ws' }
  }
});

var ctrl;

requirejs(
  ['vm-connection', 'controller', 'ui-controller', 'debugger', 'view',
   'visualizations', 'breakpoints'],
  function(vmConn, cont, uiCont, d, vw) {
    $("#graph-canvas").resizable({handleSelector: '#split-system-code', resizeWidth: false});

    var view = new vw.View(),
      vmConnection = new vmConn.VmConnection(true),
      dbg = new d.Debugger();
    ctrl = new uiCont.UiController(dbg, view, vmConnection);
    ctrl.toggleConnection();
  });


text:
#include "ngx_tcp_lua_common.h"

#define CLFACTORY_BEGIN_CODE "return function() "
#define CLFACTORY_BEGIN_SIZE (sizeof(CLFACTORY_BEGIN_CODE)-1)

#define CLFACTORY_END_CODE " end"
#define CLFACTORY_END_SIZE (sizeof(CLFACTORY_END_CODE)-1)

int ngx_tcp_lua_clfactory_loadfile(lua_State *L, const char *filename);
int ngx_tcp_lua_clfactory_loadstring(lua_State *L, const char *s);
int ngx_tcp_lua_clfactory_loadbuffer(lua_State *L, const char *buff,
        size_t size, const char *name);

#endif


text:
var moment = require('moment');

var isValidDate = function(date) { //validate the user input date and than confert it
    if (moment(date, 'DD-MM-YYYY').isValid()) {
        //dutch format
        return moment(date, 'DD-MM-YYYY').format('YYYY-M-D');
    } else if (moment(date, 'DD-MM-YY').isValid()) {
        //span year
        return moment(date, 'DD-MM-YY').format('DD-MM-YY');
    } else if (moment(date, 'YYYY-MM-DD').isValid()) {
        //browser fromat
        return moment(date, 'YYYY-MM-DD').format('YYYY-M-D');
    } else if (moment(date, 'MM-DD-YYYY').isValid()) {
        //english fromat
        return moment(date, 'MM-DD-YYYY').format('YYYY-M-D');
    } else {
        return false;
    }
};

module.exports = isValidDate;


text:
layout: docs
header: true
title: GPU vs CPU benchmark
permalink: /docs/en/CPUvsGPUbenchmark
key: docs-concepts
modify_date: "2021-08-31"
use_language_switcher: "Python-Scala"
show_nav: true
sidebar:
    nav: sparknlp
---

This section includes benchmarks for different Approach() (training classes), comparing their performance when running in `m5.8xlarge` CPU vs a `Tesla V100 SXM2` GPU, as described in the `Machine Specs` section below.

Different benchmarks, as well as their takeaways and some conclusions of how to get the best of GPU, are included as well, to guide you in the process of getting the best performance out of Spark NLP on GPU.

Each major release comes with big improvements, so please, make sure you use at least that version to fully levearge Spark NLP capabilities on GPU.

### Machine specs

#### CPU
An AWS `m5.8xlarge` machine was used for the CPU benchmarking. This machine consists of `32 vCPUs` and `128 GB of RAM`, as you can check in the official specification webpage available [here](https://aws.amazon.com/ec2/instance-types/m5/)

#### GPU
A `Tesla V100 SXM2` GPU with `32GB` of memory was used to calculate the GPU benchmarking.

### Versions
The benchmarking was carried out with the following Spark NLP versions:

Spark version: `3.0.2`

Hadoop version: `3.2.0`

SparkNLP version: `3.3.4`

Spark nodes: 1

### Benchmark on classifierDLApproach()

This experiment consisted of training a Deep Learning Binary Classifier (Question vs Statement classes) at sentence-level, using a fully connected CNN and Bert Sentence Embeddings. Only 1 Spark node was usd for the training.

We used the Spark NLP class `ClassifierDL` and it's method `Approach()` as described in the [documentation](https://nlp.johnsnowlabs.com/docs/en/annotators#classifierdl).

The pipeline looks as follows:
![](/assets/images/gpu_v2_pic3.png)

#### Dataset
The size of the dataset was relatively small (200K), consisting of:

Training (rows): `162250`

Test (rows): `40301`

#### Training params
Different batch sizes were tested to demonstrate how GPU performance improves with bigger batches compared to CPU, for a constant number of epochs and learning rate.

Epochs: `10`

Learning rate:  `0.003`

Batch sizes: `32`, `64`, `256`, `1024`

#### Results
Even for this average-sized dataset, we can observe that GPU is able to beat the CPU machine by a `76%` in both `training` and `inference` times.

#### Training times depending on batch (in minutes)

![](/assets/images/gpu_v2_pic1.png)

{:.table-model-big}
| Batch size | CPU | GPU |
| :---: | :---: | :--: |
|  32  |  66  |  16.1  |
|  64  |  65  |  15.3  |
|  256  |  64  |  14.5  |
|  1024  |  64  |  14  |

#### Inference times (in minutes)
The average inference time remained more or less constant regardless the batch size:
CPU: `8.7 min`
GPU: `2 min`

![](/assets/images/gpu_v2_pic5.png)

#### Performance metrics
A weighted F1-score of 0.88 was achieved, with a 0.90 score for question detection and 0.83 for statements.

![](/assets/images/gpu_v2_pic2.png)

### Benchmark on NerDLApproach()

This experiment consisted of training a Name Entity Recognition model (token-level), using our class NerDLApproach(), using Bert Word Embeddings and a Char-CNN-BiLSTM Neural Network. Only 1 Spark node was used for the training.

We used the Spark NLP class `NerDL` and it's method `Approach()` as described in the [documentation](https://nlp.johnsnowlabs.com/docs/en/annotators#nerdl).

The pipeline looks as follows:
![](/assets/images/gpu_v2_pic4.png)

#### Dataset
The size of the dataset was small (17K), consisting of:

Training (rows): `14041`

Test (rows): `3250`

#### Training params
Different batch sizes were tested to demonstrate how GPU performance improves with bigger batches compared to CPU, for a constant number of epochs and learning rate.

Epochs: `10`

Learning rate:  `0.003`

Batch sizes: `32`, `64`, `256`,  `512`, `1024`, `2048`

#### Results
Even for this small dataset, we can observe that GPU is able to beat the CPU machine by a `62%` in `training` time and a `68%` in `inference` times. It's important to mention that the batch size is very relevant when using GPU, since CPU scales much worse with bigger batch sizes than GPU.

#### Training times depending on batch (in minutes)

![](/assets/images/gpu_v2_pic6.png)

{:.table-model-big}
| Batch size | CPU | GPU |
| :---: | :---: | :--: |
| 32 | 9.5 | 10 |
| 64 | 8.1 | 6.5 |
| 256 | 6.9 | 3.5 |
| 512 | 6.7  | 3 |
| 1024 | 6.5 | 2.5 |
| 2048 | 6.5 | 2.5 |

#### Inference times (in minutes)
Although CPU times in inference remain more or less constant regardless the batch sizes, GPU time experiment good improvements the bigger the batch size is.

CPU times: `~29 min`

{:.table-model-big}
| Batch size | GPU |
| :---: | :--: |
| 32 | 10 |
| 64 | 6.5 |
| 256 | 3.5 |
| 512 | 3 |
| 1024 | 2.5 |
| 2048 | 2.5 |

![](/assets/images/gpu_v2_pic7.png)

#### Performance metrics
A macro F1-score of about `0.92` (`0.90` in micro) was achieved, with the following charts extracted from the `NERDLApproach()` logs:

![](/assets/images/gpu_v2_pic8.png)

### Inference benchmark on BertSentenceEmbeddings()

This experiment consisted of benchmarking the improvement obtained in inference by using GPU on BertSentenceEmbeddings().

We used the Spark NLP class `BertSentenceEmbeddings()` described in the Transformers [documentation](https://nlp.johnsnowlabs.com/docs/en/transformers#bertsentenceembeddings).

The pipeline contains only two components and looks as follows:
![](/assets/images/gpu_v2_pic9.png)

#### Dataset
The size of the dataset was bigger than the previous ones, with `417735` rows for inference.

#### Results
We have observed in previous experiments, using BertSentenceEmbeddings (classifierDL) and also BertEmbeddings (NerDL) how GPU improved both training and inference times. In this case, we observe again big improvements in inference, what is already pointing that one of the main reasons of why GPU improves so much over CPU is the better management of Embeddings (word, sentence level) and bigger batch sizes.

Batch sizes: `32`, `64`, `256`, `1024`

#### Inference times depending on batch (in minutes)
![](/assets/images/gpu_v2_pic10.png)

{:.table-model-big}
| Batch size | CPU | GPU |
| :---: | :---: | :--: |
| 32 | 80 | 9.9 |
| 64 | 77 | 9.8 |
| 256 | 63 | 9.4 |
| 1024 | 62 | 9.1 |

### Takeaways: How to get the best of the GPU
You will experiment big GPU improvements in the following cases:

{:.list1}
1. Embeddings and Transformers are used in your pipeline. Take into consideration that GPU will performance very well in Embeddings / Transformer components, but other components of your pipeline may not leverage as well GPU capabilities;
2. Bigger batch sizes get the best of GPU, while CPU does not scale with bigger batch sizes;
3. Bigger dataset sizes get the best of GPU, while may be a bottleneck while running in CPU and lead to performance drops;

### MultiGPU training
Right now, we don't support multigpu training (1 model in different GPUs in parallel), but you can train different models in different GPU.

### Where to look for more information about Training
Please, take a look at the [Spark NLP](https://nlp.johnsnowlabs.com/docs/en/training) and [Spark NLP for Healthcare](https://nlp.johnsnowlabs.com/docs/en/licensed_training) Training sections, and feel free to reach us out in case you want to maximize the performance on your GPU.


text:
<?php

namespace Imgur\Auth;

use Imgur\Exception\AuthException;
use Imgur\HttpClient\HttpClientInterface;

/**
 * Authentication class used for handling OAuth2.
 *
 * @author Adrian Ghiuta <adrian.ghiuta@gmail.com>
 */
class OAuth2 implements AuthInterface
{
    const AUTHORIZATION_ENDPOINT = 'https://api.imgur.com/oauth2/authorize';
    const ACCESS_TOKEN_ENDPOINT = 'https://api.imgur.com/oauth2/token';

    /**
     * Indicates the client that is making the request.
     *
     * @var string
     */
    private $clientId;

    /**
     * The client_secret for the application.
     *
     * @var string
     */
    private $clientSecret;

    /**
     * The class handling communication with Imgur servers.
     *
     * @var \Imgur\HttpClient\HttpClientInterface
     */
    private $httpClient;

    /**
     * The access token and refresh token values, with keys:.
     *
     * For "token":
     *     - access_token
     *     - expires_in
     *     - token_type
     *     - refresh_token
     *     - account_username
     *     - account_id
     *
     * For "code":
     *     - code
     *     - state
     *
     * For "pin":
     *     - pin
     *     - state
     *
     * @var array
     */
    private $token;

    /**
     * Instantiates the OAuth2 class, but does not trigger the authentication process.
     *
     * @param string $clientId
     * @param string $clientSecret
     */
    public function __construct(HttpClientInterface $httpClient, $clientId, $clientSecret)
    {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
        $this->httpClient = $httpClient;
    }

    /**
     * Generates the authentication URL to which a user should be pointed at in order to start the OAuth2 process.
     *
     * @param string      $responseType
     * @param string|null $state
     *
     * @return string
     */
    public function getAuthenticationURL($responseType = 'code', $state = null)
    {
        $httpQueryParameters = [
            'client_id' => $this->clientId,
            'response_type' => $responseType,
            'state' => $state,
        ];

        $httpQueryParameters = http_build_query($httpQueryParameters);

        return self::AUTHORIZATION_ENDPOINT . '?' . $httpQueryParameters;
    }

    /**
     * Exchanges a code/pin for an access token.
     *
     * @param string $code
     * @param string $requestType
     *
     * @return array
     */
    public function requestAccessToken($code, $requestType)
    {
        switch ($requestType) {
            case 'pin':
                $grantType = 'pin';
                $type = 'pin';
                break;
            case 'code':
            default:
                $grantType = 'authorization_code';
                $type = 'code';
        }

        try {
            $response = $this->httpClient->post(
                self::ACCESS_TOKEN_ENDPOINT,
                [
                    'client_id' => $this->clientId,
                    'client_secret' => $this->clientSecret,
                    'grant_type' => $grantType,
                    $type => $code,
                ]
            );

            $responseBody = json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            throw new AuthException('Request for access token failed: ' . $e->getMessage(), $e->getCode());
        }

        $responseBody['created_at'] = time();
        $this->setAccessToken($responseBody);

        $this->sign();

        return $responseBody;
    }

    /**
     * If a user has authorized their account but you no longer have a valid access_token for them,
     * then a new one can be generated by using the refresh_token.
     * When your application receives a refresh token, it is important to store that refresh token for future use.
     * If your application loses the refresh token,
     * you will have to prompt the user for their login information again.
     *
     * @throws AuthException
     *
     * @return array
     */
    public function refreshToken()
    {
        $token = $this->getAccessToken();

        try {
            $response = $this->httpClient->post(
                self::ACCESS_TOKEN_ENDPOINT,
                [
                    'refresh_token' => \is_array($token) ? $token['refresh_token'] : null,
                    'client_id' => $this->clientId,
                    'client_secret' => $this->clientSecret,
                    'grant_type' => 'refresh_token',
                ]
            );

            $responseBody = json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            throw new AuthException('Request for refresh access token failed: ' . $e->getMessage(), $e->getCode());
        }

        $this->setAccessToken($responseBody);

        $this->sign();

        return $responseBody;
    }

    /**
     * Stores the access token, refresh token and expiration date.
     *
     * @param array $token
     *
     * @throws AuthException
     *
     * @return array
     */
    public function setAccessToken($token)
    {
        if (!\is_array($token)) {
            throw new AuthException('Token is not a valid json string.');
        }

        if (isset($token['data']['access_token'])) {
            $token = $token['data'];
        }

        if (!isset($token['access_token'])) {
            throw new AuthException('Access token could not be retrieved from the decoded json response.');
        }

        $this->token = $token;

        $this->sign();
    }

    /**
     * Getter for the current access token.
     *
     * @return array|null
     */
    public function getAccessToken()
    {
        return $this->token;
    }

    /**
     * Check if the current access token (if present), is still usable.
     *
     * @return bool
     */
    public function checkAccessTokenExpired()
    {
        // don't have the data? Let's assume the token has expired
        if (!isset($this->token['created_at']) || !isset($this->token['expires_in'])) {
            return true;
        }

        return ($this->token['created_at'] + $this->token['expires_in']) < time();
    }

    /**
     * Add middleware for attaching header signature to each request.
     */
    public function sign()
    {
        $this->httpClient->addAuthMiddleware(
            $this->getAccessToken(),
            $this->clientId
        );
    }
}


text:
namespace Warbler.Data
{
    using System;
    using System.Data.Entity;
    using System.Collections.Generic;

    using Contracts;
    using Models;
    using Repositories;

    public class WarblerData : IWarblerData
    {
        private DbContext context;
        private IDictionary<Type, object> repositories;

        public WarblerData(DbContext context)
        {
            this.context = context;
            this.repositories = new Dictionary<Type, object>();
        }

        public IRepository<Message> Messages
        {
            get
            {
                return this.GetRepository<Message>();
            }
        }

        public IRepository<Notification> Notifications
        {
            get
            {
                return this.GetRepository<Notification>();
            }
        }

        public IRepository<User> Users
        {
            get
            {
                return this.GetRepository<User>();
            }
        }

        public IRepository<Warble> Warbles
        {
            get
            {
                return this.GetRepository<Warble>();
            }
        }

        public int SaveChanges()
        {
            return this.context.SaveChanges();
        }

        private IRepository<T> GetRepository<T>() where T: class
        {
            Type typeOfRepository = typeof(T);
            if (!this.repositories.ContainsKey(typeOfRepository))
            {
                var repositoryInstance = Activator.CreateInstance(typeof(GenericRepository<T>), context);

                this.repositories.Add(typeOfRepository, repositoryInstance);
            }

            return (IRepository<T>)this.repositories[typeOfRepository];
        }
    }
}


text:
package org.aws4j.data.dynamo.attribute;

public class OneToManyAttribute<M, V, E extends MetaModel<V>> extends RelationalAttribute<M, V, E>{

	public OneToManyAttribute(Class<M> modelClass, Class<V> valueClass, Class<E> metaClass, String name) {
	}

	public E meta() {
		return null;
	}

}


text:
#include <geode/internal/geode_globals.hpp>

#include <ace/Time_Value.h>
#include <ace/OS.h>

namespace test {
void dummyFunc() {}

void millisleep(uint32_t x) {
  ACE_Time_Value timeV(0);
  timeV.msec(static_cast<long>(x));
  ACE_OS::sleep(timeV);
}
}  // namespace test

#define SLEEP(x) test::millisleep(x);
#define LOG LOGDEBUG

#include "TallyListener.hpp"
#include "TallyLoader.hpp"
#include "TallyWriter.hpp"
#include <util/Log.hpp>

#ifdef _WIN32
#define _T_DLL_EXPORT __declspec(dllexport)
#else
#define _T_DLL_EXPORT
#endif

extern "C" {

_T_DLL_EXPORT apache::geode::client::CacheListener* createCacheListener() {
  TallyListener* tl = new TallyListener();
  tl->beQuiet(true);
  return tl;
}

_T_DLL_EXPORT apache::geode::client::CacheLoader* createCacheLoader() {
  return new TallyLoader();
}

_T_DLL_EXPORT apache::geode::client::CacheWriter* createCacheWriter() {
  return new TallyWriter();
}
}


text:
#ifndef LINEARSEARCH_H
#define LINEARSEARCH_H

#include "flann/general.h"
#include "flann/algorithms/nn_index.h"

namespace flann
{

struct LinearIndexParams : public IndexParams {
	LinearIndexParams() : IndexParams(LINEAR) {};

	flann_algorithm_t getIndexType() const { return algorithm; }

	void fromParameters(const FLANNParameters& p)
	{
		assert(p.algorithm==algorithm);
	}

	void toParameters(FLANNParameters& p) const
	{
		p.algorithm = algorithm;
	}

	void print() const
	{
		logger.info("Index type: %d\n",(int)algorithm);
	}
};

template <typename Distance>
class LinearIndex : public NNIndex<Distance>
{
	typedef typename Distance::ElementType ElementType;
	typedef typename Distance::ResultType DistanceType;

	const Matrix<ElementType> dataset;
	const LinearIndexParams& index_params;

	Distance distance;

public:

	LinearIndex(const Matrix<ElementType>& inputData, const LinearIndexParams& params = LinearIndexParams(),
			Distance d = Distance()) :
		dataset(inputData), index_params(params), distance(d)
	{
	}

    flann_algorithm_t getType() const
    {
        return LINEAR;
    }

	size_t size() const
	{
		return dataset.rows;
	}

	size_t veclen() const
	{
		return dataset.cols;
	}

	int usedMemory() const
	{
		return 0;
	}

	void buildIndex()
	{
		/* nothing to do here for linear search */
	}

    void saveIndex(FILE* stream)
    {
		/* nothing to do here for linear search */
    }

    void loadIndex(FILE* stream)
    {
		/* nothing to do here for linear search */
    }

	void findNeighbors(ResultSet<DistanceType>& resultSet, const ElementType* vec, const SearchParams& searchParams)
	{
		for (size_t i=0;i<dataset.rows;++i) {
			DistanceType dist = distance(dataset[i],vec, dataset.cols);
			resultSet.addPoint(dist,i);
		}
	}

	const IndexParams* getParameters() const
	{
		return &index_params;
	}

};

}

#endif // LINEARSEARCH_H


text:
#pragma once

#include <vector>

#include <nbind/api.h>

#include "Namespace.h"
#include "PatriciaCursor.h"
#include "ParserConfig.h"

struct ParserState {

	/** Flag whether the opening tag had a namespace prefix. */
	bool isQualified;
	/** Namespace of this element. */
	Namespace *nsElement;
	/** Default xmlns before entering this element. */
	Namespace *nsOuterDefault;
	/** Number of new xmlns mappings made by this element. */
	uint32_t xmlnsMapCount;

};

struct PrefixDefinition {

	PrefixDefinition(uint32_t idPrefix = 0, uint32_t idNamespace = 0) :
	idPrefix(idPrefix), idNamespace(idNamespace) {}

	uint32_t idPrefix;
	uint32_t idNamespace;

};

struct Element {

	Element(size_t prefixStackOffset, uint32_t crc32) :
	prefixStackOffset(prefixStackOffset), crc32(crc32) {}

	size_t prefixStackOffset;
	// TODO: verify open and close tags match by using CRC.
	uint32_t crc32;

};

/** Fast streaming XML parser. */

class Parser {

public:

	static constexpr uint32_t namespacePrefixTblSize = ParserConfig :: namespacePrefixTblSize;

	/** Parser states. */

	enum class State : uint32_t {
		BEGIN,
		MATCH, MATCH_SPARSE, QUOTE,
		BEFORE_TEXT, TEXT,
		BEFORE_CDATA, CDATA,
		AFTER_LT,
		BEFORE_NAME, MATCH_TRIE, NAME, UNKNOWN_NAME,
		STORE_ELEMENT_NAME, AFTER_ELEMENT_NAME,
		AFTER_CLOSE_ELEMENT_NAME,
		BEFORE_ATTRIBUTE_VALUE, AFTER_ATTRIBUTE_VALUE,
		DEFINE_XMLNS_BEFORE_PREFIX_NAME, DEFINE_XMLNS_AFTER_PREFIX_NAME,
		BEFORE_VALUE, VALUE, UNKNOWN_VALUE, DEFINE_XMLNS_AFTER_URI,
		BEFORE_SGML, SGML_DECLARATION,
		AFTER_PROCESSING_NAME, AFTER_PROCESSING_VALUE,
		BEFORE_COMMENT, COMMENT,
		EXPECT,
		PARSE_ERROR
	};

	enum class TagType : uint32_t {
		ELEMENT,
		SGML_DECLARATION,
		PROCESSING
	};

	enum class MatchTarget : uint32_t {
		ELEMENT,
		ELEMENT_NAMESPACE,
		ATTRIBUTE,
		ATTRIBUTE_NAMESPACE
	};

	static constexpr unsigned int TOKEN_SHIFT = 5;

	#define export
	#define const
	#define enum enum class

	#define CodeType TokenType : uint32_t
	#include "../src/tokenizer/CodeType.ts"
	#undef CodeType

	#define ErrorType ErrorType : uint32_t
	#include "../src/tokenizer/ErrorType.ts"
	#undef ErrorType

	#undef enum
	#undef const
	#undef export

	Parser(const ParserConfig &config);

	ErrorType destroy();

	ParserConfig *getConfig() { return(&config); }

	/** Parse a chunk of incoming data. */
	ErrorType parse(nbind::Buffer chunk);

	void setCodeBuffer(nbind::Buffer tokenBuffer, nbind::cbFunction &flushTokens) {
		this->flushTokens = std::unique_ptr<nbind::cbFunction>(new nbind::cbFunction(flushTokens));
		this->tokenBuffer = tokenBuffer;

		tokenList = reinterpret_cast<uint32_t *>(tokenBuffer.data());
		tokenBufferEnd = tokenList + tokenBuffer.length() / 4;

		flushTokens.reset();
	}

	inline void flush(uint32_t *&tokenPtr) {
		(*flushTokens)();
		tokenList[0] = 0;
		tokenPtr = tokenList + 1;
	}

	bool updateElementStack(TokenType nameTokenType) {
		if(nameTokenType == TokenType :: OPEN_ELEMENT_ID) {
			// TODO: Ensure stack is not too large.
			elementStack.emplace_back(prefixStack.size(), 0);
		} else if(nameTokenType == TokenType :: CLOSE_ELEMENT_ID) {
			if(elementStack.empty()) return(false);

			const Element &element = elementStack.back();
			size_t oldSize = element.prefixStackOffset;

			for(size_t size = prefixStack.size(); size > oldSize; --size) {
				const PrefixDefinition &old = prefixStack.back();
				Namespace *ns = config.namespaceList[old.idNamespace].get();
				// For efficiency, never undefine an xmlns prefix
				// because it may be redefined identically later.
				if(ns) {
					config.namespacePrefixTbl[old.idPrefix] = std::make_pair(old.idNamespace, ns);
				}
				prefixStack.pop_back();
			}

			elementStack.pop_back();
		}

		return(true);
	}

	/** Output a token. This is the only function writing to memory, so safety
	  * from code execution exploits depends on this and nothing else. */

	inline void writeToken(TokenType kind, uint32_t token, uint32_t *&tokenPtr) {
		if(tokenPtr >= tokenBufferEnd) flush(tokenPtr);

		// Buffer content length is stored at its beginning.
		++tokenList[0];

		// This must never write outside the range
		// from tokenList to tokenBufferEnd (exclusive).
		*tokenPtr++ = static_cast<uint32_t>(kind) + (token << TOKEN_SHIFT);
	}

	void setPrefix(uint32_t idPrefix) {
		if(idPrefix < namespacePrefixTblSize) this->idPrefix = idPrefix;
		memberPrefix->idPrefix = idPrefix;
		memberPrefix->idNamespace = config.namespacePrefixTbl[config.emptyPrefixToken].first;
	}

	bool bindPrefix(uint32_t idPrefix, uint32_t uri) {
		uint32_t nsOld = config.namespacePrefixTbl[idPrefix].first;

		if(config.bindPrefix(idPrefix, uri)) {
			// Push old prefix binding to stack, to restore it after closing tag.
			prefixStack.emplace_back(idPrefix, nsOld);
			if(elementPrefix.idPrefix == idPrefix) {
				elementPrefix.idNamespace = config.namespacePrefixTbl[idPrefix].first;
			}
			return(true);
		}

		return(false);
	}

	bool addUri(uint32_t uri, uint32_t idNamespace);

	// Emit content for a partially matched token.
	// If the input buffer was drained, emit the match length and some
	// valid token beginning identically, to recover the complete name.
	inline void emitPartialName(
		const unsigned char *p,
		size_t offset,
		TokenType tokenType,
		uint32_t *&tokenPtr
	);

	inline void updateRowCol(unsigned char c);

	inline uint32_t getRow() { return(row); }
	inline uint32_t getCol() { return(col); }

	ParserConfig config;

	/** Prefix and namespace of current element. */
	PrefixDefinition elementPrefix;
	PrefixDefinition attributePrefix;
	PrefixDefinition *memberPrefix = &attributePrefix;

	std::vector<PrefixDefinition> prefixStack;
	std::vector<Element> elementStack;

	PatriciaCursor cursor;

	unsigned char *nameCharTbl;
	unsigned char *nameStartCharTbl;
	const char *pattern;

	State state;
	State matchState;
	State noMatchState;
	State partialMatchState;
	State afterNameState;
	State afterTextState;
	State afterMatchTrieState;
	/** Next state after reading an element, attribute or processing instruction
	  * name, a text node or an attribute value. */
	State nextState;
	/** Next state if the current character was not the expected one. */
	State otherState;
	/** Next state after reading an attribute value. Regular elements and
	  * processing instructions need different handling. */
	State afterValueState;
	/** Flag whether the previously emitted name was found in a trie. */
	bool knownName;

	TagType tagType;
	MatchTarget matchTarget;

	unsigned char textEndChar;

	/** Expected character for moving to another state. */
	unsigned char expected;

	size_t pos;

	uint32_t row;
	uint32_t col;

	uint32_t idToken;
	uint32_t idPrefix;

	uint32_t idElement;

	uint32_t sgmlNesting;

	TokenType nameTokenType;
	TokenType textTokenType;
	TokenType valueTokenType;
	const unsigned char *tokenStart;

	// TODO: Maybe this could be std::function<void ()>
	std::unique_ptr<nbind::cbFunction> flushTokens;

	Patricia Namespace :: *trie;

	nbind::Buffer tokenBuffer;
	uint32_t *tokenList;
	const uint32_t *tokenBufferEnd;

};


text:
<?php

/**
 * --------
 * WARNING: This is an extension for MediaWiki 1.12 through 1.15 only.
 * Do not use it with other versions of MediaWiki without extensive testing!
 * --------
 *
 * Internationalisation file for AnyWikiDraw_body.php.
 *
 * @author Werner Randelshofer
 * @version $Id: AnyWikiDraw.i18n.php 120 2009-06-28 08:05:06Z rawcoder $
 */
$messages = array();
$messages['en'] = array(
    'anywikidraw' => 'AnyWikiDraw Drawing Extension',
    'anywikidraw_about' => '
On this Wiki the AnyWikiDraw $1 Drawing Extension is installed.
'.
        '
With this extension, you can edit drawings directly inside of a Wiki page.
'.
        '
To include a drawing in a page, use a tag of the form '.
        '<nowiki>{{#drawing:File.svg|width|height}}</nowiki>.
'.
        '
For example '.
        '<nowiki>{{#drawing:HappyFace.svg|400|300}}</nowiki>.
'.
        '
The following filename extensions are supported: .svg, .png, .jpg.
'.
        '
If the file doesn\'t exist, it will be created the first time a drawing has been edited.
'.
        '
All files that have been created using this extension are listed on the [[Special:Imagelist|file list]] special page.',
    'anywikidraw_license_terms_new_work' => 'By saving your work you agree to the license terms of this Wiki. '.
        '
For more information see $1. ',
    'anywikidraw_license_terms_derived_work' => 'By saving your changes you agree to the terms given by the copyright holder of the original work. '.
        '
For more information see $2. ',
    'anywikidraw_upload_disabled' => '
You can not edit drawings using AnyWikiDraw, because you have not enabled file uploading using $wgEnableUploads=true; in LocalSettings.php.
',
    'anywikidraw_cookie_http_only' => '
You can not edit drawings using AnyWikiDraw, because you have not made cookies accessible to Java applets using $wgCookieHttpOnly=false; in LocalSettings.php.
',
    'anywikidraw_extension_disabled' => '
You can not edit drawings with extension $2 using AnyWikiDraw, because you have not enabled this extension using $wgFileExtensions[] = \'$2\'; in LocalSettings.php.
',
    'anywikidraw_extensions_blacklisted' => '
You can not edit drawings with extensions $2 using AnyWikiDraw, because you have explicitly blocked this extension using $wgFileBlacklist = \'$2\'; in LocalSettings.php.
',
);
?>


text:
package com.krishagni.catissueplus.core.biospecimen.services.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.springframework.context.MessageSource;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

import com.krishagni.catissueplus.core.administrative.domain.PermissibleValue;
import com.krishagni.catissueplus.core.biospecimen.domain.Participant;
import com.krishagni.catissueplus.core.biospecimen.domain.Visit;
import com.krishagni.catissueplus.core.biospecimen.services.SprPdfGenerator;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.Utility;

public class SprText2PdfGenerator implements SprPdfGenerator {
	private MessageSource messageSource;

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	@Override
	public File generate(File file, Map<String, Object> contextMap) {
		Visit visit = (Visit)contextMap.get("visit");
		FileOutputStream out = null;
		Document document = new Document();
		try {
			File sprReport = File.createTempFile("spr-report", ".pdf");
			out= new FileOutputStream(sprReport);

			PdfWriter pdfWriter = PdfWriter.getInstance(document, out);
			pdfWriter.setPageEvent(new PdfPageEventHelper() {
				@Override
				public void onStartPage(PdfWriter writer, Document document) {
					String restricted = getMessage("spr_restricted");
					Paragraph paragraph = new Paragraph(restricted);
					paragraph.getFont().setSize(10);

					float xOffset = pdfWriter.getPageSize().getWidth() / 2;
					float yOffset = pdfWriter.getPageSize().getTop() - 25;
					ColumnText.showTextAligned(
						writer.getDirectContent(),
						Element.ALIGN_CENTER,
						paragraph,
						xOffset,
						yOffset,
						0
					);
				}
			});

			document.open();
			document.addTitle(getMessage("spr_title"));

			Paragraph header = new Paragraph();
			header.setAlignment(Element.ALIGN_CENTER);
			Chunk headerText = getChunk(getMessage("spr_header"), 10, true, true);
			header.add(headerText);
			document.add(header);
			document.add(Chunk.NEWLINE);

			Paragraph patientInfo = new Paragraph();
			Chunk patientInfoText = getChunk(getMessage("spr_patient_info"), 10, true, false);
			patientInfo.add(patientInfoText);
			document.add(patientInfo);
			PdfPTable patientInfoTbl = getHeader(visit);
			document.add(patientInfoTbl);

			String fileText = Utility.getFileText(file);
			document.add(new Paragraph(fileText, getFont(8,false)));

			Chunk endReport = getChunk(getMessage("spr_end_of_report"), 6, false, true);
			Paragraph footer = new Paragraph();
			footer.setAlignment(Element.ALIGN_CENTER);
			footer.add(endReport);
			document.add(footer);

			return sprReport;
		} catch(Exception e) {
			throw OpenSpecimenException.serverError(e);
		} finally {
			document.close();
			IOUtils.closeQuietly(out);
		}
	}

	private PdfPTable getHeader(Visit visit) {
		PdfPTable header = new PdfPTable(3);
		header.setSpacingBefore(4f);
		header.setHorizontalAlignment(Element.ALIGN_LEFT);
		header.setWidthPercentage(100);
		header.setSpacingAfter(4f);

		Participant participant = visit.getRegistration().getParticipant();

		Map<String, String> headerInfo = new LinkedHashMap<String, String>();
		headerInfo.put(getMessage("spr_protocol_name"), visit.getCollectionProtocol().getShortTitle());
		headerInfo.put(getMessage("spr_gender"), PermissibleValue.getValue(participant.getGender()));
		headerInfo.put(getMessage("spr_printed_by"),
				AuthUtil.getCurrentUser().getLastName() + ", " + AuthUtil.getCurrentUser().getFirstName());
		headerInfo.put(getMessage("spr_visit_name"), visit.getName());
		headerInfo.put(getMessage("spr_ppid"), visit.getRegistration().getPpid());

		Integer ageAtColl = Utility.yearsBetween(visit.getRegistration().getParticipant().getBirthDate(), visit.getVisitDate());
		String ageRangeStr = "-";
		if (ageAtColl != null) {
			ageAtColl = (ageAtColl / 10) * 10;
			ageRangeStr = ageAtColl + " - " + (ageAtColl + 9);
		}
		headerInfo.put(getMessage("spr_age_at_collection"), ageRangeStr);

		headerInfo.put(getMessage("spr_printed_on_date"), Utility.getDateString(new Date()));
		headerInfo.put(getMessage("spr_participant_race"),
				Utility.stringListToCsv(PermissibleValue.toValueList(participant.getRaces()), false));
		headerInfo.put(getMessage("spr_visit_date"), Utility.getYear(visit.getVisitDate()).toString());

		for (Map.Entry<String, String> entry : headerInfo.entrySet()) {
			Paragraph paragraph = new Paragraph();
			paragraph.add(getChunk(entry.getKey(), 8, true, false));

			String val = (entry.getValue() != null) ? entry.getValue() : "-";
			paragraph.add(getChunk(val, 8, false, false));

			PdfPCell cell = new PdfPCell(paragraph);
			cell.setHorizontalAlignment(Element.ALIGN_LEFT);
			header.addCell(cell);
		}

		return header;
	}

	private Font getFont(int size, boolean bold) {
		int font = bold ? Font.BOLD: Font.NORMAL;
		return new Font(FontFamily.HELVETICA, size, font);
	}

	private Chunk getChunk(String message, int fontSize, boolean bold, boolean underline) {
		Chunk chunk = new Chunk(message);
		chunk.setFont(getFont(fontSize, bold));
		if (underline) {
			chunk.setUnderline(0.1f, -2f);
		}
		return chunk;
	}

	private String getMessage(String code) {
		return messageSource.getMessage(code, null, Locale.getDefault());
	}
}


text:
/**
 * This file is part of the CernVM File System.
 */

#ifndef CVMFS_REFLOG_H_
#define CVMFS_REFLOG_H_

#include <string>
#include <vector>

#include "reflog_sql.h"

namespace manifest {

// TODO(rmeusel): this shares a lot of database management code with
//                SqliteHistory and (potentially) ...Catalog. This might be an
//                architectural weakness and should be cleaned up.
class Reflog {
 public:
  static Reflog* Open(const std::string &database_path);
  static Reflog* Create(const std::string &database_path,
                        const std::string &repo_name);

  std::string CloseAndReturnDatabaseFile() {
    return database_->CloseAndReturnDatabaseFile();
  }

  bool AddCertificate(const shash::Any &certificate);
  bool AddCatalog(const shash::Any &catalog);
  bool AddHistory(const shash::Any &history);
  bool AddMetainfo(const shash::Any &metainfo);

  uint64_t CountEntries();
  bool ListCatalogs(std::vector<shash::Any> *hashes) const;

  bool RemoveCatalog(const shash::Any &hash);

  bool ContainsCertificate(const shash::Any &certificate) const;
  bool ContainsCatalog(const shash::Any &catalog) const;
  bool ContainsHistory(const shash::Any &history) const;
  bool ContainsMetainfo(const shash::Any &metainfo) const;

  void BeginTransaction();
  void CommitTransaction();

  void TakeDatabaseFileOwnership();
  void DropDatabaseFileOwnership();
  bool OwnsDatabaseFile() const {
    return database_.IsValid() && database_->OwnsFile();
  }

  std::string fqrn() const;
  std::string database_file() const;

 protected:
  bool AddReference(const shash::Any               &hash,
                    const SqlReflog::ReferenceType  type);
  bool ContainsReference(const shash::Any               &hash,
                         const SqlReflog::ReferenceType  type) const;

 private:
  bool CreateDatabase(const std::string &database_path,
                      const std::string &repo_name);
  bool OpenDatabase(const std::string &database_path);

  void PrepareQueries();

 private:
  UniquePtr<ReflogDatabase>       database_;

  UniquePtr<SqlInsertReference>   insert_reference_;
  UniquePtr<SqlCountReferences>   count_references_;
  UniquePtr<SqlListReferences>    list_references_;
  UniquePtr<SqlRemoveReference>   remove_reference_;
  UniquePtr<SqlContainsReference> contains_reference_;
};

}  // namespace manifest

#endif  // CVMFS_REFLOG_H_


text:
"""
Type coercion.
"""

from __future__ import print_function, division, absolute_import

from flypy import jit, ijit, cjit, cast
from flypy.types import Type, Pointer, void

jit = cjit

#===------------------------------------------------------------------===
# coerce
#===------------------------------------------------------------------===

#@jit('a -> Type[a] -> a')
#def coerce(x, ty):
#    return x

# -- bool

@jit('a -> Type[bool] -> bool')
def coerce(x, ty):
    return bool(x)

# -- numeric

@jit('a : integral -> Type[b : integral] -> b')
def coerce(x, ty):
    return cast(x, ty)

@jit('a -> Type[b : integral] -> b')
def coerce(x, ty):
    return int(x)

@jit('a : floating -> Type[b : integral] -> b')
def coerce(x, ty):
    raise TypeError("Can't coerce float to int")

@jit('a -> Type[b : floating] -> b')
def coerce(x, ty):
    return cast(x, ty)

@jit('a -> Type[b : complexes] -> b')
def coerce(x, ty):
    return complex(x)

# -- pointer

@jit('Pointer[a] -> Type[Pointer[void]] -> Pointer[void]')
def coerce(x, ty):
    return cast(x, ty)

#===------------------------------------------------------------------===
# helper functions
#===------------------------------------------------------------------===

def can_coerce(src_type, dst_type):
    """
    Check whether we can coerce a value of type `src_type` to a value
    of type `dst_type`
    """
    from flypy.compiler.overloading import best_match

    try:
        best_match(coerce, [src_type, Type[dst_type]])
    except TypeError:
        return False
    else:
        return True


text:
namespace Utility {

	using std::experimental::optional;
	using std::experimental::make_optional;
		}

#endif


text:
define([
        'angular',
        'config',
        'modules/common/adminlte/directives/initAppDirective',
        // 'modules/common/adminlte/directives/chartJSDirective',
        // 'modules/common/adminlte/directives/timelineDirective'

    ],

    function (angular, ApplicationConfiguration, initAppDirective, chartJSDirective, timelineDirective) {

        'use strict';

        var adminLTEModule = ApplicationConfiguration.registerModule('adminLTEModule');

        adminLTEModule.directive('initAdminLteLayout', initAppDirective);
        // adminLTEModule.directive('chartJs', chartJSDirective);
        return adminLTEModule;
    });


text:
#include "Tiano.h"
#include EFI_GUID_DEFINITION(PciOptionRomTable)

EFI_GUID gEfiPciOptionRomTableGuid = EFI_PCI_OPTION_ROM_TABLE_GUID;

EFI_GUID_STRING(&gEfiPciOptionRomTableGuid, "PCI Option ROM Table", "PCI Option ROM Table GUID in EFI System Table");


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

namespace Scale.Logger
{
    /// <summary>
    /// Logger object for writing messages to a log.
    /// </summary>
    public interface ILogger
    {
        /// <summary>
        /// The Key that identifies this instance of Logger.
        /// </summary>
        string Key { get; }

        /// <summary>
        /// Logs a message. message can be a format string with optional args.
        /// </summary>
        void Message(string message, object[] args = null, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "",
            [CallerLineNumber] int lineNumber = 0);

        /// <summary>
        /// Logs an information message. message can be a format string with optional args.
        /// </summary>
        void Info(string message, object[] args = null, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "",
            [CallerLineNumber] int lineNumber = 0);

        /// <summary>
        /// Logs an error message. message can be a format string with optional args.
        /// </summary>
        void Error(string message, object[] args = null, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "",
            [CallerLineNumber] int lineNumber = 0);

        /// <summary>
        /// Logs an Exception stack trace.
        /// </summary>
        void Error(Exception exception, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "",
            [CallerLineNumber] int lineNumber = 0);

        /// <summary>
        /// Logs an error message and Exception stack trace. message can be a format string with optional args.
        /// </summary>
        void Error(Exception exception, string message, object[] args = null, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "",
            [CallerLineNumber] int lineNumber = 0);
    }
}


text:
. ./include.sh

# To get verbose output
#$PYTHON -m unittest -v high_level_api

$PYTHON $examples_src/high_level_api.py

rm -f test.index


text:
homebrew-phabricator
====================


text:
using System;

namespace Xsolla
{
	public class XsollaStatusPing: IParseble
	{
		//rootNode	{{"status":"canceled", "final":"true", "elapsedTime":"394", "group":"troubled", "api":{"ver":"1.0.1"}}}	SimpleJSON.JSONClass
		private String _status;
		private bool _final;
		private int _elapsedTime;
		private XsollaStatus.Group _group;

		public IParseble Parse (SimpleJSON.JSONNode rootNode)
		{
			if (rootNode != null && !"null".Equals(rootNode.ToString()))
			{
				this._status = rootNode["status"];
				this._final = rootNode["final"].AsBool;
				this._elapsedTime = rootNode["elapsedTime"].AsInt;
				switch(rootNode["group"])
				{
				case "invoice":
					{
						this._group = XsollaStatus.Group.INVOICE;
						break;
					}
				case "done":
					{
						this._group = XsollaStatus.Group.DONE;
						break;
					}
				case "delivering":
					{
						this._group = XsollaStatus.Group.DELIVERING;
						break;
					}
				case "troubled":
					{
						this._group = XsollaStatus.Group.TROUBLED;
						break;
					}
				default:
					{
						this._group = XsollaStatus.Group.UNKNOWN;
						break;
					}
				}
			}
			return this;
		}

		public XsollaStatus.Group GetGroup()
		{
			return _group;
		}

		public String GetStatus()
		{
			return _status;
		}

		public bool isFinal()
		{
			return _final;
		}

		public int GetElapsedTiem()
		{
			return _elapsedTime;
		}

		public XsollaStatusPing ()
		{
		}
	}
}


text:
package de.uni.leipzig.sdw.dbpedia.slicing.rdf

import java.io.StringReader

import scala.collection.convert.decorateAll._

import com.hp.hpl.jena.graph.Triple
import org.apache.commons.io.output.ByteArrayOutputStream
import org.apache.flink.api.scala._
import org.apache.flink.core.fs.FileSystem.WriteMode
import org.apache.jena.riot.{RDFLanguages, RDFDataMgr}

/**
  * Created by Markus Ackermann.
  * No rights reserved.
  */
trait NTriplesWindowedIO {

  def readTripleLines(lines: Iterator[String]): Iterator[Triple]

  def serializeTripleLines(triples: Iterator[Triple]): Iterator[String]

  val READ_CHUNK_SIZE = 10000
  val SERIALISATION_CHUNK_SIZE = 10000
}

trait RDFManagerNTriplesIO extends NTriplesWindowedIO with JenaBanana {

  override def readTripleLines(lines: Iterator[String]): Iterator[Triple] = {

    lines.grouped(READ_CHUNK_SIZE) map { tripleLines =>
      val reader = new StringReader(tripleLines.mkString("\n"))
      val graph = ops.makeEmptyMGraph()

      RDFDataMgr.read(graph, reader, "http://synthetic.base/", RDFLanguages.NTRIPLES)

      ops.getTriples(graph)
    } flatten
  }

  override def serializeTripleLines(triples: Iterator[Triple]): Iterator[String] = {
    triples.grouped(SERIALISATION_CHUNK_SIZE) map { tripleChunk =>
      val graph = ops.makeEmptyMGraph()
      tripleChunk foreach (graph.add)
      val outputStream = new ByteArrayOutputStream()
      RDFDataMgr.writeTriples(outputStream, tripleChunk.toIterator.asJava)
      outputStream.toString
    }
  }
}

trait BananaNTriplesIO extends NTriplesWindowedIO with JenaBanana {

  override def readTripleLines(lines: Iterator[String]): Iterator[Triple] = {

    lines.grouped(READ_CHUNK_SIZE) map { tripleLines =>
      val reader = new StringReader(tripleLines.mkString("\n"))

      val graph = ntriplesReader.read(reader, "http://synthetic.base/").get
      ops.getTriples(graph)
    } flatten
  }

  override def serializeTripleLines(triples: Iterator[Triple]): Iterator[String] = {
    triples.grouped(SERIALISATION_CHUNK_SIZE) map { tripleChunk =>
      val graph = ops.makeEmptyMGraph()
      tripleChunk foreach (graph.add)

      val outputStream = new ByteArrayOutputStream()
      ntriplesWriter.write(graph, outputStream, "http://synthetic.base/")
      outputStream.toString
    }
  }
}


text:
module Azure::Support::Mgmt
    VERSION = '0.17.1'
end


text:
FROM golang:1.15-alpine as builder
COPY main.go .
RUN go build -o /app main.go

FROM alpine:3
CMD ["./app"]
COPY --from=builder /app .


text:
package services

import connectors.AccountsConnector
import enums.Registration
import javax.inject.Inject
import models.registration.{OrgRegistration, UserRegistration}
import play.api.mvc.Request

import scala.concurrent.{Future, ExecutionContext => ExC}

class DefaultRegisterService @Inject()(val accountsConnector: AccountsConnector) extends RegisterService

trait RegisterService {
  val accountsConnector: AccountsConnector

  def registerIndividual(user : UserRegistration)(implicit req: Request[_], ec: ExC): Future[Registration.Value] = {
    for {
      userNameInUse <- accountsConnector.checkUserName(user.userName)
      emailInUse    <- accountsConnector.checkEmailAddress(user.email)
      registered    <- if(!userNameInUse & !emailInUse) {
        accountsConnector.createNewIndividualUser(user)
      } else {
        Future.successful(evaluateInUseResponses(userNameInUse, emailInUse))
      }
    } yield registered
  }

  def registerOrg(org: OrgRegistration)(implicit req: Request[_], ec: ExC): Future[Registration.Value] = {
    for {
      userNameInUse <- accountsConnector.checkUserName(org.orgUserName)
      emailInUse    <- accountsConnector.checkEmailAddress(org.orgEmail)
      registered    <- if(!userNameInUse & !emailInUse) {
        accountsConnector.createNewOrgUser(org)
      } else {
        Future.successful(evaluateInUseResponses(userNameInUse, emailInUse))
      }
    } yield registered
  }

  private def evaluateInUseResponses(inUse: (Boolean, Boolean)): Registration.Value = {
    inUse match {
      case (true, true)   => Registration.bothInUse
      case (false, true)  => Registration.emailInUse
      case (true, false)  => Registration.userNameInUse
      case _              => Registration.failed
    }
  }
}


text:
import Model from 'ember-data/model';
import Ember from 'ember';

import attr from 'ember-data/attr';
import { belongsTo } from 'ember-data/relationships';

import DurationCalculations from 'travis/mixins/duration-calculations';
import DurationAttributes from 'travis/mixins/duration-attributes';

export default Model.extend(DurationCalculations, DurationAttributes, {
  build: belongsTo({ async: true }),

  number: attr(),
  name: attr(),

  state: attr(),

  notStarted: Ember.computed('state', function () {
    let state = this.get('state');
    let waitingStates = ['queued', 'created', 'received'];
    return waitingStates.includes(state);
  })
});


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:map="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center"
              android:orientation="vertical"
              android:padding="16dp"
              tools:context="cz.muni.fi.a2p06.stolencardatabase.fragments.CarLocationStepFragment">
    <!-- TODO Landscape layout_weights-->

    <TextView
        android:id="@+id/car_location_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/car_location_hint_text"
        android:textStyle="italic"/>

    <com.google.android.gms.maps.MapView
        android:id="@+id/car_location_mapView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:layout_weight="2"
        map:cameraZoom="17"
        map:liteMode="true"
        map:mapType="normal"
        map:uiMapToolbar="false"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <Button
            android:id="@+id/car_location_set_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/car_location_set_button"/>

        <Button
            android:id="@+id/car_location_delete_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/delete"/>

    </LinearLayout>

</LinearLayout>


text:
/*
This module provides a support for animated SVG to the deck so as to create
animation like in most presentation solution e.g powerpoint, keynote, etc.
Slides can include svg documents which then can be animated using the Animator.
*/

(function($, deck, undefined) {
    var $d = $(document);

    /*
	Extends defaults/options.
	*/
    $.extend(true, $[deck].defaults, {
        classes: {
            placeholder: 'deck-svg',
            control: 'deck-svg-control'
        }
    });

    /*
        jQuery.deck('Init')
        */
    $d.bind('deck.init', function() {
        var opts = $[deck]('getOptions');
        var container = $[deck]('getContainer');

        /* Go through all slides */
        $.each($[deck]('getSlides'), function(i, $el) {
            var $slide = $[deck]('getSlide',i);

            if( $slide.has("object[type='deckjs/asvg']").length>0 ) {
                $slide.data('animators', new Array());
            }

            /* Find all the object of type deckjs/asvg */
            $slide.find("object[type='deckjs/asvg']").each(function(index) {
                var id = $(this)
                /* Load attributes and validate them */
                var attributes = loadObjectParams(this);
                if( !validateParams(attributes) ) {
                    throw "Error while initializing "+$(this).attr('id')+", please ensure you have settup the required parameters."
                    return false;
                }

                /* Add this animator to the list of animators of the current slide. */
                $slide.data('animators').push(attributes['animator']);

                /* Create aSVG placeholder */
                var aSVG = createaSVG(this, attributes);
                $(this).replaceWith(aSVG['placeholder']);

                // Finaly load the SVG data
                aSVG['canvas'].svg({
                    loadURL: attributes['src'],
                    onLoad: function(svg) {
                        // nothing to do here
                    },
                    settings: {
                        // no settings
                    }
                });
            });
        });
    })
    /* Update current slide number with each change event */
    .bind('deck.change', function(e, from, to) {
        var opts = $[deck]('getOptions');
        var $slideTo = $[deck]('getSlide', to);
        var $container = $[deck]('getContainer');

        /* Restart all animator in the slide */
        if( $.isArray($slideTo.data('animators')) ) {
            $.each($slideTo.data('animators'), function(index, animator){
               $(window).attr(animator).restart();
            });
        }
    }).bind('deck.animator.init', function(e, data) {
        $('#deck-svg-next').removeClass("disabled");
    });

    /*
        Load parameters from an Object element
        */
    function loadObjectParams(objectElement) {
        var attributes = {};
        $(objectElement).children("param").each(function(index){
            attributes[$(this).attr("name")] = $(this).attr("value");
        });
        return attributes;
    }

    /*
        Return true if default params are set.
        */
    function validateParams(params) {
        return params['src'] && params['width'] && params['height'] && params['animator'];
    }

    /*
        Create aSVG placeholder
        */
    function createaSVG(object, attributes) {
        var $canvas, $control, $next, $reload, $placeholder;

        /* Create svg canvas */
        $canvas = $("
").attr({
            'id':  $(object).attr('id')
        }).css({
            'height': attributes['height'],
            'width': attributes['width']
        }).click(function(e) {
            var animator = $(window).attr(attributes['animator']);
            if( animator.isCompleted() ) {
                animator.restart();
            } else {
                animator.next();
            }
        });

        /* Create canvas control */

        // next button
        $next = $("").attr({
            'id':'deck-svg-next',
            'class':'deck-svg-button'
        }).click(function(e) {
            var animator = $(window).attr(attributes['animator']);
            animator.next();
            if( animator.isCompleted() ) {
                $(this).addClass("disabled");
            }
        });

        // reload button
        $reload = $("").attr({
            'id':'deck-svg-reload',
            'class':'deck-svg-button'
        }).click(function(e) {
            $(window).attr(attributes['animator']).restart();
            $next.removeClass("disabled");
        });

        // append everything in a control panel
        $control = $("
")
            .addClass($[deck]('getOptions').classes.control)
            .append($reload,$next);

        /* Create placeholder i.e canvas + control */
        $placeholder = $("
").attr({
            'class': $(object).attr('class')
        }).addClass($[deck]('getOptions').classes.placeholder)
          .append($canvas)
          .append($control);

        return {placeholder:$placeholder, canvas:$canvas};
    }
})(jQuery, 'deck');


text:
package net.anotheria.extensions.php.mappers;

import net.anotheria.extensions.php.dto.PHPProducerDTO;
import net.anotheria.extensions.php.exceptions.MappingException;
import net.anotheria.moskito.core.registry.IProducerRegistry;

/**
 * Interface for producer mappers.
 *
 * Final mappers must have default public constructor to be used
 */
public interface Mapper {

    /**
     * Updates producer in given
     * registry with given stats data.
     *
     * Creates and registers new producer if producer with given id not exists.
     *
     * @param producerRegistry registry of producers to update
     * @param producerDTO new producers stats data to be applied
     */
    void mapProducer(IProducerRegistry producerRegistry, PHPProducerDTO producerDTO) throws MappingException;

}


text:
// Generated from /POI/java/org/apache/poi/hssf/record/GutsRecord.java

#pragma once

#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/fwd-POI.hpp>
#include <org/apache/poi/util/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/StandardRecord.hpp>
#include <java/lang/Cloneable.hpp>

struct default_init_tag;

class poi::hssf::record::GutsRecord final
    : public StandardRecord
    , public ::java::lang::Cloneable
{

public:
    typedef StandardRecord super;
    static constexpr int16_t sid { int16_t(128) };

private:
    int16_t field_1_left_row_gutter {  };
    int16_t field_2_top_col_gutter {  };
    int16_t field_3_row_level_max {  };
    int16_t field_4_col_level_max {  };
protected:
    void ctor();
    void ctor(RecordInputStream* in);

public:
    void setLeftRowGutter(int16_t gut);
    void setTopColGutter(int16_t gut);
    void setRowLevelMax(int16_t max);
    void setColLevelMax(int16_t max);
    int16_t getLeftRowGutter();
    int16_t getTopColGutter();
    int16_t getRowLevelMax();
    int16_t getColLevelMax();
    ::java::lang::String* toString() override;
    void serialize(::poi::util::LittleEndianOutput* out) override;

public: /* protected */
    int32_t getDataSize() override;

public:
    int16_t getSid() override;
    GutsRecord* clone() override;

    // Generated
    GutsRecord();
    GutsRecord(RecordInputStream* in);
protected:
    GutsRecord(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();
    int32_t serialize(int32_t offset, ::int8_tArray* data);
    ::int8_tArray* serialize();

private:
    virtual ::java::lang::Class* getClass0();
};