text:
from __future__ import  absolute_import

from bokeh.models.annotations import Legend, BoxAnnotation, Span
from bokeh.core.enums import (
    NamedColor as Color, LineJoin, LineCap, FontStyle, TextAlign,
    TextBaseline)

FILL = ["fill_color", "fill_alpha"]
BACKGROUND = ['background_fill_color', 'background_fill_alpha']
BORDER = ["border_line_color", "border_line_width", "border_line_alpha",
    "border_line_join", "border_line_cap", "border_line_dash",
    "border_line_dash_offset"]
LINE = ["line_color", "line_width", "line_alpha", "line_join", "line_cap",
    "line_dash", "line_dash_offset"]
LABEL = ["label_text_font", "label_text_font_size", "label_text_font_style",
    "label_text_color", "label_text_alpha", "label_text_align",
    "label_text_baseline"]
PROPS = ["name", "tags"]

def check_border(annotation):
    assert annotation.border_line_color == Color.black
    assert annotation.border_line_width == 1
    assert annotation.border_line_alpha == 1.0
    assert annotation.border_line_join == LineJoin.miter
    assert annotation.border_line_cap == LineCap.butt
    assert annotation.border_line_dash == []
    assert annotation.border_line_dash_offset == 0

def check_label(annotation):
    assert annotation.label_text_font == "helvetica"
    assert annotation.label_text_font_size == {"value": "10pt"}
    assert annotation.label_text_font_style == FontStyle.normal
    assert annotation.label_text_color == "#444444"
    assert annotation.label_text_alpha == 1.0
    assert annotation.label_text_align == TextAlign.left
    assert annotation.label_text_baseline == TextBaseline.middle

def check_props(annotation, *props):
    expected = set(sum((PROPS,) + props, []))
    found = set(annotation.properties())
    missing = expected.difference(found)
    extra = found.difference(expected)
    assert len(missing) == 0, "Properties missing: {0}".format(", ".join(sorted(missing)))
    assert len(extra) == 0, "Extra properties: {0}".format(", ".join(sorted(extra)))

def check_fill(annotation):
    assert annotation.fill_color == '#fff9ba'
    assert annotation.fill_alpha == 0.4

def check_background(annotation):
    assert annotation.background_fill_color == '#ffffff'
    assert annotation.background_fill_alpha == 1.0

def check_line(annotation, line_color='#cccccc', line_width=0.3, line_alpha=1.0):
    assert annotation.line_color == line_color
    assert annotation.line_width == line_width
    assert annotation.line_alpha == line_alpha
    assert annotation.line_join == LineJoin.miter
    assert annotation.line_cap == LineCap.butt
    assert annotation.line_dash == []
    assert annotation.line_dash_offset == 0

def test_Legend():
    legend = Legend()
    assert legend.plot is None
    assert legend.location == 'top_right'
    assert legend.label_standoff == 15
    assert legend.label_height == 20
    assert legend.label_width == 50
    assert legend.glyph_height == 20
    assert legend.glyph_width == 20
    assert legend.legend_padding == 10
    assert legend.legend_spacing == 3
    assert legend.legends == []
    yield check_border, legend
    yield check_label, legend
    yield check_background, legend
    yield (check_props, legend, [
        "plot",
        "location",
        "orientation",
        "label_standoff",
        "label_height",
        "label_width",
        "glyph_height",
        "glyph_width",
        "legend_padding",
        "legend_spacing",
        "legends",
        "level"
    ], LABEL, BORDER, BACKGROUND)

def test_BoxAnnotation():
    box = BoxAnnotation()
    assert box.plot is None
    assert box.left == None
    assert box.left_units == 'data'
    assert box.right == None
    assert box.right_units == 'data'
    assert box.bottom == None
    assert box.bottom_units == 'data'
    assert box.top == None
    assert box.top_units == 'data'
    assert box.x_range_name == 'default'
    assert box.y_range_name == 'default'
    assert box.level == 'annotation'
    yield check_line, box, '#cccccc', 1, 0.3
    yield check_fill, box
    yield (check_props, box, [
        "render_mode",
        "plot",
        "left",
        "left_units",
        "right",
        "right_units",
        "bottom",
        "bottom_units",
        "top",
        "top_units",
        "x_range_name",
        "y_range_name",
        "level",
    ], LINE, FILL)

def test_Span():
    line = Span()
    assert line.plot is None
    assert line.location is None
    assert line.location_units == 'data'
    assert line.dimension == 'width'
    assert line.x_range_name == 'default'
    assert line.y_range_name == 'default'
    assert line.level == 'annotation'
    assert line.render_mode == 'canvas'
    yield check_line, line, 'black', 1.0
    yield (check_props, line, [
        "plot",
        "location",
        "location_units",
        "dimension",
        "x_range_name",
        "y_range_name",
        "level",
        "render_mode"
    ], LINE)

redpajama_set_name: RedPajamaGithub


text:
//////////////////////////////////////////////////////////////////////////
// Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

using Aspose.Words;
using Aspose.Words.Rendering;

namespace CSharp.Rendering_and_Printing
{
    class ActivePrintPreviewDialog : PrintPreviewDialog
    {
        /// <summary>
        /// Brings the Print Preview dialog on top when it is initially displayed.
        /// </summary>
        protected override void OnShown(EventArgs e)
        {
            Activate();
            base.OnShown(e);
        }

    }
    //ExEnd

    /// <summary>
    /// This project is set to target the x86 platform because the .NET print dialog does not
    /// seem to show when calling from a 64-bit application.
    /// </summary>
    public class DocumentPreviewAndPrint
    {
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_RenderingAndPrinting(); ;

            // Open the document.
            Document doc = new Document(dataDir + "TestFile.doc");

            //ExStart
            //ExId:DocumentPreviewAndPrint_PrintDialog_Creation
            //ExSummary:Creates the print dialog.
            PrintDialog printDlg = new PrintDialog();
            // Initialize the print dialog with the number of pages in the document.
            printDlg.AllowSomePages = true;
            printDlg.PrinterSettings.MinimumPage = 1;
            printDlg.PrinterSettings.MaximumPage = doc.PageCount;
            printDlg.PrinterSettings.FromPage = 1;
            printDlg.PrinterSettings.ToPage = doc.PageCount;
            //ExEnd

            //ExStart
            //ExId:DocumentPreviewAndPrint_PrintDialog_Check_Result
            //ExSummary:Check if the user accepted the print settings and proceed to preview the document.
            if (!printDlg.ShowDialog().Equals(DialogResult.OK))
                return;
            //ExEnd

            //ExStart
            //ExId:DocumentPreviewAndPrint_AsposeWordsPrintDocument_Creation
            //ExSummary:Creates a special Aspose.Words implementation of the .NET PrintDocument class.
            // Pass the printer settings from the dialog to the print document.
            AsposeWordsPrintDocument awPrintDoc = new AsposeWordsPrintDocument(doc);
            awPrintDoc.PrinterSettings = printDlg.PrinterSettings;
            //ExEnd

            //ExStart
            //ExId:DocumentPreviewAndPrint_ActivePrintPreviewDialog_Creation
            //ExSummary:Creates an overridden version of the .NET Print Preview dialog to preview the document.
            ActivePrintPreviewDialog previewDlg = new ActivePrintPreviewDialog();

            // Pass the Aspose.Words print document to the Print Preview dialog.
            previewDlg.Document = awPrintDoc;
            // Specify additional parameters of the Print Preview dialog.
            previewDlg.ShowInTaskbar = true;
            previewDlg.MinimizeBox = true;
            previewDlg.PrintPreviewControl.Zoom = 1;
            previewDlg.Document.DocumentName = "TestName.doc";
            previewDlg.WindowState = FormWindowState.Maximized;
            // Show the appropriately configured Print Preview dialog.
            previewDlg.ShowDialog();
            //ExEnd
        }
    }
}


text:
@interface EditPostViewController : PostEditorViewController
- (IBAction)updatePost:(UIBarButtonItem *)sender;

@end


text:
FIcontent.Gaming.Enabler.PoIUnityInterface
==========================================

Point of Interest Data Provider GE interface for .Net and Unity

Integrate with Unity
----------------
To use the PoIInterface library in Unity just copy the PoIInterface folder into the Unity Assets folder of your project.

Contact
-------

 * Legal Contact: Marcel Lancelle (marcel dot lancelle at ethz dot ch)
 * Technical Contact: Mattia Ryffel (mattia dot ryffel at disneyresearch dot com)


text:
package pet

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"

	"github.com/go-swagger/go-swagger/errors"
	"github.com/go-swagger/go-swagger/httpkit/middleware"

	"github.com/go-swagger/go-swagger/examples/generated/models"
)

// AddPetParams contains all the bound params for the add pet operation
// typically these are obtained from a http.Request
//
// swagger:parameters addPet
type AddPetParams struct {
	/*Pet object that needs to be added to the store
	  In: body
	*/
	Body *models.Pet
}

// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *AddPetParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
	var res []error

	var body models.Pet
	if err := route.Consumer.Consume(r.Body, &body); err != nil {
		res = append(res, errors.NewParseError("body", "body", "", err))
	} else {
		if err := body.Validate(route.Formats); err != nil {
			res = append(res, err)
		}

		if len(res) == 0 {
			o.Body = &body
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.fruit.launcher.DockButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center_horizontal"
    android:scaleType="center" />


text:
package format;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
 * Thread-safe.
 */
class JsonFormatter implements StringFormatter {

	private final static JsonParser parser = new JsonParser();
	private final static Gson gson = new GsonBuilder()
		.serializeNulls()
		.setLenient()
		.setPrettyPrinting()
		.create();

	public String format(String s) {

		if (s == null) {
			return null;
		}

		JsonElement el = parser.parse(s);
		return gson.toJson(el);

    }

}


text:
var fs = require("fs");
var path = require('path');
var crypto = require('crypto');

function encrypt(text, password){
	var cipher = crypto.createCipher('aes-256-cbc',password);
	var crypted = cipher.update(text,'utf8','hex');
	crypted += cipher.final('hex');
	return crypted;
}

function decrypt(text, password){
	var result;
	try{
		var decipher = crypto.createDecipher('aes-256-cbc',password);
		result = decipher.update(text,'hex','utf8');
		result += decipher.final('utf8');
	} catch(e){
		result = false;
	}

	return result;
}

var Authentication = function(setup) {

	var getPasswordFilename = function(username){
		return path.join(setup.keys, "." + crypto.createHmac('sha1', "filename-key-hash").update(username).digest('hex'));
	};

	var getPasswordFileContent = function(username, password){
		var filename = getPasswordFilename(username);
		var contentString = fs.readFileSync(filename).toString();
		var result = null;
		var content = decrypt(contentString, password);
		if (content === false){
			result = {
				err: true,
				msg: "decrypt error",
				filename : filename
			};
		} else {

			content = JSON.parse(content);
			result = {
				err: false,
				filename : filename,
				user:{
					username:content.username,
					password:content.password
				}
			};
		}

		return result;
	};

	this.remove = function(username, password){
		var content = getPasswordFileContent(username,password);
		if (content.err){
			return content;
		}else {
			fs.unlinkSync(content.filename);
			return {err : fs.existsSync(content.filename)};
		}
	};

	this.add = function(username, password){
		var filename = getPasswordFilename(username);
		if (fs.existsSync(filename)){
			return {err:true};
		} else {
			var content = {
				username:username,
				password:password
			};
			var contentString = encrypt(JSON.stringify(content), password);

			fs.writeFileSync(filename, contentString);
			return {err:!fs.existsSync(filename)};
		}
	};

	this.get = function(username, password){
		return getPasswordFileContent(username, password);
	};

	return this;
};

module.exports = Authentication;


text:
<?php

namespace Model;

/**
 * Model\SortableChild document.
 */
class SortableChild extends \Model\Base\SortableChild
{
}


text:
Static site
===========

.. todo::
    Doctrings (module, utilities)

.. automodule:: indico.modules.events.static

Models
++++++

.. automodule:: indico.modules.events.static.models.static
    :members:
    :undoc-members:

Utilities
+++++++++

.. automodule:: indico.modules.events.static.util
    :members:
    :undoc-members:


text:
import Detail from '@/components/public/detail';
import { inject, observer } from 'mobx-react';
import PropTypes from 'prop-types';
import { Tabs, Spin } from 'antd';

import Inputs from './Inputs';
import Outputs from './Outputs';
import Configuration from './Configuration';

const { DetailHead, DetailHeadItem, DetailContent, DetailAction } = Detail;
const TabPane = Tabs.TabPane;

@inject('stageTemplate')
@observer
class TemplateDetail extends React.Component {
  componentDidMount() {
    const {
      match: {
        params: { templateName },
      },
    } = this.props;
    templateName && this.props.stageTemplate.getTemplate(templateName);
  }

  render() {
    const {
      match: {
        params: { templateName },
      },
      stageTemplate: { template, templateLoading },
    } = this.props;
    if (_.get(template, 'metadata.name') !== templateName || templateLoading) {
      return <Spin />;
    }
    return (
      <Detail actions={<DetailAction />}>
        <DetailHead headName={templateName}>
          <DetailHeadItem
            name={intl.get('creationTime')}
            value={_.get(template, 'metadata.creationTimestamp')}
          />
          <DetailHeadItem
            name={intl.get('template.scene')}
            value={
              _.get(template, 'metadata.labels["cyclone.dev/scene"]') || '--'
            }
          />
          <DetailHeadItem
            name={intl.get('template.type')}
            value={
              _.get(
                template,
                'metadata.labels["stage.cyclone.dev/template-kind"]'
              ) || '--'
            }
          />
          <DetailHeadItem
            name={intl.get('description')}
            value={
              _.get(
                template,
                'metadata.annotations["cyclone.dev/description"]'
              ) || '--'
            }
          />
        </DetailHead>
        <DetailContent>
          <Tabs defaultActiveKey="inputs" type="card">
            <TabPane tab={intl.get('stage.inputs')} key="inputs">
              <Inputs inputs={_.get(template, 'spec.pod.inputs')} />
            </TabPane>
            <TabPane tab={intl.get('stage.outputs')} key="outputs">
              <Outputs outputs={_.get(template, 'spec.pod.outputs')} />
            </TabPane>
            <TabPane tab={intl.get('configuration')} key="configuration">
              <Configuration configuration={_.get(template, 'spec.pod.spec')} />
            </TabPane>
          </Tabs>
        </DetailContent>
      </Detail>
    );
  }
}

TemplateDetail.propTypes = {
  match: PropTypes.shape({
    params: PropTypes.shape({
      templateName: PropTypes.string,
    }).isRequired,
  }),
  stageTemplate: PropTypes.shape({
    getTemplate: PropTypes.func,
    template: PropTypes.object,
    templateLoading: PropTypes.bool,
  }),
};

export default TemplateDetail;


text:
This guide will assist you with installing Egoldpunk. This document assumes you are running Ubuntu 12.04 LTS, adjustments may need to be made for other OSes.

If you don't understand how to use this document, **Egoldpunk is not for you**. Egoldpunk requires a commanding understanding of UNIX system administration to be run safely.

## Install Prerequisites

Update your repository data and packages if this is a fresh install of Ubuntu:

```
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install git autoconf libtool ntp build-essential
```

It is recommended you enable [unattended security updates](https://help.ubuntu.com/community/AutomaticSecurityUpdates) to help protect your system from security issues:

```
sudo apt-get install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
```

## Install NodeJS

The latest information on installing NodeJS for your platform is [available here](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager), this is the current procedure for Ubuntu:

```
sudo apt-get install python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
```

## Install and Configure Redis

Redis is used to store your wallet data.

```
sudo apt-get install redis-server
```

Now you will need to edit `/etc/redis/redis.conf` to be more data persistent:

Change `appendonly no` to `appendonly yes`.
Change `appendfsync everysec` to `appendfsync always`.

Restart redis: `sudo service redis-server restart`.

## Install and Configure egdd

Currently Egold depends on a custom build of egdd using [this patch](https://github.com/E-gold-team/e-goldcoin.git -> watchonly2 branch).

Install prerequisites:
```
sudo apt-get install libdb4.8++ libdb4.8++-dev pkg-config libprotobuf-dev \
libminiupnpc8 minissdpd libboost-all-dev ccache libssl-dev
```

Checkout and make [egold-watchonly](https://github.com/E-gold-team/e-goldcoin/commits/watchonly2):
```
git clone https://github.com/E-gold-team/e-goldcoin.git
Switch to watchonly2 branch and checkout
cd /src
make -f makefile.unix USE_UPNP=0 USE_QRCODE=1 USE_IPV6=1
strip egdd
```

Create a user for egdd and move the binary to where it can access it:
```
adduser egdd
mkdir -p ~egdd/bin
mv egdd /usr/home/egdd/bin
```

Now you need to configure egdd:

```
su - egddd
mkdir -p ~/.E-Gold
vi ~/.E-Gold/E-Gold.conf
```

And add the following information (set the `rpcuser` and `rpcpassword` to something else):

```
rpcuser=NEWUSERNAME
rpcpassword=NEWPASSWORD
rpcallowip=127.0.0.1
rpcport=5888
port=5889
txindex=1
server=1
daemon=1
```
**If your egdd crashes due to memory consumption**, try limiting your connections by adding `maxconnections=10`. Try further adjusting to 3 if you are still having issues.

Consider adding a startup script for egdd to either init.d or via upstart.

Start egdd as the egdd user:

```
su - egdd
egdd &
```

**egdd may take up to an hour (or more, depending on growth) to download the blockchain.** Egoldpunk will not be able to function properly until this has occurred. Please be patient.

If you want something to monitor egdd to ensure it stays running and start it on system restart, take a look at [Monit](http://mmonit.com/monit/).

## Install and Configure Egoldpunk

Go to your user's home directory (`cd ~`), clone the repository and install nodejs dependencies:

```
git clone THISREPO
cd Egoldpunk
npm install
```

Now you will need to create and configure your config.json file, one for the main folder and one in `public`. From the `Egoldpunk` directory:

```
cp config.template.json config.json
```

Edit the file to connect to `egdd` on port 5888 using the user/password you set when configuring egdd:

```
{
  "bitcoind": "http://NEWUSERNAME:NEWPASSWORD@127.0.0.1:5888",
  "pricesUrl": "http://localhost:8080/rates.json",
  "httpPort": 8080
}
```

For SSL:

```
{
  "bitcoind": "http://NEWUSERNAME:NEWPASSWORD@127.0.0.1:5888",
  "pricesUrl": "http://localhost:8080/rates.json",
  "httpPort": 8080,
  "httpsPort": 8086,
  "sslKey": "./Egoldpunk.key",
  "sslCert": "./Egoldpunk.crt"
}
```
Alternately, you can use Nginx as your SSL endpoint and proxy requests over to Egoldpunk instead of opening your node install directly to the world.

Now copy the client application's config:

```
cp public/config.template.json public/config.json
```

And change `network` to `prod` instead of `testnet` to use Egoldpunk in production mode.

## Start Egoldpunk

You can start Egoldpunk from the command line:

```
node start.js
```

Try to connect by going to http://YOURADDRESS.COM:8080  (If you're using the SSL config then try  http://YOURADDRESS.COM:8085. OR https://YOURADDRESS.COM:8086) If it loads, then you should be ready to use Egoldpunk!

## egdd Price Cron Job

Edit the crontab of the user you are running Egoldpunk as, and insert the following entry:

```
TODO: ADD a hack
```

## Backing up Database

Redis maintains a file called `/var/lib/redis/dump.rdb`, which is a backup of your Redis database. It is safe to copy this file while Redis is running. **It is strongly recommended that you backup this file frequently.** You can also setup a Redis slave to listen to master in real time. Ideally you should do both!

## Extra Steps for Contributors

If you want to contribute code to this project, you will need to use Grunt. Grunt is a task-runner that presently handles minifying and uglifying Egoldpunk's CSS and JS resources.  Grunt is installed by the `npm install` you ran from the Egoldpunk directory.     //todo: check the JS shit

Running `./node_modules/grunt-cli/bin/grunt` in your Egoldpunk directory will minify and uglify everything, and running `./node_modules/grunt-cli/bin/grunt watch` will automatically uglify your JS files when they change.

You can also install grunt system-wide with `sudo npm install -g grunt-cli`.


text:
package control

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"sort"
	"strings"
	"text/template"

	yaml "github.com/cloudfoundry-incubator/candiedyaml"
	"github.com/rancher/os/pkg/log"

	"github.com/codegangsta/cli"
	"github.com/rancher/os/config"
	"github.com/rancher/os/pkg/util"
)

func configSubcommands() []cli.Command {
	return []cli.Command{
		{
			Name:   "get",
			Usage:  "get value",
			Action: configGet,
		},
		{
			Name:   "set",
			Usage:  "set a value",
			Action: configSet,
		},
		{
			Name:   "images",
			Usage:  "List Docker images for a configuration from a file",
			Action: runImages,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "input, i",
					Usage: "File from which to read config",
				},
			},
		},
		{
			Name:     "generate",
			Usage:    "Generate a configuration file from a template",
			Action:   runGenerate,
			HideHelp: true,
		},
		{
			Name:  "export",
			Usage: "export configuration",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "output, o",
					Usage: "File to which to save",
				},
				cli.BoolFlag{
					Name:  "private, p",
					Usage: "Include the generated private keys",
				},
				cli.BoolFlag{
					Name:  "full, f",
					Usage: "Export full configuration, including internal and default settings",
				},
			},
			Action: export,
		},
		{
			Name:   "merge",
			Usage:  "merge configuration from stdin",
			Action: merge,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "input, i",
					Usage: "File from which to read",
				},
			},
		},
		{
			Name:   "syslinux",
			Usage:  "edit Syslinux boot global.cfg",
			Action: editSyslinux,
		},
		{
			Name:   "validate",
			Usage:  "validate configuration from stdin",
			Action: validate,
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "input, i",
					Usage: "File from which to read",
				},
			},
		},
	}
}

