text:
using content::BrowserThread;

ExternalProcessImporterHost::ExternalProcessImporterHost()
    : weak_ptr_factory_(this),
      headless_(false),
      parent_window_(NULL),
      observer_(NULL),
      profile_(NULL),
      waiting_for_bookmarkbar_model_(false),
      installed_bookmark_observer_(false),
      is_source_readable_(true),
      client_(NULL),
      items_(0),
      cancelled_(false),
      import_process_launched_(false) {
}

void ExternalProcessImporterHost::Cancel() {
  cancelled_ = true;
  if (import_process_launched_)
    client_->Cancel();
  NotifyImportEnded();  // Tells the observer that we're done, and deletes us.
}

void ExternalProcessImporterHost::StartImportSettings(
    const importer::SourceProfile& source_profile,
    Profile* target_profile,
    uint16 items,
    ProfileWriter* writer) {
  // We really only support importing from one host at a time.
  DCHECK(!profile_);
  DCHECK(target_profile);

  profile_ = target_profile;
  writer_ = writer;
  source_profile_ = source_profile;
  items_ = items;

  if (!CheckForFirefoxLock(source_profile)) {
    Cancel();
    return;
  }

  CheckForLoadedModels(items);

  LaunchImportIfReady();
}

void ExternalProcessImporterHost::NotifyImportStarted() {
  if (observer_)
    observer_->ImportStarted();
}

void ExternalProcessImporterHost::NotifyImportItemStarted(
    importer::ImportItem item) {
  if (observer_)
    observer_->ImportItemStarted(item);
}

void ExternalProcessImporterHost::NotifyImportItemEnded(
    importer::ImportItem item) {
  if (observer_)
    observer_->ImportItemEnded(item);
}

void ExternalProcessImporterHost::NotifyImportEnded() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  firefox_lock_.reset();
  if (observer_)
    observer_->ImportEnded();
  delete this;
}

ExternalProcessImporterHost::~ExternalProcessImporterHost() {
  if (installed_bookmark_observer_) {
    DCHECK(profile_);
    BookmarkModelFactory::GetForProfile(profile_)->RemoveObserver(this);
  }
}

void ExternalProcessImporterHost::LaunchImportIfReady() {
  if (waiting_for_bookmarkbar_model_ || !registrar_.IsEmpty() ||
      !is_source_readable_ || cancelled_)
    return;

  // This is the in-process half of the bridge, which catches data from the IPC
  // pipe and feeds it to the ProfileWriter. The external process half of the
  // bridge lives in the external process (see ProfileImportThread).
  // The ExternalProcessImporterClient created in the next line owns the bridge,
  // and will delete it.
  InProcessImporterBridge* bridge =
      new InProcessImporterBridge(writer_.get(),
                                  weak_ptr_factory_.GetWeakPtr());
  client_ = new ExternalProcessImporterClient(this, source_profile_, items_,
                                              bridge);
  import_process_launched_ = true;
  client_->Start();
}

void ExternalProcessImporterHost::Loaded(BookmarkModel* model,
                                         bool ids_reassigned) {
  DCHECK(model->loaded());
  model->RemoveObserver(this);
  waiting_for_bookmarkbar_model_ = false;
  installed_bookmark_observer_ = false;

  LaunchImportIfReady();
}

void ExternalProcessImporterHost::BookmarkModelBeingDeleted(
    BookmarkModel* model) {
  installed_bookmark_observer_ = false;
}

void ExternalProcessImporterHost::BookmarkModelChanged() {
}

void ExternalProcessImporterHost::Observe(int type,
                           const content::NotificationSource& source,
                           const content::NotificationDetails& details) {
  DCHECK_EQ(type, chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED);
  registrar_.RemoveAll();
  LaunchImportIfReady();
}

void ExternalProcessImporterHost::ShowWarningDialog() {
  DCHECK(!headless_);
  importer::ShowImportLockDialog(
      parent_window_,
      base::Bind(&ExternalProcessImporterHost::OnImportLockDialogEnd,
                 weak_ptr_factory_.GetWeakPtr()));
}

void ExternalProcessImporterHost::OnImportLockDialogEnd(bool is_continue) {
  if (is_continue) {
    // User chose to continue, then we check the lock again to make
    // sure that Firefox has been closed. Try to import the settings
    // if successful. Otherwise, show a warning dialog.
    firefox_lock_->Lock();
    if (firefox_lock_->HasAcquired()) {
      is_source_readable_ = true;
      LaunchImportIfReady();
    } else {
      ShowWarningDialog();
    }
  } else {
    NotifyImportEnded();
  }
}

bool ExternalProcessImporterHost::CheckForFirefoxLock(
    const importer::SourceProfile& source_profile) {
  if (source_profile.importer_type != importer::TYPE_FIREFOX)
    return true;

  DCHECK(!firefox_lock_.get());
  firefox_lock_.reset(new FirefoxProfileLock(source_profile.source_path));
  if (firefox_lock_->HasAcquired())
    return true;

  // If fail to acquire the lock, we set the source unreadable and
  // show a warning dialog, unless running without UI (in which case the import
  // must be aborted).
  is_source_readable_ = false;
  if (headless_)
    return false;

  ShowWarningDialog();
  return true;
}

void ExternalProcessImporterHost::CheckForLoadedModels(uint16 items) {
  // A target profile must be loaded by StartImportSettings().
  DCHECK(profile_);

  // BookmarkModel should be loaded before adding IE favorites. So we observe
  // the BookmarkModel if needed, and start the task after it has been loaded.
  if ((items & importer::FAVORITES) && !writer_->BookmarkModelIsLoaded()) {
    BookmarkModelFactory::GetForProfile(profile_)->AddObserver(this);
    waiting_for_bookmarkbar_model_ = true;
    installed_bookmark_observer_ = true;
  }

  // Observes the TemplateURLService if needed to import search engines from the
  // other browser. We also check to see if we're importing bookmarks because
  // we can import bookmark keywords from Firefox as search engines.
  if ((items & importer::SEARCH_ENGINES) || (items & importer::FAVORITES)) {
    if (!writer_->TemplateURLServiceIsLoaded()) {
      TemplateURLService* model =
          TemplateURLServiceFactory::GetForProfile(profile_);
      registrar_.Add(this, chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED,
                     content::Source<TemplateURLService>(model));
      model->Load();
    }
  }
}


text:
package edu.duke.cabig.tumorregistry.domain;

import java.util.Date;
import java.lang.Integer;

/**
 * An object representing only the first course of Radiation procedure; including
 * dosages, locations, stop and start dates
 * @version 1.0
 * @created 04-Oct-2006 10:52:16 AM
 */
public class FirstCourseRadiation extends Radiation {

	private Date stopDate;
	private String numberOfTreatments;
	private String location;
	private String volume;
	private Integer regionalDose;
	private Integer boostDose;
	private String boostModality;
	private String regionalModality;

	public FirstCourseRadiation(){

	}

	public void finalize() throws Throwable {
		super.finalize();
	}

	public Integer getBoostDose() {
		return boostDose;
	}

	public void setBoostDose(Integer boostDose) {
		this.boostDose = boostDose;
	}

	public String getBoostModality() {
		return boostModality;
	}

	public void setBoostModality(String boostModality) {
		this.boostModality = boostModality;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getNumberOfTreatments() {
		return numberOfTreatments;
	}

	public void setNumberOfTreatments(String numberOfTreatments) {
		this.numberOfTreatments = numberOfTreatments;
	}

	public Integer getRegionalDose() {
		return regionalDose;
	}

	public void setRegionalDose(Integer regionalDose) {
		this.regionalDose = regionalDose;
	}

	public String getRegionalModality() {
		return regionalModality;
	}

	public void setRegionalModality(String regionalModality) {
		this.regionalModality = regionalModality;
	}

	public Date getStopDate() {
		return stopDate;
	}

	public void setStopDate(Date stopDate) {
		this.stopDate = stopDate;
	}

	public String getVolume() {
		return volume;
	}

	public void setVolume(String volume) {
		this.volume = volume;
	}

}

redpajama_set_name: RedPajamaGithub


text:
Linux-Signal-Handler
====================

Linux Signal Handler in C++


text: Utility for timing web application requests, allowing the submission of a session cookie


text:
"""Tests for the javascript compiler."""

from django.test import TestCase

from optimizations.javascriptcompiler import default_javascript_compiler

class JavascriptCompilerTest(TestCase):

    def testJavascriptCompiler(self):
        self.assertEqual(default_javascript_compiler.compile("function(){var foo = 'foo';}"), b'function(){var a="foo"};')


text:
Adds an AWS::S3::Bucket.LifecycleConfiguration resource property to the template.
Specifies the lifecycle configuration for objects in an Amazon S3 bucket.
For more information, see Object Lifecycle Management: https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html in the *Amazon Simple Storage Service Developer Guide*.

## SYNTAX

```
Add-VSS3BucketLifecycleConfiguration [-Rules] <Object> [<CommonParameters>]
```

## DESCRIPTION
Adds an AWS::S3::Bucket.LifecycleConfiguration resource property to the template.
Specifies the lifecycle configuration for objects in an Amazon S3 bucket.
For more information, see Object Lifecycle Management: https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html in the *Amazon Simple Storage Service Developer Guide*.

## PARAMETERS

### -Rules
A lifecycle rule for individual objects in an Amazon S3 bucket.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig.html#cfn-s3-bucket-lifecycleconfig-rules
DuplicatesAllowed: False
ItemType: Rule
Type: List
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

### Vaporshell.Resource.S3.Bucket.LifecycleConfiguration
## NOTES

## RELATED LINKS

[http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig.html](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig.html)


text:
<?xml version="1.0" encoding="UTF-8"?>
<LearningStandards>
  <LearningStandardItem xml:lang="en" RefID="48506CB1948147B0890BD73B816C81D4">
    <RefURI>http://corestandards.org/Math/Content/8/EE/A/1/</RefURI>
    <StandardHierarchyLevel>
      <number>7</number>
      <description>Standard</description>
    </StandardHierarchyLevel>
    <StatementCodes>
      <StatementCode>CCSS.Math.Content.8.EE.A.1</StatementCode>
    </StatementCodes>
    <Statements>
      <Statement>Know and apply the properties of integer exponents to generate equivalent numerical expressions. For example, 32&nbsp;&times;&nbsp;3&ndash;5 = 3&ndash;3 = 1/33 = 1/27.</Statement>
    </Statements>
    <GradeLevels>
      <GradeLevel>08</GradeLevel>
    </GradeLevels>
    <LearningStandardDocumentRefId>B62C1C106873438AA0126760075A65A3</LearningStandardDocumentRefId>
    <RelatedLearningStandardItems>
      <LearningStandardItemRefId RelationshipType="childOf">42D43D973FEF4A028D2AEAC7151A01DB</LearningStandardItemRefId>
    </RelatedLearningStandardItems>
  </LearningStandardItem>
</LearningStandards>


text:
<?php

namespace Helloworld\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AuthController extends AbstractActionController
{
    private $loginForm;
    private $authService;

