text:
require 'httparty'
require 'json'

module Moip::Assinaturas

  class WebServerResponseError < StandardError ; end
  class MissingTokenError < StandardError ; end

  class Client
    include HTTParty

    if Moip::Assinaturas.sandbox
      base_uri "https://sandbox.moip.com.br/assinaturas/v1"
    else
      base_uri "https://api.moip.com.br/assinaturas/v1"
    end

    basic_auth Moip::Assinaturas.token, Moip::Assinaturas.key

    class << self

      def create_plan(plan)
        peform_action!(:post, "/plans", { body: plan.to_json, headers: { 'Content-Type' => 'application/json' } })
      end

      def list_plans
        peform_action!(:get, "/plans", { headers: { 'Content-Type' => 'application/json' } })
      end

      def details_plan(code)
        peform_action!(:get, "/plans/#{code}", { headers: { 'Content-Type' => 'application/json' } })
      end

      def create_customer(customer, new_vault)
        peform_action!(:post, "/customers?new_vault=#{new_vault}", { body: customer.to_json, headers: { 'Content-Type' => 'application/json' } })
      end

      def list_customers
        peform_action!(:get, "/customers", { headers: { 'Content-Type' => 'application/json' } })
      end

      def details_customer(code)
        peform_action!(:get, "/customers/#{code}", { headers: { 'Content-Type' => 'application/json' } })
      end

      def create_subscription(subscription, new_customer)
        peform_action!(:post, "/subscriptions?new_customer=#{new_customer}", { body: subscription.to_json, headers: { 'Content-Type' => 'application/json' } })
      end

      def list_subscriptions
        peform_action!(:get, "/subscriptions", { headers: { 'Content-Type' => 'application/json' } })
      end

      def details_subscription(code)
        peform_action!(:get, "/subscriptions/#{code}", { headers: { 'Content-Type' => 'application/json' } })
      end

      def suspend_subscription(code)
        peform_action!(:put, "/subscriptions/#{code}/suspend", { headers: { 'Content-Type' => 'application/json' } })
      end

      def activate_subscription(code)
        peform_action!(:put, "/subscriptions/#{code}/activate", { headers: { 'Content-Type' => 'application/json' } })
      end

      def list_invoices(subscription_code)
        peform_action!(:get, "/subscriptions/#{subscription_code}/invoices", { headers: { 'Content-Type' => 'application/json' } })
      end

      def details_invoice(id)
        peform_action!(:get, "/invoices/#{id}", { headers: { 'Content-Type' => 'application/json' } })
      end

      def list_payments(invoice_id)
        peform_action!(:get, "/invoices/#{invoice_id}/payments", { headers: { 'Content-Type' => 'application/json' } })
      end

      def details_payment(id)
        peform_action!(:get, "/payments/#{id}", { headers: { 'Content-Type' => 'application/json' } })
      end

      private

        def peform_action!(action_name, url, options = {})
          if (Moip::Assinaturas.token.blank? or Moip::Assinaturas.key.blank?)
            raise(MissingTokenError, "Informe o token e a key para realizar a autenticação no webservice")
          end

          response = self.send(action_name, url, options)
          raise(WebServerResponseError, "Ocorreu um erro ao chamar o webservice") if response.nil?
          response
        end

    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
package org.fcrepo.utilities;

public class TimestampedCacheEntry<T> {
	private long timeStamp;
	private final T object;

	public TimestampedCacheEntry(final T object) {
		this(System.currentTimeMillis(), object);
	}

    public TimestampedCacheEntry(final long timeStamp, final T object) {
        super();
        this.timeStamp = System.currentTimeMillis();
        this.object = object;
    }

    public TimestampedCacheEntry<T> refresh() {
        this.timeStamp = System.currentTimeMillis();
		return this;
	}

	public long timestamp() {
	    return this.timeStamp;
	}

	public long age() {
	    return System.currentTimeMillis() - this.timeStamp;
	}

	public T value() {
	    return this.object;
	}

}


text:
************************
Backup and Restore
************************

.. toctree::
    :maxdepth: 1

    backup_and_restore/catalog


text:
package com.intellij.ide.actionMacro.actions;

import com.intellij.ide.actionMacro.ActionMacro;
import com.intellij.ide.actionMacro.ActionMacroConfigurable;
import com.intellij.ide.actionMacro.ActionMacroManager;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.DumbAware;
import org.jetbrains.annotations.NotNull;

final class EditMacrosAction extends AnAction implements DumbAware {
  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    ShowSettingsUtil.getInstance().editConfigurable(e.getProject(),
                                                    "#com.intellij.ide.actionMacro.EditMacrosDialog",
                                                    new ActionMacroConfigurable());
  }

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return ActionUpdateThread.EDT;
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    ActionMacro[] macros = ActionMacroManager.getInstance().getAllMacros();
    e.getPresentation().setEnabled(macros.length > 0);
  }
}


text:
require 'spec_helper'

# Merb::Router.prepare do
#   default_routes
# end

describe Merb::Helpers::Tag do
  include Merb::Helpers::Tag

  describe "#tag" do
    it 'generates
content
 from tag :div, "content"' do
      response = visit "/tag_helper/tag_with_content"

      response.should have_selector("div")
      response.body.to_s.should include("Astral Projection ~ Dancing Galaxy")
    end

    it 'outputs content returned by the block when block is given'  do
      response = visit "/tag_helper/tag_with_content_in_the_block"

      response.should have_selector("div")
      response.body.should include("Astral Projection ~ Trust in Trance 1")
    end

    it 'generates tag attributes for all of keys of last Hash' do
      response = visit "/tag_helper/tag_with_attributes"

      response.should have_selector("div.psy")
      response.should have_selector("div#bands")
      response.should have_selector("div[invalid_attr='at least in html']")
    end

    it 'handles nesting of tags/blocks' do
      response = visit "/tag_helper/nested_tags"

      response.should have_selector("div.discography ul.albums li.first")
      response.should have_selector("#tit:contains('Trust in Trance 2')")
    end
  end
end


text:
package org.virtue.game.world.region;

/**
 * @author Im Frizzy <skype:kfriz1998>
 * @author Frosty Teh Snowman <skype:travis.mccorkle>
 * @author Arthur <skype:arthur.behesnilian>
 * @author Sundays211
 * @since 2/01/2015
 */
public enum MapSize {
	DEFAULT(0, 104),
	LARGE(1, 120),
	HUGE(3, 168),
	SMALL(4, 72);

	private int serialID;
	private int tiles;

	MapSize (int id, int tiles) {
		this.serialID = id;
		this.tiles = tiles;
	}

	public int getID () {
		return serialID;
	}

	public int getTileCount () {
		return tiles;
	}
}


text:
.class Landroid/net/wifi/IWifiScanner$Stub$Proxy;
.super Ljava/lang/Object;
.source "IWifiScanner.java"

# interfaces
.implements Landroid/net/wifi/IWifiScanner;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/wifi/IWifiScanner$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .locals 0
    .param p1, "remote"    # Landroid/os/IBinder;

    .prologue
    .line 85
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 86
    iput-object p1, p0, Landroid/net/wifi/IWifiScanner$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    .line 87
    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 1

    .prologue
    .line 90
    iget-object v0, p0, Landroid/net/wifi/IWifiScanner$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public getAvailableChannels(I)Landroid/os/Bundle;
    .locals 6
    .param p1, "band"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 120
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 121
    .local v0, "_data":Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 124
    .local v1, "_reply":Landroid/os/Parcel;
    :try_start_0
    const-string v3, "android.net.wifi.IWifiScanner"

    invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 125
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    .line 126
    iget-object v3, p0, Landroid/net/wifi/IWifiScanner$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v4, 0x2

    const/4 v5, 0x0

    invoke-interface {v3, v4, v0, v1, v5}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 127
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V

    .line 128
    invoke-virtual {v1}, Landroid/os/Parcel;->readInt()I

    move-result v3

    if-eqz v3, :cond_0

    .line 129
    sget-object v3, Landroid/os/Bundle;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v3, v1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Landroid/os/Bundle;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 136
    .local v2, "_result":Landroid/os/Bundle;
    :goto_0
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 137
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 139
    return-object v2

    .line 132
    .end local v2    # "_result":Landroid/os/Bundle;
    :cond_0
    const/4 v2, 0x0

    .restart local v2    # "_result":Landroid/os/Bundle;
    goto :goto_0

    .line 136
    .end local v2    # "_result":Landroid/os/Bundle;
    :catchall_0
    move-exception v3

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 137
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v3
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .locals 1

    .prologue
    .line 94
    const-string v0, "android.net.wifi.IWifiScanner"

    return-object v0
.end method

.method public getMessenger()Landroid/os/Messenger;
    .locals 6
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 98
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 99
    .local v0, "_data":Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 102
    .local v1, "_reply":Landroid/os/Parcel;
    :try_start_0
    const-string v3, "android.net.wifi.IWifiScanner"

    invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 103
    iget-object v3, p0, Landroid/net/wifi/IWifiScanner$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v4, 0x1

    const/4 v5, 0x0

    invoke-interface {v3, v4, v0, v1, v5}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 104
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V

    .line 105
    invoke-virtual {v1}, Landroid/os/Parcel;->readInt()I

    move-result v3

    if-eqz v3, :cond_0

    .line 106
    sget-object v3, Landroid/os/Messenger;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v3, v1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Landroid/os/Messenger;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 113
    .local v2, "_result":Landroid/os/Messenger;
    :goto_0
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 114
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 116
    return-object v2

    .line 109
    .end local v2    # "_result":Landroid/os/Messenger;
    :cond_0
    const/4 v2, 0x0

    .restart local v2    # "_result":Landroid/os/Messenger;
    goto :goto_0

    .line 113
    .end local v2    # "_result":Landroid/os/Messenger;
    :catchall_0
    move-exception v3

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 114
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v3
.end method


