text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView"
        style="@style/CardView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="50dp"
        app:cardBackgroundColor="@color/default_color"
        app:cardElevation="2dp"
        app:cardPreventCornerOverlap="false"
        app:cardUseCompatPadding="true"
        >

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp">

            <LinearLayout
                android:id="@+id/info_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <com.clover_studio.spikachatmodule.view.CustomTextView
                    android:id="@+id/info_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:paddingBottom="5dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text=""
                    android:textColor="@color/white"
                    android:textSize="17sp"/>

                <com.clover_studio.spikachatmodule.view.CustomTextView
                    android:id="@+id/info_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:text=""
                    android:textColor="@color/white"
                    />
            </LinearLayout>

            <Button
                android:id="@+id/oneButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/info_layout"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:text="@string/OK"/>

        </RelativeLayout>

    </android.support.v7.widget.CardView>
</RelativeLayout>


text:
package com.farmerbb.taskbar.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;

import com.google.android.material.tabs.TabLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.farmerbb.taskbar.BuildConfig;
import com.farmerbb.taskbar.R;
import com.farmerbb.taskbar.adapter.AppListAdapter;
import com.farmerbb.taskbar.fragment.SelectAppFragment;
import com.farmerbb.taskbar.util.Blacklist;
import com.farmerbb.taskbar.util.BlacklistEntry;
import com.farmerbb.taskbar.util.TopApps;
import com.farmerbb.taskbar.util.U;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.farmerbb.taskbar.util.Constants.*;

public class SelectAppActivity extends AppCompatActivity {

    private AppListGenerator appListGenerator;
    private ProgressBar progressBar;
    private AppListAdapter hiddenAdapter;
    private AppListAdapter topAppsAdapter;

    private boolean isCollapsed;

    private class SelectAppPagerAdapter extends FragmentPagerAdapter {

        SelectAppPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return SelectAppFragment.newInstance(position);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position) {
                case U.HIDDEN:
                    return getString(R.string.tb_blacklist_dialog_title);
                case U.TOP_APPS:
                    return getString(R.string.tb_top_apps_dialog_title);
            }

            return null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        boolean noShadow = getIntent().hasExtra("no_shadow");

        if(savedInstanceState == null) {
            setContentView(R.layout.tb_configure_start_menu);
            setFinishOnTouchOutside(false);
            setTitle(R.string.tb_start_menu_apps);

            if(noShadow) {
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.dimAmount = 0;
                getWindow().setAttributes(params);

                if(U.isChromeOs(this) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
                    getWindow().setElevation(0);
            }

            SharedPreferences pref = U.getSharedPreferences(this);
            isCollapsed = !pref.getBoolean(PREF_COLLAPSED, false);

            if(!isCollapsed) {
                U.sendBroadcast(this, ACTION_HIDE_TASKBAR);
            }

            progressBar = findViewById(R.id.progress_bar);
            appListGenerator = new AppListGenerator();
            appListGenerator.execute();
        } else {
            // Workaround for ViewPager disappearing on config change
            finish();

            if(!noShadow)
                U.newHandler().post(() -> {
                    Intent intent = U.getThemedIntent(this, SelectAppActivity.class);
                    startActivity(intent);
                });
        }
    }

    @Override
    public void finish() {
        if(appListGenerator != null && appListGenerator.getStatus() == AsyncTask.Status.RUNNING)
            appListGenerator.cancel(true);

        if(!isCollapsed) {
            U.sendBroadcast(this, ACTION_SHOW_TASKBAR);
        }

        super.finish();
    }

    public AppListAdapter getAppListAdapter(int type) {
        switch(type) {
            case U.HIDDEN:
                return hiddenAdapter;
            case U.TOP_APPS:
                return topAppsAdapter;
        }

        return null;
    }

    private final class AppListGenerator extends AsyncTask<Void, Void, AppListAdapter[]> {
        @SuppressWarnings("Convert2streamapi")
        @Override
        protected AppListAdapter[] doInBackground(Void... params) {
            UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
            LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);

            final List<UserHandle> userHandles = userManager.getUserProfiles();
            final List<LauncherActivityInfo> list = new ArrayList<>();

            for(UserHandle handle : userHandles) {
                list.addAll(launcherApps.getActivityList(null, handle));
            }

            // Remove any uninstalled apps from the blacklist and top apps
            Blacklist blacklist = Blacklist.getInstance(SelectAppActivity.this);
            TopApps topApps = TopApps.getInstance(SelectAppActivity.this);
            List<String> blacklistedApps = new ArrayList<>();
            List<String> topAppsList = new ArrayList<>();
            List<String> installedApps = new ArrayList<>();

            for(BlacklistEntry entry : blacklist.getBlockedApps()) {
                blacklistedApps.add(entry.getPackageName());
            }

            for(BlacklistEntry entry : topApps.getTopApps()) {
                topAppsList.add(entry.getPackageName());
            }

            for(LauncherActivityInfo appInfo : list) {
                installedApps.add(appInfo.getApplicationInfo().packageName + "/" + appInfo.getName()
                        + ":" + userManager.getSerialNumberForUser(appInfo.getUser()));
                installedApps.add(appInfo.getApplicationInfo().packageName + "/" + appInfo.getName());
                installedApps.add(appInfo.getName());
            }

            for(String packageName : blacklistedApps) {
                if(!installedApps.contains(packageName))
                    blacklist.removeBlockedApp(SelectAppActivity.this, packageName);
            }

            for(String packageName : topAppsList) {
                if(!installedApps.contains(packageName))
                    topApps.removeTopApp(SelectAppActivity.this, packageName);
            }

            Collections.sort(list, (ai1, ai2) -> {
                String label1;
                String label2;

                try {
                    label1 = ai1.getLabel().toString();
                    label2 = ai2.getLabel().toString();
                } catch (OutOfMemoryError e) {
                    System.gc();

                    label1 = ai1.getApplicationInfo().packageName;
                    label2 = ai2.getApplicationInfo().packageName;
                }

                return Collator.getInstance().compare(label1, label2);
            });

            final List<BlacklistEntry> entries = new ArrayList<>();
            for(LauncherActivityInfo appInfo : list) {
                String label;

                try {
                    label = appInfo.getLabel().toString();
                } catch (OutOfMemoryError e) {
                    System.gc();

                    label = appInfo.getApplicationInfo().packageName;
                }

                entries.add(new BlacklistEntry(
                        appInfo.getApplicationInfo().packageName + "/" + appInfo.getName()
                                + ":" + userManager.getSerialNumberForUser(appInfo.getUser()),
                        label));
            }

            return new AppListAdapter[] {
                    new AppListAdapter(SelectAppActivity.this, R.layout.tb_row_blacklist, entries, U.HIDDEN),
                    new AppListAdapter(SelectAppActivity.this, R.layout.tb_row_blacklist, entries, U.TOP_APPS)
            };
        }

