text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:padding="@dimen/cell_padding"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <CheckBox
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:checked="false"
        android:id="@+id/checkBox"/>
</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
Jenkins PHP Cookbook CHANGELOG
==========================
This file is used to list changes made in each version of the Jenkins PHP Cookbook.

v0.0.2 (2015-15-01)
-------------------
- Add files/build

v0.0.1 (2015-15-01)
-------------------
- Create coobook with Jenkins CI and config PHP Template.


text:
package net.medhatblog.olxclone;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;

public class ViewAdDetails extends AppCompatActivity {

    private TextView title;
    private TextView price;
    private TextView description;
    private TextView name;
    private AppCompatButton delete;
    private LinearLayout layout;

    private DatabaseReference databaseReference;
    private FirebaseUser user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_ad_details);
        if(! Utility.isNetworkAvailable(this)){

            Toast.makeText(this,
                    "Please check internet connection", Toast.LENGTH_SHORT).show();

        }
        Intent intent = getIntent();

        final AdUploadInfo adUploadInfo = (AdUploadInfo) intent.getSerializableExtra("AdDetails");

        user = FirebaseAuth.getInstance().getCurrentUser();

        databaseReference = FirebaseDatabase.getInstance().getReference(adUploadInfo.getUserId()).child(adUploadInfo.getAdId());

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        title = (TextView) findViewById(R.id.title);
        price = (TextView) findViewById(R.id.price);
        description = (TextView) findViewById(R.id.description);
        name = (TextView) findViewById(R.id.name);
        layout = (LinearLayout)findViewById(R.id.layout);

        delete = (AppCompatButton) findViewById(R.id.delete);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        title.setText(adUploadInfo.adTitle);
        price.setText(adUploadInfo.adPrice);
        description.setText(adUploadInfo.adDescription);
        name.setText(adUploadInfo.adName);

        if(user.getUid().equals(adUploadInfo.getUserId())){
          delete.setVisibility(View.VISIBLE);
        }
            else{

            fab.setVisibility(View.VISIBLE);
        }

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent dial = new Intent();
                dial.setAction("android.intent.action.DIAL");
                dial.setData(Uri.parse("tel:"+adUploadInfo.adPhone));
                startActivity(dial);
            }
        });
        databaseReference.child("images").addListenerForSingleValueEvent(new ValueEventListener() {
            int i =0;
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

                View v = layout.getChildAt(i);
                    i=i+1;
                if (v instanceof ImageView) {
                    Picasso.with(getApplicationContext())
                            .load(postSnapshot.getValue().toString())
                            .placeholder(R.drawable.image_processing)
                            .error(R.drawable.no_image)
                            .fit()
                            .centerInside()
                            .into((ImageView) v);
                    v.setVisibility(View.VISIBLE);
                }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(! Utility.isNetworkAvailable(ViewAdDetails.this)){

                    Toast.makeText(ViewAdDetails.this,
                            "Please check internet connection", Toast.LENGTH_SHORT).show();
                    return;
                }
                new AlertDialog.Builder(ViewAdDetails.this)
                        .setTitle(getResources().getString(R.string.delete))
                        .setMessage(getResources().getString(R.string.delete_confirmation))
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                databaseReference.child("images").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

                            StorageReference photoRef = FirebaseStorage.getInstance().getReference().getStorage().getReferenceFromUrl(postSnapshot.getValue().toString());
                            photoRef.delete();

                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

                databaseReference.removeValue();
                                Toast.makeText(getApplicationContext(), "Ad may be take while until being deleted", Toast.LENGTH_LONG).show();
                finish();
            }
        })      .setNegativeButton(android.R.string.no, null).show();
            }});

    }
    public void imageClick(View v){

        String IdAsString = v.getResources().getResourceName(v.getId());
        final String idNumber=IdAsString.substring(IdAsString.length()-1);

        databaseReference.child("images").addListenerForSingleValueEvent(new ValueEventListener() {
            int i =0;
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    i=i+1;
                    if (i== Integer.valueOf(idNumber)){
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse(postSnapshot.getValue().toString()), "image/*");
                        if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                        }
                        break;
                    }

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}


text:
from opendc.models.authorization import Authorization
from opendc.models.model import Model
from opendc.models.user import User
from opendc.util import exceptions

class Path(Model):
    JSON_TO_PYTHON_DICT = {
        'Path': {
            'id': 'id',
            'simulationId': 'simulation_id',
            'name': 'name',
            'datetimeCreated': 'datetime_created'
        }
    }

    TABLE_NAME = 'paths'
    COLUMNS = ['id', 'simulation_id', 'name', 'datetime_created']
    COLUMNS_PRIMARY_KEY = ['id']

    def google_id_has_at_least(self, google_id, authorization_level):
        """Return True if the user has at least the given auth level over this Path."""

        # Get the User id

        try:
            user_id = User.from_google_id(google_id).read().id
        except exceptions.RowNotFoundError:
            return False

        # Check the Authorization

        authorization = Authorization.from_primary_key((user_id, self.simulation_id))

        return authorization.has_at_least(authorization_level)


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "modules/shapedetection/ShapeDetector.h"

#include "core/dom/DOMException.h"
#include "core/dom/DOMRect.h"
#include "core/dom/Document.h"
#include "core/frame/ImageBitmap.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLVideoElement.h"
#include "core/html/ImageData.h"
#include "core/loader/resource/ImageResourceContent.h"
#include "platform/graphics/Image.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "wtf/CheckedNumeric.h"

namespace blink {

namespace {

mojo::ScopedSharedBufferHandle getSharedBufferOnData(
    ScriptPromiseResolver* resolver,
    uint8_t* data,
    int size) {
  DCHECK(data);
  DCHECK(size);
  ScriptPromise promise = resolver->promise();

  mojo::ScopedSharedBufferHandle sharedBufferHandle =
      mojo::SharedBufferHandle::Create(size);
  if (!sharedBufferHandle->is_valid()) {
    resolver->reject(
        DOMException::create(InvalidStateError, "Internal allocation error"));
    return sharedBufferHandle;
  }

  const mojo::ScopedSharedBufferMapping mappedBuffer =
      sharedBufferHandle->Map(size);
  DCHECK(mappedBuffer.get());
  memcpy(mappedBuffer.get(), data, size);

  return sharedBufferHandle;
}

}  // anonymous namespace

ShapeDetector::ShapeDetector(LocalFrame& frame) {
  DCHECK(frame.interfaceProvider());
}

ScriptPromise ShapeDetector::detect(ScriptState* scriptState,
                                    const ImageBitmapSourceUnion& imageSource) {
  ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
  ScriptPromise promise = resolver->promise();

  // ImageDatas cannot be tainted by definition.
  if (imageSource.isImageData())
    return detectShapesOnImageData(resolver, imageSource.getAsImageData());

  CanvasImageSource* canvasImageSource;
  if (imageSource.isHTMLImageElement()) {
    canvasImageSource = imageSource.getAsHTMLImageElement();
  } else if (imageSource.isImageBitmap()) {
    canvasImageSource = imageSource.getAsImageBitmap();
  } else if (imageSource.isHTMLVideoElement()) {
    canvasImageSource = imageSource.getAsHTMLVideoElement();
  } else if (imageSource.isHTMLCanvasElement()) {
    canvasImageSource = imageSource.getAsHTMLCanvasElement();
  } else if (imageSource.isOffscreenCanvas()) {
    canvasImageSource = imageSource.getAsOffscreenCanvas();
  } else {
    NOTREACHED() << "Unsupported CanvasImageSource";
    resolver->reject(
        DOMException::create(NotSupportedError, "Unsupported source."));
    return promise;
  }

  if (canvasImageSource->wouldTaintOrigin(
          scriptState->getExecutionContext()->getSecurityOrigin())) {
    resolver->reject(
        DOMException::create(SecurityError, "Source would taint origin."));
    return promise;
  }

  if (imageSource.isHTMLImageElement()) {
    return detectShapesOnImageElement(resolver,
                                      imageSource.getAsHTMLImageElement());
  }

  // TODO(mcasas): Check if |video| is actually playing a MediaStream by using
  // HTMLMediaElement::isMediaStreamURL(video->currentSrc().getString()); if
  // there is a local WebCam associated, there might be sophisticated ways to
  // detect faces on it. Until then, treat as a normal <video> element.

  const FloatSize size(canvasImageSource->sourceWidth(),
                       canvasImageSource->sourceHeight());

  SourceImageStatus sourceImageStatus = InvalidSourceImageStatus;
  RefPtr<Image> image = canvasImageSource->getSourceImageForCanvas(
      &sourceImageStatus, PreferNoAcceleration, SnapshotReasonDrawImage, size);
  if (!image || sourceImageStatus != NormalSourceImageStatus) {
    resolver->reject(
        DOMException::create(InvalidStateError, "Invalid element or state."));
    return promise;
  }
  if (size.isEmpty()) {
    resolver->resolve(HeapVector<Member<DOMRect>>());
    return promise;
  }

  SkPixmap pixmap;
  RefPtr<Uint8Array> pixelData;
  uint8_t* pixelDataPtr = nullptr;
  WTF::CheckedNumeric<int> allocationSize = 0;

  // TODO(ccameron): ShapeDetector can ignore color conversion.
  sk_sp<SkImage> skImage =
      image->imageForCurrentFrame(ColorBehavior::transformToGlobalTarget());
  // Use |skImage|'s pixels if it has direct access to them.
  if (skImage->peekPixels(&pixmap)) {
    pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr());
    allocationSize = pixmap.getSafeSize();
  } else if (imageSource.isImageBitmap()) {
    ImageBitmap* imageBitmap = imageSource.getAsImageBitmap();
    pixelData = imageBitmap->copyBitmapData(imageBitmap->isPremultiplied()
                                                ? PremultiplyAlpha
                                                : DontPremultiplyAlpha,
                                            N32ColorType);
    pixelDataPtr = pixelData->data();
    allocationSize = imageBitmap->size().area() * 4 /* bytes per pixel */;
  } else {
    // TODO(mcasas): retrieve the pixels from elsewhere.
    NOTREACHED();
    resolver->reject(DOMException::create(
        InvalidStateError, "Failed to get pixels for current frame."));
    return promise;
  }

  mojo::ScopedSharedBufferHandle sharedBufferHandle = getSharedBufferOnData(
      resolver, pixelDataPtr, allocationSize.ValueOrDefault(0));
  if (!sharedBufferHandle->is_valid())
    return promise;

  return doDetect(resolver, std::move(sharedBufferHandle), image->width(),
                  image->height());
}