text:
[McNemar's test](https://www.wikiwand.com/en/McNemar's_test)
[Calculator](https://graphpad.com/quickcalcs/McNemar1.cfm)
[Calculator 2](https://scistatcalc.blogspot.com.tr/2013/11/mcnemars-test-calculator.html)

- Chi-squared statistic with Yates correction of `1.0`
- `95%` Confidence interval
- The calculated `p-value < 0.05` could be considered a significant result, rejecting the `Null Hypothesis` (compared two systems are not different).

```
gold: word2vec, test: word2vec_genia_ino
TN -> 586.0, FN -> 49.0, TP -> 377.0, FP -> 0.0
accuracy: 0.9515810276679841
precision: 1.0
recall: 0.8849765258215962
fscore: 0.9389788293897883

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 47.020 with 1 degrees of freedom.
```

```
gold: baseline, test: baseline_genia_ino
TN -> 701.0, FN -> 25.0, TP -> 215.0, FP -> 0.0
accuracy: 0.973432518597237
precision: 1.0
recall: 0.8958333333333334
fscore: 0.945054945054945

Corresponding p-value is 0.000002
The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 23.040 with 1 degrees of freedom.
```

```
gold: baseline, test: word2vec
TN -> 585.0, FN -> 7.0, TP -> 214.9615396139974, FP -> 215.0384603860026
accuracy: 0.782741232499019
precision: 0.4999105572418544
recall: 0.9684630048423102
fscore: 0.6594301244863868

McNemar chi-squared statistic with Yates correction of 1.0 is 193.013514
Corresponding p-value is 0.000000

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 193.014 with 1 degrees of freedom.

The odds ratio is 30.714, with a 95% confidence interval extending from 14.653 to 77.312
```

```
gold: baseline_genia_ino, test: word2vec_genia_ino
TN -> 629.0, FN -> 6.0, TP -> 190.9615396139974, FP -> 190.03846038600258
accuracy: 0.8070487594625958
precision: 0.5012113900629853
recall: 0.9695371999439143
fscore: 0.660810543696505

McNemar chi-squared statistic with Yates correction of 1.0 is 170.862245
Corresponding p-value is 0.000000

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 170.862 with 1 degrees of freedom.

The odds ratio is 31.667, with a 95% confidence interval extending from 14.282 to 87.375
```

```
gold: baseline, test: tfrf7
TN -> 445.0, FN -> 0.0, TP -> 218.790600507391, FP -> 622.2093994926089
accuracy: 0.5161668744225435
precision: 0.260155291923176
recall: 1.0
fscore: 0.4128940196349008

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 620.002 with 1 degrees of freedom.
```

```
gold: baseline, test: tfrf10
TN -> 304.0, FN -> 0.0, TP -> 212.46757659826125, FP -> 1208.532423401739
accuracy: 0.29940149368015145
precision: 0.14951975833797412
recall: 1.0
fscore: 0.26014299841902033

McNemar chi-squared statistic with Yates correction of 1.0 is 1206.000828
Corresponding p-value is 0.000000
```

```
gold: baseline, test: tfrfmanual
TN -> 633.0, FN -> 0.0, TP -> 224.10580249765727, FP -> 128.89419750234276
accuracy: 0.8692756617623298
precision: 0.6348606303049781
recall: 1.0
fscore: 0.7766541300667896

McNemar chi-squared statistic with Yates correction of 1.0 is 126.007813
Corresponding p-value is 0.000000

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 126.008 with 1 degrees of freedom.
```

```
gold: baseline_genia_ino, test: tfrf7_genia_ino
TN -> 506.0, FN -> 0.0, TP -> 196.88858025579924, FP -> 554.1114197442007
accuracy: 0.559179459232935
precision: 0.2621685489424757
recall: 1.0
fscore: 0.41542557713411105

Corresponding p-value is 0.000000

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 552.002 with 1 degrees of freedom.
```

```
gold: baseline_genia_ino, test: tfrf10_genia_ino
TN -> 382.0, FN -> 0.0, TP -> 190.5655563466695, FP -> 1097.4344436533306
accuracy: 0.34285362655489193
precision: 0.14795462449275582
recall: 1.0
fscore: 0.2577708584224436

McNemar chi-squared statistic with Yates correction of 1.0 is 1095.000912
Corresponding p-value is 0.000000
```

```
gold: baseline_genia_ino, test: tfrfmanual_genia_ino
TN -> 666.0, FN -> 0.0, TP -> 199.10580249765724, FP -> 115.89419750234275
accuracy: 0.8818611646255425
precision: 0.6320819126909754
recall: 1.0
fscore: 0.7745713101480295

Corresponding p-value is 0.000000
The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 113.009 with 1 degrees of freedom.
```

```
gold: tfrf7, test: tfrf7_genia_ino
TN -> 445.0, FN -> 89.0, TP -> 747.0, FP -> 0.0
accuracy: 0.9305230288836847
precision: 1.0
recall: 0.8935406698564593
fscore: 0.9437776373973468

McNemar chi-squared statistic with Yates correction of 1.0 is 87.011236
Corresponding p-value is 0.000000

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 87.011 with 1 degrees of freedom.
```

```
gold: tfrf10, test: tfrf10_genia_ino
TN -> 304.0, FN -> 132.0, TP -> 1282.0, FP -> 0.0
accuracy: 0.9231664726426076
precision: 1.0
recall: 0.9066478076379066
fscore: 0.9510385756676557

McNemar chi-squared statistic with Yates correction of 1.0 is 130.007576
Corresponding p-value is 0.000000

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 130.008 with 1 degrees of freedom.
```

```
gold: tfrfmanual, test: tfrfmanual_genia_ino
TN -> 633.0, FN -> 38.0, TP -> 313.0, FP -> 0.0
accuracy: 0.9613821138211383
precision: 1.0
recall: 0.8917378917378918
fscore: 0.9427710843373494

McNemar chi-squared statistic with Yates correction of 1.0 is 36.026316
Corresponding p-value is 0.000000

The two-tailed P value is less than 0.0001
By conventional criteria, this difference is considered to be extremely statistically significant.

The P value was calculated with McNemar's test with the continuity correction.
Chi squared equals 36.026 with 1 degrees of freedom.
```


text:
layout: page
title: About the author
tags: [about, Jekyll, theme, responsive]
modified: 2014-08-08T20:53:07.573882-04:00
comments: true
image:
  feature: kerry.jpg
---

Machine Learning Engineer and Researcher. I like good old fashioned
data structures and algorithms, algorithms for approximating hard
counting problems or sampling from intractable probability
distributions, C++, Lua, Python, Bash, Clojure, Emacs, functional
programming, software architecture, representation learning, Bayesian
machine learning, statistical language modelling and extracting
information from unstructured data, e.g. text. At the moment, I am
particularly interested in automated knowledge base construction,
building knowledge bases for inference, weak supervision, the
application of Deep Learning to Natural Language Understanding, and
writing Lua/C/CUDA code with [Torch7](http://torch.ch). I have been
slowly converted to Agile development, and am now an enthusiastic
supporter of using it in both engineering and research projects.

After a (brief) career as a Theoretical Computer Science researcher
([here](http://www.lfcs.inf.ed.ac.uk/research/complexity/) and
[here](https://www.cs.ox.ac.uk/activities/constraints/home.html)), I
spent 3 great years writing C++ and Clojure, and thinking about
language models and efficient algorithms and data structures, on the
SDK Team at [SwiftKey](http://www.swiftkey.com). Since March 2015,
I've been a Machine Learning Engineer and Researcher at
[Stratified Medical](http://www.stratifiedmedical.com), where I spend
a lot of my time trying to teach machines how to read scientific
articles.

All opinions expressed here are my own, and do not reflect the views
of my employers.


text:
import socket
import struct

from splunk_eventgen.lib.outputplugin import OutputPlugin

class S2S:
    """
    Encode and send events to Splunk over the S2S V2 wire protocol.

    It should be noted V2 is a much older protocol and is no longer utilized by any Splunk Forwarder.
    It should still work, but its a very simple protocol and we've advanced pretty far since then.
    However, if you have fully cooked events, its very lightweight and very easy to implement
    which is why I elected to implement this version.
    """

    s = None
    signature_sent = None
    useOutputQueue = True

    def __init__(self, host="localhost", port=9997):
        """
        Initialize object.  Need to know Splunk host and port for the TCP Receiver
        """
        self._open_connection(host, port)

        self.signature_sent = False

    def _open_connection(self, host="localhost", port=9997):
        """
        Open a connection to Splunk and return a socket
        """
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((host, int(port)))

    def _encode_sig(
        self, serverName="s2s-api".encode("utf-8"), mgmtPort="9997".encode("utf-8")
    ):
        """
        Create Signature element of the S2S Message.  Signature is C struct:

        struct S2S_Signature
        {
            char _signature[128];
            char _serverName[256];
            char _mgmtPort[16];
        };
        """
        if not self.signature_sent:
            self.signature_sent = True
            return struct.pack(
                "!128s256s16s",
                "--splunk-cooked-mode-v2--".encode("utf-8"),
                serverName,
                mgmtPort,
            ).decode("utf-8")
        else:
            return ""

    def _encode_string(self, tosend=""):
        """
        Encode a string to be sent across the wire to splunk

        Wire protocol has an unsigned integer of the length of the string followed
        by a null terminated string.
        """
        tosend = str(tosend).encode("utf-8")
        return struct.pack("!I%ds" % (len(tosend) + 1), len(tosend) + 1, tosend).decode(
            "utf-8"
        )

    def _encode_key_value(self, key="", value=""):
        """
        Encode a key/value pair to send across the wire to splunk

        A key value pair is merely a concatenated set of encoded strings.
        """
        return "%s%s" % (self._encode_string(key), self._encode_string(value))

    def _encode_event(
        self, index="main", host="", source="", sourcetype="", _raw="_done", _time=None
    ):
        # Create signature
        sig = self._encode_sig()

        msg_size = len(
            struct.pack("!I", 0)
        )  # size of unsigned 32 bit integer, which is the count of map entries
        maps = 1

        # May not have these, so set them first
        encoded_source = False
        encoded_sourcetype = False
        encoded_host = False

        # Encode source
        if len(source) > 0:
            encoded_source = self._encode_key_value(
                "MetaData:Source", "source::" + source
            )
            maps += 1
            msg_size += len(encoded_source)

        # Encode sourcetype
        if len(sourcetype) > 0:
            encoded_sourcetype = self._encode_key_value(
                "MetaData:Sourcetype", "sourcetype::" + sourcetype
            )
            maps += 1
            msg_size += len(encoded_sourcetype)

        # Encode host
        if len(host) > 0:
            encoded_host = self._encode_key_value("MetaData:Host", "host::" + host)
            maps += 1
            msg_size += len(encoded_host)

        # Encode index
        encoded_index = self._encode_key_value("_MetaData:Index", index)
        maps += 1
        msg_size += len(encoded_index)

        # Encode _raw
        encoded_raw = self._encode_key_value("_raw", _raw)
        msg_size += len(encoded_raw)

        # Will include a 32 bit integer 0 between the end of raw and the _raw trailer
        msg_size += len(struct.pack("!I", 0))

        # Encode "_raw" trailer... seems to just the string '_raw' repeated again at the end of the _raw field
        encoded_raw_trailer = self._encode_string("_raw")
        msg_size += len(encoded_raw_trailer)

        # Add _done... Not sure if there's a penalty to setting this for every event
        # but otherwise we don't flush immediately
        encoded_done = self._encode_key_value("_done", "_done")
        maps += 1
        msg_size += len(encoded_done)

        # Encode _time
        if _time is not None:
            encoded_time = self._encode_key_value("_time", _time)
            msg_size += len(encoded_time)
            maps += 1

        # Create buffer, starting with the signature
        buf = sig
        # Add 32 bit integer with the size of the msg, calculated earlier
        buf += struct.pack("!I", msg_size).decode("utf-8")
        # Add number of map entries, which is 5, index, host, source, sourcetype, raw
        buf += struct.pack("!I", maps).decode("utf-8")
        # Add the map entries, index, source, sourcetype, host, raw
        buf += encoded_index
        buf += encoded_host if encoded_host else ""
        buf += encoded_source if encoded_source else ""
        buf += encoded_sourcetype if encoded_sourcetype else ""
        buf += encoded_time if encoded_time else ""
        buf += encoded_done
        buf += encoded_raw
        # Add dummy zero
        buf += struct.pack("!I", 0).decode("utf-8")
        # Add trailer raw
        buf += encoded_raw_trailer
        return buf

    def send_event(
        self, index="main", host="", source="", sourcetype="", _raw="", _time=None
    ):
        """
        Encode and send an event to Splunk
        """
        if len(_raw) > 0:
            e = self._encode_event(index, host, source, sourcetype, _raw, _time)
            self.s.sendall(e.encode("utf-8"))

    def close(self):
        """
        Close connection and send final done event
        """
        self.s.close()

class S2SOutputPlugin(OutputPlugin):
    name = "s2s"
    MAXQUEUELENGTH = 10
    s2s = None
    useOutputQueue = True

    def __init__(self, sample, output_counter=None):
        OutputPlugin.__init__(self, sample, output_counter)

    def flush(self, q):
        if len(q) < 1:
            return
        if self.s2s is None:
            self.s2s = S2S(self._sample.splunkHost, self._sample.splunkPort)
        for m in q:
            self.s2s.send_event(
                m["index"],
                m["host"],
                m["source"],
                m["sourcetype"],
                m["_raw"],
                m["_time"],
            )

def load():
    """Returns an instance of the plugin"""
    return S2SOutputPlugin


text:
var example = 'example string';

console.log(example.length);


text:
(function() {
    var showErrorsModule;

    showErrorsModule = angular.module('ui.bootstrap.showErrors', []);

    showErrorsModule.directive('showErrors', [
        '$timeout', 'showErrorsConfig', '$interpolate', function($timeout, showErrorsConfig, $interpolate) {
            var getShowSuccess, getTrigger, linkFn;
            getTrigger = function(options) {
                var trigger;
                trigger = showErrorsConfig.trigger;
                if (options && (options.trigger != null)) {
                    trigger = options.trigger;
                }
                return trigger;
            };
            getShowSuccess = function(options) {
                var showSuccess;
                showSuccess = showErrorsConfig.showSuccess;
                if (options && (options.showSuccess != null)) {
                    showSuccess = options.showSuccess;
                }
                return showSuccess;
            };
            linkFn = function(scope, el, attrs, formCtrl) {
                var blurred, inputEl, inputName, inputNgEl, options, showSuccess, toggleClasses, trigger;
                blurred = false;
                options = scope.$eval(attrs.showErrors);
                showSuccess = getShowSuccess(options);
                trigger = getTrigger(options);
                inputEl = el[0].querySelector('.form-control[name]');
                inputNgEl = angular.element(inputEl);
                inputName = $interpolate(inputNgEl.attr('name') || '')(scope);
                if (!inputName) {
                    throw "show-errors element has no child input elements with a 'name' attribute and a 'form-control' class";
                }
                inputNgEl.bind(trigger, function() {
                    blurred = true;
                    return toggleClasses(formCtrl[inputName].$invalid);
                });
                scope.$watch(function() {
                    return formCtrl[inputName] && formCtrl[inputName].$invalid;
                }, function(invalid) {
                    if (!blurred) {
                        return;
                    }
                    return toggleClasses(invalid);
                });
                scope.$on('show-errors-check-validity', function() {
                    return toggleClasses(formCtrl[inputName].$invalid);
                });
                scope.$on('show-errors-reset', function() {
                    return $timeout(function() {
                        el.removeClass('has-error');
                        el.removeClass('has-success');
                        return blurred = false;
                    }, 0, false);
                });
                return toggleClasses = function(invalid) {
                    el.toggleClass('has-error', invalid);
                    if (showSuccess) {
                        return el.toggleClass('has-success', !invalid);
                    }
                };
            };
            return {
                restrict: 'A',
                require: '^form',
                compile: function(elem, attrs) {
                    if (attrs['showErrors'].indexOf('skipFormGroupCheck') === -1) {
                        if (!(elem.hasClass('form-group') || elem.hasClass('input-group'))) {
                            throw "show-errors element does not have the 'form-group' or 'input-group' class";
                        }
                    }
                    return linkFn;
                }
            };
        }
    ]);

    showErrorsModule.provider('showErrorsConfig', function() {
        var _showSuccess, _trigger;
        _showSuccess = false;
        _trigger = 'blur';
        this.showSuccess = function(showSuccess) {
            return _showSuccess = showSuccess;
        };
        this.trigger = function(trigger) {
            return _trigger = trigger;
        };
        this.$get = function() {
            return {
                showSuccess: _showSuccess,
                trigger: _trigger
            };
        };
    });

}).call(this);


text:
@interface MsgModel : NSObject
@property (nonatomic,copy) NSString *msg;
@property (nonatomic,assign) BOOL isRight;
@end


text: from .dashboard import run  # noqa: F401


text:
import React, { Component, PropTypes } from 'react';

import {
  createMarkers,
  getLocationByName,
  getNewMap,
  loadMapApi
} from './utils';

export default class GenerationMap extends Component {
  static propTypes = {
    addMarkerToStore: PropTypes.func.isRequired,
    headerHeight: PropTypes.string.isRequired,
    markerLostFocus: PropTypes.func.isRequired,
    showStoreInfo: PropTypes.func.isRequired,
    stores: PropTypes.array.isRequired
  };

  mapStyle = {
    width: '100%',
    height: `calc(100vh - ${this.props.headerHeight})`
  };

  componentDidMount() {
    this.initMap();
  }

  async initMap() {
    await loadMapApi();
    // create geocoder instance
    const geocoder = new google.maps.Geocoder();
    this.setState({ geocoder });
    // get location
    const location = await getLocationByName(geocoder, 'Mexico City');
    // get map instance
    const map = getNewMap(location, this.refs.map, this.props.markerLostFocus);
    this.setState({ map });
    // create markers
    const { addMarkerToStore, showStoreInfo, stores } = this.props;
    createMarkers(addMarkerToStore, geocoder, map, showStoreInfo, stores);
  }

  render() {
    return (

        {this.props.children}

    );
  }
}


text:
from google.cloud import dialogflowcx_v3beta1

def sample_delete_webhook():
    # Create a client
    client = dialogflowcx_v3beta1.WebhooksClient()

    # Initialize request argument(s)
    request = dialogflowcx_v3beta1.DeleteWebhookRequest(
        name="name_value",
    )

    # Make the request
    client.delete_webhook(request=request)

# [END dialogflow_v3beta1_generated_Webhooks_DeleteWebhook_sync]


text:
function [type] = ft_voltype(vol, desired)

% FT_VOLTYPE determines the type of volume conduction model
%
% Use as
%   [type] = ft_voltype(vol)
% to get a string describing the type, or
%   [flag] = ft_voltype(vol, desired)
% to get a boolean value.
%
% The volume conduction model types that are recognized are
%
%  singlesphere    analytical single sphere model for EEG or MEG
%  multisphere     local spheres model for MEG, one sphere per channel
%  concentric      analytical 4-sphere model for EEG
%  infinite        infinite homogenous medium
%  openmeeg    volume based on the OpenMEEG boundary element implementation
%  bemcp           volume based on the implementation from Christophe Phillips
%  dipoli      volume based on the implementation from Thom Oostendorp
%  asa         volume based on the (commercial) ASA software
%  simbio          volume based on the FEM SimBio software
%  fns             volume based on the FNS finite differences software
%
% See also FT_READ_VOL, FT_COMPUTE_LEADFIELD

% Copyright (C) 2007-2010, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_voltype.m 5590 2012-04-04 10:50:35Z roboos $

% these are for remembering the type on subsequent calls with the same input arguments
persistent previous_argin previous_argout

vol = ft_datatype_headmodel(vol);

if iscell(vol) && numel(vol)<4
  % this might represent combined EEG, ECoG and/or MEG
  type = cell(size(vol));
  if nargin<2
    desired = cell(size(vol)); % empty elements
  end
  for i=1:numel(vol)
    type{i} = ft_voltype(vol{i}, desired{i});
  end
  return
end

if nargin<2
  % ensure that all input arguments are defined
  desired = [];
end

current_argin = {vol, desired};
if isequal(current_argin, previous_argin)
  % don't do the type detection again, but return the previous values from cache
  type = previous_argout{1};
  return
end

if isfield(vol, 'type')
  % preferably the structure specifies its own type
  type = vol.type;

elseif isfield(vol, 'r') && numel(vol.r)==1 && ~isfield(vol, 'label')
  type = 'singlesphere';

elseif isfield(vol, 'r') && isfield(vol, 'o') && isfield(vol, 'label')
  % this is before the spheres have been assigned to the coils
  % and every sphere is still associated with a channel
  type = 'multisphere';

elseif isfield(vol, 'r') && isfield(vol, 'o') && size(vol.r,1)==size(vol.o,1) && size(vol.r,1)>4
  % this is after the spheres have been assigned to the coils
  % note that this one is easy to confuse with the concentric one
  type = 'multisphere';

elseif isfield(vol, 'r') && numel(vol.r)>=2 && ~isfield(vol, 'label')
  type = 'concentric';

elseif isfield(vol, 'bnd') && strcmp(type, {'dipoli', 'asa', 'bemcp', 'openmeeg'})
  type = any(strcmp(type, {'dipoli', 'asa', 'bemcp', 'openmeeg'}));

elseif isempty(vol)
  type = 'infinite';

else
  type = 'unknown';

end % if isfield(vol, 'type')

if ~isempty(desired)
  % return a boolean flag
  switch desired
    case 'bem'
      type = any(strcmp(type, {'dipoli', 'asa', 'bemcp', 'openmeeg'}));
    otherwise
      type = any(strcmp(type, desired));
  end % switch desired
end % detemine the correspondence to the desired type

% remember the current input and output arguments, so that they can be
% reused on a subsequent call in case the same input argument is given
current_argout  = {type};
previous_argin  = current_argin;
previous_argout = current_argout;

return % voltype main()


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var Number = require( '@stdlib/number/ctor' );
var isNonPositiveNumber = require( './../lib/primitive.js' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof isNonPositiveNumber, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns `true` if provided a primitive number having a nonpositive number value', function test( t ) {
	t.equal( isNonPositiveNumber( -3.0 ), true, 'returns true' );
	t.end();
});

tape( 'the function returns `false` if provided a number object, even if the number has a nonpositive number value', function test( t ) {
	t.equal( isNonPositiveNumber( new Number( -5.0 ) ), false, 'returns false' ); // eslint-disable-line no-new-wrappers
	t.end();
});

tape( 'the function returns `false` if not provided a number', function test( t ) {
	var values;
	var i;

	values = [
		'-5',
		null,
		true,
		void 0,
		[],
		{},
		function noop() {}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.equal( isNonPositiveNumber( values[i] ), false, 'returns false when provided '+values[i] );
	}
	t.end();
});


text:
require 'test_helper'

class TicketQueueTest < ActiveSupport::TestCase

  should validate_presence_of(:name)
  should validate_uniqueness_of(:name)

  should validate_presence_of(:description)
  should validate_presence_of(:url)
  should validate_presence_of(:priority)
  should validate_presence_of(:default_due_in)
  should validate_presence_of(:start_date)

  should have_many(:tickets)

  context 'A given ticket queue' do

    setup do
      @ticket_queue = ticket_queues(:one)
    end

    should 'require a name' do
      @ticket_queue.name = nil
      @ticket_queue.valid?
      assert @ticket_queue.errors[:name].any? == true
    end

    should 'require a uniqie name' do
      @ticket_queue.name = 'Queue2'
      @ticket_queue.valid?
      assert @ticket_queue.errors[:name].any? == true
    end

    should 'require a description' do
      @ticket_queue.description = nil
      @ticket_queue.valid?
      assert @ticket_queue.errors[:description].any? == true
    end

    should 'require a url' do
      @ticket_queue.url = nil
      @ticket_queue.valid?
      assert @ticket_queue.errors[:url].any? == true
    end

    should 'require a priority' do
      @ticket_queue.priority = nil
      @ticket_queue.valid?
      assert @ticket_queue.errors[:priority].any? == true
    end

    should 'require a default due in' do
      @ticket_queue.default_due_in = nil
      @ticket_queue.valid?
      assert @ticket_queue.errors[:default_due_in].any? == true
    end

    should 'require a start_date' do
      @ticket_queue.start_date = nil
      @ticket_queue.valid?
      assert @ticket_queue.errors[:start_date].any? == true
    end

    should 'require a start date if an end date is present' do
      @ticket_queue.start_date = nil
      @ticket_queue.end_date = Date.today()
      @ticket_queue.valid?
      assert @ticket_queue.errors[:end_date].any? == true
      assert_equal @ticket_queue.errors[:end_date].join(';'), "requires a start date"
    end

    should 'require an end date on or after start date' do
      @ticket_queue.start_date = Date.today
      @ticket_queue.end_date = Date.today - 1.day
      @ticket_queue.valid?
      assert @ticket_queue.errors[:end_date].any? == true
      assert_equal @ticket_queue.errors[:end_date].join(';'), "cannot be less than the start date"
    end

  end # a given ticket queue

  context 'A new ticket queue' do

    setup do
      @ticket_queue = TicketQueue.new()
    end

    should 'require a name' do
      @ticket_queue.valid?
      assert @ticket_queue.errors[:name].any? == true
      @ticket_queue.name = "QueueName"
      @ticket_queue.valid?
      assert @ticket_queue.errors[:name].any? == false
    end

    should 'require a uniqie name' do
      @ticket_queue.name = 'Queue2'
      @ticket_queue.valid?
      assert @ticket_queue.errors[:name].any? == true
    end

    should 'require a description' do
      @ticket_queue.valid?
      assert @ticket_queue.errors[:description].any? == true
      @ticket_queue.description = 'A description'
      @ticket_queue.valid?
      assert @ticket_queue.errors[:description].any? == false
    end

    should 'require a url' do
      @ticket_queue.valid?
      assert @ticket_queue.errors[:url].any? == true
      @ticket_queue.url = 'vanderbilt.edu'
      @ticket_queue.valid?
      assert @ticket_queue.errors[:url].any? == false
    end

    should 'require a priority' do
      @ticket_queue.valid?
      assert @ticket_queue.errors[:priority].any? == true
      @ticket_queue.priority = 1
      @ticket_queue.valid?
      assert @ticket_queue.errors[:priority].any? == false
    end

    should 'require a default due in' do
      @ticket_queue.valid?
      assert @ticket_queue.errors[:default_due_in].any? == true
      @ticket_queue.default_due_in = 3
      @ticket_queue.valid?
      assert @ticket_queue.errors[:default_due_in].any? == false
    end

    should 'require a start_date' do
      @ticket_queue.valid?
      assert @ticket_queue.errors[:start_date].any? == true
      @ticket_queue.start_date = Date.today()
      @ticket_queue.valid?
      assert @ticket_queue.errors[:start_date].any? == false
    end

    should 'require a start date if an end date is present' do
      @ticket_queue.end_date = Date.today()
      @ticket_queue.valid?
      assert @ticket_queue.errors[:end_date].any? == true
      assert_equal @ticket_queue.errors[:end_date].join(';'), "requires a start date"
    end

    should 'require an end date on or after start date' do
      @ticket_queue.start_date = Date.today
      @ticket_queue.end_date = Date.today - 1.day
      @ticket_queue.valid?
      assert @ticket_queue.errors[:end_date].any? == true
      assert_equal @ticket_queue.errors[:end_date].join(';'), "cannot be less than the start date"
    end

  end # a new ticket queue

end


text:
class CreateFavorites < ActiveRecord::Migration
  def change
    create_table :favorites do |t|
      t.references :recipe, index: true
      t.references :user, index: true

      t.timestamps
    end
  end
end


text:
package net.minecraft.network.status.server;

import java.io.IOException;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.status.INetHandlerStatusClient;

public class S01PacketPong implements Packet<INetHandlerStatusClient>
{
    private long clientTime;

    public S01PacketPong()
    {
    }

    public S01PacketPong(long time)
    {
        this.clientTime = time;
    }

    /**
     * Reads the raw packet data from the data stream.
     */
    public void readPacketData(PacketBuffer buf) throws IOException
    {
        this.clientTime = buf.readLong();
    }

    /**
     * Writes the raw packet data to the data stream.
     */
    public void writePacketData(PacketBuffer buf) throws IOException
    {
        buf.writeLong(this.clientTime);
    }

    /**
     * Passes this Packet on to the NetHandler for processing.
     */
    public void processPacket(INetHandlerStatusClient handler)
    {
        handler.handlePong(this);
    }
}


text:
"""Test valid templates."""
#
# (C) Pywikibot team, 2015-2019
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, division, unicode_literals

import os

import pywikibot
from pywikibot import i18n
from pywikibot.textlib import extract_templates_and_params_regex_simple

from tests.aspects import unittest, MetaTestCaseClass, TestCase
from tests.utils import add_metaclass

PACKAGES = (
    'redirect-broken-redirect-template',  # speedy deletion template
    'archivebot-archiveheader',  # archive header template
)

class TestValidTemplateMeta(MetaTestCaseClass):

    """Test meta class."""

    def __new__(cls, name, bases, dct):
        """Create the new class."""
        def test_method(site, package):

            def test_template(self):
                """Test validity of template."""
                lang = site.lang
                if lang not in keys:
                    return

                if not i18n.twhas_key(lang, package):
                    return

                msg = i18n.twtranslate(lang, package, fallback=False)

                # check whether the message contains a template
                templates = extract_templates_and_params_regex_simple(msg)
                self.assertIsInstance(templates, list)
                self.assertIsNotEmpty(templates)

                # known problems
                if (package == PACKAGES[0] and site.code in ['simple', 'test2']
                        or package == PACKAGES[1] and site.code == 'test'):
                    raise unittest.SkipTest(
                        "{site} wiki has '{site.lang}' language code but "
                        "missing template for package '{package}'. Must be "
                        'solved by the corresponding script.'
                        .format(site=site, package=package))

                # check whether template exists
                title = templates[0][0]
                page = pywikibot.Page(site, title, ns=10)
                self.assertTrue(
                    page.exists(),
                    msg='Invalid L10N in package "{package}"\n'
                    'template "{title}" does not exist for lang '
                    '"{site.lang}" on site "{site}"'
                    .format(package=package, title=title, site=site))

            return test_template

        # create test methods for package messages processed by unittest
        site = pywikibot.Site(dct['code'], dct['family'])
        codes = site.family.languages_by_size
        del site
        for package in PACKAGES:
            keys = i18n.twget_keys(package)
            for code in codes:
                current_site = pywikibot.Site(code, dct['family'])
                test_name = ('test_{}_{}'
                             .format(package, code)).replace('-', '_')
                cls.add_method(
                    dct, test_name, test_method(current_site, package),
                    doc_suffix='{0} and language {1}'.format(
                        package, code))

        return super(TestValidTemplateMeta, cls).__new__(cls, name, bases, dct)

@add_metaclass
class TestValidTemplate(TestCase):

    """Test cases L10N message templates processed by unittest."""

    __metaclass__ = TestValidTemplateMeta

    family = 'wikipedia'
    code = 'en'

    @classmethod
    def setUpClass(cls):
        """Skip test gracefully if i18n package is missing."""
        super(TestValidTemplate, cls).setUpClass()
        if not i18n.messages_available():
            raise unittest.SkipTest("i18n messages package '{}' not available."
                                    .format(i18n._messages_package_name))

class TestSites(TestCase):

    """Other test L10N cases processed by unittest."""

    family = 'wikipedia'
    code = 'en'

    def test_valid_sites(self):
        """Test whether language key has a corresponding site."""
        codes = self.site.family.languages_by_size
        languages = {pywikibot.Site(code, self.family).lang for code in codes}
        # langs used by foreign wikis
        languages.update(('pt-br', 'zh-tw'))
        for package in PACKAGES:
            keys = i18n.twget_keys(package)
            for key in keys:
                with self.subTest(package=package, key=key):
                    self.assertIn(key, languages,
                                  "json key '{}' is not a site language"
                                  .format(key))

def setUpModule():  # noqa: N802
    """Skip Travis tests if PYWIKIBOT_NO_L10N_TESTS variable is set."""
    if os.environ.get('PYWIKIBOT_NO_L10N_TESTS', '0') == '1':
        raise unittest.SkipTest('L10N tests disabled.')

if __name__ == '__main__':  # pragma: no cover
    try:
        unittest.main()
    except SystemExit:
        pass


text:
package net.ihiroky.niotty;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
import static org.mockito.Mockito.*;

/**
 * @author Hiroki Itoh
 */
public class DefaultTransportFutureTest {

    private DefaultTransportFuture sut_;
    private Listener listener_;

    private static ExecutorService executor_;

    @BeforeClass
    public static void setUpClass() {
        executor_ = Executors.newCachedThreadPool();
    }

    @AfterClass
    public static void tearDownClass() {
        executor_.shutdownNow();
        executor_ = null;
    }

    @Before
    public void setUp() {
        @SuppressWarnings("unchecked")
        AbstractTransport transport = mock(AbstractTransport.class);
        EventDispatcher eventDispatcher = mock(EventDispatcher.class);
        when(eventDispatcher.isInDispatcherThread()).thenReturn(true);
        when(transport.eventDispatcher()).thenReturn(eventDispatcher);
        sut_ = new DefaultTransportFuture(transport);
        listener_ = new Listener();
    }

    @Test
    public void testSetThrowable_CallListenerOnce() throws Exception {
        sut_.addListener(listener_);
        Exception e = new Exception();
        sut_.setThrowable(e);
        sut_.setThrowable(e);

        assertThat(listener_.count(), is(1));
        assertThat(listener_.future(), is(sut_));
    }

    @Test
    public void testDone_CallListenerOnce() throws Exception {
        sut_.addListener(listener_);
        sut_.done();
        sut_.done();

        assertThat(listener_.count(), is(1));
        assertThat(listener_.future(), is(sut_));
    }

    @Test
    public void testCancel_CallListenerOnce() throws Exception {
        sut_.addListener(listener_);
        sut_.cancel();
        sut_.cancel();

        assertThat(listener_.count(), is(1));
        assertThat(listener_.future(), is(sut_));
    }
    @Test(expected = IndexOutOfBoundsException.class)
    public void testThrowRuntimeExceptionIfFailed_ThrowableIsIndexOutOfBoundException() throws Exception {
        sut_.executing();
        sut_.setThrowable(new IndexOutOfBoundsException());
        sut_.throwRuntimeExceptionIfFailed();
    }

    @Test
    public void testThrowRuntimeExceptionIfFailed_ThrowableIsIOException() throws Exception {
        sut_.executing();
        sut_.setThrowable(new IOException());

        try {
            sut_.throwRuntimeExceptionIfFailed();
        } catch (RuntimeException re) {
            Throwable t = re.getCause();
            assertThat(t, is(instanceOf(IOException.class)));
        }
    }

    @Test(expected = AssertionError.class)
    public void testThrowRuntimeExceptionIfFailed_ThrowableIsAssertionError() throws Exception {
        sut_.executing();
        sut_.setThrowable(new AssertionError());
        sut_.throwRuntimeExceptionIfFailed();
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void testThrowExceptionIfFailed_ThrowableIsIndexOutOfBoundException() throws Exception {
        sut_.executing();
        sut_.setThrowable(new IndexOutOfBoundsException());
        sut_.throwExceptionIfFailed();
    }

    @Test(expected = IOException.class)
    public void testThrowExceptionIfFailed_ThrowableIsIOException() throws Exception {
        sut_.executing();
        sut_.setThrowable(new IOException());
        sut_.throwExceptionIfFailed();
    }

    @Test(expected = AssertionError.class)
    public void testThrowExceptionIfFailed_ThrowableIsAssertionError() throws Exception {
        sut_.executing();
        sut_.setThrowable(new AssertionError());
        sut_.throwExceptionIfFailed();
    }

    @Test
    public void testIsCancelled_ReturnsTrueIfCancelled() throws Exception {
        sut_.cancel();
        assertThat(sut_.isCancelled(), is(true));
    }

    @Test
    public void testIsCancelled_ReturnsFalseIfDone() throws Exception {
        sut_.executing();
        sut_.done();
        assertThat(sut_.isCancelled(), is(false));
    }

    @Test
    public void testIsCancelled_ReturnsFalseByDefault() throws Exception {
        assertThat(sut_.isCancelled(), is(false));
    }

    @Test
    public void testIsCancelled_ReturnsFalseIfExecuting() throws Exception {
        sut_.executing();
        assertThat(sut_.isCancelled(), is(false));
    }

    @Test
    public void testIsSuccessful_ReturnsTrueIfDoneAndNoThrowable() throws Exception {
        sut_.executing();
        sut_.done();
        assertThat(sut_.isSuccessful(), is(true));
    }

    @Test
    public void testIsSuccessful_ReturnsTrueIfNotExecutingBeforeDone() throws Exception {
        sut_.done();
        assertThat(sut_.isSuccessful(), is(true));
    }

    @Test
    public void testIsSuccessful_ReturnsFalseIfSetThrowable() throws Exception {
        sut_.executing();
        sut_.setThrowable(new Exception());
        assertThat(sut_.isSuccessful(), is(false));
    }

    @Test
    public void testIsSuccessful_ReturnsFalseByDefault() throws Exception {
        assertThat(sut_.isSuccessful(), is(false));
    }

    @Test
    public void testIsSuccessful_ReturnsFalseIfExecuting() throws Exception {
        sut_.executing();
        assertThat(sut_.isSuccessful(), is(false));
    }
    @Test
    public void testIsDone_ReturnFalseByDefault() throws Exception {
        assertThat(sut_.isDone(), is(false));
    }

    @Test
    public void testIsDone_ReturnTrueIfDone() throws Exception {
        sut_.executing();
        sut_.done();
        assertThat(sut_.isDone(), is(true));
    }

    @Test
    public void testThrowable_ReturnNullIfNotSetThrowable() throws Exception {
        assertThat(sut_.throwable(), is(nullValue()));
    }

    @Test
    public void testThrowable_ReturnInstanceIfSetThrowable() throws Exception {
        Exception e = new Exception();
        sut_.executing();
        sut_.setThrowable(e);
        assertThat(sut_.throwable(), is((Throwable) e));
    }

    @Test
    public void testThrowable_ReturnsInstanceIfNotExecutingBeforeSet() throws Exception {
        Exception e = new Exception();
        sut_.setThrowable(e);
        assertThat(sut_.throwable(), is((Throwable) e));
    }

    @Test(timeout = 1000)
    public void testAwait() throws Exception {
        long start = System.currentTimeMillis();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    sut_.done();
                } catch (Exception e) {
                    sut_.setThrowable(e);
                }
            }
        });
        sut_.await();
        long elapsed = System.currentTimeMillis() - start;
        assertThat(Long.toString(elapsed), elapsed >= 10, is(true));
    }

    @Test(expected = InterruptedException.class)
    public void testAwait_ThrowsInterruptedExceptionIfInterrupted() throws Exception {
        final Thread thread = Thread.currentThread();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10);
                    thread.interrupt();
                } catch (Exception ignored) {
                }
            }
        });
        sut_.await();
    }

    @Test(timeout = 1000)
    public void testAwaitUninterruptibly() throws Exception {
        long start = System.currentTimeMillis();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    sut_.done();
                } catch (Exception e) {
                    sut_.setThrowable(e);
                }
            }
        });
        sut_.awaitUninterruptibly();
        long elapsed = System.currentTimeMillis() - start;
        assertThat(Long.toString(elapsed), elapsed >= 10, is(true));
    }

    @Test
    public void testAwaitUninterruptibly_InterruptedIfInterrupted() throws Exception {
        final Thread thread = Thread.currentThread();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    thread.interrupt();
                    sut_.done();
                } catch (Exception e) {
                    sut_.setThrowable(e);
                }
            }
        });
        sut_.awaitUninterruptibly();
        assertThat(Thread.interrupted(), is(true));
    }

    @Test(timeout = 1000)
    public void testAwaitTimeout_InTimeout() throws Exception {
        long start = System.currentTimeMillis();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    sut_.done();
                } catch (Exception e) {
                    sut_.setThrowable(e);
                }
            }
        });
        sut_.await(100, TimeUnit.MILLISECONDS);
        long elapsed = System.currentTimeMillis() - start;
        assertThat(Long.toString(elapsed), elapsed >= 10 && elapsed <= 100, is(true));
    }

    @Test(timeout = 1000)
    public void testAwaitTimeout_ExceedsTimeout() throws Exception {
        long start = System.currentTimeMillis();
//        executor_.execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(100);
//                    sut_.done();
//                } catch (Exception ignored) {
//                }
//            }
//        });
        sut_.await(10, TimeUnit.MILLISECONDS);
        long elapsed = System.currentTimeMillis() - start;
        assertThat(Long.toString(elapsed), elapsed >= 10 && elapsed < 100, is(true));
    }

    @Test(expected = InterruptedException.class, timeout = 1000)
    public void testWaitCompletionTimeout_ThrowsInterruptedExceptionIfInterrupted() throws Exception {
        final Thread thread = Thread.currentThread();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10);
                    thread.interrupt();
                } catch (Exception ignored) {
                }
            }
        });
        sut_.await(100, TimeUnit.MILLISECONDS);
    }

    @Test(timeout = 1000)
    public void testAwaitUninterruptiblyTimeout_InTimeout() throws Exception {
        long start = System.currentTimeMillis();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    sut_.done();
                } catch (Exception e) {
                    sut_.setThrowable(e);
                }
            }
        });
        sut_.awaitUninterruptibly(100, TimeUnit.MILLISECONDS);
        long elapsed = System.currentTimeMillis() - start;
        assertThat(Long.toString(elapsed), elapsed >= 10, is(true));
    }

    @Test(timeout = 1000)
    public void testAwaitUninterruptiblyTimeout_ExceedsTimeout() throws Exception {
        long start = System.currentTimeMillis();
//        executor_.execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(10);
//                    sut_.done();
//                } catch (Exception ignored) {
//                }
//            }
//        });
        sut_.awaitUninterruptibly(10, TimeUnit.MILLISECONDS);
        long elapsed = System.currentTimeMillis() - start;
        assertThat(Long.toString(elapsed), elapsed >= 10, is(true));
    }

    @Test(timeout = 1000)
    public void testAwaitUninterruptiblyTimeout_InterruptedIfInterrupted() throws Exception {
        final Thread thread = Thread.currentThread();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    thread.interrupt();
                    sut_.done();
                } catch (Exception ignored) {
                }
            }
        });
        sut_.awaitUninterruptibly(1000, TimeUnit.MILLISECONDS);
        assertThat(Thread.interrupted(), is(true));
    }

    @Test
    public void testJoin_ExceptionIfInterrupted() throws Exception {
        final Thread thread = Thread.currentThread();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    thread.interrupt();
                } catch (Exception ignored) {
                }
            }
        });
        try {
            sut_.join();
            throw new AssertionError();
        } catch (TransportException te) {
            assertThat(te.getCause(), is(instanceOf(InterruptedException.class)));
        }
    }

    @Test
    public void testJoin_ExceptionIfCancelled() throws Exception {
        sut_.cancel();
        try {
            sut_.join();
            throw new AssertionError();
        } catch (TransportException te) {
            assertThat(te.getCause(), is(instanceOf(CancellationException.class)));
        }
    }

    @Test
    public void testJoin_ExceptionIfFailed() throws Exception {
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    sut_.setThrowable(new IOException());
                } catch (InterruptedException ignored) {
                }
            }
        });
        try {
            sut_.join();
            throw new AssertionError();
        } catch (TransportException te) {
            assertThat(te.getCause(), is(instanceOf(IOException.class)));
        }
    }

    @Test
    public void testJoin_Done() throws Exception {
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    sut_.done();
                } catch (InterruptedException ignored) {
                }
            }
        });
        sut_.join();
    }

    @Test
    public void testJoinTimeout_ExceptionIfInterrupted() throws Exception {
        final Thread thread = Thread.currentThread();
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    thread.interrupt();
                } catch (Exception ignored) {
                }
            }
        });
        try {
            sut_.join(1000, TimeUnit.MILLISECONDS);
            throw new AssertionError();
        } catch (TransportException te) {
            assertThat(te.getCause(), is(instanceOf(InterruptedException.class)));
        }
    }

    @Test
    public void testJoinTimeout_ExceptionIfCancelled() throws Exception {
        sut_.cancel();
        try {
            sut_.join(1000, TimeUnit.MILLISECONDS);
            throw new AssertionError();
        } catch (TransportException te) {
            assertThat(te.getCause(), is(instanceOf(CancellationException.class)));
        }
    }

    @Test
    public void testJoinTimeout_ExceptionIfFailed() throws Exception {
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    sut_.setThrowable(new IOException());
                } catch (InterruptedException ignored) {
                }
            }
        });
        try {
            sut_.join(1000, TimeUnit.MILLISECONDS);
            throw new AssertionError();
        } catch (TransportException te) {
            assertThat(te.getCause(), is(instanceOf(IOException.class)));
        }
    }

    @Test
    public void testJoinTimeout_Done() throws Exception {
        executor_.execute(new Runnable() {
            @Override
            public void run() {
                sut_.executing();
                try {
                    Thread.sleep(10);
                    sut_.done();
                } catch (InterruptedException ignored) {
                }
            }
        });
        sut_.join(1000, TimeUnit.MILLISECONDS);
    }

    @Test
    public void testJoinTimeout_ExceptionIfTimeout() throws Exception {
        try {
            sut_.join(10, TimeUnit.MILLISECONDS);
            throw new AssertionError();
        } catch (TransportException te) {
            assertThat(te.getCause(), is(instanceOf(TimeoutException.class)));
        }
    }

    private static class Listener implements CompletionListener {

        DefaultTransportFuture future_;
        int counter_;

        @Override
        public void onComplete(TransportFuture future) {
            synchronized (this) {
                future_ = (DefaultTransportFuture) future;
                counter_++;
                notifyAll();
            }
        }

        DefaultTransportFuture future() throws InterruptedException {
            synchronized (this) {
                while (future_ == null) {
                    wait();
                }
            }
            return future_;
        }

        int count() {
            synchronized (this) {
                return counter_;
            }
        }
    }
}