func imagesFromConfig(cfg *config.CloudConfig) []string {
	imagesMap := map[string]int{}

	for _, service := range cfg.Rancher.BootstrapContainers {
		imagesMap[service.Image] = 1
	}
	for _, service := range cfg.Rancher.Services {
		imagesMap[service.Image] = 1
	}

	images := make([]string, len(imagesMap))
	i := 0
	for image := range imagesMap {
		images[i] = image
		i++
	}
	sort.Strings(images)
	return images
}

func runImages(c *cli.Context) error {
	configFile := c.String("input")
	cfg, err := config.ReadConfig(nil, false, configFile)
	if err != nil {
		log.WithFields(log.Fields{"err": err, "file": configFile}).Fatalf("Could not read config from file")
	}
	images := imagesFromConfig(cfg)
	fmt.Println(strings.Join(images, " "))
	return nil
}

func runGenerate(c *cli.Context) error {
	if err := genTpl(os.Stdin, os.Stdout); err != nil {
		log.Fatalf("Failed to generate config, err: '%s'", err)
	}
	return nil
}

func genTpl(in io.Reader, out io.Writer) error {
	bytes, err := ioutil.ReadAll(in)
	if err != nil {
		log.Fatal("Could not read from stdin")
	}
	tpl := template.Must(template.New("osconfig").Parse(string(bytes)))
	return tpl.Execute(out, env2map(os.Environ()))
}

func env2map(env []string) map[string]string {
	m := make(map[string]string, len(env))
	for _, s := range env {
		d := strings.Split(s, "=")
		m[d[0]] = d[1]
	}
	return m
}

func editSyslinux(c *cli.Context) error {
	cmd := exec.Command("system-docker", "run", "--rm", "-it",
		"-v", "/:/host",
		"-w", "/host",
		"--entrypoint=vi",
		"rancher/os-console:"+config.Version,
		"boot/global.cfg")
	cmd.Stdout, cmd.Stderr, cmd.Stdin = os.Stdout, os.Stderr, os.Stdin
	return cmd.Run()
}

func configSet(c *cli.Context) error {
	if c.NArg() < 2 {
		return nil
	}

	key := c.Args().Get(0)
	value := c.Args().Get(1)
	if key == "" {
		return nil
	}

	err := config.Set(key, value)
	if err != nil {
		log.Fatal(err)
	}

	return nil
}

func configGet(c *cli.Context) error {
	arg := c.Args().Get(0)
	if arg == "" {
		return nil
	}

	val, err := config.Get(arg)
	if err != nil {
		log.WithFields(log.Fields{"key": arg, "val": val, "err": err}).Fatal("config get: failed to retrieve value")
	}

	printYaml := false
	switch val.(type) {
	case []interface{}:
		printYaml = true
	case map[interface{}]interface{}:
		printYaml = true
	}

	if printYaml {
		bytes, err := yaml.Marshal(val)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(string(bytes))
	} else {
		fmt.Println(val)
	}

	return nil
}

func merge(c *cli.Context) error {
	bytes, err := inputBytes(c)
	if err != nil {
		log.Fatal(err)
	}

	if err = config.Merge(bytes); err != nil {
		log.Error(err)
		validationErrors, err := config.ValidateBytes(bytes)
		if err != nil {
			log.Fatal(err)
		}
		for _, validationError := range validationErrors.Errors() {
			log.Error(validationError)
		}
		log.Fatal("EXITING: Failed to parse configuration")
	}

	return nil
}

func export(c *cli.Context) error {
	content, err := config.Export(c.Bool("private"), c.Bool("full"))
	if err != nil {
		log.Fatal(err)
	}

	output := c.String("output")
	if output == "" {
		fmt.Println(content)
	} else {
		err := util.WriteFileAtomic(output, []byte(content), 0400)
		if err != nil {
			log.Fatal(err)
		}
	}

	return nil
}

func validate(c *cli.Context) error {
	bytes, err := inputBytes(c)
	if err != nil {
		log.Fatal(err)
	}
	validationErrors, err := config.ValidateBytes(bytes)
	if err != nil {
		log.Fatal(err)
	}
	for _, validationError := range validationErrors.Errors() {
		log.Error(validationError)
	}
	return nil
}

func inputBytes(c *cli.Context) ([]byte, error) {
	input := os.Stdin
	inputFile := c.String("input")
	if inputFile != "" {
		var err error
		input, err = os.Open(inputFile)
		if err != nil {
			return nil, err
		}
		defer input.Close()
	}
	return ioutil.ReadAll(input)
}


text:
/*global Window, HTMLDocument*/
define(['jquery'], function($) {
    'use strict';

    $.ajaxSetup({
        headers: {
            'X-CSRF-Header': 1
        }
    });
    $.expr[':'].parents = function(a, i, m) {
        return $(a).parents(m[3]).length < 1;
    };

    $.Deferred.getStackHook = function() {
        // Throw an error so we can extract the stack from the Error
        try {
            throw new Error('Exception in jQuery.Deferred');
        } catch (err) {
            return err.stack;
        }
    };

    $.fn.extend({
        focus: (function(originalFocus) {
            return function() {
                var $elem = $(this);
                if (!arguments.length && $elem.attr('data-focusable')) {
                    // the element has own implementation to set focus
                    $elem.triggerHandler('set-focus');
                    return $elem;
                } else {
                    return originalFocus.apply(this, arguments);
                }
            };
        })($.fn.focus),

        offset: (function(originalOffset) {
            return function() {
                if (!arguments.length) {
                    if (this[0] instanceof HTMLDocument) {
                        return originalOffset.call($(this[0].documentElement));
                    }
                    if (this[0] instanceof Window) {
                        return originalOffset.call($(this[0].document.documentElement));
                    }
                }
                return originalOffset.apply(this, arguments);
            };
        })($.fn.offset),

        /**
         * Sets cursor to end of input
         */
        setCursorPosition: function(index) {
            return this.each(function() {
                var el = this;
                if ('selectionStart' in el) {
                    try {
                        el.selectionEnd = el.selectionStart = index === 'end' ? el.value.length : index;
                    } catch (ex) {
                        // avoid exeption when use these actions with unsupported input types (email, number etc)
                    }
                }
            });
        },

        /**
         * Sets cursor to end of input
         */
        setCursorToEnd: function() {
            return this.setCursorPosition('end');
        },

        /**
         * Sets focus on first form field
         */
        focusFirstInput: function() {
            var $input = this.find(':input:visible, [data-focusable]')
                    .not(':checkbox, :radio, :button, :submit, :disabled, :file');
            var $autoFocus = $input.filter('[autofocus]');
            if ($autoFocus.length || $input.length) {
                var $element = ($autoFocus.length ? $autoFocus : $input).first();
                if ($element.isInViewPort()) {
                    $element.setCursorToEnd().focus();
                }
            }
        },

        isInViewPort: function() {
            var $element = $(this);
            var elementTop = $element.offset().top;
            var elementBottom = elementTop + $element.height();
            var viewPortTop = $(window).scrollTop();
            var viewPortBottom = viewPortTop + $(window).height();

            return (
                (elementTop >= viewPortTop) && (elementBottom <= viewPortBottom)
            );
        },

        /**
         * source http://stackoverflow.com/questions/13607252/getting-border-width-in-jquery
         */
        getBorders: function(el) {
            var computed = window.getComputedStyle(el || this[0], null);
            function convertBorderToPx(cssValue) {
                switch (cssValue) {
                    case 'thin':
                        return 1;
                    case 'medium':
                        return 2;
                    case 'thick':
                        return 5;
                    default:
                        return Math.round(parseFloat(cssValue));
                }
            }

            return {
                top: convertBorderToPx(computed.getPropertyValue('borderTopWidth') ||
                    computed.borderTopWidth),
                bottom: convertBorderToPx(computed.getPropertyValue('borderBottomWidth') ||
                    computed.borderBottomWidth),
                left: convertBorderToPx(computed.getPropertyValue('borderLeftWidth') ||
                    computed.borderLeftWidth),
                right: convertBorderToPx(computed.getPropertyValue('borderRightWidth') ||
                    computed.borderRightWidth)
            };
        },

        /**
         * Inserts string in <textarea> or <input> at the cursor position and sets cursor after inserted data
         *
         * @returns {number}
         */
        insertAtCursor: function(str) {
            return this.each(function() {
                var start;
                var end;
                var el = this;
                var value = el.value;
                if ('selectionStart' in el) {
                    // avoid exeption when use these actions with unsupported input types (email, number etc)
                    try {
                        start = el.selectionStart;
                        end = el.selectionEnd;
                        el.value = value.substr(0, start) + str + value.substr(end);
                        el.selectionEnd = el.selectionStart = start + str.length;
                    } catch (ex) {
                        el.value += str;
                    }
                } else {
                    el.value += str;
                }
            });
        },

        /**
         * Thanks http://stackoverflow.com/questions/290254/how-to-order-events-bound-with-jquery
         */
        bindFirst: function(eventType, selector, eventData, handler) {
            var indexOfDot = eventType.indexOf('.');
            var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : '';

            eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;
            handler = handler !== undefined ? handler : (eventData !== undefined ? eventData : selector);
            eventData = typeof eventData !== 'function' ? eventData : undefined;
            selector = typeof selector !== 'function' ? selector : undefined;

            return this.each(function() {
                var $this = $(this);
                var currentAttrListener = this['on' + eventType];

                if (currentAttrListener) {
                    $this.bind(eventType, function(e) {
                        return currentAttrListener(e.originalEvent);
                    });

                    this['on' + eventType] = null;
                }

                $this.on(eventType + eventNameSpace, selector, eventData, handler);

                var allEvents = $this.data('events') || $._data($this[0], 'events');
                var typeEvents = allEvents[eventType];
                var newEvent = typeEvents.pop();
                typeEvents.unshift(newEvent);
            });
        },

        /**
         * Temporarily adds class to element
         */
        addClassTemporarily: function(className, delay) {
            delay = delay || 0;
            return this.each(function() {
                var $el = $(this);
                $el.addClass(className);
                setTimeout(function() {
                    $el.removeClass(className);
                }, delay);
            });
        },

        formFieldValues: function(data) {
            var els = this.find(':input').get();

            if (arguments.length === 0) {
                // return all data
                data = {};
                $.each(els, function() {
                    if (this.name && !this.disabled && (
                            this.checked ||
                            /select|textarea/i.test(this.nodeName) ||
                            /text|hidden|password/i.test(this.type))
                    ) {
                        if (data[this.name] === void 0) {
                            data[this.name] = [];
                        }
                        data[this.name].push($(this).val());
                    }
                });
                return data;
            } else {
                $.each(els, function() {
                    if (this.name && data[this.name]) {
                        var names = data[this.name];
                        var $this = $(this);
                        if (Object.prototype.toString.call(names) !== '[object Array]') {
                            names = [names]; //backwards compat to old version of this code
                        }
                        if (this.type === 'checkbox' || this.type === 'radio') {
                            var val = $this.val();
                            var found = false;
                            for (var i = 0; i < names.length; i++) {
                                if (names[i] === val) {
                                    found = true;
                                    break;
                                }
                            }
                            $this.attr('checked', found);
                        } else {
                            $this.val(names[0]);
                        }
                    }
                });
                return this;
            }
        }
    });

    return $;
});


