text:
package com.github.nikdon.telepooz.model

import java.time.Duration

/**
  * This object represents a voice note.
  *
  * @param file_id    Unique identifier for this file
  * @param duration   Duration of the audio in seconds as defined by sender
  * @param mime_type  MIME type of the file as defined by sender
  * @param file_size  File size
  */
case class Voice(file_id: String,
                 duration: Duration,
                 mime_type: String,
                 file_size: Int)

redpajama_set_name: RedPajamaGithub


text:
package tests.gameboard;

public class SetupRandomBoardTests {

}


text:
static Ihandle *inboundCheckbox, *outboundCheckbox, *kpsInput;

static volatile short capEnabled = 0,
    capInbound = 1, capOutbound = 1,
    kps = 32 / FIXED_EPSILON; // kb / second

static PacketNode capHeadNode = {0}, capTailNode = {0};
static PacketNode *bufHead = &capHeadNode, *bufTail = &capTailNode;
static int bufSize = 0;
static DWORD capLastTick = 0;

static Ihandle* capSetupUI() {
    Ihandle *capControlsBox = IupHbox(
        inboundCheckbox = IupToggle("Inbound", NULL),
        outboundCheckbox = IupToggle("Outbound", NULL),
        IupLabel("Bandwidth Cap(kb/s):"),
        kpsInput = IupText(NULL),
        NULL
        );

    IupSetCallback(inboundCheckbox, "ACTION", (Icallback)uiSyncToggle);
    IupSetAttribute(inboundCheckbox, SYNCED_VALUE, (char*)&capInbound);
    IupSetCallback(outboundCheckbox, "ACTION", (Icallback)uiSyncToggle);
    IupSetAttribute(outboundCheckbox, SYNCED_VALUE, (char*)&capOutbound);

    IupSetAttribute(kpsInput, "VISIBLECOLUMNS", "4");
    IupSetAttribute(kpsInput, "VALUE", "32.0");
    IupSetCallback(kpsInput, "VALUECHANGED_CB", (Icallback)uiSyncFixed);
    IupSetAttribute(kpsInput, SYNCED_VALUE, (char*)&kps);
    IupSetAttribute(kpsInput, FIXED_MAX, CAP_MAX);
    IupSetAttribute(kpsInput, FIXED_MIN, CAP_MIN);

    // enable by default to avoid confusing
    IupSetAttribute(inboundCheckbox, "VALUE", "ON");
    IupSetAttribute(outboundCheckbox, "VALUE", "ON");

    if (parameterized) {
        setFromParameter(inboundCheckbox, "VALUE", NAME"-inbound");
        setFromParameter(outboundCheckbox, "VALUE", NAME"-outbound");
        setFromParameter(kpsInput, "VALUE", NAME"-kps");
    }

    return capControlsBox;
}

// TODO these are exactly the same as throttle ones, try move them into packet.c
static INLINE_FUNCTION short isBufEmpty() {
    short ret = bufHead->next == bufTail;
    if (ret) assert(bufSize == 0);
    return ret;
}

static void clearBufPackets(PacketNode *tail) {
    PacketNode *oldLast = tail->prev;
    LOG("Cap end, send all %d packets. Buffer at max: %s", bufSize, bufSize);
    while (!isBufEmpty()) {
        insertAfter(popNode(bufTail->prev), oldLast);
        --bufSize;
    }
}

static void capStartUp() {
    if (bufHead->next == NULL && bufTail->next == NULL) {
        bufHead->next = bufTail;
        bufTail->prev = bufHead;
        bufSize = 0;
    } else {
        assert(isBufEmpty());
    }

    startTimePeriod();
    capLastTick = timeGetTime();
}

static void capCloseDown(PacketNode *head, PacketNode *tail) {
    UNREFERENCED_PARAMETER(head);

    clearBufPackets(tail);
    endTimePeriod();
}

static short capProcess(PacketNode *head, PacketNode *tail) {
    short capped = FALSE;
    PacketNode *pac, *pacTmp, *oldLast;
    DWORD curTick = timeGetTime();
    DWORD deltaTick = curTick - capLastTick;
    int bytesCapped = (int)(deltaTick * 0.001 * kps * FIXED_EPSILON * 1024);
    int totalBytes = 0;
    LOG("kps val: %d, capped kps %.2f, capped at %d bytes", kps, kps * FIXED_EPSILON, bytesCapped);
    capLastTick = curTick;

    // process buffered packets
    oldLast = tail->prev;
    while (!isBufEmpty()) {
        // TODO should check direction in buffer?
        // sends at least one from buffer or it would get stuck
        pac = bufTail->prev;
        totalBytes += pac->packetLen;
        insertAfter(popNode(pac), oldLast);
        --bufSize;

        LOG("sending out packets of %d bytes", totalBytes);

        if (totalBytes > bytesCapped) {
            break;
        }
    }

    // process live packets
    pac = oldLast;
    while (pac != head) {
        if (!checkDirection(pac->addr.Direction, capInbound, capOutbound)) {
            pac = pac->prev;
            continue;
        }

        // live packets can all be kept
        totalBytes += pac->packetLen;

        if (totalBytes > bytesCapped) {
            int capCnt = 0;
            capped = TRUE;
            // buffer from pac to head
            while (bufSize < KEEP_AT_MOST && pac != head) {
                pacTmp = pac->prev;
                insertAfter(popNode(pac), bufHead);
                ++bufSize;
                ++capCnt;
                pac = pacTmp;
            }

            if (pac != head) {
                LOG("! hitting cap max, dropping all remaining");
                while (pac != head) {
                    pacTmp = pac->prev;
                    freeNode(pac);
                    pac = pacTmp;
                }
            }
            assert(pac == head);
            LOG("capping %d packets", capCnt);
            break;
        } else {
            pac = pac->prev;
        }
    }

    return capped;
}

Module capModule = {
    "Cap",
    NAME,
    (short*)&capEnabled,
    capSetupUI,
    capStartUp,
    capCloseDown,
    capProcess,
    // runtime fields
    0, 0, NULL
};


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="org.xbmc.kore">

  <!-- For espresso testing purposes, this is removed in live builds, but not in dev builds -->
  <uses-permission android:name="android.permission.SET_ANIMATION_SCALE" />

</manifest>


text:
#include "App.xaml.h"
#include "OpenGLESPage.xaml.h"

using namespace cocos2d;

App::App()
{
    InitializeComponent();
}

void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
{
    if (mPage == nullptr)
    {
        mPage = ref new OpenGLESPage(&mOpenGLES);
    }

    // Place the page in the current window and ensure that it is active.
    Windows::UI::Xaml::Window::Current->Content = mPage;
    Windows::UI::Xaml::Window::Current->Activate();
}


text:
<?php

namespace App\Model\Service;

use App\Model\DomainObject\DomainObjectFactory;
use App\Model\DataMapper\DataMapperFactory;

class ServiceFactory
{
	protected $data_mapper_factory;
	protected $domain_object_factory;
	private $services_namespace;

	public function __construct(DataMapperFactory $data_mapper_factory, DomainObjectFactory $domain_object_factory)
	{
		$this->data_mapper_factory   = $data_mapper_factory;
		$this->domain_object_factory = $domain_object_factory;
		$this->services_namespace	 = "App\\Model\\Service\\";
	}

	public function get($service_name)
	{
		//normalize service name
		$service_name = ucfirst(strtolower($service_name)) . 'Service';

		//load the class
		include($service_name . '.php');

		//Create class name with namespace
		$full_class_name = $this->services_namespace . $service_name;

		if(class_exists($full_class_name)) {

			return new $full_class_name($this->data_mapper_factory, $this->domain_object_factory);
		}
		else {

			throw new \Exception("Invalid Service: {$service_name}");
		}
	}
}


text:
package cz.suky.teamtasks.android.model;

import java.util.List;

/**
 * TTodo list object
 * Created by suky on 2.6.15.
 */
public class TaskList extends AbstractModel {

    public static final String TABLE_NAME  = "TaskList";
    public static final String COLUMN_NAME = "name";

    public static final TaskList notFoundList = new TaskList("Nothing here...");

    private static final long serialVersionUID = 1;

    private String name;

    private List<TaskValue> taskValues;

    public TaskList() {

    }

    public TaskList(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public List<TaskValue> getTaskValues() {
        return taskValues;
    }

    public void setTaskValues(List<TaskValue> taskValues) {
        this.taskValues = taskValues;
    }
}


text:
from django.contrib import admin
import models

class BatchJobAdmin(admin.ModelAdmin):
	list_display = ['email', 'timestamp', 'completed', 'job']
	search_fields = ['email']
	list_filter = ['job', 'completed']
	ordering = ['-timestamp']

admin.site.register(models.BatchJob, BatchJobAdmin)
admin.site.register(models.GroupList)


text:
require 'test_helper'

describe OmfCommon::Auth::Certificate do
  before do
    OmfCommon::Auth::CertificateStore.init

    @root = OmfCommon::Auth::Certificate.create_root

    OmfCommon::Auth::CertificateStore.instance.register(@root)
  end

  after do
    OmfCommon::Auth::CertificateStore.reset
  end

  it "must create a self-signed root CA cert" do
    @root.must_be_kind_of OmfCommon::Auth::Certificate