ScriptPromise ShapeDetector::detectShapesOnImageData(
    ScriptPromiseResolver* resolver,
    ImageData* imageData) {
  ScriptPromise promise = resolver->promise();

  if (imageData->size().isZero()) {
    resolver->resolve(HeapVector<Member<DOMRect>>());
    return promise;
  }

  uint8_t* const data = imageData->data()->data();
  WTF::CheckedNumeric<int> allocationSize = imageData->size().area() * 4;

  mojo::ScopedSharedBufferHandle sharedBufferHandle =
      getSharedBufferOnData(resolver, data, allocationSize.ValueOrDefault(0));
  if (!sharedBufferHandle->is_valid())
    return promise;

  return doDetect(resolver, std::move(sharedBufferHandle), imageData->width(),
                  imageData->height());
}

ScriptPromise ShapeDetector::detectShapesOnImageElement(
    ScriptPromiseResolver* resolver,
    const HTMLImageElement* img) {
  ScriptPromise promise = resolver->promise();

  if (img->bitmapSourceSize().isZero()) {
    resolver->resolve(HeapVector<Member<DOMRect>>());
    return promise;
  }

  ImageResourceContent* const imageResource = img->cachedImage();
  if (!imageResource || imageResource->errorOccurred()) {
    resolver->reject(DOMException::create(
        InvalidStateError, "Failed to load or decode HTMLImageElement."));
    return promise;
  }

  Image* const blinkImage = imageResource->getImage();
  if (!blinkImage) {
    resolver->reject(DOMException::create(
        InvalidStateError, "Failed to get image from resource."));
    return promise;
  }

  // TODO(ccameron): ShapeDetector can ignore color conversion.
  const sk_sp<SkImage> image = blinkImage->imageForCurrentFrame(
      ColorBehavior::transformToGlobalTarget());
  DCHECK_EQ(img->naturalWidth(), static_cast<unsigned>(image->width()));
  DCHECK_EQ(img->naturalHeight(), static_cast<unsigned>(image->height()));

  if (!image) {
    resolver->reject(DOMException::create(
        InvalidStateError, "Failed to get image from current frame."));
    return promise;
  }

  const SkImageInfo skiaInfo =
      SkImageInfo::MakeN32(image->width(), image->height(), image->alphaType());

  const uint32_t allocationSize = skiaInfo.getSafeSize(skiaInfo.minRowBytes());

  mojo::ScopedSharedBufferHandle sharedBufferHandle =
      mojo::SharedBufferHandle::Create(allocationSize);
  if (!sharedBufferHandle.is_valid()) {
    DLOG(ERROR) << "Requested allocation : " << allocationSize
                << "B, larger than |mojo::edk::kMaxSharedBufferSize| == 16MB ";
    // TODO(xianglu): For now we reject the promise if the image is too large.
    // But consider resizing the image to remove restriction on the user side.
    // Also, add LayoutTests for this case later.
    resolver->reject(
        DOMException::create(InvalidStateError, "Image exceeds size limit."));
    return promise;
  }

  const mojo::ScopedSharedBufferMapping mappedBuffer =
      sharedBufferHandle->Map(allocationSize);

  const SkPixmap pixmap(skiaInfo, mappedBuffer.get(), skiaInfo.minRowBytes());
  if (!image->readPixels(pixmap, 0, 0)) {
    resolver->reject(DOMException::create(
        InvalidStateError,
        "Failed to read pixels: Unable to decompress or unsupported format."));
    return promise;
  }

  return doDetect(resolver, std::move(sharedBufferHandle), img->naturalWidth(),
                  img->naturalHeight());
}

}  // namespace blink


text:
(function( $ ) {
        $.fn.jumpAndEqualizeHeight = function(arrayElem, options) {

            options = $.extend({
                directParent: true
            }, options);

        var $wrap = this;

        $(arrayElem).each(function (index, elem){

            var $elem = $wrap.find(elem);
            var maxHeight = 0;

            var widthWrap = $wrap.outerWidth();

            var widthFirstLine = 0;
            var numberElemLine = 0;
            var firstLineElem = 0;
            var lastLineElem = 0;
            var numberLine = 0;

            if(options.directParent) {

                $elem.each(function (index, el) {
                    var $parentsArray = $(el).parentsUntil($wrap);
                    var $lastElement = $($parentsArray[$parentsArray.length - 1]);
                    widthFirstLine += $lastElement.innerWidth();

                    if (widthWrap < widthFirstLine) {
                        numberElemLine = index;

                        return false;
                    }

                });

            } else {
                console.info('TODO: function not yet implemented');
                return false;
            }

            lastLineElem = numberElemLine;
            numberLine = $elem.length / numberElemLine;

            var funAlignLine = function () {

                for (var i = firstLineElem; i < lastLineElem; i++) {
                    var itemHeight = $($elem[i]).height();

                    maxHeight = itemHeight > maxHeight ? itemHeight : maxHeight;
                }

                if ($elem[0].tagName === 'IMG') {
                    //if it's a picture
                    for (var i = firstLineElem; i < lastLineElem; i++) {
                        var itemHeight = $($elem[i]).height();
                        if (itemHeight < maxHeight) {
                            var margin = maxHeight - itemHeight;
                            $($elem[i]).css('margin-bottom', margin);
                        }
                    }

                } else {
                    //if it's something else
                    for (var i = firstLineElem; i < lastLineElem; i++) {

                        $($elem[i]).height(maxHeight);
                    }
                }

                maxHeight = 0;
                firstLineElem += numberElemLine;

                if ((lastLineElem + numberElemLine) < $elem.length) {
                    lastLineElem += numberElemLine;
                } else {
                    lastLineElem = $elem.length;
                }

            };
            $elem.height('');
            for (var i = 0; i < numberLine; i++) {
                funAlignLine();
            }

        });
    }

})(jQuery);


text:
/*
 ============================================================================
 Name         :  Assignmet1.c
 Author        : Luca Zelioli and Minna
 Description :   Program that print out information about the student
 ============================================================================
 */

#ifndef HEADER_H_
#define HEADER_H_

int sumOfEven();
void thirdNum();
void RandTime();
void isTribonacci();

#endif /* HEADER_H_ */


text:
package org.apache.druid.common.utils;

import org.apache.druid.java.util.common.ISE;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ThreadLocalRandom;

/**
 */
public class SocketUtil
{

  public static int findOpenPort(int basePort)
  {
    final int startPort = basePort < 0 ? -1 : ThreadLocalRandom.current().nextInt(0x7fff) + basePort;
    return findOpenPortFrom(startPort);
  }

  public static int findOpenPortFrom(int startPort)
  {
    int currPort = startPort;

    while (currPort < 0xffff) {
      try (ServerSocket socket = new ServerSocket(currPort)) {
        return currPort;
      }
      catch (IOException e) {
        ++currPort;
      }
    }

    throw new ISE("Unable to find open port between [%d] and [%d]", startPort, currPort);
  }
}


text:
download=false
install=false
test=true

data_dir=https://www.cis.uni-muenchen.de/~schmid/tools/TreeTagger/data/

if [ ! -d treetagger ];
then
    mkdir treetagger
fi

cd treetagger

if [ $download = "true" ];
then
    curl -O $data_dir/tree-tagger-MacOSX-3.2.3.tar.gz
    curl -O $data_dir/tagger-scripts.tar.gz
    curl -O $data_dir/install-tagger.sh
    curl -O $data_dir/english.par.gz
fi

if [ $install = "true" ];
then
    sh install-tagger.sh
fi

if [ $test = "true" ];
then
    echo 'Hello world!' | cmd/tree-tagger-english
fi


text:
package info;

/**
 * Created by 袁刚 on 2017/5/31.
 */

public class MeseageUserReport {
//    public String imageUrl;
    public String Username;
    public String time;

    public MeseageUserReport(String username, String time) {
//        this.imageUrl = imageUrl;
        Username = username;
        this.time = time;
    }

//    public MeseageUserReport() {
//    }

//    public String getImageUrl() {
//        return imageUrl;
//    }

    public String getUsername() {
        return Username;
    }

    public String getTime() {
        return time;
    }

//    public void setImageUrl(String imageUrl) {
//        this.imageUrl = imageUrl;
//    }
//
//    public void setUsername(String username) {
//        Username = username;
//    }
//
//    public void setTime(String time) {
//        this.time = time;
//    }
}


text:
module AnswerHelpers
  def answer(key, &fallback)
    found = get(:answers)[key]
    found.nil? ? fallback.call : found
  end

  def load_answers
    set(:answers, extract_answers(self.class.cli_options))
  end

  private

  def extract_answers(options)
    options.except(
      "version-check", :"version-check",
      "force", :force
    ).reduce({}) do |hash, (k, v)|
      hash.merge(k => v == "none" ? nil : v)
    end
  end
end


text:
#ifndef OVR_VrApi_Version_h
#define OVR_VrApi_Version_h

// At some point we will transition to product version 1
// and reset the major version back to 1 (first product release, version 1.0).
#define VRAPI_PRODUCT_VERSION	1
#define VRAPI_MAJOR_VERSION		0
#define VRAPI_MINOR_VERSION		0
#define VRAPI_PATCH_VERSION		1

// Internal build identifier
#define VRAPI_BUILD_VERSION		182923

// Internal build description
#define VRAPI_BUILD_DESCRIPTION "Production"

// Minimum version of the driver required for this API
#define VRAPI_DRIVER_VERSION	23383800

#endif	// OVR_VrApi_Version_h


text:
require 'spec_helper'

RSpec.describe 'Coinroom integration specs' do
  let(:client) { Cryptoexchange::Client.new }
  let(:btc_usd_pair) { Cryptoexchange::Models::MarketPair.new(base: 'BTC', target: 'USD', market: 'coinroom') }

  it 'fetch pairs' do
    pairs = client.pairs('coinroom')
    expect(pairs).not_to be_empty

    pair = pairs.first
    expect(pair.base).to_not be nil
    expect(pair.target).to_not be nil
    expect(pair.market).to eq 'coinroom'
  end

  it 'fetch ticker' do
    ticker = client.ticker(btc_usd_pair)

    expect(ticker.base).to eq 'BTC'
    expect(ticker.target).to eq 'USD'
    expect(ticker.market).to eq 'coinroom'
    expect(ticker.last).to be_a Numeric
    expect(ticker.ask).to be_a Numeric
    expect(ticker.bid).to be_a Numeric
    expect(ticker.low).to be_a Numeric
    expect(ticker.high).to be_a Numeric
    expect(ticker.volume).to be_a Numeric
    expect(ticker.timestamp).to be nil

    expect(ticker.payload).to_not be nil
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.github.eduardovalentim</groupId>
		<artifactId>easymath</artifactId>
		<version>0.1.18-SNAPSHOT</version>
	</parent>

	<artifactId>easymath-processor</artifactId>
	<packaging>jar</packaging>
	<name>${project.artifactId}</name>

	<dependencies>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>easymath-core</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity-engine-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.antlr</groupId>
			<artifactId>antlr4-runtime</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-params</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.10.1</version>
				<configuration>
					<compilerArgument>-proc:none</compilerArgument>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.antlr</groupId>
				<artifactId>antlr4-maven-plugin</artifactId>
				<version>${antlr4.version}</version>
				<executions>
					<execution>
						<goals>
							<goal>antlr4</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<listener>true</listener>
					<visitor>true</visitor>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>build-helper-maven-plugin</artifactId>
				<version>1.7</version>
				<executions>
					<execution>
						<id>add-source</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>add-source</goal>
						</goals>
						<configuration>
							<sources>
								<source>${project.build.directory}/generated-sources/antlr4</source>
							</sources>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
  Espédaillac est
       un village
       géographiquement positionné dans le département de Lot en Midi-Pyrénées. On dénombrait 255 habitants en 2008.

