text:
package compat

import (
	"github.com/emmyzkp/emmy/anauth"
	"google.golang.org/grpc"
)

// ConnectionConfig wraps client.ConnectionConfig that holds connection information.
// Clients need to provide these information in order to establish connection to the server.
// For more details see documentation for the github.com/emmyzkp/emmy/client package.
type ConnectionConfig struct {
	Endpoint           string // Server's Endpoint
	ServerNameOverride string
	CACertificate      []byte
	TimeoutMillis      int
}

// NewConnectionConfig constructs an instance of ConnectionConfig based on the provided server
// endpoint, serverNameOverride and CA certificate.
func NewConnectionConfig(endpoint, serverNameOverride string,
	certificate []byte, timeout int) *ConnectionConfig {
	return &ConnectionConfig{
		endpoint,
		serverNameOverride,
		certificate,
		timeout,
	}
}

// Connection wraps *grpc.ClientConn. A Connection should be constructed independently and then
// passed as an argument to protocol clients. Same Connection can be re-used for many clients.
type Connection struct {
	*grpc.ClientConn
}

// NewConnection accepts *ConnectionConfig and uses the provided configuration information to
// establish connection to the server.
func NewConnection(cfg *ConnectionConfig) (*Connection, error) {
	conn, err := anauth.GetConnection(cfg.Endpoint, []anauth.ConnOption{
		anauth.WithCACert(cfg.CACertificate),
		anauth.WithServerNameOverride(cfg.ServerNameOverride),
		anauth.WithTimeout(cfg.TimeoutMillis)}...)

	if err != nil {
		return nil, err
	}

	return &Connection{conn}, err
}

// Close attempts to close connection to the server.
func (c *Connection) Close() error {
	if err := c.ClientConn.Close(); err != nil {
		return err
	}

	return nil
}


text:
package org.kie.pmml.models.regression.evaluator;

import java.util.Map;

import org.kie.api.pmml.PMMLRequestData;
import org.kie.pmml.commons.model.enums.MINING_FUNCTION;
import org.kie.pmml.commons.model.enums.OP_TYPE;
import org.kie.pmml.evaluator.core.utils.PMMLRequestDataBuilder;
import org.kie.pmml.models.regression.model.enums.MODEL_TYPE;
import org.kie.pmml.models.regression.model.enums.REGRESSION_NORMALIZATION_METHOD;

/**
 * @see Regression
 */
public class TestUtils {

    public static final String MODEL_NAME = "Sample for linear regression";
    public static final String ALGORITHM_NAME = "linearRegression";
    public static final MINING_FUNCTION _MINING_FUNCTION = MINING_FUNCTION.REGRESSION;
    public static final MODEL_TYPE _MODEL_TYPE = MODEL_TYPE.LINEAR_REGRESSION;
    public static final REGRESSION_NORMALIZATION_METHOD _REGRESSION_NORMALIZATION_METHOD = REGRESSION_NORMALIZATION_METHOD.SOFTMAX;
    public static final boolean SCORABLE = true;
    public static final String TARGETFIELD_NAME = "number_of_claims";
    public static final OP_TYPE _OP_TYPE = OP_TYPE.CONTINUOUS;
    public static final String CARPARK = "carpark";
    public static final String STREET = "street";
    public static final double INTERCEPT = 132.37;
    public static final double CARPARK_COEFF = 41.1;
    public static final double STREET_COEFF = 325.03;
    public static final double AGE_COEFF = 7.1;
    public static final double SALARY_COEFF = 0.01;

    public static PMMLRequestData getPMMLRequestData(String modelName, Map<String, Object> parameters) {
        String correlationId = "CORRELATION_ID";
        PMMLRequestDataBuilder pmmlRequestDataBuilder = new PMMLRequestDataBuilder(correlationId, modelName);
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            Object pValue = entry.getValue();
            Class class1 = pValue.getClass();
            pmmlRequestDataBuilder.addParameter(entry.getKey(), pValue, class1);
        }
        return pmmlRequestDataBuilder.build();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.plugins.scala.base

import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import org.jetbrains.plugins.scala.util.TestUtils

/**
  * @author Pavel Fatin
  */
abstract class LibraryTestCase extends LightCodeInsightFixtureTestCase {
  private var libraryLoader: Option[ScalaLibraryLoader] = None

  override def setUp() {
    super.setUp()

    val loader = ScalaLibraryLoader.withMockJdk(myFixture.getProject, myFixture.getModule, rootPath = null)
    libraryLoader = Some(loader)

    loader.loadScala(TestUtils.DEFAULT_SCALA_SDK_VERSION)
  }

  override def tearDown() {
    try {
      libraryLoader.foreach(_.clean())
    } finally {
      super.tearDown()
    }
  }
}


text:
sap.ui.define([
		'jquery.sap.global',
		'sap/ui/core/mvc/Controller',
		'sap/ui/model/Filter',
		'sap/ui/model/json/JSONModel'
	], function(jQuery, Controller, Filter, JSONModel) {
	"use strict";

	var ListController = Controller.extend("sap.m.sample.ListSelectionSearch.List", {

		onInit : function (evt) {
			// set explored app's demo model on this sample
			var oModel = new JSONModel(jQuery.sap.getModulePath("sap.ui.demo.mock", "/products.json"));
			this.getView().setModel(oModel);
		},

		onSearch : function (oEvt) {

			// add filter for search
			var aFilters = [];
			var sQuery = oEvt.getSource().getValue();
			if (sQuery && sQuery.length > 0) {
				var filter = new Filter("Name", sap.ui.model.FilterOperator.Contains, sQuery);
				aFilters.push(filter);
			}

			// update list binding
			var list = this.getView().byId("idList");
			var binding = list.getBinding("items");
			binding.filter(aFilters, "Application");
		},

		onSelectionChange : function (oEvt) {

			var oList = oEvt.getSource();
			var oLabel = this.getView().byId("idFilterLabel");
			var oInfoToolbar = this.getView().byId("idInfoToolbar");

			// With the 'getSelectedContexts' function you can access the context paths
			// of all list items that have been selected, regardless of any current
			// filter on the aggregation binding.
			var aContexts = oList.getSelectedContexts(true);

			// update UI
			var bSelected = (aContexts && aContexts.length > 0);
			var sText = (bSelected) ? aContexts.length + " selected" : null;
			oInfoToolbar.setVisible(bSelected);
			oLabel.setText(sText);
		}
	});

	return ListController;

});


text:
using System;

namespace RelEnt.SimpleSerialization
{
	[AttributeUsage(AttributeTargets.Field)]
	public sealed class SimpleSerializableFieldAttribute : Attribute
	{
		/// <summary>
		/// This field should be serialized. Overrides the setting in the SimpleSerializableType
		/// attribute.
		/// </summary>
		public bool Include { get; set; }
	}
}


text:
/**
 * Button
 * @flow
 */
import cn from './Button.css'
import React, { PropTypes } from 'react'
import type { ReactElement } from 'react'

export function Button (props: Object): ReactElement {
  return (
    <button
      className={cn.button}
      type='button'
      {...props}
    />
  )
}
Button.propTypes = {
  children: PropTypes.node.isRequired
}

export function ColorButton (props: Object): ReactElement {
  return (
    <button
      className={cn.color}
      type='button'
      {...props}
    />
  )
}
ColorButton.propTypes = {
  children: PropTypes.node.isRequired
}


text:
using System.Windows;

namespace DesktopWidgets.Windows
{
    /// <summary>
    ///     Interaction logic for ManageWidgets.xaml
    /// </summary>
    public partial class ManageWidgets : Window
    {
        public ManageWidgets()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}


text:
var inherits = require('util').inherits,
    EventEmitter = require('events').EventEmitter,
    Pinger = require('./lib/pinger')(inherits, EventEmitter),
    EndpointError = require('./lib/error')(inherits),
    Endpoint = require('./lib/endpoint')(inherits, EventEmitter, Pinger, EndpointError),
    RequestSet = require('./lib/request_set')

module.exports = require('./lib/pool')(inherits, EventEmitter, Endpoint, RequestSet)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>GreaterThan — Zend Framework 2 2.3.0dev documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="Zend Framework 2 2.3.0dev documentation" href="../index.html" />

Navigation