    @root.addresses.must_be_kind_of Hash
    @root.addresses.must_equal({ email: "sa@acme.org", geni: "acme.org+authority+sa" })

    @root.subject.must_be_kind_of OpenSSL::X509::Name
    @root.subject.to_s(OpenSSL::X509::Name::RFC2253).must_equal "CN=sa,OU=Roadrunner,O=ACME,ST=CA,C=US"
    @root.key.must_be_kind_of OpenSSL::PKey::RSA
    @root.digest.must_be_kind_of OpenSSL::Digest::SHA1

    cert = @root.to_x509
    cert.must_be_kind_of OpenSSL::X509::Certificate

    # It is self signed
    cert.issuer.must_equal @root.subject
    cert.verify(cert.public_key).must_equal true
  end

  it "must create an end-entity cert using root cert" do
    lambda { @root.create_for_resource }.must_raise ArgumentError

    @entity = @root.create_for_resource('my_addr', 'my_resource')
    cert = @entity.to_x509

    cert.issuer.must_equal @root.subject
    cert.issuer.wont_equal cert.subject

    cert.issuer.to_s(OpenSSL::X509::Name::RFC2253).must_equal "CN=sa,OU=Roadrunner,O=ACME,ST=CA,C=US"
    cert.subject.to_s(OpenSSL::X509::Name::RFC2253).must_match /CN=my_addr\/type=my_resource\/uuid=.+,OU=Roadrunner,O=ACME,ST=CA,C=US/

    cert.verify(@root.to_x509.public_key).must_equal true

    @entity.verify_cert.must_equal true
  end

  it "must be verified successfully by using X509 cert store" do
    store = OpenSSL::X509::Store.new
    store.add_cert(@root.to_x509)

    @entity = @root.create_for_resource('my_addr', 'my_resource')

    store.verify(@root.to_x509).must_equal true
    store.verify(@entity.to_x509).must_equal true
  end

  it "must verify cert validity" do
    @root.verify_cert.must_equal true
    @root.create_for_resource('my_addr', :my_resource).verify_cert.must_equal true
  end

  describe "when init from an exisitng cert in pem format" do
    before do
      @private_folder = "#{File.dirname(__FILE__)}/../../fixture"
      @cert = OmfCommon::Auth::Certificate.create_from_pem(File.read("#{@private_folder}/omf_test.cert.pem"))
      @key = OpenSSL::PKey::RSA.new(File.read("#{@private_folder}/omf_test.pem"))
      @pub_key = OpenSSL::PKey::RSA.new(File.read("#{@private_folder}/omf_test.pub.pem"))
    end

    it "must verify itself" do
      # It is a self signed cert
      @cert.subject.to_s(OpenSSL::X509::Name::RFC2253).must_equal "O=Internet Widgits Pty Ltd,ST=Some-State,C=AU"
      @cert.to_x509.issuer.to_s(OpenSSL::X509::Name::RFC2253).must_equal "O=Internet Widgits Pty Ltd,ST=Some-State,C=AU"
      @cert.verify_cert.must_equal true
    end

    it "must not have pirivate key initialised"  do
      @cert.can_sign?.must_equal false
    end

    it "must have a correct public key" do
      @pub_key.public?.must_equal true
      @pub_key.private?.must_equal false
      @cert.to_x509.public_key.to_s.must_equal @pub_key.to_s
    end

    it "must have a correct private key associated" do
      @key.public?.must_equal true
      @key.private?.must_equal true
      @cert.to_x509.check_private_key(@key).must_equal true
    end
  end

  describe "when provided an existing cert with a private key attached" do
    it "must parse it into a Certificate instance correctly" do
      private_folder = "#{File.dirname(__FILE__)}/../../fixture"

      x509_cert = File.read("#{private_folder}/omf_test.cert.pem")
      priv_key = File.read("#{private_folder}/omf_test.pem")
      pub_key = File.read("#{private_folder}/omf_test.pub.pem")

      # Now create an instance using this cert
      test_entity = OmfCommon::Auth::Certificate.create_from_pem(x509_cert + priv_key)
      test_entity.to_x509.public_key.to_s.must_equal  pub_key.to_s
      test_entity.can_sign?.must_equal true
      test_entity.to_x509.check_private_key(OpenSSL::PKey::RSA.new(priv_key)).must_equal true
    end
  end
end


text:
'use strict'

var test = require('tape')
var Decoder = require('../decoder')
var Encoder = require('../encoder')

test('encoder.pipe(decoder)', function (t) {
  t.plan(5)

  var decoder = new Decoder()
  var encoder = new Encoder()

  decoder.on('request', function (req) {
    t.ok(false)
  })

  decoder.on('response', function (res) {
    t.equal(res.rtspVersion, '1.0')
    t.equal(res.statusCode, 200)
    t.equal(res.statusMessage, 'OK')
    t.deepEqual(res.headers, { 'cseq': '42', 'foo': 'Bar', 'content-length': '12' })

    var buffers = []
    res.on('data', buffers.push.bind(buffers))
    res.on('end', function () {
      var data = Buffer.concat(buffers).toString()
      t.equal(data, 'Hello World!')
    })
  })

  encoder.pipe(decoder)

  var res = encoder.response()
  res.setHeader('CSeq', 42)
  res.setHeader('Foo', 'Bar')
  res.setHeader('Content-Length', 12)
  res.write('Hello World!')
})


text:
<?php

declare(strict_types=1);

namespace StructType;

use InvalidArgumentException;
use WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for GetPeopleInsightsResponseMessageType StructType
 * @package Ews
 * @subpackage Structs
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class EwsGetPeopleInsightsResponseMessageType extends EwsResponseMessageType
{
    /**
     * The People
     * Meta information extracted from the WSDL
     * - minOccurs: 0
     * @var \ArrayType\EwsArrayOfPersonType|null
     */
    protected ?\ArrayType\EwsArrayOfPersonType $People = null;
    /**
     * Constructor method for GetPeopleInsightsResponseMessageType
     * @uses EwsGetPeopleInsightsResponseMessageType::setPeople()
     * @param \ArrayType\EwsArrayOfPersonType $people
     */
    public function __construct(?\ArrayType\EwsArrayOfPersonType $people = null)
    {
        $this
            ->setPeople($people);
    }
    /**
     * Get People value
     * @return \ArrayType\EwsArrayOfPersonType|null
     */
    public function getPeople(): ?\ArrayType\EwsArrayOfPersonType
    {
        return $this->People;
    }
    /**
     * Set People value
     * @param \ArrayType\EwsArrayOfPersonType $people
     * @return \StructType\EwsGetPeopleInsightsResponseMessageType
     */
    public function setPeople(?\ArrayType\EwsArrayOfPersonType $people = null): self
    {
        $this->People = $people;

        return $this;
    }
}


text:
@import Cocoa;

@interface ViewController : NSViewController

- (IBAction)exportHTML:(id)sender;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<fileResource exportedWithPermissions="true" dataFile="homePages_icons_sprite.png.data">
    <folder>/organizations/organization_1/themes/default/images</folder>
    <name>homePages_icons_sprite.png</name>
    <version>0</version>
    <label>homePages_icons_sprite.png</label>
    <creationDate>2015-05-27T15:05:02.196-07:00</creationDate>
    <updateDate>2015-05-27T15:05:02.196-07:00</updateDate>
    <fileType>img</fileType>
</fileResource>


text:
namespace Billing
{
    using System;
    using System.Threading;
    using NServiceBus;
    using Sales.Contracts;

    public class OrderPlacedHandler : IHandleMessages<OrderPlaced>
    {
        public IBus Bus { get; set; }

        public void Handle(OrderPlaced message)
        {
            Console.Out.WriteLine("Billing started for order");
            Thread.Sleep(5000);
            Console.Out.WriteLine("Billing complete for order");

            Bus.Publish(new OrderBilled
            {
                OrderId = message.OrderId
            });
        }
    }
}


text:
from unittest import TestCase

class TestCaseTest(TestCase):
    def getTarget(self):
        from funkload_friendly.test import TestCase

        class target(TestCase):
            log_directory = '/tmp/'
            result_directory = '/tmp/'

            def dummy(self):
                pass

        return target

    def getOne(self, *args, **kwargs):
        return self.getTarget()(*args, **kwargs)

    def test_set_session_id(self):
        """update session_id
        """
        testcase = self.getOne(methodName='dummy')
        testcase.session_id_key = 'sessionid'
        testcase.set_session_id('test_id')
        self.assertEqual(
            testcase.cookie[testcase.session_id_key],
            'test_id')

class DescriptionTest(TestCase):
    def getTarget(self):
        from funkload_friendly.test import description as target
        return target

    def test_decorate_method(self):
        """decorate instance method
        """
        description = self.getTarget()

        class Target(object):
            @description("spam description")
            def described_method(self):
                pass

        target = Target()
        self.assertEqual(
            target.described_method.description,
            "spam description")


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("app_add_not_null_column", "0001_create_table")]

    operations = [
        migrations.AddField(
            model_name="a",
            name="new_not_null_field",
            field=models.IntegerField(default=1),
            preserve_default=False,
        )
    ]