text:
package com.mangopay.entities;

import com.google.gson.annotations.SerializedName;
import com.mangopay.core.Dto;
import com.mangopay.core.enumerations.CountryIso;
import com.mangopay.entities.subentities.CountryAuthorizationData;

public class CountryAuthorization extends Dto {
    @SerializedName("CountryCode")
    private CountryIso countryCode;

    @SerializedName("CountryName")
    private String countryName;

    @SerializedName("Authorization")
    private CountryAuthorizationData authorization;

    @SerializedName("LastUpdate")
    private Long lastUpdate;

    public CountryIso getCountryCode() {
        return countryCode;
    }

    public CountryAuthorization setCountryCode(CountryIso countryCode) {
        this.countryCode = countryCode;
        return this;
    }

    public String getCountryName() {
        return countryName;
    }

    public CountryAuthorization setCountryName(String countryName) {
        this.countryName = countryName;
        return this;
    }

    public CountryAuthorizationData getAuthorization() {
        return authorization;
    }

    public CountryAuthorization setAuthorization(CountryAuthorizationData authorization) {
        this.authorization = authorization;
        return this;
    }

    public Long getLastUpdate() {
        return lastUpdate;
    }

    public CountryAuthorization setLastUpdate(Long lastUpdate) {
        this.lastUpdate = lastUpdate;
        return this;
    }
}