          index

Zend Framework 2 2.3.0dev documentation »

GreaterThan¶

<tt class="docutils literal">Zend\Validator\GreaterThan</tt> allows you to validate if a given value is greater than a minimum border value.

Note

Zend\Validator\GreaterThan supports only number validation

It should be noted that <tt class="docutils literal">Zend\Validator\GreaterThan</tt> supports only the validation of numbers. Strings or dates
can not be validated with this validator.

Supported options for Zend\Validator\GreaterThan¶

The following options are supported for <tt class="docutils literal">Zend\Validator\GreaterThan</tt>:

inclusive: Defines if the validation is inclusive the minimum border value or exclusive. It defaults to
<tt class="docutils literal">FALSE</tt>.

min: Sets the minimum allowed value.

Basic usage¶

To validate if a given value is greater than a defined border simply use the following example.

1
2
3
4

$valid  = new Zend\Validator\GreaterThan(array('min' => 10));
$value  = 8;
$return = $valid->isValid($value);
// returns false

The above example returns <tt class="docutils literal">TRUE</tt> for all values which are greater than 10.

Validation inclusive the border value¶

Sometimes it is useful to validate a value by including the border value. See the following example:

1
2
3
4
5
6
7
8
9

$valid  = new Zend\Validator\GreaterThan(
    array(
        'min' => 10,
        'inclusive' => true
    )
);
$value  = 10;
$result = $valid->isValid($value);
// returns true

The example is almost equal to our first example but we included the border value. Now the value ‘10’ is allowed
and will return <tt class="docutils literal">TRUE</tt>.

Table Of Contents

GreaterThan

Supported options for Zend\Validator\GreaterThan

Basic usage

Validation inclusive the border value

This Page

        Show Source

Edit Source

            Note: You need to stay logged into your GitHub account to contribute to the documentation.

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

Zend Framework 2 2.3.0dev documentation »

        © Copyright 2013, Zend Technologies Ltd..
      Created using Sphinx 1.2b3.

Edit this document

        The source code of this file is hosted on GitHub. Everyone can
        update and fix errors in this document with few clicks -
        no downloads needed.

            Login with your GitHub account.

            Go to

                GreaterThan
             on GitHub.

            Edit file contents using GitHub's text editor in your web browser

            Fill in the Commit message text box at the end of the page telling why
            you did the changes. Press Propose file change button next to it when done.

            On Send a pull request page you don't need to fill in text anymore. Just
            press Send pull request button.

            Your changes are now queued for review under project's Pull requests tab on GitHub.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Epicr. syst. mycol. (Upsaliae) 27 (1838)

#### Original name
Agaricus unguentatus Fr.

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using nhs.itk.hl7v3.rim;
using System.Xml.Serialization;
using nhs.itk.hl7v3.datatypes;
using nhs.itk.hl7v3.xml;
using System.Xml;

namespace nhs.itk.hl7v3.cda.classes
{
    internal class r_relatedEntity : RoleClass
    {
        internal string templateId { get; set; }
        internal string templateText { get; set; }

        internal e_person assignedPerson;
        internal e_organisation representedOrganisation;

        internal r_relatedEntity()
            : base()
        { }

        internal r_relatedEntity(string classCode)
            : base(classCode)
        { }

        internal void InitPerson()
        {
            if (assignedPerson == null)
            {
                assignedPerson = new e_person("PSN", "INSTANCE");
            }
        }

        internal void NullPerson()
        {
                assignedPerson = null;

        }

        internal void InitOrganisation()
        {
            if (representedOrganisation == null)
            {
                representedOrganisation = new e_organisation("ORG", "INSTANCE");
            }
        }

        internal new void AddId(string root, string extension)
        {
            base.AddId(root, extension);
        }

        #region XML Serialization Members

        internal void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("classCode", ClassCode);

            its.TemplateSignpost(templateId + "#" + templateText, writer);
            writeXML(writer);

            if (assignedPerson != null)
            {
                writer.WriteStartElement("relatedPerson");
                assignedPerson.TemplateId = templateId;
                assignedPerson.TemplateText = "relationshipHolder";
                assignedPerson.WriteXml(writer);
                writer.WriteEndElement();
            }

            if (representedOrganisation != null)
            {
                writer.WriteStartElement("representedOrganisation");
                representedOrganisation.TemplateId = templateId;
                representedOrganisation.TemplateText = "representedOrganisation";
                representedOrganisation.WriteXml(writer);
                writer.WriteEndElement();
            }
        }
        #endregion
    }
}


text:
"""Tensorflow Code for Generalized Bags Training for Scenario V."""
import pathlib
import pickle
import random

import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras

rng = np.random.default_rng(4372849)

path_to_root_data_dir = (pathlib.Path(__file__).parent /
                         "../../Data/").resolve()

directory_full_datasets = str(path_to_root_data_dir) + "/FullDatasets/"

root_for_experiments = str(path_to_root_data_dir) + "/"

cluster_bags_method = 5

datasetName_list = ["Ionosphere", "Australian", "Heart"]

n_features_list = [35, 15, 14]

n_clusters = 3

NUM_LABELS = 1
META_BATCH_SIZE = 32
NUM_BATCHES = 1000

T1 = NUM_LABELS - 1
T2 = T1 + 1
T3 = T1 + NUM_LABELS
T4 = T3 + 1
T5 = T4 + 1

mean_arr = np.array([0, 0, 0, 0])

correlation_matrix = np.array(
    [[5.35714286, -1.78571429, -1.78571429, -1.78571429],
     [-1.78571429, 0.5952381, 0.5952381, 0.5952381],
     [-1.78571429, 0.5952381, 0.5952381, 0.5952381],
     [-1.78571429, 0.5952381, 0.5952381, 0.5952381]])

mse = tf.keras.losses.MeanSquaredError()

mae = tf.keras.losses.MeanAbsoluteError()

kld = tf.keras.losses.KLDivergence()

def custom_loss_ell2sq_genbag(y_true_extended, y_pred):
  """L_2^2 Generalized Bags Loss."""
  y_combined = tf.concat((y_pred, y_true_extended), axis=1)
  cumu_loss = 0
  loss = 0
  # pylint: disable=cell-var-from-loop
  for partition_num in range(META_BATCH_SIZE):
    y_combined_sliced = tf.gather(
        y_combined,
        tf.where(
            tf.equal(y_combined[:, T5],
                     tf.constant(partition_num, dtype=float)))[:, 0])
    y_combined_sliced_pred = tf.gather(
        y_combined_sliced, tf.range(T2), axis=1)
    y_combined_sliced_actual = tf.gather(
        y_combined_sliced, tf.range(T2, T4), axis=1)
    wts = tf.gather(y_combined_sliced, [T4], axis=1)
    wtd_y_combined_sliced_pred = y_combined_sliced_pred * wts
    wtd_y_combined_sliced_actual = y_combined_sliced_actual * wts
    wtd_sum_y_combined_sliced_pred = tf.reduce_sum(
        wtd_y_combined_sliced_pred, axis=0)
    wtd_sum_y_combined_sliced_actual = tf.reduce_sum(
        wtd_y_combined_sliced_actual, axis=0)
    loss = mse(
        y_true=wtd_sum_y_combined_sliced_actual,
        y_pred=wtd_sum_y_combined_sliced_pred)
    cumu_loss = cumu_loss + loss
    print()
  tf.print("Step loss: ", cumu_loss)
  return cumu_loss

def custom_loss_abs_genbag(y_true_extended, y_pred):
  """L_1 Generalized Bags Loss."""
  y_combined = tf.concat((y_pred, y_true_extended), axis=1)
  cumu_loss = 0
  loss = 0
  # pylint: disable=cell-var-from-loop
  for partition_num in range(META_BATCH_SIZE):
    y_combined_sliced = tf.gather(
        y_combined,
        tf.where(
            tf.equal(y_combined[:, T5],
                     tf.constant(partition_num, dtype=float)))[:, 0])
    y_combined_sliced_pred = tf.gather(
        y_combined_sliced, tf.range(T2), axis=1)
    y_combined_sliced_actual = tf.gather(
        y_combined_sliced, tf.range(T2, T4), axis=1)
    wts = tf.gather(y_combined_sliced, [T4], axis=1)
    wtd_y_combined_sliced_pred = y_combined_sliced_pred * wts
    wtd_y_combined_sliced_actual = y_combined_sliced_actual * wts
    wtd_sum_y_combined_sliced_pred = tf.reduce_sum(
        wtd_y_combined_sliced_pred, axis=0)
    wtd_sum_y_combined_sliced_actual = tf.reduce_sum(
        wtd_y_combined_sliced_actual, axis=0)
    loss = mae(
        y_true=wtd_sum_y_combined_sliced_actual,
        y_pred=wtd_sum_y_combined_sliced_pred)
    cumu_loss = cumu_loss + loss
    print()
  tf.print("Step loss: ", cumu_loss)
  return cumu_loss

def custom_loss_kld_genbag(y_true_extended, y_pred):
  """KL-div Bags Loss."""
  y_combined = tf.concat((y_pred, y_true_extended), axis=1)
  cumu_loss = 0
  # pylint: disable=cell-var-from-loop
  for partition_num in range(META_BATCH_SIZE):
    y_combined_sliced = tf.gather(
        y_combined,
        tf.where(
            tf.equal(y_combined[:, T5],
                     tf.constant(partition_num, dtype=float)))[:, 0])
    y_combined_sliced_pred = tf.gather(
        y_combined_sliced, tf.range(T2), axis=1)
    y_combined_sliced_actual = tf.gather(
        y_combined_sliced, tf.range(T2, T4), axis=1)
    wts = tf.gather(y_combined_sliced, [T4], axis=1)
    wtd_y_combined_sliced_pred = y_combined_sliced_pred * wts
    wtd_y_combined_sliced_actual = y_combined_sliced_actual * wts