        @Override
        protected void onPostExecute(AppListAdapter[] adapters) {
            hiddenAdapter = adapters[U.HIDDEN];
            topAppsAdapter = adapters[U.TOP_APPS];

            SelectAppPagerAdapter pagerAdapter = new SelectAppPagerAdapter(getSupportFragmentManager());
            ViewPager viewPager = findViewById(R.id.pager);
            viewPager.setAdapter(pagerAdapter);

            FrameLayout container = findViewById(R.id.inflate_tabs_here);
            View tabLayout;

            if(getPackageName().equals(BuildConfig.ANDROIDX86_APPLICATION_ID)) {
                tabLayout = getLayoutInflater().inflate(R.layout.tb_tab_layout, container, false);
                tabLayout.findViewById(R.id.hidden).setOnClickListener(v -> viewPager.setCurrentItem(U.HIDDEN));
                tabLayout.findViewById(R.id.top_apps).setOnClickListener(v -> viewPager.setCurrentItem(U.TOP_APPS));
            } else {
                tabLayout = new TabLayout(SelectAppActivity.this);
                ((TabLayout) tabLayout).setupWithViewPager(viewPager);
            }

            container.addView(tabLayout);

            findViewById(R.id.configure_start_menu_layout).setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
            setFinishOnTouchOutside(true);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Generated by generate-clone-reducer.js

const Shift = require('shift-ast');

module.exports = class CloneReducer {
  reduceArrayAssignmentTarget(node, { elements, rest }) {
    return new Shift.ArrayAssignmentTarget({ elements, rest });
  }

  reduceArrayBinding(node, { elements, rest }) {
    return new Shift.ArrayBinding({ elements, rest });
  }

  reduceArrayExpression(node, { elements }) {
    return new Shift.ArrayExpression({ elements });
  }

  reduceArrowExpression(node, { params, body }) {
    return new Shift.ArrowExpression({ isAsync: node.isAsync, params, body });
  }

  reduceAssignmentExpression(node, { binding, expression }) {
    return new Shift.AssignmentExpression({ binding, expression });
  }

  reduceAssignmentTargetIdentifier(node) {
    return new Shift.AssignmentTargetIdentifier({ name: node.name });
  }

  reduceAssignmentTargetPropertyIdentifier(node, { binding, init }) {
    return new Shift.AssignmentTargetPropertyIdentifier({ binding, init });
  }

  reduceAssignmentTargetPropertyProperty(node, { name, binding }) {
    return new Shift.AssignmentTargetPropertyProperty({ name, binding });
  }

  reduceAssignmentTargetWithDefault(node, { binding, init }) {
    return new Shift.AssignmentTargetWithDefault({ binding, init });
  }

  reduceAwaitExpression(node, { expression }) {
    return new Shift.AwaitExpression({ expression });
  }

  reduceBinaryExpression(node, { left, right }) {
    return new Shift.BinaryExpression({ left, operator: node.operator, right });
  }

  reduceBindingIdentifier(node) {
    return new Shift.BindingIdentifier({ name: node.name });
  }

  reduceBindingPropertyIdentifier(node, { binding, init }) {
    return new Shift.BindingPropertyIdentifier({ binding, init });
  }

  reduceBindingPropertyProperty(node, { name, binding }) {
    return new Shift.BindingPropertyProperty({ name, binding });
  }

  reduceBindingWithDefault(node, { binding, init }) {
    return new Shift.BindingWithDefault({ binding, init });
  }

  reduceBlock(node, { statements }) {
    return new Shift.Block({ statements });
  }

  reduceBlockStatement(node, { block }) {
    return new Shift.BlockStatement({ block });
  }

  reduceBreakStatement(node) {
    return new Shift.BreakStatement({ label: node.label });
  }

  reduceCallExpression(node, { callee, arguments: _arguments }) {
    return new Shift.CallExpression({ callee, arguments: _arguments });
  }

  reduceCatchClause(node, { binding, body }) {
    return new Shift.CatchClause({ binding, body });
  }

  reduceClassDeclaration(node, { name, super: _super, elements }) {
    return new Shift.ClassDeclaration({ name, super: _super, elements });
  }

  reduceClassElement(node, { method }) {
    return new Shift.ClassElement({ isStatic: node.isStatic, method });
  }

  reduceClassExpression(node, { name, super: _super, elements }) {
    return new Shift.ClassExpression({ name, super: _super, elements });
  }

  reduceCompoundAssignmentExpression(node, { binding, expression }) {
    return new Shift.CompoundAssignmentExpression({ binding, operator: node.operator, expression });
  }

  reduceComputedMemberAssignmentTarget(node, { object, expression }) {
    return new Shift.ComputedMemberAssignmentTarget({ object, expression });
  }

  reduceComputedMemberExpression(node, { object, expression }) {
    return new Shift.ComputedMemberExpression({ object, expression });
  }

  reduceComputedPropertyName(node, { expression }) {
    return new Shift.ComputedPropertyName({ expression });
  }

  reduceConditionalExpression(node, { test, consequent, alternate }) {
    return new Shift.ConditionalExpression({ test, consequent, alternate });
  }

  reduceContinueStatement(node) {
    return new Shift.ContinueStatement({ label: node.label });
  }

  reduceDataProperty(node, { name, expression }) {
    return new Shift.DataProperty({ name, expression });
  }

  reduceDebuggerStatement(node) {
    return new Shift.DebuggerStatement;
  }

  reduceDirective(node) {
    return new Shift.Directive({ rawValue: node.rawValue });
  }

  reduceDoWhileStatement(node, { body, test }) {
    return new Shift.DoWhileStatement({ body, test });
  }

  reduceEmptyStatement(node) {
    return new Shift.EmptyStatement;
  }

  reduceExport(node, { declaration }) {
    return new Shift.Export({ declaration });
  }

  reduceExportAllFrom(node) {
    return new Shift.ExportAllFrom({ moduleSpecifier: node.moduleSpecifier });
  }

  reduceExportDefault(node, { body }) {
    return new Shift.ExportDefault({ body });
  }

  reduceExportFrom(node, { namedExports }) {
    return new Shift.ExportFrom({ namedExports, moduleSpecifier: node.moduleSpecifier });
  }

  reduceExportFromSpecifier(node) {
    return new Shift.ExportFromSpecifier({ name: node.name, exportedName: node.exportedName });
  }

  reduceExportLocalSpecifier(node, { name }) {
    return new Shift.ExportLocalSpecifier({ name, exportedName: node.exportedName });
  }

  reduceExportLocals(node, { namedExports }) {
    return new Shift.ExportLocals({ namedExports });
  }

  reduceExpressionStatement(node, { expression }) {
    return new Shift.ExpressionStatement({ expression });
  }

  reduceForAwaitStatement(node, { left, right, body }) {
    return new Shift.ForAwaitStatement({ left, right, body });
  }

  reduceForInStatement(node, { left, right, body }) {
    return new Shift.ForInStatement({ left, right, body });
  }

  reduceForOfStatement(node, { left, right, body }) {
    return new Shift.ForOfStatement({ left, right, body });
  }

  reduceForStatement(node, { init, test, update, body }) {
    return new Shift.ForStatement({ init, test, update, body });
  }

  reduceFormalParameters(node, { items, rest }) {
    return new Shift.FormalParameters({ items, rest });
  }

  reduceFunctionBody(node, { directives, statements }) {
    return new Shift.FunctionBody({ directives, statements });
  }

  reduceFunctionDeclaration(node, { name, params, body }) {
    return new Shift.FunctionDeclaration({ isAsync: node.isAsync, isGenerator: node.isGenerator, name, params, body });
  }

  reduceFunctionExpression(node, { name, params, body }) {
    return new Shift.FunctionExpression({ isAsync: node.isAsync, isGenerator: node.isGenerator, name, params, body });
  }

  reduceGetter(node, { name, body }) {
    return new Shift.Getter({ name, body });
  }

  reduceIdentifierExpression(node) {
    return new Shift.IdentifierExpression({ name: node.name });
  }

  reduceIfStatement(node, { test, consequent, alternate }) {
    return new Shift.IfStatement({ test, consequent, alternate });
  }

  reduceImport(node, { defaultBinding, namedImports }) {
    return new Shift.Import({ defaultBinding, namedImports, moduleSpecifier: node.moduleSpecifier });
  }

  reduceImportNamespace(node, { defaultBinding, namespaceBinding }) {
    return new Shift.ImportNamespace({ defaultBinding, namespaceBinding, moduleSpecifier: node.moduleSpecifier });
  }

  reduceImportSpecifier(node, { binding }) {
    return new Shift.ImportSpecifier({ name: node.name, binding });
  }

  reduceLabeledStatement(node, { body }) {
    return new Shift.LabeledStatement({ label: node.label, body });
  }

  reduceLiteralBooleanExpression(node) {
    return new Shift.LiteralBooleanExpression({ value: node.value });
  }

  reduceLiteralInfinityExpression(node) {
    return new Shift.LiteralInfinityExpression;
  }

  reduceLiteralNullExpression(node) {
    return new Shift.LiteralNullExpression;
  }

  reduceLiteralNumericExpression(node) {
    return new Shift.LiteralNumericExpression({ value: node.value });
  }

  reduceLiteralRegExpExpression(node) {
    return new Shift.LiteralRegExpExpression({ pattern: node.pattern, global: node.global, ignoreCase: node.ignoreCase, multiLine: node.multiLine, dotAll: node.dotAll, unicode: node.unicode, sticky: node.sticky });
  }

  reduceLiteralStringExpression(node) {
    return new Shift.LiteralStringExpression({ value: node.value });
  }

  reduceMethod(node, { name, params, body }) {
    return new Shift.Method({ isAsync: node.isAsync, isGenerator: node.isGenerator, name, params, body });
  }

  reduceModule(node, { directives, items }) {
    return new Shift.Module({ directives, items });
  }

  reduceNewExpression(node, { callee, arguments: _arguments }) {
    return new Shift.NewExpression({ callee, arguments: _arguments });
  }

  reduceNewTargetExpression(node) {
    return new Shift.NewTargetExpression;
  }

  reduceObjectAssignmentTarget(node, { properties, rest }) {
    return new Shift.ObjectAssignmentTarget({ properties, rest });
  }

  reduceObjectBinding(node, { properties, rest }) {
    return new Shift.ObjectBinding({ properties, rest });
  }

  reduceObjectExpression(node, { properties }) {
    return new Shift.ObjectExpression({ properties });
  }

  reduceReturnStatement(node, { expression }) {
    return new Shift.ReturnStatement({ expression });
  }

  reduceScript(node, { directives, statements }) {
    return new Shift.Script({ directives, statements });
  }

  reduceSetter(node, { name, param, body }) {
    return new Shift.Setter({ name, param, body });
  }

  reduceShorthandProperty(node, { name }) {
    return new Shift.ShorthandProperty({ name });
  }

  reduceSpreadElement(node, { expression }) {
    return new Shift.SpreadElement({ expression });
  }

  reduceSpreadProperty(node, { expression }) {
    return new Shift.SpreadProperty({ expression });
  }

  reduceStaticMemberAssignmentTarget(node, { object }) {
    return new Shift.StaticMemberAssignmentTarget({ object, property: node.property });
  }

  reduceStaticMemberExpression(node, { object }) {
    return new Shift.StaticMemberExpression({ object, property: node.property });
  }

  reduceStaticPropertyName(node) {
    return new Shift.StaticPropertyName({ value: node.value });
  }

  reduceSuper(node) {
    return new Shift.Super;
  }

  reduceSwitchCase(node, { test, consequent }) {
    return new Shift.SwitchCase({ test, consequent });
  }

  reduceSwitchDefault(node, { consequent }) {
    return new Shift.SwitchDefault({ consequent });
  }

  reduceSwitchStatement(node, { discriminant, cases }) {
    return new Shift.SwitchStatement({ discriminant, cases });
  }

  reduceSwitchStatementWithDefault(node, { discriminant, preDefaultCases, defaultCase, postDefaultCases }) {
    return new Shift.SwitchStatementWithDefault({ discriminant, preDefaultCases, defaultCase, postDefaultCases });
  }

  reduceTemplateElement(node) {
    return new Shift.TemplateElement({ rawValue: node.rawValue });
  }

  reduceTemplateExpression(node, { tag, elements }) {
    return new Shift.TemplateExpression({ tag, elements });
  }

  reduceThisExpression(node) {
    return new Shift.ThisExpression;
  }

  reduceThrowStatement(node, { expression }) {
    return new Shift.ThrowStatement({ expression });
  }

  reduceTryCatchStatement(node, { body, catchClause }) {
    return new Shift.TryCatchStatement({ body, catchClause });
  }

  reduceTryFinallyStatement(node, { body, catchClause, finalizer }) {
    return new Shift.TryFinallyStatement({ body, catchClause, finalizer });
  }

  reduceUnaryExpression(node, { operand }) {
    return new Shift.UnaryExpression({ operator: node.operator, operand });
  }

  reduceUpdateExpression(node, { operand }) {
    return new Shift.UpdateExpression({ isPrefix: node.isPrefix, operator: node.operator, operand });
  }

  reduceVariableDeclaration(node, { declarators }) {
    return new Shift.VariableDeclaration({ kind: node.kind, declarators });
  }

  reduceVariableDeclarationStatement(node, { declaration }) {
    return new Shift.VariableDeclarationStatement({ declaration });
  }

  reduceVariableDeclarator(node, { binding, init }) {
    return new Shift.VariableDeclarator({ binding, init });
  }

  reduceWhileStatement(node, { test, body }) {
    return new Shift.WhileStatement({ test, body });
  }

  reduceWithStatement(node, { object, body }) {
    return new Shift.WithStatement({ object, body });
  }

  reduceYieldExpression(node, { expression }) {
    return new Shift.YieldExpression({ expression });
  }

  reduceYieldGeneratorExpression(node, { expression }) {
    return new Shift.YieldGeneratorExpression({ expression });
  }
};


text:
`git-count` is a git-subcommand that counts the number of lines of code that each author wrote.

## Installation

```sh
git clone https://github.com/neethouse/git-count.git
cd git-count
cp git-count <path/to/bin>
# "<path/to/bin>" is directory that included "$PATH".
```

### Use homebrew

```sh
brew tap neethouse/neet
brew install git-count
```

## How to use

### 1. Execute following command.

```sh
#only Objective-C files.
git count . "\.[hm]$"

# . is directory.
# "\.[hm]$" is egrep regex.
```
### 2. You'll get a nice siesta time.

( ˘ω˘ ) スヤァ…

### 3. You can get the rankings.

```
899 files found.

mironal       34019
mtmta         28792
ryohey        3963
YanaC         2116

Total 68890
```

### 4. 晒しあげ (☝◞‸◟)☝

## Help

```
usage: git count [--ltsv] [--csv] [--parallel] <path> [<regex>]

CAUTION !!

Is very time consuming, if the repository is large.

OPTIONS

    <path>
        Attempt to counts the file hierarchy rooted in each file.

        e.g.
            Following the "src" directory.   -> git count "path/to/src"
            Following the "test" directory.  -> git count "path/to/test"
            Following the current directory. -> git count "."

    <regex>
        If you specify this regex pattern.
        You can count lines that files that match the regular expression.
        This regex pattern is the egrep regex pattern.

        e.g.
            Following the "src" directory.   -> git count "path/to/src"
            Only Java source code.  -> git count "." "\.java$"
            Only Scala source code. -> git count "." "\.scala$"
            Only Objective-C code.  -> git count "." "\.[hm]$"

        Or

        You can use default regex from git-config.

        git config --local git-count.regex "your regex pattern"
        git config --global git-count.regex "your regex pattern"

        Commandline argument takes precedence.

    --ltsv
        Output LTSV format.
        The standard formatis usedif you do not specify.

        e.g.
            @username0:count0<TAB>@username1:count1<TAB>@username2:count2<TAB>total:total-count<TAB>files:file-count

    --csv
        Output CSV format.
        The standard formatis usedif you do not specify.

        e.g.
            @username0,10
            @usernamet,22
            @username2,30
            total,62
            files,3

    --parallel
        Run in parallel xargs(-P 4). default is no parallel.

For more information -> "https://github.com/neethouse/git-count"
version : ${VERSION}
```

## Tips

### Use default regex pattern

You can use default regex from git-config.

`git config --local git-count.regex "your regex pattern"`

or

`git config --global git-count.regex "your regex pattern"`

Commandline argument takes precedence.

### LTSV format

```sh
git count --ltsv .
```

```
mironal:37002   mtmta:36458     ryohey:3627     YanaC:2034      total:79121     files:986
```

### CSV format

```sh
git count --csv .
```

```
mironal,37002
mtmta,36458
ryohey,3627
YanaC,2034
total,79121
files,986
```


text:
#!/usr/bin/php
<?php
include 'lib/sunny.php';
include 'crawlers/mp3skull.php';

$site = 'http://mp3skull.com/';
$table = 'mp3skull';

$append = false;
$threads = 10;
$limit = 100;

$ignore = array(
			'4shared\.com',
			'preview',
		);

/* create a new sunny crawler */
$sunny = new Mp3skull($site, $db);

/* append_queue autostarts crawl on init / autoqueues link on crawl */
	$sunny->append_queue($append);

/* set of patterns to ignore in the found url */
	$sunny->ignore_url_pattern($ignore);

/* uncomment this section to create a new table */
	$sunny->init($table, $threads, $limit);

/* uncomment this section to start the crawler */
	// $sunny->crawl($table, $threads, $limit);
	$sunny->crawl_all($table, $threads, $limit);

?>


text:
class YouTrack::Client::GetProjects < YouTrack::Client::Request

  def self.attributes
    @_attributes ||= %w[name shortName isImporting subsystems assignees versions]
  end

  def real
    service.request(
      :path   => "/project/all",
      :parser => YouTrack::Parser::ProjectsParser,
      :query  => {"verbose" => true},
    )
  end

  def mock
    service.response(
      :body => service.data[:projects].values.map { |p| Cistern::Hash.slice(p, *self.class.attributes) }
    )
  end
end


text:
module ShouldCompile where

newtype Pair1 f g a = Pair1 {unPair1 :: (f a, g a)}
  deriving (Eq, Ord, Show)


text:
#ifndef _MODBUS_PRIVATE_H_
#define _MODBUS_PRIVATE_H_

#ifndef _MSC_VER
# include <stdint.h>
# include <sys/time.h>
#else
# include "stdint.h"
# include <time.h>
typedef int ssize_t;
#endif
#include <sys/types.h>
#include <config.h>

#include "modbus.h"

MODBUS_BEGIN_DECLS

/* It's not really the minimal length (the real one is report slave ID
 * in RTU (4 bytes)) but it's a convenient size to use in RTU or TCP
 * communications to read many values or write a single one.
 * Maximum between :
 * - HEADER_LENGTH_TCP (7) + function (1) + address (2) + number (2)
 * - HEADER_LENGTH_RTU (1) + function (1) + address (2) + number (2) + CRC (2)
 */
#define _MIN_REQ_LENGTH 12

#define _REPORT_SLAVE_ID 180

#define _MODBUS_EXCEPTION_RSP_LENGTH 5

/* Timeouts in microsecond (0.5 s) */
#define _RESPONSE_TIMEOUT    500000
#define _BYTE_TIMEOUT        500000

/* Function codes */
#define _FC_READ_COILS                0x01
#define _FC_READ_DISCRETE_INPUTS      0x02
#define _FC_READ_HOLDING_REGISTERS    0x03
#define _FC_READ_INPUT_REGISTERS      0x04
#define _FC_WRITE_SINGLE_COIL         0x05
#define _FC_WRITE_SINGLE_REGISTER     0x06
#define _FC_READ_EXCEPTION_STATUS     0x07
#define _FC_WRITE_MULTIPLE_COILS      0x0F
#define _FC_WRITE_MULTIPLE_REGISTERS  0x10
#define _FC_REPORT_SLAVE_ID           0x11
#define _FC_WRITE_AND_READ_REGISTERS  0x17

typedef enum {
    _MODBUS_BACKEND_TYPE_RTU=0,
    _MODBUS_BACKEND_TYPE_TCP
} modbus_bakend_type_t;

/* This structure reduces the number of params in functions and so
 * optimizes the speed of execution (~ 37%). */
typedef struct _sft {
    int slave;
    int function;
    int t_id;
} sft_t;

typedef struct _modbus_backend {
    unsigned int backend_type;
    unsigned int header_length;
    unsigned int checksum_length;
    unsigned int max_adu_length;
    int (*set_slave) (modbus_t *ctx, int slave);
    int (*build_request_basis) (modbus_t *ctx, int function, int addr,
                                int nb, uint8_t *req);
    int (*build_response_basis) (sft_t *sft, uint8_t *rsp);
    int (*prepare_response_tid) (const uint8_t *req, int *req_length);
    int (*send_msg_pre) (uint8_t *req, int req_length);
    ssize_t (*send) (modbus_t *ctx, const uint8_t *req, int req_length);
    ssize_t (*recv) (modbus_t *ctx, uint8_t *rsp, int rsp_length);
    int (*check_integrity) (modbus_t *ctx, uint8_t *msg,
                            const int msg_length);
    int (*pre_check_confirmation) (modbus_t *ctx, const uint8_t *req,
                                   const uint8_t *rsp, int rsp_length);
    int (*connect) (modbus_t *ctx);
    void (*close) (modbus_t *ctx);
    int (*flush) (modbus_t *ctx);
    int (*select) (modbus_t *ctx, fd_set *rfds, struct timeval *tv, int msg_length);
    int (*filter_request) (modbus_t *ctx, int slave);
} modbus_backend_t;

struct _modbus {
    /* Slave address */
    int slave;
    /* Socket or file descriptor */
    int s;
    int debug;
    int error_recovery;
    struct timeval response_timeout;
    struct timeval byte_timeout;
    const modbus_backend_t *backend;
    void *backend_data;
};

void _modbus_init_common(modbus_t *ctx);
void _error_print(modbus_t *ctx, const char *context);

#ifndef HAVE_STRLCPY
size_t strlcpy(char *dest, const char *src, size_t dest_size);
#endif

MODBUS_END_DECLS

#endif  /* _MODBUS_PRIVATE_H_ */


text:
/*
 * File...........: linux/drivers/s390/block/dasd_ioctl.c
 * Author(s)......: Holger Smolinski <Holger.Smolinski@de.ibm.com>
 *		    Horst Hummel <Horst.Hummel@de.ibm.com>
 *		    Carsten Otte <Cotte@de.ibm.com>
 *		    Martin Schwidefsky <schwidefsky@de.ibm.com>
 * Bugreports.to..: <Linux390@de.ibm.com>
 * (C) IBM Corporation, IBM Deutschland Entwicklung GmbH, 1999-2001
 *
 * i/o controls for the dasd driver.
 */
#include <linux/config.h>
#include <linux/interrupt.h>
#include <linux/major.h>
#include <linux/fs.h>
#include <linux/blkpg.h>

#include <asm/ccwdev.h>
#include <asm/uaccess.h>

/* This is ugly... */
#define PRINTK_HEADER "dasd_ioctl:"

#include "dasd_int.h"

/*
 * SECTION: ioctl functions.
 */
static struct list_head dasd_ioctl_list = LIST_HEAD_INIT(dasd_ioctl_list);

/*
 * Find the ioctl with number no.
 */
static struct dasd_ioctl *
dasd_find_ioctl(int no)
{
	struct dasd_ioctl *ioctl;

	list_for_each_entry (ioctl, &dasd_ioctl_list, list)
		if (ioctl->no == no)
			return ioctl;
	return NULL;
}

/*
 * Register ioctl with number no.
 */
int
dasd_ioctl_no_register(struct module *owner, int no, dasd_ioctl_fn_t handler)
{
	struct dasd_ioctl *new;
	if (dasd_find_ioctl(no))
		return -EBUSY;
	new = kmalloc(sizeof (struct dasd_ioctl), GFP_KERNEL);
	if (new == NULL)
		return -ENOMEM;
	new->owner = owner;
	new->no = no;
	new->handler = handler;
	list_add(&new->list, &dasd_ioctl_list);
	return 0;
}

/*
 * Deregister ioctl with number no.
 */
int
dasd_ioctl_no_unregister(struct module *owner, int no, dasd_ioctl_fn_t handler)
{
	struct dasd_ioctl *old = dasd_find_ioctl(no);
	if (old == NULL)
		return -ENOENT;
	if (old->no != no || old->handler != handler || owner != old->owner)
		return -EINVAL;
	list_del(&old->list);
	kfree(old);
	return 0;
}

int
dasd_ioctl(struct inode *inp, struct file *filp,
	   unsigned int no, unsigned long data)
{
	struct block_device *bdev = inp->i_bdev;
	struct dasd_device *device = bdev->bd_disk->private_data;
	struct dasd_ioctl *ioctl;
	const char *dir;
	int rc;

	if ((_IOC_DIR(no) != _IOC_NONE) && (data == 0)) {
		PRINT_DEBUG("empty data ptr");
		return -EINVAL;
	}
	dir = _IOC_DIR (no) == _IOC_NONE ? "0" :
		_IOC_DIR (no) == _IOC_READ ? "r" :
		_IOC_DIR (no) == _IOC_WRITE ? "w" :
		_IOC_DIR (no) == (_IOC_READ | _IOC_WRITE) ? "rw" : "u";
	DBF_DEV_EVENT(DBF_DEBUG, device,
		      "ioctl 0x%08x %s'0x%x'%d(%d) with data %8lx", no,
		      dir, _IOC_TYPE(no), _IOC_NR(no), _IOC_SIZE(no), data);
	/* Search for ioctl no in the ioctl list. */
	list_for_each_entry(ioctl, &dasd_ioctl_list, list) {
		if (ioctl->no == no) {
			/* Found a matching ioctl. Call it. */
			if (!try_module_get(ioctl->owner))
				continue;
			rc = ioctl->handler(bdev, no, data);
			module_put(ioctl->owner);
			return rc;
		}
	}
	/* No ioctl with number no. */
	DBF_DEV_EVENT(DBF_INFO, device,
		      "unknown ioctl 0x%08x=%s'0x%x'%d(%d) data %8lx", no,
		      dir, _IOC_TYPE(no), _IOC_NR(no), _IOC_SIZE(no), data);
	return -EINVAL;
}

long
dasd_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	int rval;

	lock_kernel();
	rval = dasd_ioctl(filp->f_dentry->d_inode, filp, cmd, arg);
	unlock_kernel();

	return (rval == -EINVAL) ? -ENOIOCTLCMD : rval;
}

static int
dasd_ioctl_api_version(struct block_device *bdev, int no, long args)
{
	int ver = DASD_API_VERSION;
	return put_user(ver, (int __user *) args);
}

/*
 * Enable device.
 * used by dasdfmt after BIODASDDISABLE to retrigger blocksize detection
 */
static int
dasd_ioctl_enable(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;

	if (!capable(CAP_SYS_ADMIN))
		return -EACCES;
	device = bdev->bd_disk->private_data;
	if (device == NULL)
		return -ENODEV;
	dasd_enable_device(device);
	/* Formatting the dasd device can change the capacity. */
	down(&bdev->bd_sem);
	i_size_write(bdev->bd_inode, (loff_t)get_capacity(device->gdp) << 9);
	up(&bdev->bd_sem);
	return 0;
}

/*
 * Disable device.
 * Used by dasdfmt. Disable I/O operations but allow ioctls.
 */
static int
dasd_ioctl_disable(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;

	if (!capable(CAP_SYS_ADMIN))
		return -EACCES;
	device = bdev->bd_disk->private_data;
	if (device == NULL)
		return -ENODEV;
	/*
	 * Man this is sick. We don't do a real disable but only downgrade
	 * the device to DASD_STATE_BASIC. The reason is that dasdfmt uses
	 * BIODASDDISABLE to disable accesses to the device via the block
	 * device layer but it still wants to do i/o on the device by
	 * using the BIODASDFMT ioctl. Therefore the correct state for the
	 * device is DASD_STATE_BASIC that allows to do basic i/o.
	 */
	dasd_set_target_state(device, DASD_STATE_BASIC);
	/*
	 * Set i_size to zero, since read, write, etc. check against this
	 * value.
	 */
	down(&bdev->bd_sem);
	i_size_write(bdev->bd_inode, 0);
	up(&bdev->bd_sem);
	return 0;
}

/*
 * Quiesce device.
 */
static int
dasd_ioctl_quiesce(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;
	unsigned long flags;

	if (!capable (CAP_SYS_ADMIN))
		return -EACCES;

	device = bdev->bd_disk->private_data;
	if (device == NULL)
		return -ENODEV;

	DEV_MESSAGE (KERN_DEBUG, device, "%s",
		     "Quiesce IO on device");
	spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
	device->stopped |= DASD_STOPPED_QUIESCE;
	spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
	return 0;
}

/*
 * Quiesce device.
 */
static int
dasd_ioctl_resume(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;
	unsigned long flags;

	if (!capable (CAP_SYS_ADMIN))
		return -EACCES;

	device = bdev->bd_disk->private_data;
	if (device == NULL)
		return -ENODEV;

	DEV_MESSAGE (KERN_DEBUG, device, "%s",
		     "resume IO on device");

	spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
	device->stopped &= ~DASD_STOPPED_QUIESCE;
	spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);

