text:
.class Landroid/support/v4/content/ModernAsyncTask$2;
.super Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable;
.source "ModernAsyncTask.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/support/v4/content/ModernAsyncTask;-><init>()V
.end annotation

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

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable",
        "<TParams;TResult;>;"
    }
.end annotation

# instance fields
.field final synthetic this$0:Landroid/support/v4/content/ModernAsyncTask;

# direct methods
.method constructor <init>(Landroid/support/v4/content/ModernAsyncTask;)V
    .locals 1

    .prologue
    .line 123
    .local p1, "this$0":Landroid/support/v4/content/ModernAsyncTask;, "Landroid/support/v4/content/ModernAsyncTask<TParams;TProgress;TResult;>;"
    iput-object p1, p0, Landroid/support/v4/content/ModernAsyncTask$2;->this$0:Landroid/support/v4/content/ModernAsyncTask;

    const/4 v0, 0x0

    invoke-direct {p0, v0}, Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable;-><init>(Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable;)V

    return-void
.end method

# virtual methods
.method public call()Ljava/lang/Object;
    .locals 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TResult;"
        }
    .end annotation

    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/Exception;
        }
    .end annotation

    .prologue
    .line 125
    iget-object v0, p0, Landroid/support/v4/content/ModernAsyncTask$2;->this$0:Landroid/support/v4/content/ModernAsyncTask;

    invoke-static {v0}, Landroid/support/v4/content/ModernAsyncTask;->-get0(Landroid/support/v4/content/ModernAsyncTask;)Ljava/util/concurrent/atomic/AtomicBoolean;

    move-result-object v0

    const/4 v1, 0x1

    invoke-virtual {v0, v1}, Ljava/util/concurrent/atomic/AtomicBoolean;->set(Z)V

    .line 127
    const/16 v0, 0xa

    invoke-static {v0}, Landroid/os/Process;->setThreadPriority(I)V

    .line 128
    iget-object v0, p0, Landroid/support/v4/content/ModernAsyncTask$2;->this$0:Landroid/support/v4/content/ModernAsyncTask;

    iget-object v1, p0, Landroid/support/v4/content/ModernAsyncTask$2;->this$0:Landroid/support/v4/content/ModernAsyncTask;

    iget-object v2, p0, Landroid/support/v4/content/ModernAsyncTask$2;->mParams:[Ljava/lang/Object;

    invoke-virtual {v1, v2}, Landroid/support/v4/content/ModernAsyncTask;->doInBackground([Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/support/v4/content/ModernAsyncTask;->-wrap0(Landroid/support/v4/content/ModernAsyncTask;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method


text:
package goacc

import (
	"testing"
	"time"
)

func TestNoClosingAccount(t *testing.T) {
	adb := initDB()
	defer adb.Stop()

	a := standardAccounts()
	err := adb.CreateAccounts(a)
	handleErr(t, err)

	localTime := time.Now().Local().Location()
	start := time.Date(2014, time.October, 1, 0, 0, 0, 0, localTime).UnixNano()
	end := time.Date(2014, time.October, 30, 0, 0, 0, 0, localTime).UnixNano()

	_, err = adb.TrialBalance(start, end)
	if err == nil {
		t.Error("Expected error but got none - requested trial balance with no closing account")
	}
}

redpajama_set_name: RedPajamaGithub


text:
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */

'use strict';

const msRest = require('ms-rest');
const ServiceClient = msRest.ServiceClient;

const models = require('./models');
const operations = require('./operations');

/** Class representing a LUISAuthoringClient. */
class LUISAuthoringClient extends ServiceClient {
  /**
   * Create a LUISAuthoringClient.
   * @param {credentials} credentials - Subscription credentials which uniquely identify client subscription.
   * @param {string} endpoint - Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com).
   * @param {object} [options] - The parameter options
   * @param {Array} [options.filters] - Filters to be added to the request pipeline
   * @param {object} [options.requestOptions] - Options for the underlying request object
   * {@link https://github.com/request/request#requestoptions-callback Options doc}
   * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
   */
  constructor(credentials, endpoint, options) {
    if (credentials === null || credentials === undefined) {
      throw new Error('\'credentials\' cannot be null.');
    }
    if (endpoint === null || endpoint === undefined) {
      throw new Error('\'endpoint\' cannot be null.');
    }

    if (!options) options = {};

    super(credentials, options);

    this.baseUri = '{Endpoint}/luis/api/v2.0';
    this.credentials = credentials;
    this.endpoint = endpoint;

    let packageInfo = this.getPackageJsonInfo(__dirname);
    this.addUserAgentInfo(`${packageInfo.name}/${packageInfo.version}`);
    this.features = new operations.Features(this);
    this.examples = new operations.Examples(this);
    this.model = new operations.Model(this);
    this.apps = new operations.Apps(this);
    this.versions = new operations.Versions(this);
    this.train = new operations.Train(this);
    this.permissions = new operations.Permissions(this);
    this.pattern = new operations.Pattern(this);
    this.settings = new operations.Settings(this);
    this.azureAccounts = new operations.AzureAccounts(this);
    this.models = models;
    msRest.addSerializationMixin(this);
  }

}

module.exports = LUISAuthoringClient;
module.exports['default'] = LUISAuthoringClient;
module.exports.LUISAuthoringClient = LUISAuthoringClient;
module.exports.LUISAuthoringModels = models;


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

<title>Uses of Interface org.springframework.messaging.simp.user.SimpSubscription (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.springframework.messaging.simp.user.SimpSubscription

Packages that use SimpSubscription

Package
Description

org.springframework.messaging.simp.user

Support for handling messages to "user" destinations (i.e.

org.springframework.web.socket.messaging

WebSocket integration for Spring's messaging module.

Uses of SimpSubscription in org.springframework.messaging.simp.user

Methods in org.springframework.messaging.simp.user that return types with arguments of type SimpSubscription

Modifier and Type
Method and Description

Set<SimpSubscription>
MultiServerUserRegistry.findSubscriptions(SimpSubscriptionMatcher matcher)

Set<SimpSubscription>
SimpUserRegistry.findSubscriptions(SimpSubscriptionMatcher matcher)

Find subscriptions with the given matcher.

Set<SimpSubscription>
SimpSession.getSubscriptions()

Return the subscriptions for this session.

Methods in org.springframework.messaging.simp.user with parameters of type SimpSubscription

Modifier and Type
Method and Description

boolean
SimpSubscriptionMatcher.match(SimpSubscription subscription)

Match the given subscription.

Uses of SimpSubscription in org.springframework.web.socket.messaging

Methods in org.springframework.web.socket.messaging that return types with arguments of type SimpSubscription

Modifier and Type
Method and Description

Set<SimpSubscription>
DefaultSimpUserRegistry.findSubscriptions(SimpSubscriptionMatcher matcher)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
const path = require('path')
const LiveServer = require('live-server')

const fixturePath = path.join(__dirname, './fixtures/docs')
const args = process.argv.slice(2)
console.log('[e2e tests] : args passed to live server', args)
const params = {
  port: args[0] || 3000,
  root: args[1] || fixturePath,
  open: false
  // NoBrowser: true
}
LiveServer.start(params)


text:
package com.print_stack_trace.voogasalad.controller.guiElements.splashScreen;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import com.print_stack_trace.voogasalad.utilities.reflection.Reflection;
import com.print_stack_trace.voogasalad.controller.guiElements.resourceReader.ResourceReader;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.util.Duration;

public abstract class AbstractUserSplashScreen {
	protected Group myGroup=new Group();
	protected Timeline myTimeline=new Timeline();
	protected int DEFAULT_FPS=300;
	protected HashMap<String, String> myData;
	protected Scene myScene;
	protected HashMap<Integer,SplashScreenObject> myNodes=new HashMap<Integer,SplashScreenObject>();
	protected EventHandler myEvent;

	public AbstractUserSplashScreen(String resourceName, Number width, Number height){
		this(resourceName, width, height, null);

	}

	public AbstractUserSplashScreen(Number width, Number height){
		this ("", width, height);
	}

	public AbstractUserSplashScreen(String resource, Number width, Number height, EventHandler event){
		this.initialize(width.doubleValue(), height.doubleValue());
		myData=new ResourceReader(resource).getProperties();
		myEvent=event;

		KeyFrame myKeyFrame=new KeyFrame(Duration.millis(1000/DEFAULT_FPS), e->update());
		myTimeline.setCycleCount(Timeline.INDEFINITE);
		myTimeline.getKeyFrames().add(myKeyFrame);
		myTimeline.play();

		makeNode();
		add();
		update();
	}

	public Scene getScene(){
		return myScene;
	}

	public Scene initialize(double width, double height){
		myScene=new Scene(myGroup,width, height);
		return myScene;
	}

	private EventHandler stopAnimation(){
		return myEvent;
	}

	private void update(){
		int count=0;
		for (Integer node: myNodes.keySet()){
			if (!myNodes.get(node).update()){
				myNodes.get(node).addEnd(stopAnimation());
				count++;
			}
		}
		if (count==myNodes.keySet().size()){
			myTimeline.stop();
		}
	}

	private void add(){
		int max=0;
		for (Integer index: myNodes.keySet()){
			max=Math.max(max, index);
		}
		for (int i=0; i<=max; i++){
			if (myNodes.containsKey(i)){
				myGroup.getChildren().add(myNodes.get(i).getNode());
			}
		}
	}

	private void makeNode(){
		for (String key: myData.keySet()){
			String [] values=myData.get(key).split(";");
			String value=values[0];
			String className=values[1];
			SplashScreenObject newSplashScreenObject= (SplashScreenObject) Reflection.createInstance(className, value, myScene.getWidth(), myScene.getHeight(), myGroup);
			myNodes.put(Integer.parseInt(values[2]), newSplashScreenObject);
		}
	}

}


text:
package org.apache.xalan.templates;

public class ElemComment
  extends ElemTemplateElement{
  // Constructors

  public ElemComment(){
    super();
  }
  // Methods

  public void execute(org.apache.xalan.transformer.TransformerImpl arg1) throws javax.xml.transform.TransformerException{
  }
  public java.lang.String getNodeName(){
    return (java.lang.String) null;
  }
  public int getXSLToken(){
    return 0;
  }
  public ElemTemplateElement appendChild(ElemTemplateElement arg1){
    return (ElemTemplateElement) null;
  }
}


text:
export default ngModule => {

    ngModule.directive('messages', ($log,source) => {
        $log.debug('Setup messages directive');

        return {
            restrict: 'E',
            scope: {},
//            templateUrl: 'components/messages/messages.html',
            controllerAs: 'vm',
            controller: /*@ngInject*/ function (vm = this) {
                vm.message = 'Hello Messages';

            },
            link: function(scope, elem){
                source.filter(x => x % 2 === 1)
                    .map(x => x + '!')
                    .forEach(x => elem.append('<li>' + x + '</li>'));
            }
        };
    });
};


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title></title>

		<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'/>

		<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'/>

		<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css'/>

		<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'/>

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">

<link rel="stylesheet" href="/static/css/style.css">

Chat

						Hello Moon!

						Hello Mars!

						Hello World!

						<input type="text" id="chat-input-form" placeholder="Type some lovely words..."/>
						<button id="chat-submit">Go!</button>


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Link'
        db.create_table('punns_link', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('punn', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['punns.Punn'])),
            ('album', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['punns.Album'])),
            ('order', self.gf('django.db.models.fields.PositiveIntegerField')()),
            ('created_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
            ('last_modified_date', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, null=True, blank=True)),
        ))
        db.send_create_signal('punns', ['Link'])

        # Adding model 'Album'
        db.create_table('punns_album', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('base62id', self.gf('django.db.models.fields.CharField')(max_length=140, blank=True)),
            ('title', self.gf('django.db.models.fields.CharField')(max_length=140)),
            ('content', self.gf('django.db.models.fields.TextField')(max_length=10000, blank=True)),
            ('author', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('created_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
            ('last_modified_date', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, null=True, blank=True)),
        ))
        db.send_create_signal('punns', ['Album'])

    def backwards(self, orm):
        # Deleting model 'Link'
        db.delete_table('punns_link')

        # Deleting model 'Album'
        db.delete_table('punns_album')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'punns.album': {
            'Meta': {'object_name': 'Album'},
            'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'base62id': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}),
            'content': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}),
            'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_modified_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '140'})
        },
        'punns.cat': {
            'Meta': {'object_name': 'Cat'},
            'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_top_level': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '140'}),
            'top_level_cat': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['punns.Cat']", 'null': 'True', 'blank': 'True'})
        },
        'punns.favorite': {
            'Meta': {'object_name': 'Favorite'},
            'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'punn': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['punns.Punn']"})
        },
        'punns.link': {
            'Meta': {'object_name': 'Link'},
            'album': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['punns.Album']"}),
            'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_modified_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
            'order': ('django.db.models.fields.PositiveIntegerField', [], {}),
            'punn': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['punns.Punn']"})
        },
        'punns.punn': {
            'Meta': {'object_name': 'Punn'},
            'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'base62id': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}),
            'cat': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['punns.Cat']", 'null': 'True', 'blank': 'True'}),
            'content': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_top': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_video': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'karma': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
            'original_punn': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['punns.Punn']", 'null': 'True', 'blank': 'True'}),
            'pic': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            'publish_on_facebook': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '140', 'blank': 'True'}),
            'source': ('django.db.models.fields.URLField', [], {'max_length': '300', 'blank': 'True'}),
            'status': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}),
            'tags': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['punns.Tags']", 'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
            'translated_title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}),
            'views': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}),
            'youtube_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'})
        },
        'punns.reblog': {
            'Meta': {'object_name': 'Reblog'},
            'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'origin': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['punns.Punn']"})
        },
        'punns.tags': {
            'Meta': {'object_name': 'Tags'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'tag': ('django.db.models.fields.CharField', [], {'max_length': '140'})
        }
    }

    complete_apps = ['punns']


