text:
'use strict';

var Axes = require('../../plots/cartesian/axes');
var alignPeriod = require('../../plots/cartesian/align_period');
var hasColorscale = require('../../components/colorscale/helpers').hasColorscale;
var colorscaleCalc = require('../../components/colorscale/calc');
var arraysToCalcdata = require('./arrays_to_calcdata');
var calcSelection = require('../scatter/calc_selection');

module.exports = function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var size, pos, origPos;

    var sizeOpts = {
        msUTC: !!(trace.base || trace.base === 0)
    };

    var hasPeriod;
    if(trace.orientation === 'h') {
        size = xa.makeCalcdata(trace, 'x', sizeOpts);
        origPos = ya.makeCalcdata(trace, 'y');
        pos = alignPeriod(trace, ya, 'y', origPos);
        hasPeriod = !!trace.yperiodalignment;
    } else {
        size = ya.makeCalcdata(trace, 'y', sizeOpts);
        origPos = xa.makeCalcdata(trace, 'x');
        pos = alignPeriod(trace, xa, 'x', origPos);
        hasPeriod = !!trace.xperiodalignment;
    }

    // create the "calculated data" to plot
    var serieslen = Math.min(pos.length, size.length);
    var cd = new Array(serieslen);

    // set position and size
    for(var i = 0; i < serieslen; i++) {
        cd[i] = { p: pos[i], s: size[i] };

        if(hasPeriod) {
            cd[i].orig_p = origPos[i]; // used by hover
        }

        if(trace.ids) {
            cd[i].id = String(trace.ids[i]);
        }
    }

    // auto-z and autocolorscale if applicable
    if(hasColorscale(trace, 'marker')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.color,
            containerStr: 'marker',
            cLetter: 'c'
        });
    }
    if(hasColorscale(trace, 'marker.line')) {
        colorscaleCalc(gd, trace, {
            vals: trace.marker.line.color,
            containerStr: 'marker.line',
            cLetter: 'c'
        });
    }

    arraysToCalcdata(cd, trace);
    calcSelection(cd, trace);

    return cd;
};


text:
package com.google.errorprone.bugpatterns;

/**
 * @author scottjohnson@google.com (Scott Johnson)
 */
public class SelfEqualityPositiveCases {
  private double value;

  //BUG: Suggestion includes "!Double.isNaN(value)"
  private boolean othervalue = value == value;

  public boolean testEquality(double x, float y, int z) {
    boolean retVal;

    //BUG: Suggestion includes "!Double.isNaN(x)"
    retVal = x == x;

    //BUG: Suggestion includes "Double.isNaN(x)"
    retVal = x != x;

    //BUG: Suggestion includes "!Float.isNaN(y)"
    retVal = y == y;

    //BUG: Suggestion includes "Float.isNaN(y)"
    retVal = y != y;

    //BUG: Suggestion includes "true"
    retVal = z == z;

    //BUG: Suggestion includes "false"
    retVal = z != z;

    return retVal;
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof SelfEqualityPositiveCases)) {
      return false;
    }
    SelfEqualityPositiveCases other = (SelfEqualityPositiveCases) o;

    boolean ret;

    //BUG: Suggestion includes "value == other.value"
    ret = value == value;

    //BUG: Suggestion includes "this.value == other.value"
    ret = this.value == value;

    //BUG: Suggestion includes "other.value == this.value"
    ret = value == this.value;

    //BUG: Suggestion includes "this.value == other.value"
    ret = this.value == this.value;

    return ret;
  }

}

redpajama_set_name: RedPajamaGithub


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

using System;
using System.Runtime.Serialization;

namespace ReleaseNotesUtil
{
    /// <summary>
    /// Info that we care about from a DiagnosticDescriptor.
    /// </summary>
    [DataContract]
    internal class RuleInfo
    {
        public RuleInfo(string id, string title, string category, bool isEnabledByDefault, bool hasCodeFix, string messageFormat, string description, string helpLink)
        {
            Id = id ?? throw new ArgumentNullException(nameof(id));
            Title = title ?? throw new ArgumentNullException(nameof(title));
            Category = category ?? throw new ArgumentNullException(nameof(category));
            IsEnabledByDefault = isEnabledByDefault;
            HasCodeFix = hasCodeFix;
            MessageFormat = messageFormat ?? throw new ArgumentNullException(nameof(messageFormat));
            Description = description;
            HelpLink = helpLink;
        }

        public RuleInfo()
        {
        }

        [DataMember]
        public string? Id { get; set; }

        [DataMember]
        public string? Title { get; set; }

        [DataMember]
        public string? Category { get; set; }

        [DataMember]
        public bool IsEnabledByDefault { get; set; }

        [DataMember]
        public bool HasCodeFix { get; set; }

        [DataMember]
        public string? MessageFormat { get; set; }

        [DataMember]
        public string? Description { get; set; }

        [DataMember]
        public string? HelpLink { get; set; }

        // Computed properties.
        public string IdWithHelpLinkMarkdown
            => !string.IsNullOrWhiteSpace(this.HelpLink)
                ? $"[{this.Id}]({this.HelpLink})"
                : this.Id ?? string.Empty;

        public string DescriptionOrMessageFormatMarkdown
            => (!string.IsNullOrWhiteSpace(this.Description)
                    ? this.Description
                    : this.MessageFormat)
                ?? string.Empty;
    }
}


text:
class Asciidoc < Formula
  homepage "http://asciidoc.org/"
  url "https://downloads.sourceforge.net/project/asciidoc/asciidoc/8.6.9/asciidoc-8.6.9.tar.gz"
  sha1 "82e574dd061640561fa0560644bc74df71fb7305"

  bottle do
    cellar :any
    revision 1
    sha1 "14ff65fa337658acf5011b24a728a2f6f413fd3c" => :yosemite
    sha1 "84793575a498025283f81295feeee74103386b70" => :mavericks
    sha1 "7c932bea7c4d3e56072a7adb5cd4914cd5972414" => :mountain_lion
  end

  head do
    url "https://github.com/asciidoc/asciidoc.git"
    depends_on "autoconf" => :build
  end

  depends_on "docbook"

  option "with-docbook-xsl", "Install DTDs to generate manpages"
  depends_on "docbook-xsl" => :optional

  def install
    system "autoconf" if build.head?
    system "./configure", "--prefix=#{prefix}"

    # otherwise OS X's xmllint bails out
    inreplace "Makefile", "-f manpage", "-f manpage -L"
    system "make", "install"
  end

  def caveats; <<-EOS.undent
      If you intend to process AsciiDoc files through an XML stage
      (such as a2x for manpage generation) you need to add something
      like:

        export XML_CATALOG_FILES=#{etc}/xml/catalog

      to your shell rc file so that xmllint can find AsciiDoc's
      catalog files.

      See `man 1 xmllint' for more.
    EOS
  end

  test do
    (testpath/"test.txt").write("== Hello World!")
    system "#{bin}/asciidoc", "-b", "html5", "-o", "test.html", "test.txt"
    assert_match /\<h2 id="_hello_world"\>Hello World!\<\/h2\>/, File.read("test.html")
  end
end


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

	<Button android:id="@+id/button_1"
			style="@style/im_popup_number_button"
			android:text="1"/>
	<Button android:id="@+id/button_2"
			style="@style/im_popup_number_button"
			android:text="2"
			android:layout_toRightOf="@+id/button_1"/>
	<Button android:id="@+id/button_3"
			style="@style/im_popup_number_button"
			android:text="3"
			android:layout_toRightOf="@+id/button_2"/>

	<Button android:id="@+id/button_4"
			style="@style/im_popup_number_button"
			android:text="4"
			android:layout_below="@+id/button_1"/>
	<Button android:id="@+id/button_5"
			style="@style/im_popup_number_button"
			android:text="5"
			android:layout_toRightOf="@+id/button_4"
			android:layout_below="@+id/button_1"/>
	<Button android:id="@+id/button_6"
			style="@style/im_popup_number_button"
			android:text="6"
			android:layout_toRightOf="@+id/button_5"
			android:layout_below="@+id/button_1"/>

	<Button android:id="@+id/button_7"
			style="@style/im_popup_number_button"
			android:text="7"
			android:layout_below="@+id/button_4"/>
	<Button android:id="@+id/button_8"
			style="@style/im_popup_number_button"
			android:text="8"
			android:layout_toRightOf="@+id/button_7"
			android:layout_below="@+id/button_4"/>
	<Button android:id="@+id/button_9"
			style="@style/im_popup_number_button"
			android:text="9"
			android:layout_toRightOf="@+id/button_8"
			android:layout_below="@+id/button_4"/>

	<Button android:id="@+id/button_close"
			style="@style/im_popup_close_button"
			android:text="@string/close"
			android:layout_below="@+id/button_7"/>

	<Button android:id="@+id/button_clear"
			style="@style/im_popup_clear_button"
			android:text="@string/clear"
			android:layout_toRightOf="@+id/button_close"
			android:layout_alignBottom="@+id/button_close"/>
</RelativeLayout>


text:
<?php

namespace ProjectBundle\Bundle\CoreBundle\Controller;

class AuthController extends BaseController
{
    public function loginAction()
    {
        die('hello login');
    }

    public function logoutAction()
    {
        die('logout');
    }
}


text:
/*
 * zw_cmd_tool.h
 *
 *  Created on: Aug 23, 2016
 *      Author: aes
 */

#ifndef XML_ZW_CMD_TOOL_H_
#define XML_ZW_CMD_TOOL_H_

#include <stdint.h>
#include <stdio.h>
struct zw_enum {
  const char* name;
  int value;
};

struct zw_bitparam {
  int mask;

  const char* name;
  struct zw_enum enums[];
};
struct zw_parameter {
  // int offset; //Byte Offset in package where this parameter is located
  int length;  // Length of this parameter, 0 means dynamic length. In this case
               // length location will be given.

  const struct zw_parameter* length_location;  // Parameter in this package
                                               // where this length is given 0
                                               // mean fixed length
  int length_location_mask;  // Mask of length location

  int mask;  // Mask of this parameter
  enum {
    DISPLAY_DECIMAL,
    DISPLAY_HEX,
    DISPLAY_ASCII,
    DISPLAY_BITMASK,
    DISPLAY_ENUM,
    DISPLAY_ENUM_EXCLUSIVE,
    DISPLAY_STRUCT
  } display;

  const char* name;
  // Optional parameter
  const struct zw_parameter* optionaloffs;  // Parameter of bits indicating if
                                            // this parameter is present
  int optionalmask;  // Mask of precnese bits

  //  struct zw_bitparam* bitparam[];   //Bit parameters
  struct zw_enum* enums;
  const struct zw_parameter* subparams[];
};

struct zw_command {

  int cmd_number;
  int cmd_mask;
  const char* name;
  const char* help;

  const struct zw_parameter* params[];
};

struct zw_command_class {
  int cmd_class_number;
  int cmd_class_number_version;

  const char* name;
  const char* help;
  const struct zw_command* commands[];
};

/**
 * Return a list of command class names
 *
 * @return the number of elements
 */
int zw_cmd_tool_get_command_class_names(const char** name);

/**
 * Get class structure from class name
 */
const struct zw_command_class* zw_cmd_tool_get_class_by_name(const char* name);

/**
 * Return a list of command names for a command class
 *  * @return the number of elements
 */
int zw_cmd_tool_get_cmd_names(const struct zw_command_class* c,
                              const char** names);

/**
 * Retrieve a command structure by its name an the command class
 */
const struct zw_command* zw_cmd_tool_get_cmd_by_name(
    const struct zw_command_class* cls, const char* name);

/**
 * Get the parameter names of a command
 */
int zw_cmd_tool_get_param_names(const struct zw_command* cmd,
                                const char** names);

/**
 * Get parameter by its name
 */
const struct zw_parameter* zw_cmd_tool_get_param_by_name(
    const struct zw_command* cmd, const char* name);

struct zw_param_data {
  const struct zw_parameter* param;
  const uint8_t* data;
  int len;
  int index;
};

/**
 * Construct a z-wave command
 * @param dst destination buffer
 * @param cmd command to generate
 * @prarm param_name_list list of parameternames
 */
int zw_cmd_tool_create_zw_command(uint8_t* dst, int dst_len,
                                  const char* cmdClass, const char* cmd,
                                  struct zw_param_data* data[]);

/**
 * Display help related to a specific command
 *
 * the help is line should be in the format
 *
 * help <COMMAND_CLASS_xxxx> <COMMAND_xxxx>
 */
void zw_cmd_tool_display_help(FILE* f, char* line);

#endif /* XML_ZW_CMD_TOOL_H_ */


text:
.. _kernels:

==========================
Making kernels for Jupyter
==========================

A 'kernel' is a program that runs and introspects the user's code. IPython
includes a kernel for Python code, and people have written kernels for
`several other languages <https://github.com/ipython/ipython/wiki/IPython-kernels-for-other-languages>`_.