	dasd_schedule_bh (device);
	return 0;
}

/*
 * performs formatting of _device_ according to _fdata_
 * Note: The discipline's format_function is assumed to deliver formatting
 * commands to format a single unit of the device. In terms of the ECKD
 * devices this means CCWs are generated to format a single track.
 */
static int
dasd_format(struct dasd_device * device, struct format_data_t * fdata)
{
	struct dasd_ccw_req *cqr;
	int rc;

	if (device->discipline->format_device == NULL)
		return -EPERM;

	if (device->state != DASD_STATE_BASIC) {
		DEV_MESSAGE(KERN_WARNING, device, "%s",
			    "dasd_format: device is not disabled! ");
		return -EBUSY;
	}

	DBF_DEV_EVENT(DBF_NOTICE, device,
		      "formatting units %d to %d (%d B blocks) flags %d",
		      fdata->start_unit,
		      fdata->stop_unit, fdata->blksize, fdata->intensity);

	/* Since dasdfmt keeps the device open after it was disabled,
	 * there still exists an inode for this device.
	 * We must update i_blkbits, otherwise we might get errors when
	 * enabling the device later.
	 */
	if (fdata->start_unit == 0) {
		struct block_device *bdev = bdget_disk(device->gdp, 0);
		bdev->bd_inode->i_blkbits = blksize_bits(fdata->blksize);
		bdput(bdev);
	}

	while (fdata->start_unit <= fdata->stop_unit) {
		cqr = device->discipline->format_device(device, fdata);
		if (IS_ERR(cqr))
			return PTR_ERR(cqr);
		rc = dasd_sleep_on_interruptible(cqr);
		dasd_sfree_request(cqr, cqr->device);
		if (rc) {
			if (rc != -ERESTARTSYS)
				DEV_MESSAGE(KERN_ERR, device,
					    " Formatting of unit %d failed "
					    "with rc = %d",
					    fdata->start_unit, rc);
			return rc;
		}
		fdata->start_unit++;
	}
	return 0;
}