text:
package config

import "github.com/opentable/sous/util/logging"

// Verbosity configures how chatty Sous is on its logs
type Verbosity struct {
	Silent, Quiet, Loud, Debug bool
}

// UpdateLevel updates the logging level of the provided LogSet
// to reflect this Verbosity
func (v Verbosity) UpdateLevel(set *logging.LogSet) {
	switch {
	default:
		// do nothing - if no flag provided, keep configured levels
	case v.Silent:
		set.BeSilent()
	case v.Quiet:
		set.BeQuiet()
	case v.Loud:
		set.BeChatty()
	case v.Debug:
		set.BeHelpful()
	}
}


text:
// +build !windows

package shim

import (
	"context"
	"net"
	"path/filepath"
	"strings"
	"syscall"
	"time"

	"github.com/containerd/containerd/namespaces"
	"github.com/containerd/containerd/sys"
	"github.com/pkg/errors"
)

const shimBinaryFormat = "containerd-shim-%s-%s"

func getSysProcAttr() *syscall.SysProcAttr {
	return &syscall.SysProcAttr{
		Setpgid: true,
	}
}

// SetScore sets the oom score for a process
func SetScore(pid int) error {
	return sys.SetOOMScore(pid, sys.OOMScoreMaxKillable)
}

// SocketAddress returns an abstract socket address
func SocketAddress(ctx context.Context, id string) (string, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return "", err
	}
	return filepath.Join(string(filepath.Separator), "containerd-shim", ns, id, "shim.sock"), nil
}

// AnonDialer returns a dialer for an abstract socket
func AnonDialer(address string, timeout time.Duration) (net.Conn, error) {
	address = strings.TrimPrefix(address, "unix://")
	return net.DialTimeout("unix", "\x00"+address, timeout)
}

// NewSocket returns a new socket
func NewSocket(address string) (*net.UnixListener, error) {
	if len(address) > 106 {
		return nil, errors.Errorf("%q: unix socket path too long (> 106)", address)
	}
	l, err := net.Listen("unix", "\x00"+address)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to listen to abstract unix socket %q", address)
	}
	return l.(*net.UnixListener), nil
}


text:
<?php

namespace Kodazzi\Config;

use Kodazzi\Config\ConfigBuilderInterface;

class ConfigBuilder implements ConfigBuilderInterface
{
	private $config = array();

	public function loadConfigGlobal()
	{
		$this->config['app'] = require Ki_APP . 'config/app.cf.php';
		$this->config['db'] = require Ki_APP . 'config/db.cf.php';
		$this->config['providers'] = require Ki_APP . 'config/providers.cf.php';
		$this->config['security'] = require Ki_APP . 'config/security.cf.php';
		$this->config['bundles'] = require Ki_APP . 'config/bundles.cf.php';
	}

	public function get( $file, $key = null, $default = -1)
	{
		if ( array_key_exists( $file, $this->config ) )
		{
            if($key)
            {
                if(array_key_exists( $key, $this->config[$file] ))
                {
                    return $this->config[$file][$key];
                }
            }
            else if($key === null)
            {
                return $this->config[$file];
            }
		}

		if ( $default === -1 )
        {
            throw new \Exception("No se encontró la clave de configuración <b>$key</b>");
        }

		return $default;
	}
}


text:
/**
  * @author Wei Xing
  */

trait Similar {
  def isSimilar(o: Any): Boolean
  def isNotSimilar(o: Any): Boolean = !isSimilar(0)
}

class Point(val x: Int, val y: Int) extends Similar {
  override def isSimilar(o: Any): Boolean =
    o.isInstanceOf[Point] && o.asInstanceOf[Point].x == x
}

object Traits {
  def main(args: Array[String]) {
    val p1 = new Point(1, 2)
    val p2 = new Point(1, 3)
    val p3 = new Point(2, 1)

    assert(p1.isSimilar(p2))
    assert(!p1.isSimilar(p3))
    assert(!p1.isSimilar(3))
  }
}


text: Image source: {{ include.credit }}


text:
import { NgModule } from '@angular/core';
import {
  RouterModule,
  Routes,
} from '@angular/router';

import { FileUploadComponent } from './file-upload.component';

const routes: Routes = [
  {
    path: '',
    component: FileUploadComponent,
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class FileUploadRoutingModule { }


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.logging;

import org.openqa.selenium.Beta;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;

/**
 * Represents the logging preferences.
 *
 * Sample usage:
 *  DesiredCapabilities caps = DesiredCapabilities.firefox();
 *  LoggingPreferences logs = new LoggingPreferences();
 *  logs.enable(LogType.DRIVER, Level.INFO);
 *  caps.setCapability(CapabilityType.LOGGING_PREFS, logs);
 *
 *  WebDriver driver = new FirefoxDriver(caps);
 */
public class LoggingPreferences implements Serializable {

  private static final long serialVersionUID = 6708028456766320675L;

  // Mapping the {@link LogType} to {@link Level}
  private final Map<String, Level> prefs = new HashMap<>();

  /**
   * Enables logging for the given log type at the specified level and above.
   * @param logType String the logType. Can be any of {@link LogType}.
   * @param level {@link Level} the level.
   */
  public void enable(String logType, Level level) {
    prefs.put(logType, level);
  }

  /**
   * @return the set of log types for which logging has been enabled.
   */
  public Set<String> getEnabledLogTypes() {
    return new HashSet<>(prefs.keySet());
  }

  /**
   * @param logType The log type.
   * @return the {@link Level} for the given {@link LogType} if enabled.
   *     Otherwise returns {@link Level#OFF}.
   */
  public Level getLevel(String logType) {
    return prefs.get(logType) == null ? Level.OFF : prefs.get(logType);
  }

  /**
   * Adds the given logging preferences giving them precedence over existing
   * preferences.
   *
   * @param prefs The logging preferences to add.
   * @return A references to this object.
   */
  public LoggingPreferences addPreferences(LoggingPreferences prefs) {
    if (prefs == null) {
      return this;
    }
    for (String logType : prefs.getEnabledLogTypes()) {
      enable(logType, prefs.getLevel(logType));
    }
    return this;
  }

  @Override
  public int hashCode() {
    return prefs.hashCode();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof LoggingPreferences)) {
      return false;
    }

    LoggingPreferences that = (LoggingPreferences) o;

    return prefs.equals(that.prefs);
  }

  @Beta
  public Map<String, Object> toJson() {
    TreeMap<String, Object> converted = new TreeMap<>();
    for (String logType : getEnabledLogTypes()) {
      converted.put(logType, LogLevelMapping.getName(getLevel(logType)));
    }
    return converted;
  }
}