Le parc de logements, à Espédaillac, se décomposait en 2011 en quatre appartements et 249 maisons soit
 un marché plutôt équilibré.

Si vous pensez emmenager à Espédaillac, vous pourrez aisément trouver une maison à acheter.

À coté de Espédaillac sont positionnées géographiquement les villes de
Assier à 9 km, 645 habitants,
Sonac à 9 km, 79 habitants,
Fontanes-du-Causse localisée à 9 km, 67 habitants,
Blars située à 9 km, 126 habitants,
Lunegarde localisée à 8 km, 70 habitants,
Saint-Simon située à 8 km, 127 habitants,
 entre autres. De plus, Espédaillac est située à seulement 21 km de Figeac.

La ville propose quelques  équipements sportifs, elle dispose, entre autres, de un terrain de tennis.


text:
<legend>
  Beneficiary details
</legend>
<form>

    First name

      <input class="form-control" type="text" name="firstName" ng-model="beneficiary.firstName" required>
      Beneficiary's first name must be provided

    Last name

      <input class="form-control" type="text" name="lastName" ng-model="beneficiary.lastName" required>
      Beneficiary's last name must be provided

</form>


text:
@interface KetTests : SenTestCase

@end


text:
{% for person in site.people %}

{{ person.name }}

			{{ person.role }}

{{ person.output }}

{% endfor %}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wyam.Common.Configuration;
using Wyam.Common.Documents;
using Wyam.Common.Execution;
using Wyam.Common.IO;
using Wyam.Common.Meta;
using Wyam.Common.Modules;
using Wyam.Common.Util;
using Wyam.Core.Modules.Control;
using Wyam.Core.Modules.Metadata;
using Wyam.Feeds;
using Wyam.Web.Pipelines;

namespace Wyam.BookSite
{
    ///
    /// A recipe for creating book and ebook marketing sites.
    ///
    /// <metadata cref="BookSiteKeys.Title" usage="Setting">The title of the book.</metadata>
    /// <metadata cref="BookSiteKeys.Title" usage="Input">The title of the post, chapter, or page.</metadata>
    /// <metadata cref="BookSiteKeys.ProcessIncludes" usage="Setting" />
    /// <metadata cref="BookSiteKeys.ProcessIncludes" usage="Input" />
    /// <metadata cref="BookSiteKeys.Subtitle" usage="Setting" />
    /// <metadata cref="BookSiteKeys.Description" usage="Setting" />
    /// <metadata cref="BookSiteKeys.Description" usage="Input">Used with chapters to provide an optional description of the chapter.</metadata>
    /// <metadata cref="BookSiteKeys.Image" usage="Setting" />
    /// <metadata cref="BookSiteKeys.Image" usage="Input">An image to display on the blog or chapter page.</metadata>
    /// <metadata cref="BookSiteKeys.BookImage" usage="Setting" />
    /// <metadata cref="BookSiteKeys.BookLink" usage="Setting" />
    /// <metadata cref="BookSiteKeys.BookLinkText" usage="Setting" />
    /// <metadata cref="BookSiteKeys.BlogPath" usage="Setting" />
    /// <metadata cref="BookSiteKeys.ChaptersPath" usage="Setting" />
    /// <metadata cref="BookSiteKeys.ChaptersIntro" usage="Setting" />
    /// <metadata cref="BookSiteKeys.IgnoreFolders" usage="Setting" />
    /// <metadata cref="BookSiteKeys.SectionsPath" usage="Setting" />
    /// <metadata cref="BookSiteKeys.MarkdownConfiguration" usage="Setting" />
    /// <metadata cref="BookSiteKeys.MarkdownExtensionTypes" usage="Setting" />
    /// <metadata cref="BookSiteKeys.IncludeDateInPostPath" usage="Setting" />
    /// <metadata cref="BookSiteKeys.MetaRefreshRedirects" usage="Setting" />
    /// <metadata cref="BookSiteKeys.NetlifyRedirects" usage="Setting" />
    /// <metadata cref="BookSiteKeys.BlogRssPath" usage="Setting" />
    /// <metadata cref="BookSiteKeys.BlogAtomPath" usage="Setting" />
    /// <metadata cref="BookSiteKeys.BlogRdfPath" usage="Setting" />
    /// <metadata cref="BookSiteKeys.ValidateAbsoluteLinks" usage="Setting" />
    /// <metadata cref="BookSiteKeys.ValidateRelativeLinks" usage="Setting" />
    /// <metadata cref="BookSiteKeys.ValidateLinksAsError" usage="Setting" />
    /// <metadata cref="BookSiteKeys.BlogPageSize" usage="Setting" />
    /// <metadata cref="BookSiteKeys.ChapterNumber" usage="Input" />
    /// <metadata cref="BookSiteKeys.Published" usage="Input" />
    /// <metadata cref="BookSiteKeys.ShowInNavbar" usage="Input" />
    /// <metadata cref="BookSiteKeys.Order" usage="Input" />
    public class BookSite : Recipe
    {
        ///
        /// Reads chapter files. These files can be either Markdown or Razor format
        /// and should be placed, one per chapter, in the folder specified by
        /// <see cref="BookSiteKeys.ChaptersPath"/>.
        ///
        [SourceInfo]
        public static Pages Chapters { get; } = new Pages(
            nameof(Chapters),
            new PagesSettings
            {
                PagesPattern = ctx => ctx.DirectoryPath(BookSiteKeys.ChaptersPath).FullPath,
                MarkdownConfiguration = ctx => ctx.String(BookSiteKeys.MarkdownConfiguration),
                MarkdownExtensionTypes = ctx => ctx.List<Type>(BookSiteKeys.MarkdownExtensionTypes),
                ProcessIncludes = (doc, ctx) => doc.Bool(BookSiteKeys.ProcessIncludes),
                Sort = (x, y) => Comparer.Default.Compare(x.Get<int>(BookSiteKeys.ChapterNumber), y.Get<int>(BookSiteKeys.ChapterNumber))
            })
                .InsertBefore(
                    Pages.CreateTreeAndSort,
                    new Where((doc, ctx) => doc.Get<int>(BookSiteKeys.ChapterNumber) > 0));

        /// <inheritdoc cref="Web.Pipelines.BlogPosts" />
        [SourceInfo]
        public static BlogPosts BlogPosts { get; } = new BlogPosts(
            nameof(BlogPosts),
            new BlogPostsSettings
            {
                PublishedKey = BookSiteKeys.Published,
                MarkdownConfiguration = ctx => ctx.String(BookSiteKeys.MarkdownConfiguration),
                MarkdownExtensionTypes = ctx => ctx.List<Type>(BookSiteKeys.MarkdownExtensionTypes),
                ProcessIncludes = (doc, ctx) => doc.Bool(BookSiteKeys.ProcessIncludes),
                IncludeDateInPostPath = ctx => ctx.Bool(BookSiteKeys.IncludeDateInPostPath),
                PostsPath = ctx => ctx.DirectoryPath(BookSiteKeys.BlogPath).FullPath
            });

        /// <inheritdoc cref="Web.Pipelines.Pages" />
        [SourceInfo]
        public static Pages Pages { get; } = new Pages(
            nameof(Pages),
            new PagesSettings
            {
                IgnorePaths = ctx => new[]
                {
                    ctx.DirectoryPath(BookSiteKeys.BlogPath).FullPath,
                    ctx.DirectoryPath(BookSiteKeys.ChaptersPath).FullPath,
                    ctx.DirectoryPath(BookSiteKeys.SectionsPath).FullPath
                }
                    .Concat(ctx.List(BookSiteKeys.IgnoreFolders, Array.Empty<string>())),
                MarkdownConfiguration = ctx => ctx.String(BookSiteKeys.MarkdownConfiguration),
                MarkdownExtensionTypes = ctx => ctx.List<Type>(BookSiteKeys.MarkdownExtensionTypes),
                ProcessIncludes = (doc, ctx) => doc.Bool(BookSiteKeys.ProcessIncludes),
                Sort = (x, y) =>
                {
                    int order = Comparer.Default.Compare(x.String(BookSiteKeys.Order), y.String(BookSiteKeys.Order));
                    return order == 0 ? Comparer.Default.Compare(x.String(Keys.Title), y.String(Keys.Title)) : order;
                },
                CreateTree = true,
                TreePlaceholderFactory = TreePlaceholderFactory
            });

        ///
        /// Reads sections for the homepage. These files can be either Markdown or Razor format
        /// and should be placed, one per section, in the folder specified by
        /// <see cref="BookSiteKeys.SectionsPath"/>.
        ///
        [SourceInfo]
        public static Pages Sections { get; } = new Pages(
            nameof(Sections),
            new PagesSettings
            {
                PagesPattern = ctx => ctx.DirectoryPath(BookSiteKeys.SectionsPath).FullPath,
                MarkdownConfiguration = ctx => ctx.String(BookSiteKeys.MarkdownConfiguration),
                MarkdownExtensionTypes = ctx => ctx.List<Type>(BookSiteKeys.MarkdownExtensionTypes),
                ProcessIncludes = (doc, ctx) => doc.Bool(BookSiteKeys.ProcessIncludes),
                Sort = (x, y) =>
                {
                    int order = Comparer.Default.Compare(x.String(BookSiteKeys.Order), y.String(BookSiteKeys.Order));
                    return order == 0 ? Comparer.Default.Compare(x.String(Keys.Title), y.String(Keys.Title)) : order;
                }
            });

        ///
        /// Generates the index pages for blog posts.
        ///
        [SourceInfo]
        public static Archive BlogIndexes { get; } = new Archive(
            nameof(BlogIndexes),
            new ArchiveSettings
            {
                Pipelines = new string[] { BlogPosts },
                File = "_BlogIndex.cshtml",
                Layout = "/_Layout.cshtml",
                PageSize = ctx => ctx.Get(BookSiteKeys.BlogPageSize, int.MaxValue),
                Title = (doc, ctx) => "Blog",
                RelativePath = (doc, ctx) => $"{ctx.DirectoryPath(BookSiteKeys.BlogPath).FullPath}"
            });

