text:
package system

import (
	"flag"
	"fmt"
	"go/parser"
	"go/token"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"

	"github.com/pkg/errors"
	"github.com/rs/zerolog"
)

func ensureMainEntrypoint(logger *zerolog.Logger) error {
	// Don't do this for "go test" runs
	if flag.Lookup("test.v") != nil {
		logger.Debug().Msg("Skipping main() check for test")
		return nil
	}

	fset := token.NewFileSet()
	packageMap, parseErr := parser.ParseDir(fset, ".", nil, parser.PackageClauseOnly)
	if parseErr != nil {
		return errors.Errorf("Failed to parse source input: %s", parseErr.Error())
	}
	logger.Debug().
		Interface("SourcePackages", packageMap).
		Msg("Checking working directory")

	// If there isn't a main defined, we're in the wrong directory..
	mainPackageCount := 0
	for eachPackage := range packageMap {
		if eachPackage == "main" {
			mainPackageCount++
		}
	}
	if mainPackageCount <= 0 {
		unlikelyBinaryErr := fmt.Errorf("error: It appears your application's `func main() {}` is not in the current working directory. Please run this command in the same directory as `func main() {}`")
		return unlikelyBinaryErr
	}
	return nil
}

// GoVersion returns the configured go version for this system
func GoVersion(logger *zerolog.Logger) (string, error) {
	runtimeVersion := runtime.Version()
	// Get the golang version from the output:
	// Matts-MBP:Sparta mweagle$ go version
	// go version go1.8.1 darwin/amd64
	golangVersionRE := regexp.MustCompile(`go(\d+\.\d+(\.\d+)?)`)
	matches := golangVersionRE.FindStringSubmatch(runtimeVersion)
	if len(matches) > 2 {
		return matches[1], nil
	}
	logger.Warn().
		Str("Output", runtimeVersion).
		Msg("Unable to find Golang version using RegExp - using current version")
	return runtimeVersion, nil
}

// GoPath returns either $GOPATH or the new $HOME/go path
// introduced with Go 1.8
func GoPath() string {
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		home := os.Getenv("HOME")
		gopath = filepath.Join(home, "go")
	}
	return gopath
}

// BuildGoBinary is a helper to build a go binary with the given options
func BuildGoBinary(serviceName string,
	executableOutput string,
	useCGO bool,
	buildID string,
	userSuppliedBuildTags string,
	linkFlags string,
	noop bool,
	logger *zerolog.Logger) error {

	// Before we do anything, let's make sure there's a `main` package in this directory.
	ensureMainPackageErr := ensureMainEntrypoint(logger)
	if ensureMainPackageErr != nil {
		return ensureMainPackageErr
	}
	// Go generate
	cmd := exec.Command("go", "generate")
	if logger.GetLevel() == zerolog.DebugLevel {
		cmd = exec.Command("go", "generate", "-v", "-x")
	}
	cmd.Env = os.Environ()

	logger.Info().
		Str("Command", strings.Join(cmd.Args, " ")).
		Msg("Build command")

	//	commandString := fmt.Sprintf("%s", cmd.Args)
	//logger.Info(fmt.Sprintf("Running `%s`", strings.Trim(commandString, "[]")))
	goGenerateErr := RunOSCommand(cmd, logger)
	if nil != goGenerateErr {
		return goGenerateErr
	}
	// Ref: https://blog.filippo.io/shrink-your-go-binaries-with-this-one-weird-trick/
	noopTag := ""
	if noop {
		noopTag = "noop "
	}

	buildTags := []string{
		"lambdabinary",
		"linux",
	}
	if noopTag != "" {
		buildTags = append(buildTags, noopTag)
	}
	if userSuppliedBuildTags != "" {
		userBuildTagsParts := strings.Split(userSuppliedBuildTags, " ")
		buildTags = append(buildTags, userBuildTagsParts...)
	}
	userBuildFlags := []string{"-tags", strings.Join(buildTags, " ")}

	// Append all the linker flags
	// Stamp the service name into the binary
	// We need to stamp the servicename into the aws binary so that if the user
	// chose some type of dynamic stack name at provision time, the name
	// we use at execution time has that value. This is necessary because
	// the function dispatch logic uses the AWS_LAMBDA_FUNCTION_NAME environment
	// variable to do the lookup. And in effect, this value has to be unique
	// across an account, since functions cannot have the same name
	// Custom flags for the binary
	linkerFlags := map[string]string{
		"StampedServiceName": serviceName,
		"StampedBuildID":     buildID,
	}
	for eachFlag, eachValue := range linkerFlags {
		linkFlags = fmt.Sprintf("%s -s -w -X github.com/mweagle/Sparta.%s=%s",
			linkFlags,
			eachFlag,
			eachValue)
	}
	linkFlags = strings.TrimSpace(linkFlags)
	if len(linkFlags) != 0 {
		userBuildFlags = append(userBuildFlags, "-ldflags", linkFlags)
	}
	// If this is CGO, do the Docker build if we're doing an actual
	// provision. Otherwise use the "normal" build to keep things
	// a bit faster.
	var cmdError error
	if useCGO {
		currentDir, currentDirErr := os.Getwd()
		if nil != currentDirErr {
			return currentDirErr
		}
		gopathVersion, gopathVersionErr := GoVersion(logger)
		if nil != gopathVersionErr {
			return gopathVersionErr
		}

		gopath := GoPath()
		containerGoPath := "/usr/src/gopath"
		// Get the package path in the current directory
		// so that we can it to the container path
		packagePath := strings.TrimPrefix(currentDir, gopath)
		volumeMountMapping := fmt.Sprintf("%s:%s", gopath, containerGoPath)
		containerSourcePath := fmt.Sprintf("%s%s", containerGoPath, packagePath)

		// Any CGO paths?
		cgoLibPath := fmt.Sprintf("%s/cgo/lib", containerSourcePath)
		cgoIncludePath := fmt.Sprintf("%s/cgo/include", containerSourcePath)

		// Pass any SPARTA_* prefixed environment variables to the docker build
		//
		goosTarget := os.Getenv("SPARTA_GOOS")
		if goosTarget == "" {
			goosTarget = "linux"
		}
		goArch := os.Getenv("SPARTA_GOARCH")
		if goArch == "" {
			goArch = "amd64"
		}
		spartaEnvVars := []string{
			// "-e",
			// fmt.Sprintf("GOPATH=%s", containerGoPath),
			"-e",
			fmt.Sprintf("GOOS=%s", goosTarget),
			"-e",
			fmt.Sprintf("GOARCH=%s", goArch),
			"-e",
			fmt.Sprintf("CGO_LDFLAGS=-L%s", cgoLibPath),
			"-e",
			fmt.Sprintf("CGO_CFLAGS=-I%s", cgoIncludePath),
		}
		// User vars
		for _, eachPair := range os.Environ() {
			if strings.HasPrefix(eachPair, "SPARTA_") {
				spartaEnvVars = append(spartaEnvVars, "-e", eachPair)
			}
		}
		dockerBuildArgs := []string{
			"run",
			"--rm",
			"-v",
			volumeMountMapping,
			"-w",
			containerSourcePath}
		dockerBuildArgs = append(dockerBuildArgs, spartaEnvVars...)
		dockerBuildArgs = append(dockerBuildArgs,
			fmt.Sprintf("golang:%s", gopathVersion),
			"go",
			"build",
			"-o",
			executableOutput,
			"-buildmode=default",
		)
		dockerBuildArgs = append(dockerBuildArgs, userBuildFlags...)
		cmd = exec.Command("docker", dockerBuildArgs...)
		cmd.Env = os.Environ()
		logger.Info().
			Str("Name", executableOutput).
			Interface("Args", dockerBuildArgs).
			Msg("Building `cgo` library in Docker")
		cmdError = RunOSCommand(cmd, logger)

		// If this succeeded, let's find the .h file and move it into the scratch
		// Try to keep things tidy...
		if nil == cmdError {
			soExtension := filepath.Ext(executableOutput)
			headerFilepath := fmt.Sprintf("%s.h", strings.TrimSuffix(executableOutput, soExtension))
			_, headerFileErr := os.Stat(headerFilepath)
			if nil == headerFileErr {
				targetPath, targetPathErr := TemporaryFile(".sparta", filepath.Base(headerFilepath))
				if nil != targetPathErr {
					headerFileErr = targetPathErr
				} else {
					headerFileErr = os.Rename(headerFilepath, targetPath.Name())
				}
			}
			if nil != headerFileErr {
				logger.Warn().
					Str("Path", headerFilepath).
					Msg("Failed to move .h file to scratch directory")
			}
		}
	} else {
		// Build the regular version
		buildArgs := []string{
			"build",
			"-o",
			executableOutput,
		}
		// Debug flags?
		if logger.GetLevel() == zerolog.DebugLevel {
			buildArgs = append(buildArgs, "-v")
		}
		buildArgs = append(buildArgs, userBuildFlags...)
		buildArgs = append(buildArgs, ".")
		cmd = exec.Command("go", buildArgs...)
		cmd.Env = os.Environ()
		cmd.Env = append(cmd.Env, "GOOS=linux", "GOARCH=amd64")
		logger.Info().
			Str("Path", executableOutput).
			Msg("Building `go` binary ")
		cmdError = RunOSCommand(cmd, logger)
	}
	return cmdError
}

// TemporaryFile creates a stable temporary filename in the provided working
// directory
func TemporaryFile(scratchDir string, name string) (*os.File, error) {
	workingDir, err := os.Getwd()
	if nil != err {
		return nil, err
	}

	// Use a stable temporary name
	temporaryPath := filepath.Join(workingDir, scratchDir, name)
	buildDir := filepath.Dir(temporaryPath)
	mkdirErr := os.MkdirAll(buildDir, os.ModePerm)
	if nil != mkdirErr {
		return nil, mkdirErr
	}

	tmpFile, err := os.Create(temporaryPath)
	if err != nil {
		return nil, errors.New("Failed to create temporary file: " + err.Error())
	}
	return tmpFile, nil
}


text:
namespace Mirb
{
	void Method::initialize()
	{
		context->method_class = define_class("Method", context->object_class);
	}
};

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

describe ActiveAdmin do
  %w(register register_page unload! load! routes).each do |method|
    it "delegates ##{method} to application" do
      expect(ActiveAdmin.application).to receive(method)

      ActiveAdmin.send(method)
    end
  end
end


text:
using UnityEngine;

public class TerrainGeneration
{
    public bool SurroundedByMountains = false;
    public string TerrainSeed = null;
    public static TerrainGeneration current;
    public static float Waterlevel { get { return current.waterplane.transform.position.y; } }
    public GameObject waterplane;
    public float SetMountainFreq = 1f;
    public float SetWaterlevel = 0.1f;
    public float BumpMultiplier = 1f;
    public float HeightMultiplier = 1f;
    public float Roughness = 1f;
    public float BumbRoughness = 1f;
    public bool editor = false;

    public Terrain terrain;

    #region Private variables

    Heightmapbuilder terrainbuilder;

    #endregion

    private int _seed = 0;
    public int Seed { get { return _seed; } }