    public function loginAction()
    {
        if($this->authService->hasIdentity()) {
            return new ViewModel(array(
                'loginSuccess' => true,
                'userLoggedIn' => $this->authService->getIdentity()
            ));
        }

        if(!$this->loginForm) {
            throw new \BadMethodCallException("Login Form ainda não definido!");
        }

        if(!$this->authService) {
            throw new \BadMethodCallException("Serviço Auth ainda não definido!");
        }

        if($this->getRequest()->isPost()) {
            $this->loginForm->setData($this->getRequest()->getPost());

            if($this->loginForm->isValid()) {
                $data = $this->loginForm->getData();

                $this->authService->getAdapter()->setIdentity($data['username']);
                $this->authService->getAdapter()->setCredential($data['password']);

                $authResult = $this->authService->authenticate();

                if(!$authResult->isValid()) {
                    return new ViewModel(array(
                        'form' => $this->loginForm,
                        'loginError' => true
                    ));
                }else {
                    return new ViewModel(array(
                        'loginSuccess' => true,
                        'userLoggedIn' => $authResult->getIdentity()
                    ));
                }
                var_dump($this->loginForm->getData());exit;
            }else {
                return new ViewModel(array(
                    'form' => $this->loginForm
                ));
            }
        }else {
            return new ViewModel(array(
                'form' => $this->loginForm
            ));
        }
    }

    public function logoutAction()
    {
        if($this->authService->hasIdentity())
            $this->authService->clearIdentity();
        $this->redirect()->toUrl('/login');
    }

    public function setLoginForm($loginForm)
    {
        $this->loginForm = $loginForm;
    }

    public function getLoginForm()
    {
        return $this->loginForm;
    }

    public function setAuthService($authService)
    {
        $this->authService = $authService;
    }

    public function getAuthService()
    {
        return $this->authService;
    }
}


text:
import { Action } from '@ngrx/store';
import { CombatantTypes, EntityStatuses, IEnemy, IPartyMember } from '../base-entity';
import { Item } from '../item';
import { IPartyStatsDiff } from '../mechanics';
import { type } from '../util';
import { CombatAttack, CombatEncounter, CombatType } from './combat.model';

export interface CombatVictorySummary {
  /** The encounter ID */
  id: string;
  /** The type of encounter */
  type: CombatType;
  /** The array of party members that survived the combat encounter */
  party: IPartyMember[];
  /** The list of enemies that were in the encounter */
  enemies: IEnemy[];
  /** Party members that leveled up */
  levels: IPartyStatsDiff[];
  /** Items collected during combat */
  items?: Item[];
  /** Items collected during combat */
  gold: number;
  /** Total experience from the encounter */
  exp: number;
}

//
// Fixed Encounter Actions
//

export class CombatEncounterAction implements Action {
  static typeId: 'COMBAT_ENCOUNTER' = type('COMBAT_ENCOUNTER');
  type = CombatEncounterAction.typeId;

  constructor(public payload: CombatEncounter) {}
}

export class CombatEncounterErrorAction implements Action {
  static typeId: 'COMBAT_ENCOUNTER_ERROR' = type('COMBAT_ENCOUNTER_ERROR');
  type = CombatEncounterErrorAction.typeId;

  constructor(public payload: CombatEncounter) {}
}

export class CombatEncounterReadyAction implements Action {
  static typeId: 'COMBAT_ENCOUNTER_READY' = type('COMBAT_ENCOUNTER_READY');
  readonly type = CombatEncounterReadyAction.typeId;

  constructor(public payload: CombatEncounter) {}
}

//
// Attack Actions
//

export class CombatAttackAction implements Action {
  static typeId: 'COMBAT_ATTACK' = type('COMBAT_ATTACK');
  readonly type = CombatAttackAction.typeId;

  constructor(public payload: CombatAttack) {}
}

export interface ICombatStatusPayload {
  classes: EntityStatuses[];
  target: CombatantTypes;
}

/** Add the given list of statuses to the target */
export class CombatSetStatusAction implements Action {
  static typeId: 'COMBAT_SET_STATUS' = type('COMBAT_SET_STATUS');
  readonly type = CombatSetStatusAction.typeId;

  constructor(public payload: ICombatStatusPayload) {}
}

/** Clear the given list of statuses from the target */
export class CombatClearStatusAction implements Action {
  static typeId: 'COMBAT_CLEAR_STATUS' = type('COMBAT_CLEAR_STATUS');
  readonly type = CombatClearStatusAction.typeId;

  constructor(public payload: ICombatStatusPayload) {}
}

/** Async event that notifies the user of combat victory and updates the game-state party tree. */
export class CombatEscapeAction implements Action {
  static typeId: 'COMBAT_ESCAPE' = type('COMBAT_ESCAPE');
  readonly type = CombatEscapeAction.typeId;
}

/** Dispatched after UI animation side-effects are complete */
export class CombatEscapeCompleteAction implements Action {
  static typeId: 'COMBAT_ESCAPE_DONE' = type('COMBAT_ESCAPE_DONE');
  type = CombatEscapeCompleteAction.typeId;
}

/** Async event that notifies the user of combat victory and updates the game-state party tree. */
export class CombatVictoryAction implements Action {
  static typeId: 'COMBAT_VICTORY' = type('COMBAT_VICTORY');
  readonly type = CombatVictoryAction.typeId;

  constructor(public payload: CombatVictorySummary) {}
}

/** Dispatched after UI animation side-effects are complete */
export class CombatVictoryCompleteAction implements Action {
  static typeId: 'COMBAT_VICTORY_DONE' = type('COMBAT_VICTORY_DONE');
  type = CombatVictoryCompleteAction.typeId;