text:
import convert
import random

import tensorflow as tf
import tensorflow.contrib as tfc

from tensorflow.contrib.learn import DNNRegressor, SKCompat

random.seed(0xbedbeef)  # so we get consistent results

fit_boards = []
fit_moves = []

with open('train_data/acm.pgn') as pgn:
    boards, moves = convert.generate_next_boards(pgn)

    fit_boards += boards
    fit_moves += moves

target_boards = []

with open('train_data/man_machine.pgn') as pgn:
    boards, moves = convert.generate_next_boards(pgn)

    target_boards += boards

nn = SKCompat(DNNRegressor(hidden_units=[64, 128, 63],
                  feature_columns=[tfc.layers.real_valued_column("")]))

nn.fit(tf.constant(fit_boards), tf.constant(fit_moves))

res = nn.predict(target_boards)

print(res)


text:
import React from 'react';
import { describe, it } from 'flow-typed-test';
import {
  StaticRouter,
  MemoryRouter,
  Router,
  Prompt,
  Redirect,
  Route,
  Switch,
  withRouter,
  matchPath,
} from 'react-router';
import type {
  Location,
  Match,
  ContextRouter,
  RouterHistory,
} from 'react-router';

describe('Location', () => {
  it('should error if wrong type is passed', () => {
    // $FlowExpectedError[incompatible-type]
    const locationError: Location = 'location';
  });

  it('should work if type is correct', () => {
    const location: Location = {
      pathname: '/path',
      search: '?search',
      hash: '#hash',
      state: null,
      key: 'key',
    };
  });
});

describe('StaticRouter', () => {
  <StaticRouter context={{}}>

  </StaticRouter>;
  <StaticRouter location="/" context={{}} basename="/foo/">

  </StaticRouter>;

  // $FlowExpectedError[prop-missing]
  <StaticRouter />;
});

describe('MemoryRouter', () => {
  <MemoryRouter>

  </MemoryRouter>;
  <MemoryRouter
    initialEntries={['/one', '/two', { pathname: '/three' }]}
    initialIndex={1}
    getUserConfirmation={(
      message: string,
      callback: (confirmed: boolean) => void,
    ): void => {}}
    keyLength={3}
  >

  </MemoryRouter>;

  // $FlowExpectedError[incompatible-type]
  <MemoryRouter initialEntries={''} />;
});

describe('RouterHistory', () => {
  declare var history: RouterHistory;
  <Router history={history}>

  </Router>;

  // $FlowExpectedError[prop-missing]
  <Router>

  </Router>;
});

describe('Prompt', () => {
  <Prompt message="ok?" when={true} />;
  <Prompt message={location => 'ok?'} />;
  <Prompt message={location => true} />;

  // $FlowExpectedError[prop-missing]
  <Prompt />;
});

describe('Redirect', () => {
  <Redirect to="/foo" push />;
  <Redirect
    to={{
      pathname: '/login',
      search: '?utm=foo',
      state: { referrer: '/current' },
    }}
  />;
  <Redirect to="/foo" push from="/x" />;

  // $FlowExpectedError[prop-missing]
  <Redirect />;
});

describe('Route', () => {
  const User = () =>
;
  <Route
    path={['/', '/user/:username']}
    children={({ match }) =>
}
  />;
  <Route path="/user/:username" component={User} exact={true} strict={true} />;
  <Route path="/home" render={({ match }) =>
Home {match.path}
} />;
  <Route
    path="/"
    children={({ match }) =>
}
  />;
  <Route>

children

  </Route>;

// $FlowExpectedError[incompatible-type]
  <Route path="/user/:username" component={<User />} />;
});

describe('Switch', () => {
  <Switch>
    <Route />
    <Route />
  </Switch>;
});

describe('withRouter', () => {
  type FooProps = {|
    ...ContextRouter,
    name: string,
  |};
  const Foo = ({ location, name }: FooProps) => (

      {location.pathname} {name}

  );
  const FooWithRouter = withRouter(Foo);
  <FooWithRouter name="name" />;

  class Bar extends React.Component<FooProps> {}
  const BarWithRouter = withRouter(Bar);
  <BarWithRouter name="name" />;

  // $FlowExpectedError[incompatible-call]
  withRouter('nope');

  const FooWithRouterError = withRouter(Foo);
  <FooWithRouterError name="3" />;

  const BarWithRouterError = withRouter(Bar);
  // $FlowExpectedError
  <BarWithRouterError name={3} />;

  const IncorrectHistoryUsage = ({ history, name }: FooProps) => {
    // Wrong arguments here
    // $FlowExpectedError[incompatible-call]
    history.push(['bla']);
    return
{name}
;
  };
});

describe('matchPath', () => {
  // matchPath
  const match: null | Match = matchPath('/the/pathname', {
    path: '/the/:dynamicId',
    exact: true,
    strict: false,
  });
  const match2: null | Match = matchPath('/the/pathname', {
    path: ['/the/:dynamicId', '/the/otherRoute'],
    exact: true,
    strict: false,
  });
  const match3: null | Match = matchPath('/the/pathname', '/the/:dynamicId');
  const match4: null | Match = matchPath('/the/pathname', [
    '/the/:dynamicId',
    '/the/otherRoute',
  ]);
  const match5: null | Match = matchPath('/the/pathname');

  // $FlowExpectedError[incompatible-call]
  matchPath();
  // $FlowExpectedError[incompatible-type]
  const matchError: string = matchPath('/the/pathname', 'the/:dynamicId');
});

describe('Unrouted', () => {
  const Unrouted: React$ComponentType<{|
    ...ContextRouter,
    someProp: string,
  |}> = () => ;

  const Routed1: React$ComponentType<{| someProp: string |}> = withRouter(
    Unrouted,
  );

  const Unrouted2: React$ComponentType<{|
    ...ContextRouter,
    someProp: string,
  |}> = () => ;

  const Routed2: React$ComponentType<{| someProp2: string |}> = withRouter(
    // $FlowExpectedError[prop-missing]
    Unrouted2,
  );
});


text:
package org.spongepowered.api.registry;

public enum RegistrationPhase {
    PRE_REGISTRY,
    PRE_INIT,
    INIT,
    POST_INIT,
    LOADED,
    ;
}


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

namespace Microsoft.Azure.Management.DataFactories.Registration.Models
{
    /// <summary>
    /// Parameters specifying the ComputeType definition for a create or update
    /// operation.
    /// </summary>
    public class ComputeTypeCreateOrUpdateParameters
    {
        /// <summary>
        /// Required. The definition of a ComputeType to be created or updated.
        /// </summary>
        public ComputeType ComputeType { get; set; }

        /// <summary>
        /// Initializes a new instance of the
        /// ComputeTypeCreateOrUpdateParameters class.
        /// </summary>
        public ComputeTypeCreateOrUpdateParameters()
        {
        }

        /// <summary>
        /// Initializes a new instance of the
        /// ComputeTypeCreateOrUpdateParameters class with required
        /// arguments.
        /// </summary>
        public ComputeTypeCreateOrUpdateParameters(ComputeType computeType)
            : this()
        {
            Ensure.IsNotNull(computeType, "computeType");
            this.ComputeType = computeType;
        }
    }
}


text:
require 'erb'
require 'fileutils'
require 'yaml'
require 'redcloth'
require 'syntax/convertors/html'