text:
<?xml version='1.0' encoding='utf-8'?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="PACKAGE" android:versionCode="1" android:versionName="1.0">
    <application android:label="@string/app_name">
        <activity android:label="@string/app_name" android:name="ACTIVITY_ENTRY_NAME">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data android:name="md1" android:value="val" />
        <meta-data android:name="md2" android:value="val" />
        <meta-data android:name="md3" android:value="val" />
    </application>
</manifest>


text:
import React, { Component } from 'react';
import { Button } from '../../common';
import { ThemeContext } from '../../contexts';
import { truncate } from '../../utils/truncate';
import './Toolbar.css';

interface ToolbarProps {
  entryKey: string;
  editLabel: string;
  onClickDelete: () => void;
  onClickEdit: () => void;
}

interface ToolbarState {
  copyIcon: string;
}

class Toolbar extends Component<ToolbarProps, ToolbarState> {
  public state = { copyIcon: 'copy' };
  public timeout: number = 0;

  public componentWillUnmount() {
    window.clearTimeout(this.timeout);
  }

  public render() {
    const { entryKey, onClickEdit, onClickDelete, editLabel } = this.props;
    const { copyIcon } = this.state;

    return (
      <ThemeContext.Consumer>
        {({ theme }) => (

              {truncate(entryKey, 20)}

              <Button
                className='is-icon-button'
                onClick={this.copy}>
                <i className={`fas fa-${copyIcon}`}>
              </Button>
              <Button
                className='is-icon-button'
                onClick={onClickEdit}>
                <i className={`fas fa-${editLabel}`}>
              </Button>
              <Button
                className='is-icon-button'
                onClick={onClickDelete}>

              </Button>

        )}
      </ThemeContext.Consumer>
    );
  }

  private copy = () => {
    const { entryKey } = this.props;
    const textarea = document.createElement('textarea');
    textarea.value = entryKey;
    textarea.setAttribute('readonly', '');
    textarea.style.position = 'absolute';
    textarea.style.opacity = '0';
    document.body.append(textarea);
    textarea.select();
    const didCopy = document.execCommand('copy');
    document.body.removeChild(textarea);

    if (didCopy) {
      this.setState({ copyIcon: 'check' }, () => {
        this.timeout = window.setTimeout(() => this.setState({ copyIcon: 'copy' }), 2500);
      });
    }
  }
}

export default Toolbar;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Castle.MicroKernel;
using System.Web.Http.Dependencies;

namespace SystemsStatus.Web.Dependency
{
    internal class WindsorDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver
    {
        private readonly IKernel container;

        public WindsorDependencyResolver(IKernel container)
        {
            this.container = container;
        }

        public IDependencyScope BeginScope()
        {
            return new WindsorDependencyScope(this.container);
        }

        public object GetService(Type serviceType)
        {
            return this.container.HasComponent(serviceType) ? this.container.Resolve(serviceType) : null;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return this.container.ResolveAll(serviceType).Cast<object>();
        }

        public void Dispose() { }
    }
}


text:
package io.corbel.iam.model;

import com.google.common.base.Joiner;
import io.corbel.lib.ws.digest.Digester;
import io.corbel.lib.ws.digest.DigesterFactory;
import org.junit.Test;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author Alexander De Leon
 *
 */
public class GroupIdGeneratorTest {

    private static final char SEPARATOR = ':';
    private static final String TEST_ID = "hash_id";
    private static final String TEST_DOMAIN = "domain";
    private static final String TEST_NAME = "name";

    @Test
    public void testIdGeneration() {
        Digester digesterMock = mock(Digester.class);
        GroupIdGenerator generator = new GroupIdGenerator(digesterMock);
        Group client = new Group();
        client.setDomain(TEST_DOMAIN);
        client.setName(TEST_NAME);
        when(digesterMock.digest(TEST_DOMAIN + ":" + TEST_NAME)).thenReturn(TEST_ID);
        assertThat(generator.generateId(client)).isEqualTo(TEST_ID);
    }

    @Test
    public void testEqualIdGeneration(){
        Group client = new Group();
        client.setDomain(TEST_DOMAIN);
        client.setName(TEST_NAME);

        Digester digester = DigesterFactory.murmur3_32();
        String idA = digester.digest(getIdString(client));

        Group client2 = new Group();
        client2.setDomain(TEST_DOMAIN);
        client2.setName(TEST_NAME);

        digester = DigesterFactory.murmur3_32();
        String idB = digester.digest(getIdString(client));
        assertThat(idA).isEqualTo(idB);
    }

    private String getIdString(Group entity){
        return Joiner.on(SEPARATOR).join(entity.getDomain(), entity.getName());
    }

}


text:
'use strict';

angular.module('flippersApp')
    .controller('AdminCtrl', function($q, $scope, $http, Auth, User, Restangular) {

        $scope.editing = false;

        $scope.users = [];
        $scope.newUser = {};
        $scope.roles = ['user', 'admin', 'viewer'];

        var loaded = [];
        var deleted = [];

        function reload() {
            return User.getList()

            .then(function(users) {
                loaded = users;
                resetWith(loaded);
            })

            .catch(function(err) {
                console.log(err);

                loaded = [];
                resetWith(loaded);
            });
        }

        function resetWith(users) {
            deleted = [];
            $scope.users = [];

            _.each(users, function(user) {
                user.persistent = true;
                $scope.users.push(user);
            });
        }

        function equal(lhs, rhs) {
            return _.isEqual(lhs, rhs, function(a, b) {
                return a._id === b._id &&
                    a.email === b.email &&
                    a.role === b.role;
            });
        }

        function asyncSave(users) {
            var promises = [];

            _.each(users, function(user) {
                if (!user.persistent) {
                    // CREATE invitation to register
                    // User.invite(user);
                } else if (user.deleted) {
                    // DELETE
                    promises.push(user.remove());
                } else {
                    var original = _.find(loaded, function(loadedUser) {
                        return user._id === loadedUser._id;
                    });

                    // Only update when the original values are different than the current values
                    if (original && !equal(user, original)) {
                        promises.push(user.put());
                    }
                }
            });

            return $q.all(promises);
        }

        // Initial loading of users
        reload();

        $scope.edit = function() {
            $scope.editing = true;

            var clones = _.map($scope.users, function(user) {
                return Restangular.copy(user);
            });

            resetWith(clones);
        };

        $scope.save = function() {
            return asyncSave($scope.users)

            .finally(function() {
                reload();
                $scope.editing = false;
            });
        };

        $scope.cancel = function() {
            resetWith(loaded);
            $scope.editing = false;
        };

        $scope.canModify = function(user) {
            return $scope.editing && !user.deleted;
        };

        $scope.canDelete = function(user) {
            return Auth.getCurrentUser()._id !== user._id;
        };

        $scope.delete = function(user) {
            if (user.persistent) {
                user.deleted = !user.deleted;
            } else {
                angular.forEach($scope.users, function(u, i) {
                    if (u === user) {
                        $scope.users.splice(i, 1);
                    }
                });
            }
        };

        $scope.add = function(user) {
            $scope.users.push(user);
            $scope.newUser = {};
        };
    });


text:
using LASI.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using NFluent;
using Fact = Xunit.FactAttribute;
using LASI.Utilities;
using static LASI.Utilities.EnumerableExtensions;