  constructor(public payload: CombatVictorySummary) {}
}

export type CombatActions =
  | CombatEncounterAction
  | CombatEncounterReadyAction
  | CombatAttackAction
  | CombatSetStatusAction
  | CombatClearStatusAction
  | CombatEscapeAction
  | CombatEscapeCompleteAction
  | CombatVictoryAction
  | CombatVictoryCompleteAction;


text:
AlamofireImage 3.0 is the latest major release of AlamofireImage, an image component library for Alamofire supporting iOS, tvOS, macOS and watchOS written in Swift. As a major release, following Semantic Versioning conventions, 3.0 introduces several API-breaking changes that one should be aware of.

This guide is provided in order to ease the transition of existing applications using AlamofireImage 2.x to the latest APIs, as well as explain the design and structure of new and changed functionality.

## Requirements

- iOS and tvOS 9.0+, macOS 10.11+, watchOS 2.0+
- Xcode 8.0+
- Swift 3.0+

For those of you that would like to use AlamofireImage on iOS 8 or macOS 10.9, please use the latest tagged 2.x release which supports both Swift 2.2 and 2.3.

## Benefits of Upgrading

The benefits of upgrading can be summarized as follows:

- **Alamofire 4 Compatability**
- **Complete Swift 3 Compatibility:** includes the full adoption of the new [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/).
- **New Error System:** uses a new `AFIError` type to adhere to the new pattern proposed in [SE-0112](https://github.com/apple/swift-evolution/blob/master/proposals/0112-nserror-bridging.md).

---

## Breaking API Changes

AlamofireImage 3 has fully adopted the new Swift 3 changes and conventions, including the new [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/). Because of this, almost every API in AlamofireImage has been modified in some way. We can't possibly document every single change, so we're going to attempt to identify the most common APIs and how they have changed to help you through those sometimes less than helpful compiler errors. If you're interested in the underlying Alamofire 4 changes, check out the [migration guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md).

### Requests

```swift
// AlamofireImage 2
Alamofire.request(.GET, "https://httpbin.org/image/png").responseImage { response in
	if let image = response.result.value {
		print("image downloaded: \(image)")
	}
}

// AlamofireImage 3
Alamofire.request("https://httpbin.org/image/png").responseImage { response in
	if let image = response.result.value {
		print("image downloaded: \(image)")
	}
}
```

### UIImage and UIImageView Extensions

The `UIImage` and `UIImageView` extensions have undergone extensive renaming.

#### Loading an Image

```swift
// AlamofireImage 2
imageView.af_setImageWithURL(
	URL,
	placeholderImage: placeholderImage,
	filter: filter
)

// AlamofireImage 3
imageView.af_setImage(
	withURL: url,
	placeholderImage: placeholderImage,
	filter: filter
)
```

#### Loading an Image with Placeholder, Filter and Transition

```swift
// AlamofireImage 2
imageView.af_setImageWithURL(
	URL,
	placeholderImage: placeholderImage,
	filter: filter,
	imageTransition: .CrossDissolve(0.2)
)

// AlamofireImage 3
imageView.af_setImage(
	withURL: url,
	placeholderImage: placeholderImage,
	filter: filter,
	imageTransition: .crossDissolve(0.2)
)
```

### Image Cache

#### Getting an Image

```swift
// AlamofireImage 2
let cachedAvatar = imageCache.imageWithIdentifier("avatar")

// AlamofireImage 3
let cachedAvatar = imageCache.image(withIdentifier: "avatar")
```

#### Adding an Image

```swift
// AlamofireImage 2
imageCache.addImage(avatarImage, withIdentifier: "avatar")

// AlamofireImage 3
imageCache.add(avatarImage, withIdentifier: "avatar")

// With an Additional Identifier

// AlamofireImage 2
imageCache.addImage(avatarImage, forRequest: urlRequest, withAdditionalIdentifier: "circle")

// AlamofireImage 3
imageCache.add(avatarImage, for: urlRequest, withIdentifier: "circle")
```

#### Removing an Image

```swift
// AlamofireImage 2
imageCache.removeImageWithIdentifier("avatar")

// AlamofireImage 3
imageCache.removeImage(withIdentifier: "avatar")

// With an Addtional Identifier

// AlamofireImage 2
imageCache.removeImageForRequest(urlRequest, withAdditionalIdentifier: "circle")

// AlamofireImage 3
imageCache.removeImage(for: urlRequest, withIdentifier: "circle")
```


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRentalRelationship extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('rental_summary_item', function (Blueprint $table) {
            $table->foreign('rental_id')
                  ->references('id')
                  ->on('rental')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');

            $table->foreign('summary_id')
                  ->references('id')
                  ->on('rental_summary')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
        });

        Schema::table('rental_tr', function (Blueprint $table) {
            $table->foreign('rental_id')
                  ->references('id')
                  ->on('rental')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');

        });

        Schema::table('rental_payment', function (Blueprint $table) {
            $table->foreign('rental_id')
                  ->references('id')
                  ->on('rental')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');

        });

        Schema::table('rental_summary', function (Blueprint $table) {
            $table->foreign('rental_id')
                  ->references('id')
                  ->on('rental')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');

        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('rental_summary_item', function (Blueprint $table) {
            $table->dropForeign(['rental_summary_item_rental_id_foreign','rental_summary_item_summary_id_foreign']);
        });
        Schema::table('rental_tr', function (Blueprint $table) {
            $table->dropForeign('rental_tr_rental_id_foreign');
        });
        Schema::table('rental_payment', function (Blueprint $table) {
            $table->dropForeign('rental_payment_rental_id_foreign');
        });
        Schema::table('rental_summary', function (Blueprint $table) {
            $table->dropForeign('rental_summary_rental_id_foreign');
        });
        Schema::table('rental', function (Blueprint $table) {
            $table->dropForeign('rental_book_id_foreign');
        });
    }
}


text:
package com.garethahealy.activemq.client.poc.services;

import com.garethahealy.activemq.client.poc.producers.Producer;

public class MessageService {

    private Producer producer;

    public MessageService(Producer producer) {
        this.producer = producer;
    }

    public boolean sendMessagesToQueue(String firstName, String surname) {
        return producer.produce("hello", new Object[] {firstName, surname});
    }
}


text:
.wpthemeLeft {float: right;}
.wpthemeRight {float: left;}
.wpthemeHeader {text-align: right;}
.wpthemeHeader .wpthemeNavContainer1,
.wpthemeBanner .wpthemeNavContainer1 {float: right;}
.wpthemeHeaderNav ul {padding: 0 5px 0 0;}
.wpthemePrimaryNav li {margin: 0 0 0 1px;}
ul.wpthemeCommonActions > li {float: right;}
.wpthemeBanner ul.wpthemeCommonActions > li > span,
.wpthemeBanner ul.wpthemeCommonActions li a,
.wpthemeBanner ul.wpthemeCommonActions li a:link,
.wpthemeBanner ul.wpthemeCommonActions li a:active {border-left: 1px solid #4b4b4b;border-left: 1px solid rgba(255,255,255,.15);border-right: 0;padding: 0 0 0 10px;}
.wpthemeCommonActions a.wpthemeHelp,
.wpthemeCommonActions a.wpthemeHelp:focus,
.wpthemeCommonActions a.wpthemeHelp:hover,
.wpthemeCommonActions a.wpthemeHelp:active {margin-right: 10px;}
.locale_ar .wpthemeCommonActions .wpthemeHelp img{background-position:0 -864px;}
.locale_ar .wpthemeCommonActions .wpthemeHelp img:hover {background-position:0 -838px;}
.wpthemeSecondaryNav li{margin: 0 0 0 -1px;}
.wpthemeSearch {margin: 14px 5px 14px 20px;}
.wpthemeSearch input.wpthemeSearchButton {	padding: 0 0 2px 2px;}
.wpthemeControl .wpthemeControlHeader h2 {padding: 5px 0 5px 5px;}
.edit-mode .wpthemeControl .wpthemeControlHeader .dndHandle {float: right; margin: 0 0 0 4px;}
.wpthemeCol{margin: 0 20px 0 0;}
.wpthemeRow {margin: 0 0 20px 20px; padding: 0 5px 0 0;}
.wpthemeRow .wpthemeControl ,.hiddenWidgetsDiv .wpthemeControl {float: right; margin: 0 0 0 7.5px;}
.wpthemeRow .component-control { float: right; }
.wpthemeRow .ibmDndHorizontalGhost { margin: 7.5px 0 7.5px 7.5px; }
.wpthemeMainContent .hiddenWidgetsDiv {padding: 0 7.5px 0 0;}
.hiddenWidgetsDiv .hiddenWidgetMessage {margin:0 0 7.5px -7.5px;}
.wptheme_ie7 body {overflow:hidden;}
.wptheme_ie7 .wpthemeControl .wpthemeControlHeader h2 {float:right}
.wptheme_ie7 .wpthemeControlHeader .wpthemeIcon {float:left}
.wpthemeNavList .wpthemeClose,.wpthemeNavList .wpthemeClose:active {margin-right: -10px; margin-left: 20px;}
.wpthemeHeaderNav .wpthemeClose,.wpthemeHeaderNav .wpthemeClose:active {margin-right: -2px;}
.wpthemeHeaderNav .wpthemeSelected .wpthemeClose {background-color:transparent;}
.wpthemePrimaryNav .wpthemeSelected .wpthemeClose,.wpthemePrimaryNav .wpthemeSelected .wpthemeClose:active {margin-right: -17px; margin-left: 0; background: none; border-style: none;}
.wptheme_ie7 .wpthemeCommonActions.wpthemeRight {width: 50%;}
.wptheme_ie7 .wpthemeBanner .wpthemeNavContainer1 {width: 66.5%;}
.wptheme_ie7 .wpthemeHeader .wpthemeNavContainer1 {width: 70%;}
.wptheme_ie7 .wpthemeHeader .wpthemeInner .wpthemeRight {width: 30%;}
.wptheme_ie7 .wpthemeHeader .wpthemeNavContainer1 .wpthemeNavList,
.wptheme_ie7 .wpthemeBanner .wpthemeNavContainer1 .wpthemePrimaryNav {width: 100%;}
.wptheme_ie7 .wpthemeHeaderNav ul li a,
.wptheme_ie7 .wpthemePrimaryNav li a,
.wptheme_ie7 .wpthemeSecondaryNav a {float: none;}
.wptheme_ie7 .wpthemeSecondaryNav a {display: inline;}
.wptheme_ie7 .wpthemeNavList .wpthemeClose {margin: 0px;}
.wpthemeFooterCol {text-align: right;}
.wpthemeCrumbTrail {margin: 6px 20px 0 0;}
.wpthemeCommonActions .wpthemeSearch {margin: 13px 0 12px 20px;}
.wpthemeCommonActions a.wpthemeHelp, .wpthemeCommonActions a.wpthemeHelp:focus, .wpthemeCommonActions a.wpthemeHelp:hover, .wpthemeCommonActions a.wpthemeHelp:active {margin-right: 0px;}
.wpthemeBannerPrimaryNavigation .wpthemeNavContainer1 {float: right;}
.wpthemeOverlay .wpthemeOverlayImg {margin-right:49%;}
.wpthemeLayoutContainers div.ibmDndColumn.ibmDndDropZonesActive .portal-drop-target section {right: -1px;}
.wpthemeLayoutContainers div.ibmDndRow.ibmDndDropZonesActive .portal-drop-target section {right: -15px;}


text:
'use strict';

var _get = require('babel-runtime/helpers/get')['default'];

var _inherits = require('babel-runtime/helpers/inherits')['default'];

var _createClass = require('babel-runtime/helpers/create-class')['default'];

var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _Paper = require('../Paper');

var _Paper2 = _interopRequireDefault(_Paper);

var _PaperHeader = require('../Paper/Header');

var _PaperHeader2 = _interopRequireDefault(_PaperHeader);

var _PaperPeopleList = require('../Paper/PeopleList');

var _PaperPeopleList2 = _interopRequireDefault(_PaperPeopleList);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _stylesScss = require('./styles.scss');

var _stylesScss2 = _interopRequireDefault(_stylesScss);

var ChatBar = (function (_React$Component) {
  _inherits(ChatBar, _React$Component);

  function ChatBar() {
    _classCallCheck(this, ChatBar);

    _get(Object.getPrototypeOf(ChatBar.prototype), 'constructor', this).apply(this, arguments);
  }

  _createClass(ChatBar, [{
    key: 'render',
    value: function render() {
      var className = (0, _classnames2['default'])(_stylesScss2['default'].chatBar, this.props.className);
      var people = [{
        name: 'Sun Moore',
        href: '/people/username'
      }, {
        name: 'Jade Johnson',
        href: '/people/username'
      }, {
        name: 'Monica Düsseldorf',
        href: '/people/username'
      }, {
        name: 'George Anthony',
        href: '/people/username'
      }];

      return _react2['default'].createElement(
        _Paper2['default'],
        { className: className },
        _react2['default'].createElement(
          _PaperHeader2['default'],
          null,
          'CHAT'
        ),
        _react2['default'].createElement(_PaperPeopleList2['default'], { entries: people })
      );
    }
  }], [{
    key: 'propTypes',
    value: {
      className: _react.PropTypes.string
    },
    enumerable: true
  }]);

  return ChatBar;
})(_react2['default'].Component);

exports['default'] = ChatBar;
module.exports = exports['default'];


text:
realpath_Darwin() {
    [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}

realpath_Linux() {
    readlink -f ${1}
}

#call the proper version based on your kernel type
CURRENT_DIR=$(realpath_$(uname) $(dirname ${BASH_SOURCE[0]}) )

BUILD_DIR=$(mktemp -d ${TMPDIR-/tmp}/dig_release.XXXXXXXX)
CLONE_URL="https://github.com/NextCenturyCorporation/dig.git"
BUMP_VER=dev
PUSH_REQUIRED=0
GIT_PUSH_OPTS=""
DRY_RUN=0

backup() {
    #backup some values so we can rollback if necessary
    GIT_CURRENT="$(git rev-parse @)"
}

rollback() {
    echo "** Rolling back because something failed **"
    cd ${CURRENT_DIR}
    echo "Deleting git tag: ${GIT_TAG}"
    git tag -d ${GIT_TAG}
    echo "Rolling back to commit: ${GIT_CURRENT}"
    git reset ${GIT_CURRENT}
    echo "Resetting changes made by npm version"
    git checkout package.json npm-shrinkwrap.json
    echo "Complete!"
}

cleanup() {
    exitval=$1
    if [[ $exitval -gt 0 ]]; then
	echo "Error occured: $exitval"
	rollback
    fi
    exit $exitval
}

ctrl_c() {
    echo "Caught SIGINT/SIGTERM. Cleaning up"
    cleanup 99
}

help() {
    cat <<EOF
Usage
These options push to docker hub and are for release builds.
You can select only one of the options at a time. If you select more than one, only the last one will be honored.
The versions are tagged in git
-M Bump the major version and build
-m Bump the minor version and build
-p Bump the patch version and build
-a Premajor
-i Preminor
-t Prepatch

Passing no parameters performs a development build in which the prerelease version is bumped.
All builds after a pre{major,minor,patch} build has been launched, until the release is finalized (major,minor,patch} should be pre-release builds.
do-release will tag the commit in git with the current version number.

-d will trigger a dry-run in which changes will not be persisted to git or docker-hub

-u force a development build to push the resulting image to docker hub
EOF
cleanup 0
}

get_options() {

    while getopts ":Mmpuc:aitd" opt; do
	case $opt in
	    M)
		BUMP_VER=maj
		;;
	    m)
		BUMP_VER=min
		;;
	    p)
		BUMP_VER=patch
		;;
	    a)
		BUMP_VER=pmajor
		;;
	    i)
		BUMP_VER=pminor
		;;
	    t)
		BUMP_VER=ppatch
		;;
	    u)
		echo "Forcing a push to docker-hub"
		FORCE_PUSH_TO_DOCKER=1
		;;
	    d)
		GIT_PUSH_OPTS="--dry-run"
		DRY_RUN=1
		echo "*************************"
		echo "* PERFORMING A DRY-RUN! *"
		echo "*************************"
		sleep 1s
		;;
	    \?)
		echo "INVALID OPTION: -$OPTARG" >&2
		help
		;;
	    h)
		help
		;;
	    c)
		CONFDIR=$OPTARG
		echo "Using ${CONFDIR} as config dir"
		;;
	esac
    done
}