    def thisbagloss():
      wtd_sum_y_combined_sliced_pred = tf.reduce_sum(
          wtd_y_combined_sliced_pred, axis=0)
      avg_sum_y_combined_sliced_pred = tf.divide(
          wtd_sum_y_combined_sliced_pred, tf.reduce_sum(wts))
      wtd_sum_y_combined_sliced_actual = tf.reduce_sum(
          wtd_y_combined_sliced_actual, axis=0)
      avg_sum_y_combined_sliced_actual = tf.divide(
          wtd_sum_y_combined_sliced_actual, tf.reduce_sum(wts))
      oneminus_avg_sum_y_combined_sliced_pred = (
          -1.0) * avg_sum_y_combined_sliced_pred + 1.0
      oneminus_avg_sum_y_combined_sliced_actual = (
          -1.0) * avg_sum_y_combined_sliced_actual + 1.0
      loss1 = kld(
          y_true=avg_sum_y_combined_sliced_actual,
          y_pred=avg_sum_y_combined_sliced_pred)
      loss2 = kld(
          y_true=oneminus_avg_sum_y_combined_sliced_actual,
          y_pred=oneminus_avg_sum_y_combined_sliced_pred)
      thisloss = loss1 + loss2
      return thisloss

    this_bag_loss = tf.cond(
        tf.reduce_sum(wts) > 0.0, thisbagloss, lambda: 0.0)
    cumu_loss = cumu_loss + this_bag_loss
    print()
  tf.print("Step loss: ", cumu_loss)
  return cumu_loss

binacc = m = tf.keras.metrics.BinaryAccuracy()

def custom_binacc_func():
  """Custom Binary Accuracy using slices."""
  def retfunc(y_true, y_pred):
    return binacc(tf.gather(y_true, [0], axis=1), y_pred)

  retfunc.__name__ = "BinaryAcc"
  return retfunc

custom_binacc = custom_binacc_func()

auc = tf.keras.metrics.AUC()

def custom_auc(y_true, y_pred):
  """Custom AUC using slices."""
  return auc(tf.gather(y_true, [0], axis=1), y_pred)

class Linear(keras.layers.Layer):
  """Linear Classifier."""

  def __init__(self, units=32, input_dim=32):
    super(Linear, self).__init__()
    self.w = self.add_weight(
        shape=(input_dim, units), initializer="zeros", trainable=True)
    self.b = self.add_weight(
        shape=(units,), initializer="zeros", trainable=True)

  def call(self, inputs):
    return tf.nn.sigmoid(tf.matmul(inputs, self.w) + self.b)

for datasetIndex, datasetName in enumerate(datasetName_list):

  NUM_FEATURES = n_features_list[datasetIndex]

  name_dir = root_for_experiments + datasetName + "/"

  cluster_bags_methodoutfile = name_dir + datasetName + "_TFexpOutputClusterBags_" + str(
      cluster_bags_method)

  for foldnumber in range(1, 6):

    folddir = name_dir + "Fold_" + str(foldnumber) + "/"

    for splitnumber in range(1, 6):

      splitdir = folddir + "Split_" + str(splitnumber) + "/"

      test_data_file = splitdir + datasetName + "_" + str(
          foldnumber) + "_" + str(splitnumber) + "-test.csv"

      train_data_file = splitdir + datasetName + "_" + str(
          foldnumber) + "_" + str(splitnumber) + "-train.csv"

      cluster_dir = splitdir + "ClusterBags_" + str(cluster_bags_method) + "/"

      random_seed = rng.integers(low=1000000, size=1)[0]
      numpy_seed = rng.integers(low=1000000, size=1)[0]
      tf_seed = rng.integers(low=1000000, size=1)[0]

      random.seed(random_seed)

      np.random.seed(numpy_seed)

      tf.random.set_seed(tf_seed)

      print()
      print("*********starting************")
      print(cluster_dir)
      print("random_seed = ", random_seed)
      print("numpy_seed = ", numpy_seed)
      print("tf_seed = ", tf_seed)

      # print(train_data_file)

      train_df = pd.read_csv(train_data_file)

      test_df = pd.read_csv(test_data_file)

      distn_Id_to_bags_list = []

      # first pick up the straddle

      distn_Id_to_bags_list.append(
          pickle.load(open(cluster_dir + "straddle_bags", "rb")))

      # next the tail bags
      for i in range(n_clusters):
        distn_Id_to_bags_list.append(
            pickle.load(open(cluster_dir + "tail_bags_" + str(i), "rb")))

      print("distn_Id_to_bags_list")
      print(distn_Id_to_bags_list)

      print("correlation_matrix")
      print(correlation_matrix)

      def label_map(x):
        if x == -1:
          return 0
        else:
          return 1

      list_of_features = []

      for i in range(1, NUM_FEATURES):
        list_of_features.append("x." + str(i))

      list_of_features.append("constant")

      # pylint: disable=unnecessary-lambda
      train_df["label"] = train_df["label"].map(lambda x: label_map(x))

      # pylint: disable=unnecessary-lambda
      test_df["label"] = test_df["label"].map(lambda x: label_map(x))

      train_bag_counts = train_df["bag"].value_counts()
      myLinearModel_l2_S = keras.Sequential(
          [Linear(input_dim=NUM_FEATURES, units=NUM_LABELS)])

      myLinearModel_l2_S.compile(
          optimizer=tf.keras.optimizers.SGD(learning_rate=0.0001),
          loss=custom_loss_ell2sq_genbag)

      myLinearModel_l2_R = keras.Sequential(
          [Linear(input_dim=NUM_FEATURES, units=NUM_LABELS)])

      myLinearModel_l2_R.compile(
          optimizer=tf.keras.optimizers.SGD(learning_rate=0.0001),
          loss=custom_loss_ell2sq_genbag)

      myLinearModel_l1_S = keras.Sequential(
          [Linear(input_dim=NUM_FEATURES, units=NUM_LABELS)])

      myLinearModel_l1_S.compile(
          optimizer=tf.keras.optimizers.SGD(learning_rate=0.0001),
          loss=custom_loss_abs_genbag)

      myLinearModel_l1_R = keras.Sequential(
          [Linear(input_dim=NUM_FEATURES, units=NUM_LABELS)])

      myLinearModel_l1_R.compile(
          optimizer=tf.keras.optimizers.SGD(learning_rate=0.0001),
          loss=custom_loss_abs_genbag)

      myLinearModel_l2_U = keras.Sequential(
          [Linear(input_dim=NUM_FEATURES, units=NUM_LABELS)])

      myLinearModel_l2_U.compile(
          optimizer=tf.keras.optimizers.SGD(learning_rate=0.0001),
          loss=custom_loss_ell2sq_genbag)

      myLinearModel_l1_U = keras.Sequential(
          [Linear(input_dim=NUM_FEATURES, units=NUM_LABELS)])

      myLinearModel_l1_U.compile(
          optimizer=tf.keras.optimizers.SGD(learning_rate=0.0001),
          loss=custom_loss_abs_genbag)

      myLinearModel_KL_U = keras.Sequential(
          [Linear(input_dim=NUM_FEATURES, units=NUM_LABELS)])

      myLinearModel_KL_U.compile(
          optimizer=tf.keras.optimizers.SGD(learning_rate=0.0001),
          loss=custom_loss_kld_genbag)

      for step in range(NUM_BATCHES):
        print("Enter Batch: ", step)
        batch_df = pd.DataFrame()
        batch_rand_df = pd.DataFrame()
        batch_unif_df = pd.DataFrame()
        for genBagNo in range(META_BATCH_SIZE):
          sampled_wts = np.random.multivariate_normal(mean_arr,
                                                      correlation_matrix)
          random_wts = np.random.normal(size=1 + n_clusters)
          unifbag_wts = np.eye(1 + n_clusters)[random.randrange(1 + n_clusters)]
          genBag_df = pd.DataFrame()
          genBag_rand_df = pd.DataFrame()
          genBag_unif_df = pd.DataFrame()
          for i in range(1 + n_clusters):
            this_bag_list = random.sample(distn_Id_to_bags_list[i], 1)
            this_bag_df = train_df.iloc[this_bag_list[0]].copy()
            this_bag_rand_df = train_df.iloc[this_bag_list[0]].copy()
            this_bag_unif_df = train_df.iloc[this_bag_list[0]].copy()
            this_bag_df["wt"] = sampled_wts[i]
            this_bag_rand_df["wt"] = random_wts[i]
            this_bag_unif_df["wt"] = unifbag_wts[i]
            genBag_df = genBag_df.append(this_bag_df, ignore_index=True)
            genBag_rand_df = genBag_rand_df.append(
                this_bag_rand_df, ignore_index=True)
            genBag_unif_df = genBag_unif_df.append(
                this_bag_unif_df, ignore_index=True)

          genBag_df["genBagNo"] = genBagNo
          genBag_rand_df["genBagNo"] = genBagNo
          genBag_unif_df["genBagNo"] = genBagNo

          batch_df = batch_df.append(genBag_df, ignore_index=True)