text:
import {Type, CONST_EXPR, CONST, isPresent, isBlank} from 'angular2/src/facade/lang';
import {
  RenderTemplateCmd,
  RenderCommandVisitor,
  RenderBeginElementCmd,
  RenderTextCmd,
  RenderNgContentCmd,
  RenderBeginComponentCmd,
  RenderEmbeddedTemplateCmd
} from 'angular2/src/core/render/render';

var _nextTemplateId: number = 0;

export function nextTemplateId(): number {
  return _nextTemplateId++;
}

/**
 * A compiled host template.
 *
 * This is const as we are storing it as annotation
 * for the compiled component type.
 */
@CONST()
export class CompiledHostTemplate {
  // Note: _templateGetter is a function so that CompiledHostTemplate can be
  // a const!
  constructor(private _templateGetter: Function) {}

  getTemplate(): CompiledTemplate { return this._templateGetter(); }
}

/**
 * A compiled template.
 */
export class CompiledTemplate {
  // Note: paramGetter is a function so that we can have cycles between templates!
  // paramGetter returns a tuple with:
  // - ChangeDetector factory function
  // - TemplateCmd[]
  // - styles
  constructor(public id: number,
              private _dataGetter: /*()=>Array<Function, TemplateCmd[], string[]>*/ Function) {}

  getData(appId: string): CompiledTemplateData {
    var data = this._dataGetter(appId, this.id);
    return new CompiledTemplateData(data[0], data[1], data[2]);
  }
}

export class CompiledTemplateData {
  constructor(public changeDetectorFactory: Function, public commands: TemplateCmd[],
              public styles: string[]) {}
}

const EMPTY_ARR = CONST_EXPR([]);

export interface TemplateCmd extends RenderTemplateCmd {
  visit(visitor: RenderCommandVisitor, context: any): any;
}

export class TextCmd implements TemplateCmd, RenderTextCmd {
  constructor(public value: string, public isBound: boolean, public ngContentIndex: number) {}
  visit(visitor: RenderCommandVisitor, context: any): any {
    return visitor.visitText(this, context);
  }
}

export function text(value: string, isBound: boolean, ngContentIndex: number): TextCmd {
  return new TextCmd(value, isBound, ngContentIndex);
}

export class NgContentCmd implements TemplateCmd, RenderNgContentCmd {
  isBound: boolean = false;
  constructor(public index: number, public ngContentIndex: number) {}
  visit(visitor: RenderCommandVisitor, context: any): any {
    return visitor.visitNgContent(this, context);
  }
}

export function ngContent(index: number, ngContentIndex: number): NgContentCmd {
  return new NgContentCmd(index, ngContentIndex);
}

export interface IBeginElementCmd extends TemplateCmd, RenderBeginElementCmd {
  variableNameAndValues: Array<string | number>;
  eventTargetAndNames: string[];
  directives: Type[];
  visit(visitor: RenderCommandVisitor, context: any): any;
}

export class BeginElementCmd implements TemplateCmd, IBeginElementCmd, RenderBeginElementCmd {
  constructor(public name: string, public attrNameAndValues: string[],
              public eventTargetAndNames: string[],
              public variableNameAndValues: Array<string | number>, public directives: Type[],
              public isBound: boolean, public ngContentIndex: number) {}
  visit(visitor: RenderCommandVisitor, context: any): any {
    return visitor.visitBeginElement(this, context);
  }
}

export function beginElement(name: string, attrNameAndValues: string[],
                             eventTargetAndNames: string[],
                             variableNameAndValues: Array<string | number>, directives: Type[],
                             isBound: boolean, ngContentIndex: number): BeginElementCmd {
  return new BeginElementCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues,
                             directives, isBound, ngContentIndex);
}

export class EndElementCmd implements TemplateCmd {
  visit(visitor: RenderCommandVisitor, context: any): any {
    return visitor.visitEndElement(context);
  }
}

export function endElement(): TemplateCmd {
  return new EndElementCmd();
}

export class BeginComponentCmd implements TemplateCmd, IBeginElementCmd, RenderBeginComponentCmd {
  isBound: boolean = true;
  templateId: number;
  constructor(public name: string, public attrNameAndValues: string[],
              public eventTargetAndNames: string[],
              public variableNameAndValues: Array<string | number>, public directives: Type[],
              public nativeShadow: boolean, public ngContentIndex: number,
              public template: CompiledTemplate) {
    this.templateId = template.id;
  }
  visit(visitor: RenderCommandVisitor, context: any): any {
    return visitor.visitBeginComponent(this, context);
  }
}

export function beginComponent(
    name: string, attrNameAnsValues: string[], eventTargetAndNames: string[],
    variableNameAndValues: Array<string | number>, directives: Type[], nativeShadow: boolean,
    ngContentIndex: number, template: CompiledTemplate): BeginComponentCmd {
  return new BeginComponentCmd(name, attrNameAnsValues, eventTargetAndNames, variableNameAndValues,
                               directives, nativeShadow, ngContentIndex, template);
}

export class EndComponentCmd implements TemplateCmd {
  visit(visitor: RenderCommandVisitor, context: any): any {
    return visitor.visitEndComponent(context);
  }
}

export function endComponent(): TemplateCmd {
  return new EndComponentCmd();
}

export class EmbeddedTemplateCmd implements TemplateCmd, IBeginElementCmd,
    RenderEmbeddedTemplateCmd {
  isBound: boolean = true;
  name: string = null;
  eventTargetAndNames: string[] = EMPTY_ARR;
  constructor(public attrNameAndValues: string[], public variableNameAndValues: string[],
              public directives: Type[], public isMerged: boolean, public ngContentIndex: number,
              public changeDetectorFactory: Function, public children: TemplateCmd[]) {}
  visit(visitor: RenderCommandVisitor, context: any): any {
    return visitor.visitEmbeddedTemplate(this, context);
  }
}

export function embeddedTemplate(attrNameAndValues: string[], variableNameAndValues: string[],
                                 directives: Type[], isMerged: boolean, ngContentIndex: number,
                                 changeDetectorFactory: Function,
                                 children: TemplateCmd[]): EmbeddedTemplateCmd {
  return new EmbeddedTemplateCmd(attrNameAndValues, variableNameAndValues, directives, isMerged,
                                 ngContentIndex, changeDetectorFactory, children);
}

export interface CommandVisitor extends RenderCommandVisitor {
  visitText(cmd: TextCmd, context: any): any;
  visitNgContent(cmd: NgContentCmd, context: any): any;
  visitBeginElement(cmd: BeginElementCmd, context: any): any;
  visitEndElement(context: any): any;
  visitBeginComponent(cmd: BeginComponentCmd, context: any): any;
  visitEndComponent(context: any): any;
  visitEmbeddedTemplate(cmd: EmbeddedTemplateCmd, context: any): any;
}

export function visitAllCommands(visitor: CommandVisitor, cmds: TemplateCmd[],
                                 context: any = null) {
  for (var i = 0; i < cmds.length; i++) {
    cmds[i].visit(visitor, context);
  }
}


text:
package org.apache.hc.client5.http.impl.classic;

import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.StandardMethods;
import org.apache.hc.client5.http.classic.ExecChain;
import org.apache.hc.client5.http.classic.ExecRuntime;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.DecompressingEntity;
import org.apache.hc.client5.http.entity.GzipDecompressingEntity;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class TestContentCompressionExec {

    @Mock
    private ExecRuntime execRuntime;
    @Mock
    private ExecChain execChain;
    @Mock
    private ClassicHttpRequest originaRequest;

    private HttpClientContext context;
    private HttpHost host;
    private ExecChain.Scope scope;
    private ContentCompressionExec impl;

    @Before
    public void setup() {
        host = new HttpHost("somehost", 80);
        context = HttpClientContext.create();
        scope = new ExecChain.Scope("test", new HttpRoute(host), originaRequest, execRuntime, context);
        impl = new ContentCompressionExec();
    }

    @Test
    public void testContentEncodingNoEntity() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);

        final HttpEntity entity = response.getEntity();
        Assert.assertNull(entity);
    }

    @Test
    public void testNoContentEncoding() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
        final StringEntity original = new StringEntity("plain stuff");
        response.setEntity(original);

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);

        final HttpEntity entity = response.getEntity();
        Assert.assertNotNull(entity);
        Assert.assertTrue(entity instanceof StringEntity);
    }

    @Test
    public void testGzipContentEncoding() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
        final StringEntity original = new StringEntity("encoded stuff");
        original.setContentEncoding("GZip");
        response.setEntity(original);

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);

        final HttpEntity entity = response.getEntity();
        Assert.assertNotNull(entity);
        Assert.assertTrue(entity instanceof DecompressingEntity);
    }

    @Test
    public void testGzipContentEncodingZeroLength() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
        final StringEntity original = new StringEntity("");
        original.setContentEncoding("GZip");
        response.setEntity(original);

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);

        final HttpEntity entity = response.getEntity();
        Assert.assertNotNull(entity);
        Assert.assertTrue(entity instanceof StringEntity);
    }

    @Test
    public void testXGzipContentEncoding() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
        final StringEntity original = new StringEntity("encoded stuff");
        original.setContentEncoding("x-gzip");
        response.setEntity(original);

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);

        final HttpEntity entity = response.getEntity();
        Assert.assertNotNull(entity);
        Assert.assertTrue(entity instanceof DecompressingEntity);
    }

    @Test
    public void testDeflateContentEncoding() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
        final StringEntity original = new StringEntity("encoded stuff");
        original.setContentEncoding("deFlaTe");
        response.setEntity(original);

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);

        final HttpEntity entity = response.getEntity();
        Assert.assertNotNull(entity);
        Assert.assertTrue(entity instanceof DecompressingEntity);
    }

    @Test
    public void testIdentityContentEncoding() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
        final StringEntity original = new StringEntity("encoded stuff");
        original.setContentEncoding("identity");
        response.setEntity(original);

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);

        final HttpEntity entity = response.getEntity();
        Assert.assertNotNull(entity);
        Assert.assertTrue(entity instanceof StringEntity);
    }

    @Test(expected=HttpException.class)
    public void testUnknownContentEncoding() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
        final StringEntity original = new StringEntity("encoded stuff");
        original.setContentEncoding("whatever");
        response.setEntity(original);

        impl = new ContentCompressionExec(false);

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);
    }

    @Test
    public void testContentEncodingRequestParameter() throws Exception {
        final ClassicHttpRequest request = new BasicClassicHttpRequest(StandardMethods.GET.name(), host, "/");
        final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
        final StringEntity original = new StringEntity("encoded stuff");
        original.setContentEncoding("GZip");
        response.setEntity(original);

        final RequestConfig config = RequestConfig.custom()
                .setContentCompressionEnabled(false)
                .build();

        context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);

        Mockito.when(execChain.proceed(request, scope)).thenReturn(response);

        impl.execute(request, scope, execChain);

        final HttpEntity entity = response.getEntity();
        Assert.assertNotNull(entity);
        Assert.assertFalse(entity instanceof GzipDecompressingEntity);
    }

}