push_new_version() {
    git remote update origin
    if [[ $(git log HEAD..origin/master --oneline | wc -l) -gt 0 ]]; then
	echo "You need to fetch/merge before using do-release"
	cleanup 6
    fi
    git push ${GIT_PUSH_OPTS} origin master
    git push ${GIT_PUSH_OPTS} origin ${GIT_TAG}

}

sanity_check() {
    #Ensure we are on the master branch
    if [[ "$(git rev-parse --abbrev-ref HEAD)" != "master" ]]; then
	echo "You must be on the master branch to create a release"
	cleanup 3
    fi

    #Ehsure the working directory is clean
    if [[ ! -z "$(git status --porcelain --untracked-files=no)" ]]; then
	echo "Working directory is not clean!"
	echo "Please commit or stash your code before running do-release"
	cleanup 1
    fi

    #Ensure that we are using npm v2 or greater
    if [[ -z "$(npm -v | sed -n '/^2/p')" ]]; then
	echo "You have a version of npm that is too old!"
	cleanup 4
    fi

    #Ensure we have makeself available
    command -v makeself >/dev/null 2>&1 || {
	echo "You do not have makeself installed. Cannot continue."
	cleanup 10
    }

    if [[ -z "${CONFDIR}" ]]; then
	echo "You did not set the config directory with -c"
	cleanup 20
    fi

}

version() {
    GIT_TAG=""
    if [[ "$BUMP_VER" == "maj" ]]; then
	GIT_TAG=$(npm version major)
	PUSH_TO_DOCKER=1
    elif [[ "$BUMP_VER" == "min" ]]; then
	GIT_TAG=$(npm version minor)
	PUSH_TO_DOCKER=1
    elif [[ "$BUMP_VER" == "patch" ]]; then
	PUSH_TO_DOCKER=1
	GIT_TAG=$(npm version patch)
    elif [[ "$BUMP_VER" == "pmajor" ]]; then
	PUSH_TO_DOCKER=0
	GIT_TAG=$(npm version premajor)
    elif [[ "$BUMP_VER" == "pminor" ]]; then
	PUSH_TO_DOCKER=0
	GIT_TAG=$(npm version preminor)
    elif [[ "$BUMP_VER" == "ppatch" ]]; then
	PUSH_TO_DOCKER=0
	GIT_TAG=$(npm version prepatch)
    else
	PUSH_TO_DOCKER=0
	GIT_TAG=$(npm version prerelease)
    fi

    if [[ "$?" != 0 ]]; then
	echo "Stale tag exists that needs to be removed"
        cleanup 30
    fi

    if [[ "$FORCE_PUSH_TO_DOCKER" -eq 1 ]]; then
	PUSH_TO_DOCKER=1
    fi

    if [[ "$DRY_RUN" -eq 1 ]]; then
	PUSH_TO_DOCKER=0
    fi

    if [[ $? != 0 ]]; then
	echo "There was an error with npm version, cannot continue"
	rollback
	cleanup 2
    fi
}

build() {
    if [[ "$PUSH_TO_DOCKER" -eq 1 ]]; then
	package_opts="-d"
    fi
    cd ${BUILD_DIR}
    git clone ${CURRENT_DIR} dig
    cd dig
    cp -r ${CONFDIR} conf
    npm install
    grunt build
    ${BUILD_DIR}/dig/scripts/package.sh $package_opts
    cp dig_deploy.sh ${CURRENT_DIR}
    cd ${CURRENT_DIR}
    if [[ $UID != 0 ]]; then
	echo "Deleting temporary build directory"
	rm -rf ${BUILD_DIR}
    fi
}

trap ctrl_c SIGINT
trap ctrl_c SIGTERM

backup
get_options $@
sanity_check
version
build
if [[ "$DRY_RUN" -eq 1 ]]; then
    echo -e "DRY RUN COMPLETE\nNot pushing changes"
    rollback
else
    push_new_version
fi


text:
originaltileset = gettileset() -- get base tileset of the map
originaltilecount = tilecount()
originalcliffcount = cliffcount()
usedcliffs = {} -- empty table
unusedcliffs = {}
noncliffs = {}

-- this is just to show off the available functions
for i = tilecount() - 1, 0, -1 do
  tile = get(i) -- get tile with index i from the tile list
  if iscliff(tile) and (gettileset(tile) == originaltileset) and isusedascliff(tile) then
    table.insert(usedcliffs, tile)
  end
  if iscliff(tile) and not isusedascliff(tile) then
    table.insert(unusedcliffs, tile)
  end
  if isnoncliff(tile) then
    table.insert(noncliffs, tile)
  end
  if not iscliff(tile) and not isused(tile) and (gettileset(tile) == originaltileset) then
    remove(i) -- we can remove by index or by tileid
  end
end

log("Left should be Ldrt, Ldrg, Lgrs, Lrok, cCc1")
for i = 0, tilecount() - 1 do
  log(get(i))
end

log("Should contain Ldrt")
for i = 1, table.getn(usedcliffs) do
  log(usedcliffs[i])
end

log("Should contain Lgrs")
for i = 1, table.getn(unusedcliffs) do
  log(unusedcliffs[i])
end

log("Should contain cCc1")
for i = 1, table.getn(noncliffs) do
  log(noncliffs[i])
end

settileset("C") -- changing to felwood
replace(0, getcliffversion("cCc1")) -- we can also replace by index
replace("cCc1", getnoncliffversion("Ldrt"))
replace("Lgrs", "cWc1")
replace("Lrok", "Crck")
add("Cvin") -- max is 16 tiles


text:
from numpy import log

def compute_entropy(array_1d):

    probability = array_1d / array_1d.sum()

    return -(probability * log(probability)).sum()


text:
package tikv

import (
	"bytes"
	"context"
	"math"

	"github.com/pingcap/errors"
	"github.com/pingcap/failpoint"
	"github.com/pingcap/kvproto/pkg/kvrpcpb"
	"github.com/pingcap/kvproto/pkg/metapb"
	"github.com/pingcap/kvproto/pkg/pdpb"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/store/tikv/tikvrpc"
	"github.com/pingcap/tidb/util"
	"github.com/pingcap/tidb/util/logutil"
	"github.com/pingcap/tidb/util/stringutil"
	"go.uber.org/zap"
)

func equalRegionStartKey(key, regionStartKey []byte) bool {
	return bytes.Equal(key, regionStartKey)
}

func (s *tikvStore) splitBatchRegionsReq(bo *Backoffer, keys [][]byte, scatter bool) (*tikvrpc.Response, error) {
	// equalRegionStartKey is used to filter split keys.
	// If the split key is equal to the start key of the region, then the key has been split, we need to skip the split key.
	groups, _, err := s.regionCache.GroupKeysByRegion(bo, keys, equalRegionStartKey)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var batches []batch
	for regionID, groupKeys := range groups {
		batches = appendKeyBatches(batches, regionID, groupKeys, rawBatchPutSize)
	}

	if len(batches) == 0 {
		return nil, nil
	}
	// The first time it enters this function.
	if bo.totalSleep == 0 {
		logutil.BgLogger().Info("split batch regions request",
			zap.Int("split key count", len(keys)),
			zap.Int("batch count", len(batches)),
			zap.Uint64("first batch, region ID", batches[0].regionID.id),
			zap.Stringer("first split key", kv.Key(batches[0].keys[0])))
	}
	if len(batches) == 1 {
		resp := s.batchSendSingleRegion(bo, batches[0], scatter)
		return resp.resp, errors.Trace(resp.err)
	}
	ch := make(chan singleBatchResp, len(batches))
	for _, batch1 := range batches {
		go func(b batch) {
			backoffer, cancel := bo.Fork()
			defer cancel()

			util.WithRecovery(func() {
				select {
				case ch <- s.batchSendSingleRegion(backoffer, b, scatter):
				case <-bo.ctx.Done():
					ch <- singleBatchResp{err: bo.ctx.Err()}
				}
			}, func(r interface{}) {
				if r != nil {
					ch <- singleBatchResp{err: errors.Errorf("%v", r)}
				}
			})
		}(batch1)
	}

	srResp := &kvrpcpb.SplitRegionResponse{Regions: make([]*metapb.Region, 0, len(keys)*2)}
	for i := 0; i < len(batches); i++ {
		batchResp := <-ch
		if batchResp.err != nil {
			logutil.BgLogger().Info("batch split regions failed", zap.Error(batchResp.err))
			if err == nil {
				err = batchResp.err
			}
		}

		// If the split succeeds and the scatter fails, we also need to add the region IDs.
		if batchResp.resp != nil {
			spResp := batchResp.resp.Resp.(*kvrpcpb.SplitRegionResponse)
			regions := spResp.GetRegions()
			srResp.Regions = append(srResp.Regions, regions...)
		}
	}
	return &tikvrpc.Response{Resp: srResp}, errors.Trace(err)
}