When Jupyter starts a kernel, it passes it a connection file. This specifies
how to set up communications with the frontend.

There are two options for writing a kernel:

1. You can reuse the IPython kernel machinery to handle the communications, and
   just describe how to execute your code. This is much simpler if the target
   language can be driven from Python. See :doc:`wrapperkernels` for details.
2. You can implement the kernel machinery in your target language. This is more
   work initially, but the people using your kernel might be more likely to
   contribute to it if it's in the language they know.

Connection files
================

Your kernel will be given the path to a connection file when it starts (see
:ref:`kernelspecs` for how to specify the command line arguments for your kernel).
This file, which is accessible only to the current user, will contain a JSON
dictionary looking something like this::

    {
      "control_port": 50160,
      "shell_port": 57503,
      "transport": "tcp",
      "signature_scheme": "hmac-sha256",
      "stdin_port": 52597,
      "hb_port": 42540,
      "ip": "127.0.0.1",
      "iopub_port": 40885,
      "key": "a0436f6c-1916-498b-8eb9-e81ab9368e84"
    }

The ``transport``, ``ip`` and five ``_port`` fields specify five ports which the
kernel should bind to using `ZeroMQ <http://zeromq.org/>`_. For instance, the
address of the shell socket in the example above would be::

    tcp://127.0.0.1:57503

New ports are chosen at random for each kernel started.

``signature_scheme`` and ``key`` are used to cryptographically sign messages, so
that other users on the system can't send code to run in this kernel. See
:ref:`wire_protocol` for the details of how this signature is calculated.

Handling messages
=================

After reading the connection file and binding to the necessary sockets, the
kernel should go into an event loop, listening on the hb (heartbeat), control
and shell sockets.

:ref:`Heartbeat <kernel_heartbeat>` messages should be echoed back immediately
on the same socket - the frontend uses this to check that the kernel is still
alive.

Messages on the control and shell sockets should be parsed, and their signature
validated. See :ref:`wire_protocol` for how to do this.

The kernel will send messages on the iopub socket to display output, and on the
stdin socket to prompt the user for textual input.

.. seealso::

   :doc:`messaging`
     Details of the different sockets and the messages that come over them

   `Creating Language Kernels for IPython <http://andrew.gibiansky.com/blog/ipython/ipython-kernels/>`_
     A blog post by the author of `IHaskell <https://github.com/gibiansky/IHaskell>`_,
     a Haskell kernel

   `simple_kernel <https://github.com/dsblank/simple_kernel>`_
     A simple example implementation of the kernel machinery in Python

.. _kernelspecs:

Kernel specs
============

A kernel identifies itself to IPython by creating a directory, the name of which
is used as an identifier for the kernel. These may be created in a number of
locations:

+--------+--------------------------------------------+-----------------------------------+
|        | Unix                                       | Windows                           |
+========+============================================+===================================+
| System | ``/usr/share/jupyter/kernels``             | ``%PROGRAMDATA%\jupyter\kernels`` |
|        |                                            |                                   |
|        | ``/usr/local/share/jupyter/kernels``       |                                   |
+--------+--------------------------------------------+-----------------------------------+
| Env    |                          ``{sys.prefix}/share/jupyter/kernels``                |
+--------+--------------------------------------------+-----------------------------------+
| User   | ``~/.local/share/jupyter/kernels`` (Linux) | ``%APPDATA%\jupyter\kernels``     |
|        |                                            |                                   |
|        | ``~/Library/Jupyter/kernels`` (Mac)        |                                   |
+--------+--------------------------------------------+-----------------------------------+

The user location takes priority over the system locations, and the case of the
names is ignored, so selecting kernels works the same way whether or not the
filesystem is case sensitive.

Other locations may also be searched if the :envvar:`JUPYTER_PATH` environment
variable is set.

Inside the directory, the most important file is *kernel.json*. This should be a
JSON serialised dictionary containing the following keys and values:

- **argv**: A list of command line arguments used to start the kernel. The text
  ``{connection_file}`` in any argument will be replaced with the path to the
  connection file.
- **display_name**: The kernel's name as it should be displayed in the UI.
  Unlike the kernel name used in the API, this can contain arbitrary unicode
  characters.
- **language**: The name of the language of the kernel.
  When loading notebooks, if no matching kernelspec key (may differ across machines)
  is found, a kernel with a matching `language` will be used.
  This allows a notebook written on any Python or Julia kernel to be properly associated
  with the user's Python or Julia kernel, even if they aren't listed under the same name as the author's.
- **env** (optional): A dictionary of environment variables to set for the kernel.
  These will be added to the current environment variables before the kernel is
  started.

For example, the kernel.json file for IPython looks like this::

    {
     "argv": ["python3", "-m", "IPython.kernel",
              "-f", "{connection_file}"],
     "display_name": "Python 3",
     "language": "python"
    }

To see the available kernel specs, run::

    jupyter kernelspec list

To start the terminal console or the Qt console with a specific kernel::

    jupyter console --kernel bash
    jupyter qtconsole --kernel bash

The notebook offers you the available kernels in a dropdown menu from the 'New'
button.


text:
<?xml version="1.0"?>
<!--
   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.
-->

<!DOCTYPE Repository
          PUBLIC "-//The Apache Software Foundation//DTD Jackrabbit 2.0//EN"
          "http://jackrabbit.apache.org/dtd/repository-2.0.dtd">

<!-- Example Repository Configuration File
     Used by
     - org.apache.jackrabbit.core.config.RepositoryConfigTest.java
     -
-->
<Repository>
    <!--
        virtual file system where the repository stores global state
        (e.g. registered namespaces, custom node types, etc.)
    -->
    <FileSystem class="org.apache.jackrabbit.core.fs.local.LocalFileSystem">
        <param name="path" value="${rep.home}/repository"/>
    </FileSystem>

    <!--
        data store configuration
    -->
    <DataStore class="org.apache.jackrabbit.core.data.FileDataStore"/>

    <!--
        security configuration
    -->
    <Security appName="Jackrabbit">
        <!--
            security manager:
            class: FQN of class implementing the JackrabbitSecurityManager interface
        -->
        <SecurityManager class="org.apache.jackrabbit.core.DefaultSecurityManager" workspaceName="security">
            <WorkspaceAccessManager class="org.apache.jackrabbit.core.security.simple.SimpleWorkspaceAccessManager"/>            <!--
            workspace access:
            class: FQN of class implementing the WorkspaceAccessManager interface
            -->
            <!-- <WorkspaceAccessManager class="..."/> -->
            <!-- <param name="config" value="${rep.home}/security.xml"/> -->
        </SecurityManager>

        <!--
            access manager:
            class: FQN of class implementing the AccessManager interface
        <AccessManager class="org.apache.jackrabbit.core.security.simple.SimpleAccessManager">
            <param name="config" value="${rep.home}/access.xml"/>
        </AccessManager>
        -->

        <LoginModule class="net.unit8.longadeseo.security.AnonymousLoginModule">
        </LoginModule>

    </Security>

    <!--
        location of workspaces root directory and name of default workspace
    -->
    <Workspaces rootPath="${rep.home}/workspaces" defaultWorkspace="default"/>
    <!--
        workspace configuration template:
        used to create the initial workspace if there's no workspace yet
    -->
    <Workspace name="${wsp.name}">
        <!--
            virtual file system of the workspace:
            class: FQN of class implementing the FileSystem interface
        -->
        <FileSystem class="org.apache.jackrabbit.core.fs.local.LocalFileSystem">
            <param name="path" value="${wsp.home}"/>
        </FileSystem>
        <!--
            persistence manager of the workspace:
            class: FQN of class implementing the PersistenceManager interface
        -->
        <PersistenceManager class="org.apache.jackrabbit.core.persistence.pool.DerbyPersistenceManager">
          <param name="url" value="jdbc:derby:${wsp.home}/db;create=true"/>
          <param name="schemaObjectPrefix" value="${wsp.name}_"/>
        </PersistenceManager>
        <!--
            Search index and the file system it uses.
            class: FQN of class implementing the QueryHandler interface
        -->
        <SearchIndex class="org.apache.jackrabbit.core.query.lucene.SearchIndex">
            <param name="path" value="${wsp.home}/index"/>
            <param name="supportHighlighting" value="true"/>
        </SearchIndex>

        <WorkspaceSecurity>
            <AccessControlProvider class="org.apache.jackrabbit.core.security.authorization.combined.CombinedProvider" />
        </WorkspaceSecurity>
    </Workspace>

    <!--
        Configures the versioning
    -->
    <Versioning rootPath="${rep.home}/version">
        <!--
            Configures the filesystem to use for versioning for the respective
            persistence manager
        -->
        <FileSystem class="org.apache.jackrabbit.core.fs.local.LocalFileSystem">
            <param name="path" value="${rep.home}/version" />
        </FileSystem>

        <!--
            Configures the persistence manager to be used for persisting version state.
            Please note that the current versioning implementation is based on
            a 'normal' persistence manager, but this could change in future
            implementations.
        -->
        <PersistenceManager class="org.apache.jackrabbit.core.persistence.pool.DerbyPersistenceManager">
          <param name="url" value="jdbc:derby:${rep.home}/version/db;create=true"/>
          <param name="schemaObjectPrefix" value="version_"/>
        </PersistenceManager>
    </Versioning>

    <!--
        Search index for content that is shared repository wide
        (/jcr:system tree, contains mainly versions)
    -->
    <SearchIndex class="org.apache.jackrabbit.core.query.lucene.SearchIndex">
        <param name="path" value="${rep.home}/repository/index"/>
        <param name="supportHighlighting" value="true"/>
    </SearchIndex>
</Repository>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Schr. naturf. Ges. Leipzig 1: 48 (1822)

#### Original name
Sphaeria zeae Schwein., 1822

### Remarks
null


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

namespace MoarDT.CRDT
{
    public abstract class AbstractCRDT
    {
        internal static string DefaultClientId()
        {
            return System.Net.Dns.GetHostName();
        }
    }
}


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

import java.io.Serializable;

import com.jain.addon.web.bean.JVisibilityType;
import com.jain.addon.web.bean.annotation.JNIAttribute;

@SuppressWarnings("serial")
public class ZIP implements Serializable {
	private String zip;

	@JNIAttribute (lable = "zip", visibility = JVisibilityType.COLLAPSED, order = 201)
	public String getZip() {
		return zip;
	}

	public void setZip(String zip) {
		this.zip = zip;
	}
}


text:
package io.craigmiller160.locus;

import io.craigmiller160.locus.concurrent.UIThreadExecutorFactory;
import io.craigmiller160.locus.sample.ModelOne;
import io.craigmiller160.locus.sample.ViewOne;
import io.craigmiller160.locus.sample.ViewThree;
import io.craigmiller160.locus.util.LocusStorage;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * A special test class to test the combined
 * functionality of LocusModel & LocusView.
 * LocusModel should be able to remotely update
 * properties in LocusView every time it updates
 * a model.
 *
 * Please note that if any of these tests are failing,
 * it is entirely possible that other tests are failing
 * as well in the individual LocusModelTest & LocusViewTest
 * classes. Those tests will need to be resolved first
 * before being able to ensure that these work.
 *
 * Created by craig on 4/1/16.
 */
public class LocusModelViewTest {

    private static final Logger logger = LoggerFactory.getLogger(LocusModelViewTest.class);

    private LocusStorage storage;
    private LocusModel locusModel;
    private LocusView locusView;
    private ViewOne viewOne;
    private ViewThree viewThree;
    private ModelOne modelOne;
    private UIThreadExecutorFactory factory;