text:
ActiveRecord::Schema.define(:version => 20110228064239) do

  create_table "products", :force => true do |t|
    t.string   "name"
    t.decimal  "price"
    t.datetime "released_at"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "versions", :force => true do |t|
    t.string   "item_type",  :null => false
    t.integer  "item_id",    :null => false
    t.string   "event",      :null => false
    t.string   "whodunnit"
    t.text     "object"
    t.datetime "created_at"
  end

  add_index "versions", ["item_type", "item_id"], :name => "index_versions_on_item_type_and_item_id"

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<body bgcolor="white">
<p>
Aranea JSP tags that render Uilib FormElements in a way that one or many of
these can be selected at a time.
</p>
</body>
</html>


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

package com.google.api.ads.dfp.appengine.fetcher;

import com.google.api.ads.dfp.appengine.util.Channels;
import com.google.api.ads.dfp.jaxws.factory.DfpServices;
import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception;
import com.google.api.ads.dfp.jaxws.v201403.LineItemCreativeAssociationServiceInterface;
import com.google.api.ads.dfp.jaxws.v201403.Statement;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.inject.Inject;

/**
 * A class to make API requests to fetch line item creative association entities.
 *
 * @author Jeff Sham
 */
public class LineItemCreativeAssociationFetcher extends AbstractFetcher {

  @Inject
  public LineItemCreativeAssociationFetcher(
      DfpServices dfpServices, Channels channels) {
    super(dfpServices, channels);
  }

  public void fetch(String filterText, String channelKey, String tag, String requestId,
      DfpSession session) {
    // Create the service.
    final LineItemCreativeAssociationServiceInterface lineItemCreativeAssociationService =
        dfpServices.get(session, LineItemCreativeAssociationServiceInterface.class);

    // Create the page fetcher.
    PageFetcher pageFetcher = new PageFetcher() {

      public Object getByStatement(Statement statement) throws ApiException_Exception {
        return lineItemCreativeAssociationService.getLineItemCreativeAssociationsByStatement(
            statement);
      }
    };
    // Fetch the objects.
    fetchObjects(filterText, channelKey, tag, requestId, pageFetcher);
  }
}


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

'use strict';

/**
 * @fileoverview This file generates the code for ParseTrees.js based on a JSON
 * file, which gets passed in on the command line.
 */

var fs = require('fs');
var util = require('./util.js');
var print = console.log.bind(console);

util.printLicense();
util.printAutoGenerated();

print("import {ParseTree} from './ParseTree';");
print("module ParseTreeType from './ParseTreeType';");

// export var ARGUMENT_LIST = 'ARGUMENT_LIST';
var data = fs.readFileSync(process.argv[2], 'utf-8');
var trees = util.parseJSON(data);

function getType(types) {
  return types.join('|');
}

function printInitialiser(name) {
  print('    this.%s = %s;', name, name);
}

var names = Object.keys(trees);

names.forEach(function(name) {
  var treeTypeName = util.toConstantName(name);
  var paramNames = Object.keys(trees[name]);
  // var params = trees[name];
  // var paramNames = params.map(function(p) { return p.name; });
  print();
  print('var %s = ParseTreeType.%s;', treeTypeName, treeTypeName);
  print('export class %s extends ParseTree {', name);
  print('  /**');
  paramNames.forEach(function(paramName) {
    var types = trees[name][paramName];
    print('   * @param {%s} %s', getType(types), paramName);
  });
  print('   */');
  print('  constructor(%s) {', paramNames.join(', '));
  paramNames.forEach(printInitialiser);
  print('  }');
  print();
  print('  /**');
  print('   * @param {ParseTreeTransformer} transformer');
  print('   */');
  print('  transform(transformer) {');
  print('    return transformer.transform%s(this);', name);
  print('  }');
  print();
  print('  /**');
  print('   * @param {ParseTreeVisitor} visitor');
  print('   */');
  print('  visit(visitor) {');
  print('    visitor.visit%s(this);', name);
  print('  }');
  print();
  print('  /**');
  print('   * @type {ParseTreeType}');
  print('   */');
  print('  get type() {');
  print('    return %s;', treeTypeName);
  print('  }');
  print('}');
});


text:
require 'rspec'
require 'webrick'
require 'em-http-request'
require 'responder'
require 'logger'

RSpec.configure do |config|
  config.order = 'random'

  config.before(:suite) do
    trap(:INT) { EM.stop }
    trap(:TERM){ EM.stop }
    Thread.new do
      Rack::Handler::WEBrick.run(
        Responder.new,
        :Port => 6701,
        :AccessLog => [],
        :Logger => WEBrick::Log::new("/dev/null", 7))
    end
    sleep 3
  end

end


text:
package com.alburivan.slickform.animators;

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.ProgressBar;

/**
 * Created by Ivan on 5/19/2016 based on http://stackoverflow.com/questions/8035682/animate-progressbar-update-in-android
 */
public class ProgressBarAnimation extends Animation {

    private ProgressBar progressBar;
    private float from;
    private float  to;

    public ProgressBarAnimation(ProgressBar progressBar, float from, float to) {
        super();
        this.progressBar = progressBar;
        this.from = from;
        this.to = to;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        float value = from + (to - from) * interpolatedTime;
        progressBar.setProgress((int) value);
    }

}


text: Yeoman generator includes gulp, express, mongoose and socket.io


text:
package com.github.thomasfischl.eurydome.backend.service;

import java.util.List;

import javax.inject.Inject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.github.thomasfischl.eurydome.backend.dal.TaskDataStore;
import com.github.thomasfischl.eurydome.backend.model.DOTask;
import com.github.thomasfischl.eurydome.backend.task.AbstractTask;
import com.github.thomasfischl.eurydome.backend.task.StepDefinition;

@Service
public class TaskService implements ApplicationContextAware {

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

  private ApplicationContext ctx;

  @Inject
  private TaskDataStore taskDataStore;

  @Override
  public void setApplicationContext(ApplicationContext ctx) throws BeansException {
    this.ctx = ctx;
  }

  @Scheduled(fixedDelay = 5000)
  public void execute() {
    if (!taskDataStore.isConnected()) {
      return;
    }

    List<DOTask> tasks = taskDataStore.findAll();

    for (DOTask task : tasks) {
      if (!task.isCompleted()) {
        executeTask(task);
      }
    }
  }

  public void executeTask(DOTask task) {
    AbstractTask taskInstance;
    try {
      taskInstance = ctx.getBean(task.getTaskType(), AbstractTask.class);
    } catch (BeansException e) {
      LOG.error("Can't find task with name '" + task.getTaskType() + "'.", e);
      task.addLogOutput("Can't find task with name '" + task.getTaskType() + "'.");
      task.setStatus(DOTask.STATUS_FAILED);
      taskDataStore.save(task);
      return;
    }
    taskInstance.prepare(task);
    List<StepDefinition> steps = taskInstance.getSteps();

    int totalStepCount = steps.size();
    task.setTotalSteps(totalStepCount);
    task.setStep(0);
    task.setStatus(DOTask.STATUS_RUNNING);
    taskDataStore.save(task);

    taskInstance.begin();

    int step = 1;
    for (StepDefinition stepDefinition : steps) {
      try {
        taskDataStore.reload(task);
        task.setStep(step);
        task.setStepName(stepDefinition.getName());
        task.addLogOutput("Execute Step " + step + ": " + stepDefinition.getName());
        taskDataStore.save(task);

        stepDefinition.getTask().run();
        step++;
      } catch (Exception e) {
        LOG.error("Error occurs during execution step '" + step + ": " + stepDefinition.getName() + "'.", e);
        taskDataStore.reload(task);
        task.addLogOutput(e.getMessage());
        task.setStatus(DOTask.STATUS_FAILED);
        taskDataStore.save(task);
        taskInstance.completeWithError(e.getMessage());
        return;
      }
    }

    taskInstance.complete();
  }
}