func (s *tikvStore) batchSendSingleRegion(bo *Backoffer, batch batch, scatter bool) singleBatchResp {
	failpoint.Inject("MockSplitRegionTimeout", func(val failpoint.Value) {
		if val.(bool) {
			if _, ok := bo.ctx.Deadline(); ok {
				<-bo.ctx.Done()
			}
		}
	})

	req := tikvrpc.NewRequest(tikvrpc.CmdSplitRegion, &kvrpcpb.SplitRegionRequest{
		SplitKeys: batch.keys,
	}, kvrpcpb.Context{
		Priority: kvrpcpb.CommandPri_Normal,
	})

	sender := NewRegionRequestSender(s.regionCache, s.client)
	resp, err := sender.SendReq(bo, req, batch.regionID, readTimeoutShort)

	batchResp := singleBatchResp{resp: resp}
	if err != nil {
		batchResp.err = errors.Trace(err)
		return batchResp
	}
	regionErr, err := resp.GetRegionError()
	if err != nil {
		batchResp.err = errors.Trace(err)
		return batchResp
	}
	if regionErr != nil {
		err := bo.Backoff(BoRegionMiss, errors.New(regionErr.String()))
		if err != nil {
			batchResp.err = errors.Trace(err)
			return batchResp
		}
		resp, err = s.splitBatchRegionsReq(bo, batch.keys, scatter)
		batchResp.resp = resp
		batchResp.err = err
		return batchResp
	}

	spResp := resp.Resp.(*kvrpcpb.SplitRegionResponse)
	regions := spResp.GetRegions()
	if len(regions) > 0 {
		// Divide a region into n, one of them may not need to be scattered,
		// so n-1 needs to be scattered to other stores.
		spResp.Regions = regions[:len(regions)-1]
	}
	logutil.BgLogger().Info("batch split regions complete",
		zap.Uint64("batch region ID", batch.regionID.id),
		zap.Stringer("first at", kv.Key(batch.keys[0])),
		zap.Stringer("first new region left", stringutil.MemoizeStr(func() string {
			if len(spResp.Regions) == 0 {
				return ""
			}
			return logutil.Hex(spResp.Regions[0]).String()
		})),
		zap.Int("new region count", len(spResp.Regions)))

	if !scatter {
		if len(spResp.Regions) == 0 {
			return batchResp
		}
		return batchResp
	}

	for i, r := range spResp.Regions {
		if err = s.scatterRegion(r.Id); err == nil {
			logutil.BgLogger().Info("batch split regions, scatter region complete",
				zap.Uint64("batch region ID", batch.regionID.id),
				zap.Stringer("at", kv.Key(batch.keys[i])),
				zap.Stringer("new region left", logutil.Hex(r)))
			continue
		}

		logutil.BgLogger().Info("batch split regions, scatter region failed",
			zap.Uint64("batch region ID", batch.regionID.id),
			zap.Stringer("at", kv.Key(batch.keys[i])),
			zap.Stringer("new region left", logutil.Hex(r)),
			zap.Error(err))
		if batchResp.err == nil {
			batchResp.err = err
		}
		if ErrPDServerTimeout.Equal(err) {
			break
		}
	}
	return batchResp
}

// SplitRegions splits regions by splitKeys.
func (s *tikvStore) SplitRegions(ctx context.Context, splitKeys [][]byte, scatter bool) (regionIDs []uint64, err error) {
	bo := NewBackoffer(ctx, int(math.Min(float64(len(splitKeys))*splitRegionBackoff, maxSplitRegionsBackoff)))
	resp, err := s.splitBatchRegionsReq(bo, splitKeys, scatter)
	regionIDs = make([]uint64, 0, len(splitKeys))
	if resp != nil && resp.Resp != nil {
		spResp := resp.Resp.(*kvrpcpb.SplitRegionResponse)
		for _, r := range spResp.Regions {
			regionIDs = append(regionIDs, r.Id)
		}
		logutil.BgLogger().Info("split regions complete", zap.Int("region count", len(regionIDs)), zap.Uint64s("region IDs", regionIDs))
	}
	return regionIDs, errors.Trace(err)
}

func (s *tikvStore) scatterRegion(regionID uint64) error {
	failpoint.Inject("MockScatterRegionTimeout", func(val failpoint.Value) {
		if val.(bool) {
			failpoint.Return(ErrPDServerTimeout)
		}
	})

	logutil.BgLogger().Info("start scatter region",
		zap.Uint64("regionID", regionID))
	bo := NewBackoffer(context.Background(), scatterRegionBackoff)
	for {
		err := s.pdClient.ScatterRegion(context.Background(), regionID)
		if err == nil {
			break
		}
		err = bo.Backoff(BoPDRPC, errors.New(err.Error()))
		if err != nil {
			return errors.Trace(err)
		}
	}
	logutil.BgLogger().Debug("scatter region complete",
		zap.Uint64("regionID", regionID))
	return nil
}

// WaitScatterRegionFinish implements SplittableStore interface.
// backOff is the back off time of the wait scatter region.(Milliseconds)
// if backOff <= 0, the default wait scatter back off time will be used.
func (s *tikvStore) WaitScatterRegionFinish(regionID uint64, backOff int) error {
	if backOff <= 0 {
		backOff = waitScatterRegionFinishBackoff
	}
	logutil.BgLogger().Info("wait scatter region",
		zap.Uint64("regionID", regionID), zap.Int("backoff(ms)", backOff))

	bo := NewBackoffer(context.Background(), backOff)
	logFreq := 0
	for {
		resp, err := s.pdClient.GetOperator(context.Background(), regionID)
		if err == nil && resp != nil {
			if !bytes.Equal(resp.Desc, []byte("scatter-region")) || resp.Status != pdpb.OperatorStatus_RUNNING {
				logutil.BgLogger().Info("wait scatter region finished",
					zap.Uint64("regionID", regionID))
				return nil
			}
			if logFreq%10 == 0 {
				logutil.BgLogger().Info("wait scatter region",
					zap.Uint64("regionID", regionID),
					zap.String("reverse", string(resp.Desc)),
					zap.String("status", pdpb.OperatorStatus_name[int32(resp.Status)]))
			}
			logFreq++
		}
		if err != nil {
			err = bo.Backoff(BoRegionMiss, errors.New(err.Error()))
		} else {
			err = bo.Backoff(BoRegionMiss, errors.New("wait scatter region timeout"))
		}
		if err != nil {
			return errors.Trace(err)
		}
	}
}

// CheckRegionInScattering uses to check whether scatter region finished.
func (s *tikvStore) CheckRegionInScattering(regionID uint64) (bool, error) {
	bo := NewBackoffer(context.Background(), locateRegionMaxBackoff)
	for {
		resp, err := s.pdClient.GetOperator(context.Background(), regionID)
		if err == nil && resp != nil {
			if !bytes.Equal(resp.Desc, []byte("scatter-region")) || resp.Status != pdpb.OperatorStatus_RUNNING {
				return false, nil
			}
		}
		if err != nil {
			err = bo.Backoff(BoRegionMiss, errors.New(err.Error()))
		} else {
			return true, nil
		}
		if err != nil {
			return true, errors.Trace(err)
		}
	}
}


text:
package tech.aroma.notification.service.server;

import java.net.SocketException;

import com.google.inject.Guice;
import com.google.inject.Injector;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.aroma.notification.service.ModuleNotificationService;
import tech.aroma.notification.service.operations.ModuleNotificationOperations;
import tech.aroma.thrift.notification.service.NotificationService;
import tech.aroma.thrift.notification.service.NotificationServiceConstants;
import tech.sirwellington.alchemy.annotations.access.Internal;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * This Main Class runs the Notification Service on a Server Socket.
 *
 * @author SirWellington
 */
@Internal
public final class TcpServer
{

    private final static Logger LOG = LoggerFactory.getLogger(TcpServer.class);
    private static final int PORT = NotificationServiceConstants.SERVICE_PORT;

    public static void main(String[] args) throws TTransportException, SocketException
    {
        Injector injector = Guice.createInjector(new ModuleNotificationService(),
                                                 new ModuleNotificationOperations());

        NotificationService.Iface bananaService = injector.getInstance(NotificationService.Iface.class);
        NotificationService.Processor processor = new NotificationService.Processor<>(bananaService);

        TServerSocket socket = new TServerSocket(PORT);
        socket.getServerSocket().setSoTimeout((int) SECONDS.toMillis(60));

        TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(socket)
                .protocolFactory(new TBinaryProtocol.Factory())
                .processor(processor)
                .requestTimeout(60)
                .requestTimeoutUnit(SECONDS)
                .minWorkerThreads(5)
                .maxWorkerThreads(100);

        LOG.info("Starting Notification Service at port {}", PORT);

        TThreadPoolServer server = new TThreadPoolServer(serverArgs);
        server.serve();
        server.stop();
    }
}


text:
package com.socialize.google.gson.stream;

import com.socialize.google.gson.internal.JsonReaderInternalAccess;
import com.socialize.google.gson.internal.bind.JsonTreeReader;

import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;