        ///
        /// Generates the chapter index.
        ///
        [SourceInfo]
        public static Archive ChapterIndex { get; } = new Archive(
            nameof(ChapterIndex),
            new ArchiveSettings
            {
                Pipelines = new string[] { Chapters },
                File = "_ChapterIndex.cshtml",
                Layout = "/_Layout.cshtml",
                Title = (doc, ctx) => "Chapters",
                RelativePath = (doc, ctx) => $"{ctx.DirectoryPath(BookSiteKeys.ChaptersPath).FullPath}"
            });

        /// <inheritdoc cref="Web.Pipelines.Feeds" />
        [SourceInfo]
        public static Web.Pipelines.Feeds BlogFeed { get; } = new Web.Pipelines.Feeds(
            nameof(BlogFeed),
            new FeedsSettings
            {
                Pipelines = new string[] { BlogPosts },
                RssPath = ctx => ctx.FilePath(BookSiteKeys.BlogRssPath),
                AtomPath = ctx => ctx.FilePath(BookSiteKeys.BlogAtomPath),
                RdfPath = ctx => ctx.FilePath(BookSiteKeys.BlogRdfPath)
            });

        /// <inheritdoc cref="Web.Pipelines.RenderPages" />
        [SourceInfo]
        public static RenderPages RenderPages { get; } = new RenderPages(
            nameof(RenderPages),
            new RenderPagesSettings
            {
                Pipelines = new string[] { Pages },
                Layout = (doc, ctx) => "/_Layout.cshtml"
            });

        ///
        /// Renders the chapter pages if they have content.
        ///
        [SourceInfo]
        public static RenderPages RenderChapters { get; } = new RenderPages(
            nameof(RenderChapters),
            new RenderPagesSettings
            {
                Pipelines = new string[] { Chapters },
                Layout = (doc, ctx) => "/_Chapter.cshtml",
                Sort = (x, y) => Comparer.Default.Compare(x.Get<int>(BookSiteKeys.ChapterNumber), y.Get<int>(BookSiteKeys.ChapterNumber))
            });

        /// <inheritdoc cref="Web.Pipelines.RenderBlogPosts" />
        [SourceInfo]
        public static RenderBlogPosts RenderBlogPosts { get; } = new RenderBlogPosts(
            nameof(RenderBlogPosts),
            new RenderBlogPostsSettings
            {
                Pipelines = new string[] { BlogPosts },
                PublishedKey = BookSiteKeys.Published,
                Layout = (doc, ctx) => "/_BlogPost.cshtml"
            });

        /// <inheritdoc cref="Web.Pipelines.Redirects" />
        [SourceInfo]
        public static Redirects Redirects { get; } = new Redirects(
            nameof(Redirects),
            new RedirectsSettings
            {
                Pipelines = new string[] { RenderPages, RenderBlogPosts },
                MetaRefreshRedirects = ctx => ctx.Bool(BookSiteKeys.MetaRefreshRedirects),
                NetlifyRedirects = ctx => ctx.Bool(BookSiteKeys.NetlifyRedirects)
            });

        /// <inheritdoc cref="Web.Pipelines.Less" />
        [SourceInfo]
        public static Web.Pipelines.Less Less { get; } = new Web.Pipelines.Less(nameof(Less));

        /// <inheritdoc cref="Web.Pipelines.Sass" />
        [SourceInfo]
        public static Web.Pipelines.Sass Sass { get; } = new Web.Pipelines.Sass(nameof(Sass));

        /// <inheritdoc cref="Web.Pipelines.Resources" />
        [SourceInfo]
        public static Resources Resources { get; } = new Resources(nameof(Resources));

        /// <inheritdoc cref="Web.Pipelines.ValidateLinks" />
        [SourceInfo]
        public static ValidateLinks ValidateLinks { get; } = new ValidateLinks(
            nameof(ValidateLinks),
            new ValidateLinksSettings
            {
                Pipelines = new string[] { RenderPages, RenderBlogPosts, Resources },
                ValidateAbsoluteLinks = ctx => ctx.Bool(BookSiteKeys.ValidateAbsoluteLinks),
                ValidateRelativeLinks = ctx => ctx.Bool(BookSiteKeys.ValidateRelativeLinks),
                ValidateLinksAsError = ctx => ctx.Bool(BookSiteKeys.ValidateLinksAsError)
            });

        /// <inheritdoc />
        public override void Apply(IEngine engine)
        {
            // Global metadata defaults
            engine.Settings[BookSiteKeys.Title] = "My Book";
            engine.Settings[BookSiteKeys.Description] = "The best book you'll ever read.";
            engine.Settings[BookSiteKeys.BookImage] = "/images/book.png";
            engine.Settings[BookSiteKeys.BookLinkText] = "Order Now";
            engine.Settings[BookSiteKeys.MarkdownConfiguration] = "advanced+bootstrap";
            engine.Settings[BookSiteKeys.IncludeDateInPostPath] = false;
            engine.Settings[BookSiteKeys.BlogPath] = "blog";
            engine.Settings[BookSiteKeys.ChaptersPath] = "chapters";
            engine.Settings[BookSiteKeys.SectionsPath] = "sections";
            engine.Settings[BookSiteKeys.BlogPageSize] = 5;
            engine.Settings[BookSiteKeys.MetaRefreshRedirects] = true;
            engine.Settings[BookSiteKeys.BlogRssPath] = GenerateFeeds.DefaultRssPath;
            engine.Settings[BookSiteKeys.BlogAtomPath] = GenerateFeeds.DefaultAtomPath;
            engine.Settings[BookSiteKeys.BlogRdfPath] = GenerateFeeds.DefaultRdfPath;

            base.Apply(engine);
        }