text:
package com.epam.ta.reportportal.ws.model.externalsystem;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * Basic class for accessible data
 * //TODO: AV - refactor to support polymorphism
 *
 * @author Andrei_Ramanchuk
 */
@JsonInclude(Include.NON_NULL)
public class Authentic {

	@JsonProperty(value = "username")
	private String username;

	@JsonProperty(value = "password")
	private String password;

	@JsonProperty(value = "domain")
	private String domain;

	@JsonProperty(value = "token")
	private String token;

	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}

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

	public String getUsername() {
		return username;
	}

	public void setPassword(String pass) {
		this.password = pass;
	}

	public String getPassword() {
		return password;
	}

	public void setToken(String value) {
		this.token = value;
	}

	public String getToken() {
		return token;
	}

	@Override
	public String toString() {
		final StringBuilder sb = new StringBuilder("Authentic{");
		sb.append("username='").append(username).append('\'');
		sb.append(", password='").append(password).append('\''); //NOSONAR
		sb.append(", token='").append(token).append('\'');
		sb.append('}');
		return sb.toString();
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
  Class: AutomationObject::State::ElementProxy

    — Documentation by YARD 0.9.9

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" charset="utf-8" />

    Index (E) »
    AutomationObject » State
     »
    ElementProxy

        <svg width="24" height="24">
          <rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
        </svg>

Class: AutomationObject::State::ElementProxy

Inherits:

      Proxy::Proxy

Object

Proxy::Proxy

AutomationObject::State::ElementProxy

        show all

Defined in:

lib/automation_object/state/element_proxy.rb

Overview

Proxy class to allow for usage of hooks

      Instance Method Summary
      collapse

      #initialize(composite, element)  ⇒ ElementProxy

    constructor

A new instance of ElementProxy.

      #method_missing(method_symbol, *args, &block)  ⇒ Object

Overiding base method to run possible hooks.

      #respond_to_missing?(method, include_private = false)  ⇒ Boolean

Constructor Details

    #initialize(composite, element)  ⇒ <tt>ElementProxy</tt>

Returns a new instance of ElementProxy

9
10
11
12

# File 'lib/automation_object/state/element_proxy.rb', line 9

def initialize(composite, element)
  @composite = composite
  @subject = element
end

Dynamic Method Handling

    This class handles dynamic methods through the <tt>method_missing</tt> method

    #method_missing(method_symbol, *args, &block)  ⇒ <tt>Object</tt>

Overiding base method to run possible hooks

15
16
17
18
19
20
21
22
23
24
25

# File 'lib/automation_object/state/element_proxy.rb', line 15

def method_missing(method_symbol, *args, &block)
  # Run before hook if needed
  @composite.method_hooks[method_symbol].before if @composite.method_hook?(method_symbol)

  subject_return = @subject.send(method_symbol, *args, &block)

  # Run after hook if needed
  @composite.method_hooks[method_symbol].after if @composite.method_hook?(method_symbol)

  subject_return
end

Instance Method Details

    #respond_to_missing?(method, include_private = false)  ⇒ <tt>Boolean</tt>

Returns:

        (<tt>Boolean</tt>)

27
28
29

# File 'lib/automation_object/state/element_proxy.rb', line 27

def respond_to_missing?(method, include_private = false)
  @subject.respond_to_missing?(method, include_private)
end

  Generated on Sun Jul 16 19:31:28 2017 by
  yard
  0.9.9 (ruby-2.3.1).


text:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://www.zeroturnaround.com/alderaan/rebel-2_0.xsd">

	<classpath>
		<dir name="/Users/trademakers/Documents/github/Activiti/modules/activiti-webapp-rest2/target/classes">
		</dir>
	</classpath>

	<web>
		<link target="/">
			<dir name="/Users/trademakers/Documents/github/Activiti/modules/activiti-webapp-rest2/src/main/webapp">
			</dir>
		</link>
	</web>

</application>


text:
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password simplepass'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password simplepass'

apt-get update
apt-get install -y mysql-server

sudo sed -i 's/127.0.0.1/0.0.0.0/g' /etc/mysql/my.cnf

mysql -u root --password="simplepass" <<< "use mysql; GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'simplepass'; FLUSH PRIVILEGES;"
mysql -u root --password="simplepass" <<< "CREATE SCHEMA yii2basic"

sudo service mysql restart


text:
package ninja.eivind.hotsreplayuploader.files.tempwatcher;

import javafx.application.Platform;
import ninja.eivind.hotsreplayuploader.HotsReplayUploaderTest;
import ninja.eivind.hotsreplayuploader.services.platform.PlatformService;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import rules.JavaFXThreadingRule;

import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.function.Consumer;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@HotsReplayUploaderTest
public class RecursiveTempWatcherTest {

    private static final Logger logger = LoggerFactory.getLogger(RecursiveTempWatcherTest.class);
    @Rule
    public JavaFXThreadingRule rule = new JavaFXThreadingRule();
    @Autowired
    private PlatformService platformService;
    private RecursiveTempWatcher tempWatcher;
    private BattleLobbyTempDirectories directories;

    @Before
    public void setUp() throws Exception {
        directories = platformService.getBattleLobbyTempDirectories();
        if (!(directories.getRoot().exists() || directories.getRoot().mkdirs())) {
            fail("Could not create tmp root");
        }

        // give file creation some time to complete
        Thread.sleep(250);

        tempWatcher = new RecursiveTempWatcher(directories);

        CountDownLatch latch = new CountDownLatch(1);
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                tempWatcher.start();
                latch.countDown();
            }
        });
        if (!latch.await(1, TimeUnit.SECONDS)) {
            fail("Service did not start.");
        }
        // give watchers some time to wind up
        Thread.sleep(250);
    }

    @Test
    public void testSetCallbackIsAppliedProperly() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        tempWatcher.setCallback(file -> latch.countDown());
        TempWatcher lastChild = getChildRecursively(tempWatcher);
        Consumer<File> callback = lastChild.getCallback();

        callback.accept(null);

        if (!latch.await(500, TimeUnit.MILLISECONDS)) {
            throw new TimeoutException("Latch was not tripped.");
        }
    }

    @Test
    public void testCallbackIsInvokedWhenRelevantFileIsDiscovered() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        final File[] fileAccessor = new File[1];
        final File tempWriteReplayFolder = new File(directories.getRemainder(), "TempWriteReplayP99");
        final File target = new File(tempWriteReplayFolder, BattleLobbyWatcher.REPLAY_SERVER_BATTLELOBBY);

        tempWatcher.setCallback(file -> {
            fileAccessor[0] = file;
            latch.countDown();
        });

        if (!(tempWriteReplayFolder.mkdirs() && target.createNewFile())) {
            fail("Could not create file to drop target " + target + " in");
        }

        long stopAt = System.currentTimeMillis() + 50_000;
        while (latch.getCount() != 0) {
            if (System.currentTimeMillis() > stopAt) {
                fail("Latch was not tripped");
            }
            Thread.sleep(1_000);
        }

        final String expected = target.getName();
        final String actual = fileAccessor[0].getName();

        assertEquals(expected, actual);
    }

    private TempWatcher getChildRecursively(RecursiveTempWatcher tempWatcher) {
        TempWatcher child = tempWatcher.getChild();
        //noinspection InstanceofConcreteClass
        if (child instanceof RecursiveTempWatcher) {
            return getChildRecursively((RecursiveTempWatcher) child);
        }
        return tempWatcher;
    }

    @Test
    public void testGetChildCount() throws Exception {
        final File remainder = directories.getRemainder();
        if (!remainder.mkdirs()) {
            fail("Failed to create files.");
        }

        final String rootString = directories.getRoot().toString();
        final String remainderString = remainder.toString();
        final String difference = remainderString.replace(rootString, "").substring(1);

        final String remainderRegex = tempWatcher.getRemainderRegex();

        logger.info("Remainder string: {}", remainderString);
        logger.info("Root string: {}", rootString);
        logger.info("Difference string: {}", difference);
        logger.info("Splitting using regex string: {}", remainderRegex);
        final int expected = difference.split(remainderRegex).length;
        final int actual = tempWatcher.getChildCount();

        assertSame(String.format("Expecting %d children for tempwatcher", expected), expected, actual);
    }

    @After
    public void tearDown() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        Platform.runLater(() -> {
            if (tempWatcher.cancel()) {
                latch.countDown();
            }
        });
        if (!latch.await(1, TimeUnit.SECONDS)) {
            fail("Service failed to stop");
        }
        // give watchers some time to wind down recursively
        Thread.sleep(1000L);
        cleanupRecursive(directories.getRoot());
    }

    private void cleanupRecursive(File file) throws InterruptedException {
        File[] children = file.listFiles();
        for (File child : children != null ? children : new File[0]) {
            cleanupRecursive(child);
        }
        if (file.exists() && !file.delete()) {
            fail("Failed to clean up file " + file);
        }

        // give io some time to complete
        Thread.sleep(250);
    }
}