namespace LASI.Core.Tests
{
    //using Tripple = ValueTuple<Word, Word, Word>;
    /// <summary>
    ///This is A test class for VerbPhraseTest and is intended
    ///to contain all VerbPhraseTest Unit Tests
    /// </summary>
    public class VerbPhraseTest
    {
        /// <summary>
        ///A test for AdjectivalModifier
        /// </summary>
        [Fact]
        public void AdjectivalModifierTest()
        {
            var target = new VerbPhrase(new PastTenseVerb("grew"));
            IEntity subject = new PersonalPronoun("he");
            target.BindSubject(subject);
            IDescriptor expected = new Adjective("tall");
            IDescriptor actual;
            target.PostpositiveDescriptor = expected;
            actual = target.PostpositiveDescriptor;
            Check.That(actual).IsEqualTo(expected);
            Check.That(subject.Descriptors).Contains(expected);
        }
        /// <summary>
        ///A test for AggregateDirectObject
        /// </summary>
        [Fact]
        public void AggregateDirectObjectTest()
        {
            var target = CreateVerbPhrase();
            IAggregateEntity directObject = new AggregateEntity(
                new NounPhrase(new ProperSingularNoun("John"), new ProperSingularNoun("Smith")),
                new NounPhrase(new PossessivePronoun("his"), new CommonPluralNoun("cats"))
            );
            target.BindDirectObject(directObject);
            IAggregateEntity actual;
            actual = target.AggregateDirectObject;
            Check.That(directObject.Except(actual)).IsEmpty();
        }
        /// <summary>
        ///A test for AggregateIndirectObject
        /// </summary>
        [Fact]
        public void AggregateIndirectObjectTest()
        {
            var target = CreateVerbPhrase();
            var indirectObject = new AggregateEntity(
                new NounPhrase(
                    new ProperSingularNoun("John"),
                    new ProperSingularNoun("Smith")
                ), new NounPhrase(
                    new PossessivePronoun("his"),
                    new CommonPluralNoun("cats")
                )
            );
            target.BindIndirectObject(indirectObject);
            IAggregateEntity actual;
            actual = target.AggregateIndirectObject;
            Check.That(actual.Except(indirectObject)).IsEmpty();
        }
        /// <summary>
        ///A test for AggregateSubject
        /// </summary>
        [Fact]
        public void AggregateSubjectTest()
        {
            var target = CreateVerbPhrase();
            var subject = new AggregateEntity(
                new NounPhrase(
                    new ProperSingularNoun("John"),
                    new ProperSingularNoun("Smith")
                ), new NounPhrase(
                    new PossessivePronoun("his"),
                    new CommonPluralNoun("cats")
                )
            );
            target.BindSubject(subject);
            IAggregateEntity actual;
            actual = target.AggregateSubject;
            Check.That(actual.Except(subject)).IsEmpty();
        }
        /// <summary>
        ///A test for AttachObjectViaPreposition
        /// </summary>
        [Fact]
        public void AttachObjectViaPrepositionTest()
        {
            var target = new VerbPhrase(new BaseVerb("consume"));
            IPrepositional prepositional = new Preposition("with");
            ILexical prepositionalObject = new NounPhrase(new Adjective("great"), new CommonSingularNoun("haste"));
            prepositional.BindObject(prepositionalObject);
            target.AttachObjectViaPreposition(prepositional);
            Check.That(target.ObjectOfThePreposition).IsEqualTo(prepositionalObject);
        }
        /// <summary>
        ///A test for BindDirectObject
        /// </summary>
        [Fact]
        public void BindDirectObjectTest()
        {
            var target = CreateVerbPhrase();
            IEntity directObject = new NounPhrase(new Determiner("the"), new CommonSingularNoun("forest"));
            target.BindDirectObject(directObject);
            Check.That(target.HasDirectObject(e => e == directObject)).IsTrue();
        }
        /// <summary>
        ///A test for BindIndirectObject
        /// </summary>
        [Fact]
        public void BindIndirectObjectTest()
        {
            var target = CreateVerbPhrase();
            IEntity indirectObject = new ProperSingularNoun("John");
            target.BindIndirectObject(indirectObject);
            Check.That(target.HasIndirectObject(e => e == indirectObject)).IsTrue();
        }
        /// <summary>
        ///A test for BindSubject
        /// </summary>
        [Fact]
        public void BindSubjectTest()
        {
            var target = CreateVerbPhraseHelp();
            IEntity subject = new CommonPluralNoun("cats");
            target.BindSubject(subject);
            Check.That(target.HasSubject(e => e == subject)).IsTrue();
        }
        /// <summary>
        ///A test for BoundSubject
        /// </summary>
        [Fact]
        public void BoundSubjectTest()
        {
            var target = CreateVerbPhrase();
            IEntity expected = new PersonalPronoun("he");
            IEntity actual;
            target.BindSubject(expected);
            actual = target.Subjects.First();
            Check.That(actual).IsEqualTo(expected);
        }
        /// <summary>
        ///A test for DirectObjects
        /// </summary>
        [Fact]
        public void DirectObjectsTest()
        {
            var target = CreateVerbPhrase();
            IEnumerable<IEntity> actual;
            actual = target.DirectObjects;
            Check.That(target.DirectObjects).IsEmpty();
            IEntity directObject = new NounPhrase(
                new Determiner("the"),
                new CommonSingularNoun("book")
            );
            target.BindDirectObject(directObject);
            Check.That(target.DirectObjects).Contains(directObject);
        }
        /// <summary>
        ///A test for HasDirectObject
        /// </summary>
        [Fact]
        public void HasDirectObjectTest()
        {
            var target = CreateVerbPhrase();
            IEntity entity = new CommonPluralNoun("cats");
            target.BindDirectObject(entity);

            var expected = true;
            bool actual;
            actual = target.HasDirectObject(predicate);
            Check.That(actual).IsEqualTo(expected);

            bool predicate(IEntity e) => e.Text == "cats";
        }
        /// <summary>
        ///A test for HasIndirectObject
        /// </summary>
        [Fact]
        public void HasIndirectObjectTest()
        {
            var target = CreateVerbPhraseHelp();
            IEntity entity = new CommonPluralNoun("cats");
            target.BindIndirectObject(entity);

            var expected = true;
            bool actual;
            actual = target.HasIndirectObject(predicate);
            Check.That(actual).IsEqualTo(expected);

            bool predicate(IEntity e) => e.Text == "cats";
        }
        /// <summary>
        ///A test for HasObject
        /// </summary>
        [Fact]
        public void HasObjectTest()
        {
            var target = CreateVerbPhraseHelp();
            IEntity entity = new CommonPluralNoun("cats");

            var expected = true;
            bool actual;
            target.BindDirectObject(entity);
            actual = target.HasObject(predicate);
            Check.That(actual).IsEqualTo(expected);
            target.BindIndirectObject(entity);
            actual = target.HasObject(predicate);
            Check.That(actual).IsEqualTo(expected);

            bool predicate(IEntity e) => e.Text == "cats";
        }
        [Fact]
        public void HasSubjectOrObjectRespectsDirectObjects()
        {
            var target = CreateVerbPhraseHelp();

            target.BindDirectObject(new CommonPluralNoun("cats"));

            Check.That(target.HasSubjectOrObject(e => e.Text == "cats")).IsTrue();
        }
        [Fact]
        public void HasSubjectOrObjectRespectsIndirectObjects()
        {
            var target = CreateVerbPhraseHelp();

            target.BindIndirectObject(new CommonPluralNoun("cats"));

            Check.That(target.HasSubjectOrObject(e => e.Text == "cats")).IsTrue();
        }
        /// <summary>
        ///A test for HasSubjectOrObject
        /// </summary>
        [Fact]
        public void HasSubjectOrObjectRespectsSubjects()
        {
            var target = CreateVerbPhraseHelp();

            target.BindSubject(new CommonPluralNoun("cats"));

            Check.That(target.HasSubjectOrObject(e => e.Text == "cats")).IsTrue();
        }
        /// <summary>
        ///A test for HasSubject
        /// </summary>
        [Fact]
        public void HasSubjectTest()
        {
            var target = CreateVerbPhraseHelp();

            target.BindSubject(new CommonPluralNoun("cats"));

            Check.That(target.HasSubject(e => e.Text == "cats")).IsTrue();
        }
        /// <summary>
        ///A test for IndirectObjects
        /// </summary>
        [Fact]
        public void IndirectObjectsTest()
        {
            var target = CreateVerbPhrase();
            IEnumerable<IEntity> actual;
            actual = target.IndirectObjects;
            Check.That(target.IndirectObjects).IsEmpty();
            IEntity indirectObject = new PersonalPronoun("them");
            target.BindIndirectObject(indirectObject);
            Check.That(target.IndirectObjects).Contains(indirectObject);
        }
        /// <summary>
        ///A test for IsClassifier
        /// </summary>
        [Fact]
        public void IsClassifierTest()
        {
            var target = new VerbPhrase(
                new Adverb("certainly"),
                new PastTenseVerb("is")
            );

            Check.That(target.IsClassifier).IsTrue();
        }
        /// <summary>
        ///A test for IsClassifier
        /// </summary>
        [Fact]
        public void IsClassifierTest1()
        {
            var target = new VerbPhrase(
                new Adverb("certainly"),
                new PastTenseVerb("owned"),
                new Quantifier("many")
            );

            Check.That(target.IsClassifier).IsFalse();
        }
        /// <summary>
        ///A test for IsPossessive
        /// </summary>
        [Fact]
        public void IsPossessiveTest()
        {
            var target = new VerbPhrase(
                new Adverb("certainly"),
                new PastTenseVerb("had"),
                new Quantifier("many")
            );
            Check.That(target.IsPossessive).IsTrue();
        }
        /// <summary>
        ///A test for IsPossessive
        /// </summary>
        [Fact]
        public void IsPossessiveTest1()
        {
            var target = new VerbPhrase(
                new Adverb("certainly"),
                new PastTenseVerb("was")
            );

            Check.That(target.IsPossessive).IsFalse();
        }
        /// <summary>
        ///A test for Modality
        /// </summary>
        [Fact]
        public void ModalityTest()
        {
            var target = CreateVerbPhrase();
            var expected = new ModalAuxilary("cannot");
            ModalAuxilary actual;
            target.Modality = expected;
            actual = target.Modality;
            Check.That(actual).IsEqualTo(expected);
        }
        /// <summary>
        ///A test for ModifyWith
        /// </summary>
        [Fact]
        public void ModifyWithTest()
        {
            var target = CreateVerbPhrase();
            IAdverbial adv = new Adverb("daringly");
            target.ModifyWith(adv);
            Check.That(target.AdverbialModifiers).Contains(adv);
        }
        /// <summary>
        ///A test for ToString
        /// </summary>
        [Fact]
        public void ToStringTest()
        {
            Phrase.VerboseOutput = false;
            var target = new VerbPhrase(
                new BaseVerb("run"),
                new Adverb("swiftly"),
                new Preposition("through")
            );
            var expected = "VerbPhrase \"run swiftly through\"";
            string actual;
            actual = target.ToString();
            Check.That(actual).IsEqualTo(expected);
        }
        /// <summary>
        ///A test for VerbPhrase Constructor
        /// </summary>
        [Fact]
        public void VerbPhraseConstructorTest()
        {
            IEnumerable<Word> composedWords = new Word[] { new BaseVerb("run"), new Adverb("swiftly"), new Preposition("through") };
            var target = new VerbPhrase(composedWords);
            Check.That(target.Words).IsEqualTo(composedWords);
        }
        /// <summary>
        ///A test for VerbPhrase Constructor
        /// </summary>
        [Fact]
        public void VerbPhraseConstructorTest1()
        {
            var target = new VerbPhrase(new BaseVerb("run"), new Adverb("swiftly"), new Preposition("through"));
            var words = target.Words.ToList();

            Check.That(words[0].Text).IsEqualTo("run");
            Check.That(words[0].GetType()).IsEqualTo(typeof(BaseVerb));
            Check.That(words[1].Text).IsEqualTo("swiftly");
            Check.That(words[1].GetType()).IsEqualTo(typeof(Adverb));
            Check.That(words[2].Text).IsEqualTo("through");
            Check.That(words[2].GetType()).IsEqualTo(typeof(Preposition));
        }

        private static VerbPhrase CreateVerbPhrase() => new VerbPhrase(new BaseVerb("run"), new Adverb("swiftly"), new Preposition("through"));
        private static VerbPhrase CreateVerbPhraseHelp() => new VerbPhrase(new BaseVerb("help"));
    }
}


text:
"""
Events:
	always
	daily
	monthly
	weekly
"""

# imports - standard imports
import os
import time

# imports - third party imports
import schedule

# imports - module imports
import frappe
from frappe.installer import update_site_config
from frappe.utils import get_sites, now_datetime
from frappe.utils.background_jobs import get_jobs

DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'

def start_scheduler():
	'''Run enqueue_events_for_all_sites every 2 minutes (default).
	Specify scheduler_interval in seconds in common_site_config.json'''

	schedule.every(frappe.get_conf().scheduler_tick_interval or 60).seconds.do(enqueue_events_for_all_sites)

	while True:
		schedule.run_pending()
		time.sleep(1)

def enqueue_events_for_all_sites():
	'''Loop through sites and enqueue events that are not already queued'''

	if os.path.exists(os.path.join('.', '.restarting')):
		# Don't add task to queue if webserver is in restart mode
		return

	with frappe.init_site():
		sites = get_sites()

	for site in sites:
		try:
			enqueue_events_for_site(site=site)
		except Exception as e:
			print(e.__class__, 'Failed to enqueue events for site: {}'.format(site))

def enqueue_events_for_site(site):
	def log_and_raise():
		error_message = 'Exception in Enqueue Events for Site {0}\n{1}'.format(site, frappe.get_traceback())
		frappe.logger("scheduler").error(error_message)

	try:
		frappe.init(site=site)
		frappe.connect()
		if is_scheduler_inactive():
			return

		enqueue_events(site=site)

		frappe.logger("scheduler").debug('Queued events for site {0}'.format(site))
	except frappe.db.OperationalError as e:
		if frappe.db.is_access_denied(e):
			frappe.logger("scheduler").debug('Access denied for site {0}'.format(site))
		else:
			log_and_raise()
	except:
		log_and_raise()

	finally:
		frappe.destroy()