/**
 * Reads a JSON (RFC 4627)
 * encoded value as a stream of tokens. This stream includes both literal
 * values (strings, numbers, booleans, and nulls) as well as the begin and
 * end delimiters of objects and arrays. The tokens are traversed in
 * depth-first order, the same order that they appear in the JSON document.
 * Within JSON objects, name/value pairs are represented by a single token.
 *
 *
Parsing JSON

 * To create a recursive descent parser for your own JSON streams, first create
 * an entry point method that creates a {@code JsonReader}.
 *
 *
Next, create handler methods for each structure in your JSON text. You'll
 * need a method for each object type and for each array type.
 *

 *
Within array handling methods, first call {@link
 *       #beginArray} to consume the array's opening bracket. Then create a
 *       while loop that accumulates values, terminating when {@link #hasNext}
 *       is false. Finally, read the array's closing bracket by calling {@link
 *       #endArray}.
 *
Within object handling methods, first call {@link
 *       #beginObject} to consume the object's opening brace. Then create a
 *       while loop that assigns values to local variables based on their name.
 *       This loop should terminate when {@link #hasNext} is false. Finally,
 *       read the object's closing brace by calling {@link #endObject}.
 *

 *
When a nested object or array is encountered, delegate to the
 * corresponding handler method.
 *
 *
When an unknown name is encountered, strict parsers should fail with an
 * exception. Lenient parsers should call {@link #skipValue()} to recursively
 * skip the value's nested tokens, which may otherwise conflict.
 *
 *
If a value may be null, you should first check using {@link #peek()}.
 * Null literals can be consumed using either {@link #nextNull()} or {@link
 * #skipValue()}.
 *
 *
Example

 * Suppose we'd like to parse a stream of messages such as the following:
 {@code
 * [
 *   {
 *     "id": 912345678901,
 *     "text": "How do I read a JSON stream in Java?",
 *     "geo": null,
 *     "user": {
 *       "name": "json_newb",
 *       "followers_count": 41
 *      }
 *   },
 *   {
 *     "id": 912345678902,
 *     "text": "@json_newb just use JsonReader!",
 *     "geo": [50.454722, -104.606667],
 *     "user": {
 *       "name": "jesse",
 *       "followers_count": 2
 *     }
 *   }
 * ]}

 * This code implements the parser for the above structure:
   {@code
 *
 *   public List<Message> readJsonStream(InputStream in) throws IOException {
 *     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
 *     try {
 *       return readMessagesArray(reader);
 *     } finally {
 *       reader.close();
 *     }
 *   }
 *
 *   public List<Message> readMessagesArray(JsonReader reader) throws IOException {
 *     List<Message> messages = new ArrayList<Message>();
 *
 *     reader.beginArray();
 *     while (reader.hasNext()) {
 *       messages.add(readMessage(reader));
 *     }
 *     reader.endArray();
 *     return messages;
 *   }
 *
 *   public Message readMessage(JsonReader reader) throws IOException {
 *     long id = -1;
 *     String text = null;
 *     User user = null;
 *     List<Double> geo = null;
 *
 *     reader.beginObject();
 *     while (reader.hasNext()) {
 *       String name = reader.nextName();
 *       if (name.equals("id")) {
 *         id = reader.nextLong();
 *       } else if (name.equals("text")) {
 *         text = reader.nextString();
 *       } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
 *         geo = readDoublesArray(reader);
 *       } else if (name.equals("user")) {
 *         user = readUser(reader);
 *       } else {
 *         reader.skipValue();
 *       }
 *     }
 *     reader.endObject();
 *     return new Message(id, text, user, geo);
 *   }
 *
 *   public List<Double> readDoublesArray(JsonReader reader) throws IOException {
 *     List<Double> doubles = new ArrayList<Double>();
 *
 *     reader.beginArray();
 *     while (reader.hasNext()) {
 *       doubles.add(reader.nextDouble());
 *     }
 *     reader.endArray();
 *     return doubles;
 *   }
 *
 *   public User readUser(JsonReader reader) throws IOException {
 *     String username = null;
 *     int followersCount = -1;
 *
 *     reader.beginObject();
 *     while (reader.hasNext()) {
 *       String name = reader.nextName();
 *       if (name.equals("name")) {
 *         username = reader.nextString();
 *       } else if (name.equals("followers_count")) {
 *         followersCount = reader.nextInt();
 *       } else {
 *         reader.skipValue();
 *       }
 *     }
 *     reader.endObject();
 *     return new User(username, followersCount);
 *   }}

 *
 *
Number Handling

 * This reader permits numeric values to be read as strings and string values to
 * be read as numbers. For example, both elements of the JSON array {@code
 * [1, "1"]} may be read using either {@link #nextInt} or {@link #nextString}.
 * This behavior is intended to prevent lossy numeric conversions: double is
 * JavaScript's only numeric type and very large values like {@code
 * 9007199254740993} cannot be represented exactly on that platform. To minimize
 * precision loss, extremely large values should be written and read as strings
 * in JSON.
 *
 *
Non-Execute Prefix

 * Web servers that serve private data using JSON may be vulnerable to Cross-site
 * request forgery attacks. In such an attack, a malicious site gains access
 * to a private JSON file by executing it with an HTML {@code


text:
package com.sdl.ecommerce.api;

/**
 * Query Filter Attribute.
 * Used for include/exclude information in E-Commerce queries.
 *
 * @author nic
 */
public class QueryFilterAttribute {

    public enum FilterMode {
        INCLUDE,
        EXCLUDE
    }

    private String name;
    private String value;
    private FilterMode mode;

    public QueryFilterAttribute(String name, String value) {
        this(name, value, FilterMode.INCLUDE);
    }

    public QueryFilterAttribute(String name, String value, FilterMode mode) {
        this.name = name;
        this.value = value;
        this.mode = mode;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public FilterMode getMode() {
        return mode;
    }

}


text:
package org.compass.core.test.transaction.type.jta;

/**
 * @author kimchy
 */
public class JTASyncJustCloseTransactionTests extends AbstractJustCloseJTATests {

    protected String getCompassConfig() {
        return "/org/compass/core/test/transaction/type/jta/compass.jtasync.cfg.xml";
    }
}


text:
/* 	$OpenBSD: tests.c,v 1.7 2021/05/21 03:48:07 djm Exp $ */
/*
 * Regress test for misc helper functions.
 *
 * Placed in the public domain.
 */

#include "includes.h"

#include <sys/types.h>
#include <sys/param.h>
#include <stdio.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdlib.h>
#include <string.h>

#include "../test_helper/test_helper.h"

#include "log.h"
#include "misc.h"

void test_parse(void);
void test_convtime(void);
void test_expand(void);
void test_argv(void);
void test_strdelim(void);

void
tests(void)
{
	test_parse();
	test_convtime();
	test_expand();
	test_argv();
	test_strdelim();
}


text:
class AdminNoCaching(object):
    """
    Middleware to ensure the admin is not cached by Fastly or other caches
    """

    def process_response(self, request, response):
        if request.path.startswith('/admin'):
            response['Cache-Control'] = 'private'
        return response


text:
var Tag = require('./tag');
var tag = Tag.tag,
	tag_end = Tag.tag_end;

var formTag = function(url, htmlOptions){
	htmlOptions = htmlOptions || {};
	htmlOptions.method = htmlOptions.method || "POST";

	if(htmlOptions.multipart){
		htmlOptions.enctype = "multipart/form-data";
		delete htmlOptions.multipart;
	}

	htmlOptions["accept-charset"] = "UTF-8";

	htmlOptions.action = url;

    return tag('form', htmlOptions);
};

var formEnd = function(){
	return tag_end('form');
};

exports.form_tag = formTag;
exports.form_end = formEnd;


text:
from __future__ import unicode_literals

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

class Migration(migrations.Migration):

    dependencies = [
        ('funding', '0031_plainpayoutaccount'),
    ]

    operations = [
        migrations.CreateModel(
            name='PaymentCurrency',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('code', models.CharField(default=b'EUR', max_length=50)),
                ('min_amount', models.DecimalField(decimal_places=2, default=5.0, max_digits=10)),
                ('max_amount', models.DecimalField(blank=True, decimal_places=2, default=5.0, max_digits=10, null=True)),
                ('default1', models.DecimalField(decimal_places=2, default=10.0, max_digits=10)),
                ('default2', models.DecimalField(decimal_places=2, default=25.0, max_digits=10)),
                ('default3', models.DecimalField(decimal_places=2, default=50.0, max_digits=10)),
                ('default4', models.DecimalField(decimal_places=2, default=100.0, max_digits=10)),
                ('provider', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='funding.PaymentProvider')),
            ],
        ),
    ]


text:
ristorantino-app
================

Ristorantino Base App, for ristorantion vendor aplication


text:
#include "BaseTest.hpp"
#include <boost/test/unit_test.hpp>
#include <KurentoException.hpp>

#include <gst/gst.h>

#include <json/json.h>

#define GST_CAT_DEFAULT _server_json_test_
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "test_server_json_test"

namespace kurento
{

class ClientHandler : public F
{
public:
  ClientHandler() : F()
  {
    GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                             GST_DEFAULT_NAME);
  };

  ~ClientHandler () {}

protected:
  void check_system_overload ();

  void runTests ()
  {
    setResourceLimit (0.015);
    start ();

    check_system_overload();
  }
};

void
ClientHandler::check_system_overload()
{
  Json::Value request;
  Json::Value response;
  std::string pipeId;
  std::string objId;

  Json::Value params;
  Json::Value constructorParams;
  Json::Value operationParams;

  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "create";

  params["type"] = "MediaPipeline";
  params["sessionId"] = "1234567";

  request["params"] = params;
  request["sessionId"] = "sessionId";

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"]["value"].isString() );

  pipeId = response["result"]["value"].asString();

  int times = 0;

  do {

    params["type"] = "WebRtcEndpoint";
    constructorParams ["mediaPipeline"] = pipeId;
    params["constructorParams"] = constructorParams;
    params["sessionId"] = "1234567";

    request["id"] = getId();
    request["params"] = params;

    response = sendRequest (request);

    times ++;
  } while (!response.isMember ("error") );

  BOOST_CHECK (times > 0);
  BOOST_CHECK (response.isMember ("error") );

  BOOST_CHECK (response["error"]["data"]["type"].asString() ==
               "NOT_ENOUGH_RESOURCES");
}

BOOST_FIXTURE_TEST_SUITE ( server_json_test, ClientHandler)

BOOST_AUTO_TEST_CASE ( resource_limit )
{
  runTests();
}

BOOST_AUTO_TEST_SUITE_END()

} /* kurento */


text:
/* This file is autogenerated, do not edit*/
#include "runos_automoc.dir/moc_Controller_5GPNZUKY4KGIBR.cpp"
#include "runos_automoc.dir/moc_Flow_E5NED2LOZ3L7GP.cpp"
#include "runos_automoc.dir/moc_FlowManager_Q74647O4RP53EO.cpp"
#include "runos_automoc.dir/moc_HostManager_NZ6PN5ZDHNEBHE.cpp"
#include "runos_automoc.dir/moc_LinkDiscovery_R3WHYFI3JCZ35S.cpp"
#include "runos_automoc.dir/moc_Loader_J32DEEZINL773N.cpp"
#include "runos_automoc.dir/moc_OFTransaction_GX6LB3JBTMC7ZV.cpp"
#include "runos_automoc.dir/moc_RestListener_O5HDGQOD2URAGW.cpp"
#include "runos_automoc.dir/moc_RestMultipart_SP5DGCOHIDVXDE.cpp"
#include "runos_automoc.dir/moc_STP_4755PDFI77ILRI.cpp"
#include "runos_automoc.dir/moc_Stats_W3TLGRL2OJTVZA.cpp"
#include "runos_automoc.dir/moc_Switch_J4NPTPLXSR3OF5.cpp"
#include "runos_automoc.dir/moc_Topology_NIA2QZG5DETI7O.cpp"
#include "runos_automoc.dir/moc_WebUIManager_OOAWAVVTL3HJDW.cpp"