text:
#include "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h"

btEmptyAlgorithm::btEmptyAlgorithm(const btCollisionAlgorithmConstructionInfo& ci)
	: btCollisionAlgorithm(ci)
{
}

void btEmptyAlgorithm::processCollision (btCollisionObject* ,btCollisionObject* ,const btDispatcherInfo& ,btManifoldResult* )
{
}

btScalar btEmptyAlgorithm::calculateTimeOfImpact(btCollisionObject* ,btCollisionObject* ,const btDispatcherInfo& ,btManifoldResult* )
{
	return btScalar(1.);
}


text:
<?php

define('PGV_SCRIPT_NAME', 'uploadmedia.php');
require './config.php';
require_once PGV_ROOT.'includes/functions/functions_mediadb.php';

/**
 * This functions checks if an existing directory is physically writeable
 * The standard PHP function only checks for the R/O attribute and doesn't
 * detect authorisation by ACL.
 */
function dir_is_writable($dir) {
	$err_write = false;
	$handle = @fopen(filename_decode($dir."x.y"),"w+");
	if	($handle) {
		$i = fclose($handle);
		$err_write = true;
		@unlink(filename_decode($dir."x.y"));
	}
	return($err_write);
}

if (!PGV_USER_CAN_EDIT) {
	header("Location: login.php?url=uploadmedia.php");
	exit;
}

print_header($pgv_lang["upload_media"]);
?>

<?php
print "".UTF8_strtoupper($pgv_lang["upload_media"])."

\n";
$action = safe_POST('action');
if ($action == "upload") {
	process_uploadMedia_form();
}

// Check if Media Directory is writeable or if Media features are enabled
// If one of these is not true then do not continue
if (!dir_is_writable($MEDIA_DIRECTORY) || !$MULTI_MEDIA) {
	print "";
	print $pgv_lang["no_upload"];
	print "
";
} else {
	show_mediaUpload_form('uploadmedia.php', false);		// We have the green light to upload media, print the form
}
print_footer();
?>


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

<title>Uses of Interface java.sql.ResultSet (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
java.sql.ResultSet

Packages that use ResultSet

Package
Description

java.sql

Provides the API for accessing and processing data stored in a
data source (usually a relational database) using the
JavaTM programming language.

javax.sql

Provides the API for server side data source access and processing from
the JavaTM programming language.

javax.sql.rowset

Standard interfaces and base classes for JDBC RowSet
implementations.

javax.sql.rowset.serial

Provides utility classes to allow serializable mappings between SQL types
and data types in the Java programming language.

javax.sql.rowset.spi

The standard classes and interfaces that a third party vendor has to
use in its implementation of a synchronization provider.

Uses of ResultSet in java.sql

Methods in java.sql that return ResultSet

Modifier and Type
Method and Description

ResultSet
PreparedStatement.executeQuery()

Executes the SQL query in this PreparedStatement object
 and returns the ResultSet object generated by the query.

ResultSet
Statement.executeQuery(String sql)

Executes the given SQL statement, which returns a single
 ResultSet object.

ResultSet
DatabaseMetaData.getAttributes(String catalog,
             String schemaPattern,
             String typeNamePattern,
             String attributeNamePattern)

Retrieves a description of the given attribute of the given type
 for a user-defined type (UDT) that is available in the given schema
 and catalog.

ResultSet
DatabaseMetaData.getBestRowIdentifier(String catalog,
                    String schema,
                    String table,
                    int scope,
                    boolean nullable)

Retrieves a description of a table's optimal set of columns that
 uniquely identifies a row.

ResultSet
DatabaseMetaData.getCatalogs()

Retrieves the catalog names available in this database.

ResultSet
DatabaseMetaData.getClientInfoProperties()

Retrieves a list of the client info properties
 that the driver supports.

ResultSet
DatabaseMetaData.getColumnPrivileges(String catalog,
                   String schema,
                   String table,
                   String columnNamePattern)

Retrieves a description of the access rights for a table's columns.

ResultSet
DatabaseMetaData.getColumns(String catalog,
          String schemaPattern,
          String tableNamePattern,
          String columnNamePattern)

Retrieves a description of table columns available in
 the specified catalog.

ResultSet
DatabaseMetaData.getCrossReference(String parentCatalog,
                 String parentSchema,
                 String parentTable,
                 String foreignCatalog,
                 String foreignSchema,
                 String foreignTable)

Retrieves a description of the foreign key columns in the given foreign key
 table that reference the primary key or the columns representing a unique constraint of the  parent table (could be the same or a different table).

ResultSet
DatabaseMetaData.getExportedKeys(String catalog,
               String schema,
               String table)

Retrieves a description of the foreign key columns that reference the
 given table's primary key columns (the foreign keys exported by a
 table).

ResultSet
DatabaseMetaData.getFunctionColumns(String catalog,
                  String schemaPattern,
                  String functionNamePattern,
                  String columnNamePattern)

Retrieves a description of the given catalog's system or user
 function parameters and return type.

ResultSet
DatabaseMetaData.getFunctions(String catalog,
            String schemaPattern,
            String functionNamePattern)

Retrieves a description of the  system and user functions available
 in the given catalog.

ResultSet
Statement.getGeneratedKeys()

Retrieves any auto-generated keys created as a result of executing this
 Statement object.

ResultSet
DatabaseMetaData.getImportedKeys(String catalog,
               String schema,
               String table)

Retrieves a description of the primary key columns that are
 referenced by the given table's foreign key columns (the primary keys
 imported by a table).

ResultSet
DatabaseMetaData.getIndexInfo(String catalog,
            String schema,
            String table,
            boolean unique,
            boolean approximate)

Retrieves a description of the given table's indices and statistics.

ResultSet
DatabaseMetaData.getPrimaryKeys(String catalog,
              String schema,
              String table)

Retrieves a description of the given table's primary key columns.

ResultSet
DatabaseMetaData.getProcedureColumns(String catalog,
                   String schemaPattern,
                   String procedureNamePattern,
                   String columnNamePattern)

Retrieves a description of the given catalog's stored procedure parameter
 and result columns.

ResultSet
DatabaseMetaData.getProcedures(String catalog,
             String schemaPattern,
             String procedureNamePattern)

Retrieves a description of the stored procedures available in the given
 catalog.

ResultSet
DatabaseMetaData.getPseudoColumns(String catalog,
                String schemaPattern,
                String tableNamePattern,
                String columnNamePattern)

Retrieves a description of the pseudo or hidden columns available
 in a given table within the specified catalog and schema.

ResultSet
Array.getResultSet()

Retrieves a result set that contains the elements of the SQL
 ARRAY value
 designated by this Array object.

ResultSet
Statement.getResultSet()

Retrieves the current result as a ResultSet object.

ResultSet
Array.getResultSet(long index,
            int count)

Retrieves a result set holding the elements of the subarray that
 starts at index index and contains up to
 count successive elements.

ResultSet
Array.getResultSet(long index,
            int count,
            Map<String,Class<?>> map)

Retrieves a result set holding the elements of the subarray that
 starts at index index and contains up to
 count successive elements.

ResultSet
Array.getResultSet(Map<String,Class<?>> map)

Retrieves a result set that contains the elements of the SQL
 ARRAY value designated by this Array object.

ResultSet
DatabaseMetaData.getSchemas()

Retrieves the schema names available in this database.

ResultSet
DatabaseMetaData.getSchemas(String catalog,
          String schemaPattern)

Retrieves the schema names available in this database.

ResultSet
DatabaseMetaData.getSuperTables(String catalog,
              String schemaPattern,
              String tableNamePattern)

Retrieves a description of the table hierarchies defined in a particular
 schema in this database.

ResultSet
DatabaseMetaData.getSuperTypes(String catalog,
             String schemaPattern,
             String typeNamePattern)

Retrieves a description of the user-defined type (UDT) hierarchies defined in a
 particular schema in this database.

ResultSet
DatabaseMetaData.getTablePrivileges(String catalog,
                  String schemaPattern,
                  String tableNamePattern)

Retrieves a description of the access rights for each table available
 in a catalog.

ResultSet
DatabaseMetaData.getTables(String catalog,
         String schemaPattern,
         String tableNamePattern,
         String[] types)

Retrieves a description of the tables available in the given catalog.

ResultSet
DatabaseMetaData.getTableTypes()

Retrieves the table types available in this database.

ResultSet
DatabaseMetaData.getTypeInfo()

Retrieves a description of all the data types supported by
 this database.

ResultSet
DatabaseMetaData.getUDTs(String catalog,
       String schemaPattern,
       String typeNamePattern,
       int[] types)

Retrieves a description of the user-defined types (UDTs) defined
 in a particular schema.

ResultSet
DatabaseMetaData.getVersionColumns(String catalog,
                 String schema,
                 String table)

Retrieves a description of a table's columns that are automatically
 updated when any value in a row is updated.

Uses of ResultSet in javax.sql

Subinterfaces of ResultSet in javax.sql

Modifier and Type
Interface and Description

interface
RowSet

The interface that adds support to the JDBC API for the
 JavaBeans™ component model.

Methods in javax.sql that return ResultSet

Modifier and Type
Method and Description

ResultSet
RowSetInternal.getOriginal()