    private void setupViews(){
        Map<Class<?>,Object> views = TestUtils.setupViews(storage);
        viewOne = (ViewOne) views.get(ViewOne.class);
        viewThree = (ViewThree) views.get(ViewThree.class);
    }

    private void setupModels(){
        Map<Class<?>,Object> models = TestUtils.setupModels(storage);
        modelOne = (ModelOne) models.get(ModelOne.class);
    }

    private void setupLocus(){
        this.locusView = new LocusView(storage, factory);
        this.locusModel = new LocusModel(storage, locusView);
    }

    @Before
    public void initialize(){
        storage = TestUtils.setupStorage();
        factory = TestUtils.setupUIThreadExecutor(storage);
        setupViews();
        setupModels();
        setupLocus();
    }

    /**
     * Test setting a property in a model and the
     * corresponding view.
     */
    @Test
    public void testSetModelAndView(){
        BigDecimal value = new BigDecimal("3.33333");
        locusModel.setValue("ObjectField", value);

        assertNotNull("ModelOne ObjectField is null", modelOne.getObjectField());
        assertNotNull("ViewOne ObjectField is null", viewOne.getObjectField());

        assertEquals("ModelOne ObjectField wrong value", value, modelOne.getObjectField());
        assertEquals("ViewOne ObjectField wrong value", value, viewOne.getObjectField());
    }

    /**
     * Test setting a model property in multiple views.
     */
    @Test
    public void testSetModelAndMultipleViews(){
        String value = "Value";
        locusModel.setValue("StringField", value);

        assertNotNull("ModelOne StringField is null", modelOne.getStringField());
        assertNotNull("ViewOne StringField is null", viewOne.getStringField());
        assertNotNull("ViewThree StringField is null", viewThree.getStringField());

        assertEquals("ModelOne StringField wrong value", value, modelOne.getStringField());
        assertEquals("ViewOne StringField wrong value", value, viewOne.getStringField());
        assertEquals("ViewThree StringField wrong value", value, viewThree.getStringField());
    }

    /**
     * Test adding a value to a collection property in both
     * a model and a view.
     */
    @Test
    public void testAddModelAndView(){
        String value = "Value";
        locusModel.addValue("String", value);

        String mResult = modelOne.getString(0);
        String vResult = viewOne.getString(0);

        assertEquals("ModeOne has the wrong value in the first position in its String collection", value, mResult);
        assertEquals("ViewOne has the wrong value in the first position in its String collection", value, vResult);
    }

    /**
     * Test removing a value from a collection property in
     * both a model and a view.
     */
    @Test
    public void testRemoveModelAndView(){
        String value = "Value";
        modelOne.addString(value);
        viewOne.addString(value);

        locusModel.removeValue("String", value);

        boolean modelException = false;
        try{
            modelOne.getString(0);
        }
        catch(IndexOutOfBoundsException ex){
            modelException = true;
            logger.error("LocusModelViewTest testRemoveModelAndView() model exception stack trace", ex);
        }

        boolean viewException = false;
        try{
            viewOne.getString(0);
        }
        catch(IndexOutOfBoundsException ex){
            viewException = true;
            logger.error("LocusModelViewTest testRemoveModelAndView() model exception stack trace", ex);
        }

        assertTrue("ModelOne should've thrown an exception for the value not being in the collection", modelException);
        assertTrue("ViewOne should've thrown an exception for the value not being in the collection", viewException);
    }

}


text:
module Fog
  module AWS
    class EFS
      class FileSystem < Fog::Model
        identity :id, :aliases => 'FileSystemId'

        attribute :owner_id,                :aliases => 'OwnerId'
        attribute :creation_token,          :aliases => 'CreationToken'
        attribute :performance_mode,        :aliases => 'PerformanceMode'
        attribute :creation_time,           :aliases => 'CreationTime'
        attribute :state,                   :aliases => 'LifeCycleState'
        attribute :name,                    :aliases => 'Name'
        attribute :number_of_mount_targets, :aliases => 'NumberOfMountTargets'
        attribute :size_in_bytes,           :aliases => 'SizeInBytes'

        def ready?
          state == 'available'
        end

        def mount_targets
          requires :identity
          service.mount_targets(:file_system_id => self.identity).all
        end

        def destroy
          requires :identity

          service.delete_file_system(self.identity)

          true
        end

        def save
          params = {}
          params.merge!(:performance_mode => self.performance_mode) if self.performance_mode

          merge_attributes(service.create_file_system(self.creation_token || Fog::Mock.random_hex(32), params).body)
        end
      end
    end
  end
end


text:
'use strict';

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

// service to store data shared by controllers and open modals
angular.module('modalHelper', []).factory('modalHelper', function () {
  var model = {};
  var events = {
    reset: [],
    close: [],
    showLoader: [],
    hideLoader: [],
    clearModel: []
  };

  var setModel = function setModel(items) {
    model = items;
    publish('reset', [model.modalId]);
  };
  var getModel = function getModel() {
    return model;
  };
  var clearModel = function clearModel(modalId) {
    model = {};
    publish('clearModel', [modalId]);
  };
  var on = function on(evName, fn) {
    if (!events[evName]) {
      throw 'modalHelper: cannot subscribe to unknown \'' + evName + '\' event';
    }
    events[evName].push(fn);
  };

  var getPic = function getPic(result) {
    var pic = '',
        idx = 0;
    if (result.images.length > 1) {
      idx = result.images.length - 2;
    }
    pic = result.images[idx];
    return pic.url;
  };

  var publish = function publish(evName, args) {
    if (!events[evName]) {
      throw 'modalHelper: cannot publish unknown ' + evName + ' event';
    }
    events[evName].forEach(function (fn) {
      return fn.apply(undefined, _toConsumableArray(args));
    });
  };

  return { setModel: setModel, getModel: getModel, on: on, publish: publish, getPic: getPic, clearModel: clearModel };
});


text:
package util

import (
	"fmt"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/v1"
	extensions "k8s.io/kubernetes/pkg/apis/extensions/v1beta1"
	labelsutil "k8s.io/kubernetes/pkg/util/labels"
)

// GetPodTemplateWithHash returns copy of provided template with additional
// label which contains hash of provided template
func GetPodTemplateWithGeneration(template v1.PodTemplateSpec, generation int64) v1.PodTemplateSpec {
	obj, _ := api.Scheme.DeepCopy(template)
	newTemplate := obj.(v1.PodTemplateSpec)
	// DaemonSet pods shouldn't be deleted by NodeController in case of node problems.
	// Add infinite toleration for taint notReady:NoExecute here
	// to survive taint-based eviction enforced by NodeController
	// when node turns not ready.
	v1.AddOrUpdateTolerationInPodSpec(&newTemplate.Spec, &v1.Toleration{
		Key:      metav1.TaintNodeNotReady,
		Operator: v1.TolerationOpExists,
		Effect:   v1.TaintEffectNoExecute,
	})

	// DaemonSet pods shouldn't be deleted by NodeController in case of node problems.
	// Add infinite toleration for taint unreachable:NoExecute here
	// to survive taint-based eviction enforced by NodeController
	// when node turns unreachable.
	v1.AddOrUpdateTolerationInPodSpec(&newTemplate.Spec, &v1.Toleration{
		Key:      metav1.TaintNodeUnreachable,
		Operator: v1.TolerationOpExists,
		Effect:   v1.TaintEffectNoExecute,
	})

	templateGenerationStr := fmt.Sprint(generation)
	newTemplate.ObjectMeta.Labels = labelsutil.CloneAndAddLabel(
		template.ObjectMeta.Labels,
		extensions.DaemonSetTemplateGenerationKey,
		templateGenerationStr,
	)
	return newTemplate
}

// IsPodUpdate checks if pod contains label with provided hash
func IsPodUpdated(dsTemplateGeneration int64, pod *v1.Pod) bool {
	podTemplateGeneration, generationExists := pod.ObjectMeta.Labels[extensions.DaemonSetTemplateGenerationKey]
	dsTemplateGenerationStr := fmt.Sprint(dsTemplateGeneration)
	return generationExists && podTemplateGeneration == dsTemplateGenerationStr
}

// SplitByAvailablePods splits provided daemon set pods by availabilty
func SplitByAvailablePods(minReadySeconds int32, pods []*v1.Pod) ([]*v1.Pod, []*v1.Pod) {
	unavailablePods := []*v1.Pod{}
	availablePods := []*v1.Pod{}
	for _, pod := range pods {
		if v1.IsPodAvailable(pod, minReadySeconds, metav1.Now()) {
			availablePods = append(availablePods, pod)
		} else {
			unavailablePods = append(unavailablePods, pod)
		}
	}
	return availablePods, unavailablePods
}


text:
layout: materia
title: "Métodos Numéricos"
carrera: "at"
tipo: Electiva
caracter: Cuatrimestral
carga_horaria:
    semanal: 10
    total: 160
correlativas:
  - materia: "Matemática 4"
    tipo: TP
    url: /materias-at/mate4
  - materia: "Cálculo Numérico"
    tipo: TP
    url: /materias-at/calculo
  - materia: "Ondas en la Atmósfera 1"
    tipo: TP
    url: /materias-at/ondas1
  - materia: "Ondas en la Atmósfera 2"
    tipo: TP
    url: /materias-at/ondas2

viejoplan: "Vale por Métodos Numéricos en Ciencias de la Atmósfera"
anteriores:
  - "2do cuatrimestre 2015: LU y MI de 14 a 18"
  - "2do cuatrimestre 2013: LU y MI de 14 a 19"

programa: http://www-atmo.at.fcen.uba.ar/programas/MetodosNumericos.pdf
encuestas: http://encuestas_finales.exactas.uba.ar/mat/m15130.html
---

### Contenidos mínimos
Métodos numéricos. Diferencias finitas. Convergencia. Consistencia. Estabilidad implícita. Método matricial de Newman, de energía. Métodos implícitos y semiemplícitos. Métodos espectrales. Elementos finitos. Ejemplos. Aplicaciones.

### Tips
En el plan viejo Métodos Numéricos se dicta cada 2 años, otra que hay que agendar. No sabemos como será a partir de la implementación del plan nuevo, además hay varias materias relacionadas con el modelado numérico. Si se dictan todas, habrá para elegir.


text: .ng-ckeditor { border: 0 none }


text:
class Record < ActiveRecord::Base
  belongs_to :assignment
end


text:
package com.opengamma.strata.finance.rate.swap;

import static com.opengamma.strata.basics.currency.Currency.GBP;
import static com.opengamma.strata.basics.date.HolidayCalendars.EUTA;
import static com.opengamma.strata.basics.index.FxIndices.ECB_EUR_GBP;
import static com.opengamma.strata.basics.index.FxIndices.ECB_EUR_USD;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.assertThrowsIllegalArg;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.testng.Assert.assertEquals;

import java.time.LocalDate;

import org.testng.annotations.Test;

import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.date.DaysAdjustment;
import com.opengamma.strata.basics.schedule.SchedulePeriod;

/**
 * Test.
 */
@Test
public class FxResetCalculationTest {

  private static final DaysAdjustment MINUS_TWO_DAYS = DaysAdjustment.ofBusinessDays(-2, EUTA);
  private static final DaysAdjustment MINUS_THREE_DAYS = DaysAdjustment.ofBusinessDays(-3, EUTA);
  private static final LocalDate DATE_2014_03_31 = date(2014, 3, 31);
  private static final LocalDate DATE_2014_06_30 = date(2014, 6, 30);

  public void test_builder() {
    FxResetCalculation test = FxResetCalculation.builder()
        .index(ECB_EUR_GBP)
        .referenceCurrency(GBP)
        .fixingDateOffset(MINUS_TWO_DAYS)
        .fixingRelativeTo(FxResetFixingRelativeTo.PERIOD_START)
        .build();
    assertEquals(test.getIndex(), ECB_EUR_GBP);
    assertEquals(test.getReferenceCurrency(), GBP);
    assertEquals(test.getFixingDateOffset(), MINUS_TWO_DAYS);
    assertEquals(test.getFixingRelativeTo(), FxResetFixingRelativeTo.PERIOD_START);
  }