          batch_rand_df = batch_rand_df.append(
              genBag_rand_df, ignore_index=True)

          batch_unif_df = batch_unif_df.append(
              genBag_unif_df, ignore_index=True)

        features_matrix = batch_df[list_of_features].to_numpy()

        features_matrix_rand = batch_rand_df[list_of_features].to_numpy()

        features_matrix_unif = batch_unif_df[list_of_features].to_numpy()

        label_wt_genBagno_matrix = batch_df[["label", "wt",
                                             "genBagNo"]].to_numpy(dtype=float)

        label_wt_genBagno_matrix_rand = batch_rand_df[[
            "label", "wt", "genBagNo"
        ]].to_numpy(dtype=float)

        label_wt_genBagno_matrix_unif = batch_unif_df[[
            "label", "wt", "genBagNo"
        ]].to_numpy(dtype=float)

        myLinearModel_l2_S.train_on_batch(
            x=features_matrix, y=label_wt_genBagno_matrix)

        myLinearModel_l1_S.train_on_batch(
            x=features_matrix, y=label_wt_genBagno_matrix)

        myLinearModel_l2_R.train_on_batch(
            x=features_matrix_rand, y=label_wt_genBagno_matrix_rand)

        myLinearModel_l1_R.train_on_batch(
            x=features_matrix_rand, y=label_wt_genBagno_matrix_rand)

        myLinearModel_l2_U.train_on_batch(
            x=features_matrix_unif, y=label_wt_genBagno_matrix_unif)

        myLinearModel_l1_U.train_on_batch(
            x=features_matrix_unif, y=label_wt_genBagno_matrix_unif)

        myLinearModel_KL_U.train_on_batch(
            x=features_matrix_unif, y=label_wt_genBagno_matrix_unif)

        print("After training step: ", step)

      print("Testing on Full Dataset")

      myLinearModel_l2_S.compile(metrics=[custom_auc])

      myLinearModel_l1_S.compile(metrics=[custom_auc])

      myLinearModel_l2_R.compile(metrics=[custom_auc])

      myLinearModel_l1_R.compile(metrics=[custom_auc])

      myLinearModel_l2_U.compile(metrics=[custom_auc])

      myLinearModel_l1_U.compile(metrics=[custom_auc])

      myLinearModel_KL_U.compile(metrics=[custom_auc])

      test_df["wt"] = 0

      test_df["genBagNo"] = 0

      features_matrix_test = test_df[list_of_features].to_numpy()

      label_wt_genBagno_matrix_test = test_df[["label", "wt", "genBagNo"
                                              ]].to_numpy(dtype=float)

      results_linear_l2_S = myLinearModel_l2_S.test_on_batch(
          x=features_matrix_test, y=label_wt_genBagno_matrix_test)

      results_linear_l1_S = myLinearModel_l1_S.test_on_batch(
          x=features_matrix_test, y=label_wt_genBagno_matrix_test)

      results_linear_l2_R = myLinearModel_l2_R.test_on_batch(
          x=features_matrix_test, y=label_wt_genBagno_matrix_test)

      results_linear_l1_R = myLinearModel_l1_R.test_on_batch(
          x=features_matrix_test, y=label_wt_genBagno_matrix_test)

      results_linear_l2_U = myLinearModel_l2_U.test_on_batch(
          x=features_matrix_test, y=label_wt_genBagno_matrix_test)

      results_linear_l1_U = myLinearModel_l1_U.test_on_batch(
          x=features_matrix_test, y=label_wt_genBagno_matrix_test)

      results_linear_KL_U = myLinearModel_KL_U.test_on_batch(
          x=features_matrix_test, y=label_wt_genBagno_matrix_test)

      results_string = (
          datasetName + ", " + str(cluster_bags_method) + ", " +
          str(splitnumber) + ",  " + str(foldnumber) + ", " +
          str(results_linear_l2_S[1]) + ", " + str(results_linear_l1_S[1]) +
          ", " + str(results_linear_l2_R[1]) + ", " +
          str(results_linear_l1_R[1]) + ", " + str(results_linear_l2_U[1]) +
          ", " + str(results_linear_l1_U[1]) + ", " +
          str(results_linear_KL_U[1]) + "\n")

      print("Test Results: ")
      print(results_string)

      with open(cluster_bags_methodoutfile, "a") as filetoAppend:
        filetoAppend.write(results_string)


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the MIT license.  See License.txt in the project root for license information.

using System.Threading.Tasks;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.UnitTests.CSharpPerformanceCodeFixVerifier<
    Microsoft.CodeAnalysis.CSharp.PerformanceSensitiveAnalyzers.EnumeratorAllocationAnalyzer,
    Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;

namespace Microsoft.CodeAnalysis.PerformanceSensitive.Analyzers.UnitTests
{
    public class EnumeratorAllocationAnalyzerTests
    {
        [Fact]
        public async Task EnumeratorAllocation_BasicAsync()
        {
            var sampleProgram =
@"using System.Collections.Generic;
using System;
using System.Linq;
using Roslyn.Utilities;

public class MyClass
{
    [PerformanceSensitive(""uri"")]
    public void SomeMethod()
    {
        int[] intData = new[] { 123, 32, 4 };
        IList<int> iListData = new[] { 123, 32, 4 };
        List<int> listData = new[] { 123, 32, 4 }.ToList();

        foreach (var i in intData)
        {
            Console.WriteLine(i);
        }

        foreach (var i in listData)
        {
            Console.WriteLine(i);
        }

        foreach (var i in iListData) // Allocations (line 19)
        {
            Console.WriteLine(i);
        }

        foreach (var i in (IEnumerable<int>)intData) // Allocations (line 24)
        {
            Console.WriteLine(i);
        }
    }
}";
            await VerifyCS.VerifyAnalyzerAsync(sampleProgram,
                // Test0.cs(25,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation
#pragma warning disable RS0030 // Do not used banned APIs
                VerifyCS.Diagnostic().WithLocation(25, 24),
#pragma warning restore RS0030 // Do not used banned APIs
                // Test0.cs(30,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation
#pragma warning disable RS0030 // Do not used banned APIs
                VerifyCS.Diagnostic().WithLocation(30, 24));
#pragma warning restore RS0030 // Do not used banned APIs
        }

        [Fact]
        public async Task EnumeratorAllocation_AdvancedAsync()
        {
            var sampleProgram =
@"using System.Collections.Generic;
using System;
using Roslyn.Utilities;

public class MyClass
{
    [PerformanceSensitive(""uri"")]
    public void SomeMethod()
    {
        // These next 3 are from the YouTube video
        foreach (object a in new[] { 1, 2, 3}) // Allocations 'new [] { 1. 2, 3}'
        {
            Console.WriteLine(a.ToString());
        }

        IEnumerable<string> fx1 = default(IEnumerable<string>);
        foreach (var f in fx1) // Allocations 'in'
        {
        }

        List<string> fx2 = default(List<string>);
        foreach (var f in fx2) // NO Allocations
        {
        }
    }
}";
            await VerifyCS.VerifyAnalyzerAsync(sampleProgram,
                // Test0.cs(17,24): warning HAA0401: Non-ValueType enumerator may result in a heap allocation
#pragma warning disable RS0030 // Do not used banned APIs
                VerifyCS.Diagnostic().WithLocation(17, 24));
#pragma warning restore RS0030 // Do not used banned APIs
        }

        [Fact]
        public async Task EnumeratorAllocation_Via_InvocationExpressionSyntaxAsync()
        {
            var sampleProgram =
@"using System.Collections.Generic;
using System.Collections;
using System;
using Roslyn.Utilities;

public class MyClass
{
    [PerformanceSensitive(""uri"")]
    public void SomeMethod()
    {
        var enumeratorRaw = GetIEnumerableRaw();
        while (enumeratorRaw.MoveNext())
        {
            Console.WriteLine(enumeratorRaw.Current.ToString());
        }

        var enumeratorRawViaIEnumerable = GetIEnumeratorViaIEnumerable();
        while (enumeratorRawViaIEnumerable.MoveNext())
        {
            Console.WriteLine(enumeratorRawViaIEnumerable.Current.ToString());
        }
    }

    private IEnumerator GetIEnumerableRaw()
    {
        return new[] { 123, 32, 4 }.GetEnumerator();
    }

    private IEnumerator<int> GetIEnumeratorViaIEnumerable()
    {
        int[] intData = new[] { 123, 32, 4 };
        return (IEnumerator<int>)intData.GetEnumerator();
    }
}";
            await VerifyCS.VerifyAnalyzerAsync(sampleProgram,
                // Test0.cs(17,43): warning HAA0401: Non-ValueType enumerator may result in a heap allocation
#pragma warning disable RS0030 // Do not used banned APIs
                VerifyCS.Diagnostic().WithLocation(17, 43));
#pragma warning restore RS0030 // Do not used banned APIs
        }