        /// <inheritdoc />
        public override void Scaffold(IFile configFile, IDirectory inputDirectory)
        {
            // Config file
            configFile?.WriteAllText(@"#recipe BookSite

// Customize your settings and add new ones here
Settings[Keys.Host] = ""host.com"";
Settings[BookSiteKeys.Title] = ""Your Book Title"";
Settings[BookSiteKeys.Subtitle] = ""The Subtitle Of Your Book."";
Settings[BookSiteKeys.Description] = ""A short description of your book."";
Settings[BookSiteKeys.BookLink] = ""https://a/link/to/your/book"";
Settings[BookSiteKeys.BookImage] = ""/images/book.jpg"";  // Add an image at this path to your input folder
Settings[BookSiteKeys.Image] = ""/images/banner.jpg"";  // Add an image at this path to your input folder
Settings[BookSiteKeys.ChaptersIntro] = ""A short introduction to the content of your book."";

// Add any pipeline customizations here");

            // Chapter
            inputDirectory.GetFile("chapters/first-chapter.md").WriteAllText(
                @"Title: First Chapter
Description: An optional description of this chapter.
ChapterNumber: 1
---
An optional longer description of your chapter.");

            // Blog Post
            inputDirectory.GetFile("blog/first-post.md").WriteAllText(
                @"Title: First Post
Published: 1/1/2016
---
This is a new blog post.");

            // Home sections
            inputDirectory.GetFile("sections/endorsements.cshtml").WriteAllText(@"Title: What Readers Are Saying
Order: 1
---

A newspaper quote.

Daily Newspaper

Quote from a reviewer.

Reviewer on GoodReads

I loved this book. It was incredible.

Internet Person

");
            inputDirectory.GetFile("sections/author.cshtml").WriteAllText(@"Title: About The Author
Order: 2
---

Your Name

Say a little something about yourself.

");

            // Page
            inputDirectory.GetFile("custom-page.md").WriteAllText(@"Title: Custom Page
---
You can add as many custom pages as you want.");
        }

        private static IDocument TreePlaceholderFactory(object[] path, MetadataItems items, IExecutionContext context)
        {
            FilePath indexPath = new FilePath(string.Join("/", path.Concat(new[] { "index.html" })));
            items.Add(Keys.RelativeFilePath, indexPath);
            items.Add(Keys.Title, Title.GetTitle(indexPath));
            return context.GetDocument(context.GetContentStream("@Html.Partial(\"_ChildPages\")"), items);
        }
    }
}


text:
package com.google.cloud.genomics.dataflow.utils;

import com.google.cloud.genomics.dataflow.model.LdVariant;
import com.google.genomics.v1.Variant;
import com.google.genomics.v1.VariantCall;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.Arrays;

@RunWith(JUnit4.class)
public class LdVariantProcessorTest {

  private Variant v1, v2, v3, v4;

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Before
  public void setUp() {
    VariantCall[][] calls = new VariantCall[2][2];

    for (int i = 0; i < 2; i++) {
      for (int j = 0; j < 2; j++) {
        calls[i][j] = VariantCall.newBuilder().setCallSetName(String.valueOf(i * 10 + j))
            .setPhaseset("*").addGenotype(i).addGenotype(j).build();
      }
    }

    v1 = Variant.newBuilder().setReferenceName("chr3").setStart(10000).setEnd(10001)
        .setId("v1")
        .setReferenceBases("A").addAlternateBases("T")
        .addAllCalls(Arrays.asList(calls[0][0], calls[0][1], calls[1][1])).build();

    v2 = Variant.newBuilder().setReferenceName("chr3").setStart(10001).setEnd(10002)
        .setId("v2")
        .addNames("rsidv2")
        .setReferenceBases("A").addAlternateBases("T")
        .addAllCalls(Arrays.asList(calls[0][0], calls[0][1], calls[1][1])).build();

    v3 = Variant.newBuilder().setReferenceName("chr3").setStart(10001).setEnd(10002)
        .setId("v3")
        .addNames("rsidv3a").addNames("rsidv3b")
        .setReferenceBases("A").addAlternateBases("T")
        .addAllCalls(Arrays.asList(calls[0][0], calls[0][1], calls[0][1])).build();

    v4 = Variant.newBuilder().setReferenceName("chr3").setStart(10001).setEnd(10002)
        .setId("v4")
        .addNames("rsidv4a").addNames("rsidv4b").addNames("rsidv4c")
        .setReferenceBases("A").addAlternateBases("T")
        .addAllCalls(Arrays.asList(calls[0][0], calls[0][1])).build();
  }

  @Test
  public void testLdVariantProcessor() {
    LdVariantProcessor vp = new LdVariantProcessor(Arrays.asList("0", "1", "11"));

    LdVariant lv1 = vp.convertVariant(v1);
    LdVariant lv2 = vp.convertVariant(v2);

    Assert.assertTrue(lv1.getInfo().compareTo(lv2.getInfo()) == -1);
    Assert.assertFalse(lv1.getInfo().equals(lv2.getInfo()));
    Assert.assertTrue(lv1.getInfo().equals(lv1.getInfo()));

    Assert.assertTrue(v1.getReferenceName().equals("chr3"));
  }

  @Test
  public void testCallSetNameRepeated() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Individual 1 included more than one time in call set.");
    LdVariantProcessor vp = new LdVariantProcessor(Arrays.asList("0", "1"));
    vp.convertVariant(v3);
  }

  @Test
  public void testCallSetMissingIndividual() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Individual missing from call set.");
    LdVariantProcessor vp = new LdVariantProcessor(Arrays.asList("0", "1", "11"));
    vp.convertVariant(v4);
  }
}


text:
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.RecoveryServices;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// ProtectionPoliciesOperations operations.
    /// </summary>
    public partial interface IProtectionPoliciesOperations
    {
        /// <summary>
        /// Provides the details of the backup policies associated to Recovery
        /// Services Vault. This is an asynchronous operation. Status of the
        /// operation can be fetched using GetPolicyOperationResult API.
        /// </summary>
        /// <param name='vaultName'>
        /// The name of the recovery services vault.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The name of the resource group where the recovery services vault is
        /// present.
        /// </param>
        /// <param name='policyName'>
        /// Backup policy information to be fetched.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ProtectionPolicyResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string policyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Creates or modifies a backup policy. This is an asynchronous
        /// operation. Status of the operation can be fetched using
        /// GetPolicyOperationResult API.
        /// </summary>
        /// <param name='vaultName'>
        /// The name of the recovery services vault.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The name of the resource group where the recovery services vault is
        /// present.
        /// </param>
        /// <param name='policyName'>
        /// Backup policy to be created.
        /// </param>
        /// <param name='parameters'>
        /// resource backup policy
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ProtectionPolicyResource>> CreateOrUpdateWithHttpMessagesAsync(string vaultName, string resourceGroupName, string policyName, ProtectionPolicyResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Deletes specified backup policy from your Recovery Services Vault.
        /// This is an asynchronous operation. Status of the operation can be
        /// fetched using GetPolicyOperationResult API.
        /// </summary>
        /// <param name='vaultName'>
        /// The name of the recovery services vault.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The name of the resource group where the recovery services vault is
        /// present.
        /// </param>
        /// <param name='policyName'>
        /// Backup policy to be deleted.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string vaultName, string resourceGroupName, string policyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
module Jaguar::HTTP
  class Response
    attr_accessor :status, :body
    attr_reader :headers

    def initialize(status: 200, headers: Headers.new, body: [])
      @status = status.to_i
      @headers = headers
      @body = Array(body)
    end

    def pre_process(request)

    end

    def post_process(request)
      # set default headers (adapted from webrick http response)
      @headers["server"] ||= "Jaguar/#{Jaguar::VERSION} (Ruby/#{RUBY_VERSION}/#{RUBY_RELEASE_DATE}"
      @headers["date"] ||= Time.now.httpdate
      @headers["content-type"] ||= "text/plain"

      # rework content-length/transfer-encoding
      # Determine the message length (RFC2616 -- 4.4 Message Length)
      # 4.4.1
      if @status == 304 || @status == 204 || WEBrick::HTTPStatus::info?(@status)
        @headers.delete('content-length')
        @body.clear unless @body.empty?

      else
        encoding, @encoder = Jaguar::Transcoder.choose(request.headers["accept-encoding"])
        unless encoding.nil? or encoding == "identity"
          @headers.delete("content-length")
          @headers.add("content-encoding", encoding)
        end

        unless @headers.get("vary").include?("*")
          @headers.add_header("vary", "accept-encoding")
        end
      end
    end

    def stream(keep_open: false)
      @headers["content-type"] = "text/event-stream; charset=utf-8"
      @headers["cache-control"] = 'no-cache'
      reader, writer = IO.pipe
      @body = Stream::Reader.new(reader)
      writer = Stream::Writer.new(writer)
      if block_given?
        begin
          yield writer
        ensure
          writer.close unless keep_open
        end
      else
        writer
      end
    end

    private

    def encode(&action)
      return enum_for(__method__) unless block_given?
      if @encoder
        mtime = @headers["last-modified"] ?
                Time.httpdate(@headers["last-modified"]) :
                Time.now
        @encoder.encode(mtime: mtime) do |encoder|
          encoder.encode(@body) do |encoded|
            action.call(encoded)
          end
        end
      else
        @body.each(&action)
      end
    end

    def reason
      WEBrick::HTTPStatus::StatusMessage[@status]
    end

    def LOG(&msg)
      return unless $JAGUAR_DEBUG
      $stderr << "server response: " + msg.call.inspect + "\n"
    end

  end
end


text:
self.addEventListener('install', function(event) {
  // インストール処理
  console.log('install できました!!');
});

self.addEventListener('activate', function(event) {
  // 有効化
  console.log('activate できました!!');
});

self.addEventListener('fetch', function(event) {
  console.log('proxied', event.request.url);

  if (
    [
      'https://teramotodaiki.github.io/service-worker-test/',
      'https://teramotodaiki.github.io/service-worker-test/index.html'
    ].includes(event.request.url) === false
  ) {
    // スルー
    event.respondWith(
      fetch(event.request)
    );
    return;
  }

  const html = `
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Service Worker Test</title>
        <script type="text/javascript">
            console.log('sw', 'serviceWorker' in navigator);
            if ('serviceWorker' in navigator) {
              navigator.serviceWorker.register('./sw.js?_=${new Date().getTime()}').then(function(registration) {
                // 登録成功
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
              }).catch(function(err) {
                // 登録失敗 :(
                console.log('ServiceWorker registration failed: ', err);
              });
            }
        </script>
    </head>
    <body>
        おめでとうございます!キャッシュです! 10
    </body>
</html>
`;
  const file = new Blob([html], {
    type: 'text/html',
  });

  event.respondWith(
    Promise.resolve(
      new Response(file)
    )
  );
});


text:
#include "vom/cmd.hpp"

namespace VOM {
/**
 * Free ostream function to print a command
 */
std::ostream&
operator<<(std::ostream& os, const cmd& cmd)
{
  os << cmd.to_string();

  return (os);
}
}

/*
 * fd.io coding-style-patch-verification: OFF
 *
 * Local Variables:
 * eval: (c-set-style "mozilla")
 * End:
 */


text:
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({

/***/ 0:
/***/ function(module, exports, __webpack_require__) {

	module.exports = __webpack_require__(216);

/***/ },

/***/ 216:
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	module.exports = __webpack_require__(217);

/***/ },

/***/ 217:
/***/ function(module, exports, __webpack_require__) {

	var __vue_script__, __vue_template__
	var __vue_styles__ = {}
	__webpack_require__(218)
	__vue_script__ = __webpack_require__(220)
	if (__vue_script__ &&
	    __vue_script__.__esModule &&
	    Object.keys(__vue_script__).length > 1) {
	  console.warn("[vue-loader] packages/tab-container-item/src/tab-container-item.vue: named exports in *.vue files are ignored.")}
	__vue_template__ = __webpack_require__(221)
	module.exports = __vue_script__ || {}
	if (module.exports.__esModule) module.exports = module.exports.default
	var __vue_options__ = typeof module.exports === "function" ? (module.exports.options || (module.exports.options = {})) : module.exports
	if (__vue_template__) {
	__vue_options__.template = __vue_template__
	}
	if (!__vue_options__.computed) __vue_options__.computed = {}
	Object.keys(__vue_styles__).forEach(function (key) {
	var module = __vue_styles__[key]
	__vue_options__.computed[key] = function () { return module }
	})

/***/ },

/***/ 218:
/***/ function(module, exports) {

	// removed by extract-text-webpack-plugin

/***/ },

/***/ 220:
/***/ function(module, exports) {

	'use strict';

	exports.__esModule = true;
	exports.default = {
	  name: 'mt-tab-container-item',

	  props: ['id']
	};

/***/ },

/***/ 221:
/***/ function(module, exports) {

	module.exports = "\n<div\n  v-show=\"$parent.swiping || id === $parent.active\"\n  class=\"mint-tab-container-item\">\n  <slot></slot>\n</div>\n";

/***/ }

/******/ });


text:
#include <iostream>
#include <map>
#include <set>
#include <string>

#include "webrtc/base/bind.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/helpers.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/p2p/base/stun.h"
#include "webrtc/p2p/stunprober/stunprober.h"

namespace stunprober {

namespace {

void IncrementCounterByAddress(std::map<rtc::IPAddress, int>* counter_per_ip,
                               const rtc::IPAddress& ip) {
  counter_per_ip->insert(std::make_pair(ip, 0)).first->second++;
}

}  // namespace

StunProber::Requester::Requester(
    StunProber* prober,
    ServerSocketInterface* socket,
    const std::vector<rtc::SocketAddress>& server_ips)
    : prober_(prober),
      socket_(socket),
      response_packet_(new rtc::ByteBuffer(nullptr, kMaxUdpBufferSize)),
      server_ips_(server_ips),
      thread_checker_(prober->thread_checker_) {
}

StunProber::Requester::~Requester() {
  if (socket_) {
    socket_->Close();
  }
  for (auto req : requests_) {
    if (req) {
      delete req;
    }
  }
}

void StunProber::Requester::SendStunRequest() {
  DCHECK(thread_checker_.CalledOnValidThread());
  requests_.push_back(new Request());
  Request& request = *(requests_.back());
  cricket::StunMessage message;

  // Random transaction ID, STUN_BINDING_REQUEST
  message.SetTransactionID(
      rtc::CreateRandomString(cricket::kStunTransactionIdLength));
  message.SetType(cricket::STUN_BINDING_REQUEST);

  rtc::scoped_ptr<rtc::ByteBuffer> request_packet(
      new rtc::ByteBuffer(nullptr, kMaxUdpBufferSize));
  if (!message.Write(request_packet.get())) {
    prober_->End(WRITE_FAILED, 0);
    return;
  }

  auto addr = server_ips_[num_request_sent_];
  request.server_addr = addr.ipaddr();

  int rv = 0;

  // Only bind to the interface at the first request.
  if (num_request_sent_ == 0) {
    rtc::IPAddress local_addr;
    rv = prober_->GetLocalAddress(&local_addr);
    if (rv != 0) {
      prober_->End(GENERIC_FAILURE, rv);
      return;
    }
    rv = socket_->Bind(rtc::SocketAddress(local_addr, 0));
    if (rv < 0) {
      prober_->End(GENERIC_FAILURE, rv);
      return;
    }
  }

  // The write must succeed immediately. Otherwise, the calculating of the STUN
  // request timing could become too complicated. Callback is ignored by passing
  // empty AsyncCallback.
  rv = socket_->SendTo(addr, const_cast<char*>(request_packet->Data()),
                       request_packet->Length(), AsyncCallback());
  if (rv < 0) {
    prober_->End(WRITE_FAILED, rv);
    return;
  }

  request.sent_time_ms = rtc::Time();

  // Post a read waiting for response. For share mode, the subsequent read will
  // be posted inside OnStunResponseReceived.
  if (num_request_sent_ == 0) {
    ReadStunResponse();
  }

  num_request_sent_++;
  DCHECK(static_cast<size_t>(num_request_sent_) <= server_ips_.size());
}

void StunProber::Requester::ReadStunResponse() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!socket_) {
    return;
  }

  int rv = socket_->RecvFrom(
      response_packet_->ReserveWriteBuffer(kMaxUdpBufferSize),
      kMaxUdpBufferSize, &addr_,
      [this](int result) { this->OnStunResponseReceived(result); });
  if (rv != SocketInterface::IO_PENDING) {
    OnStunResponseReceived(rv);
  }
}

void StunProber::Requester::Request::ProcessResponse(
    rtc::ByteBuffer* message,
    int buf_len,
    const rtc::IPAddress& local_addr) {
  int64 now = rtc::Time();

  cricket::StunMessage stun_response;
  if (!stun_response.Read(message)) {
    // Invalid or incomplete STUN packet.
    received_time_ms = 0;
    return;
  }

  // Get external address of the socket.
  const cricket::StunAddressAttribute* addr_attr =
      stun_response.GetAddress(cricket::STUN_ATTR_MAPPED_ADDRESS);
  if (addr_attr == nullptr) {
    // Addresses not available to detect whether or not behind a NAT.
    return;
  }

  if (addr_attr->family() != cricket::STUN_ADDRESS_IPV4 &&
      addr_attr->family() != cricket::STUN_ADDRESS_IPV6) {
    return;
  }

  received_time_ms = now;

  srflx_addr = addr_attr->GetAddress();

  // Calculate behind_nat.
  behind_nat = (srflx_addr.ipaddr() != local_addr);
}

void StunProber::Requester::OnStunResponseReceived(int result) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(socket_);

  if (result < 0) {
    // Something is wrong, finish the test.
    prober_->End(READ_FAILED, result);
    return;
  }

  Request* request = GetRequestByAddress(addr_.ipaddr());
  if (!request) {
    // Something is wrong, finish the test.
    prober_->End(GENERIC_FAILURE, result);
    return;
  }

  num_response_received_++;

  // Resize will set the end_ to indicate that there are data available in this
  // ByteBuffer.
  response_packet_->Resize(result);
  request->ProcessResponse(response_packet_.get(), result,
                           prober_->local_addr_);

  if (static_cast<size_t>(num_response_received_) < server_ips_.size()) {
    // Post another read response.
    ReadStunResponse();
  }
}

StunProber::Requester::Request* StunProber::Requester::GetRequestByAddress(
    const rtc::IPAddress& ipaddr) {
  DCHECK(thread_checker_.CalledOnValidThread());
  for (auto request : requests_) {
    if (request->server_addr == ipaddr) {
      return request;
    }
  }

  return nullptr;
}

StunProber::StunProber(HostNameResolverInterface* host_name_resolver,
                       SocketFactoryInterface* socket_factory,
                       TaskRunnerInterface* task_runner)
    : interval_ms_(0),
      socket_factory_(socket_factory),
      resolver_(host_name_resolver),
      task_runner_(task_runner) {
}

StunProber::~StunProber() {
  for (auto req : requesters_) {
    if (req) {
      delete req;
    }
  }
}

bool StunProber::Start(const std::vector<rtc::SocketAddress>& servers,
                       bool shared_socket_mode,
                       int interval_ms,
                       int num_request_per_ip,
                       int timeout_ms,
                       const AsyncCallback callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  interval_ms_ = interval_ms;
  shared_socket_mode_ = shared_socket_mode;

  requests_per_ip_ = num_request_per_ip;
  if (requests_per_ip_ == 0 || servers.size() == 0) {
    return false;
  }

  timeout_ms_ = timeout_ms;
  servers_ = servers;
  finished_callback_ = callback;
  resolver_->Resolve(servers_[0], &resolved_ips_,
                     [this](int result) { this->OnServerResolved(0, result); });
  return true;
}

void StunProber::OnServerResolved(int index, int result) {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (result == 0) {
    all_servers_ips_.insert(all_servers_ips_.end(), resolved_ips_.begin(),
                            resolved_ips_.end());
    resolved_ips_.clear();
  }

  index++;

  if (static_cast<size_t>(index) < servers_.size()) {
    resolver_->Resolve(
        servers_[index], &resolved_ips_,
        [this, index](int result) { this->OnServerResolved(index, result); });
    return;
  }

  if (all_servers_ips_.size() == 0) {
    End(RESOLVE_FAILED, result);
    return;
  }

  // Dedupe.
  std::set<rtc::SocketAddress> addrs(all_servers_ips_.begin(),
                                     all_servers_ips_.end());
  all_servers_ips_.assign(addrs.begin(), addrs.end());

  rtc::IPAddress addr;
  if (GetLocalAddress(&addr) != 0) {
    End(GENERIC_FAILURE, result);
    return;
  }

  MaybeScheduleStunRequests();
}

int StunProber::GetLocalAddress(rtc::IPAddress* addr) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (local_addr_.family() == AF_UNSPEC) {
    rtc::SocketAddress sock_addr;
    rtc::scoped_ptr<ClientSocketInterface> socket(
        socket_factory_->CreateClientSocket());
    int rv = socket->Connect(all_servers_ips_[0]);
    if (rv != SUCCESS) {
      End(GENERIC_FAILURE, rv);
      return rv;
    }
    rv = socket->GetLocalAddress(&sock_addr);
    if (rv != SUCCESS) {
      End(GENERIC_FAILURE, rv);
      return rv;
    }
    local_addr_ = sock_addr.ipaddr();
    socket->Close();
  }
  *addr = local_addr_;
  return 0;
}

StunProber::Requester* StunProber::CreateRequester() {
  DCHECK(thread_checker_.CalledOnValidThread());
  rtc::scoped_ptr<ServerSocketInterface> socket(
      socket_factory_->CreateServerSocket(kMaxUdpBufferSize,
                                          kMaxUdpBufferSize));
  if (!socket) {
    return nullptr;
  }
  if (shared_socket_mode_) {
    return new Requester(this, socket.release(), all_servers_ips_);
  } else {
    std::vector<rtc::SocketAddress> server_ip;
    server_ip.push_back(
        all_servers_ips_[(num_request_sent_ % all_servers_ips_.size())]);
    return new Requester(this, socket.release(), server_ip);
  }
}

bool StunProber::SendNextRequest() {
  if (!current_requester_ || current_requester_->Done()) {
    current_requester_ = CreateRequester();
    requesters_.push_back(current_requester_);
  }
  if (!current_requester_) {
    return false;
  }
  current_requester_->SendStunRequest();
  num_request_sent_++;
  return true;
}

void StunProber::MaybeScheduleStunRequests() {
  DCHECK(thread_checker_.CalledOnValidThread());
  uint32 now = rtc::Time();

  if (Done()) {
    task_runner_->PostTask(rtc::Bind(&StunProber::End, this, SUCCESS, 0),
                           timeout_ms_);
    return;
  }
  if (now >= next_request_time_ms_) {
    if (!SendNextRequest()) {
      End(GENERIC_FAILURE, 0);
      return;
    }
    next_request_time_ms_ = now + interval_ms_;
  }
  task_runner_->PostTask(
      rtc::Bind(&StunProber::MaybeScheduleStunRequests, this), 1 /* ms */);
}

bool StunProber::GetStats(StunProber::Stats* prob_stats) {
  // No need to be on the same thread.
  if (!prob_stats) {
    return false;
  }

  StunProber::Stats stats;

  int rtt_sum = 0;
  bool behind_nat_set = false;
  int64 first_sent_time = 0;
  int64 last_sent_time = 0;

  // Track of how many srflx IP that we have seen.
  std::set<rtc::IPAddress> srflx_ips;

  // If we're not receiving any response on a given IP, all requests sent to
  // that IP should be ignored as this could just be an DNS error.
  std::map<rtc::IPAddress, int> num_response_per_ip;
  std::map<rtc::IPAddress, int> num_request_per_ip;

  for (auto* requester : requesters_) {
    for (auto request : requester->requests()) {
      if (request->sent_time_ms <= 0) {
        continue;
      }

      IncrementCounterByAddress(&num_request_per_ip, request->server_addr);

      if (!first_sent_time) {
        first_sent_time = request->sent_time_ms;
      }
      last_sent_time = request->sent_time_ms;

      if (request->received_time_ms < request->sent_time_ms) {
        continue;
      }

      IncrementCounterByAddress(&num_response_per_ip, request->server_addr);

      rtt_sum += request->rtt();
      if (!behind_nat_set) {
        stats.behind_nat = request->behind_nat;
        behind_nat_set = true;
      } else if (stats.behind_nat != request->behind_nat) {
        // Detect the inconsistency in NAT presence.
        return false;
      }
      stats.srflx_addrs.insert(request->srflx_addr.ToString());
      srflx_ips.insert(request->srflx_addr.ipaddr());
    }
  }

  // We're probably not behind a regular NAT. We have more than 1 distinct
  // server reflexive IPs.
  if (srflx_ips.size() > 1) {
    return false;
  }

  int num_sent = 0;
  int num_received = 0;
  int num_server_ip_with_response = 0;

  for (const auto& kv : num_response_per_ip) {
    DCHECK_GT(kv.second, 0);
    num_server_ip_with_response++;
    num_received += kv.second;
    num_sent += num_request_per_ip[kv.first];
  }

  // Not receiving any response, the trial is inconclusive.
  if (!num_received) {
    return false;
  }

  // Shared mode is only true if we use the shared socket and there are more
  // than 1 responding servers.
  stats.shared_socket_mode =
      shared_socket_mode_ && (num_server_ip_with_response > 1);

  stats.host_ip = local_addr_.ToString();
  stats.num_request_sent = num_sent;
  stats.num_response_received = num_received;
  stats.target_request_interval_ns = interval_ms_ * 1000;

  if (num_sent) {
    stats.success_percent = static_cast<int>(100 * num_received / num_sent);
  }

  if (num_sent > 1) {
    stats.actual_request_interval_ns =
        (1000 * (last_sent_time - first_sent_time)) / (num_sent - 1);
  }

  if (num_received) {
    stats.average_rtt_ms = static_cast<int>((rtt_sum / num_received));
  }

  *prob_stats = stats;
  return true;
}

void StunProber::End(StunProber::Status status, int result) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!finished_callback_.empty()) {
    AsyncCallback callback = finished_callback_;
    finished_callback_ = AsyncCallback();

    // Callback at the last since the prober might be deleted in the callback.
    callback(status);
  }
}

}  // namespace stunprober