  public void test_builder_defaultFixingRelativeTo() {
    FxResetCalculation test = FxResetCalculation.builder()
        .index(ECB_EUR_GBP)
        .referenceCurrency(GBP)
        .fixingDateOffset(MINUS_TWO_DAYS)
        .build();
    assertEquals(test.getIndex(), ECB_EUR_GBP);
    assertEquals(test.getReferenceCurrency(), GBP);
    assertEquals(test.getFixingDateOffset(), MINUS_TWO_DAYS);
    assertEquals(test.getFixingRelativeTo(), FxResetFixingRelativeTo.PERIOD_START);
  }

  public void test_invalidCurrency() {
    assertThrowsIllegalArg(() -> FxResetCalculation.builder()
        .index(ECB_EUR_USD)
        .referenceCurrency(GBP)
        .fixingDateOffset(MINUS_TWO_DAYS)
        .build());
  }

  //-------------------------------------------------------------------------
  public void test_applyToPeriod_beforeStart_weekend() {
    FxResetCalculation base = FxResetCalculation.builder()
        .index(ECB_EUR_GBP)
        .referenceCurrency(GBP)
        .fixingDateOffset(MINUS_TWO_DAYS)
        .build();
    FxReset test = base.applyToPeriod(SchedulePeriod.of(DATE_2014_03_31, DATE_2014_06_30));
    assertEquals(test, FxReset.of(ECB_EUR_GBP, GBP, date(2014, 3, 27)));
  }

  public void test_applyToPeriod_beforeEnd_weekend() {
    FxResetCalculation base = FxResetCalculation.builder()
        .index(ECB_EUR_GBP)
        .referenceCurrency(GBP)
        .fixingDateOffset(MINUS_TWO_DAYS)
        .fixingRelativeTo(FxResetFixingRelativeTo.PERIOD_END)
        .build();
    FxReset test = base.applyToPeriod(SchedulePeriod.of(DATE_2014_03_31, DATE_2014_06_30));
    assertEquals(test, FxReset.of(ECB_EUR_GBP, GBP, date(2014, 6, 26)));
  }

  public void test_applyToPeriod_beforeStart_threeDays() {
    FxResetCalculation base = FxResetCalculation.builder()
        .index(ECB_EUR_GBP)
        .referenceCurrency(GBP)
        .fixingDateOffset(MINUS_THREE_DAYS)
        .build();
    FxReset test = base.applyToPeriod(SchedulePeriod.of(DATE_2014_03_31, DATE_2014_06_30));
    assertEquals(test, FxReset.of(ECB_EUR_GBP, GBP, date(2014, 3, 26)));
  }

  //-------------------------------------------------------------------------
  public void coverage() {
    FxResetCalculation test = FxResetCalculation.builder()
        .index(ECB_EUR_GBP)
        .referenceCurrency(GBP)
        .fixingDateOffset(MINUS_TWO_DAYS)
        .build();
    coverImmutableBean(test);
    FxResetCalculation test2 = FxResetCalculation.builder()
        .index(ECB_EUR_USD)
        .referenceCurrency(Currency.EUR)
        .fixingDateOffset(MINUS_THREE_DAYS)
        .fixingRelativeTo(FxResetFixingRelativeTo.PERIOD_END)
        .build();
    coverBeanEquals(test, test2);
  }

  public void test_serialization() {
    FxResetCalculation test = FxResetCalculation.builder()
        .index(ECB_EUR_GBP)
        .referenceCurrency(GBP)
        .fixingDateOffset(MINUS_TWO_DAYS)
        .build();
    assertSerialization(test);
  }

}


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { ModulesNavComponent } from './modules-nav.component';