module Syntax
  module Manual

    class Manual
      attr_accessor :product, :meta, :chapters, :tutorials, :examples, :recent_updates

      def Manual.load( file_name )
        File.open( file_name ) { |file| YAML.load( file ) }
      end
    end

    class Meta
      attr_accessor :copyright, :author, :email
    end

    class Product
      attr_accessor :name, :tagline, :version, :logo, :urls, :project
    end

    class Sidebar
      attr_accessor :title, :content
    end

    class Chapter
      attr_accessor :index, :title, :sections

      def initialize( index, title, sections )
        @index = index
        @title = title

        section_index = 0
        @sections = ( sections || [] ).collect do |section|
          section_index += 1
          if section.respond_to? :keys
            Section.new( section_index, section.keys.first, section.values.first )
          else
            section_index -= 1
            Section.new( section_index, nil, section )
          end
        end
      end

      def page_title
        "Chapter #{index}: #{title}"
      end
    end

    class Tutorial
      attr_accessor :index, :title, :brief, :intro, :steps, :summary

      def initialize( index, title, brief, intro, steps, summary )
        @index = index
        @title = title
        @brief = RedCloth.new( brief )
        @intro = RedCloth.new( intro ) if intro
        @summary = RedCloth.new( summary ) if summary
        @steps = steps.map { |step| RedCloth.new( step ) }
      end

      def page_title
        "Tutorial #{index}: #{title}"
      end
    end

    class Example
      attr_accessor :index, :title, :brief, :intro, :design, :implementation, :summary

      def initialize( index, title, brief, intro, design, implementation, summary )
        @index = index
        @title = title
        @brief = RedCloth.new( brief )
        @intro = RedCloth.new( intro )
        @design = RedCloth.new( design )
        @implementation = RedCloth.new( implementation )
        @summary = RedCloth.new( summary )
      end

      def page_title
        "Example #{index}: #{title}"
      end
    end

    class Section
      attr_accessor :index, :title, :content

      def initialize( index, title, content )
        @index = index
        @title = RedCloth.new( title ).to_html.gsub( %r{</?p>}, "" ) if title
        @content = FigureContainer.new( content || "" )
      end
    end

    class FigureContainer
      def initialize( content )
        @content = content
        @html = nil
      end

      def to_html
        return @html if @html
        extract_figures
        convert_to_html
        replace_figures
        @html
      end

      private

        Figure = Struct.new( :opts, :body )

        def extract_figures
          @figures = []
          @content.gsub!( /^\{\{\{(.*?)?\n(.*?)\n\}\}\}$/m ) do
            body = $2.strip
            opts = Hash[*$1.strip.split(/,/).map{|p| p.split(/=/)}.flatten]
            @figures << Figure.new( opts, body )
            "====#{@figures.length-1}===="
          end
        end

        def convert_to_html
          @html = ( @content.length < 1 ? "" :
            RedCloth.new( @content ).to_html )
        end

        def replace_figures
          @html.gsub!( /
====(.*?)====<\/p>/ ) do
            figure = @figures[$1.to_i]
            lang = figure.opts["lang"]
            caption = figure.opts["caption"] || "Figure"
            caption << " [#{lang}]" if lang

            body = figure.body

            if lang
              convertor = Syntax::Convertors::HTML.for_syntax( lang )

              body = "<link rel='stylesheet' type='text/css' " +
                     "href='stylesheets/#{lang}.css' />" +
                     "
" +
                     convertor.convert( body ) +
                     "