text:
package upgrade

import (
	"reflect"
	"testing"

	"k8s.io/kubernetes/pkg/util/version"
)

func TestSetImplicitFlags(t *testing.T) {
	var tests = []struct {
		flags         *applyFlags
		expectedFlags applyFlags
		errExpected   bool
	}{
		{ // if not dryRun or force is set; the nonInteractiveMode field should not be touched
			flags: &applyFlags{
				newK8sVersionStr:   "v1.8.0",
				dryRun:             false,
				force:              false,
				nonInteractiveMode: false,
			},
			expectedFlags: applyFlags{
				newK8sVersionStr:   "v1.8.0",
				newK8sVersion:      version.MustParseSemantic("v1.8.0"),
				dryRun:             false,
				force:              false,
				nonInteractiveMode: false,
			},
		},
		{ // if not dryRun or force is set; the nonInteractiveMode field should not be touched
			flags: &applyFlags{
				newK8sVersionStr:   "v1.8.0",
				dryRun:             false,
				force:              false,
				nonInteractiveMode: true,
			},
			expectedFlags: applyFlags{
				newK8sVersionStr:   "v1.8.0",
				newK8sVersion:      version.MustParseSemantic("v1.8.0"),
				dryRun:             false,
				force:              false,
				nonInteractiveMode: true,
			},
		},
		{ // if dryRun or force is set; the nonInteractiveMode field should be set to true
			flags: &applyFlags{
				newK8sVersionStr:   "v1.8.0",
				dryRun:             true,
				force:              false,
				nonInteractiveMode: false,
			},
			expectedFlags: applyFlags{
				newK8sVersionStr:   "v1.8.0",
				newK8sVersion:      version.MustParseSemantic("v1.8.0"),
				dryRun:             true,
				force:              false,
				nonInteractiveMode: true,
			},
		},
		{ // if dryRun or force is set; the nonInteractiveMode field should be set to true
			flags: &applyFlags{
				newK8sVersionStr:   "v1.8.0",
				dryRun:             false,
				force:              true,
				nonInteractiveMode: false,
			},
			expectedFlags: applyFlags{
				newK8sVersionStr:   "v1.8.0",
				newK8sVersion:      version.MustParseSemantic("v1.8.0"),
				dryRun:             false,
				force:              true,
				nonInteractiveMode: true,
			},
		},
		{ // if dryRun or force is set; the nonInteractiveMode field should be set to true
			flags: &applyFlags{
				newK8sVersionStr:   "v1.8.0",
				dryRun:             true,
				force:              true,
				nonInteractiveMode: false,
			},
			expectedFlags: applyFlags{
				newK8sVersionStr:   "v1.8.0",
				newK8sVersion:      version.MustParseSemantic("v1.8.0"),
				dryRun:             true,
				force:              true,
				nonInteractiveMode: true,
			},
		},
		{ // if dryRun or force is set; the nonInteractiveMode field should be set to true
			flags: &applyFlags{
				newK8sVersionStr:   "v1.8.0",
				dryRun:             true,
				force:              true,
				nonInteractiveMode: true,
			},
			expectedFlags: applyFlags{
				newK8sVersionStr:   "v1.8.0",
				newK8sVersion:      version.MustParseSemantic("v1.8.0"),
				dryRun:             true,
				force:              true,
				nonInteractiveMode: true,
			},
		},
		{ // if the new version is empty; it should error out
			flags: &applyFlags{
				newK8sVersionStr: "",
			},
			expectedFlags: applyFlags{
				newK8sVersionStr: "",
			},
			errExpected: true,
		},
		{ // if the new version is invalid; it should error out
			flags: &applyFlags{
				newK8sVersionStr: "foo",
			},
			expectedFlags: applyFlags{
				newK8sVersionStr: "foo",
			},
			errExpected: true,
		},
		{ // if the new version is valid but without the "v" prefix; it parse and prepend v
			flags: &applyFlags{
				newK8sVersionStr: "1.8.0",
			},
			expectedFlags: applyFlags{
				newK8sVersionStr: "v1.8.0",
				newK8sVersion:    version.MustParseSemantic("v1.8.0"),
			},
			errExpected: false,
		},
		{ // valid version should succeed
			flags: &applyFlags{
				newK8sVersionStr: "v1.8.1",
			},
			expectedFlags: applyFlags{
				newK8sVersionStr: "v1.8.1",
				newK8sVersion:    version.MustParseSemantic("v1.8.1"),
			},
			errExpected: false,
		},
		{ // valid version should succeed
			flags: &applyFlags{
				newK8sVersionStr: "1.8.0-alpha.3",
			},
			expectedFlags: applyFlags{
				newK8sVersionStr: "v1.8.0-alpha.3",
				newK8sVersion:    version.MustParseSemantic("v1.8.0-alpha.3"),
			},
			errExpected: false,
		},
	}
	for _, rt := range tests {
		actualErr := SetImplicitFlags(rt.flags)

		// If an error was returned; make newK8sVersion nil so it's easy to match using reflect.DeepEqual later (instead of a random pointer)
		if actualErr != nil {
			rt.flags.newK8sVersion = nil
		}

		if !reflect.DeepEqual(*rt.flags, rt.expectedFlags) {
			t.Errorf(
				"failed SetImplicitFlags:\n\texpected flags: %v\n\t  actual: %v",
				rt.expectedFlags,
				*rt.flags,
			)
		}
		if (actualErr != nil) != rt.errExpected {
			t.Errorf(
				"failed SetImplicitFlags:\n\texpected error: %t\n\t  actual: %t",
				rt.errExpected,
				(actualErr != nil),
			)
		}
	}
}