/*
 * Format device.
 */
static int
dasd_ioctl_format(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;
	struct format_data_t fdata;

	if (!capable(CAP_SYS_ADMIN))
		return -EACCES;
	if (!args)
		return -EINVAL;
	/* fdata == NULL is no longer a valid arg to dasd_format ! */
	device = bdev->bd_disk->private_data;

	if (device == NULL)
		return -ENODEV;

	if (device->features & DASD_FEATURE_READONLY)
		return -EROFS;
	if (copy_from_user(&fdata, (void __user *) args,
			   sizeof (struct format_data_t)))
		return -EFAULT;
	if (bdev != bdev->bd_contains) {
		DEV_MESSAGE(KERN_WARNING, device, "%s",
			    "Cannot low-level format a partition");
		return -EINVAL;
	}
	return dasd_format(device, &fdata);
}

#ifdef CONFIG_DASD_PROFILE
/*
 * Reset device profile information
 */
static int
dasd_ioctl_reset_profile(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;

	if (!capable(CAP_SYS_ADMIN))
		return -EACCES;

	device = bdev->bd_disk->private_data;
	if (device == NULL)
		return -ENODEV;

	memset(&device->profile, 0, sizeof (struct dasd_profile_info_t));
	return 0;
}

/*
 * Return device profile information
 */
static int
dasd_ioctl_read_profile(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;

	device = bdev->bd_disk->private_data;
	if (device == NULL)
		return -ENODEV;

	if (dasd_profile_level == DASD_PROFILE_OFF)
		return -EIO;

	if (copy_to_user((long __user *) args, (long *) &device->profile,
			 sizeof (struct dasd_profile_info_t)))
		return -EFAULT;
	return 0;
}
#else
static int
dasd_ioctl_reset_profile(struct block_device *bdev, int no, long args)
{
	return -ENOSYS;
}

static int
dasd_ioctl_read_profile(struct block_device *bdev, int no, long args)
{
	return -ENOSYS;
}
#endif

/*
 * Return dasd information. Used for BIODASDINFO and BIODASDINFO2.
 */
static int
dasd_ioctl_information(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;
	struct dasd_information2_t *dasd_info;
	unsigned long flags;
	int rc;
	struct ccw_device *cdev;

	device = bdev->bd_disk->private_data;
	if (device == NULL)
		return -ENODEV;

	if (!device->discipline->fill_info)
		return -EINVAL;

	dasd_info = kmalloc(sizeof(struct dasd_information2_t), GFP_KERNEL);
	if (dasd_info == NULL)
		return -ENOMEM;

	rc = device->discipline->fill_info(device, dasd_info);
	if (rc) {
		kfree(dasd_info);
		return rc;
	}

	cdev = device->cdev;

	dasd_info->devno = _ccw_device_get_device_number(device->cdev);
	dasd_info->schid = _ccw_device_get_subchannel_number(device->cdev);
	dasd_info->cu_type = cdev->id.cu_type;
	dasd_info->cu_model = cdev->id.cu_model;
	dasd_info->dev_type = cdev->id.dev_type;
	dasd_info->dev_model = cdev->id.dev_model;
	dasd_info->status = device->state;
	/*
	 * The open_count is increased for every opener, that includes
	 * the blkdev_get in dasd_scan_partitions.
	 * This must be hidden from user-space.
	 */
	dasd_info->open_count = atomic_read(&device->open_count);
	if (!device->bdev)
		dasd_info->open_count++;

	/*
	 * check if device is really formatted
	 * LDL / CDL was returned by 'fill_info'
	 */
	if ((device->state < DASD_STATE_READY) ||
	    (dasd_check_blocksize(device->bp_block)))
		dasd_info->format = DASD_FORMAT_NONE;

	dasd_info->features |=
		((device->features & DASD_FEATURE_READONLY) != 0);

	if (device->discipline)
		memcpy(dasd_info->type, device->discipline->name, 4);
	else
		memcpy(dasd_info->type, "none", 4);
	dasd_info->req_queue_len = 0;
	dasd_info->chanq_len = 0;
	if (device->request_queue->request_fn) {
		struct list_head *l;
#ifdef DASD_EXTENDED_PROFILING
		{
			struct list_head *l;
			spin_lock_irqsave(&device->lock, flags);
			list_for_each(l, &device->request_queue->queue_head)
				dasd_info->req_queue_len++;
			spin_unlock_irqrestore(&device->lock, flags);
		}
#endif				/* DASD_EXTENDED_PROFILING */
		spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
		list_for_each(l, &device->ccw_queue)
			dasd_info->chanq_len++;
		spin_unlock_irqrestore(get_ccwdev_lock(device->cdev),
				       flags);
	}

	rc = 0;
	if (copy_to_user((long __user *) args, (long *) dasd_info,
			 ((no == (unsigned int) BIODASDINFO2) ?
			  sizeof (struct dasd_information2_t) :
			  sizeof (struct dasd_information_t))))
		rc = -EFAULT;
	kfree(dasd_info);
	return rc;
}

/*
 * Set read only
 */
static int
dasd_ioctl_set_ro(struct block_device *bdev, int no, long args)
{
	struct dasd_device *device;
	int intval, rc;

	if (!capable(CAP_SYS_ADMIN))
		return -EACCES;
	if (bdev != bdev->bd_contains)
		// ro setting is not allowed for partitions
		return -EINVAL;
	if (get_user(intval, (int __user *) args))
		return -EFAULT;
	device =  bdev->bd_disk->private_data;
	if (device == NULL)
		return -ENODEV;

	set_disk_ro(bdev->bd_disk, intval);
	rc = dasd_set_feature(device->cdev, DASD_FEATURE_READONLY, intval);

	return rc;
}

/*
 * List of static ioctls.
 */
