text:
make_this_a_slider = function(slider_container_id) {
    var slider_container = document.getElementById(slider_container_id);
    var arrows_holder = jQuery('

')
    var slide_right = jQuery('
»');
    var slide_left = jQuery('
«');

    var slider = new Swipe(slider_container, {
        callback: function(event, index, elem) {
            arrows_holder.find('li').removeClass('selected');
            arrows_holder.find('.slider_story_' + slider.index).addClass('selected');
            slide_right.removeClass('disabled');
            slide_left.removeClass('disabled');
            if (slider.index === 0) {
                slide_left.addClass('disabled')
            } else if (slider.index === (slider.length - 1)) {
                slide_right.addClass('disabled')
            }
        }
    });

    for (var i = 0; i < slider.length; i++) {
        var slide_dot = jQuery('

');
        slide_dot.addClass('slider_story_' + i);
        (function(i) {
            slide_dot.bind('click', function() {
                slider.slide(i);
            })
        })(i);
        if (i === 0) { slide_dot.addClass('selected'); }
        arrows_holder.append(slide_dot);
    }

    slide_right.bind('click', function() {
        if (!jQuery(this).hasClass('disabled')) {
            slider.next();
        }
    });
    arrows_holder.append(slide_right);
    slide_left.bind('click', function() {
        if (!jQuery(this).hasClass('disabled')) {
            slider.prev();
        }
    });
    arrows_holder.prepend(slide_left);

    var total_holder_lis = slider.length + 2;
    var slider_dot_width = Math.floor(100 / total_holder_lis) + '%';
    /*
    arrows_holder.find('li').each(function() {
        jQuery(this).css('width', slider_dot_width);
    });
    */

    jQuery('#' + slider_container_id).after(arrows_holder);
}


text:
<?php
namespace Mvc\View;
class View
{
    public static function render($data)
    {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package sbt.internal.util

import sbt.internal.util.codec.JsonProtocol._
import sbt.util._
import scala.reflect.runtime.universe.TypeTag
import sjsonnew.JsonFormat

private[sbt] trait MiniLogger {
  def log[T](level: Level.Value, message: ObjectEvent[T]): Unit
  def log(level: Level.Value, message: => String): Unit
}

/**
 * Delegates log events to the associated LogExchange.
 */
class ManagedLogger(
    val name: String,
    val channelName: Option[String],
    val execId: Option[String],
    xlogger: MiniLogger,
    terminal: Option[Terminal],
    private[sbt] val context: LoggerContext,
) extends Logger {
  def this(
      name: String,
      channelName: Option[String],
      execId: Option[String],
      xlogger: MiniLogger
  ) =
    this(name, channelName, execId, xlogger, None, LoggerContext.globalContext)
  override def trace(t: => Throwable): Unit =
    logEvent(Level.Error, TraceEvent("Error", t, channelName, execId))
  override def log(level: Level.Value, message: => String): Unit =
    xlogger.log(level, message)

  // send special event for success since it's not a real log level
  override def success(message: => String): Unit = {
    if (terminal.fold(true)(_.isSuccessEnabled)) {
      infoEvent[SuccessEvent](SuccessEvent(message))(
        implicitly[JsonFormat[SuccessEvent]],
        StringTypeTag.fast[SuccessEvent],
      )
    }
  }

  def registerStringCodec[A: ShowLines: StringTypeTag]: Unit = {
    LogExchange.registerStringCodec[A]
  }

  @deprecated("Use macro-powered StringTypeTag.fast instead", "1.4.0")
  final def debugEvent[A](event: => A, f: JsonFormat[A], t: TypeTag[A]): Unit =
    debugEvent(event)(f, StringTypeTag.apply(t))
  @deprecated("Use macro-powered StringTypeTag.fast instead", "1.4.0")
  final def infoEvent[A](event: => A, f: JsonFormat[A], t: TypeTag[A]): Unit =
    infoEvent(event)(f, StringTypeTag.apply(t))
  @deprecated("Use macro-powered StringTypeTag.fast instead", "1.4.0")
  final def warnEvent[A](event: => A, f: JsonFormat[A], t: TypeTag[A]): Unit =
    warnEvent(event)(f, StringTypeTag.apply(t))
  @deprecated("Use macro-powered StringTypeTag.fast instead", "1.4.0")
  final def errorEvent[A](event: => A, f: JsonFormat[A], t: TypeTag[A]): Unit =
    errorEvent(event)(f, StringTypeTag.apply(t))

  final def debugEvent[A: JsonFormat: StringTypeTag](event: => A): Unit =
    logEvent(Level.Debug, event)
  final def infoEvent[A: JsonFormat: StringTypeTag](event: => A): Unit = logEvent(Level.Info, event)
  final def warnEvent[A: JsonFormat: StringTypeTag](event: => A): Unit = logEvent(Level.Warn, event)
  final def errorEvent[A: JsonFormat: StringTypeTag](event: => A): Unit =
    logEvent(Level.Error, event)
  @deprecated("Use macro-powered StringTypeTag.fast instead", "1.4.0")
  def logEvent[A](level: Level.Value, event: => A, f: JsonFormat[A], t: TypeTag[A]): Unit =
    logEvent(level, event)(f, StringTypeTag.apply(t))
  def logEvent[A: JsonFormat](level: Level.Value, event: => A)(
      implicit tag: StringTypeTag[A]
  ): Unit = {
    val v: A = event
    // println("logEvent " + tag.key)
    val entry: ObjectEvent[A] = ObjectEvent(level, v, channelName, execId, tag.key)
    xlogger.log(level, entry)
  }

  @deprecated("No longer used.", "1.0.0")
  override def ansiCodesSupported = ConsoleAppender.formatEnabledInEnv
}


text:
#ifndef InjectedBundleHitTestResult_h
#define InjectedBundleHitTestResult_h

#include "APIObject.h"
#include <WebCore/HitTestResult.h>
#include <wtf/Forward.h>
#include <wtf/PassRefPtr.h>
#include <wtf/RefPtr.h>

namespace WebKit {

class InjectedBundleNodeHandle;
class WebFrame;

class InjectedBundleHitTestResult : public APIObject {
public:
    static const Type APIType = TypeBundleHitTestResult;

    static PassRefPtr<InjectedBundleHitTestResult> create(const WebCore::HitTestResult&);

    const WebCore::HitTestResult& coreHitTestResult() const { return m_hitTestResult; }

    PassRefPtr<InjectedBundleNodeHandle> nodeHandle() const;
    WebFrame* frame() const;
    WebFrame* targetFrame() const;

    String absoluteImageURL() const;
    String absoluteLinkURL() const;
    String absoluteMediaURL() const;

    String linkLabel() const;
    String linkTitle() const;

    WebCore::IntRect imageRect() const;

    bool isSelected() const;

private:
    explicit InjectedBundleHitTestResult(const WebCore::HitTestResult& hitTestResult)
        : m_hitTestResult(hitTestResult)
    {
    }

    virtual Type type() const { return APIType; }

    WebCore::HitTestResult m_hitTestResult;
};

} // namespace WebKit

#endif // InjectedBundleHitTestResult_h


text:
require 'spec_helper'

class DummyShippingCalculator < Spree::ShippingCalculator
end

describe Spree::ShippingMethod, type: :model do
  # Regression test for https://github.com/spree/spree/issues/4492
  context "#shipments" do
    let!(:shipping_method) { create(:shipping_method) }
    let!(:shipment) do
      shipment = create(:shipment)
      shipment.shipping_rates.create!(shipping_method: shipping_method)
      shipment
    end

    it "can gather all the related shipments" do
      expect(shipping_method.shipments).to include(shipment)
    end
  end

  context "validations" do
    before { subject.valid? }

    it "validates presence of name" do
      expect(subject.error_on(:name).size).to eq(1)
    end

    context "shipping category" do
      it "validates presence of at least one" do
        expect(subject.error_on(:base).size).to eq(1)
      end

      context "one associated" do
        before { subject.shipping_categories.push create(:shipping_category) }
        it { expect(subject.error_on(:base).size).to eq(0) }
      end
    end
  end

  context "generating tracking URLs" do
    context "shipping method has a tracking URL mask on file" do
      let(:tracking_url) { "https://track-o-matic.com/:tracking" }
      before { allow(subject).to receive(:tracking_url) { tracking_url } }

      context 'tracking number has spaces' do
        let(:tracking_numbers) { ["1234 5678 9012 3456", "a bcdef"] }
        let(:expectations) { %w[https://track-o-matic.com/1234%205678%209012%203456 https://track-o-matic.com/a%20bcdef] }

        it "should return a single URL with '%20' in lieu of spaces" do
          tracking_numbers.each_with_index do |num, i|
            expect(subject.build_tracking_url(num)).to eq(expectations[i])
          end
        end
      end
    end
  end

  # Regression test for https://github.com/spree/spree/issues/4320
  context "soft deletion" do
    let(:shipping_method) { create(:shipping_method) }
    it "soft-deletes when destroy is called" do
      shipping_method.destroy
      expect(shipping_method.deleted_at).not_to be_blank
    end
  end

  describe ".with_all_shipping_category_ids" do
    let(:category1) { create(:shipping_category) }
    let(:category2) { create(:shipping_category) }

    def matching(categories)
      described_class.with_all_shipping_category_ids(categories.map(&:id))
    end

    context "with one associated shipping category" do
      let!(:shipping_method) { create(:shipping_method, shipping_categories: [category1]) }

      it "should match the associated category" do
        expect(matching([category1])).to eq [shipping_method]
      end

      it "should not match the other category" do
        expect(matching([category2])).to be_empty
      end

      it "should not match both categories" do
        expect(matching([category1, category2])).to be_empty
      end

      context "with additional joins" do
        before do
          shipping_method.zones << create(:zone)
        end
        it "should not match both categories" do
          result =
            described_class.
            joins(:zones).
            with_all_shipping_category_ids([category1.id, category2.id])
          expect(result).to be_empty
        end
      end
    end

    context "with two associated shipping categories" do
      let!(:shipping_method) { create(:shipping_method, shipping_categories: [category1, category2]) }

      it "should match the associated category" do
        expect(matching([category1])).to eq [shipping_method]
      end

      it "should match both categories" do
        expect(matching([category1, category2])).to eq [shipping_method]
      end
    end

    context "with several shipping methods" do
      let!(:shipping_method1) { create(:shipping_method, shipping_categories: [category1]) }
      let!(:shipping_method2) { create(:shipping_method, shipping_categories: [category1, category2]) }
      let!(:shipping_method3) { create(:shipping_method, shipping_categories: [category2]) }

      it "matches correctly" do
        expect(matching([category1])).to match_array [shipping_method1, shipping_method2]
      end
    end
  end

  describe ".available_in_stock_location" do
    let!(:stock_location) { create :stock_location }
    let!(:other_stock_location) { create :stock_location }

    subject { described_class.available_in_stock_location(stock_location) }

    context "when available_to_all" do
      let!(:shipping_method) { create(:shipping_method, available_to_all: true) }

      it "returns the shipping_method" do
        is_expected.to eq [shipping_method]
      end
    end

    context "when in stock location" do
      let!(:shipping_method) { create(:shipping_method, available_to_all: false, stock_locations: [stock_location]) }

      it "returns the shipping_method" do
        is_expected.to eq [shipping_method]
      end
    end

    context "when available_to_all and in stock location" do
      let!(:shipping_method) { create(:shipping_method, available_to_all: true, stock_locations: [stock_location]) }

      it "returns the shipping_method" do
        is_expected.to eq [shipping_method]
      end
    end

    context "when in no stock locations" do
      let!(:shipping_method) { create(:shipping_method, available_to_all: false) }

      it "returns no results" do
        is_expected.to be_empty
      end
    end

    context "when in another stock location" do
      let!(:shipping_method) { create(:shipping_method, available_to_all: false, stock_locations: [other_stock_location]) }

      it "returns no results" do
        is_expected.to be_empty
      end
    end

    context "when available_to_all and in another stock location" do
      let!(:shipping_method) { create(:shipping_method, available_to_all: true, stock_locations: [other_stock_location]) }

      it "returns the shipping_method" do
        is_expected.to eq [shipping_method]
      end
    end

    context "when multiple shipping methods match" do
      let!(:shipping_method1) { create(:shipping_method, available_to_all: true, stock_locations: [other_stock_location]) }
      let!(:shipping_method2) { create(:shipping_method, available_to_all: false, stock_locations: [stock_location]) }
      let!(:shipping_method3) { create(:shipping_method, available_to_all: false, stock_locations: [other_stock_location]) }

      it "returns both matching shipping_methods" do
        is_expected.to match_array([shipping_method1, shipping_method2])
      end
    end
  end

  describe ".available_for_address" do
    let!(:included_country) { create(:country, iso: "US") }
    let!(:excluded_country) { create(:country, iso: "CA") }
    let!(:included_zone) { create(:zone, countries: [included_country]) }
    let!(:excluded_zone) { create(:zone, countries: [excluded_country]) }
    let!(:shipping_method) { create(:shipping_method, zones: [included_zone]) }

    let(:matches) { described_class.available_for_address(address) }
    subject { matches }

    context "address included in zone" do
      let!(:address) { create(:address, country_iso_code: 'US') }

      it { is_expected.to include(shipping_method) }
    end

    context "address included other zone" do
      let!(:address) { create(:address, country_iso_code: 'CA') }
      it { is_expected.to_not include(shipping_method) }
    end
  end

  describe "display_on=" do
    subject do
      Spree::Deprecation.silence do
        described_class.new(display_on: display_on).available_to_users
      end
    end

    context "with 'back_end'" do
      let(:display_on) { 'back_end' }
      it { should be false }
    end

    context "with 'both'" do
      let(:display_on) { 'both' }
      it { should be true }
    end

    context "with 'front_end'" do
      let(:display_on) { 'front_end' }
      it { should be true }
    end
  end

  describe "display_on" do
    subject do
      Spree::Deprecation.silence do
        described_class.new(available_to_users: available_to_users).display_on
      end
    end

    context "when available_to_users is true" do
      let(:available_to_users) { true }
      it { should == 'both' }
    end

    context "when available_to_users is false" do
      let(:available_to_users) { false }
      it { should == 'back_end' }
    end
  end
end


text:
A open source automatic build of OpenCV

````
docker pull kevinsimper/opencv
```

More information about here

https://hub.docker.com/r/kevinsimper/opencv/


text:
[CmdletBinding(DefaultParameterSetName = 'None')]
param
(
[String]
$env:SYSTEM_DEFINITIONID,
[String]
$env:BUILD_BUILDID,

[String] [Parameter(Mandatory = $false)]
$connectedServiceName,

[String] [Parameter(Mandatory = $false)]
$TestSettings,
[String] [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()]
$TestDrop,
[String] [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()]
$LoadTest,
[String]
$ThresholdLimit,
[String] [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()]
$MachineType
)

#Set the userAgent appropriately based on whether the task is running as part of a ci or cd
if($Env:SYSTEM_HOSTTYPE -ieq "build") {
    $userAgent = "CloudLoadTestBuildTask"
}
else {
    $userAgent = "CloudLoadTestReleaseTask"
}
$global:apiVersion = "api-version=1.0"
$global:ScopedTestDrop = $TestDrop
$global:RunTestSettingsFile = $TestSettings
$ThresholdExceeded = $false
$MonitorThresholds = $false

function InitializeRestHeaders()
{
	$restHeaders = New-Object -TypeName "System.Collections.Generic.Dictionary[[String], [String]]"
	if([string]::IsNullOrWhiteSpace($connectedServiceName))
	{
		$patToken = Get-AccessToken $connectedServiceDetails
		ValidatePatToken $patToken
		$restHeaders.Add("Authorization", [String]::Concat("Bearer ", $patToken))

	}
	else
	{
		$Username = $connectedServiceDetails.Authorization.Parameters.Username
		Write-Verbose "Username = $Username" -Verbose
		$Password = $connectedServiceDetails.Authorization.Parameters.Password
		$alternateCreds = [String]::Concat($Username, ":", $Password)
		$basicAuth = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($alternateCreds))
		$restHeaders.Add("Authorization", [String]::Concat("Basic ", $basicAuth))
	}
	return $restHeaders
}

function Get-AccessToken($vssEndPoint)
{
	return $vssEndpoint.Authorization.Parameters.AccessToken
}

function ValidatePatToken($token)
{
	if([string]::IsNullOrWhiteSpace($token))
	{
		throw "Unable to generate Personal Access Token for the user. Contact Project Collection Administrator"
	}
}

# Load all dependent files for execution
. $PSScriptRoot/CltTasksUtility.ps1
. $PSScriptRoot/VssConnectionHelper.ps1

############################################## PS Script execution starts here ##########################################
WriteTaskMessages "Starting Load Test Script"

import-module "Microsoft.TeamFoundation.DistributedTask.Task.Internal"
import-module "Microsoft.TeamFoundation.DistributedTask.Task.Common"
import-module "Microsoft.TeamFoundation.DistributedTask.Task.DTA"
import-module "Microsoft.TeamFoundation.DistributedTask.Task.DevTestLabs"

Write-Output "Test settings = $TestSettings"
Write-Output "Test drop = $TestDrop"
Write-Output "Load test = $LoadTest"
Write-Output "Load generator machine type = $MachineType"
Write-Output "Run source identifier = build/$env:SYSTEM_DEFINITIONID/$env:BUILD_BUILDID"

#Validate Input
ValidateInputs $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI $connectedServiceName $TestSettings $TestDrop $LoadTest

#Setting monitoring of Threshold rule appropriately
if ($ThresholdLimit -and $ThresholdLimit -ge 0)
{
	$MonitorThresholds = $true
	Write-Output "Threshold limit = $ThresholdLimit"
}

#Initialize Connected Service Details
if([string]::IsNullOrWhiteSpace($connectedServiceName))
{
	$connectedServiceDetails = Get-ServiceEndpoint -Context $distributedTaskContext -Name SystemVssConnection
}
else
{
	$connectedServiceDetails = Get-ServiceEndpoint -Context $distributedTaskContext -Name $connectedServiceName
}

$VSOAccountUrl = $connectedServiceDetails.Url.AbsoluteUri
Write-Output "VSO Account URL is : $VSOAccountUrl"
$headers = InitializeRestHeaders
$CltAccountUrl = ComposeAccountUrl $VSOAccountUrl $headers
$TFSAccountUrl = $env:System_TeamFoundationCollectionUri.TrimEnd('/')

Write-Output "TFS account Url = $TFSAccountUrl" -Verbose
Write-Output "CLT account Url = $CltAccountUrl" -Verbose

#Upload the test drop
$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
$drop = CreateTestDrop $headers $CltAccountUrl

if ($drop.dropType -eq "TestServiceBlobDrop")
{
	$drop = GetTestDrop $headers $drop $CltAccountUrl
	Write-Output "Test Drop Source Location: $global:ScopedTestDrop"
	UploadTestDrop $drop $global:ScopedTestDrop
	WriteTaskMessages ("Uploading test files took {0}. Queuing the test run." -f $($elapsed.Elapsed.ToString()))

	#Queue the test run
	$runJson = ComposeTestRunJson $LoadTest $drop.id $MachineType

	$run = QueueTestRun $headers $runJson $CltAccountUrl
	MonitorAcquireResource $headers $run $CltAccountUrl

	#Monitor the test run
	$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
	$thresholdExceeded = MonitorTestRun $headers $run $CltAccountUrl $MonitorThresholds
	WriteTaskMessages ( "Run execution took {0}. Collecting results." -f $($elapsed.Elapsed.ToString()))

	#Print the error and messages
	$run = GetTestRun $headers $run.id $CltAccountUrl
	ShowMessages $headers $run $CltAccountUrl
	$thresholdsViolatedCount = PrintErrorSummary $headers $run $CltAccountUrl $MonitorThresholds

	if ($run.state -ne "completed")
	{
		Write-Error "Load test has failed. Please check error messages to fix the problem."
	}
	elseif ($thresholdExceeded -eq $true)
	{
		Write-Error "Load test task is marked as failed, as the number of threshold errors has exceeded permissible limit."
	}
	else
	{
		WriteTaskMessages "The load test completed successfully."
	}

	$run = GetTestRun $headers $run.id $CltAccountUrl
	$webResultsUri = $run.WebResultUrl

	Write-Output ("Run-id for this load test is {0} and its name is '{1}'." -f  $run.runNumber, $run.name)
	Write-Output ("To view run details navigate to {0}" -f $webResultsUri)
	Write-Output "To view detailed results navigate to Load Test | Load Test Manager in Visual Studio IDE, and open this run."

	$resultsMDFolder = New-Item -ItemType Directory -Force -Path "$env:Temp\LoadTestResultSummary"
	$resultFilePattern = ("CloudLoadTestResults_{0}_{1}_*.md" -f $env:AGENT_ID, $env:SYSTEM_DEFINITIONID)
	$excludeFilePattern = ("CloudLoadTestResults_{0}_{1}_{2}_*.md" -f $env:AGENT_ID, $env:SYSTEM_DEFINITIONID, $env:BUILD_BUILDID)
	Remove-Item $resultsMDFolder\$resultFilePattern -Exclude $excludeFilePattern -Force
	$summaryFile =  ("{0}\CloudLoadTestResults_{1}_{2}_{3}_{4}.md" -f $resultsMDFolder, $env:AGENT_ID, $env:SYSTEM_DEFINITIONID, $env:BUILD_BUILDID, $run.id)

	if ($thresholdExceeded -eq $true)
	{
		$thresholdMessage=("{0} thresholds violated." -f $thresholdsViolatedCount)
		$thresholdImage="bowtie-status-error"
		$thresholdImageLabel="Error"
	}
	elseif ($thresholdsViolatedCount -gt 1)
	{
		$thresholdMessage=("{0} thresholds violated." -f $thresholdsViolatedCount)
		$thresholdImage="bowtie-status-warning"
		$thresholdImageLabel="Warning"
	}
	elseif ($thresholdsViolatedCount -eq 1)
	{
		$thresholdMessage=("{0} threshold violated." -f $thresholdsViolatedCount)
		$thresholdImage="bowtie-status-warning"
		$thresholdImageLabel="Warning"
	}
	else
	{
		$thresholdMessage="No thresholds violated."
		$thresholdImage="bowtie-status-success"
		$thresholdImageLabel="Success"
	}

	$summary = ('   {4}
[Test Run: {0}]({1}) using {2}.
' -f  $run.runNumber, $webResultsUri , $run.name, $thresholdImage, $thresholdMessage, $thresholdImageLabel)
	('
{0}
' -f $summary) | Out-File  $summaryFile -Encoding ascii -Append
	UploadSummaryMdReport $summaryFile
}
else
{
	Write-Error ("Connection '{0}' failed for service '{1}'" -f $connectedServiceName, $connectedServiceDetails.Url.AbsoluteUri)
}

WriteTaskMessages "Load Test Script execution completed"


text:
package com.hp.autonomy.hod.client.api.analysis.autocomplete;

import com.hp.autonomy.hod.client.api.authentication.AuthenticationToken;
import com.hp.autonomy.hod.client.api.authentication.EntityType;
import com.hp.autonomy.hod.client.api.authentication.TokenType;
import com.hp.autonomy.hod.client.config.HodServiceConfig;
import com.hp.autonomy.hod.client.config.Requester;
import com.hp.autonomy.hod.client.error.HodErrorException;
import com.hp.autonomy.hod.client.token.TokenProxy;
import lombok.Data;
import retrofit.client.Response;

import java.util.List;

/**
 * Default implementation of an AutocompleteService.
 */
public class AutocompleteServiceImpl implements AutocompleteService {
    private final AutocompleteBackend backend;
    private final Requester<?, TokenType.Simple> requester;

    public AutocompleteServiceImpl(final HodServiceConfig<?, TokenType.Simple> config) {
        requester = config.getRequester();
        backend = config.getRestAdapter().create(AutocompleteBackend.class);
    }

    @Override
    public List<String> getSuggestions(final String text) throws HodErrorException {
        return requester.makeRequest(AutocompleteResponse.class, new BackendCaller<>(text)).getWords();
    }

    @Override
    public List<String> getSuggestions(final String text, final TokenProxy<?, TokenType.Simple> tokenProxy) throws HodErrorException {
        return requester.makeRequest(tokenProxy, AutocompleteResponse.class, new BackendCaller<>(text)).getWords();
    }

    @Data
    private class BackendCaller<E extends EntityType> implements Requester.BackendCaller<E, TokenType.Simple> {
        private final String text;

        @Override
        public Response makeRequest(final AuthenticationToken<? extends E, ? extends TokenType.Simple> token) throws HodErrorException {
            return backend.getSuggestions(token, text);
        }
    }
}


text:
namespace std
{
  using __gnu_test::pod_int;

  typedef pod_int 		value_type;
  typedef value_type* 		iterator_type;
  typedef std::less<value_type> compare_type;

  template iterator_type partial_sort_copy(iterator_type, iterator_type,
					   iterator_type, iterator_type);

  template iterator_type partial_sort_copy(iterator_type, iterator_type,
					   iterator_type, iterator_type,
					   compare_type);
}


text:
@interface HGBaseViewController ()
@property (nonatomic, strong) UIButton *backButton;
@end

@implementation HGBaseViewController
#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setBaseNavigationbar];
}

#pragma mark - Private Methods
- (void)setBaseNavigationbar {
    if (self.navigationController) {
        self.gk_navBackgroundColor = kRGBA(28, 162, 223, 1.0);
        self.gk_navTitleFont = [UIFont systemFontOfSize:18];
        self.gk_navTitleColor = [UIColor whiteColor];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
        self.gk_navItemLeftSpace = 8;
        self.gk_navItemRightSpace = 12;
        if (self.navigationController.childViewControllers.count > 1) {
            self.gk_navLeftBarButtonItem = backItem;
        }
    }
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Getters
- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        _backButton.tintColor = [UIColor whiteColor];
        [_backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_backButton sizeToFit];
    }
    return _backButton;
}

@end


text:
<?php

namespace App\Http\Controllers\Admin\Crud;

use App\Http\Controllers\Controller;
use App\Repositories\Admin\Crud\BlogRepository;

class BlogController extends Controller
{
	use PerformsCrudActions;

	/**
	 * @var BlogRepository
	 */
	protected $repository;

	public function __construct(BlogRepository $repository)
	{
		$this->repository = $repository;
	}
}


text:
package com.qiniu.storage;

import com.google.gson.Gson;
import com.qiniu.common.Constants;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.model.ResumeBlockInfo;
import com.qiniu.util.Crc32;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 分片上传
 * 参考文档:分片上传
 *

 * 分片上传通过将一个文件分割为固定大小的块(4M),每次上传一个块的内容(服务端只分块,没有分片)。
 * 等待所有块都上传完成之后,再将这些块拼接起来,构成一个完整的文件。
 * 另外分片上传还支持纪录上传进度,如果本次上传被暂停,那么下次还可以从上次
 * 上次完成的文件偏移位置,继续开始上传,这样就实现了断点续传功能。
 *

 * 服务端网络较稳定,较大文件(如500M以上)才需要将块记录保存下来。
 * 小文件没有必要,可以有效地实现大文件的上传。
 */
public final class ResumeUploader {
    private final String upToken;
    private final String key;
    private final File f;
    private final long size;
    private final StringMap params;
    private final String mime;
    private final String[] contexts;
    private final ConfigHelper configHelper;
    private final Client client;
    private final byte[] blockBuffer;
    private final Recorder recorder;
    private final long modifyTime;
    private final RecordHelper helper;
    private FileInputStream file;
    private String host = null;
    private int retryMax;

    /**
     * 构建分片上传文件的对象
     */
    public ResumeUploader(Client client, String upToken, String key, File file,
                          StringMap params, String mime, Recorder recorder, Configuration configuration) {
        this.configHelper = new ConfigHelper(configuration);
        this.client = client;
        this.upToken = upToken;
        this.key = key;
        this.f = file;
        this.size = file.length();
        this.params = params;
        this.mime = mime == null ? Client.DefaultMime : mime;
        long count = (size + Constants.BLOCK_SIZE - 1) / Constants.BLOCK_SIZE;
        this.contexts = new String[(int) count];
        this.blockBuffer = new byte[Constants.BLOCK_SIZE];
        this.recorder = recorder;
        this.modifyTime = f.lastModified();
        helper = new RecordHelper();
        retryMax = configuration.retryMax;
    }

    /**
     * 同步上传文件
     */
    public Response upload() throws QiniuException {
        try {
            return upload0();
        } finally {
            close();
        }
    }

    private Response upload0() throws QiniuException {
        if (host == null) {
            this.host = configHelper.upHost(upToken);
        }
        long uploaded = helper.recoveryFromRecord();
        try {
            this.file = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            throw new QiniuException(e);
        }
        boolean retry = false;
        int contextIndex = blockIdx(uploaded);
        try {
            file.skip(uploaded);
        } catch (IOException e) {
            close();
            throw new QiniuException(e);
        }
        while (uploaded < size) {
            int blockSize = nextBlockSize(uploaded);
            try {
                file.read(blockBuffer, 0, blockSize);
            } catch (IOException e) {
                close();
                throw new QiniuException(e);
            }

            long crc = Crc32.bytes(blockBuffer, 0, blockSize);
            Response response = null;
            QiniuException temp = null;
            try {
                response = makeBlock(blockBuffer, blockSize);
            } catch (QiniuException e) {
                if (e.code() < 0 || (e.response != null && e.response.needSwitchServer())) {
                    changeHost(upToken, host);
                }
                if (e.response == null || e.response.needRetry()) {
                    retry = true;
                    temp = e;
                } else {
                    close();
                    throw e;
                }
            }

            if (!retry) {
                ResumeBlockInfo blockInfo0 = response.jsonToObject(ResumeBlockInfo.class);
                if (blockInfo0.crc32 != crc) {
                    retry = true;
                    temp = new QiniuException(new Exception("block's crc32 is not match"));
                }
            }

            if (retry) {
                if (retryMax > 0) {
                    retryMax--;
                    try {
                        response = makeBlock(blockBuffer, blockSize);
                        retry = false;
                    } catch (QiniuException e) {
                        close();
                        throw e;
                    }
                } else {
                    close();
                    throw temp;
                }
            }

            ResumeBlockInfo blockInfo = response.jsonToObject(ResumeBlockInfo.class);
            if (blockInfo.crc32 != crc) {
                throw new QiniuException(new Exception("block's crc32 is not match"));
            }
            contexts[contextIndex++] = blockInfo.ctx;
            uploaded += blockSize;
            helper.record(uploaded);
        }
        close();

        try {
            return makeFile();
        } catch (QiniuException e) {
            try {
                return makeFile();
            } catch (QiniuException e1) {
                throw e1;
            }
        } finally {
            helper.removeRecord();
        }
    }

    private void changeHost(String upToken, String host) {
        try {
            this.host = configHelper.tryChangeUpHost(upToken, host);
        } catch (Exception e) {
            // ignore
            // use the old up host //
        }
    }

    private Response makeBlock(byte[] block, int blockSize) throws QiniuException {
        String url = host + "/mkblk/" + blockSize;
        return post(url, block, 0, blockSize);
    }

    private void close() {
        try {
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String fileUrl() {
        String url = host + "/mkfile/" + size + "/mimeType/" + UrlSafeBase64.encodeToString(mime)
                + "/fname/" + UrlSafeBase64.encodeToString(f.getName());
        final StringBuilder b = new StringBuilder(url);
        if (key != null) {
            b.append("/key/");
            b.append(UrlSafeBase64.encodeToString(key));
        }
        if (params != null) {
            params.forEach(new StringMap.Consumer() {
                @Override
                public void accept(String key, Object value) {
                    b.append("/");
                    b.append(key);
                    b.append("/");
                    b.append(UrlSafeBase64.encodeToString("" + value));
                }
            });
        }
        return b.toString();
    }

    private Response makeFile() throws QiniuException {
        String url = fileUrl();
        String s = StringUtils.join(contexts, ",");
        return post(url, StringUtils.utf8Bytes(s));
    }

    private Response post(String url, byte[] data) throws QiniuException {
        return client.post(url, data, new StringMap().put("Authorization", "UpToken " + upToken));
    }

    private Response post(String url, byte[] data, int offset, int size) throws QiniuException {
        return client.post(url, data, offset, size, new StringMap().put("Authorization", "UpToken " + upToken),
                Client.DefaultMime);
    }

    private int nextBlockSize(long uploaded) {
        if (size < uploaded + Constants.BLOCK_SIZE) {
            return (int) (size - uploaded);
        }
        return Constants.BLOCK_SIZE;
    }

    private int blockIdx(long offset) {
        return (int) (offset / Constants.BLOCK_SIZE);
    }

    private class RecordHelper {

        long recoveryFromRecord() {
            try {
                return recoveryFromRecord0();
            } catch (Exception e) {
                e.printStackTrace();
                // ignore

                return 0;
            }
        }

        long recoveryFromRecord0() {
            if (recorder == null) {
                return 0;
            }

            String recorderKey = recorder.recorderKeyGenerate(key, f);

            byte[] data = recorder.get(recorderKey);
            if (data == null) {
                return 0;
            }
            String jsonStr = new String(data);
            Record r = new Gson().fromJson(jsonStr, Record.class);
            if (r.offset == 0 || r.modify_time != modifyTime || r.size != size
                    || r.contexts == null || r.contexts.length == 0) {
                return 0;
            }
            for (int i = 0; i < r.contexts.length; i++) {
                contexts[i] = r.contexts[i];
            }

            return r.offset;
        }

        void removeRecord() {
            try {
                if (recorder != null) {
                    String recorderKey = recorder.recorderKeyGenerate(key, f);
                    recorder.del(recorderKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // ignore
            }
        }

        // save json value
        //{
        //    "size":filesize,
        //    "offset":lastSuccessOffset,
        //    "modify_time": lastFileModifyTime,
        //    "contexts": contexts
        //}
        void record(long offset) {
            try {
                if (recorder == null || offset == 0) {
                    return;
                }
                String recorderKey = recorder.recorderKeyGenerate(key, f);
                String data = new Gson().toJson(new Record(size, offset, modifyTime, contexts));
                recorder.set(recorderKey, data.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
                // ignore
            }
        }

        private class Record {
            long size;
            long offset;
            // CHECKSTYLE:OFF
            long modify_time;
            // CHECKSTYLE:ON
            String[] contexts;

            Record(long size, long offset, long modify_time, String[] contexts) {
                this.size = size;
                this.offset = offset;
                this.modify_time = modify_time;
                this.contexts = contexts;
            }
        }
    }
}


text:
require 'alloy'
require 'thor'

module Alloy
  class CLI < Thor
    include Thor::Actions

    Alloy::CLI.source_root(File.expand_path('../../templates', __FILE__))

    desc 'build SUBCOMMAND', 'Build the app and run in simulator or emulator'
    subcommand 'build', Task::Build

    desc 'install SUBCOMMAND', 'Install to device'
    subcommand 'install', Task::Install

    desc 'clean SUBCOMMAND', 'Clean up build directory'
    subcommand 'clean', Task::Clean

    desc 'coffee', 'Compile CoffeeScript into JavaScript'
    def coffee
      Chore::CoffeeScript.run
    end

    desc 'testflight', 'Upload to TestFlight'
    def testflight
      Chore::TestFlight.run
    end

    desc 'init', 'Generate alloy.json'
    def init
      template('alloy.json.erb', 'alloy.json')
    end
  end
end


text:
namespace Igor
{
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Annotations;
    using Helpers;
    using Models;
    using Simple.Web;
    using Simple.Web.Authentication;
    using Simple.Web.Behaviors;
    using Simple.Web.Links;

    [UriTemplate("/websites/{WebSpace}/{HostName}/deployment")]
    [LinksFrom(typeof(WebSiteDto), "/websites/{WebSpace}/{HostName}/deployment", Rel = "deployment")]
    public class GetDeployment : IGetAsync, IOutput<DeploymentDto>, IRequireAuthentication
    {
        private readonly IClientHelper _clientHelper;

        public GetDeployment(IClientHelper clientHelper)
        {
            _clientHelper = clientHelper;
        }

        public async Task<Status> Get()
        {
            var user = (IgorUser) CurrentUser;
            var extensions = _clientHelper.GetWebSiteExtensionsClient(HostName, user.Name, user.Password);
            try
            {
                var deployments = await extensions.Deployments.ListAsync(null, CancellationToken.None);
                var current = deployments.Deployments.FirstOrDefault(d => d.Active);
                if (current != null)
                {
                    Output = new DeploymentDto
                    {
                        Message = current.Message,
                        Time = current.ReceivedTime
                    };
                    return 200;
                }
                return 404;
            }
            catch
            {
                return 404;
            }
        }

        public string WebSpace { get; set; }
// ReSharper disable once MemberCanBePrivate.Global
        public string HostName { get; [UsedImplicitly] set; }
        public DeploymentDto Output { get; private set; }
        public IUser CurrentUser { set; private get; }
    }
}


text:
.class Lcom/android/internal/widget/multiwaveview/MultiWaveView$1;
.super Landroid/animation/AnimatorListenerAdapter;
.source "MultiWaveView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/widget/multiwaveview/MultiWaveView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/widget/multiwaveview/MultiWaveView;

# direct methods
.method constructor <init>(Lcom/android/internal/widget/multiwaveview/MultiWaveView;)V
    .locals 0
    .parameter

    .prologue
    .line 111
    iput-object p1, p0, Lcom/android/internal/widget/multiwaveview/MultiWaveView$1;->this$0:Lcom/android/internal/widget/multiwaveview/MultiWaveView;

    invoke-direct {p0}, Landroid/animation/AnimatorListenerAdapter;-><init>()V

    return-void
.end method

# virtual methods
.method public onAnimationEnd(Landroid/animation/Animator;)V
    .locals 4
    .parameter "animator"

    .prologue
    .line 113
    iget-object v0, p0, Lcom/android/internal/widget/multiwaveview/MultiWaveView$1;->this$0:Lcom/android/internal/widget/multiwaveview/MultiWaveView;

    const/4 v1, 0x0

    iget-object v2, p0, Lcom/android/internal/widget/multiwaveview/MultiWaveView$1;->this$0:Lcom/android/internal/widget/multiwaveview/MultiWaveView;

    #getter for: Lcom/android/internal/widget/multiwaveview/MultiWaveView;->mWaveCenterX:F
    invoke-static {v2}, Lcom/android/internal/widget/multiwaveview/MultiWaveView;->access$000(Lcom/android/internal/widget/multiwaveview/MultiWaveView;)F

    move-result v2

    iget-object v3, p0, Lcom/android/internal/widget/multiwaveview/MultiWaveView$1;->this$0:Lcom/android/internal/widget/multiwaveview/MultiWaveView;

    #getter for: Lcom/android/internal/widget/multiwaveview/MultiWaveView;->mWaveCenterY:F
    invoke-static {v3}, Lcom/android/internal/widget/multiwaveview/MultiWaveView;->access$100(Lcom/android/internal/widget/multiwaveview/MultiWaveView;)F

    move-result v3

    #calls: Lcom/android/internal/widget/multiwaveview/MultiWaveView;->switchToState(IFF)V
    invoke-static {v0, v1, v2, v3}, Lcom/android/internal/widget/multiwaveview/MultiWaveView;->access$200(Lcom/android/internal/widget/multiwaveview/MultiWaveView;IFF)V

    .line 114
    return-void
.end method


text:
## Apache Hadoop Base image
#
FROM prodriguezdefino/ubuntujava
MAINTAINER prodriguezdefino prodriguezdefino@gmail.com

# install Hadoop
RUN curl -s http://www.us.apache.org/dist/hadoop/common/hadoop-2.6.0/hadoop-2.6.0.tar.gz | tar -xz -C /usr/local/
RUN cd /usr/local && ln -s ./hadoop-2.6.0 hadoop

ENV HADOOP_HOME /usr/local/hadoop
ENV HADOOP_PREFIX /usr/local/hadoop
ENV HADOOP_COMMON_HOME /usr/local/hadoop
ENV HADOOP_HDFS_HOME /usr/local/hadoop
ENV HADOOP_MAPRED_HOME /usr/local/hadoop
ENV HADOOP_YARN_HOME /usr/local/hadoop
ENV HADOOP_CONF_DIR /usr/local/hadoop/etc/hadoop
ENV YARN_CONF_DIR $HADOOP_PREFIX/etc/hadoop

RUN sed -i '/^export JAVA_HOME/ s:.*:export JAVA_HOME=/usr/lib/jvm/java-8-oracle\nexport HADOOP_PREFIX=/usr/local/hadoop\nexport HADOOP_HOME=/usr/local/hadoop\n:' $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh
RUN sed -i '/^export HADOOP_CONF_DIR/ s:.*:export HADOOP_CONF_DIR=/usr/local/hadoop/etc/hadoop/:' $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh
#RUN . $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh

RUN mkdir $HADOOP_PREFIX/input
RUN cp $HADOOP_PREFIX/etc/hadoop/*.xml $HADOOP_PREFIX/input

ADD core-site.xml.template $HADOOP_PREFIX/etc/hadoop/core-site.xml.template
ADD yarn-site.xml.template $HADOOP_PREFIX/etc/hadoop/yarn-site.xml.template
ADD hdfs-site.xml $HADOOP_PREFIX/etc/hadoop/hdfs-site.xml

ADD mapred-site.xml $HADOOP_PREFIX/etc/hadoop/mapred-site.xml

# for test we temporarily change the installation configuration to start all in a local node
RUN sed s/HOSTNAME/localhost/ /usr/local/hadoop/etc/hadoop/core-site.xml.template > /usr/local/hadoop/etc/hadoop/core-site.xml

RUN $HADOOP_PREFIX/bin/hdfs namenode -format

# add some test data to load later
RUN mkdir /test-data
ADD textfiles-for-test /test-data

# fixing the libhadoop.so like a boss
RUN rm  /usr/local/hadoop/lib/native/*
RUN curl -Ls http://dl.bintray.com/sequenceiq/sequenceiq-bin/hadoop-native-64-2.6.0.tar | tar -x -C /usr/local/hadoop/lib/native/

ADD ssh_config /root/.ssh/config
RUN chmod 600 /root/.ssh/config
RUN chown root:root /root/.ssh/config

# # installing supervisord
# RUN yum install -y python-setuptools
# RUN easy_install pip
# RUN curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -o - | python
# RUN pip install supervisor
#
# ADD supervisord.conf /etc/supervisord.conf

# lets add some helpfull scripts to later add and remove nodes to/from the cluster
ADD remote-remove-node.sh /etc/remote-remove-node.sh
ADD remove-node.sh /etc/remove-node.sh
ADD remote-remove-slave.sh /etc/remote-remove-slave.sh
ADD remove-slave.sh /etc/remove-slave.sh
ADD remote-add-slave.sh /etc/remote-add-slave.sh
ADD add-slave.sh /etc/add-slave.sh
ADD remote-add-node.sh /etc/remote-add-node.sh
ADD add-node.sh /etc/add-node.sh
ADD bootstrap.sh /etc/bootstrap.sh

# set the correct permissions to them
RUN chown root:root /etc/remote-remove-node.sh && chmod 700 /etc/remote-remove-node.sh && chown root:root /etc/remove-node.sh && chmod 700 /etc/remove-node.sh && chown root:root /etc/remote-remove-slave.sh && chmod 700 /etc/remote-remove-slave.sh && chown root:root /etc/remove-slave.sh && chmod 700 /etc/remove-slave.sh && chown root:root /etc/remote-add-slave.sh && chmod 700 /etc/remote-add-slave.sh && chown root:root /etc/add-slave.sh && chmod 700 /etc/add-slave.sh && chown root:root /etc/remote-add-node.sh && chmod 700 /etc/remote-add-node.sh && chown root:root /etc/add-node.sh && chmod 700 /etc/add-node.sh && chown root:root /etc/bootstrap.sh && chmod 700 /etc/bootstrap.sh

ENV BOOTSTRAP /etc/bootstrap.sh

# workingaround docker.io build error
RUN ls -la /usr/local/hadoop/etc/hadoop/*-env.sh
RUN chmod +x /usr/local/hadoop/etc/hadoop/*-env.sh
RUN ls -la /usr/local/hadoop/etc/hadoop/*-env.sh

# fix the 254 error code
RUN sed  -i "/^[^#]*UsePAM/ s/.*/#&/"  /etc/ssh/sshd_config
RUN echo "UsePAM no" >> /etc/ssh/sshd_config
RUN echo "Port 2122" >> /etc/ssh/sshd_config

RUN service ssh start && $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh && $HADOOP_PREFIX/sbin/start-dfs.sh && $HADOOP_PREFIX/bin/hdfs dfs -mkdir -p /user/root

#let everything terminate smoothly
RUN sleep 2

RUN service ssh start && $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh && $HADOOP_PREFIX/sbin/start-dfs.sh && $HADOOP_PREFIX/bin/hdfs dfs -put $HADOOP_PREFIX/etc/hadoop/ input

ENV PATH $PATH:$HADOOP_PREFIX/bin

CMD ["/etc/bootstrap.sh", "-d"]

EXPOSE 50020 50090 50070 50010 50075 8031 8032 8033 8040 8042 49707 22 8088 8030


text:
Vim-php-cs-fixer
================

[![](https://img.shields.io/travis/stephpy/vim-php-cs-fixer.svg)](https://travis-ci.org/stephpy/vim-php-cs-fixer)
[![](https://img.shields.io/github/issues/stephpy/vim-php-cs-fixer.svg)](https://github.com/stephpy/vim-php-cs-fixer/issues)
[![](https://img.shields.io/badge/doc-%3Ah%20vim--php--cs--fixer-blue.svg)](doc/vim-php-cs-fixer.txt)
[![](https://img.shields.io/badge/license-MIT-blue.svg)](doc/vim-php-cs-fixer.txt)

Integrate [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer).

This plugin will execute the `php-cs-fixer` command on the directory or file (depends on which command you call). See options to know how to customize that.

**Options available**:

```viml
" If php-cs-fixer is in $PATH, you don't need to define line below
" let g:php_cs_fixer_path = "~/php-cs-fixer.phar" " define the path to the php-cs-fixer.phar

" If you use php-cs-fixer version 1.x
let g:php_cs_fixer_level = "symfony"                   " options: --level (default:symfony)
let g:php_cs_fixer_config = "default"                  " options: --config
" If you want to define specific fixers:
"let g:php_cs_fixer_fixers_list = "linefeed,short_tag" " options: --fixers
"let g:php_cs_fixer_config_file = '.php_cs'            " options: --config-file
" End of php-cs-fixer version 1 config params

" If you use php-cs-fixer version 2.x
let g:php_cs_fixer_rules = "@PSR2"          " options: --rules (default:@PSR2)
"let g:php_cs_fixer_cache = ".php_cs.cache" " options: --cache-file
"let g:php_cs_fixer_config_file = '.php_cs' " options: --config
" End of php-cs-fixer version 2 config params

let g:php_cs_fixer_php_path = "php"               " Path to PHP
let g:php_cs_fixer_enable_default_mapping = 1     " Enable the mapping by default (<leader>pcd)
let g:php_cs_fixer_dry_run = 0                    " Call command with dry-run option
let g:php_cs_fixer_verbose = 0                    " Return the output of command if 1, else an inline information.
```

Default mapping is `<leader>pcd`

If you want to change it:

```viml
nnoremap <silent><leader>pcd :call PhpCsFixerFixDirectory()<CR>
nnoremap <silent><leader>pcf :call PhpCsFixerFixFile()<CR>
```

If you want to add **fix on save** functionality, add this string to the end of ~/.vimrc:
```viml
autocmd BufWritePost *.php silent! call PhpCsFixerFixFile()
```

# Installation

Via **[Vundle](https://github.com/gmarik/vundle)**, add:

```viml
Bundle 'stephpy/vim-php-cs-fixer'
```

Via **[Pathogen](https://github.com/tpope/vim-pathogen)**, do:

```bash
cd ~/.vim/bundle
git clone git@github.com:stephpy/vim-php-cs-fixer.git
```

To see how to install `php-cs-fixer`, look at [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) repository.

If you see any improvement or question, contribute or create an issue


text:
<?php

namespace Autorisation\Entity;

use Doctrine\ORM\Mapping as ORM;
use Autorisation;

/**
 * Droit
 *
 * @ORM\Table(name="droit", indexes={@ORM\Index(name="idClass", columns={"idClass"}), @ORM\Index(name="idAgent", columns={"idAgent"})})
 * @ORM\Entity
 */
class Droit
{
    /**
     * @var integer
     *
     * @ORM\Column(name="idAgent", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    private $idagent;

    /**
     * @var boolean
     *
     * @ORM\Column(name="droit_create", type="boolean", nullable=false)
     */
    private $droitCreate;

    /**
     * @var boolean
     *
     * @ORM\Column(name="droit_read", type="boolean", nullable=false)
     */
    private $droitRead;

    /**
     * @var boolean
     *
     * @ORM\Column(name="droit_update", type="boolean", nullable=false)
     */
    private $droitUpdate;

    /**
     * @var boolean
     *
     * @ORM\Column(name="droit_delete", type="boolean", nullable=false)
     */
    private $droitDelete;

    /**
     * @var \Autorisation\Entity\Ressource
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Autorisation\Entity\Ressource")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="idClass", referencedColumnName="idClass")
     * })
     */
    private $idclass;

    /**
     * Set idagent
     *
     * @param integer $idagent
     * @return Droit
     */
    public function setIdagent($idagent)
    {
        $this->idagent = $idagent;

        return $this;
    }

    /**
     * Get idagent
     *
     * @return integer
     */
    public function getIdagent()
    {
        return $this->idagent;
    }

    /**
     * Set droitCreate
     *
     * @param boolean $droitCreate
     * @return Droit
     */
    public function setDroitCreate($droitCreate)
    {
        $this->droitCreate = $droitCreate;

        return $this;
    }

    /**
     * Get droitCreate
     *
     * @return boolean
     */
    public function getDroitCreate()
    {
        return $this->droitCreate;
    }

    /**
     * Set droitRead
     *
     * @param boolean $droitRead
     * @return Droit
     */
    public function setDroitRead($droitRead)
    {
        $this->droitRead = $droitRead;

        return $this;
    }

    /**
     * Get droitRead
     *
     * @return boolean
     */
    public function getDroitRead()
    {
        return $this->droitRead;
    }

    /**
     * Set droitUpdate
     *
     * @param boolean $droitUpdate
     * @return Droit
     */
    public function setDroitUpdate($droitUpdate)
    {
        $this->droitUpdate = $droitUpdate;

        return $this;
    }

    /**
     * Get droitUpdate
     *
     * @return boolean
     */
    public function getDroitUpdate()
    {
        return $this->droitUpdate;
    }

    /**
     * Set droitDelete
     *
     * @param boolean $droitDelete
     * @return Droit
     */
    public function setDroitDelete($droitDelete)
    {
        $this->droitDelete = $droitDelete;

        return $this;
    }

    /**
     * Get droitDelete
     *
     * @return boolean
     */
    public function getDroitDelete()
    {
        return $this->droitDelete;
    }

    /**
     * Set idclass
     *
     * @param \Autorisation\Entity\Ressource $idclass
     * @return Droit
     */
    public function setIdclass(\Autorisation\Entity\Ressource $idclass)
    {
        $this->idclass = $idclass;

        return $this;
    }

    /**
     * Get idclass
     *
     * @return \Autorisation\Entity\Ressource
     */
    public function getIdclass()
    {
        return $this->idclass;
    }
    public function initialiseDroits( $agent, $classe)
    {
    	$this->setIdagent($agent->getIdagent());
    	$this->setIdclass($classe);
    	$this->setDroitCreate(false);
    	$this->setDroitUpdate(false);
    	$this->setDroitRead(false);
    	$this->setDroitDelete(false);
    }
}


text:
import ldap3
import logging
import importlib

from ldap3.core.exceptions import LDAPException, LDAPCursorError
from django.conf import settings

logger = logging.getLogger(__name__)

class LDAPSearchException(LDAPException):
    pass

class LDAPSearch(object):

    def __init__(self):
        # retrieve settings and initialize connection
        ldap_servers = []
        for server in settings.PUCAS_LDAP['SERVERS']:
            ldap_servers.append(ldap3.Server(server, get_info=ldap3.ALL,
                use_ssl=True))
        server_pool = ldap3.ServerPool(ldap_servers,
            ldap3.ROUND_ROBIN, active=True, exhaust=5)

        # Load username (in DN format) and password, if in settings
        bind_dn = settings.PUCAS_LDAP.get('BIND_DN', None)
        bind_password = settings.PUCAS_LDAP.get('BIND_PASSWORD', None)

        extra_args = {}
        # Use DN and password if set. Otherwise, use anononymous bind.
        if bind_dn and bind_password:
            extra_args.update({'user': bind_dn, 'password': bind_password})

        try:
            self.conn = ldap3.Connection(server_pool, auto_bind=True,
                                         **extra_args)
        except LDAPException as err:
            logging.error('Error establishing LDAP connection: %s', err)
            # re-raise to be caught elsewhere
            raise

    def find_user(self, netid, all_attributes=False):
        if netid:
            # check for required settings and error if not available
            required_configs = ['ATTRIBUTES', 'SEARCH_BASE', 'SEARCH_FILTER']
            if any(req not in settings.PUCAS_LDAP for req in required_configs):
                raise LDAPSearchException('LDAP is not configured for user lookup')

            # for testing, to see all available attributes
            if all_attributes:
                search_attributes = '*'
            else:
                search_attributes = settings.PUCAS_LDAP['ATTRIBUTES']

            self.conn.search(settings.PUCAS_LDAP['SEARCH_BASE'],
                    settings.PUCAS_LDAP['SEARCH_FILTER'] % {'user': netid},
                    attributes=search_attributes)
            if self.conn.entries:
                if len(self.conn.entries) > 1:
                    raise LDAPSearchException('Found more than one entry for %s' % netid)

                return self.conn.entries[0]

            else:
                raise LDAPSearchException('No match found for %s' % netid)

        else:
            raise LDAPSearchException('Error: requested LDAP lookup on empty netid')

def user_info_from_ldap(user):
    '''Populate django user info from ldap'''

    # configured mapping of user fields to ldap fields
    attr_map = settings.PUCAS_LDAP.get('ATTRIBUTE_MAP', None)
    # if no map is configured, nothing to do
    if not attr_map:
        # is logging sufficient here? or should it be an exception
        logging.warning('No attribute map configured; not populating user info'
                        ' from ldap')
        return

    user_info = LDAPSearch().find_user(user.username)
    if user_info:
        for user_attr, ldap_attr in attr_map.items():
            # Handle issues where an attribute may need to be populated by
            # multiple attributes OR where it is missing.

            # if just a string, convert to a list so handling can be uniform,
            # in cases where a field is multivalued.
            if isinstance(ldap_attr, str):
                ldap_attr = [ldap_attr]

            # iterate through the list items and break on the first one to
            # correct set without raising LDAPCursorError
            # This is a simplification for multivalued fields, since
            # typically we're mapping to only one value.
            for val in ldap_attr:
                try:
                    setattr(user, user_attr, str(getattr(user_info, val)))
                    break
                except LDAPCursorError:
                    pass
            # user getattr to check for a still unset value, in which case
            # set it to an empty string, used in situations where
            # a user is being updated -- and ot make sure values are
            # strings, not lists
            if not getattr(user, user_attr, None):
                setattr(user, user_attr, '')

        # optional custom user-init method set in django config
        extra_init = settings.PUCAS_LDAP.get('EXTRA_USER_INIT', None)
        if extra_init:
            # use importlib to import the module and get hte function
            mod_name, func_name = extra_init.rsplit('.', 1)
            mod = importlib.import_module(mod_name)
            extra_init_func = getattr(mod, func_name)
            extra_init_func(user, user_info)

        user.save()


text:
The EntityLivingDeath event is fired whenever an Entity is about to die.
It can be canceled to let the entity live.

## Класс события

You will need to cast the event in the function header as this class:
`crafttweaker.event.EntityLivingDeathEvent`
You can, of course, also [import](/AdvancedFunctions/Import/) the class before and use that name then.

## Наследование от интерфейсов событий

EntityLivingDeathEvent implements the following interfaces and are able to call all of their methods/getters/setters as well:

- [ILivingEvent](/Vanilla/Events/Events/ILivingEvent/)
- [IEventCancelable](/Vanilla/Events/Events/IEventCancelable/)

## ZenGetters

| ZenGetter    | Тип                                             |
| ------------ | ----------------------------------------------- |
| damageSource | [IDamageSource](/Vanilla/Damage/IDamageSource/) |


text:
We don't need the entire Angular Bootstrap library (https://angular-ui.github.io/bootstrap/); this is our custom build downloaded from their website.

## Components Included

- Buttons
- Modal
- Popover
- Tooltip
- Typeahead


text:
#include "mainwidget.h"
#include "ui_ui.h"

#include <QString>
#include <QFileDialog>
#include <QErrorMessage>
#include <QPixmap>
#include <QVector>
#include <QRgb>
#include <cmath>
#include <cstdio>
#include <sstream>

#define WITHIN(a,b,c) b-c < a && a < b+c

MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::BallspeedUI),
    mHough(new HoughDetector),
    mMatcher(new TemplateMatcher),
    mCalibrationMatcher(new TemplateMatcher)
{
    ui->setupUi(this);
    ui->frame->setMainWidget(this);
    mDiameter = ui->diameter->value();
    mHough->setThreshold(ui->houghThreshold->value());

    ui->hough->setFixedSize(100, 100);
}

MainWidget::~MainWidget()
{
    delete ui;
}

/*
 * Slots
 */
/**
 * Load video
 */
void MainWidget::on_loadVideoButton_clicked() {
    QString path = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), QString("Movies (*.avi *.MOV *.mp4)"));
    if (path == "") {
        return;
    }
    ui->videoPath->setText(path);
    loadPath(path.toStdString());
    mLogger->setCurrentFrame(0);
}

/**
 * Change diameter of hough search area and initial template search area
 */
void MainWidget::on_diameter_valueChanged(int diam) {
    mDiameter = diam;
}

/**
 * Change hough threshold value
 */
void MainWidget::on_houghThreshold_valueChanged(int val) {
    mHough->setThreshold(val);
}

/**
 * Handle clicks on the frame
 */
void MainWidget::on_frame_clicked(QMouseEvent *me) {
    QPoint pt;
    Subimage sub;
    HoughResult res;
    int i;

    // Left click = find template
    if (me->button() == Qt::LeftButton) {
        // Get sub image
        pt = ui->frame->trueCoords(me->pos());
        sub = getSubimage(pt);
        if (!sub.exists) {
            return;
        }

        // Show hough search area
        ui->hough->setPixmap(QPixmap::fromImage(sub.toImage()));

        // Detect
        res = mHough->detect(sub);
        if (res.found) {
            mHoughResults.replace(mCur, res);

            mTmpl = getSubimage(res.pt, (int)res.radius*2);
            ui->templateImage->setPixmap(QPixmap::fromImage(mTmpl.toImage()));
            mMatcher->setTemplate(mTmpl);
        }
    // Right click = set template for calibration
    } else if (me->button() == Qt::RightButton && mCalibrationTmpl.size() < 4) {
        pt = ui->frame->trueCoords(me->pos());
        i = mCalibrationTmpl.size();
        mCalibrationTmpl.append(getSubimage(pt-QPoint(5,5), 10));

        // Fill mCalibrations with empty values so we can .replace() later
        mCalibrations.append(QVector<MatchResult>());
        mCalibrations[i].fill({QPoint(), 0.0, false}, mFrameCount);
    }
}

/**
 * Do ball matching in current frame
 */
void MainWidget::on_matchTemplate_clicked() {
    MatchResult res, cal;
    QPoint pt;

    // Match ball
    res = matchBallFrame(mCur);
    mBallMatches.replace(mCur, res);

    // Print result
    if (mCur <= 0) {
        return;
    }

    pt = getCalibratedPoint(mCur);
    std::cout << "#" << mCur << ": match(" << res.pt.x() << "," << res.pt.y() << ") calibrated(" << pt.x() << ", " << pt.y() << ") value = " << res.value << std::endl;
}

/**
 * Do ball matching in all frames
 */
void MainWidget::on_matchAllBalls_clicked() {
    int i, tmpl;
    MatchResult res, cal;
    QPoint pt;

    for (i = 0; i < ui->frameCount->text().toInt(); i++) {
        res = matchBallFrame(i);
        mBallMatches.replace(i, res);

        // Calibrate
        for (tmpl = 0; tmpl < mCalibrationTmpl.size(); tmpl++) {
            cal = matchCalibration(tmpl,i);
            mCalibrations[tmpl].replace(i, cal);
        }

        // Print results
        if (i <= 0) {
            continue;
        }

        pt = getCalibratedPoint(i);
        std::cout << "#" << i << ": match(" << res.pt.x() << "," << res.pt.y() << ") calibrated(" << pt.x() << ", " << pt.y() << ") value = " << res.value << std::endl;
        mLogger->printFrame(i);
    }
    mLogger->printTotalTime();
}

/**
 * Go to first frame
 */
void MainWidget::on_firstFrame_clicked() {
    mCur = 0;
    ui->frameEdit->setText(QString::number(mCur));
}

/**
 * Go to last frame
 */
void MainWidget::on_lastFrame_clicked() {
    mCur = mFrameCount-1;
    ui->frameEdit->setText(QString::number(mCur));
}

/**
 * Go to next frame
 */
void MainWidget::on_nextFrame_clicked() {
    mCur++;
    ui->frameEdit->setText(QString::number(mCur));
}

/**
 * Go to previous frame
 */
void MainWidget::on_prevFrame_clicked() {
    mCur--;
    ui->frameEdit->setText(QString::number(mCur));
}

/**
 * Calculates and prints the ball speed between each matched frame
 */
void MainWidget::on_calculateSpeed_clicked() {
    float mpp, speed, speedX, speedY;
    float diameter, goalheight;
    int i, distanceX, distanceY;
    bool convertDia, convertGoal;
    MatchResult first, prevcal, curcal, prevmr, curmr;
    QPoint prev, cur;

    // Check if diameter or goal height is set
    diameter = ui->ballDiameter->text().toFloat(&convertDia);
    goalheight = ui->goalHeight->text().toFloat(&convertGoal);
    if (!convertDia && !convertGoal) {
        std::cerr << "Diameter  not set!" << std::endl;
        return;
    }

    // Get meters per pixel
    // Try to use goal first.
    if (convertGoal && mCalibrationTmpl.size() == 4) {
        // Find each goal post
        QPoint pair1, pair2;
        pair1.setX(mCalibrationTmpl[0].offset().x());
        // Check if #2 belongs with #1
        if (WITHIN(mCalibrationTmpl[1].offset().x(), pair1.x(), 25)) {
            pair1.setY(1);
            pair2.setX(2);
            pair2.setY(3);
        } else { // #2 is not with #1,
            pair2.setX(1);
            if (WITHIN(mCalibrationTmpl[2].offset().x(), pair1.x(), 25)) { // check if #3 is with #1
                pair1.setY(2);
                pair2.setY(3);
            } else { // #4 and #1 is together and #2 and #3 is together
                pair1.setY(3);
                pair2.setY(2);
            }
        }

        // Find difference in goal post heights
        float diff, diff1, diff2;
        diff1 = (float)mCalibrationTmpl[0].offset().y()-(float)mCalibrationTmpl[pair1.y()].offset().y();
        diff2 = (float)mCalibrationTmpl[pair2.x()].offset().y()-(float)mCalibrationTmpl[pair2.y()].offset().y();
        diff = (fabs(diff1)+fabs(diff2))/2; // XXX: Ball is placed in the middle of the goal

        // Calculate goal height in pixels
        mpp = ((float)goalheight)/diff;
        std::cout << "Ball calc: " << ((float)diameter)/(float)mTmpl.width() << std::endl;
        std::cout << "Goal height (px): " << diff << std::endl;
    } else { // Use ball diameter instead
        mpp = ((float)diameter)/(float)mTmpl.width();
    }
    std::cout << "Meters per pixel: " << mpp << std::endl << "Template width: " << (float)mTmpl.width() << std::endl;

    // Calculate speeds
    for (i = 1; i < mFrameCount; i++) {
        prev = getCalibratedPoint(i-1);
        cur = getCalibratedPoint(i);

        // If we don't have to results, continue
        if (prev == QPoint(-1, -1) || cur == QPoint(-1,-1)) {
            continue;
        }

        // Calculate horizontal, vertical and ... speeds
        // Assume 30 fps
        distanceX = cur.x()-prev.x();
        distanceY = cur.y()-prev.y();

        speedX = mpp*(float)distanceX*15;
        speedY = mpp*(float)distanceY*15;
        speed = sqrt(speedX*speedX+speedY*speedY);

        // Print results
        printf("#%02d-#%02d:\t%3f\t| %3f\t| %3f\n", i-1, i, speedX, speedY, speed);
    }
}

/*
 * Helpers
 */
Subimage MainWidget::getSubimage(QPoint pos) {
    return getSubimage(pos, mDiameter);
}

Subimage MainWidget::getSubimage(QPoint pos, int diameter) {
    return getSubimage(pos, mCur, diameter);
}

/**
 * Return a rectangular subimage of a given frame.
 * If adjust is true, the function will automatically adjust the boundaries of the subimage
 * to boundaries of the frame. If adjust is false and the boundaries exceed the boundaries of the
 * frame, an empty subimage will be returned.
 * @param pos Center point of subimage
 * @param frame Frame number
 * @param diameter Intented width/height of subimage
 * @param filled Filled is set to true if the subimage fills the subimage
 * @param adjust Indicates whether the subimage boundaries should be adjusted to the frame boundaries
 */
Subimage MainWidget::getSubimage(QPoint pos, int frame, int diameter, bool *filled, bool adjust) {
    int adjs = 0; // number of adjustments
    cv::Mat mat, omat;
    cv::Rect rect;

    // Return empty image if there's no video opened
    if (!mVidcap.isOpened()) {
        return Subimage();
    }

    // Read frame
    mVidcap.set(CV_CAP_PROP_POS_FRAMES, frame);
    mVidcap.read(mat);

    // Boundaries
    int left = 0 > pos.x()-mDiameter*2 ? 0 : pos.x()-mDiameter*2; // min of 0 and center.x-mDiameter
    int top = 0;
    int right = mat.cols;
    int bottom = mat.rows < pos.y()+mDiameter*2 ? mat.rows : pos.y()+mDiameter*2; // max of image height and center.y+mDiameter
    std::stringstream s;
    s << "Boundaries: (" << left << ", " << top << ") , (" << right << ", " << bottom << ")";
//    mLogger->addMessage(s.str());

    // Translate pos to upper left corner
    pos -= QPoint(diameter/2, diameter/2);
    rect = cv::Rect(pos.x(), pos.y(), diameter, diameter);

    // Check if subrect is within bounds
    if (pos.x() < left || pos.x()+diameter > right ||
        pos.y() < top || pos.y()+diameter > bottom) {
        if (!adjust && filled != 0) {
            *filled = true;
            return Subimage();
        } else {
            // Adjust sub image
            if (pos.x() < left) { // Left bound
                rect.x = 0;
                adjs++;
            }
            if (pos.y() < top) { // Upper bound
                rect.y = 0;
                adjs++;
            }
            if (rect.x+diameter > right) { // Right bound
                rect.width = right-rect.x;
                adjs++;
            }
            if (rect.y+diameter > bottom) { // Lower bound
                rect.height = bottom-rect.y;
                adjs++;
            }

            if (adjs == 4 && filled != 0) {
                *filled = true;
            }
        }
    }

    pos = QPoint(rect.tl().x, rect.tl().y);

    // Get subimage
    mat(rect).copyTo(omat);
    return Subimage(omat, pos);
}

/**
 * Matches the ball template against frame #i
 */
MatchResult MainWidget::matchBallFrame(int i) {
    Subimage sub;
    MatchResult res = {QPoint(), 0, false}, mr;
    HoughResult hr;
    int diameter = mDiameter, runs;
    bool filled = false;
    QPoint center;

    // Start logging
    mLogger->setCurrentFrame(i);
    mLogger->startMatching();

    // Find center
    hr = mHoughResults.at(i);
    if (i >= 1) {
        mr = mBallMatches.at(i-1);
    }

    if (i-1 >= 0 && mr.found) {
        center = mr.pt;
    } else if (hr.found) {
        center = hr.pt;
    } else {
        // XXX Handle error
        center = QPoint(0,0);
    }

    // First try to move the search window
    if (ui->moveWindow->isChecked()) {
        for (runs = 0; runs < 2; runs++) {
            sub = getSubimage(center, i, diameter, &filled, true);
            res = mMatcher->match(sub);

            ui->hough->setPixmap(QPixmap::fromImage(sub.toImage()));
            mLogger->addIteration(sub.offset(), sub.width(), sub.height());

            // If value is less than 0.80 it probably isn't a proper match, try in a bigger area
            if (res.value > 0.80) {
                filled = true; // Do this avoid running the next loop
                break;
            }

            center += QPoint(3*mDiameter, 0);
        }
        diameter *= 2;
    }

    // Make search window bigger if there's no match
    for (; !filled; diameter *= 2) {
        sub = getSubimage(center, i, diameter, &filled, true);
        res = mMatcher->match(sub);

        ui->hough->setPixmap(QPixmap::fromImage(sub.toImage()));
        mLogger->addIteration(sub.offset(), sub.width(), sub.height());

        // If value is less than 0.80 it probably isn't a proper match, try in a bigger area
        if (res.value > 0.80) {
            break;
        }
    }

    mLogger->stopMatching();

    return res;
}

/**
 * Matches calibration template #tmpl against frame #i
 */
MatchResult MainWidget::matchCalibration(int tmpl, int i) {
    MatchResult res, prev;
    QPoint pt;
    Subimage sub;
    bool filled = false;

    if (!mCalibrationTmpl.at(tmpl).exists) {
        return res;
    }

    // Find search area
    if (i > 0) {
        prev = mCalibrations.at(tmpl).at(i-1);
    }

    if (i > 0 && prev.found) {
        pt = prev.pt;
    } else {
        pt = mCalibrationTmpl[tmpl].offset();
    }

    sub = getSubimage(pt, i, mDiameter, &filled);

    if (filled) {
        return res;
    }

    mCalibrationMatcher->setTemplate(mCalibrationTmpl[tmpl]);
    res = mCalibrationMatcher->match(sub);

    return res;
}

/**
 * Load video
 * XXX: Gives wrong frame count with some videos and needs to check framerate
 */
void MainWidget::loadPath(std::string path) {
    // Try to open path
    mVidcap.open(path);
    if (!mVidcap.isOpened()) {
        QErrorMessage *errDialog = new QErrorMessage(this);
        errDialog->showMessage("Could not open file");
        return;
    }

    // Get info
    mFrameCount = mVidcap.get(CV_CAP_PROP_FRAME_COUNT);
    mCur = 0;

    // Fill vectors
    HoughResult dummy = {QPoint(), 0, false};
    MatchResult match = {QPoint(), 0.0, false};
    mHoughResults.fill(dummy, mFrameCount);
    mBallMatches.fill(match, mFrameCount);

    // Create logger
    mLogger = new Logger(mFrameCount);
}

/**
 * Returns the calibrated point for the given frame
 * XXX: Not used right now
 */
QPoint MainWidget::getCalibratedPoint(int frame) {
    MatchResult mr, cal, first;

    // Get matchresults
    mr = mBallMatches.at(frame);
/*    first = mCalibrations.at(0);
    cal = mCalibrations.at(frame);

        printf("n: %d\n", cals.size()
    if (!first.found || !cal.found) {
        if (mr.found) {
            return mr.pt;
        }
        return QPoint(-1,-1);
    }

    // Calibrate
    return mr.pt - (cal.pt-first.pt);*/
    return mr.pt;
}

/**
 * Match all calibration templates and return the translation needed to calibrate
 * XXX: Calculate translation
 */
QPoint MainWidget::getCalibration(int frame) {
    MatchResult cal;
    QPoint pt;
    int i;

    // Match calibration templates
    for (i = 0; i < mCalibrationTmpl.size(); i++) {
        cal = matchCalibration(i,frame);
        mCalibrations[i].replace(frame, cal);
    }

    return pt;
}


text:
<!DOCTYPE html>
<html>
  <!-- Test: if select is disabled, it is barred from constraint validation
             and should not be affected by :valid pseudo-class. -->
  <link rel='stylesheet' type='text/css' href='style.css'>
  <body>
    <select class='notvalid' disabled></select>
  </body>
</html>


text:
package org.vafer.jdependency;

import java.util.HashSet;
import java.util.Set;

public final class Clazz implements Comparable<Clazz> {

    private final Set<Clazz> dependencies = new HashSet<Clazz>();
    private final Set<Clazz> references = new HashSet<Clazz>();
    private final Set<ClazzpathUnit> units = new HashSet<ClazzpathUnit>();

    private final String name;

    public Clazz( final String pName ) {
        name = pName;
    }

    public String getName() {
        return name;
    }

    public void addClazzpathUnit( final ClazzpathUnit pUnit ) {
        units.add(pUnit);
    }

    public void removeClazzpathUnit( final ClazzpathUnit pUnit ) {
        units.remove(pUnit);
    }

    public Set<ClazzpathUnit> getClazzpathUnits() {
        return units;
    }

    public void addDependency( final Clazz pClazz ) {
        pClazz.references.add(this);
        dependencies.add(pClazz);
    }

    public void removeDependency( final Clazz pClazz ) {
        pClazz.references.remove(this);
        dependencies.remove(pClazz);
    }

    public Set<Clazz> getDependencies() {
        return dependencies;
    }

    public Set<Clazz> getReferences() {
        return references;
    }

    public Set<Clazz> getTransitiveDependencies() {
        final Set<Clazz> all = new HashSet<Clazz>();
        findTransitiveDependencies(all);
        return all;
    }

    void findTransitiveDependencies( final Set<? super Clazz> pAll ) {

        for (Clazz clazz : dependencies) {
            if (!pAll.contains(clazz)) {
                pAll.add(clazz);
                clazz.findTransitiveDependencies(pAll);
            }
        }
    }

    public boolean equals( final Object pO ) {
        if (pO.getClass() != Clazz.class) {
            return false;
        }
        final Clazz c = (Clazz) pO;
        return name.equals(c.name);
    }

    public int hashCode() {
        return name.hashCode();
    }

    public int compareTo( final Clazz pO ) {
        return name.compareTo(((Clazz) pO).name);
    }

    public String toString() {
        return name;
    }

}


text:
  display: none; }

.image-viewable, .image-editable, #right .thumbnail {
  text-align: center;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  position: relative;
  background-color: white;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center; }

.image-editable div {
  margin-top: -5px;
  height: 10px;
  position: absolute;
  top: 50%;
  left: 0px;
  width: 100%;
  display: none;
  font-weight: bold; }
.image-editable .image-submit {
  border: 1px solid #076fe4;
  border-radius: 3px;
  box-shadow: inset 0 1px 0 0 #8ebcf1;
  color: white;
  display: inline-block;
  font-size: 11px;
  font-weight: bold;
  background-color: #4294f0;
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #4294f0), color-stop(100%, #0776f3));
  background-image: -webkit-linear-gradient(#4294f0, #0776f3);
  background-image: linear-gradient(#4294f0, #0776f3);
  padding: 7px 18px;
  text-decoration: none;
  text-shadow: 0 1px 0 #0065d6;
  background-clip: padding-box;
  position: absolute;
  width: 100%;
  left: 0px;
  bottom: 0px;
  display: none; }
  .image-editable .image-submit:hover:not(:disabled) {
    box-shadow: inset 0 1px 0 0 #60a2ec;
    cursor: pointer;
    background-color: #2f87ea;
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #2f87ea), color-stop(100%, #086fe3));
    background-image: -webkit-linear-gradient(#2f87ea, #086fe3);
    background-image: linear-gradient(#2f87ea, #086fe3); }
  .image-editable .image-submit:active:not(:disabled) {
    border: 1px solid #076fe4;
    box-shadow: inset 0 0 8px 4px #0868d3, inset 0 0 8px 4px #0868d3, 0 1px 1px 0 #eeeeee; }
  .image-editable .image-submit:disabled {
    opacity: 0.5;
    cursor: not-allowed; }

.image-editable:not(.highlight) {
  outline: 1px solid black; }

.image-editable.highlight {
  outline: 7px solid orange; }

.image-editable:hover div {
  display: block; }

#right {
  float: right;
  width: 400px;
  text-align: center; }
  #right .thumbnail {
    width: 100%;
    height: 400px; }
  #right .name {
    font-weight: bold;
    font-size: 20px; }

#price .label {
  font-weight: bold; }

#expiration {
  font-style: italic;
  margin-bottom: 20px; }

#description {
  margin-left: 20px; }

#clearer {
  clear: both; }

.star-strip {
  background-repeat: repeat-x;
  background-size: contain;
  background-image: url("/images/star-back.svg");
  position: relative; }
  .star-strip div {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    background-repeat: repeat-x;
    background-size: contain;
    background-image: url("/images/star.svg"); }

.star-strip:not(.large) {
  height: 15px;
  width: 75px; }

.star-strip.large {
  height: 30px;
  width: 150px; }

#rating-form .numerical-rating {
  float: right;
  width: 150px;
  height: 30px;
  background-repeat: repeat-x;
  background-size: contain;
  background-image: url("/images/star-back.svg");
  margin: 0;
  padding: 0;
  font-size: 0;
  overflow: hidden;
  position: relative;
  -webkit-transform: scaleX(-1);
  -moz-transform: scaleX(-1);
  -ms-transform: scaleX(-1);
  -o-transform: scaleX(-1);
  transform: scaleX(-1); }
  #rating-form .numerical-rating input {
    position: absolute;
    top: 0px;
    display: block;
    width: 100%;
    height: 100%;
    -webkit-appearance: none;
    -moz-appearance: none;
    -ms-appearance: none;
    -o-appearance: none;
    appearance: none;
    border: none;
    margin: 0;
    padding: 0;
    background: none;
    border: none;
    outline: none;
    cursor: pointer; }
  #rating-form .numerical-rating input:hover, #rating-form .numerical-rating input:checked {
    background-repeat: repeat-x;
    background-size: contain;
    background-image: url("/images/star.svg"); }
#rating-form textarea {
  display: none; }
#rating-form .rich-text {
  width: 50%;
  height: 150px; }
#rating-form input[type=submit] {
  margin-right: 50%;
  display: block;
  position: relative;
  margin-left: auto; }

#average-rating {
  float: right; }

h2 .clearer {
  clear: both; }

.rating {
  width: 100%;
  position: relative;
  margin-bottom: 10px; }
  .rating .margin {
    width: 36px;
    float: left; }
    .rating .margin .user {
      margin: 0;
      padding: 0;
      display: block;
      text-decoration: none; }
      .rating .margin .user .pic {
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center center;
        width: 36px;
        height: 36px;
        outline: 1px solid black; }
      .rating .margin .user .name {
        margin-top: 5px;
        font-size: 10px;
        width: 100%;
        margin: 0;
        padding: 0;
        display: block;
        color: black;
        text-decoration: none; }
  .rating .message {
    width: 100%;
    margin-left: 50px; }
  .rating .clearer {
    clear: both; }


text:
#ifndef GrDataUtils_DEFINED
#  define GrDataUtils_DEFINED
#  include "include/core/SkColor.h"
#  include "include/private/GrTypesPriv.h"
#  include "src/gpu/GrColorInfo.h"
#  include "src/gpu/GrSwizzle.h"
class GrImageInfo;
size_t GrCompressedDataSize(SkImage::CompressionType, int w, int h);
// Returns a value that can be used to set rowBytes for a transfer function.
size_t GrCompressedRowBytes(SkImage::CompressionType, int w);
// Compute the size of the buffer required to hold all the mipLevels of the specified type
// of data when all rowBytes are tight.
// Note there may still be padding between the mipLevels to meet alignment requirements.
size_t GrComputeTightCombinedBufferSize(size_t bytesPerPixel, int baseWidth, int baseHeight, SkTArray<size_t>* individualMipOffsets, int mipLevelCount);
void GrFillInData(GrPixelConfig, int baseWidth, int baseHeight, const SkTArray<size_t>& individualMipOffsets, char* dest, const SkColor4f& color);
void GrFillInCompressedData(SkImage::CompressionType, int width, int height, char* dest, const SkColor4f& color);
// Swizzle param is applied after loading and before converting from srcInfo to dstInfo.
bool GrConvertPixels(const GrImageInfo& dstInfo, void* dst, size_t dstRB, const GrImageInfo& srcInfo, const void* src, size_t srcRB, bool flipY = false);
#endif


text:
'use strict';

angular.module('myApp.view2', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view2', {
    templateUrl: 'view2/view2.html',
    controller: 'View2Ctrl'
  });
}])

.controller('View2Ctrl', [function($scope) {
    var gameState = {
    playerOneWins: 0,
    playerTwoWins: 0,
    gameOver: "",
    PLAYER_ONE: "X",
    PLAYER_TWO: "O",
    currentPlayer: "X",
    board: ["","","","","","","","",""]
    }

    var winningStates = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6]
    ]

    $scope.test = function(test){
      alert('test worked')
    }
    // Array of all win states. All we do is win
    $scope.resetBoard = function(){
      gameState.board = ["","","","","","","","",""]
      if (gameState.gameOver == ""){
        gameState.currentPlayer = gameState.PLAYER_ONE
      }
      gameState.gameOver = ""
      $scope.render()
    }

    $scope.checkWin = function(player) {
      var foundWinner = false
      gameState.winningStates.forEach(function(winners, i) {
      //winners => [6, 7, 8]
      //i => 2
        if(gameState.board[winners[0]] == player && // winners[0] => 6
           gameState.board[winners[1]] == player && // winners[1] => 7
           gameState.board[winners[2]] == player    // winners[2] => 8
          ) { foundWinner = true }
      })
      return foundWinner
    }
    //makePlay alternates the player
    //updates the board state
    //renders the board
    $scope.makePlay = function(cellId) {
      if (gameState.board[cellId] != ""){
        alert("Nice try, pick an empty square!")
        return false
      }
      if (gameState.gameOver != "" ){
        alert("Too late, suckaaa! Click new game")
        return false
      }
      gameState.board[cellId] = gameState.currentPlayer
      if (gameState.currentPlayer == gameState.PLAYER_ONE) {
        gameState.currentPlayer = gameState.PLAYER_TWO
      }
      else {
        gameState.currentPlayer = gameState.PLAYER_ONE
      }
      $scope.render()
    }
    $scope.checkCatsGame = function(){
      if (!gameState.board.includes("") && gameState.gameOver == ""){
        return true
      }
      else {
        return false
      }
    }
    $scope.render = function() {
      gameState.board.forEach(function (element, i){
        document.getElementById("cell"+i).innerHTML = element
        }
      )
      // does X win?
      if(gameState.checkWin(gameState.PLAYER_ONE)){
        document.getElementById("winner").innerHTML = "Congratulations Player One"
        gameState.gameOver = gameState.PLAYER_ONE
        gameState.playerOneWins++
        document.getElementById("p1Score").innerHTML = "Player One score: " + gameState.playerOneWins
      }
      // does O win?
      if($scope.checkWin(gameState.PLAYER_TWO)){
        document.getElementById("winner").innerHTML = "Congratulations Player Two"
        gameState.gameOver = gameState.PLAYER_TWO
        gameState.playerTwoWins++
        document.getElementById("p2Score").innerHTML = "Player Two score: " + gameState.playerTwoWins
      }
      if ($scope.checkCatsGame()){
        document.getElementById("winner").innerHTML = "Cats Game"
      }
    }

}]);


text:
import { Component, OnInit } from '@angular/core';
import { ShopOrderService } from '../../../service/shop/ShopOrderService';
import { TzBaseService } from '../../../service/TzBaseService';
import { Page } from '../../../entity/Page';
import { ShopOrder } from '../../../entity/shop/ShopOrder';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: '.m-grid__item.m-grid__item--fluid.m-wrapper',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit {
  formGroup: FormGroup;
  private fb: FormBuilder = new FormBuilder();
  // 行数据
  rows = [];
  // 表格数据是否在加载状态
  dataLoading = false;
  page: Page = new Page();
  shopOrder: ShopOrder;
  updatestatu: string;
  updatecontent: string;

  constructor(private tzBaseservice: TzBaseService, private orderService: ShopOrderService) {
    this.formGroup = this.fb.group({
      username: ['', Validators.required],
      phone: ['', Validators.required]
    });
  }

  ngOnInit() {
    this.refresh();
  }

  // 获取加载时的数据
  refresh(): void {
    this.dataLoading = true;
    this.orderService.getAllShopOrder(this.page).subscribe((res) => {
      this.rows = res.data;
      this.page.total = res.total;
      this.dataLoading = false;
    });
  }

  pageIndexChange(ev: any): void {
    console.log('---->当前页变化:', this.page.total);
    this.page.cPage = ev;
    this.refresh();
  }

  sizeChange(ev: any): void {
    console.log('---->页数大小:', this.page.total);
    this.page.pSize = ev;
    this.refresh();
  }

  showDetail(order_id: any) {
    console.log(order_id);
  }

  deleteById(order_id: string) {
    console.log('------------------' + order_id);
    this.tzBaseservice.modalService.confirm({
      title: '删除订单信息', content: '删除订单不可恢复,请谨慎操作!',
      onOk: () => {
        this.orderService.deleteOrder(order_id).subscribe(
          res => {
            this.tzBaseservice.messageService.success('删除成功');
            this.refresh();
          },
          err => {
            this.tzBaseservice.messageService.error('服务器内部错误');
            this.refresh();
          }
        );
      }
    });
  }

  openAddOrder(modal: any, order: ShopOrder = null) {
    this.tzBaseservice.modalService.open({ title: '添加订单', content: modal, footer: false });
  }

  updateOrder(data: ShopOrder) {
    console.log('接受参数' + data.status);
    if (data.status == 1) {
      this.updatestatu = '确认已经给用户发货?此操作将更改订单状态!';
      this.updatecontent = '发货确认';
      console.log('发货确认' + data.status);
    } else {
      if (data.status == 2) {
        this.updatestatu = '撤销发货?此操作将更改订单状态!';
        this.updatecontent = '撤销发货';
        console.log('撤销发货' + data.status);
      }
    }
    this.tzBaseservice.modalService.confirm({
      title: this.updatestatu, content: this.updatecontent,
      onOk: () => {
        let temp = data.status;
        console.log('最终状态' + data.status);
        if (data.status == 1) {
          data.status = data.status + 1;
        } else {
          data.status = data.status - 1;
        }
        this.orderService.updateOrderStatus(data).subscribe(
          res => {
            this.tzBaseservice.messageService.success('订单状态更改成功');
            this.refresh();
          },
          err => {
            data.status = temp;
            this.tzBaseservice.messageService.error('服务器内部错误');
            this.refresh();
          }
        );
      }
    });
  }
}


text:
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using HerpDesk.Models;
using HerpDesk.Models.TicketsViewModels;
using HerpDesk.Data;

namespace HerpDesk.Extensions
{
    public static class TicketExtensions
    {
        public static async Task<IEnumerable<TicketIndexViewModel>> GenerateViewModel(this IEnumerable<Ticket> source, ApplicationDbContext context)
        {
            List<TicketIndexViewModel> result = new List<TicketIndexViewModel>();
            List<ApplicationUser> users = await context.Users.ToListAsync();
            List<TicketAuthorLink> links = await context.Links.ToListAsync();
            foreach (var ticket in source)
            {
                var link = links.Where(c => c.TicketId == ticket.ID).FirstOrDefault();
                var author = users.Where(c => c.Id == link.AuthorId).FirstOrDefault();
                result.Add(new TicketIndexViewModel(ticket, author.Email));
            }
            return result;
        }
    }
}