text:
require_relative './spec_helper'
require_relative './fakefs_helper'
require_relative '../lib/downloader'
require 'fakeweb'

describe Downloader do
  describe "#prefix" do
    it "returns prefix value" do
      [:prefix, "prefix"].each do |key|
        config = { key => "f1" }
        downloader = Downloader.new(config)
        downloader.prefix.must_equal "[#{config[key]}]"
      end
    end
  end

  describe "#ext" do
    it "returns extension value" do
      [:ext, "ext"].each do |key|
        config = { key => "txt" }
        downloader = Downloader.new(config)
        downloader.ext.must_equal config[key]
      end
    end
  end

  describe "#destination" do
    it "returns destination path value" do
      [:destination, "destination"].each do |key|
        config = { key => "~/path/to/download" }
        downloader = Downloader.new(config)
        downloader.destination.must_equal File.expand_path(config[key])
      end
    end
  end

  describe "#run" do
    before do
      FakeFS.activate!

      config = { prefix: "f1", ext: "md", destination: "/tmp/destination" }
      @downloader = Downloader.new(config)

      @title = "Item 1"
      @url = "http://example.com/item1.txt"

      @filename = "[f1].item.1.md"

      FakeWeb.register_uri(:get, @url, body: "Hello world!")
      FakeWeb.register_uri(:head, @url, body: "")
    end

    after do
      FileUtils.rm_r(@downloader.destination) if File.directory?(@downloader.destination)
      FakeFS.deactivate!
    end

    context "when destination directory doesn't exist" do
      it "creates it" do
        @downloader.run(@title, @url)

        File.directory?(@downloader.destination).must_equal true
      end
    end

    context "when extension is set" do
      before do
        @base_name = "#{@title.downcase.gsub(' ', '.')}.#{@downloader.ext}"
      end

      it "saves downloaded file with custom name" do
        filename = "#{@downloader.prefix}.#{@base_name}"

        @downloader.run(@title, @url)

        File.exists?(File.join(@downloader.destination, filename)).must_equal true
      end

      context "when prefix is not set" do
        before do
          @downloader.prefix = nil
        end

        it "saves downloaded file without prefix" do
          @downloader.run(@title, @url)

          File.exists?(File.join(@downloader.destination, @base_name)).must_equal true
        end
      end
    end

    context "when title is not set" do
      it "saves downloaded file with prefixed original name" do
        name = "#{@downloader.prefix}.#{File.basename(@url)}"
        full_path = File.join(@downloader.destination, name)

        @downloader.run(nil, @url)
        File.exists?(full_path).must_equal true
      end

      context "when prefix is not set" do
        before do
          @downloader.prefix = nil
        end

        it "saves downloaded file with original name" do
          full_path = File.join(@downloader.destination, File.basename(@url))

          @downloader.run(nil, @url)
          File.exists?(full_path).must_equal true
        end
      end
    end

    context "when extension is not set" do
      before do
        @downloader.ext = nil
      end

      it "saves downloaded file with prefixed original name" do
        @downloader.run(@title, @url)

        name = "#{@downloader.prefix}.#{File.basename(@url)}"
        full_path = File.join(@downloader.destination, name)
        File.exists?(full_path).must_equal true
      end
    end

    it "returns name of saved file" do
      @downloader.run(@title, @url).must_equal @filename
    end

    context "when URL is incorrect" do
      before do
        FakeWeb.register_uri(:get, @url, body: "", status: ["404", "Not Found"])
      end

      it "skips downloading" do
        Mechanize::File.any_instance.expects(:save!).never

        @downloader.run(@title, @url)
      end

      it "returns empty string" do
        @downloader.run(@title, @url).must_equal ""
      end
    end

    context "when given URL has no body" do
      before do
        FakeWeb.register_uri(:get, @url, body: "")
      end

      it "returns empty string" do
        @downloader.run(@title, @url).must_equal ""
      end
    end

    context "when file already exists" do
      before do
        FileUtils.mkdir_p(@downloader.destination)
        FileUtils.touch(File.join(@downloader.destination, @filename))
      end

      it "skips downloading" do
        Mechanize::File.any_instance.expects(:save!).never

        @downloader.run(@title, @url)
      end

      it "returns file name" do
        @downloader.run(@title, @url).must_equal @filename
      end
    end
  end
end


text:
package karaokePackage;

//import com.sun.media.sound.WaveFileWriter;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import static javax.sound.sampled.AudioSystem.getAudioFileTypes;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.SoftBevelBorder;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Shwetha
 */
public class Soundcapture extends JPanel implements ActionListener {
    final int bufSize = 16384;

  Capture capture = new Capture();

  Playback playback = new Playback();

  AudioInputStream audioInputStream;

  public JButton playB, captB;

  JTextField textField;

  String errStr;

  double duration, seconds;

  File file;

  public Soundcapture()
  {}