static struct { int no; dasd_ioctl_fn_t fn; } dasd_ioctls[] =
{
	{ BIODASDDISABLE, dasd_ioctl_disable },
	{ BIODASDENABLE, dasd_ioctl_enable },
	{ BIODASDQUIESCE, dasd_ioctl_quiesce },
	{ BIODASDRESUME, dasd_ioctl_resume },
	{ BIODASDFMT, dasd_ioctl_format },
	{ BIODASDINFO, dasd_ioctl_information },
	{ BIODASDINFO2, dasd_ioctl_information },
	{ BIODASDPRRD, dasd_ioctl_read_profile },
	{ BIODASDPRRST, dasd_ioctl_reset_profile },
	{ BLKROSET, dasd_ioctl_set_ro },
	{ DASDAPIVER, dasd_ioctl_api_version },
	{ -1, NULL }
};

int
dasd_ioctl_init(void)
{
	int i;

	for (i = 0; dasd_ioctls[i].no != -1; i++)
		dasd_ioctl_no_register(NULL, dasd_ioctls[i].no,
				       dasd_ioctls[i].fn);
	return 0;

}

void
dasd_ioctl_exit(void)
{
	int i;

	for (i = 0; dasd_ioctls[i].no != -1; i++)
		dasd_ioctl_no_unregister(NULL, dasd_ioctls[i].no,
					 dasd_ioctls[i].fn);

}

EXPORT_SYMBOL(dasd_ioctl_no_register);
EXPORT_SYMBOL(dasd_ioctl_no_unregister);


text:
package main

import (
	"log"

	"github.com/armon/go-socks5"
)

func startSocksV5(listen string) {
	// Create a SOCKS5 server
	conf := &socks5.Config{}
	server, err := socks5.New(conf)
	if err != nil {
		panic(err)
	}

	log.Printf("start SOCKS5 %s\n", listen)
	// Create SOCKS5 proxy on localhost port 8000
	if err := server.ListenAndServe("tcp", listen); err != nil {
		panic(err)
	}
}


text:
package com.nummulus.amqp.driver

import org.slf4j.LoggerFactory

import com.nummulus.amqp.driver.api.provider.AmqpGuardianActor
import com.nummulus.amqp.driver.configuration.TimeOutConfigurer
import com.nummulus.amqp.driver.configuration.QueueConfigurer
import com.typesafe.config.Config

import _root_.akka.actor.ActorRef
import _root_.akka.actor.ActorSystem
import _root_.akka.actor.Props

/**
 * Default driver implementation.
 *
 * Every driver has a single connection with the broker. The connection is only
 * established if a consumer is created. Every consumer will get a separate
 * channel.
 */
private[driver] class DefaultDriver(connectionFactory: ConnectionFactory, config: Config) extends AmqpDriver
    with QueueConfigurer
    with TimeOutConfigurer {

  private val logger = LoggerFactory.getLogger(getClass)
  private val rootConfig = config.getConfig("amqp")

  private lazy val actorSystem = ActorSystem("AmqpDriver")
  private lazy val connection = createConnection()

  /**
   * Returns an actor which can communicate with the services' operation.
   *
   * @param service name of the service owning the operation to consume
   * @param operation name of the operation to consume
   * @return new consumer
   */
  override def newConsumer(service: String, operation: String): ActorRef = {
    logger.info(s"Retrieving configuration for operation '$operation' on service '$service'")
    val queueConfiguration = getConsumerQueueConfiguration(rootConfig, service, operation)

    val channel = connection.createChannel()
    val timeOut = getConsumerTimeOut(rootConfig, service, operation)
    actorSystem.actorOf(Props(classOf[DefaultConsumer], channel, queueConfiguration, timeOut, IdGenerators.random))
  }

  /**
   * Returns an actor which acts as a liaison for a services' operation.
   *
   * @param operation name of the operation to provide
   * @return new provider
   * @throws QueueConfiguration if the queue has missing keys in the configuration file
   */
  override def newProvider(operation: String): ActorRef = {
    logger.info(s"Retrieving configuration for operation '$operation'")
    val queueConfiguration = getProvideQueuerConfiguration(rootConfig, operation)

    val channel = connection.createChannel()
    actorSystem.actorOf(Props(classOf[AmqpGuardianActor], channel, queueConfiguration, IdGenerators.random), queueConfiguration.queue + "Guardian")
  }

  /**
   * Returns a newly created connection to the broker.
   */
  private def createConnection(): Connection = {
    val host = rootConfig.getString("host")

    logger.info("Connecting to AMQP broker at {}", host)
    connectionFactory.setHost(host)
    connectionFactory.newConnection()
  }

}


text:
/*
 * DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen.
 */
package com.solidfire.element.api;

import com.solidfire.gson.Gson;
import com.solidfire.core.client.Attributes;
import com.solidfire.gson.annotations.SerializedName;
import com.solidfire.core.annotation.Since;
import com.solidfire.core.javautil.Optional;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;

/**
 * ProtectionDomainServiceReplicaBudget
 **/

public class ProtectionDomainServiceReplicaBudget implements Serializable {

    public static final long serialVersionUID = -2296738286233851215L;
    @SerializedName("protectonDomainName") private String protectonDomainName;
    @SerializedName("services") private ServiceReplicaBudget[] services;
    // empty constructor
    @Since("7.0")
    public ProtectionDomainServiceReplicaBudget() {}

    // parameterized constructor
    @Since("7.0")
    public ProtectionDomainServiceReplicaBudget(
        String protectonDomainName,
        ServiceReplicaBudget[] services
    )
    {
        this.protectonDomainName = protectonDomainName;
        this.services = services;
    }

    /**
     * Protecton domain name
     **/
    public String getProtectonDomainName() { return this.protectonDomainName; }

    public void setProtectonDomainName(String protectonDomainName) {
        this.protectonDomainName = protectonDomainName;
    }
    /**
     * Replica bin budget for each block service in this protection domain.
     **/
    public ServiceReplicaBudget[] getServices() { return this.services; }

    public void setServices(ServiceReplicaBudget[] services) {
        this.services = services;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ProtectionDomainServiceReplicaBudget that = (ProtectionDomainServiceReplicaBudget) o;

        return
            Objects.equals(protectonDomainName, that.protectonDomainName) &&
            Arrays.equals(services, that.services);
    }

    @Override
    public int hashCode() {
        return Objects.hash( protectonDomainName,(Object[])services );
    }

    public java.util.Map<String, Object> toMap() {
        java.util.Map<String, Object> map = new HashMap<>();
        map.put("protectonDomainName", protectonDomainName);
        map.put("services", services);
        return map;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        Gson gson = new Gson();
        sb.append( "{ " );

        sb.append(" protectonDomainName : ").append(gson.toJson(protectonDomainName)).append(",");
        sb.append(" services : ").append(gson.toJson(Arrays.toString(services))).append(",");
        sb.append( " }" );

        if(sb.lastIndexOf(", }") != -1)
            sb.deleteCharAt(sb.lastIndexOf(", }"));

        return sb.toString();
    }

    public static Builder builder() {
        return new Builder();
    }

    public final Builder asBuilder() {
        return new Builder().buildFrom(this);
    }

    public static class Builder {
        private String protectonDomainName;
        private ServiceReplicaBudget[] services;

        private Builder() { }

        public ProtectionDomainServiceReplicaBudget build() {
            return new ProtectionDomainServiceReplicaBudget (
                         this.protectonDomainName,
                         this.services);
        }

        private ProtectionDomainServiceReplicaBudget.Builder buildFrom(final ProtectionDomainServiceReplicaBudget req) {
            this.protectonDomainName = req.protectonDomainName;
            this.services = req.services;

            return this;
        }

        public ProtectionDomainServiceReplicaBudget.Builder protectonDomainName(final String protectonDomainName) {
            this.protectonDomainName = protectonDomainName;
            return this;
        }

        public ProtectionDomainServiceReplicaBudget.Builder services(final ServiceReplicaBudget[] services) {
            this.services = services;
            return this;
        }

    }
}


text:
package knot.core.dispatch

import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.atomic.AtomicInteger

import knot.core.emitters.Emitter

import scala.concurrent.ExecutionContextExecutorService

abstract class AbstractDispatcher(implicit val es: ExecutionContextExecutorService) extends Dispatcher {

  protected[this] val attachedCount = new AtomicInteger(0)

  override def executionContext = es

  override def attach(): Unit = addAttachedCount(1)

  override def detach(): Unit = addAttachedCount(-1)

  protected def addAttachedCount(delta: Int): Int = {
    val r = attachedCount.addAndGet(delta)
    if (r < 0) {
      throw new IllegalStateException("can't have less than 0 attached count.")
    }
    r
  }

  override def createListner(emitter: Emitter): Listener = {
    Listener(emitter)
  }

  override def dispatch(receiver: Emitter, msg: Message): Boolean = {
    receiver.listener.enqueue(msg)
    execution(receiver.listener)
  }

  override def dispatch(receiver: Emitter, msg: SystemMessage): Boolean = {
    receiver.listener.systemEnqueue(msg)
    execution(receiver.listener)
  }

  override def execution(listener: Listener): Boolean = {
    if (listener.canBeScheduledForExecution) {
      if (listener.scheduled()) {
        try {
          es.execute(listener)
          true
        } catch {
          case _: RejectedExecutionException =>
            try {
              es.execute(listener)
              true
            } catch {
              case e: RejectedExecutionException =>
                listener.idol()
                throw e
            }
        }
      } else false
    } else false
  }

  override def shutdown(): Unit = es.shutdown()

  override def execute(runnable: Runnable): Unit = es.execute(runnable)
}


text:
package org.elasticsearch.search.aggregations.bucket;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.plugins.AbstractPlugin;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantTerms;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantTermsAggregatorFactory;
import org.elasticsearch.search.aggregations.bucket.significant.SignificantTermsBuilder;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.*;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope;
import org.elasticsearch.test.ElasticsearchIntegrationTest.Scope;
import org.junit.Test;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;

import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.*;

/**
 *
 */
@ClusterScope(scope = Scope.SUITE)
public class SignificantTermsSignificanceScoreTests extends ElasticsearchIntegrationTest {

    static final String INDEX_NAME = "testidx";
    static final String DOC_TYPE = "doc";
    static final String TEXT_FIELD = "text";
    static final String CLASS_FIELD = "class";

    @Override
    protected Settings nodeSettings(int nodeOrdinal) {
        return settingsBuilder()
                .put(super.nodeSettings(nodeOrdinal))
                .put("plugin.types", CustomSignificanceHeuristicPlugin.class.getName())
                .build();
    }

    public String randomExecutionHint() {
        return randomBoolean() ? null : randomFrom(SignificantTermsAggregatorFactory.ExecutionMode.values()).toString();
    }