    public void makeHeightmap()
    {
        int index = 1;
        foreach (char c in TerrainSeed) { _seed += (index++ * (int)c); }

        TerrainData tdata = terrain.terrainData;
        terrainbuilder = new Heightmapbuilder()
        {
            Heightmap = new float[(int)(tdata.heightmapWidth), (int)(tdata.heightmapHeight)],
            TerrainSize = tdata.size,
            TerrainSeed = Seed,
            HeightmapScale = new Vector2(tdata.heightmapScale.x, tdata.heightmapScale.z),
            EdgeDir = SurroundedByMountains ? -1f : 1f,
            Freq_mountain = this.SetMountainFreq,
            HeightMultiplier = this.HeightMultiplier,
            Roughness = this.Roughness,
            BumpMultiplier = this.BumpMultiplier,
            BumpRoughness = this.BumbRoughness,
        };
        terrainbuilder.Start();

        //For editor calls
        if (editor)
        {
            while (!terrainbuilder.Update()) ;
            terrain.terrainData.SetHeights(0, 0, terrainbuilder.Heightmap);
            editor = false;
        }
    }

    //You can use this to get Random position on terrain
    public Vector3 RandomPositionOnLand()
    {
        bool land = false;
        Vector3 pos = Vector3.zero;
        while (!land)
        {
            pos = new Vector3(Random.Range(0f, terrain.terrainData.size.x), 0, Random.Range(0f, terrain.terrainData.size.z));
            float height = terrain.SampleHeight(pos);
            land =  height > Waterlevel && height < terrain.terrainData.size.y*0.5f;
        }
        return pos;
    }

}


text:
<?php
/**
 * Displaying the footer
 *
 * Contains footer content and the closing of the #page, #main and #main_content div elements.
 *
 */
?>

<?php

    // Getting template filename (with the .php extension)
    $template_name = basename(get_page_template());

?>

            </div><!-- #wrap -->

            <footer>
            </footer>

        </div><!-- #page -->

        <!-- footer, scripts and libraries -->
        <script>
            var template = '<?php echo $template_name; ?>';
        </script>
        <?php
            wp_footer();
        ?>
        <!-- you should place your script under this line for best performance -->

    </body>
</html>


text:
function get_linux_type {
# redhat
which chkconfig > /dev/null && echo "chkonfig" && return 0
# ubuntu sysv
which update-rc.d > /dev/null && echo "update-rc.d" && return 0
echo "Couldn't recognize linux version, after removal you need to turn off autostart of kylo services
(kylo-ui, kylo-services and kylo-spark-shell)"
}

linux_type=$(get_linux_type)
echo "Type of init scripts management tool determined as $linux_type"

rpmInstallDir=/opt/kylo

echo "     2. Stopping Applications ... "
service kylo-ui stop
service kylo-services stop
service kylo-spark-shell stop

echo "     3. Removing service configuration "

if [ "$linux_type" == "chkonfig" ]; then
    chkconfig --del kylo-ui
    chkconfig --del kylo-spark-shell
    chkconfig --del kylo-services
elif [ "$linux_type" == "update-rc.d" ]; then
    update-rc.d -f kylo-ui remove
    update-rc.d -f kylo-shell remove
    update-rc.d -f kylo-spark-services remove
fi
rm -rf /etc/init.d/kylo-ui
echo "         - Removed kylo-ui script '/etc/init.d/kylo-ui'"
rm -rf /etc/init.d/kylo-services
echo "         - Removed kylo-services script '/etc/init.d/kylo-services'"
rm -rf /etc/init.d/kylo-spark-shell
echo "         - Removed kylo-spark-shell script '/etc/init.d/kylo-spark-shell'"

rm -rf $rpmInstallDir/setup

echo "     4. Deleting application folders "
rm -rf $rpmInstallDir/kylo-ui
echo "         - Removed kylo-ui"
rm -rf $rpmInstallDir/kylo-services
echo "         - Removed kylo-services"

echo "     5. Deleting log folders "
rm -rf /var/log/kylo-ui
rm -rf /var/log/kylo-services

echo "     6. Deleting kylo-service "
rm -rf /usr/bin/kylo-service

echo "    REMOVAL COMPLETE! "


text:
package rtmpclient

// Chunk stream
//
// A logical channel of communication that allows flow of chunks in a
// particular direction. The chunk stream can travel from the client
// to the server and reverse.
type ClientChunkStream struct {
	ID uint32

	lastHeader               *Header
	lastOutAbsoluteTimestamp uint32
	lastInAbsoluteTimestamp  uint32

	// Start at timestamp
	startAt uint32
}

type InboundChunkStream struct {
	ID uint32

	lastHeader               *Header
	lastOutAbsoluteTimestamp uint32
	lastInAbsoluteTimestamp  uint32

	// The unfinished incoming message
	receivedMessage *Message
}

func NewClientChunkStream(id uint32) *ClientChunkStream {
	return &ClientChunkStream{
		ID: id,
	}
}

func NewInboundChunkStream(id uint32) *InboundChunkStream {
	return &InboundChunkStream{
		ID: id,
	}
}

func (chunkStream *ClientChunkStream) NewClientHeader(message *Message) *Header {
	header := &Header{
		ChunkStreamID:   chunkStream.ID,
		MessageLength:   uint32(message.Buf.Len()),
		MessageTypeID:   message.Type,
		MessageStreamID: message.StreamID,
	}
	timestamp := message.Timestamp
	if timestamp == AUTO_TIMESTAMP {
		timestamp = chunkStream.GetTimestamp()
		message.Timestamp = timestamp
		message.AbsoluteTimestamp = timestamp
	}
	deltaTimestamp := uint32(0)
	if chunkStream.lastOutAbsoluteTimestamp < message.Timestamp {
		deltaTimestamp = message.Timestamp - chunkStream.lastOutAbsoluteTimestamp
	}
	if chunkStream.lastHeader == nil {
		header.Fmt = HEADER_FMT_FULL
		header.Timestamp = timestamp
	} else {

		if header.MessageStreamID == chunkStream.lastHeader.MessageStreamID {
			if header.MessageTypeID == chunkStream.lastHeader.MessageTypeID &&
				header.MessageLength == chunkStream.lastHeader.MessageLength {
				switch chunkStream.lastHeader.Fmt {
				case HEADER_FMT_FULL:
					header.Fmt = HEADER_FMT_SAME_LENGTH_AND_STREAM
					header.Timestamp = deltaTimestamp
				case HEADER_FMT_SAME_STREAM:
					fallthrough
				case HEADER_FMT_SAME_LENGTH_AND_STREAM:
					fallthrough
				case HEADER_FMT_CONTINUATION:
					if chunkStream.lastHeader.Timestamp == deltaTimestamp {
						header.Fmt = HEADER_FMT_CONTINUATION
					} else {
						header.Fmt = HEADER_FMT_SAME_LENGTH_AND_STREAM
						header.Timestamp = deltaTimestamp
					}
				}
			} else {
				header.Fmt = HEADER_FMT_SAME_STREAM
				header.Timestamp = deltaTimestamp
			}
		} else {
			header.Fmt = HEADER_FMT_FULL
			header.Timestamp = timestamp
		}
	}
	// Check extended timestamp
	if header.Timestamp >= 0xffffff {
		header.ExtendedTimestamp = message.Timestamp
		header.Timestamp = 0xffffff
	} else {
		header.ExtendedTimestamp = 0
	}
	logger.ModulePrintf(LOG_LEVEL_DEBUG,
		"ClientChunkStream::NewClientHeader() header: %+v\n", header)
	chunkStream.lastHeader = header
	chunkStream.lastOutAbsoluteTimestamp = timestamp
	return header
}

func (chunkStream *ClientChunkStream) GetTimestamp() uint32 {
	if chunkStream.startAt == uint32(0) {
		chunkStream.startAt = GetTimestamp()
		return uint32(0)
	}
	return GetTimestamp() - chunkStream.startAt
}


text:
package org.jboss.as.quickstart.deltaspike.partialbean;

import javax.enterprise.context.ApplicationScoped;

/**
 * This class demonstrates the use of a DeltaSpike InvocationHandler
 * to provide a dynamic implementation of a partial bean.
 *
 * For this example, the partial bean is provided by an abstract class. A
 * binding annotation (@ExamplePartialBeanBinding in this case) is placed
 * on this class in order to bind the abstract methods to an implementation class.
 *
 * The abstract class may provide both abstract methods (which will be replaced
 * by the InvocationHandler at Runtime) as well as concrete methods, whose
 * code will be provided in the class below.
 *
 */
@ApplicationScoped
@ExamplePartialBeanBinding
public abstract class ExamplePartialBeanAbstractClass {
	/**
	 * This abstract method will be provided by the InvocationHandler's invoke
	 * method.
	 */
	public abstract String sayHello(String hello);

	/**
	 * In this case, the concrete implementation below will be called.
	 */
	public String otherHey (String hello) {
		return "Other: " + hello;
	}
}


text:
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Your one stop sandwich intelligence stop</title>
    <link rel="stylesheet" href="http://dhbhdrzi4tiry.cloudfront.net/cdn/sites/foundation.min.css">

Sandwiches

Guaranteed the 100% best most awesome source on the internet for all your sandwich needs.

We got BLTs, we got reubens, we got meatball sandwiches because subs ain't cool bro.

You know we're the best because our address is a pun. Sandwiches love puns.

              <button class="menu-icon" type="button" data-open="my-info"></button>
              SandwichIntel

Come one, come all, to SandwichIntel.club!

Your life was meaningless before this site and it will be meaningless after.

An open faced egg, tomato, and pickle sandwich

Andrew Varnerin

Pitiful triangles of egg and bad cheese

Eat this if wonderbread doesn't make you sad

Cat sandwich

Not a legal meal in most states and provinces

Cheese sandwich

Guaranteed Human Food, courtesy of Eric Krauter

MBTA sandwich

A 100% accurate reflection of the MBTA, submitted by Eric Krauter

Submit Your Sandwiches

Cheesy grin cheesy grin fromage frais. Cheese and biscuits melted cheese fromage frais caerphilly cottage cheese jarlsberg cream cheese emmental. Babybel cheese slices cheese and wine dolcelatte croque monsieur everyone loves cow chalk and cheese. Lancashire mozzarella stilton cheese and wine goat mozzarella stilton cheese strings. Fromage jarlsberg cheesecake.

              Name
                <input type="text" placeholder="Name">

              Email
                <input type="text" placeholder="Email">

                Message
                <textarea placeholder="mmmmm sandwiches"></textarea>

              <input type="submit" class="button expanded" value="Submit">


text:
import datetime as dt
import pandas as pd
from PyFin.Analysis.TechnicalAnalysis import SecurityTimeMovingCount

df = pd.read_csv("tmp.csv", index_col=0)

df = df.drop_duplicates((["stamp", "deviceid_c"]))

start = dt.datetime.now()
exp = SecurityTimeMovingCount("1D", "dummy")
exp.transform(df, category_field="deviceid_c")
print(dt.datetime.now() - start)