text:
/*
 * SPDX-License-Identifier:	GPL-2.0+
 */

#include <common.h>
#include <dm.h>

/* Firmware access is platform-dependent.  No generic code in uclass */
UCLASS_DRIVER(firmware) = {
	.id		= UCLASS_FIRMWARE,
	.name		= "firmware",
};


text:
/** **********************************************************************
   Authors:
     * Manfred Sattler

************************************************************************ */

/**
 */
qx.Class.define("ms123.util.BaseResourceSelector", {
	extend: ms123.widgets.CollapsablePanel,
	include: qx.locale.MTranslation,

	/**
	 *****************************************************************************
	 CONSTRUCTOR
	 *****************************************************************************
	 */
	construct: function (facade, title) {
		this._setupIcons();
		this.base(arguments, title ? title : this.tr("util.resources"), new qx.ui.layout.Grow(), "icon/22/places/user-desktop.png");
		this.setValue(true);
		this.set({
			contentPadding: 0
		});
		this.facade = facade;

		this._resourceSelector = this._createResourceSelectorTree();
		this.add(this._resourceSelector, {
			edge: "center"
		});
		this._setup();
		this.contextMenu = this.facade.contextMenu;
		facade.leftSpace.add(this, {
			flex: 1
		});
	},

	/******************************************************************************
	 STATICS
	 ******************************************************************************/
	statics: {
		EVENT_RESOURCE_SELECTED: "resource_selected",
		NAMESPACE_TYPE: "namespace_type",
		PROCESS_TYPE: "process_type",
		PROCESSES_TYPE: "processes_type",
		PACK_TYPE: "pack_type",
		FIELD_TYPE: "field_type",
		FIELDS_TYPE: "fields_type",
		FIELDSET_TYPE: "fieldset_type",
		FIELDSETS_TYPE: "fieldsets_type",
		ENTITY_TYPE: "entity_type",
		ENTITIES_TYPE: "entities_type",
		CONFIGS_TYPE: "configs_type",
		CONFIG_TYPE: "config_type",
		VIEW_TYPE: "view_type",
		VIEW_PROPERTY_TYPE: "view_property_type",
		PROPERTY_TYPE: "property_type",
		VIEWS_TYPE: "views_type"
	},

	/**
	 *****************************************************************************
	 PROPERTIES
	 *****************************************************************************
	 */

	events: {
		"changeSelection": "qx.event.type.Data"
	},

	properties: {
		// overridden
	},

	/**
	 *****************************************************************************
	 MEMBERS
	 *****************************************************************************
	 */

	members: {
		_setupIcons: function () {
			var NAMESPACE_ICON = "resource/ms123/folder_database.png";
			var PROCESS_ICON = "resource/ms123/sequence.png";
			var PROCESSES_ICON = "resource/ms123/folder_link.png";
			var FIELD_ICON = "resource/ms123/column.png";
			var PACK_ICON = "resource/ms123/folder_schema.png";
			var FIELDS_ICON = "resource/ms123/attribute.png";
			var FIELDSET_ICON = "resource/ms123/sequence.png";
			var FIELDSETS_ICON = "resource/ms123/folder_link.png";
			var ENTITY_ICON = "resource/ms123/table.png";
			var ENTITIES_ICON = "resource/ms123/folder_table.png";
			var CONFIGS_ICON = "resource/ms123/settings_icon.png";
			var CONFIG_ICON = "resource/ms123/sequence.png";
			var VIEW_ICON = "resource/ms123/view.png";
			var VIEW_PROPERTY_ICON = "resource/ms123/settings-16x16.png";
			var PROPERTY_ICON = "resource/ms123/settings-16x16.png";
			var VIEWS_ICON = "resource/ms123/folder_view.png";

			this._iconMapping = {};
			this._iconMapping[ms123.util.BaseResourceSelector.NAMESPACE_TYPE] = {
				icon: NAMESPACE_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.PROCESS_TYPE] = {
				icon: PROCESS_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.PROCESSES_TYPE] = {
				icon: PROCESSES_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.FIELD_TYPE] = {
				icon: FIELD_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.PACK_TYPE] = {
				icon: PACK_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.FIELDS_TYPE] = {
				icon: FIELDS_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.FIELDSET_TYPE] = {
				icon: FIELDSET_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.FIELDSETS_TYPE] = {
				icon: FIELDSETS_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.ENTITY_TYPE] = {
				icon: ENTITY_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.ENTITIES_TYPE] = {
				icon: ENTITIES_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.CONFIGS_TYPE] = {
				icon: CONFIGS_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.CONFIG_TYPE] = {
				icon: CONFIG_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.PROPERTY_TYPE] = {
				icon: PROPERTY_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.VIEW_PROPERTY_TYPE] = {
				icon: VIEW_PROPERTY_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.VIEW_TYPE] = {
				icon: VIEW_ICON
			};
			this._iconMapping[ms123.util.BaseResourceSelector.VIEWS_TYPE] = {
				icon: VIEWS_ICON
			};
		},
		_createResourceSelectorTree: function () {
			var control = new qx.ui.tree.VirtualTree(null, "title", "children").set({
				focusable: false,
				hideRoot: true,
				keepFocus: true,
				openMode: "none",
				height: null,
				itemHeight: 20,
				selectionMode: "one",
				//dragSelection:true,
				contentPaddingLeft: 0,
				showTopLevelOpenCloseIcons: true,
				quickSelection: false
			});
			control.setIconPath("id");
			control.setIconOptions({
				converter: (function (value, model, source, target) {
					var menu = this._createContextMenu(target, model, value);
					if (menu != null) {
						target.setContextMenu(menu);
					}
					return this._getIcon(target, model, value);
				}).bind(this)
			});
			control.addListener("click", this._onClickTree, this);
			control.addListener("open", this._onOpenNode, this);
			//control.setDraggable(true);
			control.addListener("dragstart", function (e) {
				//if (!check.isValue()) {
				// e.preventDefault();
				//}
				// Register supported types
				e.addType("value");
				e.addType("items");

				// Register supported actions
				e.addAction("copy");
				e.addAction("move");
			});
			control.addListener("droprequest", function (e) {
				console.debug("Related of droprequest: " + e.getRelatedTarget());

				var action = e.getCurrentAction();
				var type = e.getCurrentType();
				console.debug("Related of droprequest: " + action + "/" + type);
				var result;

				switch (type) {
				case "items":
					result = this.getSelection();
					if (action == "copy") {
						var copy = [];
						for (var i = 0, l = result.length; i < l; i++) {
							copy[i] = result[i].clone();
						}
						result = copy;
					}
					break;

				case "value":
					result = this.getSelection()[0].getLabel();
					break;
				}

				// Remove selected items on move
				//if (action == "move")
				//{
				//   var selection = this.getSelection();
				//  for (var i=0, l=selection.length; i<l; i++) {
				//   this.remove(selection[i]);
				//  }
				// }
				// Add data to manager
				e.addData(type, result);
			});

			return control;
		},

		_setup: function () {
			var delegate = {
				configureItem: function (item) {
					item.setIndent(13);
				},
				createItem: function () {
					return new ms123.shell.TreeItem();
				},
				bindItem: (function (controller, item, id) {
					controller.bindProperty("", "model", null, item, id);
					//controller.bindProperty( controller.getLabelPath(), "label", controller.getLabelOptions(), item, id);
					controller.bindProperty("title", "label", null, item, id);
					controller.bindProperty(controller.getIconPath(), "icon", controller.getIconOptions(), item, id);
				}).bind(this)
			};

			this._resourceSelector.setDelegate(delegate);
			var t = this._createTreeModel();

			var model = qx.data.marshal.Json.createModel(t, true);
			this.setParentModel(model);
			this._resourceSelector.setModel(model);
			this._resourceSelector.getSelection().addListener("change", this._selectionChanged, this);
		},
		setParentModel: function (model) {
			var children = model.getChildren();
			if (children.getLength() > 0) {
				for (var i = 0; i < children.getLength(); i++) {
					var c = children.getItem(i);
					c.parent = model;
					this.setParentModel(c);
				}
			}
			return null;
		},
		_createTreeModel: function () {
			var fielddummy = {
				id: "fielddummy",
				level: "3",
				title: "fielddummy",
				children: []
			};

			var namespaces = [];
			var ns1 = {};
			ns1.name = this.facade.storeDesc.getNamespace();
			namespaces.push(ns1);
			this._sortByName(namespaces);
			var nsarray = [];
			for (var n = 0; n < namespaces.length; n++) {
				var namespace = namespaces[n];
				var entityarray = [];

				var ns = {}
				ns.id = namespace.name;
				ns.title = namespace.name;
				ns.type = ms123.util.BaseResourceSelector.NAMESPACE_TYPE;
				ns.level = "1";
				ns.children = entityarray;
				nsarray.push(ns);

				var cm = new ms123.config.ConfigManager();
				var entities = cm.getEntities(this.facade.storeDesc);
				this._sortByName(entities);
				for (var i = 0; i < entities.length; i++) {
					var ename = entities[i].name;
					var m = {}
					m.id = ename;
					m.title = ename;
					m.type = ms123.util.BaseResourceSelector.ENTITY_TYPE;
					m.level = "2";
					m.namespace = namespace.name;
					m.children = [fielddummy];
					entityarray.push(m);
				}
			}

			var model = {}
			model.id = "ROOT";
			model.title = "ROOTTITLE";
			model.level = "0";
			model.children = nsarray;
			return model;
		},
		_selectionChanged: function (e) {
			console.log("_selectionChanged");
		},

		_onOpenNode: function (e) {
			var item = e.getData();
			var childs = item.getChildren();
			if (childs.getLength() == 1 && childs.getItem(0).getId() == "fielddummy") {
				var fields = null;
				try {
					var cm = new ms123.config.ConfigManager();
					fields = ms123.util.Remote.rpcSync("config:getEntityMetaFields", {
						namespace: item.getNamespace(),
						storeId: this.facade.storeDesc.getStoreId(),
						entity: item.getId()
					});
				} catch (e) {
					ms123.form.Dialog.alert("BaseResourceSelector._createTreeModel3:" + e);
					return;
				}

				this._sortByName(fields);
				var fieldarray = [];
				for (var i = 0; i < fields.length; i++) {
					var fname = fields[i].name;
					var f = {}
					f.id = fname;
					f.title = fname;
					f.type = ms123.util.BaseResourceSelector.FIELD_TYPE;
					f.level = "4";
					f.children = [];
					fieldarray.push(f);
				}

				var model = qx.data.marshal.Json.createModel(fieldarray, true);
				childs.removeAll();
				childs.append(model);
				this.setParentModel(item);
			}
		},

		_sortByKey: function (array, key) {
			array.sort(function (a, b) {
				a = a[key].toLowerCase();
				b = b[key].toLowerCase();
				if (a < b) return -1;
				if (a > b) return 1;
				return 0;
			});
		},

		_sortByName: function (array) {
			array.sort(function (a, b) {
				a = a.name.toLowerCase();
				b = b.name.toLowerCase();
				if (a < b) return -1;
				if (a > b) return 1;
				return 0;
			});
		},

		_onClickTree: function (e) {
			var model = this._resourceSelector.getSelection().getItem(0);

			var target= e.getTarget();
			var classname= target.classname;

			if( classname === "qx.ui.tree.core.FolderOpenButton" ){
				return;
			}

			var type = model.getType();
			var icons = this._iconMapping[type];
			console.log("_onClickTree:" + type);
			this.facade.raiseEvent({
				model: model,
				icon: icons.icon,
				facade: this.facade,
				type: ms123.util.BaseResourceSelector.EVENT_RESOURCE_SELECTED
			});
		},
		_getIcon: function (target, model, id) {
			var type = model.getType();
			var icons = this._iconMapping[type];
			if (icons) {
				console.log("type:" + type + "->" + icons.icon);
				return icons.icon;
			}
			return "";
		},
		_createContextMenu: function (item, model, id) {
			return null;
		}
	}
});