    @Test
    public void testPlugin() throws Exception {
        String type = randomBoolean() ? "string" : "long";
        String settings = "{\"index.number_of_shards\": 1, \"index.number_of_replicas\": 0}";
        index01Docs(type, settings);
        SearchResponse response = client().prepareSearch(INDEX_NAME).setTypes(DOC_TYPE)
                .addAggregation(new TermsBuilder("class")
                        .field(CLASS_FIELD)
                        .subAggregation((new SignificantTermsBuilder("sig_terms"))
                                .field(TEXT_FIELD)
                                .significanceHeuristic(new SimpleHeuristic.SimpleHeuristicBuilder())
                                .minDocCount(1)
                        )
                )
                .execute()
                .actionGet();
        assertSearchResponse(response);
        StringTerms classes = (StringTerms) response.getAggregations().get("class");
        assertThat(classes.getBuckets().size(), equalTo(2));
        for (Terms.Bucket classBucket : classes.getBuckets()) {
            Map<String, Aggregation> aggs = classBucket.getAggregations().asMap();
            assertTrue(aggs.containsKey("sig_terms"));
            SignificantTerms agg = (SignificantTerms) aggs.get("sig_terms");
            assertThat(agg.getBuckets().size(), equalTo(2));
            Iterator<SignificantTerms.Bucket> bucketIterator = agg.iterator();
            SignificantTerms.Bucket sigBucket = bucketIterator.next();
            String term = sigBucket.getKey();
            String classTerm = classBucket.getKey();
            assertTrue(term.equals(classTerm));
            assertThat(sigBucket.getSignificanceScore(), closeTo(2.0, 1.e-8));
            sigBucket = bucketIterator.next();
            assertThat(sigBucket.getSignificanceScore(), closeTo(1.0, 1.e-8));
        }

        // we run the same test again but this time we do not call assertSearchResponse() before the assertions
        // the reason is that this would trigger toXContent and we would like to check that this has no potential side effects

        response = client().prepareSearch(INDEX_NAME).setTypes(DOC_TYPE)
                .addAggregation(new TermsBuilder("class")
                        .field(CLASS_FIELD)
                        .subAggregation((new SignificantTermsBuilder("sig_terms"))
                                .field(TEXT_FIELD)
                                .significanceHeuristic(new SimpleHeuristic.SimpleHeuristicBuilder())
                                .minDocCount(1)
                        )
                )
                .execute()
                .actionGet();

        classes = (StringTerms) response.getAggregations().get("class");
        assertThat(classes.getBuckets().size(), equalTo(2));
        for (Terms.Bucket classBucket : classes.getBuckets()) {
            Map<String, Aggregation> aggs = classBucket.getAggregations().asMap();
            assertTrue(aggs.containsKey("sig_terms"));
            SignificantTerms agg = (SignificantTerms) aggs.get("sig_terms");
            assertThat(agg.getBuckets().size(), equalTo(2));
            Iterator<SignificantTerms.Bucket> bucketIterator = agg.iterator();
            SignificantTerms.Bucket sigBucket = bucketIterator.next();
            String term = sigBucket.getKey();
            String classTerm = classBucket.getKey();
            assertTrue(term.equals(classTerm));
            assertThat(sigBucket.getSignificanceScore(), closeTo(2.0, 1.e-8));
            sigBucket = bucketIterator.next();
            assertThat(sigBucket.getSignificanceScore(), closeTo(1.0, 1.e-8));
        }
    }

    public static class CustomSignificanceHeuristicPlugin extends AbstractPlugin {

        @Override
        public String name() {
            return "test-plugin-significance-heuristic";
        }

        @Override
        public String description() {
            return "Significance heuristic plugin";
        }

        public void onModule(SignificantTermsHeuristicModule significanceModule) {
            significanceModule.registerParser(SimpleHeuristic.SimpleHeuristicParser.class);
        }

        public void onModule(TransportSignificantTermsHeuristicModule significanceModule) {
            significanceModule.registerStream(SimpleHeuristic.STREAM);
        }
    }

    public static class SimpleHeuristic extends SignificanceHeuristic {

        protected static final String[] NAMES = {"simple"};

        public static final SignificanceHeuristicStreams.Stream STREAM = new SignificanceHeuristicStreams.Stream() {
            @Override
            public SignificanceHeuristic readResult(StreamInput in) throws IOException {
                return readFrom(in);
            }

            @Override
            public String getName() {
                return NAMES[0];
            }
        };

        public static SignificanceHeuristic readFrom(StreamInput in) throws IOException {
            return new SimpleHeuristic();
        }

        /**
         * @param subsetFreq   The frequency of the term in the selected sample
         * @param subsetSize   The size of the selected sample (typically number of docs)
         * @param supersetFreq The frequency of the term in the superset from which the sample was taken
         * @param supersetSize The size of the superset from which the sample was taken  (typically number of docs)
         * @return a "significance" score
         */
        @Override
        public double getScore(long subsetFreq, long subsetSize, long supersetFreq, long supersetSize) {
            return subsetFreq / subsetSize > supersetFreq / supersetSize ? 2.0 : 1.0;
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeString(STREAM.getName());
        }

        public static class SimpleHeuristicParser implements SignificanceHeuristicParser {

            @Override
            public SignificanceHeuristic parse(XContentParser parser) throws IOException, QueryParsingException {
                parser.nextToken();
                return new SimpleHeuristic();
            }

            @Override
            public String[] getNames() {
                return NAMES;
            }
        }

        public static class SimpleHeuristicBuilder implements SignificanceHeuristicBuilder {

            @Override
            public void toXContent(XContentBuilder builder) throws IOException {
                builder.startObject(STREAM.getName()).endObject();
            }
        }
    }

    @Test
    public void testXContentResponse() throws Exception {

        String type = randomBoolean() ? "string" : "long";
        String settings = "{\"index.number_of_shards\": 1, \"index.number_of_replicas\": 0}";
        index01Docs(type, settings);
        SearchResponse response = client().prepareSearch(INDEX_NAME).setTypes(DOC_TYPE)
                .addAggregation(new TermsBuilder("class").field(CLASS_FIELD).subAggregation(new SignificantTermsBuilder("sig_terms").field(TEXT_FIELD)))
                .execute()
                .actionGet();
        assertSearchResponse(response);
        StringTerms classes = (StringTerms) response.getAggregations().get("class");
        assertThat(classes.getBuckets().size(), equalTo(2));
        for (Terms.Bucket classBucket : classes.getBuckets()) {
            Map<String, Aggregation> aggs = classBucket.getAggregations().asMap();
            assertTrue(aggs.containsKey("sig_terms"));
            SignificantTerms agg = (SignificantTerms) aggs.get("sig_terms");
            assertThat(agg.getBuckets().size(), equalTo(1));
            String term = agg.iterator().next().getKey();
            String classTerm = classBucket.getKey();
            assertTrue(term.equals(classTerm));
        }

        XContentBuilder responseBuilder = XContentFactory.jsonBuilder();
        classes.toXContent(responseBuilder, null);
        String result = null;
        if (type.equals("long")) {
            result = "\"class\"{\"doc_count_error_upper_bound\":0,\"sum_other_doc_count\":0,\"buckets\":[{\"key\":\"0\",\"doc_count\":4,\"sig_terms\":{\"doc_count\":4,\"buckets\":[{\"key\":0,\"key_as_string\":\"0\",\"doc_count\":4,\"score\":0.39999999999999997,\"bg_count\":5}]}},{\"key\":\"1\",\"doc_count\":3,\"sig_terms\":{\"doc_count\":3,\"buckets\":[{\"key\":1,\"key_as_string\":\"1\",\"doc_count\":3,\"score\":0.75,\"bg_count\":4}]}}]}";
        } else {
            result = "\"class\"{\"doc_count_error_upper_bound\":0,\"sum_other_doc_count\":0,\"buckets\":[{\"key\":\"0\",\"doc_count\":4,\"sig_terms\":{\"doc_count\":4,\"buckets\":[{\"key\":\"0\",\"doc_count\":4,\"score\":0.39999999999999997,\"bg_count\":5}]}},{\"key\":\"1\",\"doc_count\":3,\"sig_terms\":{\"doc_count\":3,\"buckets\":[{\"key\":\"1\",\"doc_count\":3,\"score\":0.75,\"bg_count\":4}]}}]}";
        }
        assertThat(responseBuilder.string(), equalTo(result));

    }