        [Fact]
        public async Task EnumeratorAllocation_IterateOverString_NoWarningAsync()
        {
            var sampleProgram =
@"using System;
using Roslyn.Utilities;

public class MyClass
{
    [PerformanceSensitive(""uri"")]
    public void SomeMethod()
    {
        foreach (char c in ""aaa"") { };
    }
}";
            await VerifyCS.VerifyAnalyzerAsync(sampleProgram);
        }
    }
}


text:
#ifndef ZEPHYR_INCLUDE_DFU_FLASH_IMG_H_
#define ZEPHYR_INCLUDE_DFU_FLASH_IMG_H_

#ifdef __cplusplus
extern "C" {
#endif

struct flash_img_context {
	u8_t buf[CONFIG_IMG_BLOCK_BUF_SIZE];
	struct device *dev;
	size_t bytes_written;
	u16_t buf_bytes;
};

/**
 * @brief Initialize context needed for writing the image to the flash.
 *
 * @param ctx context to be initialized
 * @param dev flash driver to used while writing the image
 */
void flash_img_init(struct flash_img_context *ctx, struct device *dev);

/**
 * @brief Read number of bytes of the image written to the flash.
 *
 * @param ctx context
 *
 * @return Number of bytes written to the image flash.
 */
size_t flash_img_bytes_written(struct flash_img_context *ctx);

/**
 * @brief  Process input buffers to be written to the image slot 1. flash
 * memory in single blocks. Will store remainder between calls.
 *
 * A final call to this function with flush set to true
 * will write out the remaining block buffer to flash. Since flash is written to
 * in blocks, the contents of flash from the last byte written up to the next
 * multiple of CONFIG_IMG_BLOCK_BUF_SIZE is padded with 0xff.
 *
 * @param ctx context
 * @param data data to write
 * @param len Number of bytes to write
 * @param flush when true this forces any buffered
 * data to be written to flash
 *
 * @return  0 on success, negative errno code on fail
 */
int flash_img_buffered_write(struct flash_img_context *ctx, u8_t *data,
		    size_t len, bool flush);

#ifdef __cplusplus
}
#endif

#endif	/* ZEPHYR_INCLUDE_DFU_FLASH_IMG_H_ */


text:
<?php

namespace GithubService\Model;

class DirectoryContentInfo
{
    use GithubTrait;
    use SafeAccess;