text:
require 'spec_helper'

# We stub Gitaly in `spec/support/gitaly.rb` for other tests. We don't want
# those stubs while testing the GitalyClient itself.
describe Gitlab::GitalyClient, skip_gitaly_mock: true do
  describe '.stub_class' do
    it 'returns the gRPC health check stub' do
      expect(described_class.stub_class(:health_check)).to eq(::Grpc::Health::V1::Health::Stub)
    end

    it 'returns a Gitaly stub' do
      expect(described_class.stub_class(:ref_service)).to eq(::Gitaly::RefService::Stub)
    end
  end

  describe '.stub_address' do
    it 'returns the same result after being called multiple times' do
      address = 'localhost:9876'
      prefixed_address = "tcp://#{address}"

      allow(Gitlab.config.repositories).to receive(:storages).and_return({
        'default' => { 'gitaly_address' => prefixed_address }
      })

      2.times do
        expect(described_class.stub_address('default')).to eq('localhost:9876')
      end
    end
  end

  describe '.stub' do
    # Notice that this is referring to gRPC "stubs", not rspec stubs
    before do
      described_class.clear_stubs!
    end

    context 'when passed a UNIX socket address' do
      it 'passes the address as-is to GRPC' do
        address = 'unix:/tmp/gitaly.sock'
        allow(Gitlab.config.repositories).to receive(:storages).and_return({
          'default' => { 'gitaly_address' => address }
        })

        expect(Gitaly::CommitService::Stub).to receive(:new).with(address, any_args)

        described_class.stub(:commit_service, 'default')
      end
    end

    context 'when passed a TCP address' do
      it 'strips tcp:// prefix before passing it to GRPC::Core::Channel initializer' do
        address = 'localhost:9876'
        prefixed_address = "tcp://#{address}"

        allow(Gitlab.config.repositories).to receive(:storages).and_return({
          'default' => { 'gitaly_address' => prefixed_address }
        })

        expect(Gitaly::CommitService::Stub).to receive(:new).with(address, any_args)

        described_class.stub(:commit_service, 'default')
      end
    end
  end

  describe 'allow_n_plus_1_calls' do
    context 'when RequestStore is enabled', :request_store do
      it 'returns the result of the allow_n_plus_1_calls block' do
        expect(described_class.allow_n_plus_1_calls { "result" }).to eq("result")
      end
    end

    context 'when RequestStore is not active' do
      it 'returns the result of the allow_n_plus_1_calls block' do
        expect(described_class.allow_n_plus_1_calls { "something" }).to eq("something")
      end
    end
  end

  describe 'enforce_gitaly_request_limits?' do
    def call_gitaly(count = 1)
      (1..count).each do
        described_class.enforce_gitaly_request_limits(:test)
      end
    end

    context 'when RequestStore is enabled', :request_store do
      it 'allows up the maximum number of allowed calls' do
        expect { call_gitaly(Gitlab::GitalyClient::MAXIMUM_GITALY_CALLS) }.not_to raise_error
      end

      context 'when the maximum number of calls has been reached' do
        before do
          call_gitaly(Gitlab::GitalyClient::MAXIMUM_GITALY_CALLS)
        end

        it 'fails on the next call' do
          expect { call_gitaly(1) }.to raise_error(Gitlab::GitalyClient::TooManyInvocationsError)
        end
      end

      it 'allows the maximum number of calls to be exceeded within an allow_n_plus_1_calls block' do
        expect do
          described_class.allow_n_plus_1_calls do
            call_gitaly(Gitlab::GitalyClient::MAXIMUM_GITALY_CALLS + 1)
          end
        end.not_to raise_error
      end

      context 'when the maximum number of calls has been reached within an allow_n_plus_1_calls block' do
        before do
          described_class.allow_n_plus_1_calls do
            call_gitaly(Gitlab::GitalyClient::MAXIMUM_GITALY_CALLS)
          end
        end

        it 'allows up to the maximum number of calls outside of an allow_n_plus_1_calls block' do
          expect { call_gitaly(Gitlab::GitalyClient::MAXIMUM_GITALY_CALLS) }.not_to raise_error
        end

        it 'does not allow the maximum number of calls to be exceeded outside of an allow_n_plus_1_calls block' do
          expect { call_gitaly(Gitlab::GitalyClient::MAXIMUM_GITALY_CALLS + 1) }.to raise_error(Gitlab::GitalyClient::TooManyInvocationsError)
        end
      end
    end

    context 'when RequestStore is not active' do
      it 'does not raise errors when the maximum number of allowed calls is exceeded' do
        expect { call_gitaly(Gitlab::GitalyClient::MAXIMUM_GITALY_CALLS + 2) }.not_to raise_error
      end

      it 'does not fail when the maximum number of calls is exceeded within an allow_n_plus_1_calls block' do
        expect do
          described_class.allow_n_plus_1_calls do
            call_gitaly(Gitlab::GitalyClient::MAXIMUM_GITALY_CALLS + 1)
          end
        end.not_to raise_error
      end
    end
  end

  describe 'get_request_count' do
    context 'when RequestStore is enabled', :request_store do
      context 'when enforce_gitaly_request_limits is called outside of allow_n_plus_1_calls blocks' do
        before do
          described_class.enforce_gitaly_request_limits(:call)
        end

        it 'counts gitaly calls' do
          expect(described_class.get_request_count).to eq(1)
        end
      end

      context 'when enforce_gitaly_request_limits is called inside and outside of allow_n_plus_1_calls blocks' do
        before do
          described_class.enforce_gitaly_request_limits(:call)
          described_class.allow_n_plus_1_calls do
            described_class.enforce_gitaly_request_limits(:call)
          end
        end

        it 'counts gitaly calls' do
          expect(described_class.get_request_count).to eq(2)
        end
      end

      context 'when reset_counts is called' do
        before do
          described_class.enforce_gitaly_request_limits(:call)
          described_class.reset_counts
        end

        it 'resets counts' do
          expect(described_class.get_request_count).to eq(0)
        end
      end
    end

    context 'when RequestStore is not active' do
      before do
        described_class.enforce_gitaly_request_limits(:call)
      end

      it 'returns zero' do
        expect(described_class.get_request_count).to eq(0)
      end
    end
  end

  describe 'feature_enabled?' do
    let(:feature_name) { 'my_feature' }
    let(:real_feature_name) { "gitaly_#{feature_name}" }

    context 'when Gitaly is disabled' do
      before do
        allow(described_class).to receive(:enabled?).and_return(false)
      end

      it 'returns false' do
        expect(described_class.feature_enabled?(feature_name)).to be(false)
      end
    end

    context 'when the feature status is DISABLED' do
      let(:feature_status) { Gitlab::GitalyClient::MigrationStatus::DISABLED }

      it 'returns false' do
        expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(false)
      end
    end

    context 'when the feature_status is OPT_IN' do
      let(:feature_status) { Gitlab::GitalyClient::MigrationStatus::OPT_IN }

      context "when the feature flag hasn't been set" do
        it 'returns false' do
          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(false)
        end
      end

      context "when the feature flag is set to disable" do
        before do
          Feature.get(real_feature_name).disable
        end

        it 'returns false' do
          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(false)
        end
      end

      context "when the feature flag is set to enable" do
        before do
          Feature.get(real_feature_name).enable
        end

        it 'returns true' do
          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(true)
        end
      end

      context "when the feature flag is set to a percentage of time" do
        before do
          Feature.get(real_feature_name).enable_percentage_of_time(70)
        end

        it 'bases the result on pseudo-random numbers' do
          expect(Random).to receive(:rand).and_return(0.3)
          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(true)

          expect(Random).to receive(:rand).and_return(0.8)
          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(false)
        end
      end

      context "when a feature is not persisted" do
        it 'returns false when opt_into_all_features is off' do
          allow(Feature).to receive(:persisted?).and_return(false)
          allow(described_class).to receive(:opt_into_all_features?).and_return(false)

          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(false)
        end

        it 'returns true when the override is on' do
          allow(Feature).to receive(:persisted?).and_return(false)
          allow(described_class).to receive(:opt_into_all_features?).and_return(true)

          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(true)
        end
      end
    end

    context 'when the feature_status is OPT_OUT' do
      let(:feature_status) { Gitlab::GitalyClient::MigrationStatus::OPT_OUT }

      context "when the feature flag hasn't been set" do
        it 'returns true' do
          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(true)
        end
      end

      context "when the feature flag is set to disable" do
        before do
          Feature.get(real_feature_name).disable
        end

        it 'returns false' do
          expect(described_class.feature_enabled?(feature_name, status: feature_status)).to be(false)
        end
      end
    end
  end

  describe 'timeouts' do
    context 'with default values' do
      before do
        stub_application_setting(gitaly_timeout_default: 55)
        stub_application_setting(gitaly_timeout_medium: 30)
        stub_application_setting(gitaly_timeout_fast: 10)
      end

      it 'returns expected values' do
        expect(described_class.default_timeout).to be(55)
        expect(described_class.medium_timeout).to be(30)
        expect(described_class.fast_timeout).to be(10)
      end
    end
  end
end


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('market', '0001_initial'),
    ]

    operations = [
        migrations.RenameModel(
            old_name='Users',
            new_name='User',
        ),
    ]


text:
"""
adds ec_material to texture refs that don't use a material (which was possible before 1.0, against opensim with lludp, as sl model has just texture assignments).
"""

import sys
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree

sourcefile = sys.argv[1]
source = ElementTree()
source.parse(sourcefile)

ents = source.getiterator("entity")
for ent in ents:
    for comp in ent:
        attrib = comp.attrib
        if attrib['type'] == 'EC_Mesh':
            mats_elem = comp.find(".//attribute[@name='%s']" % "Mesh materials")
            mats = mats_elem.attrib['value']
            print attrib, mats

            if not mats.endswith('.material'):
                print "texture ref found:",
                print mats

            else:
                print "MATERIAL:", mats