def enqueue_events(site):
	if schedule_jobs_based_on_activity():
		frappe.flags.enqueued_jobs = []
		queued_jobs = get_jobs(site=site, key='job_type').get(site) or []
		for job_type in frappe.get_all('Scheduled Job Type', ('name', 'method'), dict(stopped=0)):
			if not job_type.method in queued_jobs:
				# don't add it to queue if still pending
				frappe.get_doc('Scheduled Job Type', job_type.name).enqueue()

def is_scheduler_inactive():
	if frappe.local.conf.maintenance_mode:
		return True

	if frappe.local.conf.pause_scheduler:
		return True

	if is_scheduler_disabled():
		return True

	return False

def is_scheduler_disabled():
	if frappe.conf.disable_scheduler:
		return True

	return not frappe.utils.cint(frappe.db.get_single_value("System Settings", "enable_scheduler"))

def toggle_scheduler(enable):
	frappe.db.set_value("System Settings", None, "enable_scheduler", 1 if enable else 0)

def enable_scheduler():
	toggle_scheduler(True)

def disable_scheduler():
	toggle_scheduler(False)

def schedule_jobs_based_on_activity(check_time=None):
	'''Returns True for active sites defined by Activity Log
	Returns True for inactive sites once in 24 hours'''
	if is_dormant(check_time=check_time):
		# ensure last job is one day old
		last_job_timestamp = frappe.db.get_last_created('Scheduled Job Log')
		if not last_job_timestamp:
			return True
		else:
			if ((check_time  or now_datetime()) - last_job_timestamp).total_seconds() >= 86400:
				# one day is passed since jobs are run, so lets do this
				return True
			else:
				# schedulers run in the last 24 hours, do nothing
				return False
	else:
		# site active, lets run the jobs
		return True

def is_dormant(check_time=None):
	last_activity_log_timestamp = frappe.db.get_last_created('Activity Log')
	since = (frappe.get_system_settings('dormant_days') or 4) * 86400
	if not last_activity_log_timestamp:
		return True
	if ((check_time or now_datetime()) - last_activity_log_timestamp).total_seconds() >= since:
		return True
	return False

@frappe.whitelist()
def activate_scheduler():
	if is_scheduler_disabled():
		enable_scheduler()
	if frappe.conf.pause_scheduler:
		update_site_config('pause_scheduler', 0)


text:
define({
  "addTaskTip": "Fügen Sie dem Widget mindestens einen Filter hinzu, und konfigurieren Sie Parameter für jeden von ihnen.",
  "enableMapFilter": "Entfernen Sie den voreingestellten Layer-Filter aus der Karte.",
  "newFilter": "Neuer Filter",
  "filterExpression": "Filterausdruck",
  "layerDefaultSymbolTip": "Standardsymbol des Layers verwenden",
  "uploadImage": "Ein Bild hochladen",
  "selectLayerTip": "Wählen Sie einen Layer aus.",
  "setTitleTip": "Legen Sie einen Titel fest."
});


text:
<!DOCTYPE html>

    <title>webpack boilerplate</title>
    <meta charset='utf-8' />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <base href='/'>


text:
<?php

function t() {
  return call_user_func_array("BLocalization::_", func_get_args());
}

class BLocalization extends BObject
{

  /**
   * Available locales
   *
   * @var array Locales
   */
  var $locales = array(
    'en' => 'en_US',
    'de' => 'de_DE'
  );

  var $enabled = array();

  /**
   * The users locale
   *
   * @var string 2 char locale
   */
  var $user_locale = 'en';

  static $_instance = null;

  public function __construct()
 {
    // fetch cookie or default

    $this->set('enabled', BSettings::f('localization.locales', array('foo')));
    $this->set('user_locale', $this->getUserLocale());

  }

  public static function &getInstance($type=null)
  {

    if (!isset(self::$_instance) && !is_object(self::$_instance)) {

      if (is_null($type)) {
        $type = BSettings::f('localization.engine', 'none');
      }

      $classname = sprintf('BLocalization%s', ucfirst($type));

      if (!class_exists($classname))
{
        BLoader::register($classname, dirname(__FILE__).DS.'engines'.DS.(BString::camelcase_to_underscores($type)).'.inc.php');
        BLoader::autoload($classname);

        if (!class_exists($classname))
{
          die( sprintf('Invalid BLocalization type received: %s', $type) );
        }

      }

      self::$_instance = new $classname();
    }

    return self::$_instance;
  }

  /*
   * public function _()
  {
    $self =& self::getInstance();
    return call_user_func_array(array($self, 'translate'), func_get_args());
  }
   */

  public function setLocale($locale)
  {
    if (!$this->isLocale($locale)) return false;
    $this->setUserLocale($locale);

    $this->set('user_locale', $locale);
    return $locale;
  }

  public function getLocale($ietf=false)
  {
    return (($ietf) ? $this->locales[($this->get('user_locale'))] : $this->get('user_locale'));
  }

  public function isLocale($locale)
  {
    return (bool)(isset($this->locales[$locale]) && in_array($locale, $this->enabled));
  }

  public function setUserLocale($locale)
  {
    $cookie = BInput::getInstance('cookie');
    $cookie->set('user_locale', $locale, time()+(60*60*24*365), '/');
  }

  public function getUserLocale()
 {

    $default_lang = null;
    $browser_lang = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
    if ($this->isLocale($browser_lang)) {
      $default_lang = $browser_lang;
    }

    if (is_null($default_lang)) {
      $default_lang = BSettings::f('localization.default_locale', 'en');
    }

    $oInput =& BInput::getInstance('cookie');
    return $oInput->get('user_locale', $default_lang, 'cookie');
  }

  public function record()
  {

  }

  public function _($string, $options=array())
  {
    return $string;
  }
}