text:
AmdtDatabaseAdapter::AmdtDatabaseAdapter() :
    m_pDbAccessor(new AMDTProfilerDAL::AmdtDatabaseAccessor()),
    m_isDbToBeClosed(false),
    m_profileMode(AMDT_PROFILE_MODE_NONE)
{
}

AmdtDatabaseAdapter::~AmdtDatabaseAdapter()
{
    if (m_isDbToBeClosed && (m_pDbAccessor != nullptr))
    {
        // Flush the DB and clean.
        m_pDbAccessor->FlushData();

        // Reset the flag.
        m_isDbToBeClosed = false;
    }

    if (m_pDbAccessor != nullptr)
    {
        delete m_pDbAccessor;
        m_pDbAccessor = nullptr;
    }
}

bool AmdtDatabaseAdapter::CreateDb(const gtString& dbName, AMDTProfileMode profileMode)
{
    bool ret = false;

    if (m_pDbAccessor != nullptr)
    {
        // Create the session DB.
        ret = m_pDbAccessor->CreateProfilingDatabase(dbName, profileMode);

        if (ret)
        {
            // Turn on the flag so that we will know that the DB has to be closed.
            m_isDbToBeClosed = true;
            m_profileMode = profileMode;
        }
    }

    return ret;
}

bool AmdtDatabaseAdapter::OpenDb(const gtString& dbName, AMDTProfileMode profileMode, bool isReadOnly)
{
    m_profileMode = profileMode;
    return m_pDbAccessor->OpenProfilingDatabase(dbName, profileMode, isReadOnly);
}

bool AmdtDatabaseAdapter::MigrateDb(const gtString& dbName)
{
    // This add the new columns and update the version
    return m_pDbAccessor->MigrateProfilingDatabase(dbName);
}

bool AmdtDatabaseAdapter::CloseDb()
{
    return m_pDbAccessor->CloseAllConnections();
}

bool AmdtDatabaseAdapter::FlushDb()
{
    return m_pDbAccessor->FlushData();
}

bool AmdtDatabaseAdapter::FlushDbAsync()
{
    return m_pDbAccessor->FlushDataAsync();
}

bool AmdtDatabaseAdapter::GetDbFileExtension(gtString& extension) const
{
    extension.assign(DB_FILE_EXTENSION);
    return true;
}

bool AmdtDatabaseAdapter::GetDbVersion(int& version)
{
    return m_pDbAccessor->GetDbVersion(version);
}

int AmdtDatabaseAdapter::GetSupportedDbVersion(void)
{
    return AMDT_CURRENT_PROFILE_DB_VERSION;
}

bool AmdtDatabaseAdapter::InsertSessionInfoKeyValue(const gtString& key, gtString& value)
{
    return m_pDbAccessor->InsertSessionInfoKeyValue(key, value);
}

bool AmdtDatabaseAdapter::InsertSessionInfo(const gtVector<std::pair<gtString, gtString>>& sessionInfoKeyValueVec)
{
    return m_pDbAccessor->InsertSessionInfo(sessionInfoKeyValueVec);
}

bool AmdtDatabaseAdapter::InsertSessionInfo(const AMDTProfileSessionInfo& sessionInfo)
{
    bool ret = false;

    if (m_pDbAccessor != nullptr)
    {
        // FIXME: why?.. shouldn't the DAL take care of this
        // Begin a new transaction.
        m_pDbAccessor->FlushData();

        // Insert the other session info.
        ret = InsertSessionConfiguration(sessionInfo);
    }

    // FIXME: why?.. shouldn't the DAL take care of this
    // Commit the transaction.
    m_pDbAccessor->FlushData();

    return ret;
}

bool AmdtDatabaseAdapter::GetSessionInfoValue(const gtString& key, gtString& value)
{
    return m_pDbAccessor->GetSessionInfoValue(key, value);
}

bool AmdtDatabaseAdapter::GetAllSessionInfo(gtVector<std::pair<gtString, gtString>>& sessionInfoKeyValueVec)
{
    return m_pDbAccessor->GetAllSessionInfo(sessionInfoKeyValueVec);
}

bool AmdtDatabaseAdapter::GetSessionInfo(AMDTProfileSessionInfo& sessionInfo)
{
    return GetSessionConfiguration(sessionInfo);
}

bool AmdtDatabaseAdapter::IsTimelineMode()
{
    return ((m_profileMode & AMDT_PROFILE_MODE_TIMELINE) == AMDT_PROFILE_MODE_TIMELINE) ? true : false;
}

bool AmdtDatabaseAdapter::IsAggregateMode()
{
    return ((m_profileMode & AMDT_PROFILE_MODE_AGGREGATION) == AMDT_PROFILE_MODE_AGGREGATION) ? true : false;
}

bool AmdtDatabaseAdapter::InsertSessionConfiguration(const AMDTProfileSessionInfo& sessionInfo)
{
    // Insert the target machine name.
    bool isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_TARGET_MACHINE, sessionInfo.m_targetMachineName);
    GT_ASSERT(isOk);

    // Insert the target application's working dir.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_TARGET_APP_WORKING_DIR, sessionInfo.m_targetAppWorkingDir);
    GT_ASSERT(isOk);

    // Insert the target application's path.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_TARGET_APP_PATH, sessionInfo.m_targetAppPath);
    GT_ASSERT(isOk);

    // Insert the target application's working dir.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_SESSION_DIR, sessionInfo.m_sessionDir);
    GT_ASSERT(isOk);

    // Insert the target application's command line arguments.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_TARGET_APP_CMD_LINE_ARGS, sessionInfo.m_targetAppCmdLineArgs);
    GT_ASSERT(isOk);

    // Insert the target application's environment variables.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_TARGET_APP_ENV_VARS, sessionInfo.m_targetAppEnvVars);
    GT_ASSERT(isOk);

    // Insert the session type.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_SESSION_TYPE, sessionInfo.m_sessionType);
    GT_ASSERT(isOk);

    // Insert the session scope.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_SESSION_SCOPE, sessionInfo.m_sessionScope);
    GT_ASSERT(isOk);

    // Insert the system details.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_SYSTEM_DETAILS, sessionInfo.m_systemDetails);
    GT_ASSERT(isOk);

    // Insert the session start time.
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_SESSION_START_TIME, sessionInfo.m_sessionStartTime);
    GT_ASSERT(isOk);

    // Insert the session end time.
    if (IsTimelineMode() && (!sessionInfo.m_sessionEndTime.isEmpty()))
    {
        isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_SESSION_END_TIME, sessionInfo.m_sessionEndTime);
        GT_ASSERT(isOk);
    }

    if (IsAggregateMode())
    {
        gtString valueStr;

        // TODO: add affinity/css stuff
        m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_SESSION_END_TIME, sessionInfo.m_sessionEndTime);

        m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_CSS_ENABLED, sessionInfo.m_cssEnabled ? AMDT_SESSION_INFO_VALUE_YES : AMDT_SESSION_INFO_VALUE_NO);

        valueStr << sessionInfo.m_unwindDepth;
        m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_CSS_UNWIND_DEPTH, valueStr);

        valueStr.makeEmpty();
        valueStr << sessionInfo.m_unwindScope;
        m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_CSS_UNWIND_SCOPE, valueStr);

        m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_FPO_ENABLED, sessionInfo.m_cssFPOEnabled ? AMDT_SESSION_INFO_VALUE_YES : AMDT_SESSION_INFO_VALUE_NO);

        valueStr.makeEmpty();
        valueStr << sessionInfo.m_cpuFamily;
        m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_CPU_FAMILY, valueStr);

        valueStr.makeEmpty();
        valueStr << sessionInfo.m_cpuModel;
        m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_CPU_MODEL, valueStr);

        valueStr.makeEmpty();
        valueStr << (unsigned long)sessionInfo.m_coreAffinity; // TODO - convert to hex
        m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_CORE_AFFNITY, valueStr);
    }

    // Insert the DB scheme version.
    // This is useless.. rather we should use PRAGMA user_version
    isOk = m_pDbAccessor->InsertSessionInfoKeyValue(AMDT_SESSION_INFO_KEY_DB_SCHEME_VERSION, AMDT_SESSION_INFO_VALUE_DB_SCHEME_VERSION);
    GT_ASSERT(isOk);

    return isOk;
}