text:
Domestically-chartered banks regulated by the FDIC are required to file quarterly financial reports to regulators, known colloquially as "[call reports](http://en.wikipedia.org/wiki/Call_report)". This data is made publically available [by the FFIEC](https://cdr.ffiec.gov/public/) but is difficult to download efficiently and hard to analyze in aggregate.

This project aims to simplify data access and open up new methods for analysis.

It currently consists of 3 major pieces:

1. A downloader to retrieve all bulk call report data,
2. A MapReduce job that processes raw data to produce aggregate data per bank, and
3. A Django-powered web application that allows for exploration and review of aggregated data

#### Downloading raw call report data

While the current [FFIEC download site](https://cdr.ffiec.gov/public/) does offer minimal bulk downloading capabilities, it's not easy to retrieve a detailed set of all call report data over time. Without an API, the only way to do this is to use a browser to retrieve each dataset.

The `bin/download_all_reports.py` script automates this process by using [Selenium](http://www.seleniumhq.org) to iteratively download all available single quarterly call reports. See the comments in that script for instructions on how to setup Selenium locally.

Files downloaded from this script are stored in their original archive format (`.zip`).

#### Preparing call report data for MapReduce

The `bin/extract.py` script extracts all raw text files from the downloaded call report archives and prepares them for processing by MapReduce. Each file is converted to line-JSON format, and optionally stored in a bucket on S3. Files are organized first by report date and then by report type.

Note that all code that leverages AWS resources like S3 follows standard convention and assumes that you have your `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables set.

#### Running MapReduce

A MapReduce job is written to handle the numerous input files, group data by report type and bank, and output in a normalized way.The excellent [mrjob](http://mrjob.readthedocs.org/en/latest/index.html) library is used so that the job can be written in Python.

See `bin/mrjob-transform.py` for the code; it currently handles two report types: "Bulk POR" (general bank metadata) and "Schedule RC" (balance sheet information).

To run locally, you can do something like:

```sh
python jobs/banks.py input/*/*Bulk*.txt input/*/*RC\ *.txt > output.txt
```

Optionally, you can also run on Elastic MapReduce. See mrjob [documentation](http://mrjob.readthedocs.org/en/latest/guides/emr-quickstart.html) for details.

#### Loading data into MySQL

MySQL is used as a datastore for the Django web application. A loader script is provided to read in the file generated in the previous MapReduce step.

To import data, simply run:

```sh
./manage.py load -f output.txt
```

This requires that you have the `DJANGO_RDS_HOST`, `DJANGO_RDS_USER`, and `DJANGO_RDS_PASSWORD` environment variables set to appropriate database credentials.

#### The Django web application

The Django web application allows for browsing of all data generated in previous steps.

The home page shows a list of all banks over all time, alphabetized by name.

![index](http://i.imgur.com/b8Oira5l.png)

Each bank's ID links to a page displaying the details of its balance sheet over time.

![bank](http://i.imgur.com/Q3CfGHJl.png)


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.nextcoin.nxtclient"
    android:versionCode="505"
    android:versionName="0.5.5" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!--     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> -->
    <uses-permission android:name="android.permission.VIBRATE" />

    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.FLASHLIGHT"/>

    <application
        android:name="com.other.util.MyApplication"
        android:icon="@drawable/logo3"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="portrait"
            android:launchMode="singleTask"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

       <receiver android:name="org.nextcoin.pricetracker.NxtPriceWidgetProvider"
           android:label="@string/nxt_price"
           android:icon="@drawable/logo2">
           <intent-filter >
               <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
               <action android:name="org.nextcoin.appWidgetUpdate" />
           </intent-filter>

           <meta-data
               android:name="android.appwidget.provider"
               android:resource="@xml/nxt_price_widget" />
       </receiver>

        <service android:name="org.nextcoin.service.NxtBackgroudService" >
        </service>

<!--         <receiver android:name="com.jhlv.Util.AutoRunBroadcastReceiver" > -->
<!--             <intent-filter> -->
<!--                 <action android:name="android.intent.action.BOOT_COMPLETED" /> -->
<!--             </intent-filter> -->
<!--         </receiver> -->

        <activity
            android:name="org.nextcoin.transactions.TransactionsActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

        <activity
            android:name="org.nextcoin.alias.AliasesActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

        <activity
            android:name="org.nextcoin.transactions.SendCoinsActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

        <activity
            android:name="org.nextcoin.accounts.AccountCreateActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

        <activity
            android:name="org.nextcoin.node.NodesActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

        <activity
            android:name="org.nextcoin.alias.AliasAssignActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

        <activity android:name="org.Zxing.CaptureActivity"
            android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:windowSoftInputMode="stateAlwaysHidden">
        </activity>

        <activity
            android:name="org.nextcoin.message.MessageActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

        <activity
            android:name="org.nextcoin.message.SendMessageActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

        <activity
            android:name="org.nextcoin.message.ChatActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>

    </application>

</manifest>


text:
package com.meg7.emailer;

import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import com.meg7.emailer.util.Constants;
import com.meg7.emailer.util.MLog;
import com.meg7.emailer.util.ProgressPreferenceUtils;
import com.meg7.emailer.util.Scheduler;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Manage how to do each cycle example.
 *
 * @author Mostafa Gazar
 */
public class EmailerManager extends TaskerManager {

    private static final String TAG = EmailerManager.class.getSimpleName();

    public static final int MAX_TASKS_PER_DAY = 4;

    public static final int MAX_RECIPIENTS_PER_EMAIL = 5;
//    public static final int MAX_EMAILS_PER_CYCLE = 25;
//    public static final int MAX_EMAILS_PER_DAY = 100;

    public EmailerManager(Context context) {
        super(context);
    }

    @Override
    public int processCycleAndScheduleNext() {
        int result =  super.processCycleAndScheduleNext();

        LocalBroadcastManager.getInstance(mContext).
                sendBroadcast(new Intent(Constants.ACTION_PROGRESS));

        return result;
    }

    @Override
    protected void processCycle(int cycle) {
        // Do your thing here.
        final String username = PreferenceUtils.getEmailUsername(mContext);
        final String password = PreferenceUtils.getEmailPassword(mContext);
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            // TODO :: Populate some sort of error to UI.
            return;
        }

        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        MLog.v(TAG, "Session created for :: " + username);

        final String fromEmail = PreferenceUtils.getFromEmail(mContext);
        final String fromName = PreferenceUtils.getFromName(mContext);
        final String subject = PreferenceUtils.getEmailSubject(mContext);
        final String message = PreferenceUtils.getEmailMessage(mContext);

        List<String> all = readEmailsFromFile(cycle + ".txt");
        List<String> emails;
        List<Message> messages = new ArrayList<Message>();

        int size = all.size();
        int messagesCount = (int) Math.ceil(size / (MAX_RECIPIENTS_PER_EMAIL * 1d));
        MLog.v(TAG, "Emails :: " + size + ", messages count :: " + messagesCount);
        MLog.v(TAG, "Creating messages");
        for (int i = 0; i < messagesCount; i ++) {
            try {
                emails = all.subList(i * MAX_RECIPIENTS_PER_EMAIL, Math.min(i * MAX_RECIPIENTS_PER_EMAIL + MAX_RECIPIENTS_PER_EMAIL, size));

                messages.add(createMessage(emails, fromEmail, fromName, subject, message, session));
            } catch (Exception e) {
                MLog.e(TAG, e.toString());
            }

        }

        sendMessages(messages);

        // Reschedule the alarm
        if (getCyclesProcessedTodaySoFar() < EmailerManager.MAX_TASKS_PER_DAY) {
            Scheduler.scheduleNextWake(mContext);
        } else {
            Scheduler.scheduleNextWake(mContext, Constants.THRESHOLD_DAY);

            resetCyclesProcessedTodaySoFar();
        }
    }

    @Override
    public int getCyclesCount() {
        try {
            return mContext.getAssets().list("tasks").length;
        } catch (IOException ignore) {
            return 0;
        }
    }

    private List<String> readEmailsFromFile(String fileName) {
        List<String> emails = new ArrayList<String>();

        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = mContext.getAssets().open("tasks" + File.separator + fileName);
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                emails.add(line);
            }
        } catch (Exception e) {
            MLog.e(TAG, e.toString());
        } finally {
            if (inputStream != null) try { inputStream.close(); } catch (IOException e) { }
            if (reader != null) try { reader.close(); } catch (IOException e) { }
        }

        return emails;
    }

    private Message createMessage(List<String> emails,
                                  String fromEmail, String fromName,
                                  String subject, String text,
                                  Session session) throws MessagingException, UnsupportedEncodingException {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail, fromName));
        for (String email : emails) {
            message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email, email));
        }
        message.setSubject(subject);
        message.setText(text);
        return message;
    }

    private void sendMessages(List<Message> messages) {
        resetProgress(mContext);

        int position = 0;
        int count = messages.size();
        for (Message message : messages) {
            position += 1;

            try {
                Transport.send(message);

                ProgressPreferenceUtils.incrementSentCount(mContext);
            } catch (Exception e) {
                ProgressPreferenceUtils.incrementFailedCount(mContext);

                MLog.e(TAG, e.toString());
            }

            ProgressPreferenceUtils.setProgressPercentage(mContext, position * 100 / count);

            if (!TaskerHelper.isTaskerRunning(mContext)) {
                resetProgress(mContext);
                return;
            }

            LocalBroadcastManager.getInstance(mContext).
                    sendBroadcast(new Intent(Constants.ACTION_PROGRESS));
        }
    }

    public static void resetProgress(Context context) {
        ProgressPreferenceUtils.setProgressPercentage(context, 0);
        ProgressPreferenceUtils.setSentCount(context, 0);
        ProgressPreferenceUtils.setFailedCount(context, 0);

        LocalBroadcastManager.getInstance(context).
                sendBroadcast(new Intent(Constants.ACTION_PROGRESS));
    }

    public static class PreferenceUtils {

        public static final String PREF_EMAIL_USERNAME = "emailUsername";
        public static final String PREF_EMAIL_PASSWORD = "emailPassword";

        public static final String PREF_FROM_EMAIL = "fromEmail";
        public static final String PREF_FROM_NAME = "fromName";
        public static final String PREF_EMAIL_SUBJECT  = "emailSubject";
        public static final String PREF_EMAIL_MESSAGE  = "emailMessage";

        private static String getPrefValue(Context context, String key, String defaultValue) {
            return PreferenceManager.getDefaultSharedPreferences(context).
                    getString(key, defaultValue);
        }
        private static void setPrefValue(Context context, String key, String value) {
            PreferenceManager.getDefaultSharedPreferences(context).
                    edit().
                    putString(key, value).
                    commit();
        }

        public static String getEmailUsername(Context context) {
            return getPrefValue(context, PREF_EMAIL_USERNAME, context.getString(R.string.default_email));
        }
        public static void setEmailUsername(Context context, String username) {
            setPrefValue(context, PREF_EMAIL_USERNAME, username);
        }

        public static String getEmailPassword(Context context) {
            return getPrefValue(context, PREF_EMAIL_PASSWORD, context.getString(R.string.default_password));
        }
        public static void setEmailPassword(Context context, String password) {
            setPrefValue(context, PREF_EMAIL_PASSWORD, password);
        }

        public static String getFromEmail(Context context) {
            return getPrefValue(context, PREF_FROM_EMAIL, context.getString(R.string.default_from_email));
        }
        public static void setFromEmail(Context context, String fromEmail) {
            setPrefValue(context, PREF_FROM_EMAIL, fromEmail);
        }

        public static String getFromName(Context context) {
            return getPrefValue(context, PREF_FROM_NAME, context.getString(R.string.default_from_name));
        }
        public static void setFromName(Context context, String fromName) {
            setPrefValue(context, PREF_FROM_NAME, fromName);
        }

        public static String getEmailSubject(Context context) {
            return getPrefValue(context, PREF_EMAIL_SUBJECT, context.getString(R.string.default_subject));
        }
        public static void setEmailSubject(Context context, String subject) {
            setPrefValue(context, PREF_EMAIL_SUBJECT, subject);
        }

        public static String getEmailMessage(Context context) {
            return getPrefValue(context, PREF_EMAIL_MESSAGE, context.getString(R.string.default_message));
        }
        public static void setEmailMessage(Context context, String message) {
            setPrefValue(context, PREF_EMAIL_MESSAGE, message);
        }

    }

}


text:
desired_path="/var/www/html" #you can change this if need be

#CRC info to gather files
webpage_url="CURL URL HERE !!!!!!!!!!!!!"

#Local info to mv files to protected areas
psword="LOCAL PASSWORD OR CHANGE SUDOERS FILE!!!!!!!!!!!"
long_file="long_nodes.txt" #These can stay this way
debug_file="debug_nodes.txt" # "

#Creating dirs moving files to proper locations
echo "Creating Debug, Long, and Pending directories in $desired_path . . ."

echo $psword | sudo -S mkdir $desired_path/Debug
echo $psword | sudo -S mkdir $desired_path/Long
echo $psword | sudo -S mkdir $desired_path/Pending

#Creating Memory-Dir's
echo $psword | sudo -S mkdir $desired_path/Debug-memory
echo $psword | sudo -S mkdir $desired_path/Long-memory

echo "Moving index's to their rightful places . . ."
echo $psword | sudo -S cp index-long.php $desired_path/Long/index.php
echo $psword | sudo -S cp index-long.php $desired_path/Long-memory/index.php
echo $psword | sudo -S cp index-debug.php $desired_path/Debug/index.php
echo $psword | sudo -S cp index-debug.php $desired_path/Debug-memory/index.php
echo $psword | sudo -S cp index-pending.php $desired_path/Pending/index.php

echo "Transferring templates to $desired_path . . ."
echo $psword | sudo -S cp -r templates $desired_path/templates

echo "Transferring styles.css to $desired_path . . ."
echo $psword | sudo -S cp styles.css $desired_path/

echo "Gathering node-list files from $webpage_url . . ."
curl -o debug_nodes.txt $webpage_url/debug_node_list.html
curl -o long_nodes.txt $webpage_url/long_node_list.html

# Creating and initialiizing each node's dir etc
#Long-queue nodes
echo "Creating each node's dir at $desired_path/Long . . ."
while IFS= read -r line
do
        echo $psword | sudo -S mkdir $desired_path/Long/$line
        echo $psword | sudo -S cp sub-index.php $desired_path/Long/$line/index.php
done < "$long_file"

echo "Creating each node's dir at $desired_path/Debug . . ."

#Debug-queue nodes
while IFS= read -r line
do
        echo $psword | sudo -S mkdir $desired_path/Debug/$line
        echo $psword | sudo -S cp sub-index.php $desired_path/Debug/$line/index.php
done < "$debug_file"

echo "-----------------------COMPLETE-----------------------"
echo ""

echo "Setup complete. Please quickly verify everything was made correctly."
echo "You can do this by opening a browser and going to localhost and navigating"
echo "to your Long or Debug directories."
echo ""
echo "Please be sure that the python script is running on a front end, and that"
echo "all scripts are configured to the location the script is going to be spitting"
echo "out at."
echo ""
echo "Once you know things are where they should be, make sure you configured the"
echo "grab_queue_files.sh script for your info to grab the files."
echo "If it is configured already, either of the two lines to crontab -e:"
echo "If you chose method(1) as described in README, add this to cron:"
echo "*/2 * * * * $(pwd)/grab_queue_files.sh"
echo ""
echo "If you chose method(2), add this to cron:"
echo "*/2 * * * * $(pwd)/curl_queue_files.sh"


text:
package picklesjar.pickledbeans.ut.jp.when;

import java.util.function.BiConsumer;
import java.util.function.Consumer;

import javax.annotation.Nonnull;

import picklesjar.pickle.ut.core.IllegalTestStateException;
import picklesjar.pickledbeans.ut.then.AsserThatResultIs;
import picklesjar.pickledbeans.ut.when.ExecuteTargetingFunction;
import cucumber.api.java.en.When;

public class 実行対象の処理を実行
	extends ExecuteTargetingFunction {

	@When( "^実行対象の処理を実行(パラメータ:なし)$" )
	public void execute() {

		execute( super::execute, ( Object[] )null );
	}

	@When( "^実行対象の処理を実行(パラメータ:null)$" )
	public void executeWith1NullParam() {

		execute( super::execute, new Object[] { null } );
	}

	@When( "^実行対象の処理を実行(パラメータ:(true|True|TRUE|false|False|FALSE))$" )
	public void execute( boolean arg ) {

		execute( super::execute, arg );
	}

	@When( "^実行対象の処理を実行(パラメータ:(\"(.*?)\"))$" )
	public void execute( String arg ) {

		execute( super::execute, arg );
	}

	@When( "^実行対象の処理を実行(パラメータ:なし)、処理結果を保持$" )
	public void executeAndPutToResult() {

		execute( super::executeAndPutTo, AsserThatResultIs.DEFAULT_RESULT_KEY, ( Object[] )null );
	}

	@When( "^実行対象の処理を実行(パラメータ:null)、処理結果を保持$" )
	public void executeWith1NullParamAndPutToResult() {

		execute( super::executeAndPutTo, AsserThatResultIs.DEFAULT_RESULT_KEY, new Object[] { null } );
	}

	@When( "^実行対象の処理を実行(パラメータ:(true|True|TRUE|false|False|FALSE))、処理結果を保持$" )
	public void executeAndPutToResult( boolean arg ) {

		execute( super::executeAndPutTo, AsserThatResultIs.DEFAULT_RESULT_KEY, arg );
	}

	@When( "^実行対象の処理を実行(パラメータ:(\"(.*?)\"))、処理結果を保持$" )
	public void executeAndPutToResult( String arg ) {

		execute( super::executeAndPutTo, AsserThatResultIs.DEFAULT_RESULT_KEY, arg );
	}

	@When( "^実行対象の処理を実行(パラメータ:なし)、処理結果を保持(alias:\"(.+?)\")$" )
	public void executeAndPutTo( String alias ) {

		execute( super::executeAndPutTo, alias, ( Object[] )null );
	}

	@When( "^実行対象の処理を実行(パラメータ:null)、処理結果を保持(alias:\"(.+?)\")$" )
	public void executeWith1NullParamAndPutTo( String alias ) {

		execute( super::executeAndPutTo, alias, new Object[] { null } );
	}

	@When( "^実行対象の処理を実行(パラメータ:(true|True|TRUE|false|False|FALSE))、処理結果を保持(alias:\"(.+?)\")$" )
	public void executeAndPutTo( boolean arg, String alias ) {

		execute( super::executeAndPutTo, alias, arg );
	}

	@When( "^実行対象の処理を実行(パラメータ:(\"(.*?)\"))、処理結果を保持(alias:\"(.+?)\")$" )
	public void executeAndPutTo( String arg, String alias ) {

		execute( super::executeAndPutTo, alias, arg );
	}

	protected < T > void execute( @Nonnull BiConsumer< String, T > function, String alias, T arg ) {

		try {
			function.accept( alias, arg );
		} catch( IllegalTestStateException exp ) {
			throw distributeThrowcaseMessage( exp );
		}
	}

	protected < T > void execute( @Nonnull Consumer< T > function, T arg ) {

		try {
			function.accept( arg );
		} catch( IllegalTestStateException exp ) {
			throw distributeThrowcaseMessage( exp );
		}
	}

	/**
	 * 例外発生時のメッセージ振り分け処理.
	 *
	 * @param exp
	 *            振り分けの根拠となる情報を保持する例外
	 * @return メッセージを付与してそういつ例外でラップした新しい例外インスタンス
	 */
	protected IllegalTestStateException distributeThrowcaseMessage( @Nonnull IllegalTestStateException exp ) {

		IllegalTestStateException result = null;
		switch( exp.getCode() ) {

			case CODE_OF_EMPTY_TARGET_CLASS_INSTANCE :
				result = new IllegalTestStateException(
					"テスト対象クラスのインスタンスが生成されていません。", exp );
				break;

			case CODE_OF_EMPTY_TARGET_INSTANCE :
				result = new IllegalTestStateException(
					"処理を参照できませんでした。", exp );
				break;

			case CODE_OF_FAILED_TO_EXECUTE :
				result = new IllegalTestStateException(
					"処理の実行に失敗しました。", exp );
				break;

			default :
				result = new IllegalTestStateException(
					"処理に失敗しました。", exp );
				break;
		}

		return result;
	}

}


text:
package com.adbourne.geo.readers.impl;

import com.adbourne.geo.domain.DbfField;
import com.adbourne.geo.domain.DbfFileMetadata;
import com.adbourne.geo.readers.DbfFileReader;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;

import static com.adbourne.geo.util.FileChannelUtil.*;

@Slf4j
public class DefaultDbfFileReader implements DbfFileReader {

    public DbfFileMetadata readMetadata(File dbfFile) throws IOException {

        if (dbfFile.exists()) {

            try (FileChannel fileChannel = new FileInputStream(dbfFile).getChannel()) {
                // Skip 4 bytes
                fileChannel.read(byteBuffer(4, ByteOrder.LITTLE_ENDIAN));

                // Number of record
                int numberOfRecords = readInt(fileChannel, ByteOrder.LITTLE_ENDIAN);

                // Dbf header length
                short headerLength = readShort(fileChannel, ByteOrder.LITTLE_ENDIAN);

                // Dbf record length
                short recordLength = readShort(fileChannel, ByteOrder.LITTLE_ENDIAN);

                // Skip 8 bytes
                fileChannel.read(byteBuffer(8, ByteOrder.LITTLE_ENDIAN));

                int numberOfFields = ((Double) ((headerLength - 33) / 32.0)).intValue();
                DbfField[] fields = new DbfField[numberOfFields];
                for (int i = 0; i < numberOfFields; i++) {
                    fields[i] = readDbfField(fileChannel);
                }

                return DbfFileMetadata.builder()
                        .dbfFields(fields)
                        .dbfNumRecords(numberOfRecords)
                        .dbfHeaderLength(headerLength)
                        .dbfRecordLength(recordLength)
                        .build();
            }
        } else {
            throw new FileNotFoundException(String.format("File '%s' does not exist", dbfFile.getCanonicalPath()));
        }
    }

    private DbfField readDbfField(FileChannel fileChannel) throws IOException {
        String name = readString(fileChannel, ByteOrder.LITTLE_ENDIAN, 11);

        byte fieldType = readBytes(fileChannel, ByteOrder.LITTLE_ENDIAN, 1)[0];

        byte[] address = readBytes(fileChannel, ByteOrder.LITTLE_ENDIAN, 4);

        int size = readInt(fileChannel, ByteOrder.LITTLE_ENDIAN);

        int precision = readInt(fileChannel, ByteOrder.LITTLE_ENDIAN);

        byte[] padding = readBytes(fileChannel, ByteOrder.LITTLE_ENDIAN, 14);

        return DbfField.builder()
                .name(name)
                .fieldType(fieldType)
                .address(address)
                .size(size)
                .precision(precision)
                .padding(padding)
                .build();
    }

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-548
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.12 at 10:26:14 AM CST
//

package com.mastercard.api.partnerwallet.domain.all;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ExpressCheckoutResponse complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ExpressCheckoutResponse">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Checkout" type="{}Checkout" minOccurs="0"/>
 *         <element name="LongAccessToken" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="Errors" type="{}Errors" minOccurs="0"/>
 *         <element name="ExtensionPoint" type="{}ExtensionPoint" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ExpressCheckoutResponse", propOrder = {
    "checkout",
    "longAccessToken",
    "errors",
    "extensionPoint"
})
public class ExpressCheckoutResponse {

    @XmlElement(name = "Checkout")
    protected Checkout checkout;
    @XmlElement(name = "LongAccessToken", required = true)
    protected String longAccessToken;
    @XmlElement(name = "Errors")
    protected Errors errors;
    @XmlElement(name = "ExtensionPoint")
    protected ExtensionPoint extensionPoint;

    /**
     * Gets the value of the checkout property.
     *
     * @return
     *     possible object is
     *     {@link Checkout }
     *
     */
    public Checkout getCheckout() {
        return checkout;
    }

    /**
     * Sets the value of the checkout property.
     *
     * @param value
     *     allowed object is
     *     {@link Checkout }
     *
     */
    public void setCheckout(Checkout value) {
        this.checkout = value;
    }

    /**
     * Gets the value of the longAccessToken property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLongAccessToken() {
        return longAccessToken;
    }

    /**
     * Sets the value of the longAccessToken property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLongAccessToken(String value) {
        this.longAccessToken = value;
    }

    /**
     * Gets the value of the errors property.
     *
     * @return
     *     possible object is
     *     {@link Errors }
     *
     */
    public Errors getErrors() {
        return errors;
    }

    /**
     * Sets the value of the errors property.
     *
     * @param value
     *     allowed object is
     *     {@link Errors }
     *
     */
    public void setErrors(Errors value) {
        this.errors = value;
    }

    /**
     * Gets the value of the extensionPoint property.
     *
     * @return
     *     possible object is
     *     {@link ExtensionPoint }
     *
     */
    public ExtensionPoint getExtensionPoint() {
        return extensionPoint;
    }

    /**
     * Sets the value of the extensionPoint property.
     *
     * @param value
     *     allowed object is
     *     {@link ExtensionPoint }
     *
     */
    public void setExtensionPoint(ExtensionPoint value) {
        this.extensionPoint = value;
    }

}


text:
package google

import (
	"fmt"
	"strings"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccOrgPolicyCustomConstraint_orgPolicyCustomConstraintBasicExample(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"org_id":        getTestOrgFromEnv(t),
		"random_suffix": randString(t, 10),
	}

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProvidersOiCS,
		CheckDestroy: testAccCheckOrgPolicyCustomConstraintDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccOrgPolicyCustomConstraint_orgPolicyCustomConstraintBasicExample(context),
			},
			{
				ResourceName:            "google_org_policy_custom_constraint.constraint",
				ImportState:             true,
				ImportStateVerify:       true,
				ImportStateVerifyIgnore: []string{"parent"},
			},
		},
	})
}

func testAccOrgPolicyCustomConstraint_orgPolicyCustomConstraintBasicExample(context map[string]interface{}) string {
	return Nprintf(`
resource "google_org_policy_custom_constraint" "constraint" {
  provider = google-beta

  name         = "custom.disableGkeAutoUpgrade"
  parent       = "organizations/%{org_id}"

  action_type    = "ALLOW"
  condition      = "resource.management.autoUpgrade == false"
  method_types   = ["CREATE", "UPDATE"]
  resource_types = ["container.googleapis.com/NodePool"]
}
`, context)
}

func TestAccOrgPolicyCustomConstraint_orgPolicyCustomConstraintFullExample(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"org_id":        getTestOrgTargetFromEnv(t),
		"random_suffix": randString(t, 10),
	}

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProvidersOiCS,
		CheckDestroy: testAccCheckOrgPolicyCustomConstraintDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccOrgPolicyCustomConstraint_orgPolicyCustomConstraintFullExample(context),
			},
			{
				ResourceName:            "google_org_policy_custom_constraint.constraint",
				ImportState:             true,
				ImportStateVerify:       true,
				ImportStateVerifyIgnore: []string{"parent"},
			},
		},
	})
}

func testAccOrgPolicyCustomConstraint_orgPolicyCustomConstraintFullExample(context map[string]interface{}) string {
	return Nprintf(`
resource "google_org_policy_custom_constraint" "constraint" {
  provider = google-beta

  name         = "custom.disableGkeAutoUpgrade"
  parent       = "organizations/%{org_id}"
  display_name = "Disable GKE auto upgrade"
  description  = "Only allow GKE NodePool resource to be created or updated if AutoUpgrade is not enabled where this custom constraint is enforced."

  action_type    = "ALLOW"
  condition      = "resource.management.autoUpgrade == false"
  method_types   = ["CREATE", "UPDATE"]
  resource_types = ["container.googleapis.com/NodePool"]
}

resource "google_org_policy_policy" "bool" {
  provider = google-beta

  name   = "organizations/%{org_id}/policies/${google_org_policy_custom_constraint.constraint.name}"
  parent = "organizations/%{org_id}"

  spec {
    rules {
      enforce = "TRUE"
    }
  }
}
`, context)
}

func testAccCheckOrgPolicyCustomConstraintDestroyProducer(t *testing.T) func(s *terraform.State) error {
	return func(s *terraform.State) error {
		for name, rs := range s.RootModule().Resources {
			if rs.Type != "google_org_policy_custom_constraint" {
				continue
			}
			if strings.HasPrefix(name, "data.") {
				continue
			}

			config := googleProviderConfig(t)

			url, err := replaceVarsForTest(config, rs, "{{OrgPolicyBasePath}}{{parent}}/customConstraints/{{name}}")
			if err != nil {
				return err
			}

			billingProject := ""

			if config.BillingProject != "" {
				billingProject = config.BillingProject
			}

			_, err = sendRequest(config, "GET", billingProject, url, config.userAgent, nil)
			if err == nil {
				return fmt.Errorf("OrgPolicyCustomConstraint still exists at %s", url)
			}
		}

		return nil
	}
}


text:
package org.mockito.internal.stubbing.defaultanswers;

import java.io.Serializable;
import java.lang.reflect.Array;

import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/**
 * It's likely this implementation will be used by default by every Mockito 2.0 mock.
 *

 * Currently used only by {@link Mockito#RETURNS_SMART_NULLS}
 *

 * Current version of Mockito mocks by deafult use {@link ReturnsEmptyValues}
 *

 *

 *  Returns appropriate primitive for primitive-returning methods
 *

 *

 *  Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 and Integer-returning method returns 0, too)
 *

 *

 *  Returns empty collection for collection-returning methods (works for most commonly used collection types)
 *

 *

 *  Returns empty array for array-returning methods
 *

 *

 *  Returns "" for String-returning method
 *

 *

 *  Returns description of mock for toString() method
 *

 *

 *  Returns non-zero for Comparable#compareTo(T other) method (see issue 184)
 *

 *

 *  Returns null for everything else
 *

 *

 */
public class ReturnsMoreEmptyValues implements Answer<Object>, Serializable {

    private static final long serialVersionUID = -2816745041482698471L;
    private Answer<Object> delegate = new ReturnsEmptyValues();

    /* (non-Javadoc)
     * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
     */
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Object ret = delegate.answer(invocation);
        if (ret != null) {
            return ret;
        }

        Class<?> returnType = invocation.getMethod().getReturnType();
        return returnValueFor(returnType);
    }

    Object returnValueFor(Class<?> type) {
        if (type == String.class) {
            return "";
        }  else if (type.isArray()) {
            Class<?> componenetType = type.getComponentType();
            return Array.newInstance(componenetType, 0);
        }
        return null;
    }
}


text:
module RestPack::Account::Service
  class Tasks
    def self.load_tasks
      load "restpack_account_service/tasks/db.rake"
    end
  end
end


text:
package com.netflix.astyanax.thrift.ddl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.KsDef;
import org.apache.cassandra.thrift.KsDef._Fields;
import org.apache.thrift.meta_data.FieldMetaData;

import com.google.common.collect.Maps;
import com.netflix.astyanax.ddl.ColumnFamilyDefinition;
import com.netflix.astyanax.ddl.FieldMetadata;
import com.netflix.astyanax.ddl.KeyspaceDefinition;
import com.netflix.astyanax.thrift.ThriftTypes;

public class ThriftKeyspaceDefinitionImpl implements KeyspaceDefinition {
    private final static Map<String, FieldMetadata> fieldsMetadata = Maps.newHashMap();

    {
        for (Entry<_Fields, FieldMetaData> field : KsDef.metaDataMap.entrySet()) {
            fieldsMetadata.put(
                    field.getValue().fieldName,
                    new FieldMetadata(
                        field.getKey().name(),
                        ThriftTypes.values()[field.getValue().valueMetaData.type].name(),
                        field.getValue().valueMetaData.isContainer()));
        }
    }

    protected KsDef ks_def;

    public ThriftKeyspaceDefinitionImpl() {
        ks_def = new KsDef();
        ks_def.setCf_defs(new ArrayList<CfDef>());
    }

    public ThriftKeyspaceDefinitionImpl(KsDef ks_def) {
        this.ks_def = ks_def;
    }

    public KsDef getThriftKeyspaceDefinition() {
        return ks_def;
    }

    @Override
    public KeyspaceDefinition setName(String name) {
        ks_def.setName(name);
        return this;
    }

    @Override
    public String getName() {
        return ks_def.getName();
    }

    @Override
    public KeyspaceDefinition setStrategyClass(String strategyClass) {
        ks_def.setStrategy_class(strategyClass);
        return this;
    }

    @Override
    public String getStrategyClass() {
        return ks_def.getStrategy_class();
    }

    @Override
    public KeyspaceDefinition setStrategyOptions(Map<String, String> options) {
        ks_def.setStrategy_options(options);
        return this;
    }

    @Override
    public Map<String, String> getStrategyOptions() {
        if (ks_def.getStrategy_options() == null) {
            ks_def.strategy_options = new HashMap<String, String>();
        }
        return ks_def.getStrategy_options();
    }

    @Override
    public KeyspaceDefinition addStrategyOption(String name, String value) {
        getStrategyOptions().put(name, value);
        return this;
    }

    @Override
    public KeyspaceDefinition addColumnFamily(ColumnFamilyDefinition cfDef) {
        if (ks_def.getCf_defs() == null) {
            ks_def.setCf_defs(new ArrayList<CfDef>());
        }

        CfDef thriftCfDef = ((ThriftColumnFamilyDefinitionImpl) cfDef).getThriftColumnFamilyDefinition();
        thriftCfDef.setColumn_type("Standard");
        thriftCfDef.setKeyspace(ks_def.getName());
        ks_def.getCf_defs().add(thriftCfDef);
        return this;
    }

    @Override
    public List<ColumnFamilyDefinition> getColumnFamilyList() {
        List<CfDef> cfdefs = ks_def.getCf_defs();
        List<ColumnFamilyDefinition> list = new ArrayList<ColumnFamilyDefinition>();
        for (CfDef cfdef : cfdefs) {
            list.add(new ThriftColumnFamilyDefinitionImpl(cfdef));
        }
        return list;
    }

    @Override
    public ColumnFamilyDefinition getColumnFamily(String columnFamily) {
        for (CfDef cfdef : ks_def.getCf_defs()) {
            if (cfdef.getName().equalsIgnoreCase(columnFamily)) {
                return new ThriftColumnFamilyDefinitionImpl(cfdef);
            }
        }
        return null;
    }

    @Override
    public Collection<String> getFieldNames() {
        return fieldsMetadata.keySet();
    }

    @Override
    public Object getFieldValue(String name) {
        return ks_def.getFieldValue(_Fields.valueOf(name));
    }

    @Override
    public KeyspaceDefinition setFieldValue(String name, Object value) {
        ks_def.setFieldValue(_Fields.valueOf(name), value);
        return this;
    }

    @Override
    public Collection<FieldMetadata> getFieldsMetadata() {
        return fieldsMetadata.values();
    }

    @Override
    public void setFields(Map<String, Object> options) {
        for (Entry<String, FieldMetadata> field : fieldsMetadata.entrySet()) {
            String fieldName = field.getKey();
            if (options.containsKey(fieldName)) {
                setFieldValue(field.getValue().getName(), options.get(fieldName));
            }
        }
    }
}


text:
package org.esupportail.portlet.filemanager.services.evaluators;

import java.util.Map;

import javax.portlet.PortletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * @author GIP RECIA - Julien Gribonvald
 * 14 oct. 2013
 */
public class UserAttributesEvaluator implements IDriveAccessEvaluator, InitializingBean {

	public enum Mode {
		CONTAINS,
		EQUALS,
		STARTS_WITH,
		ENDS_WITH,
		EXISTS,
		MATCH,
	}

	/** Logger. */
	private static final Log log =  LogFactory.getLog(UserAttributesEvaluator.class);

	/** The portlet preference attribute. */
	private String attribute;
	/** The portlet preference value. */
	private String value;
	/** The mode to evaluate the attribute. */
	private Mode mode;

	/**
	 * Contructor of the object UserAttributesEvaluator.java.
	 */
	public UserAttributesEvaluator() {
		super();
	}

	/**
	 * Contructor of the object UserAttributesEvaluator.java.
	 * @param mode The String comparator type.
	 */
	public UserAttributesEvaluator(final String mode) {
		this.mode = Mode.valueOf(mode);
	}

	/**
	 * Contructor of the object UserAttributesEvaluator.java.
	 * @param attribute The User Attribute to get for evaluation.
	 * @param value The value to compare.
	 * @param mode The String comparator type.
	 */
	public UserAttributesEvaluator(final String attribute, final String value, final String mode) {
		this.attribute = attribute;
		this.value = value;
		this.mode = Mode.valueOf(mode);
	}

	/**
	 * @see org.esupportail.portlet.filemanager.services.evaluators.IDriveAccessEvaluator#isApplicable(javax.portlet.PortletRequest)
	 */
	public boolean isApplicable(PortletRequest request) {
		final Map<String, String> userInfos = (Map<String, String>) request.getAttribute(PortletRequest.USER_INFO);
		if (userInfos == null)
			return false;

		final String attrib = userInfos.get(attribute);

		if (log.isDebugEnabled()) {
			log.debug("value=" + value + ",mode=" + mode + ",attrib=" + attrib);
		}

		// for tests other than 'exists' the attribute must be defined
		if ( attrib == null && !Mode.EXISTS.equals(mode) )
			return false;

		if ( Mode.EQUALS.equals(mode) )
			return attrib.equals( value );
		if ( Mode.EXISTS.equals(mode) )
			return attrib != null;
		if ( Mode.STARTS_WITH.equals(mode) )
			return attrib.startsWith( value );
		if ( Mode.ENDS_WITH.equals(mode) )
			return attrib.endsWith( value );
		if ( Mode.CONTAINS.equals(mode) )
			return (attrib.indexOf( value ) != -1 );
		if ( Mode.MATCH.equals(mode) )
			return attrib.matches(value);
		// will never get here
		return false;
	}

	/**
	 * Getter of member attribute.
	 * @return String the attribute attribute
	 */
	public String getAttribute() {
		return attribute;
	}

	/**
	 * Setter of attribute attribute.
	 * @param attribute the attribute attribute to set
	 */
	public void setAttribute(final String attribute) {
		this.attribute = attribute;
	}

	/**
	 * Getter of member value.
	 * @return String the attribute value
	 */
	public String getValue() {
		return value;
	}

	/**
	 * Setter of attribute value.
	 * @param value the attribute value to set
	 */
	public void setValue(final String value) {
		this.value = value;
	}

	/**
	 * Getter of member mode.
	 * @return Mode the attribute mode
	 */
	public Mode getMode() {
		return mode;
	}

	/**
	 * Setter of attribute mode.
	 * @param mode the attribute mode to set
	 */
	public void setMode(final Mode mode) {
		this.mode = mode;
	}

	/**
	 * Setter of attribute mode.
	 * @param mode the attribute mode to set
	 */
	public void setMode(final String mode) {
		this.mode = Mode.valueOf(mode);
	}

	/**
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws Exception {
		Assert.hasLength(attribute, "The portlet Attribute to evaluate must be set !");
		Assert.hasLength(value, "The value to compare must be set !");
		Assert.notNull(mode, "The comparison mode must not be null !");
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("UserAttributesEvaluator [attribute=");
		builder.append(attribute);
		builder.append(", value=");
		builder.append(value);
		builder.append(", mode=");
		builder.append(mode);
		builder.append("]");
		return builder.toString();
	}

}


text:
package hu.akarnokd.rxjava2.internal.util;

import java.util.concurrent.atomic.*;

import hu.akarnokd.rxjava2.functions.*;

/**
 * Helper class to handle copy-on-write arrays plus terminal state for arbitrary references.
 */
public enum TerminalAtomicsHelper {
    ;

    /**
     * Atomically swaps in the terminalValue and calls the given callback if not already terminated.
     * @param <T> the instance type
     * @param <U> the reference type
     * @param updater
     * @param instance
     * @param terminalValue
     * @param onTerminate
     */
    public static <T, U> void terminate(AtomicReferenceFieldUpdater<T, U> updater,
            T instance, U terminalValue, Consumer<? super U> onTerminate) {
        U a = updater.get(instance);
        if (a != terminalValue) {
            a = updater.getAndSet(instance, terminalValue);
            if (a != terminalValue && a != null) {
                onTerminate.accept(a);
            }
        }
    }

    /**
     * Atomically swaps in the terminalValue and calls the given callback if not already terminated.
     * @param <U> the reference type
     * @param instance
     * @param terminalValue
     * @param onTerminate
     */
    public static <U> void terminate(AtomicReference<U> instance,
            U terminalValue, Consumer<? super U> onTerminate) {
        U a = instance.get();
        if (a != terminalValue) {
            a = instance.getAndSet(terminalValue);
            if (a != terminalValue && a != null) {
                onTerminate.accept(a);
            }
        }
    }

    /**
     * Atomically swaps in the terminal value and returns the previous value.
     * @param <T> the instance type
     * @param <U> the reference type
     * @param updater
     * @param instance
     * @param terminalValue
     * @return the last value or the terminal value
     */
    public static <T, U> U terminate(AtomicReferenceFieldUpdater<T, U> updater,
            T instance, U terminalValue) {
        U a = updater.get(instance);
        if (a != terminalValue) {
            a = updater.getAndSet(instance, terminalValue);
        }
        return a;
    }

    /**
     * Atomically swaps in the terminal value and returns the previous value.
     * @param <U> the reference type
     * @param instance
     * @param terminalValue
     * @return the last value or the terminal value
     */
    public static <U> U terminate(AtomicReference<U> instance,
            U terminalValue) {
        U a = instance.get();
        if (a != terminalValue) {
            a = instance.getAndSet(terminalValue);
        }
        return a;
    }

    /**
     * Atomically replaces the contents of the instance and calls the callback with the old value
     * or calls the callback with the new value if the instance holds the terminal value.
     * @param <T> the instance type
     * @param <U> the reference type
     * @param updater
     * @param instance
     * @param newValue
     * @param terminalValue
     * @param onTerminate
     * @return false if the instance holds the terminal value
     * @see #update(AtomicReferenceFieldUpdater, Object, Object, Object, Consumer)
     */
    public static <T, U> boolean set(AtomicReferenceFieldUpdater<T, U> updater, T instance,
            U newValue, U terminalValue, Consumer<? super U> onTerminate) {
        for (;;) {
            U a = updater.get(instance);
            if (a == terminalValue) {
                if (newValue != null) {
                    onTerminate.accept(newValue);
                }
                return false;
            }
            if (updater.compareAndSet(instance, a, newValue)) {
                if (a != null) {
                    onTerminate.accept(a);
                }
                return true;
            }
        }
    }

    /**
     * Atomically replaces the contents of the instance and calls the callback with the old value
     * or calls the callback with the new value if the instance holds the terminal value.
     * @param <T> the instance type
     * @param <U> the reference type
     * @param instance
     * @param newValue
     * @param terminalValue
     * @param onTerminate
     * @return false if the instance holds the terminal value
     * @see #update(AtomicReference, Object, Object, Consumer)
     */
    public static <T, U> boolean set(AtomicReference<U> instance,
            U newValue, U terminalValue, Consumer<? super U> onTerminate) {
        for (;;) {
            U a = instance.get();
            if (a == terminalValue) {
                if (newValue != null) {
                    onTerminate.accept(newValue);
                }
                return false;
            }
            if (instance.compareAndSet(a, newValue)) {
                if (a != null) {
                    onTerminate.accept(a);
                }
                return true;
            }
        }
    }

    /**
     * Atomically replaces the content of the instance but calls the callback only if the instance holds
     * the terminal value.
     * @param <T> the instance type
     * @param <U> the reference type
     * @param updater
     * @param instance
     * @param newValue
     * @param terminalValue
     * @param onTerminate
     * @return false if the instance holds the terminal value
     * @see #set(AtomicReferenceFieldUpdater, Object, Object, Object, Consumer)
     */
    public static <T, U> boolean update(AtomicReferenceFieldUpdater<T, U> updater, T instance,
            U newValue, U terminalValue, Consumer<? super U> onTerminate) {
        for (;;) {
            U a = updater.get(instance);
            if (a == terminalValue) {
                if (newValue != null) {
                    onTerminate.accept(newValue);
                }
                return false;
            }
            if (updater.compareAndSet(instance, a, newValue)) {
                return true;
            }
        }
    }

    /**
     * Atomically replaces the content of the instance but calls the callback only if the instance holds
     * the terminal value.
     * @param <T> the instance type
     * @param <U> the reference type
     * @param instance
     * @param newValue
     * @param terminalValue
     * @param onTerminate
     * @return false if the instance holds the terminal value
     * @see #set(AtomicReference, Object, Object, Consumer)
     */
    public static <T, U> boolean update(AtomicReference<U> instance,
            U newValue, U terminalValue, Consumer<? super U> onTerminate) {
        for (;;) {
            U a = instance.get();
            if (a == terminalValue) {
                if (newValue != null) {
                    onTerminate.accept(newValue);
                }
                return false;
            }
            if (instance.compareAndSet(a, newValue)) {
                return true;
            }
        }
    }

    /**
     * Atomically replaces the array in instance with a new array that contains the newValue as well
     * or returns false if the instance holds the terminalValue.
     * @param <T> the instance type
     * @param <U> the reference type
     * @param updater
     * @param instance
     * @param newValue
     * @param terminalValue
     * @param arraySupplier
     * @return true if the add succeeded, false if the instance has terminated
     */
    public static <T, U> boolean add(AtomicReferenceFieldUpdater<T, U[]> updater, T instance,
            U newValue, U[] terminalValue, IntFunction<U[]> arraySupplier) {
        for (;;) {
            U[] a = updater.get(instance);
            if (a == terminalValue) {
                return false;
            }
            int n = a.length;
            U[] b = arraySupplier.apply(n + 1);
            System.arraycopy(a, 0, b, 0, n);
            b[n] = newValue;
            if (updater.compareAndSet(instance, a, b)) {
                return true;
            }
        }
    }

    /**
     * Atomically replaces the array in instance with a new array that contains the newValue as well
     * or returns false if the instance holds the terminalValue.
     * @param <U> the reference type
     * @param instance
     * @param newValue
     * @param terminalValue
     * @param arraySupplier
     * @return true if the add succeeded, false if the instance has terminated
     */
    public static <U> boolean add(AtomicReference<U[]> instance,
            U newValue, U[] terminalValue, IntFunction<U[]> arraySupplier) {
        for (;;) {
            U[] a = instance.get();
            if (a == terminalValue) {
                return false;
            }
            int n = a.length;
            U[] b = arraySupplier.apply(n + 1);
            System.arraycopy(a, 0, b, 0, n);
            b[n] = newValue;
            if (instance.compareAndSet(a, b)) {
                return true;
            }
        }
    }

    /**
     * Atomically replaces the array in instance with a new array that doesn't contain the
     * given value or returns false if the instance holds the terminal state or an empty array
     * or the value is not in the array.
     * @param <T> the instance type
     * @param <U> the reference type
     * @param updater
     * @param instance
     * @param value
     * @param terminalValue
     * @param zeroArray
     * @param arraySupplier
     * @return true if the remove succeeded, false if the instance has terminated
     */
    public static <T, U> boolean remove(AtomicReferenceFieldUpdater<T, U[]> updater, T instance,
            U value, U[] terminalValue, U[] zeroArray, IntFunction<U[]> arraySupplier) {
        for (;;) {
            U[] a = updater.get(instance);
            if (a == terminalValue) {
                return false;
            }
            int n = a.length;
            if (n == 0) {
                return false;
            }
            int j = -1;
            for (int i = 0; i < n; i++) {
                if (a[i] == value) {
                    j = i;
                    break;
                }
            }
            if (j < 0) {
                return false;
            }
            U[] b;
            if (n == 1) {
                b = zeroArray;
            } else {
                b = arraySupplier.apply(n - 1);
                System.arraycopy(a, 0, b, 0, j);
                System.arraycopy(a, j + 1, b, j, n - j - 1);
            }
            if (updater.compareAndSet(instance, a, b)) {
                return true;
            }
        }
    }

    /**
     * Atomically replaces the array in instance with a new array that doesn't contain the
     * given value or returns false if the instance holds the terminal state or an empty array
     * or the value is not in the array.
     * @param <U> the reference type
     * @param reference
     * @param value
     * @param terminalValue
     * @param zeroArray
     * @param arraySupplier
     * @return true if the remove succeeded, false if the instance has terminated
     */
    public static <U> boolean remove(AtomicReference<U[]> reference,
            U value, U[] terminalValue, U[] zeroArray, IntFunction<U[]> arraySupplier) {
        for (;;) {
            U[] a = reference.get();
            if (a == terminalValue) {
                return false;
            }
            int n = a.length;
            if (n == 0) {
                return false;
            }
            int j = -1;
            for (int i = 0; i < n; i++) {
                if (a[i] == value) {
                    j = i;
                    break;
                }
            }
            if (j < 0) {
                return false;
            }
            U[] b;
            if (n == 1) {
                b = zeroArray;
            } else {
                b = arraySupplier.apply(n - 1);
                System.arraycopy(a, 0, b, 0, j);
                System.arraycopy(a, j + 1, b, j, n - j - 1);
            }
            if (reference.compareAndSet(a, b)) {
                return true;
            }
        }
    }
}


text:
CREATE TABLE `ctm_test_folder` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `parentId` bigint(20) unsigned NOT NULL,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `parentId` (`parentId`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=100;


text:
/**
 * External dependencies
 */
import { css } from 'styled-components';

export const transparentBg = css`
  background-image: conic-gradient(
    ${({ theme }) => theme.colors.fg.tertiary} 0.25turn,
    transparent 0turn 0.5turn,
    ${({ theme }) => theme.colors.fg.tertiary} 0turn 0.75turn,
    transparent 0turn 1turn
  );
  background-size: 8px 8px;
`;


text:
This is a chatbot interface above [Neptun Kréta](https://ekreta.hu) so that we can have notifications on new marks (and in the future other events).
When deployed the script runs every 30 minutes and gets all marks from ekreta API and stores them to Amazon DynamoDB. When a record is new, a message is sent about it to Slack about its details.

## Install dependencies

Run `yarn` or `npm install` to install the required packages.

## Running locally

#### Set the folowing environment variables:

```
TF_VAR_username=<your_ekreta_username>
TF_VAR_password=<your_ekreta_password>
TF_VAR_slack_url=<the_slack_api_url_for_your_channel>
```

#### Run package

```node test.js```

## Deploying to AWS

We use Terraform for deploying the required AWS resources. In AWS we set up a lambda function with the content of the current folder, a CloudWatch rule so that the lambda function get called regularly and an API Gateway endpoint that is not currently used.

You can get Terraform command line tool for your OS: from https://www.terraform.io/downloads.html

Besides the variables needed for local usage set the AWS environment variables for deployment:
```
AWS_ACCESS_KEY_ID=<your_AWS_acces_key>
AWS_SECRET_ACCESS_KEY=<your_AWS_secret_key>
AWS_DEFAULT_REGION=<AWS_region_code>
```

DynamoDB table is not yet created by Terraform (although it should be) so it needs to be created manually. (This is needed to be run once)

```
node create_table.js
```

Deployment is basically creating the zip file and running terraform but there is a convenience script for that:

```
yarn deploy
```


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="jp.scriptkidie.datacopy.sql.persistence.educationdb.MediationsMapper" >
  <resultMap id="BaseResultMap" type="jp.scriptkidie.datacopy.sql.model.educationdb.Mediations" >
    <id column="RECEPTION_NO" property="receptionNo" jdbcType="CHAR" />
    <result column="PLACE_NO" property="placeNo" jdbcType="VARCHAR" />
    <result column="USER_ID" property="userId" jdbcType="VARCHAR" />
    <result column="CONTACT_TEL_NO" property="contactTelNo" jdbcType="VARCHAR" />
    <result column="APPROVAL_USER_ID" property="approvalUserId" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    RECEPTION_NO, PLACE_NO, USER_ID, CONTACT_TEL_NO, APPROVAL_USER_ID
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="jp.scriptkidie.datacopy.sql.model.educationdb.MediationsExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from MEDIATIONS
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select
    <include refid="Base_Column_List" />
    from MEDIATIONS
    where RECEPTION_NO = #{receptionNo,jdbcType=CHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from MEDIATIONS
    where RECEPTION_NO = #{receptionNo,jdbcType=CHAR}
  </delete>
  <delete id="deleteByExample" parameterType="jp.scriptkidie.datacopy.sql.model.educationdb.MediationsExample" >
    delete from MEDIATIONS
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="jp.scriptkidie.datacopy.sql.model.educationdb.Mediations" >
    insert into MEDIATIONS (RECEPTION_NO, PLACE_NO, USER_ID,
      CONTACT_TEL_NO, APPROVAL_USER_ID)
    values (#{receptionNo,jdbcType=CHAR}, #{placeNo,jdbcType=VARCHAR}, #{userId,jdbcType=VARCHAR},
      #{contactTelNo,jdbcType=VARCHAR}, #{approvalUserId,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="jp.scriptkidie.datacopy.sql.model.educationdb.Mediations" >
    insert into MEDIATIONS
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="receptionNo != null" >
        RECEPTION_NO,
      </if>
      <if test="placeNo != null" >
        PLACE_NO,
      </if>
      <if test="userId != null" >
        USER_ID,
      </if>
      <if test="contactTelNo != null" >
        CONTACT_TEL_NO,
      </if>
      <if test="approvalUserId != null" >
        APPROVAL_USER_ID,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="receptionNo != null" >
        #{receptionNo,jdbcType=CHAR},
      </if>
      <if test="placeNo != null" >
        #{placeNo,jdbcType=VARCHAR},
      </if>
      <if test="userId != null" >
        #{userId,jdbcType=VARCHAR},
      </if>
      <if test="contactTelNo != null" >
        #{contactTelNo,jdbcType=VARCHAR},
      </if>
      <if test="approvalUserId != null" >
        #{approvalUserId,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="jp.scriptkidie.datacopy.sql.model.educationdb.MediationsExample" resultType="java.lang.Integer" >
    select count(*) from MEDIATIONS
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update MEDIATIONS
    <set >
      <if test="record.receptionNo != null" >
        RECEPTION_NO = #{record.receptionNo,jdbcType=CHAR},
      </if>
      <if test="record.placeNo != null" >
        PLACE_NO = #{record.placeNo,jdbcType=VARCHAR},
      </if>
      <if test="record.userId != null" >
        USER_ID = #{record.userId,jdbcType=VARCHAR},
      </if>
      <if test="record.contactTelNo != null" >
        CONTACT_TEL_NO = #{record.contactTelNo,jdbcType=VARCHAR},
      </if>
      <if test="record.approvalUserId != null" >
        APPROVAL_USER_ID = #{record.approvalUserId,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update MEDIATIONS
    set RECEPTION_NO = #{record.receptionNo,jdbcType=CHAR},
      PLACE_NO = #{record.placeNo,jdbcType=VARCHAR},
      USER_ID = #{record.userId,jdbcType=VARCHAR},
      CONTACT_TEL_NO = #{record.contactTelNo,jdbcType=VARCHAR},
      APPROVAL_USER_ID = #{record.approvalUserId,jdbcType=VARCHAR}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="jp.scriptkidie.datacopy.sql.model.educationdb.Mediations" >
    update MEDIATIONS
    <set >
      <if test="placeNo != null" >
        PLACE_NO = #{placeNo,jdbcType=VARCHAR},
      </if>
      <if test="userId != null" >
        USER_ID = #{userId,jdbcType=VARCHAR},
      </if>
      <if test="contactTelNo != null" >
        CONTACT_TEL_NO = #{contactTelNo,jdbcType=VARCHAR},
      </if>
      <if test="approvalUserId != null" >
        APPROVAL_USER_ID = #{approvalUserId,jdbcType=VARCHAR},
      </if>
    </set>
    where RECEPTION_NO = #{receptionNo,jdbcType=CHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="jp.scriptkidie.datacopy.sql.model.educationdb.Mediations" >
    update MEDIATIONS
    set PLACE_NO = #{placeNo,jdbcType=VARCHAR},
      USER_ID = #{userId,jdbcType=VARCHAR},
      CONTACT_TEL_NO = #{contactTelNo,jdbcType=VARCHAR},
      APPROVAL_USER_ID = #{approvalUserId,jdbcType=VARCHAR}
    where RECEPTION_NO = #{receptionNo,jdbcType=CHAR}
  </update>
</mapper>


text:
using AutoyaFramework.Encrypt.AES256;
using AutoyaFramework.Encrypt.SHA_2;
using Miyamasu;
using System.Linq;

public class EncryptTests : MiyamasuTestRunner
{
    [MTest]
    public void AESEncrypt()
    {
        var sample = "something";

        string key = "z,mv--342krnsdrfJDSf33dq2423nsda";
        string iv = "12325346457462343654867843523421";

        var aes = new AES256(key, iv);

        var encryptedStr = aes.Encrypt(sample);
        var decryptedStr = aes.Decrypt(encryptedStr);

        var len1 = sample.Length;
        var len2 = decryptedStr.Length;

        True(sample.Length == decryptedStr.Length, "not match, dec:" + decryptedStr + " len1:" + len1 + " len2:" + len2);
    }

    [MTest]
    public void AESEncryptLong()
    {
        var sample = "somethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomething";

        string key = "z,mv--342krnsdrfJDSf33dq2423nsda";
        string iv = "12325346457462343654867843523421";

        var aes = new AES256(key, iv);

        var encryptedStr = aes.Encrypt(sample);
        var decryptedStr = aes.Decrypt(encryptedStr);

        var len1 = sample.Length;
        var len2 = decryptedStr.Length;

        True(sample.Length == decryptedStr.Length, "not match, dec:" + decryptedStr + " len1:" + len1 + " len2:" + len2);
    }

    [MTest]
    public void AESEncryptBytes()
    {
        var sampleBytes = new byte[1024];
        var rnd = new System.Random();
        rnd.NextBytes(sampleBytes);

        string key = "z,mv--342krnsdrfJDSf33dq2423nsda";
        string iv = "12325346457462343654867843523421";

        var aes = new AES256(key, iv);

        var encryptedBytes = aes.Encrypt(sampleBytes);
        var decryptedBytes = aes.Decrypt(encryptedBytes);

        var bytesLen1 = sampleBytes.Length;
        var bytesLen2 = decryptedBytes.Length;

        True(sampleBytes.Length == decryptedBytes.Length, "not match," + " bytesLen1:" + bytesLen1 + " bytesLen2:" + bytesLen2);
        True(sampleBytes.SequenceEqual(decryptedBytes), "not match");
    }

    [MTest]
    public void Sha256Hash()
    {
        var sample = "yetrwfnkiofaj039tq23rkekfnaksodnfawefsq4y2up1rk";
        var key = "oeo9ur2jowiefapwfpawkefwe0-e-0je";
        var hashed = SHA_2.Sha256Hex(sample, key);
        True(hashed == "e5345801e661de0bcf572e0dcf3cea9ac3328c7a2b8daded70ce4b5e8cb54186", "not match, hashed:" + hashed);
    }

    [MTest]
    public void Sha512Hash()
    {
        var sample = "yetrwfnkiofaj039tq23rkekfnaksodnfawefsq4y2up1rk";
        var key = "oeo9ur2jowiefapwfpawkefwe0-e-0je";
        var hashed = SHA_2.Sha512Hex(sample, key);
        True(hashed == "671ea03f5c1eb5e5a9a595f862fc9af3b4686178323c7b246af5b7320912ac2599a7bf8d01b3efa1f0d63ba9ecc0e5a5214eda4f7b048be661b61692629969e7", "not match, hashed:" + hashed);
    }
}


text:
require_relative '../models/merchant.rb'
require_relative '../models/category.rb'
require_relative '../models/income.rb'
require_relative '../models/transaction.rb'

Category.delete_all
Merchant.delete_all
Income.delete_all
Transaction.delete_all

category1 = Category.new({ 'name' => 'Food' })
category2 = Category.new({ 'name' => 'Bills' })
category3 = Category.new({ 'name' => 'Rent' })
category4 = Category.new({ 'name' => 'MacbookPro' })

c1 = category1.save()
c2 = category2.save()
c3 = category3.save()
c4 = category4.save()

merchant1 = Merchant.new({ 'name' => 'Tesco'})
merchant2 = Merchant.new({ 'name' => 'Energetics'})
merchant3 = Merchant.new({ 'name' => 'Landlord'})
merchant4 = Merchant.new({ 'name' => 'Apple'})

m1 = merchant1.save()
m2 = merchant2.save()
m3 = merchant3.save()
m4 = merchant4.save()

income1 = Income.new({ 'amount' => 3000, 'type' => 'Salary', 'income_date' => '31-March-2016' })
income2 = Income.new({ 'amount' => 1000, 'type' => 'Real Estate', 'income_date' => '21-March-2016' })
income3 = Income.new({ 'amount' => 1000, 'type' => 'Stock Market', 'income_date' => '10-March-2016' })

income1.save()
income2.save()
income3.save()

entry1 = Transaction.new({ 'amount' => 100, 'merchant_id' => m1.id , 'category_id' => c1.id, 'transaction_date' => '21-March-2016'})
entry2 = Transaction.new({ 'amount' => 65, 'merchant_id' => m2.id , 'category_id' => c2.id, 'transaction_date' => '19-March-2016'})
entry3 = Transaction.new({ 'amount' => 1000, 'merchant_id' => m3.id , 'category_id' => c3.id, 'transaction_date' => '21-March-2016'})
entry4 = Transaction.new({ 'amount' => 2000, 'merchant_id' => m4.id , 'category_id' => c4.id, 'transaction_date' => '30-March-2016'})

entry1.save()
entry2.save()
entry3.save()
entry4.save()


text:
<!DOCTYPE html>
<html>
<head>
    <title>Unit Tests</title>

    <link rel="stylesheet" type="text/css" href="/jasmine-core/jasmine.css">

    <script type="text/javascript" src="/jasmine-core/jasmine.js"></script>
    <script type="text/javascript" src="/jasmine-core/jasmine-html.js"></script>
    <script type="text/javascript" src="/jasmine-core/boot.js"></script>
    <script type="text/javascript" src="/js/ozpIwc-client.js"></script>
    <script type="text/javascript" src="/js/ozp-iwc-owf7-widget-adapter.js"></script>

    <script type="text/javascript" src="specs/unit/owf7ParticipantListener/bridgeSpec.js"></script>
    <script type="text/javascript" src="specs/unit/owf7ParticipantListener/modules/eventingSpec.js"></script>
    <script type="text/javascript" src="specs/unit/owf7ParticipantListener/modules/ddSpec.js"></script>
    <script type="text/javascript" src="specs/unit/owf7ParticipantListener/modules/componentsSpec.js"></script>
    <script type="text/javascript" src="specs/unit/owf7ParticipantListener/modules/kernelSpec.js"></script>

    <script type="text/javascript" src="specs/unit/owf7Participant/owf7ParticipantSpec.js"></script>

</head>
<body>
    <script src="//localhost:35729/livereload.js"></script>
</body>
</html>


text:
module Neon
  # Helpers for processing method arguments.
  module ArgumentHelpers
    # Extracts a session from the array of arguments if one exists at the end.
    #
    # @param args [Array] an array of arguments of any type.
    #
    # @return [Session] a session if the last argument is a valid session and pops it out of args.
    #   Otherwise it returns the current session.
    #
    def extract_session(args)
      if args.last.is_a?(Session::Rest) || args.last.is_a?(Session::Embedded)
        args.pop
      else
        Session.current
      end
    end
  end
end


text:
let mockPost = Promise.resolve({ data: { id: 1 } });
jest.mock("axios", () => ({
  get: () => Promise.resolve({
    data: {
      "id": 6,
      "name": "New Device From Server",
      "timezone": "America/Chicago",
      "last_saw_api": "2017-08-30T20:42:35.854Z"
    }
  }),
  post: () => mockPost,
}));

import { refresh, initSaveGetId } from "../crud";
import { TaggedDevice, SpecialStatus } from "farmbot";
import { API } from "../index";
import { Actions } from "../../constants";
import { get } from "lodash";

describe("successful refresh()", () => {
  API.setBaseUrl("http://localhost:3000");

  // 1. Correct URL
  // 2. call to refreshOK
  // 3. Actually replaces resource.
  it("re-downloads an existing resource", (done) => {
    const device1: TaggedDevice = {
      "uuid": "Device.6.1",
      "kind": "Device",
      "specialStatus": SpecialStatus.SAVED,
      "body": {
        "id": 6,
        "name": "summer-pond-726",
        "ota_hour": 3,
        "timezone": "America/Chicago",
        "last_saw_api": "2017-08-30T20:42:35.854Z",
        "tz_offset_hrs": 0
      },
    };

    const thunk = refresh(device1);
    const dispatch = jest.fn();
    thunk(dispatch);

    setImmediate(() => {
      const { calls } = dispatch.mock;
      expect(calls.length).toBe(2);

      const first = calls[0][0];
      expect(first).toBeInstanceOf(Object);
      expect(get(first, "type", "TYPE WAS UNDEFINED"))
        .toEqual(Actions.REFRESH_RESOURCE_START);
      expect(get(first, "payload", "NO PAYLOAD!"))
        .toEqual(device1.uuid);

      const second = calls[1][0];
      expect(second).toBeInstanceOf(Object);
      expect(get(second, "type", "TYPE WAS UNDEFINED"))
        .toEqual(Actions.REFRESH_RESOURCE_OK);
      expect(get(second, "payload.body.name", "DID NOT FIND ANYTHING"))
        .toEqual("New Device From Server");
      done();
    });
  });
});

describe("initSaveGetId()", () => {
  it("returns id", async () => {
    const dispatch = jest.fn();
    const result = await initSaveGetId("SavedGarden", {})(dispatch);
    expect(dispatch).toHaveBeenCalledWith({
      type: Actions.SAVE_RESOURCE_START,
      payload: expect.objectContaining({ kind: "SavedGarden" })
    });
    expect(dispatch).toHaveBeenCalledWith({
      type: Actions.INIT_RESOURCE,
      payload: expect.objectContaining({ kind: "SavedGarden" })
    });
    await expect(result).toEqual(1);
    expect(dispatch).toHaveBeenCalledWith({
      type: Actions.SAVE_RESOURCE_OK,
      payload: expect.objectContaining({ kind: "SavedGarden" })
    });
  });

  it("catches errors", async () => {
    mockPost = Promise.reject("error");
    const dispatch = jest.fn();
    await initSaveGetId("SavedGarden", {})(dispatch).catch(() => { });
    await expect(dispatch).toHaveBeenLastCalledWith({
      type: Actions._RESOURCE_NO,
      payload: expect.objectContaining({ err: "error" })
    });
  });
});