text:
layout: post
title: "Hypothesis Testing: Z-test"
excerpt: "hypothesis testing, sigma known, z-test"
categories: knownotes
tags: [statistics]
comments: true
share: true
author: chungyu
---
> Mainly from the lecture notes of
* [JB Statistics](http://www.jbstatistics.com/)

# Example:
![ztest-exp1]({{site.url}}/images/stat/ztest-exp1.png)
![ztest-exp2]({{site.url}}/images/stat/ztest-exp2.png)

###### Supposed we also do a plot to see whether it's nearly normal
![ztest-exp5]({{site.url}}/images/stat/ztest-exp5.png)

######  And we do draw a blot plot for the 16 samples
![ztest-exp4]({{site.url}}/images/stat/ztest-exp4.png)

###### Question Does this gap really implies our initial assumption is correct? How do we decide?

---

# Z-Test
![ztest1]({{site.url}}/images/stat/ztest-1.png)
![ztest2]({{site.url}}/images/stat/ztest-2.png)
###### Definition
![ztest3]({{site.url}}/images/stat/ztest-3.png)

# Solution for the example
![sol]({{site.url}}/images/stat/sol.png)
![sol2]({{site.url}}/images/stat/sol2.png)
![sol1]({{site.url}}/images/stat/sol1.png)
![sol3]({{site.url}}/images/stat/sol3.png)
![sol4]({{site.url}}/images/stat/sol4.png)

# Question remains:

![questionafterztest]({{site.url}}/images/stat/questionafterztest.png)
![questionafterztest2]({{site.url}}/images/stat/questionafterztest2.png)


text:
<?php

namespace Chamilo\Application\Weblcms\Tool\Implementation\CourseGroup\Form\Handler;

use Chamilo\Application\Weblcms\Course\Storage\DataClass\Course;
use Chamilo\Application\Weblcms\Tool\Implementation\CourseGroup\Infrastructure\Service\PlatformGroupUsersSubscriber;
use Chamilo\Application\Weblcms\Tool\Implementation\CourseGroup\Storage\DataClass\CourseGroup;
use Chamilo\Application\Weblcms\Tool\Implementation\Teams\Form\Type\PlatformGroupTeamType;
use Chamilo\Core\User\Storage\DataClass\User;
use Chamilo\Libraries\Format\Form\FormHandler;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * @package Chamilo\Application\Weblcms\Tool\Implementation\Teams\Form\Handler
 *
 * @author Sven Vanpoucke - Hogeschool Gent
 */
class SubscribePlatformGroupUsersFormHandler extends FormHandler
{
    /**
     * @var PlatformGroupUsersSubscriber
     */
    protected $platformGroupUsersSubscriber;

    /**
     * @var CourseGroup
     */
    protected $courseGroup;

    /**
     * PlatformGroupUserSubscriberFormHandler constructor.
     *
     * @param PlatformGroupUsersSubscriber $platformGroupUsersSubscriber
     */
    public function __construct(PlatformGroupUsersSubscriber $platformGroupUsersSubscriber)
    {
        $this->platformGroupUsersSubscriber = $platformGroupUsersSubscriber;
    }

    /**
     * @param CourseGroup $courseGroup
     *
     * @return SubscribePlatformGroupUsersFormHandler
     */
    public function setCourseGroup(CourseGroup $courseGroup): SubscribePlatformGroupUsersFormHandler
    {
        $this->courseGroup = $courseGroup;

        return $this;
    }

    /**
     * @param FormInterface $form
     * @param Request $request
     *
     * @return bool
     * @throws \Exception
     */
    public function handle(FormInterface $form, Request $request): bool
    {
        if (!parent::handle($form, $request))
        {
            return false;
        }

        if (!$this->courseGroup instanceof CourseGroup)
        {
            throw new \RuntimeException('The form handler can not be executed without a valid course group object');
        }

        $data = $form->getData();

        $platformGroupIds = json_decode($data[PlatformGroupTeamType::ELEMENT_PLATFORM_GROUPS]);

        $this->platformGroupUsersSubscriber->subscribeUsersFromPlatformGroupsInCourseGroup(
            $this->courseGroup, $platformGroupIds
        );

        return true;
    }

    protected function rollBackModel(FormInterface $form)
    {
    }
}


text:
from __future__ import absolute_import
from builtins import object
from proteus import *
from proteus.default_p import *
try:
    from .risingBubble import *
except:
    from risingBubble import *
from proteus.mprans import MCorr3P

LevelModelType = MCorr3P.LevelModel
coefficients = MCorr3P.Coefficients(LS_model=LS_model,
                                    V_model=V_model,
                                    ME_model=MCORR_model,
                                    VOF_model=VOF_model,
                                    VOS_model=VOS_model,
                                    applyCorrection=applyCorrection,
                                    nd=nd,
                                    checkMass=False,
                                    useMetrics=useMetrics,
                                    epsFactHeaviside=epsFact_consrv_heaviside,
                                    epsFactDirac=epsFact_consrv_dirac,
                                    epsFactDiffusion=epsFact_consrv_diffusion)

class zero_phi(object):
    def __init__(self):
        pass
    def uOfX(self,X):
        return 0.0
    def uOfXT(self,X,t):
        return 0.0

initialConditions  = {0:zero_phi()}


text:
<?php

$installer = $this;
$installer->startSetup();
$installer->run("
    DROP TABLE IF EXISTS {$installer->getTable('sms/templates')};
    CREATE TABLE `{$installer->getTable('sms/templates')}` (
      `id` int(11) NOT NULL auto_increment,
      `type` text,
      `message` text,
      `active` int(10),
      `updated_at` datetime default NULL,
      `created_at` timestamp NOT NULL default CURRENT_TIMESTAMP,
      PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

");
$installer->endSetup();


text:
package ardb

import (
	"crypto/rand"
	"fmt"
	"testing"

	"github.com/stretchr/testify/require"
	"github.com/zero-os/0-Disk/config"
	"github.com/zero-os/0-Disk/errors"
	"github.com/zero-os/0-Disk/nbd/ardb/command"
	"github.com/zero-os/0-Disk/redisstub/ledisdb"
)

func cluster() StorageCluster {
	server := ledisdb.NewServer()
	cluster, err := NewUniCluster(config.StorageServerConfig{
		Address: server.Address(),
	}, nil)
	if err != nil {
		panic(err)
	}
	return cluster
}

func TestUniCluster(t *testing.T) {
	server := ledisdb.NewServer()
	defer server.Close()

	const (
		vdiskID          = "foo"
		metaKey          = "meta_" + vdiskID
		blockSize  int64 = 8
		blockCount int64 = 8
	)

	serverConfig := config.StorageServerConfig{State: config.StorageServerStateRIP}

	require := require.New(t)

	_, err := NewUniCluster(serverConfig, nil)
	require.Equal(ErrNoServersAvailable, err, "should fail, as server is dead")

	serverConfig = config.StorageServerConfig{}
	_, err = NewUniCluster(serverConfig, nil)
	require.Error(err, "should fail, as we have an invalid config")

	serverConfig = config.StorageServerConfig{
		Address: server.Address(),
		State:   config.StorageServerStateOffline,
	}
	_, err = NewUniCluster(serverConfig, nil)
	require.Equal(ErrServerStateNotSupported, err, "should fail, as we have an invalid server state")

	serverConfig.State = config.StorageServerStateOnline
	cluster, err := NewUniCluster(serverConfig, nil)
	require.NoError(err, "should succeed now, as the server is available")

	var contentSlice [][]byte

	// store blocks, this should be fine
	for index := int64(0); index < blockCount; index++ {
		content := make([]byte, blockSize)
		rand.Read(content)
		contentSlice = append(contentSlice, content)

		_, err = cluster.Do(Command(command.Increment, metaKey))
		_, err = cluster.DoFor(index, Command(command.HashSet, vdiskID, index, content))
		require.NoError(err)
	}

	// check the meta key
	fetchedBlockCount, err := Int64(cluster.Do(Command(command.Get, metaKey)))
	require.NoError(err)
	require.Equal(blockCount, fetchedBlockCount)

	// load blocks, this should be fine as well
	for index := int64(0); index < blockCount; index++ {
		content, err := Bytes(cluster.DoFor(index, Command(command.HashGet, vdiskID, index)))
		require.NoError(err)
		require.Equal(contentSlice[index], content)
	}
}

func TestCluster(t *testing.T) {
	server := ledisdb.NewServer()
	defer server.Close()

	const (
		vdiskID          = "foo"
		metaKey          = "meta_" + vdiskID
		blockSize  int64 = 8
		blockCount int64 = 8
	)

	sourceClusterConfig := config.StorageClusterConfig{
		Servers: []config.StorageServerConfig{
			config.StorageServerConfig{State: config.StorageServerStateRIP},
			config.StorageServerConfig{State: config.StorageServerStateRIP},
			config.StorageServerConfig{State: config.StorageServerStateRIP},
		},
	}

	require := require.New(t)

	_, err := NewCluster(sourceClusterConfig, nil)
	require.Equal(ErrNoServersAvailable, err, "should fail, as we don't have any online servers")

	sourceClusterConfig.Servers[1] = config.StorageServerConfig{}
	_, err = NewCluster(sourceClusterConfig, nil)
	require.Error(err, "should fail, as we have an invalid config")

	sourceClusterConfig.Servers[1] = config.StorageServerConfig{
		Address: server.Address(),
		State:   config.StorageServerStateOffline,
	}
	_, err = NewCluster(sourceClusterConfig, nil)
	require.Equal(ErrServerStateNotSupported, err, "should fail, as we have an invalid server state")

	sourceClusterConfig.Servers[1].State = config.StorageServerStateOnline
	cluster, err := NewCluster(sourceClusterConfig, nil)
	require.NoError(err, "should succeed now, as we have one available server")

	var contentSlice [][]byte

	// store blocks, this should be fine
	for index := int64(0); index < blockCount; index++ {
		content := make([]byte, blockSize)
		rand.Read(content)
		contentSlice = append(contentSlice, content)

		_, err = cluster.Do(Command(command.Increment, metaKey))
		_, err = cluster.DoFor(index, Command(command.HashSet, vdiskID, index, content))
		require.NoError(err)
	}

	// check the meta key
	fetchedBlockCount, err := Int64(cluster.Do(Command(command.Get, metaKey)))
	require.NoError(err)
	require.Equal(blockCount, fetchedBlockCount)

	// load blocks, this should be fine as well
	for index := int64(0); index < blockCount; index++ {
		content, err := Bytes(cluster.DoFor(index, Command(command.HashGet, vdiskID, index)))
		require.NoError(err)
		require.Equal(contentSlice[index], content)
	}
}

func TestComputeServerIndex_MaxAvailability(t *testing.T) {
	require := require.New(t)

	const (
		serverCount = 13
		objectCount = 100
	)

	for objectIndex := int64(0); objectIndex < objectCount; objectIndex++ {
		index, err := ComputeServerIndex(serverCount, objectIndex,
			func(_ int64) (bool, error) { return true, nil })
		require.NoError(err)
		require.Equal(objectIndex%serverCount, index)
	}
}

func TestComputeServerIndex_ErrorAtEvenServerIndex(t *testing.T) {
	require := require.New(t)

	const (
		serverCount = 15
		objectCount = 111
	)

	for objectIndex := int64(0); objectIndex < objectCount; objectIndex++ {
		index, err := ComputeServerIndex(serverCount, objectIndex, func(i int64) (bool, error) {
			if i%2 == 0 {
				return false, ErrServerUnavailable
			}
			return true, nil
		})

		if (objectIndex%serverCount)%2 == 0 {
			require.Equal(ErrServerUnavailable, err)
		} else {
			require.NoError(err)
			require.Equal(objectIndex%serverCount, index)
		}
	}
}

func TestComputeServerIndex_OddIndexedServersDead(t *testing.T) {
	require := require.New(t)

	pred := func(i int64) (bool, error) {
		if i%2 == 1 {
			return false, nil
		}
		return true, nil
	}

	test := func(index, count, serverIndex int64, err error) {
		require.NoError(err)
		if index != -1 {
			require.Equal(serverIndex, index)
			return
		}
		// is any other serverIndex
		for i := int64(0); i < count; i += 2 {
			if i == serverIndex {
				return
			}
		}
		t.Fatal("serverIndex was odd")
	}

	count := int64(2)

	serverIndex, err := ComputeServerIndex(count, 0, pred)
	test(0, count, serverIndex, err)

	serverIndex, err = ComputeServerIndex(count, 1, pred)
	test(0, count, serverIndex, err)

	count++

	serverIndex, err = ComputeServerIndex(count, 1, pred)
	test(-1, count, serverIndex, err)

	serverIndex, err = ComputeServerIndex(count, 2, pred)
	test(-1, count, serverIndex, err)
}

func TestComputeServerIndex_SomeServersDead_SomeServersError(t *testing.T) {
	require := require.New(t)

	pred := func(i int64) (bool, error) {
		switch i {
		case 1:
			return false, nil
		case 2:
			return false, ErrServerUnavailable
		default:
			return true, nil
		}
	}

	const count = int64(3)

	test := func(index, serverIndex int64, err error) {
		if errors.Cause(err) == ErrServerUnavailable {
			return // this is possible
		}

		require.NoError(err)
		if index != -1 {
			require.Equal(serverIndex, index)
			return
		}
		// is any other serverIndex
		for i := int64(0); i < count; i += 2 {
			if i == serverIndex {
				return
			}
		}
		t.Fatal("serverIndex was odd")
	}

	testErr := func(_ int64, err error) {
		require.Equal(ErrServerUnavailable, err)
	}

	for i := int64(0); i < 30; i += 3 {
		serverIndex, err := ComputeServerIndex(count, i, pred)
		test(0, serverIndex, err)

		serverIndex, err = ComputeServerIndex(count, i+1, pred)
		test(-1, serverIndex, err)

		testErr(ComputeServerIndex(count, i+2, pred))
	}
}

func TestUniClusterDoForAll(t *testing.T) {
	server := ledisdb.NewServer()
	defer server.Close()

	uniCluster, err := NewUniCluster(config.StorageServerConfig{Address: server.Address()}, nil)
	if err != nil {
		t.Fatal(err)
	}

	testClusterDoForAll(t, uniCluster)
}

func TestClusterDoForAll(t *testing.T) {
	// create a cluster config for 4 servers
	var cfg config.StorageClusterConfig
	for i := 0; i < 4; i++ {
		server := ledisdb.NewServer()
		defer server.Close()
		cfg.Servers = append(cfg.Servers, config.StorageServerConfig{
			Address: server.Address(),
		})
	}

	cluster, err := NewCluster(cfg, nil)
	if err != nil {
		t.Fatal(err)
	}

	testClusterDoForAll(t, cluster)
}

func testClusterDoForAll(t *testing.T, cluster StorageCluster) {
	require := require.New(t)

	const valueCount = 1024
	// base test - ensure these values don't exist yet using the DoFor metho
	for i := int64(0); i < valueCount; i++ {
		exists, err := Bool(cluster.DoFor(i, Command(command.Exists, fmt.Sprintf("foo:%d", i))))
		require.NoError(err)
		require.False(exists)
	}

	// now check the same with DoForAll
	var pairs []IndexActionPair
	for i := int64(0); i < valueCount; i++ {
		pairs = append(pairs, IndexActionPair{
			Index:  i,
			Action: Command(command.Exists, fmt.Sprintf("foo:%d", i)),
		})
	}
	replies, err := cluster.DoForAll(pairs)
	require.NoError(err)
	require.Len(replies, valueCount)
	for _, reply := range replies {
		exists, err := Bool(reply, nil)
		require.NoError(err)
		require.False(exists)
	}

	// now let's store the index as the value for each value
	pairs = nil
	for i := int64(0); i < valueCount; i++ {
		pairs = append(pairs, IndexActionPair{
			Index:  i,
			Action: Command(command.Set, fmt.Sprintf("foo:%d", i), i),
		})
	}
	replies, err = cluster.DoForAll(pairs)
	require.NoError(err)
	require.Len(replies, valueCount)
	for _, reply := range replies {
		ok, err := String(reply, nil)
		require.NoError(err)
		require.Equal("OK", ok)
	}

	// now let's get values, and ensure that the order is correct
	pairs = nil
	for i := int64(0); i < valueCount; i++ {
		pairs = append(pairs, IndexActionPair{
			Index:  i,
			Action: Command(command.Get, fmt.Sprintf("foo:%d", i)),
		})
	}
	replies, err = cluster.DoForAll(pairs)
	require.NoError(err)
	require.Len(replies, valueCount)
	for i, reply := range replies {
		index, err := Int64(reply, nil)
		require.NoError(err)
		require.Equal(int64(i), index)
	}

	// let's delete all odd indices using `DoFor`, as a last sanity check
	for i := int64(1); i < valueCount; i += 2 {
		ok, err := Int(cluster.DoFor(i, Command(command.Delete, fmt.Sprintf("foo:%d", i))))
		require.NoError(err)
		require.Equal(1, ok)
	}

	// now let's get values, and ensure that the odd indices are deleted, and that the order is still correct
	pairs = nil
	for i := int64(0); i < valueCount; i++ {
		pairs = append(pairs, IndexActionPair{
			Index:  i,
			Action: Command(command.Get, fmt.Sprintf("foo:%d", i)),
		})
	}
	replies, err = cluster.DoForAll(pairs)
	require.NoError(err)
	require.Len(replies, valueCount)
	for i, reply := range replies {
		index, err := Int64(reply, nil)
		if i%2 == 1 {
			require.Equal(ErrNil, err)
			continue
		}
		require.NoError(err)
		require.Equal(int64(i), index)
	}
}


text:
///////////////////////////////////////////////////////////
// CHKPATH.C
// Routines to check path and create directory.
///////////////////////////////////////////////////////////

#define INCL_DOSFILEMGR
#define INCL_DOSPROCESS
#define INCL_DOS
#include <os2.h>
#include <direct.h>
#include <stdio.h>
#include <string.h>

#include "zin.h"

APIRET CheckPath (char * szPath)
{
FILESTATUS3  PathInfoBuf;     /* File info buffer */
ULONG        PathInfoBufSize; /* Data buffer size */

//WinMessageBox(HWND_DESKTOP, hwndClient, szPath, "CheckPath", 0, NULL);
PathInfoBufSize = sizeof(FILESTATUS3);

return DosQueryPathInfo(szPath, 1, &PathInfoBuf,
                             PathInfoBufSize);

}

///////////////////////////////////////////////////////////
// CreateDirectory
// Creates the specified path.
//
// History:
//    Created:    04/10/95    Bruce Shankle
//
// Returns 0 if successful, 1 otherwise.
///////////////////////////////////////////////////////////
APIRET CreateDirectory(char * szPath)
{
static CHAR szPathBuffer[CCHMAXPATH];
static CHAR szTestPathBuffer[CCHMAXPATH];
CHAR * p;

int iRes;
APIRET apiret;

//Clear path buffer
strcpy (szPathBuffer, "");

//See if last character is a \ or a / (some people type this) and eliminate it

p=szPath+strlen(szPath)-1;
if ( (*p=='\\') || (*p=='/') )
    {
    *p='\0';
    }

p=szPath+3;
strncpy(szPathBuffer, szPath, 3);

//Loop through to each \ and build and create dirs as we go
while ( strlen(szPathBuffer) < strlen(szPath) )
    {
    if ( (*p=='\\') || (*p=='/') )
        {
   //     WinMessageBox(HWND_DESKTOP, hwndClient, "p=92", "", 0, NULL);
        //Make sure path doesn't already exist
        strcpy(szTestPathBuffer,szPathBuffer);
        apiret=CheckPath(szTestPathBuffer);

        if (apiret!=0)
            {
      //      WinMessageBox(HWND_DESKTOP, hwndClient, szPathBuffer, "mkdir", 0, NULL);
            strcpy(szTestPathBuffer,szPathBuffer);
            iRes=mkdir(szTestPathBuffer);
         //   sprintf(szBuffer,"MKDir returned: %d", iRes);
          //  WinMessageBox(HWND_DESKTOP, hwndClient, szBuffer, "", 0, NULL);
            if (iRes!=0) return 1;
            }

        strcat(szPathBuffer, "\\");
       // WinMessageBox(HWND_DESKTOP, hwndClient, szPathBuffer, "mkdir sp", 0, NULL);

        p++;
        }

    else
        {
        //Copy next character of path
        strncat(szPathBuffer, p, 1);
        //WinMessageBox(HWND_DESKTOP, hwndClient, szPathBuffer, "mkdir", 0, NULL);
        p++;
        }
    }

//Create last part of path
strcpy(szTestPathBuffer,szPathBuffer);
apiret=CheckPath(szTestPathBuffer);
if (apiret!=0)
    {
    //WinMessageBox(HWND_DESKTOP, hwndClient, szPathBuffer, "mkdir last", 0, NULL);
    strcpy(szTestPathBuffer,szPathBuffer);
    iRes=mkdir(szTestPathBuffer);
    //sprintf(szBuffer,"MKDir returned: %d", iRes);
    //WinMessageBox(HWND_DESKTOP, hwndClient, szBuffer, "", 0, NULL);
    if (iRes!=0) return 1;
    }

//Make sure path exists and return
strcpy(szTestPathBuffer,szPathBuffer);
return CheckPath(szTestPathBuffer);
}
///////////////////////////////////////////////////////////

///////////////////////////////////////////////
//GetCurrentDirectory
//This functions gets the directory from
//which the exe was started.
void GetCurrentDirectory(char * szCurrentDirectory)
{
PTIB ptib;      //Pointer to thread info block
PPIB ppib;      //Pointer to process info block
APIRET  rc;     //Return code
PCHAR pchar;    //pointer to character

//Get info about current thread
rc = DosGetInfoBlocks(&ptib, &ppib);

//Get name of this exe file
rc=DosQueryModuleName(ppib->pib_hmte, CCHMAXPATH, szCurrentDirectory);

//Set a pointer to end of filename.
pchar=szCurrentDirectory+CCHMAXPATH;

//Back up until we hit a "\"
while((*pchar!='\\') && (pchar!=szCurrentDirectory)) pchar--;

//Move forward one and set a null
if(*pchar=='\\')
        {
        pchar++;
        *pchar='\0';
        }
}
//////////////////////////////////////////////////////


text:
package org.wso2.carbon.bpel.extensions.javaclass;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.WaitBeforeShutdownObserver;

public class ClassActivityShutdown implements WaitBeforeShutdownObserver {

    private static Log log = LogFactory.getLog(ClassActivityShutdown.class);
    private boolean status = false;

    //triggered before shutting down server and shutdown the scheduler if exists
    public void startingShutdown() {
        ClassActivityHolder.getInstance().destroyClassActivities();
        if (log.isDebugEnabled()) {
            log.debug("Destroying ClassActivities.");
        }
        status = true;
    }

    //keep blocking until the status is true
    public boolean isTaskComplete() {
        return status;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="chart_items">25</integer>
</resources>


text:
package frontend

import slick.util.AsyncExecutor

object DB {
  val connection = slick.jdbc.JdbcBackend.Database.forURL(
    driver="org.h2.Driver",
    url = "jdbc:h2:./db/accounts;DB_CLOSE_DELAY=-1",
    //url = "jdbc:h2:mem:accounts;DB_CLOSE_DELAY=-1",
    user = "sa", password ="sa",
    executor = AsyncExecutor("db-pool", numThreads=4, queueSize=5000))
}


text:
package org.apache.taverna.reference.impl;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.apache.taverna.reference.ReferenceSet;
import org.apache.taverna.reference.ReferenceSetDao;
import org.apache.taverna.reference.WorkflowRunIdEntity;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;

public class ReferenceSetServiceTest {

	private List<ReferenceSetServiceImpl> serviceList = new ArrayList<ReferenceSetServiceImpl>();

	@Before
	public void setup() throws Exception {

		AppContextSetup.setup();

		ReferenceSetServiceImpl service = null;

		for (ApplicationContext context : AppContextSetup.contextList) {

			service = new ReferenceSetServiceImpl();
			service.setReferenceSetDao((ReferenceSetDao)context.getBean("testDao"));
			service.setT2ReferenceGenerator(new SimpleT2ReferenceGenerator());
			serviceList.add(service);
		}
	}

	@Test
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void testDelete() throws Exception {
		ReferenceContextImpl invocationContext = new ReferenceContextImpl();
		invocationContext.addEntity(new WorkflowRunIdEntity("wfRunRefSetTest0"));
		for (ReferenceSetServiceImpl service : serviceList){
			ReferenceSet set = service.registerReferenceSet(new HashSet(), invocationContext);
			assertNotNull(service.getReferenceSet(set.getId()));
			assertTrue(service.delete(set.getId()));
			assertNull(service.getReferenceSet(set.getId()));
			assertFalse(service.delete(set.getId()));
		}
	}

	@Test
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void testDeleteReferenceSetsForWFRun() throws Exception {

		for (ReferenceSetServiceImpl service : serviceList){

			String wfRunId1 = "wfRunRefSetTest1";
			ReferenceContextImpl invocationContext1 = new ReferenceContextImpl();
			invocationContext1.addEntity(new WorkflowRunIdEntity(wfRunId1));

			String wfRunId2 = "wfRunRefSetTest2";
			ReferenceContextImpl invocationContext2 = new ReferenceContextImpl();
			invocationContext2.addEntity(new WorkflowRunIdEntity(wfRunId2));

			ReferenceSet set1 = service.registerReferenceSet(new HashSet(), invocationContext1);
			ReferenceSet set2 = service.registerReferenceSet(new HashSet(), invocationContext1);
			ReferenceSet set3 = service.registerReferenceSet(new HashSet(), invocationContext2);

			assertNotNull(service.getReferenceSet(set1.getId()));
			assertNotNull(service.getReferenceSet(set2.getId()));
			assertNotNull(service.getReferenceSet(set3.getId()));

			service.deleteReferenceSetsForWorkflowRun(wfRunId1);

			assertNull(service.getReferenceSet(set1.getId()));
			assertNull(service.getReferenceSet(set2.getId()));
			assertNotNull(service.getReferenceSet(set3.getId()));

		}
	}

}


text:
# isNodeREPL

> Check if running in a [Node.js][node-js] REPL environment.

## Usage

```javascript
var isNodeREPL = require( '@stdlib/assert/is-node-repl' );
```

#### isNodeREPL()

Returns a `boolean` indicating if running in a [Node.js][node-js] REPL environment.

```javascript
var bool = isNodeREPL();
// returns <boolean>
```

## Examples

```javascript
var isNodeREPL = require( '@stdlib/assert/is-node-repl' );

console.log( isNodeREPL() );
// => <boolean>
```

[node-js]: https://nodejs.org/en/