    protected function getDataMap() {
        $dataMap = [
            ['dIRECTORYCONTENTChild', 'DIRECTORY_CONTENT_child', 'multiple' => true, 'class' => 'GithubService\\Model\\Content'],
        ];

        return $dataMap;
    }
}


text:
var common_locale = {lc:{"ar":function(n){
  if (n === 0) {
    return 'zero';
  }
  if (n == 1) {
    return 'one';
  }
  if (n == 2) {
    return 'two';
  }
  if ((n % 100) >= 3 && (n % 100) <= 10 && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 100) >= 11 && (n % 100) <= 99 && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"en":function(n){return n===1?"one":"other"},"bg":function(n){return n===1?"one":"other"},"bn":function(n){return n===1?"one":"other"},"ca":function(n){return n===1?"one":"other"},"cs":function(n){
  if (n == 1) {
    return 'one';
  }
  if (n == 2 || n == 3 || n == 4) {
    return 'few';
  }
  return 'other';
},"da":function(n){return n===1?"one":"other"},"de":function(n){return n===1?"one":"other"},"el":function(n){return n===1?"one":"other"},"es":function(n){return n===1?"one":"other"},"et":function(n){return n===1?"one":"other"},"eu":function(n){return n===1?"one":"other"},"fa":function(n){return "other"},"fi":function(n){return n===1?"one":"other"},"fil":function(n){return n===0||n==1?"one":"other"},"fr":function(n){return Math.floor(n)===0||Math.floor(n)==1?"one":"other"},"ga":function(n){return n==1?"one":(n==2?"two":"other")},"gl":function(n){return n===1?"one":"other"},"he":function(n){return n===1?"one":"other"},"hi":function(n){return n===0||n==1?"one":"other"},"hr":function(n){
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
      ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"hu":function(n){return "other"},"id":function(n){return "other"},"is":function(n){
    return ((n%10) === 1 && (n%100) !== 11) ? 'one' : 'other';
  },"it":function(n){return n===1?"one":"other"},"ja":function(n){return "other"},"ko":function(n){return "other"},"lt":function(n){
  if ((n % 10) == 1 && ((n % 100) < 11 || (n % 100) > 19)) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 9 &&
      ((n % 100) < 11 || (n % 100) > 19) && n == Math.floor(n)) {
    return 'few';
  }
  return 'other';
},"lv":function(n){
  if (n === 0) {
    return 'zero';
  }
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  return 'other';
},"mk":function(n){return (n%10)==1&&n!=11?"one":"other"},"mr":function(n){return n===1?"one":"other"},"ms":function(n){return "other"},"mt":function(n){
  if (n == 1) {
    return 'one';
  }
  if (n === 0 || ((n % 100) >= 2 && (n % 100) <= 4 && n == Math.floor(n))) {
    return 'few';
  }
  if ((n % 100) >= 11 && (n % 100) <= 19 && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"nl":function(n){return n===1?"one":"other"},"no":function(n){return n===1?"one":"other"},"pl":function(n){
  if (n == 1) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || n != 1 && (n % 10) == 1 ||
      ((n % 10) >= 5 && (n % 10) <= 9 || (n % 100) >= 12 && (n % 100) <= 14) &&
      n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"pt":function(n){return n===1?"one":"other"},"ro":function(n){
  if (n == 1) {
    return 'one';
  }
  if (n === 0 || n != 1 && (n % 100) >= 1 &&
      (n % 100) <= 19 && n == Math.floor(n)) {
    return 'few';
  }
  return 'other';
},"ru":function(n){
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
      ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"sk":function(n){
  if (n == 1) {
    return 'one';
  }
  if (n == 2 || n == 3 || n == 4) {
    return 'few';
  }
  return 'other';
},"sl":function(n){
  if ((n % 100) == 1) {
    return 'one';
  }
  if ((n % 100) == 2) {
    return 'two';
  }
  if ((n % 100) == 3 || (n % 100) == 4) {
    return 'few';
  }
  return 'other';
},"sq":function(n){return n===1?"one":"other"},"sr":function(n){
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
      ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"sv":function(n){return n===1?"one":"other"},"ta":function(n){return n===1?"one":"other"},"th":function(n){return "other"},"tr":function(n){return n===1?"one":"other"},"uk":function(n){
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
      ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"ur":function(n){return n===1?"one":"other"},"vi":function(n){return "other"},"zh":function(n){return "other"}},
c:function(d,k){if(!d)throw new Error("MessageFormat: Data required for '"+k+"'.")},
n:function(d,k,o){if(isNaN(d[k]))throw new Error("MessageFormat: '"+k+"' isn't a number.");return d[k]-(o||0)},
v:function(d,k){common_locale.c(d,k);return d[k]},
p:function(d,k,o,l,p){common_locale.c(d,k);return d[k] in p?p[d[k]]:(k=common_locale.lc[l](d[k]-o),k in p?p[k]:p.other)},
s:function(d,k,p){common_locale.c(d,k);return d[k] in p?p[d[k]]:p.other}};
(window.blockly = window.blockly || {}).common_locale = {
"and":function(d){return "そして"},
"backToPreviousLevel":function(d){return "前のレベルに戻る"},
"blocklyMessage":function(d){return "ブロッキー"},
"blocks":function(d){return "ブロック"},
"booleanFalse":function(d){return "false"},
"booleanTrue":function(d){return "true"},
"catActions":function(d){return "操作"},
"catColour":function(d){return "色"},
"catLists":function(d){return "リスト"},
"catLogic":function(d){return "ロジック(論理)"},
"catLoops":function(d){return "ループ"},
"catMath":function(d){return "数値"},
"catProcedures":function(d){return "関数"},
"catText":function(d){return "テキスト"},
"catVariables":function(d){return "変数"},
"clearPuzzle":function(d){return "最初からやり直す"},
"clearPuzzleConfirm":function(d){return "パズルを最初の状態にリセットし、追加または変更されたすべてのブロックを削除します。"},
"clearPuzzleConfirmHeader":function(d){return "本当に最初からやり直してもよいですか?"},
"codeMode":function(d){return "コード"},
"codeTooltip":function(d){return "生成されたJavaScriptコードを見る。"},
"continue":function(d){return "続行"},
"defaultTwitterText":function(d){return "私の作品を試してみてください"},
"designMode":function(d){return "デザイン"},
"dialogCancel":function(d){return "キャンセル"},
"dialogOK":function(d){return "OK"},
"directionEastLetter":function(d){return "東"},
"directionNorthLetter":function(d){return "北"},
"directionSouthLetter":function(d){return "南"},
"directionWestLetter":function(d){return "西"},
"dropletBlock_addOperator_description":function(d){return "二つの数値を足す"},
"dropletBlock_addOperator_signatureOverride":function(d){return "演算子を追加"},
"dropletBlock_andOperator_description":function(d){return "両方の式が true と false それ以外の場合場合にのみ true を返します"},
"dropletBlock_andOperator_signatureOverride":function(d){return "ブール演算子"},
"dropletBlock_assign_x_description":function(d){return "変数を割り当て直す"},
"dropletBlock_assign_x_param0":function(d){return "x"},
"dropletBlock_assign_x_param0_description":function(d){return "The variable name being assigned to"},
"dropletBlock_assign_x_param1":function(d){return "value"},
"dropletBlock_assign_x_param1_description":function(d){return "The value the variable is being assigned to."},
"dropletBlock_assign_x_signatureOverride":function(d){return "変数を代入"},
"dropletBlock_callMyFunction_description":function(d){return "パラメーターを受け取らず、名前付き関数を呼び出す"},
"dropletBlock_callMyFunction_n_description":function(d){return "1 つまたは複数のパラメーターを名前付き関数を呼び出す"},
"dropletBlock_callMyFunction_n_signatureOverride":function(d){return "パラメーターを持つ関数を呼び出す"},
"dropletBlock_callMyFunction_signatureOverride":function(d){return "関数をコール"},
"dropletBlock_declareAssign_x_array_1_4_description":function(d){return "変数を作成し、配列として初期化する"},
"dropletBlock_declareAssign_x_array_1_4_param0":function(d){return "x"},
"dropletBlock_declareAssign_x_array_1_4_param0_description":function(d){return "The name you will use in the program to reference the variable"},
"dropletBlock_declareAssign_x_array_1_4_param1":function(d){return "1,2,3,4"},
"dropletBlock_declareAssign_x_array_1_4_param1_description":function(d){return "The initial values to the array"},
"dropletBlock_declareAssign_x_array_1_4_signatureOverride":function(d){return "Declare a variable assigned to an array"},
"dropletBlock_declareAssign_x_description":function(d){return "'Var' の後、指定された名前を持つ変数を宣言し、式の右側に値を割り当てます"},
"dropletBlock_declareAssign_x_param0":function(d){return "x"},
"dropletBlock_declareAssign_x_param0_description":function(d){return "The name you will use in the program to reference the variable"},
"dropletBlock_declareAssign_x_param1":function(d){return "0"},
"dropletBlock_declareAssign_x_param1_description":function(d){return "The initial value of the variable"},
"dropletBlock_declareAssign_x_prompt_description":function(d){return "変数を作成し、プロンプトを表示することにより、値を割り当てる"},
"dropletBlock_declareAssign_x_prompt_param0":function(d){return "x"},
"dropletBlock_declareAssign_x_prompt_param0_description":function(d){return "The name you will use in the program to reference the variable"},
"dropletBlock_declareAssign_x_prompt_param1":function(d){return "値を入力"},
"dropletBlock_declareAssign_x_prompt_param1_description":function(d){return "ユーザに値の入力を促すときに表示される文字列"},
"dropletBlock_declareAssign_x_prompt_signatureOverride":function(d){return "ユーザに値の入力を促し、入力された値を保存する"},
"dropletBlock_declareAssign_x_signatureOverride":function(d){return "変数を宣言します。"},
"dropletBlock_divideOperator_description":function(d){return "二つの値をを割る"},
"dropletBlock_divideOperator_signatureOverride":function(d){return "Divide operator"},
"dropletBlock_equalityOperator_description":function(d){return "等しいさをテスト"},
"dropletBlock_equalityOperator_param0":function(d){return "x"},
"dropletBlock_equalityOperator_param0_description":function(d){return "The first value to use for comparison."},
"dropletBlock_equalityOperator_param1":function(d){return "y"},
"dropletBlock_equalityOperator_param1_description":function(d){return "The second value to use for comparison."},
"dropletBlock_equalityOperator_signatureOverride":function(d){return "Equality operator"},
"dropletBlock_forLoop_i_0_4_description":function(d){return "初期化式、条件式、インクリメント式、ループの反復処理ごとに実行されるステートメントのブロックから成るループを作成します"},
"dropletBlock_forLoop_i_0_4_signatureOverride":function(d){return "for ループ"},
"dropletBlock_functionParams_n_description":function(d){return "1 つまたは複数のパラメーターで、かかるとタスクを実行または関数が呼び出されたときに値を計算する一連のステートメント"},
"dropletBlock_functionParams_n_signatureOverride":function(d){return "パラメーターを持つ関数を定義します。"},
"dropletBlock_functionParams_none_description":function(d){return "タスクの実行または関数が呼び出されたときに、値が計算されるステートメントのセット"},
"dropletBlock_functionParams_none_signatureOverride":function(d){return "関数を定義します。"},
"dropletBlock_getTime_description":function(d){return "現在の時刻をミリ秒単位で取得します。"},
"dropletBlock_greaterThanOperator_description":function(d){return "Compare two numbers"},
"dropletBlock_greaterThanOperator_param0":function(d){return "x"},
"dropletBlock_greaterThanOperator_param0_description":function(d){return "The first value to use for comparison."},
"dropletBlock_greaterThanOperator_param1":function(d){return "y"},
"dropletBlock_greaterThanOperator_param1_description":function(d){return "The second value to use for comparison."},
"dropletBlock_greaterThanOperator_signatureOverride":function(d){return "Greater than operator"},
"dropletBlock_ifBlock_description":function(d){return "指定した条件が true の場合、ステートメントのブロックを実行します"},
"dropletBlock_ifBlock_signatureOverride":function(d){return "if statement"},
"dropletBlock_ifElseBlock_description":function(d){return "Do something if a condition is true, otherwise do something else"},
"dropletBlock_ifElseBlock_signatureOverride":function(d){return "if/else statement"},
"dropletBlock_inequalityOperator_description":function(d){return "Test for inequality"},
"dropletBlock_inequalityOperator_param0":function(d){return "x"},
"dropletBlock_inequalityOperator_param0_description":function(d){return "The first value to use for comparison."},
"dropletBlock_inequalityOperator_param1":function(d){return "y"},
"dropletBlock_inequalityOperator_param1_description":function(d){return "The second value to use for comparison."},
"dropletBlock_inequalityOperator_signatureOverride":function(d){return "Inequality operator"},
"dropletBlock_lessThanOperator_description":function(d){return "Compare two numbers"},
"dropletBlock_lessThanOperator_param0":function(d){return "x"},
"dropletBlock_lessThanOperator_param0_description":function(d){return "The first value to use for comparison."},
"dropletBlock_lessThanOperator_param1":function(d){return "y"},
"dropletBlock_lessThanOperator_param1_description":function(d){return "The second value to use for comparison."},
"dropletBlock_lessThanOperator_signatureOverride":function(d){return "Less than operator"},
"dropletBlock_mathAbs_description":function(d){return "Absolute value"},
"dropletBlock_mathAbs_param0":function(d){return "x"},
"dropletBlock_mathAbs_param0_description":function(d){return "An arbitrary number."},
"dropletBlock_mathAbs_signatureOverride":function(d){return "Math.abs(x)"},
"dropletBlock_mathMax_description":function(d){return "Maximum value"},
"dropletBlock_mathMax_param0":function(d){return "n1, n2,..., nX"},
"dropletBlock_mathMax_param0_description":function(d){return "One or more numbers to compare."},
"dropletBlock_mathMax_signatureOverride":function(d){return "Math.max(n1, n2, ..., nX)"},
"dropletBlock_mathMin_description":function(d){return "Minimum value"},
"dropletBlock_mathMin_param0":function(d){return "n1, n2,..., nX"},
"dropletBlock_mathMin_param0_description":function(d){return "One or more numbers to compare."},
"dropletBlock_mathMin_signatureOverride":function(d){return "Math.min(n1, n2, ..., nX)"},
"dropletBlock_mathRound_description":function(d){return "Round to the nearest integer"},
"dropletBlock_mathRound_param0":function(d){return "x"},
"dropletBlock_mathRound_param0_description":function(d){return "An arbitrary number."},
"dropletBlock_mathRound_signatureOverride":function(d){return "Math.round(x)"},
"dropletBlock_multiplyOperator_description":function(d){return "Multiply two numbers"},
"dropletBlock_multiplyOperator_signatureOverride":function(d){return "Multiply operator"},
"dropletBlock_notOperator_description":function(d){return "Logical NOT of a boolean"},
"dropletBlock_notOperator_signatureOverride":function(d){return "AND boolean operator"},
"dropletBlock_orOperator_description":function(d){return "Logical OR of two booleans"},
"dropletBlock_orOperator_signatureOverride":function(d){return "OR boolean operator"},
"dropletBlock_randomNumber_max_description":function(d){return "Get a random number between 0 and the specified maximum value"},
"dropletBlock_randomNumber_max_param0":function(d){return "max"},
"dropletBlock_randomNumber_max_param0_description":function(d){return "The maximum number returned"},
"dropletBlock_randomNumber_max_signatureOverride":function(d){return "randomNumber(max)"},
"dropletBlock_randomNumber_min_max_description":function(d){return "Get a random number between the specified minimum and maximum values"},
"dropletBlock_randomNumber_min_max_param0":function(d){return "min"},
"dropletBlock_randomNumber_min_max_param0_description":function(d){return "The minimum number returned"},
"dropletBlock_randomNumber_min_max_param1":function(d){return "max"},
"dropletBlock_randomNumber_min_max_param1_description":function(d){return "The maximum number returned"},
"dropletBlock_randomNumber_min_max_signatureOverride":function(d){return "randomNumber(min, max)"},
"dropletBlock_return_description":function(d){return "Return a value from a function"},
"dropletBlock_return_signatureOverride":function(d){return "返す"},
"dropletBlock_setAttribute_description":function(d){return "Sets the given value"},
"dropletBlock_subtractOperator_description":function(d){return "Subtract two numbers"},
"dropletBlock_subtractOperator_signatureOverride":function(d){return "Subtract operator"},
"dropletBlock_whileBlock_description":function(d){return "Repeat something while a condition is true"},
"dropletBlock_whileBlock_signatureOverride":function(d){return "while loop"},
"emptyBlocksErrorMsg":function(d){return ""繰り返す"または\"もし\"のブロックを動作をさせるためには内側に別のブロックが必要になります。ブロック内に内側のブロックが適切にはめ込まれているか確認をしてください。"},
"emptyBlockInFunction":function(d){return "The function "+common_locale.v(d,"name")+" has an unfilled input."},
"emptyBlockInVariable":function(d){return "The variable "+common_locale.v(d,"name")+" has an unfilled input."},
"emptyFunctionBlocksErrorMsg":function(d){return "関数ブロックは、中に他のブロックがないと動きません。"},
"emptyFunctionalBlock":function(d){return "入力値が空のブロックがあります。"},
"emptyTopLevelBlock":function(d){return "There are no blocks to run. You must attach a block to the "+common_locale.v(d,"topLevelBlockName")+" block."},
"end":function(d){return "終了"},
"errorEmptyFunctionBlockModal":function(d){return "関数の中に他のブロックがありません。「編集」をクリックしてから緑色のブロックの中にほかのブロックを持ってきてください。"},
"errorIncompleteBlockInFunction":function(d){return "「編集」をクリックして、関数定義の中に足りないブロックがないか確認してください。"},
"errorParamInputUnattached":function(d){return "ワークスペース内の関数ブロックのそれぞれのパラメーター入力にブロックをくっつけるのを忘れないでください。"},
"errorQuestionMarksInNumberField":function(d){return "\"???\"を何かの値に置きかえてみて。"},
"errorRequiredParamsMissing":function(d){return "「編集」をクリックして必要なパラメータを作ってください。新しいパラメーターブロックを関数の定義にドラッグして持ってきましょう。"},
"errorUnusedFunction":function(d){return "関数を作りましたが、ワークスペースの中で使われていません。ツールボックスの「関数」をクリックして、プログラムの中で使われているか確認してください。"},
"errorUnusedParam":function(d){return "パラメーターブロックを追加しましたが、使われていないようです。「編集」をクリックして緑色のブロックの中にパラメーターブロックを置いて、パラメータが使われていることを確認してください。"},
"extraTopBlocks":function(d){return "ブロックを外しました。もしかして、「実行時」のブロックにつなげたかったですか?"},
"extraTopBlocksWhenRun":function(d){return "You have unattached blocks. Did you mean to attach these to the \"when run\" block?"},
"finalStage":function(d){return "おめでとうございます !最終ステージをクリアしました。"},
"finalStageTrophies":function(d){return "おめでとうございます !最終ステージをクリアしたので  "+common_locale.p(d,"numTrophies",0,"ja",{"one":"トロフィー","other":common_locale.n(d,"numTrophies")+" トロフィー"})+"を獲得しました。"},
"finish":function(d){return "完了"},
"generatedCodeInfo":function(d){return "アメリカのトップの大学(例えば、"+common_locale.v(d,"berkeleyLink")+" "+common_locale.v(d,"harvardLink")+")でもブロック ベースのプログラミングを教えています 。あなたが組み合わせたブロックは実際のプログラム言語でどのようになっているか確認できるようにJavaScriptで表示できます。JavaScriptは世界中で最も広く使われているプログラム言語です。"},
"genericFeedback":function(d){return "どうなったかよく見て、プログラムを直してみよう。"},
"hashError":function(d){return "申し訳ありませんが、'%1'は保存されているプログラムと一致しません。"},
"help":function(d){return "ヘルプ"},
"hideToolbox":function(d){return "(Hide)"},
"hintHeader":function(d){return "コツ:"},
"hintRequest":function(d){return "ヒントを見る"},
"hintTitle":function(d){return "ヒント:"},
"infinity":function(d){return "無限\n"},
"jump":function(d){return "ジャンプ"},
"keepPlaying":function(d){return "Keep Playing"},
"levelIncompleteError":function(d){return "構成に必要なブロックをすべて使っていますが、使い方が適切ではありません。"},
"listVariable":function(d){return "リスト"},
"makeYourOwnFlappy":function(d){return "自分だけの「パタパタゲーム」を作りましょう。"},
"missingBlocksErrorMsg":function(d){return "下にあるブロックを使ってこのパズルを解いてみましょう。"},
"nextLevel":function(d){return "おめでとうございます !あなたはパズルを "+common_locale.v(d,"puzzleNumber")+" 完了しました。"},
"nextLevelTrophies":function(d){return "おめでとうございます !あなたはパズル "+common_locale.v(d,"puzzleNumber")+" をクリアし、"+common_locale.p(d,"numTrophies",0,"ja",{"one":"トロフィー","other":common_locale.n(d,"numTrophies")+" トロフィー"})+"を獲得しました。"},
"nextPuzzle":function(d){return "次のパズル"},
"nextStage":function(d){return "おめでとうございます !"+common_locale.v(d,"stageName")+"を クリアしました。"},
"nextStageTrophies":function(d){return "おめでとうございます! "+common_locale.v(d,"stageName")+" をクリアして "+common_locale.p(d,"numTrophies",0,"ja",{"one":"a trophy","other":common_locale.n(d,"numTrophies")+" trophies"})+" を手に入れました。"},
"numBlocksNeeded":function(d){return "おめでとうございます !あなたはパズル "+common_locale.v(d,"puzzleNumber")+" をクリアしました。 (ヒント: "+common_locale.p(d,"numBlocks",0,"ja",{"one":"1ブロック","other":common_locale.n(d,"numBlocks")+"ブロック"})+" だけで解くこともできました。)"},
"numLinesOfCodeWritten":function(d){return "あなたはたった今 "+common_locale.p(d,"numLines",0,"ja",{"one":"1 行","other":common_locale.n(d,"numLines")+" 行"})+" のコードを書きました!"},
"openWorkspace":function(d){return "仕組み"},
"orientationLock":function(d){return "デバイスの設定にあるオリエンテーション(方向)ロックをオフにしてください。"},
"play":function(d){return "再生する"},
"print":function(d){return "印刷"},
"puzzleTitle":function(d){return "パズル "+common_locale.v(d,"puzzle_number")+" (全 "+common_locale.v(d,"stage_total")+" ステージ)"},
"readonlyWorkspaceHeader":function(d){return "View only: "},
"repeat":function(d){return "繰り返し"},
"resetProgram":function(d){return "リセット"},
"rotateText":function(d){return "お使いのデバイスを回転させてください。"},
"runProgram":function(d){return "実行"},
"runTooltip":function(d){return "ワークスペース内にブロックで作られたプログラムを実行します。\n"},
"saveToGallery":function(d){return "ギャラリーに保存"},
"savedToGallery":function(d){return "ギャラリーに保存されました!"},
"score":function(d){return "スコア"},
"shareFailure":function(d){return "プログラムをシェアできませんでした。"},
"showBlocksHeader":function(d){return "ブロックを表示"},
"showCodeHeader":function(d){return "コードの表示"},
"showGeneratedCode":function(d){return "コードを表示します。"},
"showTextHeader":function(d){return "Show Text"},
"showToolbox":function(d){return "Show Toolbox"},
"signup":function(d){return "イントロのコースに申し込む"},
"stringEquals":function(d){return "文字列 =?"},
"subtitle":function(d){return "ビジュアル ・ プログラミング環境"},
"textVariable":function(d){return "テキスト"},
"toggleBlocksErrorMsg":function(d){return "ブロックとして表示させるために、あなたのプログラムのエラーを直す必要があります。"},
"tooFewBlocksMsg":function(d){return "すべての必要な種類のブロックを使用していますが、これらの種類のブロックも使ってみてこのパズルを完成させてください。"},
"tooManyBlocksMsg":function(d){return "このパズルは <x id='START_SPAN'/><x id='END_SPAN'/>のブロックで解決できます。\n"},
"tooMuchWork":function(d){return "ちょっと作業が多すぎますね!もう少し繰り返し回数を少なくできませんか?"},
"toolboxHeader":function(d){return "ブロック達"},
"toolboxHeaderDroplet":function(d){return "Toolbox"},
"totalNumLinesOfCodeWritten":function(d){return "すべての時間の合計:  "+common_locale.p(d,"numLines",0,"ja",{"one":"1 ライン","other":common_locale.n(d,"numLines")+" ライン"})+" のコード\n"},
"tryAgain":function(d){return "やり直す"},
"tryHOC":function(d){return "「コードの時間」に挑戦する"},
"wantToLearn":function(d){return "プログラムを覚えてみたいですか?"},
"watchVideo":function(d){return "ビデオを見る"},
"when":function(d){return "とき"},
"whenRun":function(d){return "実行した時"},
"workspaceHeaderShort":function(d){return "ワークスペース:"}};


text:
/**
 * directivas en angular
 */

(function () {
    'user strict';

    angular.module('app.components.perfil').directive('social', social);

    social.$inject = [];

    function social(){
        //DDO (Directive Definition Object)
        return {
            template:`

Social

directiva

            `,
            link

        };

        function link(scope, element, attrs) {

            element.on('click', function (e) {
                alert('click con directiva');
            })

        }

    }

}());


text:
import { FC } from 'react'
import Link from 'next/link'

import { Wrapper, Note, Addr } from '../styles/desktop_view/simple_layout'

const SimpleLayout: FC = () => {
  return (
    <Wrapper>
      <Note>
        由{' '}
        <Link href="https://groupher.com" passHref>
          <Addr>Groupher</Addr>
        </Link>{' '}
        提供服务
      </Note>
    </Wrapper>
  )
}

export default SimpleLayout


text:
<?php
/**
 * Vainyl
 *
 * PHP Version 7
 *
 * @package   Core
 * @license   https://opensource.org/licenses/MIT MIT License
 * @link      https://vainyl.com
 */
declare(strict_types=1);

namespace Vainyl\Core\Application;

use Vainyl\Core\ArrayInterface;
use Vainyl\Core\Extension\AbstractExtension;
use Vainyl\Core\NameableInterface;
use Vainyl\Core\StringInterface;

/**
 * Interface EnvironmentInterface
 *
 * @author Taras P. Girnyk <taras.p.gyrnik@gmail.com>
 */
interface EnvironmentInterface extends NameableInterface, ArrayInterface, StringInterface
{
    /**
     * @return bool
     */
    public function isDebugEnabled(): bool;

    /**
     * @return bool
     */
    public function isCachingEnabled(): bool;

    /**
     * @return string
     */
    public function getApplicationDirectory(): string;

    /**
     * @return string
     */
    public function getConfigDirectory(): string;

    /**
     * @return string
     */
    public function getDebugDirectory(): string;

    /**
     * @return string
     */
    public function getCacheDirectory(): string;

    /**
     * @return string
     */
    public function getContainerConfig(): string;

    /**
     * @return AbstractExtension[]
     */
    public function getExtensions(): array;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright Txus Ballesteros 2016 (@txusballesteros)
This file is part of some open source application.
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
Contact: Txus Ballesteros <txus.ballesteros@gmail.com>
-->
<com.redbooth.WelcomePageLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/welcome_page"
    tools:background="@color/page3">

    <View
        android:id="@+id/android_destiny"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="20dp"
        android:layout_marginRight="40dp"/>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/easel"/>

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="70dp">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/arrow_chart"/>

            <View
                android:id="@+id/arrow_chart_mask"
                android:layout_width="150dp"
                android:layout_height="90dp"
                android:transformPivotX="150dp"
                android:background="@color/white"/>

        </FrameLayout>

        <ImageView
            android:id="@+id/avatar5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:layout_marginLeft="10dp"
            android:scaleX="0"
            android:scaleY="0"
            android:src="@drawable/avatar_lucy2" />

    </RelativeLayout>

    <TextView
        style="@style/text_title"
        android:id="@+id/title"
        android:layout_above="@+id/subtitle"
        android:text="In sync and on track"
        app:view_behavior=".ParallaxTitleBehaviour" />

    <TextView
        style="@style/text_subtitle"
        android:id="@+id/subtitle"
        android:layout_alignParentBottom="true"
        android:text="Visualize progress and notify\nteam members of important\nupdates."
        app:view_behavior=".ParallaxSubtitleBehaviour" />

</com.redbooth.WelcomePageLayout>


text:
title: The Water Jug Problem in Hedgehog
author: Ezequiel A. Alvarez
tags: haskell, hypothesis, hedgehog, quickcheck
---

A couple of weeks ago this [blog post](http://hypothesis.works/articles/how-not-to-die-hard-with-hypothesis/) over at the Hypothesis blog caught my eye. I had heard of TLA+ before, but the simplicity of the [linked solution](https://github.com/tlaplus/Examples/blob/master/specifications/DieHard/DieHard.tla) surprised me.

And the Python solution was very nice too, I totally have to bring Hypothesis to the office someday.

Anyway, some days later that same week, @jystic [announced the release of Hedgehog](https://www.reddit.com/r/haskell/comments/646k3d/ann_hedgehog_property_testing/), a property based testing library, much like QuickCheck but with a more modern approach.

Look, I'd never used QuickCheck or property testing for a real project before, so I was kind of surprised when I recognized some of the advantages @jystic said his library had. Specifically:

* No Arbitrary instances.
* * The amount of boilerplate needed to avoid orphan instances is tedious in general.
* Showing the values and code where a property fails.
* * The first *frictious* moment I had when using QuickCheck was exactly because of this.

So it was set. Let's try Hedgehog with the Water Jug problem.

## The problem

This is better explained in the Hypothesis post, but let's recapitulate: you have 2 water jugs that you can either fill or empty. One has 5 litter capacity and the other 3. You win by leaving 4 litters in the big one.

## The code

I didn't want many dependencies, so no state monads or funny folds. Just a good old finite state machine. The `fsm` function will take a **state** and a **step**, and return a new **state**.

We start by importing,

```haskell
module Jugs where

import           Hedgehog
import           Hedgehog.Internal.Property (TestLimit(..))
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
```

and then defining our type for the problem:

```haskell
data Step = FillBig
          | FillSmall
          | EmptyBig
          | EmptySmall
          | SmallIntoBig
          | BigIntoSmall
          deriving (Show, Eq, Enum)
```

Those are all the different kinds of steps we'll have.

We will also need state to keep track of how much water our jugs have,

```haskell
data State = State
  { bigJug :: Int
  , smallJug :: Int
  } deriving (Show, Eq)
```

which by the way start out empty:

```haskell
initial :: State
initial = State { bigJug = 0, smallJug = 0}
```

Now, let's define what each step does:

```haskell
fsm :: State -> Step -> State
fsm s FillBig = s { bigJug = 5 }
fsm s FillSmall = s { smallJug = 3 }
fsm s EmptyBig = s { bigJug = 0 }
fsm s EmptySmall = s { smallJug = 0 }
fsm (State big small) SmallIntoBig =
    let big' = min 5 (big + small) in
    State { bigJug = big'
          , smallJug = small - (big' - big) }
fsm (State big small) BigIntoSmall =
    let small' = min 3 (big + small) in
    State { bigJug = big - (small' - small)
          , smallJug = small' }
```

That was easy. Let's also define a function that executes a list of steps from the initial state:

```haskell
execute :: [Step] -> State
execute = foldl fsm initial
```

Finally, the Hedgehog bits. We want to say: give me a random list of steps that has length between 0 and 20. We do it like so:

```haskell
steps :: Monad m => Gen m [Step]
steps = Gen.list (Range.linear 0 20) (Gen.enum FillBig BigIntoSmall)
```

Also we define our property, which we want to see proven false,

```haskell
prop_solution :: Property
prop_solution = withTests (TestLimit 5000) . property $ do
    s <- forAll steps
    let (State big small) = execute s
    assert $ big /= 4
```

also setting the TestLimit to 5000, so it doesn't give up too early.

## The solution

We can load this file using `stack ghci --package=hedgehog-0.1`, after adding hedgehog and any other missing deps to the global stack project (that is `~/.stack/global-project/stack.yaml`). Finally, we get:

```haskell
*Jugs λ> check prop_solution
  ✗ <interactive> failed after 3290 tests and 5 shrinks.

       ┏━━ Jugs.hs ━━━
    44 ┃ prop_solution :: Property
    45 ┃ prop_solution = withTests (TestLimit 5000) . property $ do
    46 ┃     s <- forAll steps
       ┃     │ [ FillBig
       ┃     │ , BigIntoSmall
       ┃     │ , EmptySmall
       ┃     │ , BigIntoSmall
       ┃     │ , FillBig
       ┃     │ , BigIntoSmall
       ┃     │ ]
    47 ┃     let (State big small) = execute s
    48 ┃     assert $ big /= 4
       ┃     ^^^^^^^^^^^^^^^^^
```

Isn't that pretty? It even has colors on my terminal.

Also, the solution is exactly the same the Hypothesis post had! (I saw other solutions, some even not optimal, but this one was the most common).

I think I'm gonna like Hedgehog.

In the meantime, I'll see about implementing the [generic solution](http://vigna.di.unimi.it/ftp/papers/Jugs.pdf) some day.