describe('Component: ModulesNav', () => {
  it('should create an instance', () => {
    const component = new ModulesNavComponent();
    expect(component).toBeTruthy();
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/progress_background" />

    <item android:id="@android:id/progress">
        <clip android:drawable="@drawable/progress_fill" />
    </item>
</layer-list>


text:
package com.helger.commons.mime;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Exception for errors that occur during MIME type parsing.<br>
 * Since v10 it is a checked exception
 *
 * @author Philip Helger
 */
public class MimeTypeParserException extends Exception
{
  public MimeTypeParserException (@Nonnull final String sMsg)
  {
    super (sMsg);
  }

  public MimeTypeParserException (@Nonnull final String sMsg, @Nullable final Throwable aCause)
  {
    super (sMsg, aCause);
  }
}


text:
package demo.dp.c.mediator;

/**
 *  An abstract Mediator
 */
public interface Mediator  {
    public void Register(Colleague c, String type);
    public void Changed(String type);
}


text:
#include "toonz/scriptengine.h"
#include "toonz/scriptbinding.h"
#include "toonz/scriptbinding_files.h"
#include "trenderer.h"
#include "toonz/toonzfolders.h"
#include <QScriptEngine>
#include <QScriptProgram>
#include <QFile>
#include <QTextStream>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QtGlobal>
#include <QApplication>

//=========================================================

namespace {

void sleep(unsigned long msec) {
  QMutex mutex;
  mutex.lock();
  QWaitCondition waitCondition;
  waitCondition.wait(&mutex, msec);
  mutex.unlock();
}

QString print(QScriptValue arg, bool addQuotes) {
  if (arg.isArray()) {
    QString s   = "[";
    quint32 len = arg.property(QLatin1String("length")).toUInt32();
    for (quint32 i = 0; i < len; ++i) {
      QScriptValue item = arg.property(i);
      if (i > 0) s += ",";
      s += print(item, addQuotes);
    }
    s += "]";
    return s;
  } else if (arg.isBool()) {
    return arg.toBool() ? "true" : "false";
  } else if (arg.isString()) {
    if (addQuotes)
      return "\"" + arg.toString() + "\"";
    else
      return arg.toString();
  } else
    return arg.toString();
}

QScriptValue printFunction(QScriptContext *context, QScriptEngine *engine) {
  QString result;
  for (int i = 0; i < context->argumentCount(); ++i) {
    if (i > 0) result.append(" ");
    result.append(print(context->argument(i), false));
  }
  QScriptValue calleeData = context->callee().data();
  ScriptEngine *se = qobject_cast<ScriptEngine *>(calleeData.toQObject());
  se->emitOutput(ScriptEngine::SimpleText, result);
  sleep(50);
  return se->voidValue();
}

QScriptValue warningFunction(QScriptContext *context, QScriptEngine *engine) {
  QString result;
  for (int i = 0; i < context->argumentCount(); ++i) {
    if (i > 0) result.append(" ");
    result.append(print(context->argument(i), false));
  }
  QScriptValue calleeData = context->callee().data();
  ScriptEngine *se = qobject_cast<ScriptEngine *>(calleeData.toQObject());
  se->emitOutput(ScriptEngine::Warning, result);
  sleep(50);
  return se->voidValue();
}

QScriptValue runFunction(QScriptContext *context, QScriptEngine *engine) {
  if (context->argumentCount() != 1) {
    return context->throwError("expected one parameter");
  }
  TFilePath fp;
  QScriptValue err =
      TScriptBinding::checkFilePath(context, context->argument(0), fp);
  if (err.isError()) return err;
  if (!fp.isAbsolute()) {
    fp = ToonzFolder::getLibraryFolder() + "scripts" + fp;
  }

  QString fpStr = QString::fromStdWString(fp.getWideString());
  QFile file(fpStr);
  if (!file.open(QIODevice::ReadOnly)) {
    return context->throwError("can't read file " + fpStr);
  }
  QTextStream in(&file);
  QString content = in.readAll();
  file.close();

  QScriptProgram program(content, fpStr);

  QScriptContext *parent = context->parentContext();
  if (parent != 0) {
    context->setActivationObject(context->parentContext()->activationObject());
    context->setThisObject(context->parentContext()->thisObject());
  }

  QScriptValue ret = engine->evaluate(program);

  if (engine->hasUncaughtException()) {
    int line = engine->uncaughtExceptionLineNumber();
    return context->throwError(QString("%1, at line %2 of %3")
                                   .arg(ret.toString())
                                   .arg(line)
                                   .arg(fpStr));
  }

  return ret;
}

/*
  QScriptValue glub(QScriptContext *context, QScriptEngine *engine)
  {
    QScriptValue global = engine->globalObject();
    QScriptValue te = global.property("_engine");
    ScriptEngine *se = qscriptvalue_cast<ScriptEngine*>(te);
    se->postCommand(context->argument(0));
    return 0;
  }
  */

}  // namespace

//=========================================================

class ScriptEngine::Executor final : public QThread {
  ScriptEngine *m_engine;
  QString m_cmd;

public:
  Executor(ScriptEngine *engine, const QString &cmd)
      : m_engine(engine), m_cmd(cmd) {}

  void run() override {
    m_engine->m_engine->collectGarbage();
    QScriptValue result = m_engine->m_engine->evaluate(m_cmd);
    if (result.isError()) {
      m_engine->emitOutput(ScriptEngine::SyntaxError, result.toString());
    } else if (result.isUndefined()) {
      m_engine->emitOutput(ScriptEngine::UndefinedEvaluationResult,
                           "undefined");
    } else {
      if (qscriptvalue_cast<TScriptBinding::Void *>(result)) {
      } else {
        m_engine->emitOutput(ScriptEngine::EvaluationResult,
                             print(result, true));
      }
    }
  }
};

class ScriptEngine::MainThreadEvaluationData {
public:
  QMutex m_mutex;
  QWaitCondition m_cond;
  QScriptValue m_fun, m_args, m_result;
};

//=========================================================

inline void defineFunction(ScriptEngine *se, const QString &name,
                           QScriptEngine::FunctionSignature f) {
  QScriptEngine *engine = se->getQScriptEngine();
  QScriptValue fObj     = engine->newFunction(f);
  fObj.setData(engine->newQObject(se));
  engine->globalObject().setProperty(name, fObj);
}

//=========================================================

ScriptEngine::ScriptEngine() : m_executor(0), m_engine(new QScriptEngine()) {
  // I must call TRenderer::initialize(), because a script could cause a
  // rendering driven by a working thread
  TRenderer::initialize();

  m_mainThreadEvaluationData = new MainThreadEvaluationData();
  QScriptValue global        = m_engine->globalObject();
  QScriptValue ctor;

  QScriptEngine &engine = *m_engine;

  defineFunction(this, "print", printFunction);
  defineFunction(this, "warning", warningFunction);
  defineFunction(this, "run", runFunction);

  /*
QScriptValue print = engine.newFunction(printFunction);
print.setData(engine.newQObject(this));
engine.globalObject().setProperty("print", print);

QScriptValue print = engine.newFunction(printFunction);
print.setData(engine.newQObject(this));
engine.globalObject().setProperty("print", print);

QScriptValue run = engine.newFunction(runFunction);
run.setData(engine.newQObject(this));
engine.globalObject().setProperty("run", run);

*/
  // QScriptValue g = engine.newFunction(glub);
  // g.setData(engine.newQObject(this));
  // engine.globalObject().setProperty("glub", g);

  // engine.globalObject().setProperty("_engine", engine.newQObject(this));

  m_voidValue  = new QScriptValue();
  *m_voidValue = engine.newQObject(new TScriptBinding::Void(),
                                   QScriptEngine::AutoOwnership);

  engine.globalObject().setProperty("void", *m_voidValue);

  TScriptBinding::bindAll(engine);
  bool ret = connect(this, SIGNAL(mainThreadEvaluationPosted()), this,
                     SLOT(onMainThreadEvaluationPosted()));
  assert(ret);
}

ScriptEngine::~ScriptEngine() {
  delete m_mainThreadEvaluationData;
  delete m_voidValue;
}

const QScriptValue &ScriptEngine::evaluateOnMainThread(
    const QScriptValue &fun, const QScriptValue &arguments) {
  MainThreadEvaluationData *d = m_mainThreadEvaluationData;
  QMutexLocker locker(&d->m_mutex);
  d->m_fun    = fun;
  d->m_args   = arguments;
  d->m_result = QScriptValue();
  emit mainThreadEvaluationPosted();
  d->m_cond.wait(&d->m_mutex);
  return d->m_result;
}

void ScriptEngine::onMainThreadEvaluationPosted() {
  Q_ASSERT(qApp && qApp->thread() == QThread::currentThread());
  MainThreadEvaluationData *d = m_mainThreadEvaluationData;
  QMutexLocker locker(&d->m_mutex);
  d->m_result = d->m_fun.call(d->m_fun, d->m_args);
  d->m_cond.wakeOne();
}

void ScriptEngine::evaluate(const QString &cmd) {
  if (m_executor) return;
  m_executor = new Executor(this, cmd);
  connect(m_executor, SIGNAL(finished()), this, SLOT(onTerminated()));
  m_executor->start();
}

bool ScriptEngine::isEvaluating() const { return m_engine->isEvaluating(); }

void ScriptEngine::interrupt() { m_engine->abortEvaluation(); }

void ScriptEngine::onTerminated() {
  emit evaluationDone();
  delete m_executor;
  m_executor = 0;
}


text:
import axios from 'axios-es6';
import { API_URL } from '../config';

export const apiAddProduct = product => async () => {
  try {
    const response = await axios.post(`${API_URL}/admin`, {
      ...product,
      published: true,
      action: 'addProduct',
    });
    if (response.status !== 200) {
      throw new Error('Can not add new product');
    }
    return response.data;
  } catch (error) {
    throw error;
  }
};

export const apiProducts = ({ product, action: productAction }) => async () => {
  try {
    const response = await axios.post(`${API_URL}/admin`, {
      product,
      productAction,
      action: 'products',
    });
    if (response.status !== 200) {
      throw new Error('Can get categories');
    }
    return response.data;
  } catch (error) {
    throw error;
  }
};

export const apiCategories = ({
  category,
  action: categoryAction,
}) => async () => {
  try {
    const response = await axios.post(`${API_URL}/admin`, {
      category,
      categoryAction,
      action: 'categories',
    });
    if (response.status !== 200) {
      throw new Error('Can get categories');
    }
    return response.data;
  } catch (error) {
    throw error;
  }
};

export const apiLoadImages = ({ email, token }) => async () => {
  try {
    const response = await axios.post(`${API_URL}/admin`, {
      email,
      token,
      action: 'getImages',
    });
    if (response.status !== 200) {
      throw new Error('Can not login');
    }
    return response.data;
  } catch (error) {
    throw error;
  }
};

export const apiLogin = ({ email, password }) => async () => {
  try {
    const response = await axios.post(`${API_URL}/admin`, {
      email,
      password,
      action: 'login',
    });
    if (response.status !== 200) {
      throw new Error('Can not login');
    }
    return response.data;
  } catch (error) {
    throw error;
  }
};


text:
package eu.socialsensor.sfc.input;

/**
 * @brief  The type of input data that is used for the
 * creation of input feeds
 * @author ailiakop
 * @email  ailiakop@iti.gr
 */
public enum DataInputType {

	CONFIG_FILE, MONGO_STORAGE , DYSCO, TXT_FILE
}


text:
"""
    lunaport_worker.tasks.hooks
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Functions to readct on some service events.
"""

import socket
import string
import json
import datetime as dt
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint

from .. import __version__
from utils import (
    celery,
    get_logger,
    lunaport_c1,
    worker_cfg
)
from .. clients import ConductorClient, GolemClient, BaseClinetError
from lunaport_client.exceptions import LunaportClientError

@celery.task
def on_user_add(login, src_case_id=66):
    """
    Create default case for new user.
    Args:
        login - str.
    """
    t_start = dt.datetime.now()
    log_ext = {
        'task_name': 'on_user_add',
        'wroker_ver': __version__
    }
    logger = get_logger(**log_ext)
    src_case = lunaport_c1.case_get(src_case_id)
    dst_case = {
        'name': '{}_sandbox'.format(login),
        'descr': src_case['descr'],
        'oracle': src_case['oracle'],
    }
    lunaport_c1.case_post(dst_case)

def main():
    on_user_add('gkomissarov1')

if __name__ == '__main__':
    main()


text:
<?php
/**
 * Created by PhpStorm.
 * User: funkill
 * Date: 07.07.15
 * Time: 18:29
 */

namespace Matcher\Types;

use Matcher\Exceptions\BadValueException;

class Object implements TypeInterface
{

    /**
     * @param mixed $match
     * @param array $handlers
     * @throws BadValueException
     * @return mixed
     */
    public function match($match, array $handlers)
    {
        $class = get_class($match);
        if (array_key_exists($class, $handlers)) {
            return $handlers[$class]($match);
        }

        foreach ($handlers as $pattern => $closure) {
            if ($match instanceof $pattern) {
                return $closure($match);
            }
        }

        throw new BadValueException('Value not found');
    }

}


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

import ghidra.framework.plugintool.PluginTool;
import ghidra.util.exception.DuplicateNameException;

/**
 *
 * Interface to define methods to manage running tools and tools in
 * the Tool Chest. The ToolManager also keeps track of the workspaces, and
 * what tools are running in workspace, as well as the connections among tools
 * across all workspaces.
 *
 *
 */
public interface ToolManager {

	/**
	 * The name to use for a new unnamed workspace; used by the Ghidra
	 * Project Window when the user creates a new workspace.
	 */
	public final static String DEFAULT_WORKSPACE_NAME = "Workspace";

	/**
	 * Property used when sending the change event when a workspace name is
	 * changed.
	 */
	public final static String WORKSPACE_NAME_PROPERTY = "WorkspaceName";

	/**
	 * Get the connection object for the producer and consumer tools
	 *
	 * @param producer tool that is producing the tool event
	 * @param consumer tool that is consuming the tool event
	 * @return the connection
	 */
	public ToolConnection getConnection(PluginTool producer, PluginTool consumer);

	/**
	 * Get a list of tools that produce at least one tool event.
	 *
	 * @return zero-length array if no tool produces any events
	 */
	public PluginTool[] getProducerTools();

	/**
	 * Get a list of tools that consume at least one tool event.
	 *
	 * @return zero-length array if no tool consumes any events
	 */
	public PluginTool[] getConsumerTools();

	/**
	 * Get a list running tools across all workspaces.
	 *
	 * @return zero-length array if there are no running tools.
	 */
	public PluginTool[] getRunningTools();

	/**
	 * Create a workspace with the given name.
	 *
	 * @param name name of workspace
	 * @return the workspace
	 * @throws DuplicateNameException if a workspace with this name already exists
	 */
	public Workspace createWorkspace(String name) throws DuplicateNameException;

	/**
	 * Remove the workspace.
	 *
	 * @param ws workspace to remove
	 */
	public void removeWorkspace(Workspace ws);

	/**
	 * Get list of known workspaces.
	 *
	 * @return an array of known workspaces
	 */
	public Workspace[] getWorkspaces();

	/**
	 * Get the active workspace
	 *
	 * @return the active workspace
	 */
	public Workspace getActiveWorkspace();

	/**
	 * Add the listener that will be notified when a tool is added
	 * or removed.
	 *
	 * @param listener workspace listener to add
	 */
	public void addWorkspaceChangeListener(WorkspaceChangeListener listener);

	/**
	 * Remove the workspace listener.
	 *
	 * @param l workspace listener to remove
	 */
	public void removeWorkspaceChangeListener(WorkspaceChangeListener l);

	/**
	 * Removes all connections involving tool
	 * @param tool tool for which to remove all connections
	 */
	public void disconnectTool(PluginTool tool);

	/**
	 * A configuration change was made to the tool; a plugin was added
	 * or removed.
	 * @param tool tool that changed
	 */
	public void toolChanged(PluginTool tool);
}


text:
<?php

	class EntityAccessException extends Exception {}

?>


text:
package com.opengamma.analytics.financial.model.tree;

import static org.testng.AssertJUnit.assertEquals;

import org.testng.annotations.Test;

import com.opengamma.util.test.TestGroup;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class RecombiningBinomialTreeTest {
  private static final Double[][] DATA = new Double[][] {new Double[] {1.}, new Double[] {2., 3.}, new Double[] {4., 5., 6.}, new Double[] {7., 8., 9., 10.}};
  private static final RecombiningBinomialTree<Double> TREE = new RecombiningBinomialTree<>(DATA);

  @Test
  public void test() {
    final RecombiningBinomialTree<Double> other = new RecombiningBinomialTree<>(DATA);
    assertEquals(TREE, other);
    for (int i = 0; i < DATA.length; i++) {
      assertEquals(DATA[i].length, TREE.getMaxNodesForStep(i));
    }
  }
}


text:
function [w, strength] = trismoothmp(p, s, G, beta)
% trismoothmp   Creates resolution-based Laplacian smoothing matrix.
%    [W, STRENGTH] = trismoothmp(P, S, G, BETA) creates a Laplacian
%    smoothing matrix that takes into account several characteristics
%    of a mesh of triangular dislocation elements, P, and constraining
%    data, including station displacement uncertainties, contained in
%    station structure S; the partial derivatives relating station
%    displacement to .  W represents the 2*nEl-by-2*nEl generic smoothing matrix,
%    while STRENGTH is a 2*nEl-by-2*nEl matrix defining the weighting
%    of the smoothing matrix to be used in an inversion.
%
%    The entries of WEIGHT are determined by:
%    - Inter-element distance (larger elements are smoothed less)
%    - Magnitude of the partial derivatives relating slip to displacement
%      (elements less well resolved are smoothed more)
%    - Uncertainty of constraining stations (noisier stations weight the
%      summed partial derivatives less)
%    - Mesh-wide smoothing factor, BETA.
%
%    The final value of WEIGHT is given as:
%    (1/DIST^2)*(MP/SS^2)*BETA
%    where DIST is the mean distance between an element and its neighbors,
%    MP is the sum of the rows of the partial derivatives relating station
%    displacement to each component of slip, SS is the station displacement
%    uncertainty, and BETA is the mesh-wide smoothing factor.
%

% Find neighbors
share = SideShare(p.v);

% Find intercentroid distances
dists = TriDistCalc(share, p.xc, p.yc, p.zc);

% Make the smoothing matrix
w = MakeTriSmoothAlt(share);

% Distance based smoothing
distScale = (sum(dists, 2)./sum(dists ~= 0, 2)).^2;

% Find sum of partials, weighted by uncertainties

% First trim verticals, if necessary
if size(G, 1) == 3*numel(s.eastVel)
   GU = G./repmat(stack3([s.eastSig.^2 s.northSig.^2 s.upSig.^2]), 1, size(G, 2));
   GUm = sqrt(GU(1:3:end, :).^2 + GU(2:3:end, :).^2 + GU(3:3:end, :).^2);
else
   GU = G./repmat(stack2([s.eastSig.^2 s.northSig.^2]), 1, size(G, 2));
   GUm = sqrt(GU(1:2:end, :).^2 + GU(2:2:end, :).^2);
end
sGUm = sum(GUm);

% Trim one slip component, if necessary
if size(w, 2) > size(G, 2)
   triS = [1:sum(p.nEl)]'; % All include strike
   triD = find(abs(p.dip - 90) > 1); % Find those with dip-slip
   triT = find(abs(p.dip - 90) <= 1); % Find those with tensile slip
   colkeep = setdiff(1:numel(p.v), [3*triD-0; 3*triT-1]);
   w = w(colkeep, :);
   w = w(:, colkeep);
end

if size(sGUm, 2) > size(G, 2)
   sGUm = sGUm(colkeep);
end

% Weight smoothing by distance, partials strength, and smoothing factor
strength = stack2(repmat(distScale(:), 1, 2)).*2.^sGUm(:);

% Smoothing factor
if numel(beta) == 1
   beta = repmat(beta, 2*sum(p.nEl), 1);
elseif numel(beta) == numel(p.nEl)
   pidx = zeros(sum(p.nEl), 1);
   pidx(1+[0; p.nEl(1:end-1)]) = 1;
   pidx = cumsum(pidx);
   beta = stack2(repmat(beta(pidx), 1, 2));
else
   error('BETA must be a scalar or a vector equal in size to p.nEl.')
end

% Full product
strength = beta./strength;


text:
#include <fcntl.h>
#include <gtest/gtest.h>
#include <sys/stat.h>
#include <sys/time.h>

#include "build/Protocol/Raft.pb.h"
#include "Core/Debug.h"
#include "Core/ProtoBuf.h"
#include "Core/StringUtil.h"
#include "Core/STLUtil.h"
#include "Server/Globals.h"
#include "Server/RaftConsensus.h"
#include "Server/StateMachine.h"
#include "Storage/FilesystemUtil.h"
#include "Storage/MemoryLog.h"
#include "Storage/SnapshotFile.h"

namespace LogCabin {
namespace Server {
extern bool stateMachineSuppressThreads;
extern uint32_t stateMachineChildSleepMs;
namespace {

class ServerStateMachineTest : public ::testing::Test {
  public:
    ServerStateMachineTest()
      : globals()
      , consensus()
      , stateMachine()
      , timeMocker()
    {
        RaftConsensusInternal::startThreads = false;
        consensus.reset(new RaftConsensus(globals));
        consensus->serverId = 1;
        consensus->log.reset(new Storage::MemoryLog());
        consensus->storageLayout.initTemporary();

        Storage::Log::Entry entry;
        entry.set_term(1);
        entry.set_type(Protocol::Raft::EntryType::CONFIGURATION);
        *entry.mutable_configuration() =
            Core::ProtoBuf::fromString<Protocol::Raft::Configuration>(
                "prev_configuration {"
                "    servers { server_id: 1, addresses: '127.0.0.1:5254' }"
                "}");
        consensus->init();
        consensus->append({&entry});
        consensus->startNewElection();
        consensus->configuration->localServer->lastSyncedIndex =
            consensus->log->getLastLogIndex();
        consensus->advanceCommitIndex();

        stateMachineSuppressThreads = true;
        stateMachine.reset(new StateMachine(consensus, globals.config,
                                            globals));
    }
    ~ServerStateMachineTest() {
        stateMachineSuppressThreads = false;
        stateMachineChildSleepMs = 0;
    }

    Core::Buffer
    serialize(const StateMachine::Command::Request& command) {
        Core::Buffer out;
        Core::ProtoBuf::serialize(command, out);
        return out;
    }

    Globals globals;
    std::shared_ptr<RaftConsensus> consensus;
    std::unique_ptr<StateMachine> stateMachine;
    Core::Time::SteadyClock::Mocker timeMocker;
};

TEST_F(ServerStateMachineTest, query_tree)
{
    StateMachine::Query::Request request;
    StateMachine::Query::Response response;
    auto& read = *request.mutable_tree()->mutable_read();
    read.set_path("/foo");
    EXPECT_TRUE(stateMachine->query(request, response));
    EXPECT_EQ(Protocol::Client::Status::LOOKUP_ERROR,
              response.tree().status());
}

TEST_F(ServerStateMachineTest, query_unknown)
{
    StateMachine::Query::Request request;
    StateMachine::Query::Response response;
    Core::Debug::setLogPolicy({{"", "ERROR"}});
    EXPECT_FALSE(stateMachine->query(request, response));
    EXPECT_FALSE(stateMachine->query(request, response));
}

struct WaitHelper {
    explicit WaitHelper(StateMachine& stateMachine)
        : stateMachine(stateMachine)
        , iter(0)
    {
    }
    void operator()() {
        ++iter;
        if (iter == 1) {
            EXPECT_EQ(0U, stateMachine.lastApplied);
            stateMachine.lastApplied = 2;
        } else if (iter == 2) {
            EXPECT_EQ(2U, stateMachine.lastApplied);
            stateMachine.lastApplied = 3;
        }
    }
    StateMachine& stateMachine;
    uint64_t iter;
};

TEST_F(ServerStateMachineTest, wait)
{
    WaitHelper helper(*stateMachine);
    stateMachine->entriesApplied.callback = std::ref(helper);
    stateMachine->wait(3);
    EXPECT_EQ(2U, helper.iter);
}

TEST_F(ServerStateMachineTest, waitForResponse_wait)
{
    StateMachine::Command::Request request;
    request.mutable_open_session();
    StateMachine::Command::Response response;
    WaitHelper helper(*stateMachine);
    stateMachine->entriesApplied.callback = std::ref(helper);
    EXPECT_TRUE(stateMachine->waitForResponse(3, request, response));
    EXPECT_EQ(2U, helper.iter);
}

TEST_F(ServerStateMachineTest, waitForResponse_tree)
{
    Core::Debug::setLogPolicy({{"Server/StateMachine.cc", "ERROR"}});
    stateMachine->sessions.insert({1, {}});
    StateMachine::Session& session = stateMachine->sessions.at(1);
    StateMachine::Command::Response r1;
    StateMachine::Command::Response r2;
    r1.mutable_tree()->set_status(Protocol::Client::Status::LOOKUP_ERROR);
    session.responses.insert({1, r1});

    StateMachine::Command::Request request;
    auto& exactlyOnce = *request.mutable_tree()->mutable_exactly_once();
    exactlyOnce.set_client_id(2);
    exactlyOnce.set_rpc_number(1);
    EXPECT_TRUE(stateMachine->waitForResponse(0, request, r2));
    EXPECT_EQ("tree { "
              "  status: SESSION_EXPIRED "
              "}", r2);

    exactlyOnce.set_client_id(1);
    exactlyOnce.set_rpc_number(2);
    EXPECT_TRUE(stateMachine->waitForResponse(0, request, r2));
    EXPECT_EQ("tree { "
              "  status: SESSION_EXPIRED "
              "}", r2);

    Core::Debug::setLogPolicy({{"", "WARNING"}});
    exactlyOnce.set_client_id(1);
    exactlyOnce.set_rpc_number(1);
    EXPECT_TRUE(stateMachine->waitForResponse(0, request, r2));
    EXPECT_EQ(r1, r2);
}

TEST_F(ServerStateMachineTest, waitForResponse_openSession)
{
    StateMachine::Command::Request request;
    request.mutable_open_session();
    StateMachine::Command::Response response;
    stateMachine->lastApplied = 3;
    EXPECT_TRUE(stateMachine->waitForResponse(3, request, response));
    EXPECT_EQ("open_session { "
              "  client_id: 3 "
              "}",
              response);
}

TEST_F(ServerStateMachineTest, waitForResponse_closeSession)
{
    stateMachine->lastApplied = 3;
    StateMachine::Command::Request request;
    request.mutable_close_session()->set_client_id(3);
    StateMachine::Command::Response response;
    stateMachine->versionHistory.insert({3, 2});
    EXPECT_FALSE(stateMachine->waitForResponse(2, request, response));
    EXPECT_FALSE(response.has_close_session());
    EXPECT_TRUE(stateMachine->waitForResponse(3, request, response));
    EXPECT_EQ("close_session { "
              "}",
              response);
}

TEST_F(ServerStateMachineTest, waitForResponse_advanceVersion)
{
    StateMachine::Command::Request request;
    request.mutable_advance_version()->
        set_requested_version(90);
    StateMachine::Command::Response response;
    stateMachine->lastApplied = 3;
    EXPECT_TRUE(stateMachine->waitForResponse(3, request, response));
    EXPECT_EQ("advance_version { "
              "  running_version: 1 "
              "}",
              response);
}

TEST_F(ServerStateMachineTest, waitForResponse_unknown)
{
    StateMachine::Command::Request request; // empty
    StateMachine::Command::Response response;
    stateMachine->lastApplied = 3;
    EXPECT_FALSE(stateMachine->waitForResponse(3, request, response));
    EXPECT_EQ("", response);
}

struct IsTakingSnapshotHelper {
    explicit IsTakingSnapshotHelper(StateMachine& stateMachine)
        : stateMachine(stateMachine)
        , count(0)
    {
    }
    void operator()() {
        std::function<void()> callback;
        std::swap(callback, stateMachine.mutex.callback);
        if (count == 1) {
            stateMachine.mutex.unlock();
            EXPECT_TRUE(stateMachine.isTakingSnapshot());
            stateMachine.mutex.lock();
        }
        std::swap(callback, stateMachine.mutex.callback);
        ++count;
    }
    StateMachine& stateMachine;
    uint64_t count;
};

TEST_F(ServerStateMachineTest, isTakingSnapshot)
{
    IsTakingSnapshotHelper helper(*stateMachine);
    EXPECT_FALSE(stateMachine->isTakingSnapshot());
    {
        std::unique_lock<Core::Mutex> lockGuard(stateMachine->mutex);
        stateMachine->mutex.callback = std::ref(helper);
        stateMachine->takeSnapshot(1, lockGuard);
    }
    EXPECT_FALSE(stateMachine->isTakingSnapshot());
}

struct StartTakingSnapshotHelper {
    explicit StartTakingSnapshotHelper(StateMachine& stateMachine)
        : stateMachine(stateMachine)
        , count(0)
    {
    }
    void operator()() {
        if (count == 0) {
            std::unique_lock<Core::Mutex> lockGuard(stateMachine.mutex);
            stateMachine.takeSnapshot(1, lockGuard);
        }
        ++count;

    }
    StateMachine& stateMachine;
    uint64_t count;
};

TEST_F(ServerStateMachineTest, startTakingSnapshot)
{
    EXPECT_FALSE(stateMachine->isSnapshotRequested);
    EXPECT_EQ(0U, stateMachine->snapshotSuggested.notificationCount);
    StartTakingSnapshotHelper helper(*stateMachine);
    stateMachine->snapshotStarted.callback = std::ref(helper);
    stateMachine->startTakingSnapshot();
    EXPECT_TRUE(stateMachine->isSnapshotRequested);
    EXPECT_EQ(1U, stateMachine->snapshotSuggested.notificationCount);
}

TEST_F(ServerStateMachineTest, startTakingSnapshot_alreadyStarted)
{
    stateMachine->childPid = 1000;
    stateMachine->startTakingSnapshot();
    EXPECT_FALSE(stateMachine->isSnapshotRequested);
    EXPECT_EQ(0U, stateMachine->snapshotSuggested.notificationCount);
    stateMachine->childPid = 0;
}

struct StopTakingSnapshotHelper {
    explicit StopTakingSnapshotHelper(StateMachine& stateMachine)
        : stateMachine(stateMachine)
        , count(0)
    {
    }
    void operator()() {
        if (count == 3) {
            int status = 0;
            EXPECT_EQ(stateMachine.childPid,
                      waitpid(stateMachine.childPid, &status, 0))
                << strerror(errno);
            EXPECT_TRUE(WIFSIGNALED(status));
            EXPECT_EQ(SIGTERM, WTERMSIG(status));
            stateMachine.childPid = 0;
        }
        ++count;
    }
    StateMachine& stateMachine;
    uint64_t count;
};

TEST_F(ServerStateMachineTest, stopTakingSnapshot)
{
    // start a snapshot
    errno = 0;
    pid_t pid = fork();
    ASSERT_NE(pid, -1) << strerror(errno); // error
    if (pid == 0) { // child
        stateMachine->globals.unblockAllSignals();
        while (true)
            usleep(5000);
    }
    // parent continues here
    stateMachine->childPid = pid;
    StopTakingSnapshotHelper helper(*stateMachine);
    stateMachine->snapshotCompleted.callback = std::ref(helper);
    stateMachine->stopTakingSnapshot();
    EXPECT_EQ(4U, helper.count);
}

TEST_F(ServerStateMachineTest, stopTakingSnapshot_noSnapshot)
{
    stateMachine->stopTakingSnapshot();
}

TEST_F(ServerStateMachineTest, getInhibit)
{
    // time is mocked
    EXPECT_EQ(std::chrono::nanoseconds::zero(),
              stateMachine->getInhibit());
    stateMachine->setInhibit(std::chrono::nanoseconds(0));
    EXPECT_EQ(std::chrono::nanoseconds::zero(),
              stateMachine->getInhibit());
    stateMachine->setInhibit(std::chrono::nanoseconds(1));
    EXPECT_EQ(std::chrono::nanoseconds(1),
              stateMachine->getInhibit());
    stateMachine->setInhibit(std::chrono::seconds(10000));
    EXPECT_EQ(std::chrono::seconds(10000),
              stateMachine->getInhibit());
}

TEST_F(ServerStateMachineTest, setInhibit)
{
    stateMachine->setInhibit(std::chrono::nanoseconds::zero());
    EXPECT_EQ(std::chrono::nanoseconds::zero(),
              stateMachine->getInhibit());
    stateMachine->setInhibit(std::chrono::nanoseconds(100));
    EXPECT_EQ(std::chrono::nanoseconds(100),
              stateMachine->getInhibit());
    stateMachine->setInhibit(std::chrono::nanoseconds(-100));
    EXPECT_EQ(std::chrono::nanoseconds::zero(),
              stateMachine->getInhibit());
    stateMachine->setInhibit(std::chrono::nanoseconds::max());
    EXPECT_LT(std::chrono::seconds(60L * 60L * 24L * 365L * 100L),
              stateMachine->getInhibit());
    EXPECT_LT(0U, stateMachine->snapshotSuggested.notificationCount);
}

TEST_F(ServerStateMachineTest, apply_tree)
{
    stateMachine->sessionTimeoutNanos = 1;
    RaftConsensus::Entry entry;
    entry.index = 6;
    entry.type = RaftConsensus::Entry::DATA;
    entry.clusterTime = 2;
    StateMachine::Command::Request command =
        Core::ProtoBuf::fromString<StateMachine::Command::Request>(
            "tree: { "
            " exactly_once: { "
            "  client_id: 39 "
            "  first_outstanding_rpc: 2 "
            "  rpc_number: 3 "
            " } "
            " make_directory { "
            "  path: '/a' "
            " } "
            "}");
    entry.command = serialize(command);
    std::vector<std::string> children;

    // session does not exist
    stateMachine->sessions.insert({1, {}});
    stateMachine->apply(entry);
    stateMachine->expireSessions(entry.clusterTime);
    stateMachine->tree.listDirectory("/", children);
    EXPECT_EQ((std::vector<std::string> {}), children);
    ASSERT_EQ(0U, stateMachine->sessions.size());

    // session exists and need to apply
    stateMachine->sessions.insert({1, {}});
    stateMachine->sessions.insert({39, {}});
    stateMachine->apply(entry);
    stateMachine->expireSessions(entry.clusterTime);
    stateMachine->tree.listDirectory("/", children);
    EXPECT_EQ((std::vector<std::string> {"a/"}), children);
    ASSERT_EQ(1U, stateMachine->sessions.size());
    EXPECT_EQ(2U, stateMachine->sessions.at(39).lastModified);

    // session exists and response exists
    stateMachine->sessions.insert({1, {}});
    stateMachine->tree.removeDirectory("/a");
    stateMachine->apply(entry);
    stateMachine->expireSessions(entry.clusterTime);
    stateMachine->tree.listDirectory("/", children);
    EXPECT_EQ((std::vector<std::string> {}), children);
    ASSERT_EQ(1U, stateMachine->sessions.size());
    EXPECT_EQ(2U, stateMachine->sessions.at(39).lastModified);

    // session exists but response discarded
    stateMachine->sessions.insert({1, {}});
    stateMachine->expireResponses(stateMachine->sessions.at(39), 4);
    stateMachine->apply(entry);
    stateMachine->expireSessions(entry.clusterTime);
    stateMachine->tree.listDirectory("/", children);
    EXPECT_EQ((std::vector<std::string> {}), children);
    ASSERT_EQ(1U, stateMachine->sessions.size());
    EXPECT_EQ(2U, stateMachine->sessions.at(39).lastModified);
}

TEST_F(ServerStateMachineTest, apply_openSession)
{
    stateMachine->sessionTimeoutNanos = 1;
    stateMachine->sessions.insert({1, {}});
    StateMachine::Command::Request command =
        Core::ProtoBuf::fromString<StateMachine::Command::Request>(
            "open_session: {}");
    RaftConsensus::Entry entry;
    entry.index = 6;
    entry.type = RaftConsensus::Entry::DATA;
    entry.command = serialize(command);
    entry.clusterTime = 2;

    stateMachine->apply(entry);
    stateMachine->expireSessions(entry.clusterTime);
    ASSERT_EQ((std::vector<uint64_t>{6U}),
              Core::STLUtil::sorted(
                  Core::STLUtil::getKeys(stateMachine->sessions)));
    StateMachine::Session& session = stateMachine->sessions.at(6);
    EXPECT_EQ(2U, session.lastModified);
    EXPECT_EQ(0U, session.firstOutstandingRPC);
    EXPECT_EQ(0U, session.responses.size());
}

TEST_F(ServerStateMachineTest, apply_closeSession)
{
    stateMachine->sessions.insert({2, {}});
    stateMachine->sessions.insert({3, {}});
    stateMachine->sessions.insert({4, {}});
    StateMachine::Command::Request command;
    command.mutable_close_session()->set_client_id(3);

    RaftConsensus::Entry entry;
    entry.index = 6;
    entry.type = RaftConsensus::Entry::DATA;
    entry.command = serialize(command);
    entry.clusterTime = 2;

    // first apply will have no effect (only warning) because state machine
    // version 1 does not support the CloseSession command
    Core::Debug::setLogPolicy({
        {"Server/StateMachine.cc", "ERROR"},
        {"", "WARNING"},
    });
    stateMachine->versionHistory.insert({4, 1});
    stateMachine->apply(entry);
    ASSERT_EQ((std::vector<uint64_t>{2, 3, 4}),
              Core::STLUtil::sorted(
                  Core::STLUtil::getKeys(stateMachine->sessions)));
    Core::Debug::setLogPolicy({
        {"", "WARNING"},
    });

    // second apply will work
    stateMachine->versionHistory.insert({5, 2});
    stateMachine->apply(entry);
    ASSERT_EQ((std::vector<uint64_t>{2, 4}),
              Core::STLUtil::sorted(
                  Core::STLUtil::getKeys(stateMachine->sessions)));

    // third apply will have no effect since the session was already closed
    stateMachine->apply(entry);
    ASSERT_EQ((std::vector<uint64_t>{2, 4}),
              Core::STLUtil::sorted(
                  Core::STLUtil::getKeys(stateMachine->sessions)));
}

TEST_F(ServerStateMachineTest, apply_advanceVersion)
{
    RaftConsensus::Entry entry;
    entry.index = 6;
    entry.type = RaftConsensus::Entry::DATA;
    entry.clusterTime = 2;

    // stay at version 1
    StateMachine::Command::Request command;
    command.mutable_advance_version()->set_requested_version(1);
    entry.command = serialize(command);
    stateMachine->apply(entry);
    stateMachine->apply(entry);
    stateMachine->apply(entry); // should silently succeed
    EXPECT_EQ(1U, stateMachine->getVersion(10000));

    // up to version 2
    command.mutable_advance_version()->set_requested_version(2);
    entry.command = serialize(command);
    stateMachine->apply(entry);
    EXPECT_EQ(2U, stateMachine->getVersion(10000));

    // downgrade to version 1 should give warning
    command.mutable_advance_version()->set_requested_version(1);
    entry.command = serialize(command);
    Core::Debug::setLogPolicy({
        {"Server/StateMachine.cc", "ERROR"},
        {"", "WARNING"},
    });
    stateMachine->apply(entry);
    Core::Debug::setLogPolicy({
        {"", "WARNING"},
    });
    EXPECT_EQ(2U, stateMachine->getVersion(10000));
}

TEST_F(ServerStateMachineTest, apply_unknown)
{
    StateMachine::Command::Request command =
        Core::ProtoBuf::fromString<StateMachine::Command::Request>("");
    RaftConsensus::Entry entry;
    entry.index = 6;
    entry.type = RaftConsensus::Entry::DATA;
    entry.clusterTime = 2;
    entry.command = serialize(command);
    // should be no-op, definitely shouldn't panic, expect warning
    Core::Debug::setLogPolicy({
        {"Server/StateMachine.cc", "ERROR"},
        {"", "WARNING"},
    });
    stateMachine->apply(entry);
    stateMachine->apply(entry);
}

// This tries to test the use of kill() to stop a snapshotting child and exit
// quickly.
TEST_F(ServerStateMachineTest, applyThreadMain_exiting_TimingSensitive)
{
    // instruct the child process to sleep for 10s
    stateMachineChildSleepMs = 10000;
    consensus->exit();
    {
        // applyThread won't be able to kill() yet due to mutex
        std::unique_lock<Core::Mutex> lockGuard(stateMachine->mutex);
        stateMachine->applyThread = std::thread(&StateMachine::applyThreadMain,
                                                stateMachine.get());
        struct timeval startTime;
        EXPECT_EQ(0, gettimeofday(&startTime, NULL));
        stateMachine->takeSnapshot(1, lockGuard);
        struct timeval endTime;
        EXPECT_EQ(0, gettimeofday(&endTime, NULL));
        uint64_t elapsedMillis = uint64_t(
            ((endTime.tv_sec   * 1000 * 1000 + endTime.tv_usec) -
             (startTime.tv_sec * 1000 * 1000 + startTime.tv_usec)) / 1000);
        EXPECT_GT(200U, elapsedMillis) <<
            "This test depends on timing, so failures are likely under "
            "heavy load, valgrind, etc.";
    }
    EXPECT_EQ(0U, consensus->lastSnapshotIndex);
}

TEST_F(ServerStateMachineTest, serializeSessions)
{
    StateMachine::Command::Response r1;
    r1.mutable_tree()->set_status(Protocol::Client::Status::LOOKUP_ERROR);

    StateMachine::Command::Response r2;
    r2.mutable_tree()->set_status(Protocol::Client::Status::TYPE_ERROR);

    StateMachine::Session s1;
    s1.lastModified = 6;
    s1.firstOutstandingRPC = 5;
    s1.responses.insert({5, r1});
    s1.responses.insert({7, r2});
    stateMachine->sessions.insert({4, s1});

    StateMachine::Session s2;
    s2.firstOutstandingRPC = 9;
    s2.responses.insert({10, r2});
    s2.responses.insert({11, r1});
    stateMachine->sessions.insert({80, s2});

    StateMachine::Session s3;
    s3.firstOutstandingRPC = 6;
    stateMachine->sessions.insert({91, s3});

    SnapshotStateMachine::Header header;
    stateMachine->serializeSessions(header);

    stateMachine->sessions.at(80).responses.at(10) = r1;
    stateMachine->sessions.at(80).firstOutstandingRPC = 10;

    stateMachine->loadSessions(header);

    EXPECT_EQ((std::vector<std::uint64_t>{4, 80, 91}),
              Core::STLUtil::sorted(
                Core::STLUtil::getKeys(stateMachine->sessions)));
    EXPECT_EQ(6U, stateMachine->sessions.at(4).lastModified);
    EXPECT_EQ(5U, stateMachine->sessions.at(4).firstOutstandingRPC);
    EXPECT_EQ(9U, stateMachine->sessions.at(80).firstOutstandingRPC);
    EXPECT_EQ(6U, stateMachine->sessions.at(91).firstOutstandingRPC);
    EXPECT_EQ((std::vector<std::uint64_t>{5, 7}),
              Core::STLUtil::sorted(
                Core::STLUtil::getKeys(
                    stateMachine->sessions.at(4).responses)));
    EXPECT_EQ(r1, stateMachine->sessions.at(4).responses.at(5));
    EXPECT_EQ(r2, stateMachine->sessions.at(4).responses.at(7));
    EXPECT_EQ((std::vector<std::uint64_t>{10, 11}),
              Core::STLUtil::sorted(
                Core::STLUtil::getKeys(
                    stateMachine->sessions.at(80).responses)));
    EXPECT_EQ(r2, stateMachine->sessions.at(80).responses.at(10));
    EXPECT_EQ(r1, stateMachine->sessions.at(80).responses.at(11));
    EXPECT_EQ((std::vector<std::uint64_t>{}),
              Core::STLUtil::sorted(
                Core::STLUtil::getKeys(
                    stateMachine->sessions.at(91).responses)));
}

TEST_F(ServerStateMachineTest, serializeVersionHistory)
{
    // since MAX_SUPPORTED_VERSION is 1, these values all have to be 1 for now
    stateMachine->versionHistory[1] = 1;
    stateMachine->versionHistory[3] = 1;
    SnapshotStateMachine::Header header;
    stateMachine->serializeVersionHistory(header);
    stateMachine->versionHistory.erase(3);
    stateMachine->versionHistory[5] = 1;
    stateMachine->loadVersionHistory(header);
    EXPECT_EQ((std::map<uint64_t, uint16_t> {
                   {0, 1},
                   {1, 1},
                   {3, 1},
               }),
              stateMachine->versionHistory);
}

TEST_F(ServerStateMachineTest, expireResponses)
{
    stateMachine->sessions.insert({1, {}});
    StateMachine::Session& session = stateMachine->sessions.at(1);
    session.responses.insert({1, {}});
    session.responses.insert({2, {}});
    session.responses.insert({4, {}});
    session.responses.insert({5, {}});
    stateMachine->expireResponses(session, 4);
    stateMachine->expireResponses(session, 3);
    EXPECT_EQ(4U, session.firstOutstandingRPC);
    EXPECT_EQ((std::vector<uint64_t>{4U, 5U}),
              Core::STLUtil::sorted(
                  Core::STLUtil::getKeys(session.responses)));
}

TEST_F(ServerStateMachineTest, expireSessions)
{
    stateMachine->sessionTimeoutNanos = 1;
    stateMachine->sessions.insert({1, {}});
    stateMachine->sessions.at(1).lastModified = 100;
    stateMachine->sessions.insert({2, {}});
    stateMachine->sessions.at(2).lastModified = 400;
    stateMachine->sessions.insert({3, {}});
    stateMachine->sessions.at(3).lastModified = 200;
    stateMachine->sessions.insert({4, {}});
    stateMachine->sessions.at(4).lastModified = 201;
    stateMachine->sessions.insert({5, {}});
    stateMachine->expireSessions(202);
    EXPECT_EQ((std::vector<uint64_t>{2U, 4U}),
              Core::STLUtil::sorted(
                  Core::STLUtil::getKeys(stateMachine->sessions)));
}

TEST_F(ServerStateMachineTest, getVersion)
{
    EXPECT_EQ(1U, stateMachine->getVersion(0));
    EXPECT_EQ(1U, stateMachine->getVersion(1));
    EXPECT_EQ(1U, stateMachine->getVersion(10));

    stateMachine->versionHistory[2] = 50;
    stateMachine->versionHistory[3] = 60;
    stateMachine->versionHistory[6] = 90;

    EXPECT_EQ(1U, stateMachine->getVersion(0));
    EXPECT_EQ(1U, stateMachine->getVersion(1));
    EXPECT_EQ(50U, stateMachine->getVersion(2));
    EXPECT_EQ(60U, stateMachine->getVersion(3));
    EXPECT_EQ(60U, stateMachine->getVersion(4));
    EXPECT_EQ(60U, stateMachine->getVersion(5));
    EXPECT_EQ(90U, stateMachine->getVersion(6));
    EXPECT_EQ(90U, stateMachine->getVersion(7));
}

// loadSessions tested along with serializeSessions above

// loadSnapshot normal path tested along with takeSnapshot below

TEST_F(ServerStateMachineTest, loadSnapshot_empty)
{
    std::unique_ptr<Storage::SnapshotFile::Writer> writer =
        consensus->beginSnapshot(1);
    writer->save();
    consensus->readSnapshot();
    EXPECT_DEATH(stateMachine->loadSnapshot(*consensus->snapshotReader),
                 "no format version field");
}

TEST_F(ServerStateMachineTest, loadSnapshot_unknownFormatVersion)
{
    std::unique_ptr<Storage::SnapshotFile::Writer> writer =
        consensus->beginSnapshot(1);
    uint8_t formatVersion = 2;
    writer->writeRaw(&formatVersion, sizeof(formatVersion));
    writer->save();
    consensus->readSnapshot();
    EXPECT_DEATH(stateMachine->loadSnapshot(*consensus->snapshotReader),
                 "Snapshot contents format version read was 2, but this code "
                 "can only read version 1");
}

// loadVersionHistory normal path tested along with serializeVersionHistory
// above

TEST_F(ServerStateMachineTest, loadVersionHistory_unknownVersion)
{
    stateMachine->versionHistory.insert({1, 3});
    SnapshotStateMachine::Header header;
    stateMachine->serializeVersionHistory(header);
    EXPECT_DEATH(stateMachine->loadVersionHistory(header),
                 "State machine version read from snapshot was 3, but this "
                 "code only supports 1 through 2");
}

struct SnapshotThreadMainHelper {
    explicit SnapshotThreadMainHelper(StateMachine& stateMachine)
        : stateMachine(stateMachine)
        , count(0)
    {
    }
    void operator()() {
        // append a new entry every iteration so that shouldTakeSnapshot can
        // return true
        Storage::Log::Entry entry;
        entry.set_term(1);
        entry.set_type(Protocol::Raft::EntryType::CONFIGURATION);
        *entry.mutable_configuration() =
            Core::ProtoBuf::fromString<Protocol::Raft::Configuration>(
                "prev_configuration {"
                "    servers { server_id: 1, addresses: '127.0.0.1:5254' }"
                "}");
        stateMachine.consensus->append({&entry});
        stateMachine.consensus->commitIndex =
            stateMachine.consensus->log->getLastLogIndex();
        stateMachine.lastApplied = stateMachine.consensus->commitIndex;

        if (count == 0) {
            // not inhibited, shouldn't take snapshot, no snapshot requested:
            // slept
            EXPECT_EQ(0U, stateMachine.numSnapshotsAttempted);

            stateMachine.setInhibit(std::chrono::nanoseconds(1));
            stateMachine.isSnapshotRequested = true;
            EXPECT_FALSE(
                    stateMachine.shouldTakeSnapshot(stateMachine.lastApplied));
        } else if (count == 1) {
            // inhibited and snapshot requested:
            // took snapshot
            EXPECT_EQ(1U, stateMachine.numSnapshotsAttempted);
            EXPECT_FALSE(stateMachine.isSnapshotRequested);

            EXPECT_FALSE(
                    stateMachine.shouldTakeSnapshot(stateMachine.lastApplied));
            stateMachine.snapshotMinLogSize = 1U;
            stateMachine.snapshotRatio = 0U;
            EXPECT_TRUE(
                    stateMachine.shouldTakeSnapshot(stateMachine.lastApplied));
        } else if (count == 2) {
            // inhibited, should take snapshot, and no snapshot requested:
            // slept
            EXPECT_EQ(1U, stateMachine.numSnapshotsAttempted);

            EXPECT_TRUE(
                    stateMachine.shouldTakeSnapshot(stateMachine.lastApplied));
            stateMachine.setInhibit(std::chrono::nanoseconds(0));
        } else if (count == 3) {
            // not inhibited, should take snapshot, and no snapshot requested:
            // took snapshot
            EXPECT_EQ(2U, stateMachine.numSnapshotsAttempted);

            stateMachine.exiting = true;
        }
        ++count;

    }
    StateMachine& stateMachine;
    uint64_t count;
};

TEST_F(ServerStateMachineTest, snapshotThreadMain)
{
    // time is mocked
    stateMachine->lastApplied = 1;
    SnapshotThreadMainHelper helper(*stateMachine);
    stateMachine->snapshotSuggested.callback = std::ref(helper);
    stateMachine->snapshotThreadMain();
    EXPECT_EQ(4U, helper.count);
}

struct SnapshotWatchdogThreadMainHelper {
    explicit SnapshotWatchdogThreadMainHelper(StateMachine& stateMachine)
        : count(0)
        , stateMachine(stateMachine)
    {
    }
    void operator()() {
        if (count == 0) {
            // no snapshot, do nothing
        } else if (count == 1) {
            // no snapshot still
            // start a snapshot
            errno = 0;
            pid_t pid = fork();
            ASSERT_NE(pid, -1) << strerror(errno); // error
            if (pid == 0) { // child
                stateMachine.globals.unblockAllSignals();
                while (true)
                    usleep(5000);
            }
            // parent continues here
            stateMachine.childPid = pid;
            stateMachine.writer.reset(
                new Storage::SnapshotFile::Writer(
                    stateMachine.consensus->storageLayout));
            stateMachine.numSnapshotsAttempted = 1;
        } else if (count == 2) {
            // should be tracking now
            Core::Time::SteadyClock::mockValue +=
                std::chrono::seconds(8);
        } else if (count == 3) {
            // spurious wakeup
            // make some progress
            *stateMachine.writer->sharedBytesWritten.value += 1;
            Core::Time::SteadyClock::mockValue +=
                std::chrono::seconds(3);
        } else if (count == 4) {
            // check passed
            // now don't make progress
            Core::Time::SteadyClock::mockValue +=
                std::chrono::seconds(11);
            int status = 0;
            EXPECT_EQ(0, // still running
                      waitpid(stateMachine.childPid, &status, WNOHANG))
                << status << strerror(errno);
            Core::Debug::setLogPolicy({
                {"Server/StateMachine.cc", "SILENT"},
                {"", "WARNING"},
            });
        } else if (count == 5) {
            Core::Debug::setLogPolicy({
                {"", "WARNING"},
            });
            // child should be receiving SIGKILL
            int status = 0;
            EXPECT_EQ(stateMachine.childPid,
                      waitpid(stateMachine.childPid, &status, 0))
                << strerror(errno);
            EXPECT_TRUE(WIFSIGNALED(status));
            EXPECT_EQ(SIGKILL, WTERMSIG(status));
            stateMachine.childPid = 0;
            stateMachine.writer->discard();
            stateMachine.writer.reset();
            stateMachine.numSnapshotsFailed = 1;
        } else if (count == 6) {
            // no more child process
            stateMachine.exiting = true;
        }
        ++count;

    }
    uint64_t count;
    StateMachine& stateMachine;
};

TEST_F(ServerStateMachineTest, snapshotWatchdogThreadMain)
{
    Core::Time::SteadyClock::mockValue =
        Core::Time::SteadyClock::time_point();
    SnapshotWatchdogThreadMainHelper helper(*stateMachine);
    stateMachine->snapshotStarted.callback = std::ref(helper);
    stateMachine->snapshotWatchdogThreadMain();
    EXPECT_EQ(7U, helper.count);
}

TEST_F(ServerStateMachineTest, takeSnapshot)
{
    EXPECT_EQ(0U, consensus->lastSnapshotIndex);
    stateMachine->tree.makeDirectory("/foo");
    stateMachine->sessions.insert({4, {}});
    {
        std::unique_lock<Core::Mutex> lockGuard(stateMachine->mutex);
        stateMachine->takeSnapshot(1, lockGuard);
    }
    stateMachine->tree.removeDirectory("/foo");
    stateMachine->sessions.clear();
    EXPECT_EQ(1U, consensus->lastSnapshotIndex);
    consensus->discardUnneededEntries();
    consensus->readSnapshot();
    stateMachine->loadSnapshot(*consensus->snapshotReader);
    std::vector<std::string> children;
    stateMachine->tree.listDirectory("/", children);
    EXPECT_EQ((std::vector<std::string>{"foo/"}), children);
    EXPECT_EQ((std::vector<std::uint64_t>{4}),
              Core::STLUtil::sorted(
                  Core::STLUtil::getKeys(stateMachine->sessions)));
}

} // namespace LogCabin::Server::<anonymous>
} // namespace LogCabin::Server
} // namespace LogCabin


text:
<?php

namespace Laradic\Generators\Laravel\EloquentModel\Processor;

use Laradic\Generators\Core\Elements\PropertyElement;
use Laradic\Generators\Core\Elements\DocBlockElement;
use Laradic\Generators\Laravel\EloquentModel\Config;
use Laradic\Generators\Laravel\EloquentModel\Model\EloquentElement;

/**
 * Class CustomPropertyProcessor
 * @package Krlove\EloquentModelGenerator\Processor
 */
class CustomPropertyProcessor implements ProcessorInterface
{
    /**
     * @inheritdoc
     */
    public function process(EloquentElement $model, Config $config)
    {
        if ($config->get('no_timestamps') === true) {
            $pNoTimestamps = new PropertyElement('timestamps', 'public', false);
            $pNoTimestamps->setDocBlock(
                new DocBlockElement('Indicates if the Element should be timestamped.', '', '@var bool')
            );
            $model->addProperty($pNoTimestamps);
        }

        if ($config->has('date_format')) {
            $pDateFormat = new PropertyElement('dateFormat', 'protected', $config->get('date_format'));
            $pDateFormat->setDocBlock(
                new DocBlockElement('The storage format of the Element\'s date columns.', '', '@var string')
            );
            $model->addProperty($pDateFormat);
        }

        if ($config->has('connection')) {
            $pConnection = new PropertyElement('connection', 'protected', $config->get('connection'));
            $pConnection->setDocBlock(
                new DocBlockElement('The connection name for the Element.', '', '@var string')
            );
            $model->addProperty($pConnection);
        }
    }

    /**
     * @inheritdoc
     */
    public function getPriority()
    {
        return 5;
    }
}