bool AmdtDatabaseAdapter::GetSessionConfiguration(AMDTProfileSessionInfo& sessionInfo)
{
    bool isOk = false;

    if (m_pDbAccessor != nullptr)
    {
        // Get the target machine name.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_TARGET_MACHINE), sessionInfo.m_targetMachineName);
        GT_ASSERT(isOk);

        // Get the target application's working dir.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_TARGET_APP_WORKING_DIR), sessionInfo.m_targetAppWorkingDir);
        GT_ASSERT(isOk);

        // Get the target application's path.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_TARGET_APP_PATH), sessionInfo.m_targetAppPath);
        GT_ASSERT(isOk);

        // Get the target application's working dir.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_SESSION_DIR), sessionInfo.m_sessionDir);
        GT_ASSERT(isOk);

        // Get the target application's command line arguments.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_TARGET_APP_CMD_LINE_ARGS), sessionInfo.m_targetAppCmdLineArgs);
        GT_ASSERT(isOk);

        // Get the target application's environment variables.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_TARGET_APP_ENV_VARS), sessionInfo.m_targetAppEnvVars);
        GT_ASSERT(isOk);

        // Get the session type.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_SESSION_TYPE), sessionInfo.m_sessionType);
        GT_ASSERT(isOk);

        // Get the session scope.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_SESSION_SCOPE), sessionInfo.m_sessionScope);
        GT_ASSERT(isOk);

        // Get the system details.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_SYSTEM_DETAILS), sessionInfo.m_systemDetails);
        GT_ASSERT(isOk);

        // Get the session start time.
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_KEY_SESSION_START_TIME), sessionInfo.m_sessionStartTime);
        GT_ASSERT(isOk);
    }

    if (isOk && IsTimelineMode())
    {
        // Calculate the sessionEndTime.
        osTime startTime;
        startTime.setFromDateTimeString(osTime::LOCAL, sessionInfo.m_sessionStartTime, osTime::NAME_SCHEME_FILE);

        // Calculate the session duration.
        SamplingTimeRange sessionTimeRange(0, 0);
        isOk = m_pDbAccessor->GetSamplesTimeRange(sessionTimeRange);

        GT_IF_WITH_ASSERT(isOk)
        {
            unsigned int sessionDurationInSeconds = sessionTimeRange.m_toTime / 1000;
            startTime.addSeconds(sessionDurationInSeconds);
            startTime.dateAsString(sessionInfo.m_sessionEndTime, osTime::NAME_SCHEME_FILE, osTime::LOCAL);
        }
    }

    if (isOk && IsAggregateMode())
    {
        gtString valueStr;

        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_CPU_FAMILY), valueStr);

        if (isOk)
        {
            valueStr.toUnsignedIntNumber(sessionInfo.m_cpuFamily);
        }

        valueStr.makeEmpty();
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_CPU_MODEL), valueStr);

        if (isOk)
        {
            valueStr.toUnsignedIntNumber(sessionInfo.m_cpuModel);
        }

        valueStr.makeEmpty();
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_CORE_AFFNITY), valueStr);

        if (isOk)
        {
            valueStr.toUnsignedInt64Number(sessionInfo.m_coreAffinity);
        }

        valueStr.makeEmpty();
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_CSS_UNWIND_DEPTH), valueStr);

        if (isOk)
        {
            gtUInt32 cssDepth = 0;
            valueStr.toUnsignedIntNumber(cssDepth);
            sessionInfo.m_unwindDepth = static_cast<gtUInt16>(cssDepth);
        }

        valueStr.makeEmpty();
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_CSS_UNWIND_SCOPE), valueStr);

        if (isOk)
        {
            gtUInt32 cssScope = 0;
            valueStr.toUnsignedIntNumber(cssScope);
            sessionInfo.m_unwindScope = static_cast<gtUInt16>(cssScope);
        }

        valueStr.makeEmpty();
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_CSS_ENABLED), valueStr);

        if (isOk)
        {
            sessionInfo.m_cssEnabled = (valueStr.compareNoCase(L"YES") == 0) ? true : false;
        }

        valueStr.makeEmpty();
        isOk = m_pDbAccessor->GetSessionInfoValue(gtString(AMDT_SESSION_INFO_FPO_ENABLED), valueStr);

        if (isOk)
        {
            sessionInfo.m_cssFPOEnabled = (valueStr.compareNoCase(L"YES") == 0) ? true : false;
        }
    }

    return isOk;
}


text:
// Copyright 2017-2020 The Cloudprober Authors.
//
// 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 udp implements a UDP server.  It listens on a
given port and echos whatever it receives.  This is used for the UDP probe.
*/
package udp

import (
	"context"
	"errors"
	"fmt"
	"net"
	"runtime"
	"strings"

	"github.com/cloudprober/cloudprober/logger"
	"github.com/cloudprober/cloudprober/metrics"
	configpb "github.com/cloudprober/cloudprober/servers/udp/proto"
	"golang.org/x/net/ipv6"
)

const (
	// recv socket buffer size - we want to use a large value here, preferably
	// the maximum allowed by the OS. 425984 is the max value in
	// Container-Optimized OS version 9592.90.0.
	readBufSize = 425984

	// Number of messages to batch read.
	batchSize = 16

	// Maximum packet size.
	// TODO(manugarg): We read and echo back only 4098 bytes. We should look at raising this
	// limit or making it configurable. Also of note, ReadFromUDP reads a single UDP datagram
	// (up to the max size of 64K-sizeof(UDPHdr)) and discards the rest.
	maxPacketSize = 4098
)

// Server implements a basic UDP server.
type Server struct {
	c    *configpb.ServerConf
	conn *net.UDPConn
	l    *logger.Logger

	advancedReadWrite bool // Set to true on non-windows systems
	p6                *ipv6.PacketConn
}

// New returns an UDP server.
func New(initCtx context.Context, c *configpb.ServerConf, l *logger.Logger) (*Server, error) {
	conn, err := Listen(&net.UDPAddr{Port: int(c.GetPort())}, l)
	if err != nil {
		return nil, err
	}
	go func() {
		<-initCtx.Done()
		conn.Close()
	}()

	s := &Server{
		c:    c,
		conn: conn,
		l:    l,
	}

	switch runtime.GOOS {
	case "windows":
		// Control messages are not supported.
	default:
		s.advancedReadWrite = true
		// We use an IPv6 connection wrapper to receive both IPv4 and IPv6 packets.
		// ipv6.PacketConn lets us use control messages (non-Windows only) to:
		//  -- receive packet destination IP (FlagDst)
		//  -- set source IP (Src).
		s.p6 = ipv6.NewPacketConn(conn)
		if err := s.p6.SetControlMessage(ipv6.FlagDst, true); err != nil {
			return nil, fmt.Errorf("SetControlMessage(ipv6.FlagDst, true) failed: %v", err)
		}
	}

	return s, nil
}

// Listen opens a UDP socket on the given port. It also attempts to set recv
// buffer to a large value so that we can have many outstanding UDP messages.
// Listen is exported only because it's used by udp probe tests.
func Listen(addr *net.UDPAddr, l *logger.Logger) (*net.UDPConn, error) {
	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		return nil, err
	}
	if err = conn.SetReadBuffer(readBufSize); err != nil {
		// Non-fatal error if we are not able to set read socket buffer.
		l.Errorf("Error setting UDP socket %v read buffer to %d: %s. Continuing...",
			conn.LocalAddr(), readBufSize, err)
	}

	return conn, nil
}

// readWriteErr is used by readAndEcho functions so that we can return both,
// the relevant error message and the original error. Original error is used
// to determine if the underlying transport has been closed.
type readWriteErr struct {
	msg string
	err error
}

func (rwerr *readWriteErr) Error() string {
	if rwerr.err != nil {
		return fmt.Sprintf("%s: %v", rwerr.msg, rwerr.err)
	}
	return rwerr.msg
}

// readAndEchoBatch reads, writes packets in batches. To determine the source
// address for outgoing packets (e.g. if server is behind a load balancer), we
// make use of control messages (configured through messages' OOB).
//
// Note that we don't need to copy or modify the messages below before echoing
// them for the following reasons:
//   - Message struct uses the same field (Addr) for sender (while receiving)
//     and destination address (while sending).
//   - Control message (type: packet-info) field that contains the received
//     packet's destination address, is also the field that's used to set the
//     source address on the outgoing packets.
func (s *Server) readAndEchoBatch(ms []ipv6.Message) *readWriteErr {
	n, err := s.p6.ReadBatch(ms, 0)
	if err != nil {
		return &readWriteErr{"error reading packets", err}
	}
	ms = ms[:n]

	// Resize buffers to match amount read.
	for _, m := range ms {
		// We only allocated a 0th buffer, so all the data is there.
		m.Buffers[0] = m.Buffers[0][:m.N]
	}

	for remaining := len(ms); remaining > 0; {
		n, err := s.p6.WriteBatch(ms, 0)
		if err != nil {
			return &readWriteErr{"error writing packets", err}
		}
		if n == 0 {
			return &readWriteErr{fmt.Sprintf("wrote zero packets, %d remain", remaining), nil}
		}
		remaining -= n
	}

	// Reset buffers to full size for re-use.
	for _, m := range ms {
		b := m.Buffers[0]
		// We only allocated a 0th buffer.
		m.Buffers[0] = b[:cap(b)]
	}

	return nil
}

// readAndEchoSimple reads a packet from the server connection and writes it
// back.
func (s *Server) readAndEchoSimple(buf []byte) *readWriteErr {
	inLen, addr, err := s.conn.ReadFromUDP(buf)
	if err != nil {
		return &readWriteErr{"error reading packet", err}
	}
	if inLen == 0 {
		return &readWriteErr{"read 0 length packet", nil}
	}

	n, err := s.conn.WriteToUDP(buf[:inLen], addr)
	if err != nil {
		return &readWriteErr{"error writing packet", err}
	}

	if n < inLen {
		s.l.Warningf("Reply truncated! Got %d bytes but only sent %d bytes", inLen, n)
	}
	return nil
}

func connClosed(err error) bool {
	// TODO(manugarg): Replace this by errors.Is(err, net.ErrClosed) once Go 1.16
	// is more widely available.
	return strings.Contains(err.Error(), "use of closed network connection")
}

// Start starts the UDP server. It returns only when context is canceled.
func (s *Server) Start(ctx context.Context, dataChan chan<- *metrics.EventMetrics) error {
	var ms []ipv6.Message              // Used for batch read-write
	buf := make([]byte, maxPacketSize) // Used for single packet read-write (windows)

	if s.advancedReadWrite {
		ms = make([]ipv6.Message, batchSize)
		for i := 0; i < batchSize; i++ {
			ms[i].Buffers = [][]byte{make([]byte, maxPacketSize)}
			ms[i].OOB = ipv6.NewControlMessage(ipv6.FlagDst)
		}
	}

	// Setup a background function to close connection if context is canceled.
	// Typically, this is not what we want (close something started outside of
	// Start function), but in case of UDP we don't have better control than
	// this. One thing we can consider is to re-setup connection in Start().
	go func() {
		<-ctx.Done()
		s.conn.Close()
	}()

	switch s.c.GetType() {

	case configpb.ServerConf_ECHO:
		s.l.Infof("Starting UDP ECHO server on port %d", int(s.c.GetPort()))

		var rwerr *readWriteErr
		for {
			if s.advancedReadWrite {
				rwerr = s.readAndEchoBatch(ms)
			} else {
				rwerr = s.readAndEchoSimple(buf)
			}
			if rwerr != nil {
				if errors.Is(rwerr.err, net.ErrClosed) {
					s.l.Warning("connection closed, stopping the start goroutine")
					return nil
				}
				s.l.Error(rwerr.Error())
			}
		}

	case configpb.ServerConf_DISCARD:
		s.l.Infof("Starting UDP DISCARD server on port %d", int(s.c.GetPort()))

		var err error
		for {
			if s.advancedReadWrite {
				_, err = s.p6.ReadBatch(ms, 0)
			} else {
				_, _, err = s.conn.ReadFromUDP(buf)
			}

			if err != nil {
				if errors.Is(err, net.ErrClosed) {
					return nil
				}
				s.l.Errorf("ReadFromUDP: %v", err)
			}
		}
	}

	return nil
}