    @Test
    public void testDeletesIssue7951() throws Exception {
        String settings = "{\"index.number_of_shards\": 1, \"index.number_of_replicas\": 0}";
        String mappings = "{\"doc\": {\"properties\":{\"text\": {\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
        assertAcked(prepareCreate(INDEX_NAME).setSettings(settings).addMapping("doc", mappings));
        String[] cat1v1 = {"constant", "one"};
        String[] cat1v2 = {"constant", "uno"};
        String[] cat2v1 = {"constant", "two"};
        String[] cat2v2 = {"constant", "duo"};
        List<IndexRequestBuilder> indexRequestBuilderList = new ArrayList<>();
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "1")
                .setSource(TEXT_FIELD, cat1v1, CLASS_FIELD, "1"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "2")
                .setSource(TEXT_FIELD, cat1v2, CLASS_FIELD, "1"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "3")
                .setSource(TEXT_FIELD, cat2v1, CLASS_FIELD, "2"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "4")
                .setSource(TEXT_FIELD, cat2v2, CLASS_FIELD, "2"));
        indexRandom(true, false, indexRequestBuilderList);

        // Now create some holes in the index with selective deletes caused by updates.
        // This is the scenario that caused this issue https://github.com/elasticsearch/elasticsearch/issues/7951
        // Scoring algorithms throw exceptions if term docFreqs exceed the reported size of the index
        // from which they are taken so need to make sure this doesn't happen.
        String[] text = cat1v1;
        indexRequestBuilderList.clear();
        for (int i = 0; i < 50; i++) {
            text = text == cat1v2 ? cat1v1 : cat1v2;
            indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "1").setSource(TEXT_FIELD, text, CLASS_FIELD, "1"));
        }
        indexRandom(true, false, indexRequestBuilderList);

        SearchResponse response1 = client().prepareSearch(INDEX_NAME).setTypes(DOC_TYPE)
                .addAggregation(new TermsBuilder("class")
                        .field(CLASS_FIELD)
                        .subAggregation(
                                new SignificantTermsBuilder("sig_terms")
                                        .field(TEXT_FIELD)
                                        .minDocCount(1)))
                .execute()
                .actionGet();
    }

    @Test
    public void testBackgroundVsSeparateSet() throws Exception {
        String type = randomBoolean() ? "string" : "long";
        String settings = "{\"index.number_of_shards\": 1, \"index.number_of_replicas\": 0}";
        index01Docs(type, settings);
        testBackgroundVsSeparateSet(new MutualInformation.MutualInformationBuilder(true, true), new MutualInformation.MutualInformationBuilder(true, false));
        testBackgroundVsSeparateSet(new ChiSquare.ChiSquareBuilder(true, true), new ChiSquare.ChiSquareBuilder(true, false));
        testBackgroundVsSeparateSet(new GND.GNDBuilder(true), new GND.GNDBuilder(false));
    }

    // compute significance score by
    // 1. terms agg on class and significant terms
    // 2. filter buckets and set the background to the other class and set is_background false
    // both should yield exact same result
    public void testBackgroundVsSeparateSet(SignificanceHeuristicBuilder significanceHeuristicExpectingSuperset, SignificanceHeuristicBuilder significanceHeuristicExpectingSeparateSets) throws Exception {

        SearchResponse response1 = client().prepareSearch(INDEX_NAME).setTypes(DOC_TYPE)
                .addAggregation(new TermsBuilder("class")
                        .field(CLASS_FIELD)
                        .subAggregation(
                                new SignificantTermsBuilder("sig_terms")
                                        .field(TEXT_FIELD)
                                        .minDocCount(1)
                                        .significanceHeuristic(
                                                significanceHeuristicExpectingSuperset)))
                .execute()
                .actionGet();
        assertSearchResponse(response1);
        SearchResponse response2 = client().prepareSearch(INDEX_NAME).setTypes(DOC_TYPE)
                .addAggregation((new FilterAggregationBuilder("0"))
                        .filter(FilterBuilders.termFilter(CLASS_FIELD, "0"))
                        .subAggregation(new SignificantTermsBuilder("sig_terms")
                                .field(TEXT_FIELD)
                                .minDocCount(1)
                                .backgroundFilter(FilterBuilders.termFilter(CLASS_FIELD, "1"))
                                .significanceHeuristic(significanceHeuristicExpectingSeparateSets)))
                .addAggregation((new FilterAggregationBuilder("1"))
                        .filter(FilterBuilders.termFilter(CLASS_FIELD, "1"))
                        .subAggregation(new SignificantTermsBuilder("sig_terms")
                                .field(TEXT_FIELD)
                                .minDocCount(1)
                                .backgroundFilter(FilterBuilders.termFilter(CLASS_FIELD, "0"))
                                .significanceHeuristic(significanceHeuristicExpectingSeparateSets)))
                .execute()
                .actionGet();

        SignificantTerms sigTerms0 = ((SignificantTerms) (((StringTerms) response1.getAggregations().get("class")).getBucketByKey("0").getAggregations().asMap().get("sig_terms")));
        assertThat(sigTerms0.getBuckets().size(), equalTo(2));
        double score00Background = sigTerms0.getBucketByKey("0").getSignificanceScore();
        double score01Background = sigTerms0.getBucketByKey("1").getSignificanceScore();
        SignificantTerms sigTerms1 = ((SignificantTerms) (((StringTerms) response1.getAggregations().get("class")).getBucketByKey("1").getAggregations().asMap().get("sig_terms")));
        double score10Background = sigTerms1.getBucketByKey("0").getSignificanceScore();
        double score11Background = sigTerms1.getBucketByKey("1").getSignificanceScore();

        double score00SeparateSets = ((SignificantTerms) ((InternalFilter) response2.getAggregations().get("0")).getAggregations().getAsMap().get("sig_terms")).getBucketByKey("0").getSignificanceScore();
        double score01SeparateSets = ((SignificantTerms) ((InternalFilter) response2.getAggregations().get("0")).getAggregations().getAsMap().get("sig_terms")).getBucketByKey("1").getSignificanceScore();
        double score10SeparateSets = ((SignificantTerms) ((InternalFilter) response2.getAggregations().get("1")).getAggregations().getAsMap().get("sig_terms")).getBucketByKey("0").getSignificanceScore();
        double score11SeparateSets = ((SignificantTerms) ((InternalFilter) response2.getAggregations().get("1")).getAggregations().getAsMap().get("sig_terms")).getBucketByKey("1").getSignificanceScore();

        assertThat(score00Background, equalTo(score00SeparateSets));
        assertThat(score01Background, equalTo(score01SeparateSets));
        assertThat(score10Background, equalTo(score10SeparateSets));
        assertThat(score11Background, equalTo(score11SeparateSets));
    }

    private void index01Docs(String type, String settings) throws ExecutionException, InterruptedException {
        String mappings = "{\"doc\": {\"properties\":{\"text\": {\"type\":\"" + type + "\"}}}}";
        assertAcked(prepareCreate(INDEX_NAME).setSettings(settings).addMapping("doc", mappings));
        String[] gb = {"0", "1"};
        List<IndexRequestBuilder> indexRequestBuilderList = new ArrayList<>();
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "1")
                .setSource(TEXT_FIELD, "1", CLASS_FIELD, "1"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "2")
                .setSource(TEXT_FIELD, "1", CLASS_FIELD, "1"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "3")
                .setSource(TEXT_FIELD, "0", CLASS_FIELD, "0"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "4")
                .setSource(TEXT_FIELD, "0", CLASS_FIELD, "0"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "5")
                .setSource(TEXT_FIELD, gb, CLASS_FIELD, "1"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "6")
                .setSource(TEXT_FIELD, gb, CLASS_FIELD, "0"));
        indexRequestBuilderList.add(client().prepareIndex(INDEX_NAME, DOC_TYPE, "7")
                .setSource(TEXT_FIELD, "0", CLASS_FIELD, "0"));
        indexRandom(true, false, indexRequestBuilderList);
    }

    @Test
    public void testScoresEqualForPositiveAndNegative() throws Exception {
        indexEqualTestData();
        testScoresEqualForPositiveAndNegative(new MutualInformation.MutualInformationBuilder(true, true));
        testScoresEqualForPositiveAndNegative(new ChiSquare.ChiSquareBuilder(true, true));
    }

    public void testScoresEqualForPositiveAndNegative(SignificanceHeuristicBuilder heuristic) throws Exception {

        //check that results for both classes are the same with exclude negatives = false and classes are routing ids
        SearchResponse response = client().prepareSearch("test")
                .addAggregation(new TermsBuilder("class").field("class").subAggregation(new SignificantTermsBuilder("mySignificantTerms")
                        .field("text")
                        .executionHint(randomExecutionHint())
                        .significanceHeuristic(heuristic)
                        .minDocCount(1).shardSize(1000).size(1000)))
                .execute()
                .actionGet();
        assertSearchResponse(response);
        StringTerms classes = (StringTerms) response.getAggregations().get("class");
        assertThat(classes.getBuckets().size(), equalTo(2));
        Iterator<Terms.Bucket> classBuckets = classes.getBuckets().iterator();
        Collection<SignificantTerms.Bucket> classA = ((SignificantTerms) classBuckets.next().getAggregations().get("mySignificantTerms")).getBuckets();
        Iterator<SignificantTerms.Bucket> classBBucketIterator = ((SignificantTerms) classBuckets.next().getAggregations().get("mySignificantTerms")).getBuckets().iterator();
        assertThat(classA.size(), greaterThan(0));
        for (SignificantTerms.Bucket classABucket : classA) {
            SignificantTerms.Bucket classBBucket = classBBucketIterator.next();
            assertThat(classABucket.getKey(), equalTo(classBBucket.getKey()));
            assertThat(classABucket.getSignificanceScore(), closeTo(classBBucket.getSignificanceScore(), 1.e-5));
        }
    }

    private void indexEqualTestData() throws ExecutionException, InterruptedException {
        assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1, SETTING_NUMBER_OF_REPLICAS, 0).addMapping("doc",
                "text", "type=string", "class", "type=string"));
        createIndex("idx_unmapped");

        ensureGreen();
        String data[] = {
                "A\ta",
                "A\ta",
                "A\tb",
                "A\tb",
                "A\tb",
                "B\tc",
                "B\tc",
                "B\tc",
                "B\tc",
                "B\td",
                "B\td",
                "B\td",
                "B\td",
                "B\td",
                "A\tc d",
                "B\ta b"
        };

        List<IndexRequestBuilder> indexRequestBuilders = new ArrayList<>();
        for (int i = 0; i < data.length; i++) {
            String[] parts = data[i].split("\t");
            indexRequestBuilders.add(client().prepareIndex("test", "doc", "" + i)
                    .setSource("class", parts[0], "text", parts[1]));
        }
        indexRandom(true, false, indexRequestBuilders);
    }
}


text:
<?php

namespace kosv\ulogin\widget;

use yii\web\AssetBundle;

/**
 * Ulogin widget asset bundle.
 *
 * @author Konstantin Voloshchuk <kosv.dev@gmail.com>
 * @since 2.0
 */
class UloginAsset extends AssetBundle
{
    public $js = [
        '//ulogin.ru/js/ulogin.js'
    ];
}


text:
package replica.crdt

import com.rbmhtechnology.eventuate.VectorTime
import com.rbmhtechnology.eventuate.crdt._
import org.scalatest.{ Matchers, WordSpec }

class EventuateCrdtSpec extends WordSpec with Matchers {

  "ORSet" should {

    "Add/Remove" in {
      val set = ORSet[String]().add("prod_a", VectorTime("replica-1" -> 0l))
      val ts = set.prepareRemove("prod_a")
      val newSet = set.remove(ts)
      newSet.value.size shouldBe 0
    }

    "Add/Remove/Add" in {
      val vectorTime = VectorTime("replica-1" -> 0l)

      val set = ORSet[String]().add("prod_a", vectorTime)

      val ts = set.prepareRemove("prod_a")
      val deletedSet = set.remove(ts)

      val added = deletedSet.add("prod_a", vectorTime)

      added.value.size shouldBe 1
    }

    "merge two addition" in {

      var tsOne = VectorTime("r1" -> 0l)
      tsOne = (tsOne increment "r1")
      val one = ORSet[String]().add("a", tsOne)

      var tsTwo = VectorTime("r2" -> 0l)
      tsTwo = (tsTwo increment "r2")
      val two = ORSet[String]().add("b", tsTwo)

      //on 1
      val merged1_2 = two.versionedEntries./:(tsOne)(_ merge _.vectorTimestamp)
      val mergedSet1_2 = one.add("b", merged1_2)

      mergedSet1_2.value.size shouldBe 2
    }

    "ORCart add several instances of the same product" in {

      val map = com.rbmhtechnology.eventuate.crdt.ORCart[String]()
                  .add("a", 1, VectorTime("r1" -> 1l))
                  .add("a", 1, VectorTime("r2" -> 1l))
                  .add("a", 2, VectorTime("r3" -> 2l))
                  .value

      map("a") shouldBe 4
    }

    "ORCart add -> remove" in {
      val map = com.rbmhtechnology.eventuate.crdt.ORCart[String]().add("a", 2, VectorTime("r1" -> 1l))

      val ts = map.prepareRemove("a")

      map.remove(ts).value.size shouldBe 0
    }
  }
}


text:
from sqlalchemy import Column, Integer, Boolean, String
from database import Base