Retrieves a ResultSet object containing the original
 value of this RowSet object.

ResultSet
RowSetInternal.getOriginalRow()

Retrieves a ResultSet object containing the original value
 of the current row only.

Uses of ResultSet in javax.sql.rowset

Subinterfaces of ResultSet in javax.sql.rowset

Modifier and Type
Interface and Description

interface
CachedRowSet

The interface that all standard implementations of
 CachedRowSet must implement.

interface
FilteredRowSet

The standard interface that all standard implementations of
 FilteredRowSet must implement.

interface
JdbcRowSet

The standard interface that all standard implementations of
 JdbcRowSet must implement.

interface
JoinRowSet

The JoinRowSet interface provides a mechanism for combining related
 data from different RowSet objects into one JoinRowSet
 object, which represents an SQL JOIN.

interface
WebRowSet

The standard interface that all implementations of a WebRowSet
 must implement.

Methods in javax.sql.rowset that return ResultSet

Modifier and Type
Method and Description

ResultSet
CachedRowSet.getOriginal()

Returns a ResultSet object containing the original value of this
 CachedRowSet object.

ResultSet
CachedRowSet.getOriginalRow()

Returns a ResultSet object containing the original value for the
 current row only of this CachedRowSet object.

Methods in javax.sql.rowset with parameters of type ResultSet

Modifier and Type
Method and Description

void
CachedRowSet.populate(ResultSet data)

Populates this CachedRowSet object with data from
 the given ResultSet object.

void
CachedRowSet.populate(ResultSet rs,
        int startRow)

Populates this CachedRowSet object with data from
 the given ResultSet object.

void
WebRowSet.writeXml(ResultSet rs,
        OutputStream oStream)

Populates this WebRowSet object with
 the contents of the given ResultSet object and writes its
 data, properties, and metadata
 to the given OutputStream object in XML format.

void
WebRowSet.writeXml(ResultSet rs,
        Writer writer)

Populates this WebRowSet object with
 the contents of the given ResultSet object and writes its
 data, properties, and metadata
 to the given Writer object in XML format.

Uses of ResultSet in javax.sql.rowset.serial

Methods in javax.sql.rowset.serial that return ResultSet

Modifier and Type
Method and Description

ResultSet
SerialArray.getResultSet()

Retrieves a ResultSet object that contains all of
 the elements in the ARRAY value that this
 SerialArray object represents.

ResultSet
SerialArray.getResultSet(long index,
            int count)

Retrieves a ResultSet object holding the elements of
 the subarray that starts at
 index index and contains up to count successive elements.

ResultSet
SerialArray.getResultSet(long index,
            int count,
            Map<String,Class<?>> map)

Retrieves a result set holding the elements of the subarray that starts at
 Retrieves a ResultSet object that contains a subarray of the
 elements in this SerialArray object, starting at
 index index and containing up to count successive
 elements.

ResultSet
SerialArray.getResultSet(Map<String,Class<?>> map)

Retrieves a ResultSet object that contains all of
 the elements of the SQL ARRAY
 value represented by this SerialArray object.

Uses of ResultSet in javax.sql.rowset.spi

Subinterfaces of ResultSet in javax.sql.rowset.spi

Modifier and Type
Interface and Description

interface
SyncResolver

Defines a framework that allows applications to use a manual decision tree
 to decide what should be done when a synchronization conflict occurs.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
package com.cloud.hypervisor.kvm.resource.wrapper;

import java.net.URISyntaxException;

import org.apache.log4j.Logger;
import org.libvirt.Connect;
import org.libvirt.DomainInfo.DomainState;
import org.libvirt.LibvirtException;

import com.cloud.agent.api.Answer;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
import com.cloud.exception.InternalErrorException;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef;
import com.cloud.hypervisor.kvm.resource.LibvirtKvmAgentHook;
import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
import com.cloud.network.Networks.TrafficType;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.ResourceWrapper;
import com.cloud.vm.VirtualMachine;

@ResourceWrapper(handles =  StartCommand.class)
public final class LibvirtStartCommandWrapper extends CommandWrapper<StartCommand, Answer, LibvirtComputingResource> {

    private static final Logger s_logger = Logger.getLogger(LibvirtStartCommandWrapper.class);

    @Override
    public Answer execute(final StartCommand command, final LibvirtComputingResource libvirtComputingResource) {
        final VirtualMachineTO vmSpec = command.getVirtualMachine();
        vmSpec.setVncAddr(command.getHostIp());
        final String vmName = vmSpec.getName();
        LibvirtVMDef vm = null;

        DomainState  state = DomainState.VIR_DOMAIN_SHUTOFF;
        final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        Connect conn = null;
        try {

            vm = libvirtComputingResource.createVMFromSpec(vmSpec);
            conn = libvirtUtilitiesHelper.getConnectionByType(vm.getHvsType());

            final NicTO[] nics = vmSpec.getNics();

            for (final NicTO nic : nics) {
                if (vmSpec.getType() != VirtualMachine.Type.User) {
                    nic.setPxeDisable(true);
                }
            }

            libvirtComputingResource.createVbd(conn, vmSpec, vmName, vm);

            if (!storagePoolMgr.connectPhysicalDisksViaVmSpec(vmSpec)) {
                return new StartAnswer(command, "Failed to connect physical disks to host");
            }

            libvirtComputingResource.createVifs(vmSpec, vm);

            s_logger.debug("starting " + vmName + ": " + vm.toString());
            String vmInitialSpecification = vm.toString();
            String vmFinalSpecification = performXmlTransformHook(vmInitialSpecification, libvirtComputingResource);
            libvirtComputingResource.startVM(conn, vmName, vmFinalSpecification);
            performAgentStartHook(vmName, libvirtComputingResource);

            libvirtComputingResource.applyDefaultNetworkRules(conn, vmSpec, false);

            // pass cmdline info to system vms
            if (vmSpec.getType() != VirtualMachine.Type.User) {
                String controlIp = null;
                for (final NicTO nic : vmSpec.getNics()) {
                    if (nic.getType() == TrafficType.Control) {
                        controlIp = nic.getIp();
                        break;
                    }
                }
                // try to patch and SSH into the systemvm for up to 5 minutes
                for (int count = 0; count < 10; count++) {
                    // wait and try passCmdLine for 30 seconds at most for CLOUDSTACK-2823
                    if (libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs())) {
                        break;
                    }
                }

                final VirtualRoutingResource virtRouterResource = libvirtComputingResource.getVirtRouterResource();
                // check if the router is up?
                for (int count = 0; count < 60; count++) {
                    final boolean result = virtRouterResource.connect(controlIp, 1, 5000);
                    if (result) {
                        break;
                    }
                }
            }

            state = DomainState.VIR_DOMAIN_RUNNING;
            return new StartAnswer(command);
        } catch (final LibvirtException e) {
            s_logger.warn("LibvirtException ", e);
            if (conn != null) {
                libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
            }
            return new StartAnswer(command, e.getMessage());
        } catch (final InternalErrorException e) {
            s_logger.warn("InternalErrorException ", e);
            if (conn != null) {
                libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
            }
            return new StartAnswer(command, e.getMessage());
        } catch (final URISyntaxException e) {
            s_logger.warn("URISyntaxException ", e);
            if (conn != null) {
                libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
            }
            return new StartAnswer(command, e.getMessage());
        } finally {
            if (state != DomainState.VIR_DOMAIN_RUNNING) {
                storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vmSpec);
            }
        }
    }

    private void performAgentStartHook(String vmName, LibvirtComputingResource libvirtComputingResource) {
        try {
            LibvirtKvmAgentHook onStartHook = libvirtComputingResource.getStartHook();
            onStartHook.handle(vmName);
        } catch (Exception e) {
            s_logger.warn("Exception occurred when handling LibVirt VM onStart hook: {}", e);
        }
    }

    private String performXmlTransformHook(String vmInitialSpecification, final LibvirtComputingResource libvirtComputingResource) {
        String vmFinalSpecification;
        try {
            // if transformer fails, everything must go as it's just skipped.
            LibvirtKvmAgentHook t = libvirtComputingResource.getTransformer();
            vmFinalSpecification = (String) t.handle(vmInitialSpecification);
            if (null == vmFinalSpecification) {
                s_logger.warn("Libvirt XML transformer returned NULL, will use XML specification unchanged.");
                vmFinalSpecification = vmInitialSpecification;
            }
        } catch(Exception e) {
            s_logger.warn("Exception occurred when handling LibVirt XML transformer hook: {}", e);
            vmFinalSpecification = vmInitialSpecification;
        }
        return vmFinalSpecification;
    }
}


text:
package com.squareup.okhttp;