  public Soundcapture(File myfile) {

    setLayout(new BorderLayout());
    EmptyBorder eb = new EmptyBorder(5, 5, 5, 5);
    SoftBevelBorder sbb = new SoftBevelBorder(SoftBevelBorder.LOWERED);
    setBorder(new EmptyBorder(5, 5, 5, 5));

    file=myfile;
    System.out.println(file);

    JPanel p1 = new JPanel();
    p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));

    JPanel p2 = new JPanel();
    p2.setBorder(sbb);
    p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));

    JPanel buttonsPanel = new JPanel();
    buttonsPanel.setBorder(new EmptyBorder(10, 0, 5, 0));
    playB = addButton("Play", buttonsPanel, false);
    captB = addButton("Record", buttonsPanel, true);
    p2.add(buttonsPanel);

    p1.add(p2);
    add(p1);

  }

  public void open() {
  }

  public void close() {
    if (playback.thread != null) {
      playB.doClick(0);
    }
    if (capture.thread != null) {
      captB.doClick(0);
    }
  }

  private JButton addButton(String name, JPanel p, boolean state) {
    JButton b = new JButton(name);
    b.addActionListener(this);
    b.setEnabled(state);
    p.add(b);
    return b;
  }

  public void actionPerformed(ActionEvent e) {
    Object obj = e.getSource();
    if (obj.equals(playB)) {
      if (playB.getText().startsWith("Play")) {
        playback.start();
        captB.setEnabled(false);
        playB.setText("Stop");
      } else {
        playback.stop();
        captB.setEnabled(true);
        playB.setText("Play");
      }
    } else if (obj.equals(captB)) {
      if (captB.getText().startsWith("Record")) {

        capture.start();
        playB.setEnabled(false);
        captB.setText("Stop");
      } else {
        capture.stop();
        playB.setEnabled(true);
      }

    }
  }

  /**
   * Write data to the OutputChannel.
   */
  public class Playback implements Runnable {

    SourceDataLine line;

    Thread thread;

    public void start() {
      errStr = null;
      thread = new Thread(this);
      thread.setName("Playback");
      thread.start();
    }

    public void stop() {
      thread = null;
    }

    private void shutDown(String message) {
      if ((errStr = message) != null) {
        System.err.println(errStr);
      }
      if (thread != null) {
        thread = null;
        captB.setEnabled(true);
        playB.setText("Play");
      }
    }

    public void run() {

      // make sure we have something to play

      if (audioInputStream == null) {
        shutDown("No loaded audio to play back");
        return;
      }
      // reset to the beginnning of the stream
      try {
        audioInputStream.reset();
      } catch (Exception e) {
        shutDown("Unable to reset the stream\n" + e);
        return;
      }

      // get an AudioInputStream of the desired format for playback

      AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
      float rate = 44100.0f;
      int channels = 2;
      int frameSize = 4;
      int sampleSize = 16;
      boolean bigEndian = true;

      AudioFormat format = new AudioFormat(encoding, rate, sampleSize, channels, (sampleSize / 8)
          * channels, rate, bigEndian);

      AudioInputStream playbackInputStream = AudioSystem.getAudioInputStream(format,
          audioInputStream);

      if (playbackInputStream == null) {
        shutDown("Unable to convert stream of format " + audioInputStream + " to format " + format);
        return;
      }

      // define the required attributes for our line,
      // and make sure a compatible line is supported.

      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
      if (!AudioSystem.isLineSupported(info)) {
        shutDown("Line matching " + info + " not supported.");
        return;
      }

      // get and open the source data line for playback.

      try {
        line = (SourceDataLine) AudioSystem.getLine(info);
        line.open(format, bufSize);
      } catch (LineUnavailableException ex) {
        shutDown("Unable to open the line: " + ex);
        return;
      }

      // play back the captured audio data

      int frameSizeInBytes = format.getFrameSize();
      int bufferLengthInFrames = line.getBufferSize() / 8;
      int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
      byte[] data = new byte[bufferLengthInBytes];
      int numBytesRead = 0;

      // start the source data line
      line.start();

      while (thread != null) {
        try {
          if ((numBytesRead = playbackInputStream.read(data)) == -1) {
            break;
          }
          int numBytesRemaining = numBytesRead;
          while (numBytesRemaining > 0) {
            numBytesRemaining -= line.write(data, 0, numBytesRemaining);
          }
        } catch (Exception e) {
          shutDown("Error during playback: " + e);
          break;
        }
      }
      // we reached the end of the stream.
      // let the data play out, then
      // stop and close the line.
      if (thread != null) {
        line.drain();
      }
      line.stop();
      line.close();
      line = null;
      shutDown(null);
    }
  } // End class Playback

  /**
   * Reads data from the input channel and writes to the output stream
   */
  class Capture implements Runnable {

    TargetDataLine line;

    Thread thread;
        private OutputStream outputStream;

    public void start() {
      errStr = null;
      thread = new Thread(this);
      thread.setName("Capture");
      thread.start();
    }

    public void stop() {
      thread = null;

    }

    private void shutDown(String message) {
      if ((errStr = message) != null && thread != null) {
        thread = null;
        playB.setEnabled(true);
        captB.setText("Record");
        System.err.println(errStr);
      }
    }

    @Override
    public void run() {

      duration = 0;
      audioInputStream = null;
      int z=1;

      // define the required attributes for our line,
      // and make sure a compatible line is supported.

      AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
      float rate = 44100.0f;
      int channels = 2;
      int frameSize = 4;
      int sampleSize = 16;
      boolean bigEndian = true;

      AudioFormat format = new AudioFormat(encoding, rate, sampleSize, channels, (sampleSize / 8)
          * channels, rate, bigEndian);

      DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

      if (!AudioSystem.isLineSupported(info)) {
        shutDown("Line matching " + info + " not supported.");
        return;
      }

      // get and open the target data line for capture.

      try {

        line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format, line.getBufferSize());
      } catch (LineUnavailableException ex) {
        shutDown("Unable to open the line: " + ex);
        return;
      } catch (SecurityException ex) {
        shutDown(ex.toString());
        //JavaSound.showInfoDialog();
        return;
      } catch (Exception ex) {
        shutDown(ex.toString());
        return;
      }

      // play back the captured audio data

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int frameSizeInBytes = format.getFrameSize();
      int bufferLengthInFrames = line.getBufferSize() / 8;
      int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
      byte[] data = new byte[bufferLengthInBytes];
      int numBytesRead;

      line.start();

      while (thread != null) {
        if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
          break;
        }

        out.write(data, 0, numBytesRead);
      }

      // we reached the end of the stream.
      // stop and close the line.
      line.stop();
      line.close();
      line = null;

      // stop and close the output stream
      try {
        out.flush();
        out.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }

      // load bytes into the audio input stream for playback

      byte audioBytes[] = out.toByteArray();
      ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
      audioInputStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes);

      long milliseconds = (long) ((audioInputStream.getFrameLength() * 1000) / format
          .getFrameRate());
      duration = milliseconds / 1000.0;

      try {
        audioInputStream.reset();
      } catch (Exception ex) {
        ex.printStackTrace();
        return;
      }
       try {

    OutputStream fos;

    fos = new FileOutputStream (new File(file+".WAV"));
    out.writeTo(fos);
    while (thread != null) {
        if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
          break;
        }
        out.write(data, 0, numBytesRead);
      }
} catch(IOException ioe) {
    // Handle exception here
    System.out.println("oooooooooooo");
}      try{
       AudioSystem.write(audioInputStream ,AudioFileFormat.Type.WAVE, new File(file+".mp3"));
       z++;
    }catch(IOException e){System.out.println("ufffff");}
    }
  } // End class Capture

  public static void main(String s[]) {
    Soundcapture ssc = new Soundcapture();
    ssc.open();
    JFrame f = new JFrame("Capture/Playback");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add("Center", ssc);
    f.pack();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int w = 360;
    int h = 170;
    f.setLocation(screenSize.width / 2 - w / 2, screenSize.height / 2 - h / 2);
    f.setSize(w, h);
    f.show();
  }

}


text:
package ru.apetrov.models;

import ru.apetrov.*;

/**
 * класс Ферзя.
 */
public class Queen extends Figure {

	/**
	 * класс проверок хода.
	 */
	private MoveChecking checking = new MoveChecking();

	/**
	 * конструктор.
	 * @param position позиция.
	 */
	public Queen(Position position) {
		super(position);
	}

	/**
	 * корректность хода.
	 * @param position новая позиция.
	 * @return возможность хода.
	 */
	@Override
	public boolean moveTo(Position position) {

		boolean result = false;

		if (checking.boardRangeChecking(position) && checking.positionOccupiedChecking(this, position) &&
				checking.moveByDiagonal(this, position) || checking.moveByVerticaleOrHorizontale(this, position)) {

			if (this.getPosition().getY() == position.getY() || this.getPosition().getX() == position.getX()) {
				result = true;
			}

			if (Math.abs(this.getPosition().getY() - position.getY()) == Math.abs(this.getPosition().getX() - position.getX())) {
				result = true;
			}
		}
		return result;
	}
}


text:
layout: project
bodyClass: project
title: "Denny's"
orderId: 003
builtIn: "Winter 2014"
client: "Denny's Diner"
headline: "The Grand Slams are Straight Outta America's Favorite Diner."
agency:
 - "Erwin Penland"
 - "http://www.erwinpenland.com/"
liveUrl: http://thegrandslams.com/
technologies:
  - HTML
  - SCSS
  - Javascript / jQuery
  - Expression Engine
screenshots: true
logo: true
---

Denny's is a great client of Erwin Penland's and I've been fortunate to work on quite a few proejcts of theirs. They are always a lot of fun to build and I actually find myself re-vsiting them for fun later on.

The Grand Slams existence (and success) is an agency-wide effort–a lot of people put a lot of work into adding another dimension to Denny's social presence and borderline-acceptable sense of humor. As Denny's Diner has a huge online following, our team had to be up to the challenge of providing an home for these Slams that would be as excellent as the daily content put out on Twitter and Tumblr.

A few standout features made this site fun to build. Things like a day and night CSS theme based time of day, the layered scroll effects, parallax header, and the Slams showing their faces on hover in the menu were all really nice touches that make this a site people don't mind coming back to over and over again.

The site has held up to thousands of hits a month through the first season of The Grand Slams webisodes. I look forward to seeing it grow through the anticipated season two. The Denny's faithful really love this stuff. It's fun to be a part of bringing a smile to people's faces.


text:
import constants from '../constants';
import ApiFetch from '../../../utils/fetch/ApiFetch';

/**
 * Close comments for a media
 *
 * **Dispatch**: `CLOSE_COMMENTS`
 *
 * @alias module:Comments.doCloseComments
 * @category actions
 *
 * @example
 * BetaSeries.getAction('comments', 'doCloseComments')({
 *   id: 438,
 *   type: 'show',
 * });
 *
 * @param {Object}  [obj]             Accept the following:
 * @param {Number}  [obj.id]          Media ID
 * @param {String}  [obj.type]        Media type => episode|show|member|movie
  *
 * @returns {Promise}
 */
const doCloseComments = ({ id, type }) =>
  dispatch =>
    ApiFetch.post('comments/close', {
      id,
      type
    }).then(() =>
      dispatch({
        type: constants.CLOSE_COMMENTS,
        payload: {
          id,
          type
        }
      }));

export default doCloseComments;


text: export * from "./configuration";