"
            end

            if figure.opts["number"] && eval(figure.opts["number"])
              line = 1
              numbers = ""
              body.each_line { numbers << "#{line}
"; line += 1 }
              body = "
" +
                     "
#{numbers}	" +
                     "#{body}

"
            end

            "
\n" +
            "#{caption}\n" +
            "
#{body}
" +
            "
"
          end
        end
    end

    YAML.add_private_type( 'file' ) { |type_id, value| File.read( value ) rescue "" }
    YAML.add_private_type( 'eval' ) { |type_id, value| eval( value ) }

    YAML.add_domain_type( 'jamisbuck.org,2004', 'manual' ) do |taguri, val|
      index = 0

      val['chapters'].collect! do |chapter|
        index += 1
        Chapter.new( index, chapter.keys.first, chapter.values.first )
      end

      index = 0
      ( val['tutorials'] ||= [] ).collect! do |tutorial|
        index += 1
        content = tutorial.values.first
        Tutorial.new( index, tutorial.keys.first, content['brief'], content['intro'],
                      content['steps'], content['summary'] )
      end

      index = 0
      ( val['examples'] ||= [] ).collect! do |example|
        index += 1
        content = example.values.first
        Example.new( index, example.keys.first, content['brief'], content['intro'], content['design'],
                     content['implementation'], content['summary'] )
      end

      YAML.object_maker( Manual, val )
    end

    YAML.add_domain_type( 'jamisbuck.org,2004', 'meta' ) do |taguri, val|
      YAML.object_maker( Meta, val )
    end

    YAML.add_domain_type( 'jamisbuck.org,2004', 'product' ) do |taguri, val|
      version = val["version"]
      if version.respond_to?( :type_id )
        if version.type_id == "version"
          if version.value =~ %r{(.*)/(.*)}
            require_file, constant = $1, $2
          else
            constant = version.value
          end

          require require_file if require_file
          val["version"] = eval(constant)
        else
          raise "Unexpected type: #{val.type_id}"
        end
      end
      YAML.object_maker( Product, val )
    end

    YAML.add_domain_type( 'jamisbuck.org,2004', 'sidebar' ) do |taguri, val|
      YAML.object_maker( Sidebar,
                         'title' => val.keys.first,
                         'content'=> RedCloth.new( val.values.first ) )
    end

  end
end

if __FILE__ == $0

  def log_action( action )
    $stderr.puts action
  end

  unless ( output_path = ARGV[0] )
    $stderr.puts "Usage: #{$0} [/path/to/save/html]"
    exit
  end

  FileUtils.mkdir_p File.join( output_path, "stylesheets" )

  log_action "Loading manual.yml..."
  manual = Syntax::Manual::Manual.load( 'manual.yml' )

  # force these to be defined at the TOPLEVEL_BINDING
  object = nil
  guts = nil

  page = File.open( "page.erb" ) { |file| ERB.new( file.read ) }
  page.filename = "page.erb"

  template = File.open( "index.erb" ) { |file| ERB.new( file.read ) }
  template.filename = "index.erb"

  File.open( File.join( output_path, "index.html" ), "w" ) do |file|
    guts = template.result
    file << page.result
  end

  template = File.open( "chapter.erb" ) { |file| ERB.new( file.read ) }
  template.filename = "chapter.erb"

  manual.chapters.each_with_index do |object,index|
    log_action "Processing chapter ##{object.index}..."

    previous_chapter = ( index < 1 ? nil : manual.chapters[index-1] )
    next_chapter = manual.chapters[index+1]

    File.open( File.join( output_path, "chapter-#{object.index}.html" ), "w" ) do |file|
      guts = template.result( binding )
      file << page.result( binding )
    end
  end

  template = File.open( "tutorial.erb" ) { |file| ERB.new( file.read ) }
  template.filename = "tutorial.erb"

  manual.tutorials.each do |object|
    log_action "Processing tutorial ##{object.index}..."
    File.open( File.join( output_path, "tutorial-#{object.index}.html" ), "w" ) do |file|
      guts = template.result
      file << page.result
    end
  end

#  template = File.open( "example.erb" ) { |file| ERB.new( file.read ) }
#  template.filename = "example.erb"

#  manual.examples.each do |object|
#    log_action "Processing example ##{object.index}..."
#    File.open( File.join( output_path, "example-#{object.index}.html" ), "w" ) do |file|
#      guts = template.result
#      file << page.result
#    end
#  end

  log_action "Copying style sheets..."
  FileUtils.cp Dir["stylesheets/*.css"], File.join( output_path, "stylesheets" )

  log_action "Done!"
end


text:
package com.msjBand.android.trip.json;

import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;
import com.msjBand.android.trip.extras.MyApplication;
import com.msjBand.android.trip.logging.L;
import org.json.JSONArray;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by Archimedes on 4/4/2016.
 */
public class Requester {
        public static JSONArray requestMasterEventsJSON(RequestQueue requestQueue, String url) {
            JSONArray response = null;
            RequestFuture<JSONArray> requestFuture = RequestFuture.newFuture();

            JsonArrayRequest request = new JsonArrayRequest(
                    Request.Method.GET,
                    url,
                    null,
                    requestFuture,
                    requestFuture);

            requestQueue.add(request);

            try {
                response = requestFuture.get(30000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Log.e("MyService", e + "");
            } catch (ExecutionException e) {
                Log.e("MyService", e + "");
            } catch (TimeoutException e) {
                Log.e("MyService", e + "");
            }
            return response;
        }

}


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using PlainElastic.Net.Utils;

namespace PlainElastic.Net.Queries
{
    public abstract class HistogramFacetBase<TFacet, T> : FacetBase<TFacet, T> where TFacet : HistogramFacetBase<TFacet, T>
    {
        /// <summary>
        /// The field to execute facet against.
        /// </summary>
        public TFacet Field(string fieldName)
        {
            RegisterJsonPart("'field': {0}", fieldName.Quotate());
            return (TFacet)this;
        }

        /// <summary>
        /// The field to execute facet against.
        /// </summary>
        public TFacet Field(Expression<Func<T, object>> field)
        {
            return Field(field.GetPropertyPath());
        }

        /// <summary>
        /// The field to execute facet against.
        /// </summary>
        public TFacet FieldOfCollection<TProp>(Expression<Func<T, IEnumerable<TProp>>> collectionField, Expression<Func<TProp, object>> field)
        {
            var collectionProperty = collectionField.GetPropertyPath();
            var fieldName = collectionProperty + "." + field.GetPropertyPath();

            return Field(fieldName);
        }

        /// <summary>
        /// The field to check if its value falls within an interval.
        /// </summary>
        public TFacet KeyField(string fieldName)
        {
            RegisterJsonPart("'key_field': {0}", fieldName.Quotate());
            return (TFacet)this;
        }

        /// <summary>
        /// The field to check if its value falls within an interval.
        /// </summary>
        public TFacet KeyField(Expression<Func<T, object>> keyField)
        {
            return KeyField(keyField.GetPropertyPath());
        }

        /// <summary>
        /// The field to check if its value falls within an interval.
        /// </summary>
        public TFacet KeyFieldOfCollection<TProp>(Expression<Func<T, IEnumerable<TProp>>> collectionField, Expression<Func<TProp, object>> keyField)
        {
            var collectionProperty = collectionField.GetPropertyPath();
            var fieldName = collectionProperty + "." + keyField.GetPropertyPath();

            return KeyField(fieldName);
        }

        /// <summary>
        /// The field to compute aggregated data per interval.
        /// </summary>
        public TFacet ValueField(string fieldName)
        {
            RegisterJsonPart("'value_field': {0}", fieldName.Quotate());
            return (TFacet)this;
        }

        /// <summary>
        /// The field to compute aggregated data per interval.
        /// </summary>
        public TFacet ValueField(Expression<Func<T, object>> valueField)
        {
            return ValueField(valueField.GetPropertyPath());
        }

        /// <summary>
        /// The field to compute aggregated data per interval.
        /// </summary>
        public TFacet ValueFieldOfCollection<TProp>(Expression<Func<T, IEnumerable<TProp>>> collectionField, Expression<Func<TProp, object>> valueField)
        {
            var collectionProperty = collectionField.GetPropertyPath();
            var fieldName = collectionProperty + "." + valueField.GetPropertyPath();

            return ValueField(fieldName);
        }

        /// <summary>
        /// The script to get value to check if it falls within an interval.
        /// </summary>
        public TFacet KeyScript(string keyScript)
        {
            RegisterJsonPart("'key_script': {0}", keyScript.Quotate());
            return (TFacet)this;
        }

        /// <summary>
        /// The script to get value to compute aggregated data per interval.
        /// </summary>
        public TFacet ValueScript(string valueScript)
        {
            RegisterJsonPart("'value_script': {0}", valueScript.Quotate());
            return (TFacet)this;
        }

        /// <summary>
        /// Sets a scripting language used for scripts.
        /// By default used mvel language.
        /// see: http://www.elasticsearch.org/guide/reference/modules/scripting.html
        /// </summary>
        public TFacet Lang(string lang)
        {
            RegisterJsonPart("'lang': {0}", lang.Quotate());
            return (TFacet)this;
        }

        /// <summary>
        /// Sets a scripting language used for scripts.
        /// By default used mvel language.
        /// see: http://www.elasticsearch.org/guide/reference/modules/scripting.html
        /// </summary>
        public TFacet Lang(ScriptLangs lang)
        {
            return Lang(lang.AsString());
        }

        /// <summary>
        /// Sets parameters used for scripts.
        /// </summary>
        public TFacet Params(string paramsBody)
        {
            RegisterJsonPart("'params': {0}", paramsBody);
            return (TFacet)this;
        }

    }
}


text:
struct User {
    int Index;
    int ConnectionState;
    char IP[20];
    unsigned int Port;
    unsigned char Type;
    SOCKET socket;
    _PER_SOCKET_CONTEXT *PerSocketContext;
    bool News;
    int PacketCount;
    ULONGLONG i64PacketTime;
};

void UserInit();

short UserAdd(SOCKET s, char *IP);

short UserDelete(int index);

bool UserSet(int index, unsigned int Port, int type, char *Name);

void UserRun();

extern User Users[MAX_USER];

#endif


text:
package org.kaaproject.kaa.server.operations.service.user;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.HashSet;

import org.junit.Before;
import org.junit.Test;
import org.kaaproject.kaa.common.dto.EndpointProfileDto;
import org.kaaproject.kaa.common.dto.EventClassFamilyVersionStateDto;
import org.kaaproject.kaa.server.common.Base64Util;
import org.kaaproject.kaa.server.common.dao.EndpointService;
import org.kaaproject.kaa.server.common.dao.exception.DatabaseProcessingException;
import org.kaaproject.kaa.server.operations.service.cache.AppSeqNumber;
import org.kaaproject.kaa.server.operations.service.cache.CacheService;
import org.kaaproject.kaa.server.operations.service.cache.EventClassFqnKey;
import org.kaaproject.kaa.server.operations.service.event.EventClassFamilyVersion;
import org.kaaproject.kaa.server.operations.service.event.EventClassFqnVersion;
import org.kaaproject.kaa.server.operations.service.event.RouteTableKey;
import org.kaaproject.kaa.server.sync.EndpointAttachRequest;
import org.kaaproject.kaa.server.sync.EndpointAttachResponse;
import org.kaaproject.kaa.server.sync.EndpointDetachRequest;
import org.kaaproject.kaa.server.sync.EndpointDetachResponse;
import org.kaaproject.kaa.server.sync.EventListenersRequest;
import org.kaaproject.kaa.server.sync.EventListenersResponse;
import org.kaaproject.kaa.server.sync.SyncStatus;
import org.mockito.Mockito;
import org.springframework.test.util.ReflectionTestUtils;

public class DefaultEndpointUserServiceTest {
    private static final int ECF1_VERSION = 43;
    private static final String ECF1_ID = "EF1_ID";
    private static final String ENDPOINT_ACCESS_TOKEN = "endpointAccessToken";
    private static final String EXTERNAL_USER_ID = "userExternalId";
    private static final String USER_ID = "userId";

    private static final String TEST_TENANT_ID = "testTenantId";

    private static final String EXTERNAL_USER_ID_OTHER = "userExternalIdOther";
    private static final int REQUEST_ID = 42;
    private static final byte[] ENDPOINT_KEY_HASH = new byte[]{1,2,3};
    private static final byte[] ENDPOINT_KEY_HASH_OTHER = new byte[]{4,5,6};
    private static final byte[] ENDPOINT_KEY_HASH1 = new byte[]{1,2,0,1};
    private static final byte[] ENDPOINT_KEY_HASH2 = new byte[]{1,2,0,2};
    private static final byte[] ENDPOINT_KEY_HASH3 = new byte[]{1,2,0,3};

    private static final String TEST_APP_ID = "testAppId";
    private static final String TEST_APP_ID2 = "testAppId2";
    private static final String TEST_APP_ID3 = "testAppId3";
    private static final String TEST_APP_TOKEN = "testAppToken";
    private static final String TEST_APP_TOKEN2 = "testAppToken2";
    private static final String TEST_APP_TOKEN3 = "testAppToken3";
    private static final int TEST_APP_SEQ_NUM = 42;

    private EndpointUserService endpointUserService;
    private EndpointService endpointService;
    private CacheService cacheService;

    @Before
    public void before() {
        endpointUserService = new DefaultEndpointUserService();
        endpointService = mock(EndpointService.class);
        cacheService = mock(CacheService.class);
        ReflectionTestUtils.setField(endpointUserService, "endpointService", endpointService);
        ReflectionTestUtils.setField(endpointUserService, "cacheService", cacheService);
    }

//    TODO: move to appropriate place
//    @Test
//    public void attachUserSuccessTest(){
//        UserAttachRequest request = new UserAttachRequest(EXTERNAL_USER_ID, USER_ACCESS_TOKEN);
//        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);
//
//        when(profileMock.getApplicationId()).thenReturn(APPLICATION_ID);
//
//        ApplicationDto appDto = new ApplicationDto();
//        appDto.setTenantId(TEST_TENANT_ID);
//
//        when(applicationService.findAppById(APPLICATION_ID)).thenReturn(appDto);
//
//        when(endpointService.checkAccessToken(appDto, EXTERNAL_USER_ID, USER_ACCESS_TOKEN)).thenReturn(Boolean.TRUE);
//
//        UserAttachResponse response = endpointUserService.attachUser(profileMock, request);
//        assertNotNull(response);
//        assertEquals(SyncStatus.SUCCESS, response.getResult());
//    }
//
//    @Test
//    public void attachUserFailureTest(){
//        UserAttachRequest request = new UserAttachRequest(EXTERNAL_USER_ID, USER_ACCESS_TOKEN);
//        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);
//
//        when(profileMock.getApplicationId()).thenReturn(APPLICATION_ID);
//
//        ApplicationDto appDto = new ApplicationDto();
//        appDto.setTenantId(TEST_TENANT_ID);
//
//        when(applicationService.findAppById(APPLICATION_ID)).thenReturn(appDto);
//
//        when(endpointService.checkAccessToken(appDto, EXTERNAL_USER_ID, USER_ACCESS_TOKEN)).thenReturn(Boolean.FALSE);
//
//        UserAttachResponse response = endpointUserService.attachUser(profileMock, request);
//        assertNotNull(response);
//        assertEquals(SyncStatus.FAILURE, response.getResult());
//    }

    @Test
    public void attachEndpointSuccessTest(){
        EndpointAttachRequest request = new EndpointAttachRequest(REQUEST_ID, ENDPOINT_ACCESS_TOKEN);
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);
        EndpointProfileDto attachedEndpointMock = mock(EndpointProfileDto.class);

        when(profileMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID);
        when(endpointService.attachEndpointToUser(EXTERNAL_USER_ID, ENDPOINT_ACCESS_TOKEN)).thenReturn(attachedEndpointMock);
        when(attachedEndpointMock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH);

        EndpointAttachResponse response = endpointUserService.attachEndpoint(profileMock, request);
        assertNotNull(response);
        assertEquals(SyncStatus.SUCCESS, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void attachEndpointFailureTest(){
        EndpointAttachRequest request = new EndpointAttachRequest(REQUEST_ID, ENDPOINT_ACCESS_TOKEN);
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);

        when(profileMock.getEndpointUserId()).thenReturn(null);

        EndpointAttachResponse response = endpointUserService.attachEndpoint(profileMock, request);
        assertNotNull(response);
        assertEquals(SyncStatus.FAILURE, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void attachEndpointDBFailureTest(){
        EndpointAttachRequest request = new EndpointAttachRequest(REQUEST_ID, ENDPOINT_ACCESS_TOKEN);
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);

        when(profileMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID);
        when(endpointService.attachEndpointToUser(EXTERNAL_USER_ID, ENDPOINT_ACCESS_TOKEN)).thenThrow(DatabaseProcessingException.class);

        EndpointAttachResponse response = endpointUserService.attachEndpoint(profileMock, request);
        assertNotNull(response);
        assertEquals(SyncStatus.FAILURE, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void detachSelfEndpointSuccessTest(){
        EndpointDetachRequest request = new EndpointDetachRequest(REQUEST_ID, Base64Util.encode(ENDPOINT_KEY_HASH));
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);

        when(profileMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID);
        when(profileMock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH);

        EndpointDetachResponse response = endpointUserService.detachEndpoint(profileMock, request);

        Mockito.verify(endpointService, Mockito.never()).findEndpointProfileByKeyHash(Mockito.any(byte[].class));
        Mockito.verify(endpointService).detachEndpointFromUser(profileMock);

        assertNotNull(response);
        assertEquals(SyncStatus.SUCCESS, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void detachEndpointSuccessTest(){
        EndpointDetachRequest request = new EndpointDetachRequest(REQUEST_ID, Base64Util.encode(ENDPOINT_KEY_HASH_OTHER));
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);
        EndpointProfileDto detachMock = mock(EndpointProfileDto.class);

        when(profileMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID);
        when(profileMock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH);
        when(endpointService.findEndpointProfileByKeyHash(ENDPOINT_KEY_HASH_OTHER)).thenReturn(detachMock);
        when(detachMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID);

        EndpointDetachResponse response = endpointUserService.detachEndpoint(profileMock, request);

        Mockito.verify(endpointService).detachEndpointFromUser(detachMock);

        assertNotNull(response);
        assertEquals(SyncStatus.SUCCESS, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void detachEndpointInvalidRequestFailureTest(){
        EndpointDetachRequest request = new EndpointDetachRequest(REQUEST_ID, null);
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);

        EndpointDetachResponse response = endpointUserService.detachEndpoint(profileMock, request);

        assertNotNull(response);
        assertEquals(SyncStatus.FAILURE, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void detachEndpointInvalidProfileFailureTest(){
        EndpointDetachRequest request = new EndpointDetachRequest(REQUEST_ID, Base64Util.encode(ENDPOINT_KEY_HASH_OTHER));
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);

        EndpointDetachResponse response = endpointUserService.detachEndpoint(profileMock, request);

        assertNotNull(response);
        assertEquals(SyncStatus.FAILURE, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void detachEndpointInvalidUserIdFailureTest(){
        EndpointDetachRequest request = new EndpointDetachRequest(REQUEST_ID, Base64Util.encode(ENDPOINT_KEY_HASH_OTHER));
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);
        EndpointProfileDto detachMock = mock(EndpointProfileDto.class);

        when(profileMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID);
        when(profileMock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH);
        when(endpointService.findEndpointProfileByKeyHash(ENDPOINT_KEY_HASH_OTHER)).thenReturn(detachMock);
        when(detachMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID_OTHER);

        EndpointDetachResponse response = endpointUserService.detachEndpoint(profileMock, request);

        Mockito.verify(endpointService, Mockito.never()).detachEndpointFromUser(detachMock);

        assertNotNull(response);
        assertEquals(SyncStatus.FAILURE, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void detachEndpointDBExceptionFailureTest(){
        EndpointDetachRequest request = new EndpointDetachRequest(REQUEST_ID, Base64Util.encode(ENDPOINT_KEY_HASH_OTHER));
        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);
        EndpointProfileDto detachMock = mock(EndpointProfileDto.class);

        when(profileMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID);
        when(profileMock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH);
        when(endpointService.findEndpointProfileByKeyHash(ENDPOINT_KEY_HASH_OTHER)).thenReturn(detachMock);
        when(detachMock.getEndpointUserId()).thenReturn(EXTERNAL_USER_ID);
        Mockito.doThrow(new DatabaseProcessingException("")).when(endpointService).detachEndpointFromUser(detachMock);

        EndpointDetachResponse response = endpointUserService.detachEndpoint(profileMock, request);

        assertNotNull(response);
        assertEquals(SyncStatus.FAILURE, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void getEventListenersTest(){
        EventListenersRequest request = new EventListenersRequest();
        request.setEventClassFQNs(Arrays.asList("fqn2", "fqn3"));
        request.setRequestId(REQUEST_ID);

        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);
        EndpointProfileDto listener1Mock = mock(EndpointProfileDto.class);
        EndpointProfileDto listener2Mock = mock(EndpointProfileDto.class);
        EndpointProfileDto listener3Mock = mock(EndpointProfileDto.class);

        EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto();
        ecfVdto.setEcfId(ECF1_ID);
        ecfVdto.setVersion(ECF1_VERSION);

        when(profileMock.getId()).thenReturn("A");
        when(profileMock.getEndpointUserId()).thenReturn(USER_ID);
        when(profileMock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH);
        when(profileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto));

        when(listener1Mock.getId()).thenReturn("B");
        when(listener1Mock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH1);
        when(listener1Mock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto));
        when(listener1Mock.getApplicationId()).thenReturn(TEST_APP_ID);

        when(listener2Mock.getId()).thenReturn("C");
        when(listener2Mock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH2);
        when(listener2Mock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto));
        when(listener2Mock.getApplicationId()).thenReturn(TEST_APP_ID2);

        when(listener3Mock.getId()).thenReturn("D");
        when(listener3Mock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH3);
        when(listener3Mock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto));
        when(listener3Mock.getApplicationId()).thenReturn(TEST_APP_ID3);

        when(endpointService.findEndpointProfilesByUserId(USER_ID)).thenReturn(Arrays.asList(profileMock, listener1Mock, listener2Mock, listener3Mock));
        when(cacheService.getTenantIdByAppToken(TEST_APP_TOKEN)).thenReturn(TEST_TENANT_ID);
        when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TEST_TENANT_ID, "fqn2"))).thenReturn(ECF1_ID);
        when(cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(TEST_TENANT_ID, "fqn3"))).thenReturn(ECF1_ID);

        when(cacheService.getAppSeqNumber(TEST_APP_TOKEN)).thenReturn(new AppSeqNumber(TEST_TENANT_ID, TEST_APP_ID, TEST_APP_TOKEN, TEST_APP_SEQ_NUM));
        when(cacheService.getAppSeqNumber(TEST_APP_TOKEN2)).thenReturn(new AppSeqNumber(TEST_TENANT_ID, TEST_APP_ID2, TEST_APP_TOKEN2, TEST_APP_SEQ_NUM));
        when(cacheService.getAppSeqNumber(TEST_APP_TOKEN3)).thenReturn(new AppSeqNumber(TEST_TENANT_ID, TEST_APP_ID3, TEST_APP_TOKEN3, TEST_APP_SEQ_NUM));

        RouteTableKey key1 = new RouteTableKey(TEST_APP_TOKEN, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION));
        RouteTableKey key2 = new RouteTableKey(TEST_APP_TOKEN2, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION));
        RouteTableKey key3 = new RouteTableKey(TEST_APP_TOKEN3, new EventClassFamilyVersion(ECF1_ID, ECF1_VERSION));

        HashSet<RouteTableKey> fqn2Keys = new HashSet<>();
        fqn2Keys.add(key1);
        fqn2Keys.add(key2);
        fqn2Keys.add(key3);
        HashSet<RouteTableKey> fqn3Keys = new HashSet<>();
        fqn3Keys.add(key1);
        fqn3Keys.add(key2);
        //No Key3 for FQN 3
        when(cacheService.getRouteKeys(new EventClassFqnVersion(TEST_TENANT_ID, "fqn2", ECF1_VERSION))).thenReturn(fqn2Keys);
        when(cacheService.getRouteKeys(new EventClassFqnVersion(TEST_TENANT_ID, "fqn3", ECF1_VERSION))).thenReturn(fqn3Keys);

        EventListenersResponse response = endpointUserService.findListeners(profileMock, TEST_APP_TOKEN, request);

        assertNotNull(response);
        assertEquals(SyncStatus.SUCCESS, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
        assertEquals(2, response.getListeners().size());
        assertTrue(response.getListeners().contains(Base64Util.encode(ENDPOINT_KEY_HASH1)));
        assertTrue(response.getListeners().contains(Base64Util.encode(ENDPOINT_KEY_HASH2)));
        assertFalse(response.getListeners().contains(Base64Util.encode(ENDPOINT_KEY_HASH3)));
        assertFalse(response.getListeners().contains(Base64Util.encode(ENDPOINT_KEY_HASH)));
    }

    @Test
    public void getEventListenersFailure1Test(){
        EventListenersRequest request = new EventListenersRequest();
        request.setEventClassFQNs(Arrays.asList("fqn2", "fqn3"));
        request.setRequestId(REQUEST_ID);

        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);

        when(profileMock.getId()).thenReturn("A");
        when(profileMock.getEndpointUserId()).thenReturn(null);

        EventListenersResponse response = endpointUserService.findListeners(profileMock, TEST_APP_TOKEN, request);

        assertNotNull(response);
        assertEquals(SyncStatus.FAILURE, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
    }

    @Test
    public void getEventListenersEmptyTest(){
        EventListenersRequest request = new EventListenersRequest();
        request.setEventClassFQNs(Arrays.asList("fqn2", "fqn3"));
        request.setRequestId(REQUEST_ID);

        EndpointProfileDto profileMock = mock(EndpointProfileDto.class);

        EventClassFamilyVersionStateDto ecfVdto = new EventClassFamilyVersionStateDto();
        ecfVdto.setEcfId(ECF1_ID);
        ecfVdto.setVersion(ECF1_VERSION);

        when(profileMock.getId()).thenReturn("A");
        when(profileMock.getEndpointUserId()).thenReturn(USER_ID);
        when(profileMock.getEndpointKeyHash()).thenReturn(ENDPOINT_KEY_HASH);
        when(profileMock.getEcfVersionStates()).thenReturn(Arrays.asList(ecfVdto));

        when(endpointService.findEndpointProfilesByUserId(USER_ID)).thenReturn(Arrays.asList(profileMock));

        EventListenersResponse response = endpointUserService.findListeners(profileMock, TEST_APP_TOKEN, request);

        assertNotNull(response);
        assertEquals(SyncStatus.SUCCESS, response.getResult());
        assertEquals(REQUEST_ID, response.getRequestId());
        assertEquals(0, response.getListeners().size());
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Klebs, Abh. preuss. geol. Landesanst. 4(1): 14 + taf. 1, fig. 10 (1907)

#### Original name
Torula heteromorpha Penz. & Sacc.

### Remarks
null


text:
<img src="barrage.jpg" alt="Barrage" width="140" height="140">
# Barrage
Barrage is a benchmarking tool and has the goal to fill the following roles.

- Orchestrate running the benchmark on the server and client(s).
- Collect benchmark statistics (requests per second and latency distribution).
- Collect hardware and OS statistics (CPU, memory, disk, network, etc).
- Generate graphs.

There are 3 system roles in Barrage.
- Orchestrator
- Server
- Clients

# Ideas
My initial thought is Barrage will have an agent and orchestrator mode. Once the benchmark run is complete it will post the benchmark details to a Gist on GitHub including the graphs.

# Prerequisites
- **Orchestrator**
  Ubuntu `subo apt-get install ansible`
  Mac `brew install ansible`

- **Server**
  Ubuntu
  ```
  sudo apt-get install dstat gnuplot xclip
  gem install bundler
  ```

# Installing
```
gem install barrage_bench
```

# Running
```
barrage benchmark playbooks/haywire
```

# Available playbooks
[Haywire](playbooks/haywire)


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

package org.flowable.common.rest.api;

import java.util.List;

/**
 * @author Tijs Rademakers
 * @deprecated use {@link PaginateListUtil} and the appropriate {@link ListProcessor} instead
 */
@Deprecated
public class DefaultPaginateList<T> extends AbstractPaginateList<T, T> {

    @Override
    protected List<T> processList(List<T> list) {
        return list;
    }
}


text:
@class HJNC;

@interface HJNCDelegate : NSObject <UINavigationControllerDelegate, UIGestureRecognizerDelegate>

//nc
@property (nonatomic, weak) HJNC *ownerNC;
@property (nonatomic, copy) CompleteBlock comleteBlock;

@end


text:
namespace net {

class CertErrors;

namespace der {
class Input;
}  // namespace der

// Parses a NameConstraints extension value and allows testing whether names are
// allowed under those constraints as defined by RFC 5280 section 4.2.1.10.
class NET_EXPORT NameConstraints {
 public:
  ~NameConstraints();

  // Parses a DER-encoded NameConstraints extension and initializes this object.
  // |extension_value| should be the extnValue from the extension (not including
  // the OCTET STRING tag). |is_critical| should be true if the extension was
  // marked critical. Returns nullptr if parsing the the extension failed.
  // The object may reference data from |extension_value|, so is only valid as
  // long as |extension_value| is.
  static std::unique_ptr<NameConstraints> Create(
      const der::Input& extension_value,
      bool is_critical,
      CertErrors* errors);

  // Tests if a certificate is allowed by the name constraints.
  // |subject_rdn_sequence| should be the DER-encoded value of the subject's
  // RDNSequence (not including Sequence tag), and may be an empty ASN.1
  // sequence. |subject_alt_names| should be the parsed representation of the
  // subjectAltName extension or nullptr if the extension was not present.
  // If the certificate is not allowed, an error will be added to |errors|.
  // Note that this method does not check hostname or IP address in commonName,
  // which is deprecated (crbug.com/308330).
  void IsPermittedCert(const der::Input& subject_rdn_sequence,
                       const GeneralNames* subject_alt_names,
                       CertErrors* errors) const;

  // Returns true if the ASCII hostname |name| is permitted.
  // |name| may be a wildcard hostname (starts with "*."). Eg, "*.bar.com"
  // would not be permitted if "bar.com" is permitted and "foo.bar.com" is
  // excluded, while "*.baz.com" would only be permitted if "baz.com" is
  // permitted.
  bool IsPermittedDNSName(base::StringPiece name) const;

  // Returns true if the directoryName |name_rdn_sequence| is permitted.
  // |name_rdn_sequence| should be the DER-encoded RDNSequence value (not
  // including the Sequence tag.)
  bool IsPermittedDirectoryName(const der::Input& name_rdn_sequence) const;

  // Returns true if the iPAddress |ip| is permitted.
  bool IsPermittedIP(const IPAddress& ip) const;

  // Returns a bitfield of GeneralNameTypes of all the types constrained by this
  // NameConstraints. Name types that aren't supported will only be present if
  // the name constraint they appeared in was marked critical.
  //
  // RFC 5280 section 4.2.1.10 says:
  // Applications conforming to this profile MUST be able to process name
  // constraints that are imposed on the directoryName name form and SHOULD be
  // able to process name constraints that are imposed on the rfc822Name,
  // uniformResourceIdentifier, dNSName, and iPAddress name forms.
  // If a name constraints extension that is marked as critical
  // imposes constraints on a particular name form, and an instance of
  // that name form appears in the subject field or subjectAltName
  // extension of a subsequent certificate, then the application MUST
  // either process the constraint or reject the certificate.
  int constrained_name_types() const { return constrained_name_types_; }

  const GeneralNames& permitted_subtrees() const { return permitted_subtrees_; }
  const GeneralNames& excluded_subtrees() const { return excluded_subtrees_; }

 private:
  [[nodiscard]] bool Parse(const der::Input& extension_value,
                           bool is_critical,
                           CertErrors* errors);

  GeneralNames permitted_subtrees_;
  GeneralNames excluded_subtrees_;
  int constrained_name_types_ = GENERAL_NAME_NONE;
};

}  // namespace net

#endif  // NET_CERT_PKI_NAME_CONSTRAINTS_H_


text:
<!DOCTYPE html>

        <meta charset="utf-8" />

        <title>TShock Inventory Viewer</title>

        <link rel="icon" type="image/png" href="favicon.png" />

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/css/foundation.min.css" />
        <link rel="stylesheet" href="<?php echo PUBLIC_URL ?>/css/main.css" />

TShock Inventory Viewer


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

import io.airlift.slice.Slice;
import io.airlift.slice.Slices;

import java.util.List;
import java.util.Optional;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static io.trino.orc.metadata.statistics.StringStatistics.STRING_VALUE_BYTES_OVERHEAD;
import static java.lang.Math.addExact;
import static java.util.Objects.requireNonNull;

public class StringStatisticsBuilder
        implements SliceColumnStatisticsBuilder
{
    private final int stringStatisticsLimitInBytes;

    private long nonNullValueCount;
    private Slice minimum;
    private Slice maximum;
    private long sum;
    private final BloomFilterBuilder bloomFilterBuilder;

    public StringStatisticsBuilder(int stringStatisticsLimitInBytes, BloomFilterBuilder bloomFilterBuilder)
    {
        this(stringStatisticsLimitInBytes, 0, null, null, 0, bloomFilterBuilder);
    }

    private StringStatisticsBuilder(int stringStatisticsLimitInBytes, long nonNullValueCount, Slice minimum, Slice maximum, long sum, BloomFilterBuilder bloomFilterBuilder)
    {
        this.stringStatisticsLimitInBytes = stringStatisticsLimitInBytes;
        this.nonNullValueCount = nonNullValueCount;
        this.minimum = minimum;
        this.maximum = maximum;
        this.sum = sum;
        this.bloomFilterBuilder = requireNonNull(bloomFilterBuilder, "bloomFilterBuilder");
    }

    public long getNonNullValueCount()
    {
        return nonNullValueCount;
    }

    @Override
    public void addValue(Slice value)
    {
        requireNonNull(value, "value is null");

        if (nonNullValueCount == 0) {
            checkState(minimum == null && maximum == null);
            minimum = value;
            maximum = value;
        }
        else if (minimum != null && value.compareTo(minimum) <= 0) {
            minimum = value;
        }
        else if (maximum != null && value.compareTo(maximum) >= 0) {
            maximum = value;
        }
        bloomFilterBuilder.addString(value);

        nonNullValueCount++;
        sum = addExact(sum, value.length());
    }

    /**
     * This method can only be used in merging stats.
     * It assumes min or max could be nulls.
     */
    private void addStringStatistics(long valueCount, StringStatistics value)
    {
        requireNonNull(value, "value is null");
        checkArgument(valueCount > 0, "valueCount is 0");
        checkArgument(value.getMin() != null || value.getMax() != null, "min and max cannot both be null");

        if (nonNullValueCount == 0) {
            checkState(minimum == null && maximum == null);
            minimum = value.getMin();
            maximum = value.getMax();
        }
        else {
            if (minimum != null && (value.getMin() == null || minimum.compareTo(value.getMin()) > 0)) {
                minimum = value.getMin();
            }
            if (maximum != null && (value.getMax() == null || maximum.compareTo(value.getMax()) < 0)) {
                maximum = value.getMax();
            }
        }

        nonNullValueCount += valueCount;
        sum = addExact(sum, value.getSum());
    }

    private Optional<StringStatistics> buildStringStatistics()
    {
        if (nonNullValueCount == 0) {
            return Optional.empty();
        }
        minimum = dropStringMinMaxIfNecessary(minimum);
        maximum = dropStringMinMaxIfNecessary(maximum);
        if (minimum == null && maximum == null) {
            // Create string stats only when min or max is not null.
            // This corresponds to the behavior of metadata reader.
            return Optional.empty();
        }
        return Optional.of(new StringStatistics(minimum, maximum, sum));
    }

    @Override
    public ColumnStatistics buildColumnStatistics()
    {
        Optional<StringStatistics> stringStatistics = buildStringStatistics();
        stringStatistics.ifPresent(s -> verify(nonNullValueCount > 0));
        return new ColumnStatistics(
                nonNullValueCount,
                stringStatistics.map(s -> STRING_VALUE_BYTES_OVERHEAD + sum / nonNullValueCount).orElse(0L),
                null,
                null,
                null,
                stringStatistics.orElse(null),
                null,
                null,
                null,
                null,
                bloomFilterBuilder.buildBloomFilter());
    }

    public static Optional<StringStatistics> mergeStringStatistics(List<ColumnStatistics> stats)
    {
        // no need to set the stats limit for the builder given we assume the given stats are within the same limit
        StringStatisticsBuilder stringStatisticsBuilder = new StringStatisticsBuilder(Integer.MAX_VALUE, new NoOpBloomFilterBuilder());
        for (ColumnStatistics columnStatistics : stats) {
            StringStatistics partialStatistics = columnStatistics.getStringStatistics();
            if (columnStatistics.getNumberOfValues() > 0) {
                if (partialStatistics == null || (partialStatistics.getMin() == null && partialStatistics.getMax() == null)) {
                    // there are non null values but no statistics, so we cannot say anything about the data
                    return Optional.empty();
                }
                stringStatisticsBuilder.addStringStatistics(columnStatistics.getNumberOfValues(), partialStatistics);
            }
        }
        return stringStatisticsBuilder.buildStringStatistics();
    }

    private Slice dropStringMinMaxIfNecessary(Slice minOrMax)
    {
        if (minOrMax == null || minOrMax.length() > stringStatisticsLimitInBytes) {
            return null;
        }

        // Do not hold the entire slice where the actual stats could be small
        if (minOrMax.isCompact()) {
            return minOrMax;
        }
        return Slices.copyOf(minOrMax);
    }
}


text:
import ReactCytoscape from './components/ReactCytoscape';
import cytoscape from 'cytoscape';

module.exports = {
	ReactCytoscape,
	cytoscape
};


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

    <groupId>org.springframework</groupId>
    <artifactId>bomproject</artifactId>
    <version>0.1.0</version>

    <properties>
        <!-- Enable Java 8 -->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.4.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Get the dependencies of a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <!-- Spring Data MongoDB-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>1.7.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path-assert</artifactId>
            <version>0.9.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
	        <resource>
	          <directory>${project.basedir}/src/main/resources</directory>
	        </resource>
	        <resource>
	          <directory>${project.build.directory}/generated-resources</directory>
	        </resource>
        </resources>
        <plugins>
            <!-- Spring Boot Maven Support -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
		    <plugin>
		      <artifactId>maven-resources-plugin</artifactId>
		      <executions>
		        <execution>
		          <!-- Serves *only* to filter the wro.xml so it can get an absolute
		            path for the project -->
		          <id>copy-resources</id>
		          <phase>validate</phase>
		          <goals>
		            <goal>copy-resources</goal>
		          </goals>
		          <configuration>
		            <outputDirectory>${basedir}/target/wro</outputDirectory>
		            <resources>
		              <resource>
		                <directory>src/main/wro</directory>
		                <filtering>true</filtering>
		              </resource>
		            </resources>
		          </configuration>
		        </execution>
		      </executions>
		    </plugin>
		    <plugin>
		      <groupId>ro.isdc.wro4j</groupId>
		      <artifactId>wro4j-maven-plugin</artifactId>
		      <version>1.7.6</version>
		      <executions>
		        <execution>
		          <phase>generate-resources</phase>
		          <goals>
		            <goal>run</goal>
		          </goals>
		        </execution>
		      </executions>
		      <configuration>
		        <wroManagerFactory>ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory</wroManagerFactory>
		        <cssDestinationFolder>${project.build.directory}/generated-resources/static/css</cssDestinationFolder>
		        <jsDestinationFolder>${project.build.directory}/generated-resources/static/js</jsDestinationFolder>
		        <wroFile>${project.build.directory}/wro/wro.xml</wroFile>
		        <extraConfigFile>${basedir}/src/main/wro/wro.properties</extraConfigFile>
		        <contextFolder>${basedir}/src/main/wro</contextFolder>
		      </configuration>
		      <dependencies>
		        <dependency>
		          <groupId>org.webjars</groupId>
		          <artifactId>jquery</artifactId>
		          <version>2.1.1</version>
		        </dependency>
		        <dependency>
		          <groupId>org.webjars</groupId>
		          <artifactId>angularjs</artifactId>
		          <version>1.3.8</version>
		        </dependency>
		        <dependency>
		          <groupId>org.webjars</groupId>
		          <artifactId>bootstrap</artifactId>
		          <version>3.2.0</version>
		        </dependency>
		      </dependencies>
		    </plugin>
        </plugins>
    </build>
</project>


text:
/*!
  \file     PointsOverlay.h
  \author   Tody
  PointsOverlay definition.
  \date     2015/12/17
*/

#ifndef POINTSOVERLAY_H
#define POINTSOVERLAY_H

#include "BaseOverlay.h"

//! PointsOverlay implementation.
class PointsOverlay : public BaseOverlay
{
public :
    //! Constructor.
    PointsOverlay ( Scene* scene )
        : BaseOverlay ( "Show Points", scene, false  )
    {
    }

    //! Destructor.
    virtual ~PointsOverlay() {}

protected:
    void renderSceneOverlayImp();

};

#endif


text:
package org.realityforge.jml;

import java.util.Enumeration;
import javax.jms.JMSException;
import javax.jms.Message;

/**
 * Class containing utility methods.
 */
public final class MessageUtil
{
  @SuppressWarnings( { "unchecked" } )
  static <T> T castToType( final Message message, final Class<T> type )
    throws Exception
  {
    if( type.isInstance( message ) )
    {
      return (T)message;
    }
    else
    {
      final String errorMessage =
        "is not of the expected type " + type.getName() + ". Actual Message Type: " + message.getClass().getName();
      throw exceptionFor( message, errorMessage, null );
    }
  }

  static Exception exceptionFor( final Message message, final String description, final Exception e )
    throws Exception
  {
    return new Exception( "Message with ID = " + message.getJMSMessageID() + " " + description, e );
  }

  public static void copyMessageHeaders( final Message from, final Message to )
    throws JMSException
  {
    //set the developer assigned headers
    to.setJMSCorrelationID( from.getJMSCorrelationID() );
    to.setJMSReplyTo( from.getJMSReplyTo() );
    to.setJMSType( from.getJMSType() );

    // these are not used by the JMS provider ... but we use them to keep
    // track of values and then explicitly pass them to send method.
    to.setJMSDeliveryMode( from.getJMSDeliveryMode() );
    to.setJMSPriority( from.getJMSPriority() );
    to.setJMSExpiration( from.getJMSExpiration() );

    // copy all the application specific properties to new message
    final Enumeration propertyNames = from.getPropertyNames();
    while( propertyNames.hasMoreElements() )
    {
      final String name = (String)propertyNames.nextElement();
      final Object value = from.getObjectProperty( name );
      to.setObjectProperty( name, value );
    }
  }
}


text:
class VertX < Formula
  desc "Toolkit for building reactive applications on the JVM."
  homepage "http://vertx.io/"
  url "https://dl.bintray.com/vertx/downloads/vert.x-3.2.1-full.tar.gz"
  sha256 "16e85a80e4f3c3eacf972953fbd36da21ba99b49cc39eda7760f1436ad8cb685"

  bottle :unneeded

  def install
    rm_f Dir["bin/*.bat"]
    libexec.install %w[bin conf lib]
    bin.install_symlink "#{libexec}/bin/vertx"
  end

  test do
    (testpath/"HelloWorld.java").write <<-EOS.undent
    import io.vertx.core.AbstractVerticle;
    public class HelloWorld extends AbstractVerticle {
      public void start() {
        System.out.println("Hello World!");
        vertx.close();
        System.exit(0);
      }
    }
    EOS
    system "#{bin}/vertx", "run", "HelloWorld.java"
  end
end


text:
<?php

namespace denbora\R_T_G_Services\examples\RESTv3\Player;

use denbora\R_T_G_Services\examples\RESTv3\RestExample;

class ExternalPOST extends RestExample
{
}


text:
package org.apache.calcite.rel.metadata;

import com.google.common.collect.ImmutableList;

/**
 * DefaultRelMetadataProvider supplies a default implementation of the
 * {@link RelMetadataProvider} interface. It provides generic formulas and
 * derivation rules for the standard logical algebra; coverage corresponds to
 * the methods declared in {@link RelMetadataQuery}.
 */
public class DefaultRelMetadataProvider extends ChainedRelMetadataProvider {
  //~ Constructors -----------------------------------------------------------

  /**
   * Creates a new default provider. This provider defines "catch-all"
   * handlers for generic RelNodes, so it should always be given lowest
   * priority when chaining.
   */
  public DefaultRelMetadataProvider() {
    super(
        ImmutableList.of(
            RelMdPercentageOriginalRows.SOURCE,
            RelMdColumnOrigins.SOURCE,
            RelMdRowCount.SOURCE,
            RelMdUniqueKeys.SOURCE,
            RelMdColumnUniqueness.SOURCE,
            RelMdPopulationSize.SOURCE,
            RelMdSize.SOURCE,
            RelMdParallelism.SOURCE,
            RelMdMemory.SOURCE,
            RelMdDistinctRowCount.SOURCE,
            RelMdSelectivity.SOURCE,
            RelMdExplainVisibility.SOURCE,
            RelMdPredicates.SOURCE,
            RelMdCollation.SOURCE));
  }
}

// End DefaultRelMetadataProvider.java