import com.squareup.okhttp.internal.RecordingHostnameVerifier;
import com.squareup.okhttp.internal.SslContextBuilder;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import com.squareup.okhttp.mockwebserver.SocketPolicy;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public final class SyncApiTest {
  private MockWebServer server = new MockWebServer();
  private OkHttpClient client = new OkHttpClient();

  private static final SSLContext sslContext = SslContextBuilder.localhost();
  private HttpResponseCache cache;

  @Before public void setUp() throws Exception {
    String tmp = System.getProperty("java.io.tmpdir");
    File cacheDir = new File(tmp, "HttpCache-" + UUID.randomUUID());
    cache = new HttpResponseCache(cacheDir, Integer.MAX_VALUE);
  }

  @After public void tearDown() throws Exception {
    server.shutdown();
    cache.delete();
  }

  @Test public void get() throws Exception {
    server.enqueue(new MockResponse()
        .setBody("abc")
        .addHeader("Content-Type: text/plain"));
    server.play();

    Request request = new Request.Builder()
        .url(server.getUrl("/"))
        .header("User-Agent", "SyncApiTest")
        .build();

    onSuccess(request)
        .assertCode(200)
        .assertContainsHeaders("Content-Type: text/plain")
        .assertBody("abc");

    assertTrue(server.takeRequest().getHeaders().contains("User-Agent: SyncApiTest"));
  }

  @Test public void connectionPooling() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));
    server.enqueue(new MockResponse().setBody("ghi"));
    server.play();

    onSuccess(new Request.Builder().url(server.getUrl("/a")).build())
        .assertBody("abc");

    onSuccess(new Request.Builder().url(server.getUrl("/b")).build())
        .assertBody("def");

    onSuccess(new Request.Builder().url(server.getUrl("/c")).build())
        .assertBody("ghi");

    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(1, server.takeRequest().getSequenceNumber());
    assertEquals(2, server.takeRequest().getSequenceNumber());
  }

  @Test public void tls() throws Exception {
    server.useHttps(sslContext.getSocketFactory(), false);
    server.enqueue(new MockResponse()
        .setBody("abc")
        .addHeader("Content-Type: text/plain"));
    server.play();

    client.setSslSocketFactory(sslContext.getSocketFactory());
    client.setHostnameVerifier(new RecordingHostnameVerifier());

    onSuccess(new Request.Builder().url(server.getUrl("/")).build())
        .assertHandshake();
  }

  @Test public void recoverFromTlsHandshakeFailure() throws Exception {
    SSLSocketFactory socketFactory = new LimitedProtocolsSocketFactory(
        sslContext.getSocketFactory(), "TLSv1", "SSLv3");
    server.useHttps(socketFactory, false);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
    server.enqueue(new MockResponse().setBody("abc"));
    server.play();

    final boolean disableTlsFallbackScsv = true;
    SSLSocketFactory clientSocketFactory =
        new FallbackTestClientSocketFactory(socketFactory, disableTlsFallbackScsv);
    client.setSslSocketFactory(clientSocketFactory);
    client.setHostnameVerifier(new RecordingHostnameVerifier());

    onSuccess(new Request.Builder().url(server.getUrl("/")).build())
        .assertBody("abc");
  }

  @Test public void post() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.play();

    Request request = new Request.Builder()
        .url(server.getUrl("/"))
        .post(Request.Body.create(MediaType.parse("text/plain"), "def"))
        .build();

    onSuccess(request)
        .assertCode(200)
        .assertBody("abc");

    RecordedRequest recordedRequest = server.takeRequest();
    assertEquals("def", recordedRequest.getUtf8Body());
    assertEquals("3", recordedRequest.getHeader("Content-Length"));
    assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
  }

  @Test public void conditionalCacheHit() throws Exception {
    server.enqueue(new MockResponse().setBody("A").addHeader("ETag: v1"));
    server.enqueue(new MockResponse()
        .clearHeaders()
        .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
    server.play();

    client.setOkResponseCache(cache);

    onSuccess(new Request.Builder().url(server.getUrl("/")).build())
        .assertCode(200).assertBody("A");
    assertNull(server.takeRequest().getHeader("If-None-Match"));

    onSuccess(new Request.Builder().url(server.getUrl("/")).build())
        .assertCode(200).assertBody("A");
    assertEquals("v1", server.takeRequest().getHeader("If-None-Match"));
  }

  @Test public void conditionalCacheMiss() throws Exception {
    server.enqueue(new MockResponse().setBody("A").addHeader("ETag: v1"));
    server.enqueue(new MockResponse().setBody("B"));
    server.play();

    client.setOkResponseCache(cache);

    onSuccess(new Request.Builder().url(server.getUrl("/")).build())
        .assertCode(200).assertBody("A");
    assertNull(server.takeRequest().getHeader("If-None-Match"));

    onSuccess(new Request.Builder().url(server.getUrl("/")).build())
        .assertCode(200).assertBody("B");
    assertEquals("v1", server.takeRequest().getHeader("If-None-Match"));
  }

  @Test public void redirect() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(301)
        .addHeader("Location: /b")
        .addHeader("Test", "Redirect from /a to /b")
        .setBody("/a has moved!"));
    server.enqueue(new MockResponse()
        .setResponseCode(302)
        .addHeader("Location: /c")
        .addHeader("Test", "Redirect from /b to /c")
        .setBody("/b has moved!"));
    server.enqueue(new MockResponse().setBody("C"));
    server.play();

    onSuccess(new Request.Builder().url(server.getUrl("/a")).build())
        .assertCode(200)
        .assertBody("C")
        .redirectedBy()
        .assertCode(302)
        .assertContainsHeaders("Test: Redirect from /b to /c")
        .redirectedBy()
        .assertCode(301)
        .assertContainsHeaders("Test: Redirect from /a to /b");

    assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
    assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reused.
    assertEquals(2, server.takeRequest().getSequenceNumber()); // Connection reused again!
  }

  @Test public void redirectWithRedirectsDisabled() throws Exception {
    client.setFollowProtocolRedirects(false);
    server.enqueue(new MockResponse()
        .setResponseCode(301)
        .addHeader("Location: /b")
        .addHeader("Test", "Redirect from /a to /b")
        .setBody("/a has moved!"));
    server.play();

    onSuccess(new Request.Builder().url(server.getUrl("/a")).build())
        .assertCode(301)
        .assertBody("/a has moved!")
        .assertContainsHeaders("Location: /b");
  }

  @Test public void follow20Redirects() throws Exception {
    for (int i = 0; i < 20; i++) {
      server.enqueue(new MockResponse()
          .setResponseCode(301)
          .addHeader("Location: /" + (i + 1))
          .setBody("Redirecting to /" + (i + 1)));
    }
    server.enqueue(new MockResponse().setBody("Success!"));
    server.play();

    onSuccess(new Request.Builder().url(server.getUrl("/0")).build())
        .assertCode(200)
        .assertBody("Success!");
  }

  @Test public void doesNotFollow21Redirects() throws Exception {
    for (int i = 0; i < 21; i++) {
      server.enqueue(new MockResponse()
          .setResponseCode(301)
          .addHeader("Location: /" + (i + 1))
          .setBody("Redirecting to /" + (i + 1)));
    }
    server.play();

    try {
      client.execute(new Request.Builder().url(server.getUrl("/0")).build());
      fail();
    } catch (IOException e) {
      assertEquals("Too many redirects: 21", e.getMessage());
    }
  }

  @Test public void postBodyRetransmittedOnRedirect() throws Exception {
    server.enqueue(new MockResponse()
        .setResponseCode(302)
        .addHeader("Location: /b")
        .setBody("Moved to /b !"));
    server.enqueue(new MockResponse()
        .setBody("This is b."));
    server.play();

    Request request = new Request.Builder()
        .url(server.getUrl("/"))
        .post(Request.Body.create(MediaType.parse("text/plain"), "body!"))
        .build();

    onSuccess(request)
        .assertCode(200)
        .assertBody("This is b.");

    RecordedRequest request1 = server.takeRequest();
    assertEquals("body!", request1.getUtf8Body());
    assertEquals("5", request1.getHeader("Content-Length"));
    assertEquals("text/plain; charset=utf-8", request1.getHeader("Content-Type"));
    assertEquals(0, request1.getSequenceNumber());

    RecordedRequest request2 = server.takeRequest();
    assertEquals("body!", request2.getUtf8Body());
    assertEquals("5", request2.getHeader("Content-Length"));
    assertEquals("text/plain; charset=utf-8", request2.getHeader("Content-Type"));
    assertEquals(1, request2.getSequenceNumber());
  }

  private RecordedResponse onSuccess(Request request) throws IOException {
    Response response = client.execute(request);
    return new RecordedResponse(request, response, response.body().string(), null);
  }
}


text:
#pragma once
#include <stdio.h>
/* Either optimize for memory usage or CPU usage */
#ifndef MEMORY_OPTIMIZE
 #if CPU_OPTIMIZE
  #define MEMORY_OPTIMIZE 0
 #else
  #define MEMORY_OPTIMIZE 1
 #endif
#endif

#ifndef CPU_OPTIMIZE
 #if MEMORY_OPTIMIZE
  #define CPU_OPTIMIZE 0
 #else
  #define CPU_OPTIMIZE 1
 #endif
#endif

/* If both MEMORY_OPTIMIZE and CPU_OPTIMIZE are set, default to only MEMORY_OPTIMIZE */
#if MEMORY_OPTIMIZE
 #if CPU_OPTIMIZE
  #error "Can not optimize for both CPU and Memory. Defaulting to Memory Optimization"
  #undef CPU_OPTIMIZE
  #define CPU_OPTIMIZE 0
 #endif
#endif

void *xmalloc( size_t size );
void *xcalloc( size_t count, size_t size );
void xfree( void *ptr );
void *xrealloc( void *ptr, size_t size );