""" Member of Parliament """
class MP(Base):
    __tablename__ = 'mps'
    id = Column(Integer, primary_key=True)
    first_name = Column(String(150))
    last_name = Column(String(150))
    party = Column(String(150))
    list_mp = Column(Boolean)
    details_url = Column(String(150))
    image_url = Column(String(150))

    _base_url = 'http://www.parliament.nz'

    """ Init a new MP """
    def __init__(self, name=None, details_url=None, electoral_details=None):
        self.last_name, self.first_name = [n.strip() for n in name.split(',')]
        self.details_url = self._base_url + details_url
        self.party, self.electorate = [e.strip() for e in electoral_details.split(',')]
        self.list_mp = False
        self._parse_electorate()

    def __repr__(self):
        return('<MP %s>' % self._formatted_title())

    def _formatted_title(self):
        return("id=%i first_name='%s' last_name='%s' party='%s'" % (self.id, self.first_name, self.last_name, self.party))

    def image_from_src(self, src):
        self.image_url = self._base_url + src

    def as_json(self):
        return {
                'id': self.id,
                'first_name': self.first_name,
                'last_name': self.last_name,
                'party': self.party,
                'list_mp': self.list_mp,
                'details_url': self.details_url,
                'image_url': self.image_url
                }

    """ Parses 'List' as a List MP """
    def _parse_electorate(self):
        if self.electorate == 'List':
            self.electorate = None
            self.list_mp = True


text:
<?php

namespace Oro\Bundle\QueryDesignerBundle\Form\Type;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Oro\Bundle\QueryDesignerBundle\Model\AbstractQueryDesigner;

abstract class AbstractQueryDesignerType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('definition', 'hidden', array('required' => false));

        $factory = $builder->getFormFactory();
        $that    = $this;
        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($that, $factory) {
                $form = $event->getForm();
                /** @var AbstractQueryDesigner $data */
                $data = $event->getData();
                if ($data) {
                    $entity = $data->getEntity();
                } else {
                    $entity = null;
                }
                $that->addFields($form, $factory, $entity);
            }
        );

        $builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            function (FormEvent $event) use ($that, $factory) {
                $form = $event->getForm();
                /** @var AbstractQueryDesigner $data */
                $data = $event->getData();
                if ($data) {
                    $entity = $data['entity'];
                } else {
                    $entity = null;
                }
                $that->addFields($form, $factory, $entity);
            }
        );
    }

    /**
     * Gets the default options for this type.
     *
     * @return array
     */
    public function getDefaultOptions()
    {
        return
            array(
                'grouping_column_choice_type' => 'oro_entity_field_select',
                'column_column_choice_type'   => 'oro_entity_field_select',
                'filter_column_choice_type'   => 'oro_entity_field_select'
            );
    }

    /**
     * Adds column and filters sub forms
     *
     * @param FormInterface        $form
     * @param FormFactoryInterface $factory
     * @param string|null          $entity
     */
    protected function addFields($form, $factory, $entity = null)
    {
        $form->add(
            $factory->createNamed(
                'grouping',
                'oro_query_designer_grouping',
                null,
                array(
                    'mapped'             => false,
                    'column_choice_type' => $form->getConfig()->getOption('grouping_column_choice_type'),
                    'entity'             => $entity ? $entity : null,
                    'auto_initialize'    => false
                )
            )
        );
        $form->add(
            $factory->createNamed(
                'column',
                'oro_query_designer_column',
                null,
                array(
                    'mapped'             => false,
                    'column_choice_type' => $form->getConfig()->getOption('column_column_choice_type'),
                    'entity'             => $entity ? $entity : null,
                    'auto_initialize'    => false
                )
            )
        );
        $form->add(
            $factory->createNamed(
                'filter',
                'oro_query_designer_filter',
                null,
                array(
                    'mapped'             => false,
                    'column_choice_type' => $form->getConfig()->getOption('filter_column_choice_type'),
                    'entity'             => $entity ? $entity : null,
                    'auto_initialize'    => false
                )
            )
        );
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd

	http://www.springframework.org/schema/context
 	http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- Déclaration des DAO JDBC -->

	<context:component-scan base-package="fr.esecure.banking">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Component" />
	</context:component-scan>

</beans>


text:
module IX.Universe.Market
 (nextMarketRolls
 ,adjustMarket
 ,evalMarket
 ,evalCommerce
 ,marketToAgt
 ,commerceToAgt)
 where

import DataStructures.Atomic
import DataStructures.Composite
import Data.Maybe (catMaybes)
import Safe (fromJustNote)
import qualified Data.List as DL
import Data.List (find)
import Data.List.Utils (addToAL)
import Data.Text (unpack)
import qualified Data.Map as M

import IX.Universe.Utils (setMessage)

nextMarketRolls :: ResourceMap -> [PInt] -> [PInt]
nextMarketRolls (ResourceMap rMap)  rolls = drop (M.size rMap) rolls

adjustMarket :: [PInt] -> ResourceMap -> ResourceMap
adjustMarket dRolls (ResourceMap rMap) =
   let currentRolls = take (M.size rMap) dRolls
       matchedRolls = zip rMap' currentRolls
   in ResourceMap $ M.fromList (map adjustLocalMarket matchedRolls)
   where
     rMap' = M.toList rMap

adjustLocalMarket ((rName,res),roll) =
   case stability res of
      Stable cDown -> manageStability cDown
      Volatile     -> (rName,priceADJ)
   where
      priceADJ
         | roll <= 50 = stableOrDec
         | otherwise  = stableOrInc
      stableOrDec
         | cPrice > lPrice = stability_check Decrement
         | otherwise       = res
      stableOrInc
         | cPrice < hPrice = stability_check Increment
         | otherwise         = res
      stability_check Decrement
         | roll <= 20 = stablize dec_price
         | otherwise  = dec_price
      stability_check Increment
         | roll >= 80 = stablize inc_price
         | otherwise    = inc_price
      manageStability (PInt cDown)
         | cDown == 0 = (rName,endStability)
         | otherwise  = (rName,decStability)
         where
            decStability  = res {stability  = Stable $ PInt (cDown - 1)}
      endStability  = res {stability  = Volatile}
      stablize res' = res' {stability = Stable $ PInt 500}
      cPrice        = currentPrice res
      lPrice        = lowestPrice res
      hPrice        = highestPrice res
      dec_price     = res {currentPrice = cPrice - pDec}
      inc_price     = res {currentPrice = cPrice + pDec}
      pDec          = PInt 1

evalMarket :: PlanetName ->
              Planet     ->
              ResourceMap ->
              Result
evalMarket p_name planet (ResourceMap r_map) =
   (MarketData p_name r_data)
   where
      r_map' = M.toList r_map
      r_list = resources planet
      r_data = zip r_list $ catMaybes $ map (flip lookup r_map') r_list

evalCommerce :: CommerceAction             ->
                Agent                      ->
                (ResourceName,ResourceMap) ->
                PInt                       ->
                (PlanetName,Planet)        ->
                Result
evalCommerce c_action agt (r_name,(ResourceMap r_map)) amt (p_name,planet') =
   case c_action of
      BuyA  -> buy_offer
      SellA -> sell_offer
   where
      buy_offer =
         case p_res of
            Just _  -> buy_attempt
               where
                  buy_attempt
                     | (credits agt) >= cost =
                          Commerce (BuyR cost) (r_name,res) amt
                     | otherwise             =
                          CError $ CantAfford r_name cost (credits agt)
                     where
                        cost = c_res
            Nothing -> not_for_sale

      sell_offer =
         case p_res of
            Just _  -> sell_attempt
            Nothing -> CError $ NotInTheMarketFor r_name p_name
         where
            sell_attempt
               | (held_comm >= amt) = Commerce (SellR revenue) (r_name,res) amt
               | otherwise          = CError $ YouDontHave r_name amt
            revenue                 = c_res

      p_res = DL.find (== r_name) $ resources planet'
      c_res = (currentPrice res) * amt
      not_for_sale = CError $ DontHave r_name
      held_comm =
         let m_amt = lookup r_name $
                     cargo         $
                     ship_stats    $
                     ship agt
         in case m_amt of
               Just amt_ -> amt_
               Nothing   -> PInt 0

      cant_afford  = CError $ CantAfford r_name c_res creds
      res = fromJustNote resFail (M.lookup r_name r_map)
      creds = credits agt
      resFail = "evalCOmmerce failed to find " ++
                show r_name                    ++
                "in resource map\n"

marketToAgt :: AgentMap -> M.Map AID Result -> [Maybe DAgentMap]
marketToAgt (AgentMap a_map) resList =
  snd `fmap` M.toList (M.mapWithKey marketToAgt' resList)
  where
    marketToAgt' aid@(AID aid') (MarketData p_name local_res) =
      Just $
      DAgentMap (mkAgent (aid,o_agent) (LocalMarketData p_name local_res))
      where
        o_agent :: Agent
        o_agent = fromJustNote aAgentFail ((M.lookup aid a_map) :: Maybe Agent)
        aAgentFail = "lookToAgt failed to match aid " ++ (unpack aid')
        mkAgent :: (AID, Agent) -> Message -> SubAgentMap
        mkAgent (aid'', o_agent ) message' =
          SubAgentMap (M.singleton aid'' n_agent)
          where
          n_agent = setMessage [message'] o_agent
    marketToAgt' _ _ = Nothing

commerceToAgt :: AgentMap          ->
                 M.Map AID Result  ->
                 [Maybe DAgentMap]
commerceToAgt (AgentMap a_map) resList =
  snd `fmap` M.toList (M.mapWithKey commerceToAgt' resList)
  where
    commerceToAgt' aid (Commerce c_action (r_name,res) amt) =
      let agt = fromJustNote aAgentFail (M.lookup aid a_map)
      in case c_action of
           BuyR cost     -> -- code smell
             Just $ DAgentMap (SubAgentMap (M.singleton aid (buy agt cost)))
           SellR revenue -> -- code smell
            Just $ DAgentMap (SubAgentMap (M.singleton aid (sell agt revenue)))
      where
        buy agt cost =
          let agtLessCost = setCredits Subtract agt cost
          in  set_agt_commodity c_action agtLessCost
        sell agt revenue =
          let agtAddRevenue = setCredits Add agt revenue
          in  set_agt_commodity c_action agtAddRevenue

        set_agt_commodity :: CommerceResult -> Agent -> Agent
        set_agt_commodity c_res
                          agt@(Player {ship = Ship shipParts shipStats}) =
          case c_res of
            (BuyR _)  -> agt {ship = up_ship (+)}
            (SellR _) -> agt {ship = up_ship (-)}
          where
            res_inv         = fromJustNote resourceFail (lookup r_name c_inv)
            c_inv           = cargo $ ship_stats'
            ship_stats'     = ship_stats (ship agt)
            up_inv  f       = addToAL c_inv r_name (res_inv `f` amt)
            set_inv up_inv' = ship_stats' {cargo = up_inv'}
            up_ship f       = Ship shipParts (set_inv (up_inv f))
        setCredits c_act agt t_creds =
          let creds = credits agt
          in case c_act of
               Subtract -> agt {credits = creds - t_creds}
               Add      -> agt {credits = creds + t_creds}
        aAgentFail      = "commerceToAgt failed to lookup" ++
                          "acting agent in aMap"           ++
                          (show aid)
        resourceFail    = "commerceAGgt failed to find " ++
                          (show r_name)                  ++
                          "in inventory of"              ++
                          (show aid)

    commerceToAgt' _ _ = Nothing


text:
<resources>
    <string name="app_name">eyepetizer_menu_animation</string>
</resources>