text:
package com.intellij.mock;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.editor.event.*;
import org.jetbrains.annotations.NotNull;

public class MockEditorEventMulticaster implements EditorEventMulticaster {
  public MockEditorEventMulticaster() {
  }

  @Override
  public void addDocumentListener(@NotNull DocumentListener listener) {
  }

  @Override
  public void addDocumentListener(@NotNull DocumentListener listener, @NotNull Disposable parentDisposable) {
      }

  @Override
  public void removeDocumentListener(@NotNull DocumentListener listener) {
  }

  @Override
  public void addEditorMouseListener(@NotNull EditorMouseListener listener) {
  }

  @Override
  public void addEditorMouseListener(@NotNull final EditorMouseListener listener, @NotNull final Disposable parentDisposable) {
  }

  @Override
  public void removeEditorMouseListener(@NotNull EditorMouseListener listener) {
  }

  @Override
  public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) {
  }

  @Override
  public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener, @NotNull Disposable parentDisposable) {
  }

  @Override
  public void removeEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) {
  }

  @Override
  public void addCaretListener(@NotNull CaretListener listener) {
  }

  @Override
  public void addCaretListener(@NotNull CaretListener listener, @NotNull Disposable parentDisposable) {
  }

  @Override
  public void removeCaretListener(@NotNull CaretListener listener) {
  }

  @Override
  public void addSelectionListener(@NotNull SelectionListener listener) {
  }

  @Override
  public void addSelectionListener(@NotNull SelectionListener listener, @NotNull Disposable parentDisposable) {
  }

  @Override
  public void removeSelectionListener(@NotNull SelectionListener listener) {
  }

  @Override
  public void addVisibleAreaListener(@NotNull VisibleAreaListener listener) {
  }

  @Override
  public void addVisibleAreaListener(@NotNull VisibleAreaListener listener, @NotNull Disposable parent) {

  }

  @Override
  public void removeVisibleAreaListener(@NotNull VisibleAreaListener listener) {
  }

}


text:
<?php

namespace app\modules\post\modules\admin;

class Module extends \yii\base\Module
{
    public $controllerNamespace = 'app\modules\post\modules\admin\controllers';

    public $theme = 'admin';

    public function init()
    {
        parent::init();
        $this->layoutPath = \Yii::getAlias('@app/themes/admin/views/layouts/');
        $this->layout = 'main';
//        \Yii::$app->view->theme->baseUrl = '@web/themes/admin';
        // custom initialization code goes here
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace NQuery.Iterators
{
    internal sealed class ConstantIterator : Iterator
    {
        private readonly EmptyRowBuffer _rowBuffer = new();
        private bool _isEof;

        public override RowBuffer RowBuffer
        {
            get { return _rowBuffer; }
        }

        public override void Open()
        {
            _isEof = false;
        }

        public override void Dispose()
        {
        }

        public override bool Read()
        {
            if (_isEof)
                return false;

            _isEof = true;
            return true;
        }
    }
}


text:
<%!
  from django.core.urlresolvers import reverse
  from django.utils.translation import ugettext as _
  from edxmako.shortcuts import marketing_link
  from django.utils.timezone import now
%>

         © ${now().strftime('%Y')} ${_('Stanford Medicine')}

        ${_('Powered by {platform_name}').format(platform_name='Open edX')}

SU Home

Maps & Directions

Search Stanford

Terms of Use

Copyright Complaints

© Stanford University,  Stanford, California 94305


text:
// Autogenerated by hob
window.cls || (window.cls = {});
cls.ResourceManager || (cls.ResourceManager = {});
cls.ResourceManager["1.0"] || (cls.ResourceManager["1.0"] = {});

cls.ResourceManager["1.0"].ResponseFinished = function(arr)
{
  this.requestID = arr[0];
  this.resourceID = arr[1];
  this.time = arr[2];
  this.contentLength = arr[3];
  this.data = arr[4] ? new cls.ResourceManager["1.0"].ResourceData(arr[4]) : null;
};

cls.ResourceManager["1.0"].ResourceData = function(arr)
{
  this.resourceID = arr[0];
  this.url = arr[1];
  /**
    * The used mime type. This may be different from the mime type
    * advertised in the HTTP headers.
    */
  this.mimeType = arr[2];
  /**
    * Original character encoding (if applicable).
    */
  this.characterEncoding = arr[3];
  /**
    * Content-Length, as advertised by HTTP headers.
    */
  this.contentLength = arr[4];
  this.content = arr[5] ? new cls.ResourceManager["1.0"].Content(arr[5]) : null;
};

cls.ResourceManager["1.0"].Content = function(arr)
{
  /**
    * If BYTES or DATA_URI was chosen as the transport mode, this field
    * contains the size of the data. (If, in addition, decoding was enabled,
    * the field contains the size of the decoded data).
    *
    * If STRING was chosen as the transport mode, this field contains the
    * string length (regardless of encoding), i.e. the number of characters,
    * not including zero terminator.
    */
  this.length = arr[0];
  /**
    * The (original) character encoding of the data (if applicable).
    */
  this.characterEncoding = arr[1];
  /**
    * This field contains the data if BYTES was chosen as the transport
    * mode. If other modes were chosen, this field is not set.
    *
    * @see ContentMode::Transport
    */
  this.byteData = arr[2];
  /**
    * This field contains the data if either STRING or DATA_URI were chosen
    * as transport mode. If some other mode was chosen, this field is not set.
    *
    * @ee ContentMode::Transport
    */
  this.stringData = arr[3];
};


text:
#ifndef USLISTENERFUNCTORS_P_H
#define USLISTENERFUNCTORS_P_H

#include <usServiceEvent.h>
#include <usModuleEvent.h>

#include <algorithm>
#include <cstring>

#ifdef US_HAVE_STD_FUNCTION
  #ifdef US_HAVE_FUNCTIONAL_H
    #include <functional>
  #elif defined(US_HAVE_TR1_FUNCTIONAL_H)
    #include <tr1/functional>
  #endif
  #define US_FUNCTION_TYPE std::function
#elif defined(US_HAVE_TR1_FUNCTION)
  #ifdef US_HAVE_TR1_FUNCTIONAL_H
    #include <tr1/functional>
  #elif defined(US_HAVE_FUNCTIONAL_H)
    #include <functional>
  #endif
  #define US_FUNCTION_TYPE std::tr1::function
#endif

#define US_MODULE_LISTENER_FUNCTOR US_FUNCTION_TYPE<void(const US_PREPEND_NAMESPACE(ModuleEvent)&)>
#define US_SERVICE_LISTENER_FUNCTOR US_FUNCTION_TYPE<void(const US_PREPEND_NAMESPACE(ServiceEvent)&)>

US_BEGIN_NAMESPACE
  template<class X>
  US_MODULE_LISTENER_FUNCTOR ModuleListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ModuleEvent)))
  { return std::bind(std::mem_fn(memFn), x, std::placeholders::_1); }

  struct ModuleListenerCompare
  {
    bool operator()(const std::pair<US_MODULE_LISTENER_FUNCTOR, void*>& p1,
                    const std::pair<US_MODULE_LISTENER_FUNCTOR, void*>& p2) const
    {
      return p1.second == p2.second &&
             p1.first.target<void(const US_PREPEND_NAMESPACE(ModuleEvent)&)>() == p2.first.target<void(const US_PREPEND_NAMESPACE(ModuleEvent)&)>();
    }
  };

  template<class X>
  US_SERVICE_LISTENER_FUNCTOR ServiceListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ServiceEvent)))
  { return std::bind(std::mem_fn(memFn), x, std::placeholders::_1); }

  struct ServiceListenerCompare
  {
    bool operator()(const US_SERVICE_LISTENER_FUNCTOR& f1,
                    const US_SERVICE_LISTENER_FUNCTOR& f2) const
    {
      return f1.target<void(const US_PREPEND_NAMESPACE(ServiceEvent)&)>() == f2.target<void(const US_PREPEND_NAMESPACE(ServiceEvent)&)>();
    }
  };
US_END_NAMESPACE

US_HASH_FUNCTION_NAMESPACE_BEGIN
US_HASH_FUNCTION_BEGIN(US_SERVICE_LISTENER_FUNCTOR)
  void(*targetFunc)(const US_PREPEND_NAMESPACE(ServiceEvent)&) = arg.target<void(const US_PREPEND_NAMESPACE(ServiceEvent)&)>();
  void* targetPtr = nullptr;
  std::memcpy(&targetPtr, &targetFunc, sizeof(void*));
  return US_HASH_FUNCTION(void*, targetPtr);
US_HASH_FUNCTION_END
US_HASH_FUNCTION_NAMESPACE_END

#endif // USLISTENERFUNCTORS_P_H


text:
// Copyright 2014 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cgotest

/*
#include <complex.h>

complex float complexFloatSquared(complex float a) { return a*a; }
complex double complexDoubleSquared(complex double a) { return a*a; }
*/
import "C"

import "testing"

func test8694(t *testing.T) {
	// Really just testing that this compiles, but check answer anyway.
	x := complex64(2 + 3i)
	x2 := x * x
	cx2 := C.complexFloatSquared(x)
	if cx2 != x2 {
		t.Errorf("C.complexFloatSquared(%v) = %v, want %v", x, cx2, x2)
	}

	y := complex128(2 + 3i)
	y2 := y * y
	cy2 := C.complexDoubleSquared(y)
	if cy2 != y2 {
		t.Errorf("C.complexDoubleSquared(%v) = %v, want %v", y, cy2, y2)
	}
}


text:
import RCPU.assembler.assembler as assembler
from RCPU.assembler.preprocessor import preprocess
import argparse
import struct
import logging

from pprint import pformat

def pretty_log_debug(stage, msg, *args, **kwargs):
    logging.debug(stage + '\n' + pformat(msg), *args, **kwargs)

def assemble(lines):
    data, text = preprocess(lines)
    resourcetable = assembler.create_resourcetable(data)
    # Replace entrypoint with a JMP instruction to that label
    text = assembler.replace_entrypoint(text)
    pretty_log_debug('preprocessed', {
        'resourcetable': resourcetable,
        'text': text,
        'data': data
    })
    # Expand text section: turns all pseudo-instructions into real instructions
    text = assembler.expand_all(text)
    # Replace labels with their locations in the binary
    text = assembler.replace_labels(text)
    # Insert references to resourcetable
    text, datasection = assembler.generate_datasection(text, resourcetable)
    # Replace symbolic arguments
    text = assembler.eval_expressions(text)
    logging.info("Expanded size: {}".format(len(text)))
    pretty_log_debug('expanded', {
        'text': text,
    })
    # Translate instructions into machine code
    binary = assembler.translate_all(text)
    binary += datasection
    return binary

def pack_binary(binary):
    return [struct.pack('>H', instruction) for instruction in binary]

def main():  # pragma: no cover
    parser = argparse.ArgumentParser(description='Assemble some assembly code.')

    parser.add_argument('infile', type=argparse.FileType('r'))
    parser.add_argument('outfile', type=argparse.FileType('wb'))
    parser.add_argument('--debug', action='store_const', const=logging.DEBUG,
                        default=logging.INFO, dest='loglevel')
    parser.add_argument('--rom', action='store_true', help='Create ROM file for RCPU_FPGA')
    args = parser.parse_args()

    logging.basicConfig(level=args.loglevel, format='%(levelname)s: %(message)s')
    lines = args.infile.readlines()
    assembled = assemble(lines)
    if args.rom:
        if len(assembled) > 4096:
            logging.warning("Assembled code too big for ROM file")
        for word in assembled[:4096]:
            args.outfile.write(("%04x\n" % word).encode('ascii'))
    else:
        packed = pack_binary(assembled)
        for instruction in packed:
            args.outfile.write(instruction)

if __name__ == '__main__':
    main()


text:
forcing module
--------------

.. automodule:: ezclimate.forcing
    :members:
    :undoc-members:
    :show-inheritance:


text:
export const DocumentPicker: {
    show(options: Options, callback: (error: Error, result: Result) => void): void;
};

export const DocumentPickerUtil: {
    allFiles(): string;
    pdf(): string;
    audio(): string;
    plainText(): string;
    video(): string;
    images(): string;
};

export interface Options {
    top?: number;
    left?: number;
    filetype: string[];
}

export interface Result {
    uri: string;
    type: string;
    fileName: string;
    fileSize: number;
}


text:
<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="drawer_item_padding_left">32dp</dimen>
	<dimen name="drawer_item_compound_drawable_padding">10dp</dimen>
</resources>


text:
package io.jenetics.example;

import static java.lang.Math.pow;
import static io.jenetics.internal.math.Randoms.indexes;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

import io.jenetics.AbstractAlterer;
import io.jenetics.AltererResult;
import io.jenetics.Chromosome;
import io.jenetics.DoubleChromosome;
import io.jenetics.DoubleGene;
import io.jenetics.Gene;
import io.jenetics.Genotype;
import io.jenetics.Phenotype;
import io.jenetics.engine.Engine;
import io.jenetics.engine.EvolutionResult;
import io.jenetics.internal.util.IntRef;
import io.jenetics.util.Factory;
import io.jenetics.util.ISeq;
import io.jenetics.util.MSeq;
import io.jenetics.util.RandomRegistry;
import io.jenetics.util.Seq;

public class DynamicGenotype {

	// Explicit Genotype factory instead of Genotype templates.
	private static final Factory<Genotype<DoubleGene>> ENCODING = () -> {
		final var random = RandomRegistry.random();
		return Genotype.of(
			// Vary the chromosome count between 10 and 20.
			IntStream.range(0, random.nextInt(10) + 10)
				// Vary the chromosome length between 10 and 20.
				.mapToObj(i -> DoubleChromosome.of(0, 10, random.nextInt(10) + 10))
				.collect(ISeq.toISeq())
		);
	};

	private static double fitness(final Genotype<DoubleGene> gt) {
		// Calculate fitness from "dynamic" Genotype.
		System.out.println("Gene count: " + gt.geneCount());
		return 0;
	}

	// The special mutator also variates the chromosome/genotype length.
	private static final class DynamicMutator<
		G extends Gene<?, G>,
		C extends Comparable<? super C>
	>
		extends AbstractAlterer<G, C>
	{
		DynamicMutator(double probability) {
			super(probability);
		}

		@Override
		public AltererResult<G, C> alter(
			final Seq<Phenotype<G, C>> population,
			final long generation
		) {
			final double p = pow(_probability, 1.0/3.0);
			final IntRef alterations = new IntRef(0);
			final MSeq<Phenotype<G, C>> pop = MSeq.of(population);

			indexes(RandomRegistry.random(), pop.size(), p).forEach(i -> {
				final Phenotype<G, C> pt = pop.get(i);

				final Genotype<G> gt = pt.genotype();
				final Genotype<G> mgt = mutate(gt, p, alterations);

				final Phenotype<G, C> mpt = Phenotype.of(mgt, generation);
				pop.set(i, mpt);
			});

			return new AltererResult<>(pop.toISeq(), alterations.value);
		}

		private Genotype<G> mutate(
			final Genotype<G> genotype,
			final double p,
			final IntRef alterations
		) {
			final List<Chromosome<G>> chromosomes =
				new ArrayList<>(ISeq.of(genotype).asList());

			// Add/remove Chromosome to Genotype.
			final var random = RandomRegistry.random();
			final double rd = random.nextDouble();
			if (rd < 1/3.0) {
				chromosomes.remove(0);
			} else if (rd < 2/3.0) {
				chromosomes.add(chromosomes.get(0).newInstance());
			}

			alterations.value +=
				indexes(RandomRegistry.random(), chromosomes.size(), p)
					.map(i -> mutate(chromosomes, i, p))
					.sum();

			return Genotype.of(chromosomes);
		}

		private int mutate(final List<Chromosome<G>> c, final int i, final double p) {
			final Chromosome<G> chromosome = c.get(i);
			final List<G> genes = new ArrayList<>(ISeq.of(chromosome).asList());

			final int mutations = mutate(genes, p);
			if (mutations > 0) {
				c.set(i, chromosome.newInstance(ISeq.of(genes)));
			}
			return mutations;
		}

		private int mutate(final List<G> genes, final double p) {
			final var random = RandomRegistry.random();
			return (int)indexes(random, genes.size(), p)
				.peek(i -> genes.set(i, genes.get(i).newInstance()))
				.count();
		}
	}

	public static void main(final String[] args) {
		final Engine<DoubleGene, Double> engine = Engine
			.builder(DynamicGenotype::fitness, ENCODING)
			.alterers(new DynamicMutator<>(0.25))
			.build();

		final EvolutionResult<DoubleGene, Double> result = engine.stream()
			.limit(20)
			.collect(EvolutionResult.toBestEvolutionResult());

		System.out.println(result.bestFitness());
	}

}


text:
set -euo pipefail

version="$1"
echo "version: $version"

script_dir="$(dirname "${BASH_SOURCE[0]}")"
cd "$script_dir"

git fetch upstream

#
# Using the current environment, that has smart_open installed
#
cd ..
python -m doctest README.rst
cd "$script_dir"

rm -rf sandbox.venv
virtualenv sandbox.venv -p $(which python3)

set +u  # work around virtualenv awkwardness
source sandbox.venv/bin/activate
set -u

cd ..
pip install -e .[test]  # for smart_open
pip install .[test]  # for gensim
python setup.py test  # for gensim

#
# Delete the release branch in case one is left lying around.
#
git checkout upstream/master
set +e
git branch -D release-"$version"
set -e

git checkout upstream/master -b release-"$version"
echo "__version__ = '$version'" > smart_open/version.py
git commit smart_open/version.py -m "bump version to $version"

echo "Next, update CHANGELOG.md."
echo "Consider running summarize_pr.sh for each PR merged since the last release."
read -p "Press Enter to continue..."

${EDITOR:-vim} CHANGELOG.md
set +e
git commit CHANGELOG.md -m "updated CHANGELOG.md for version $version"
set -e

python -c 'help("smart_open")' > help.txt

#
# The below command will fail if there are no changes to help.txt.
# We can safely ignore that failure.
#
set +e
git commit help.txt -m "updated help.txt for version $version"
set -e

echo "Have a look at the current branch, and if all looks good, run merge.sh"

cd "$script_dir"
rm -rf sandbox.venv


text:
.. _deployment:

Deployment
==========

Install via yum
---------------

::

    $ yum install pdc-server

The RPM includes a cron job to perform daily synchronization of users with
LDAP. It is installed to ``/etc/cron.daily`` and does not need any
configuration.

Configure Django settings
-------------------------

::

    # mv settings_local.py.dist to settings_local.py
    # change database settings in /usr/lib/pythonX.Y/site-packages/pdc/settings_local.py

Initialize database
-------------------

::

    # create database
    $ su - postgres
    $ psql
    postgres=# create database "db_name" owner "user_name";
    postgres=# \q

    # migrate database
    $ django-admin migrate --settings=pdc.settings --noinput

Collect static
--------------

::

    $ django-admin collectstatic --settings=pdc.settings

Config apache
-------------

replace ``PDC_HOSTNAME`` with server's hostname in ``/etc/httpd/conf.d/pdc.conf``


text:
package org.nd4j.imports;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.autodiff.execution.NativeGraphExecutioner;
import org.nd4j.autodiff.execution.conf.ExecutionMode;
import org.nd4j.autodiff.execution.conf.ExecutorConfiguration;
import org.nd4j.autodiff.execution.conf.OutputMode;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.imports.graphmapper.tf.TFGraphMapper;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.executioner.OpExecutioner;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;

import static org.junit.Assert.assertEquals;

/**
 * Created by susaneraly on 11/6/17.
 */
@Slf4j
@RunWith(Parameterized.class)
public class TFGraphTestAllHelper {

    public enum ExecuteWith {
        SAMEDIFF(SAMEDIFF_DEFAULT_BASE_DIR),
        LIBND4J(LIBND4J_DEFAULT_BASE_DIR),
        JUST_PRINT(COMMON_BASE_DIR);
        private ExecuteWith(String baseDir) {
            this.BASE_DIR = baseDir;
        }
        private final String BASE_DIR;
        public String getDefaultBaseDir() {return BASE_DIR;}
    }

    //TODO: Later, we can add this as a param so we can test different graphs in samediff and not samediff
    public static final String COMMON_BASE_DIR = "tf_graphs/examples";
    public static final String SAMEDIFF_DEFAULT_BASE_DIR = COMMON_BASE_DIR;
    public static final String LIBND4J_DEFAULT_BASE_DIR = COMMON_BASE_DIR;

    private static ExecutorConfiguration configuration = ExecutorConfiguration.builder()
            .executionMode(ExecutionMode.SEQUENTIAL)
            .profilingMode(OpExecutioner.ProfilingMode.DISABLED)
            .gatherTimings(true)
            .outputMode(OutputMode.VARIABLE_SPACE)
            .build();

    protected static List<Object[]> fetchTestParams(ExecuteWith executeWith) throws IOException {
        return fetchTestParams(executeWith.getDefaultBaseDir(),executeWith);
    }

    protected static List<Object[]> fetchTestParams(String baseDir, ExecuteWith executeWith) throws IOException {
        String[] modelNames = modelDirNames(baseDir,executeWith);
        List<Object[]> modelParams = new ArrayList<>();
        for (int i = 0; i < modelNames.length; i++) {
            Object[] currentParams = new Object[3];
            currentParams[0] = inputVars(modelNames[i], baseDir); //input variable map - could be null
            currentParams[1] = outputVars(modelNames[i], baseDir); //saved off predictions
            currentParams[2] = modelNames[i];
            modelParams.add(currentParams);
        }
        return modelParams;
    }

    protected static void checkOnlyOutput(Map<String, INDArray> inputs, Map<String, INDArray> predictions, String modelName, ExecuteWith execType) throws IOException {
        log.info("Running model " + modelName + " only output");
        checkOnlyOutput(inputs, predictions, modelName, execType.getDefaultBaseDir(), execType);
    }

    protected static void checkOnlyOutput(Map<String, INDArray> inputs, Map<String, INDArray> predictions, String modelName, String baseDir, ExecuteWith execType) throws IOException {
        Nd4j.EPS_THRESHOLD = 1e-3;
        Nd4j.getExecutioner().enableDebugMode(true);
        Nd4j.getExecutioner().enableVerboseMode(true);

        val graph = getGraphAfterExec(baseDir, modelName, inputs, execType);

        if (!execType.equals(ExecuteWith.JUST_PRINT)) {
            for (String outputNode : predictions.keySet()) {
                INDArray nd4jPred = graph.getVariable(outputNode).getArr();
                INDArray tfPred = predictions.get(outputNode);
                assertEquals("Predictions do not match on " + modelName, tfPred, nd4jPred);
            }
            log.info("\n\tTEST " + modelName + " PASSED...");
            log.info("\n========================================================\n");
        }
    }

    public static void checkIntermediate(Map<String, INDArray> inputs, String modelName, ExecuteWith execType) throws IOException {
        checkIntermediate(inputs, modelName, execType.getDefaultBaseDir(), execType);
    }

    public static void checkIntermediate(Map<String, INDArray> inputs, String modelName, String baseDir, ExecuteWith execType) throws IOException {
        Nd4j.EPS_THRESHOLD = 1e-3;
        Nd4j.getExecutioner().enableDebugMode(true);
        Nd4j.getExecutioner().enableVerboseMode(true);
        val graph = getGraphAfterExec(baseDir, modelName, inputs, execType);
        if (!execType.equals(ExecuteWith.JUST_PRINT)) {
            for (String varName : graph.variableMap().keySet()) {
                if (!inputs.containsKey(varName)) { //avoiding placeholders
                    INDArray tfValue = intermediateVars(modelName, baseDir, varName);
                    if(tfValue == null) {
                        continue;
                    }
                    assertEquals("Shape not equal on node " + varName, ArrayUtils.toString(tfValue.shape()), ArrayUtils.toString(graph.getVariable(varName).getShape()));
                    assertEquals("Value not equal on node " + varName, tfValue, graph.getVariable(varName).getArr());
                    log.info("\n\tShapes equal for " + varName);
                    log.info("\n\tValues equal for " + varName);
                }
            }
        }
    }

    public static SameDiff getGraphAfterExec(String baseDir, String modelName, Map<String, INDArray> inputs, ExecuteWith executeWith) throws IOException {
        log.info("\n\tRUNNING TEST " + modelName + "...");
        val graph = TFGraphMapper.getInstance().importGraph(new ClassPathResource(baseDir + "/" + modelName + "/frozen_model.pb").getInputStream());
        if (executeWith.equals(ExecuteWith.SAMEDIFF)) {
            if (!inputs.isEmpty()) {
                graph.execWithPlaceHolder(inputs); //This is expected to be just one result
            } else {
                graph.execAndEndResult(); //there are graphs with no placeholders like g_00
            }
        } else if (executeWith.equals(ExecuteWith.LIBND4J)) {
            for (String input : inputs.keySet()) {
                graph.associateArrayWithVariable(inputs.get(input), graph.variableMap().get(input));
            }

            //val string = graph.asFlatPrint();
            //log.info("Graph structure: \n{}", string);
            val executioner = new NativeGraphExecutioner();
            val results = executioner.executeGraph(graph, configuration);

            //assertTrue(results.length > 0); //FIXME: Later

            //graph.asFlatFile(new File("../../../libnd4j/tests_cpu/resources/conv_0.fb"));
        } else if (executeWith.equals(ExecuteWith.JUST_PRINT)) {
            for (String input : inputs.keySet()) {
                graph.associateArrayWithVariable(inputs.get(input), graph.variableMap().get(input));
            }

            val string = graph.asFlatPrint();
            log.info("Graph structure: \n{}", string);
        }
        return graph;
    }

    private static String[] modelDirNames(String base_dir,ExecuteWith executeWith) throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new ClassPathResource(base_dir).getClassLoader());
        Resource[] resources = resolver.getResources("classpath*:" + base_dir + "/**/frozen_model.pb");
        String[] exampleNames = new String[resources.length];
        for (int i = 0; i < resources.length; i++) {
            String nestedName = resources[i].getURL().toString().split(base_dir + "/")[1];
            exampleNames[i] = nestedName.replaceAll(Pattern.quote(executeWith.getDefaultBaseDir()),"").replaceAll("/frozen_model.pb","");
        }
        return exampleNames;
    }

    protected static Map<String, INDArray> inputVars(String modelName, String base_dir) throws IOException {
        return readVars(modelName, base_dir, "**.placeholder");
    }

    protected static Map<String, INDArray> outputVars(String modelName, String base_dir) throws IOException {
        return readVars(modelName, base_dir, "**.prediction");
    }

    /**
     * Possible for a single node to give multiple outputs
     * How is a node that has a list of outputs like in the case of "node_multiple_out" work
     * Below is hardcoded for a single node
     */
    protected static INDArray intermediateVars(String modelName, String base_dir, String varName) throws IOException {
        //convert varName to convention used in naming files
        // "/" replaced by "____"; followed by a digit indicating the output number followed by prediction_inbw.(shape|csv)
        if (varName.contains(":")) {
            varName = varName.replace(':','.');
        }
        else {
            varName = varName + ".0";
        }
        Map<String, INDArray> nodeSepOutput = readVars(modelName, base_dir, varName.replaceAll("/", "____") + ".prediction_inbw");
        //required check for pattern matching as there are scopes and "*" above is a greedy match
        Set<String> removeList = confirmPatternMatch(nodeSepOutput.keySet(), varName);
        for (String toRemove : removeList) {
            nodeSepOutput.remove(toRemove);
        }
        return nodeSepOutput.get(varName); //this *should* return a list of the indarrays for each node
    }

    public static Set<String> confirmPatternMatch(Set<String> setOfNames, String varName) {
        Set<String> removeList = new HashSet<>();
        for (String name : setOfNames) {
            if (name.equals(varName)) continue;
            String[] splitByPeriod = name.split("\\.");
            //not a number - maybe another variable deeper in the same scope
            if (!NumberUtils.isNumber(splitByPeriod[splitByPeriod.length - 1])) {
                removeList.add(name);
            } else if (!String.join(".", Arrays.copyOfRange(splitByPeriod, 0, splitByPeriod.length - 1)).equals(varName)) {
                removeList.add(name);
            }
        }
        return removeList;
    }

    protected static Map<String, INDArray> readVars(String modelName, String base_dir, String pattern) throws IOException {
        Map<String, INDArray> varMap = new HashMap<>();
        String modelDir = base_dir + "/" + modelName;
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new ClassPathResource(modelDir).getClassLoader());
        Resource[] resources = resolver.getResources("classpath*:" + modelDir + "/" + pattern + ".shape");
        for (int i = 0; i < resources.length; i++) {
            String fileName = resources[i].getFilename();
            String varPath = modelDir + "/" + fileName;
            String[] varNameArr = fileName.split("\\.");
            String varName = String.join(".", Arrays.copyOfRange(varNameArr, 0, varNameArr.length - 2));
            int[] varShape = Nd4j.readNumpy(new ClassPathResource(varPath).getInputStream(), ",").data().asInt();
            float[] varContents = Nd4j.readNumpy(new ClassPathResource(varPath.replace(".shape", ".csv")).getInputStream(), ",").data().asFloat();
            INDArray varValue;
            if (varShape.length == 1) {
                if (varShape[0] == 0) {
                    varValue = Nd4j.trueScalar(varContents[0]);
                } else {
                    varValue = Nd4j.trueVector(varContents);
                }
            }
            else {
                varValue = Nd4j.create(varContents,varShape);
            }
            //varValue = Nd4j.readNumpy(new ClassPathResource(varPath.replace(".shape", ".csv")).getInputStream(), ",").reshape(varShape);
            if (varName.contains("____")) {
                //these are intermediate node outputs
                varMap.put(varName.replaceAll("____", "/"), varValue);
            } else {
                varMap.put(varName, varValue);
            }
        }
        return varMap;
    }
}


text:
echo "=========================================================="
echo "Starting on       : $(date)"
echo "Running on node   : $(hostname)"
echo "Current directory : $(pwd)"
echo "Current job ID    : $JOB_ID"
echo "Current job name  : $JOB_NAME"
echo "Task index number : $TASK_ID"
echo "=========================================================="
echo ""

echo "Processed directory is ${2}"

Rscript $1/buildJoinIterationFileClust.R  $1  $2  $3  $4  $1/weightedVoting/weightedVoting.csv


text:
package logger

import (
	"github.com/cnf/structhash"
	"github.com/mitchellh/mapstructure"

	"github.com/cnf/stacker/engine"
)

// Config object for logger
type Config struct {
	Location string `toml:"location" version:"1"`
}

// Target returns the namespace of the target of this config
func (c *Config) Target() *engine.NameSpace {
	return &engine.NameSpace{
		Type:   "module",
		Module: "logger",
	}
}

// NewConfig returns a logger config with defaults
func NewConfig() *Config {
	return &Config{}
}

// ConfigDecoder ...
type ConfigDecoder struct{}

// Version ...
func (c *Config) Version() int {
	return 1
}

// Hash returns the unique hash for this config object
func (c *Config) Hash() string {
	hash, err := structhash.Hash(c, engine.LatestHashVersion)
	if err != nil {
		return ""
	}
	return hash
}

// RegisterConfigDecoder with the engine.
func RegisterConfigDecoder() {
	engine.RegisterConfigDecoder("logger", &ConfigDecoder{})
}

// DecodeConfig returns a parsed config object
func (cd *ConfigDecoder) DecodeConfig(data interface{}) (engine.Config, error) {
	var md mapstructure.Metadata
	cfg := NewConfig()
	config := &mapstructure.DecoderConfig{
		Metadata: &md,
		Result:   cfg,
	}
	decoder, err := mapstructure.NewDecoder(config)
	if err != nil {
		return nil, err
	}
	if err := decoder.Decode(data); err != nil {
		return nil, err
	}
	return cfg, nil
}


text:
package cx_test

import (
	"context"

	cx "cloud.google.com/go/dialogflow/cx/apiv3"
	cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb"
	"google.golang.org/api/iterator"
	locationpb "google.golang.org/genproto/googleapis/cloud/location"
	longrunningpb "google.golang.org/genproto/googleapis/longrunning"
)

func ExampleNewVersionsClient() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	// TODO: Use client.
	_ = c
}

func ExampleVersionsClient_ListVersions() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &cxpb.ListVersionsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dialogflow/cx/apiv3/cxpb#ListVersionsRequest.
	}
	it := c.ListVersions(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp
	}
}

func ExampleVersionsClient_GetVersion() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &cxpb.GetVersionRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dialogflow/cx/apiv3/cxpb#GetVersionRequest.
	}
	resp, err := c.GetVersion(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleVersionsClient_CreateVersion() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &cxpb.CreateVersionRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dialogflow/cx/apiv3/cxpb#CreateVersionRequest.
	}
	op, err := c.CreateVersion(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleVersionsClient_UpdateVersion() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &cxpb.UpdateVersionRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dialogflow/cx/apiv3/cxpb#UpdateVersionRequest.
	}
	resp, err := c.UpdateVersion(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleVersionsClient_DeleteVersion() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &cxpb.DeleteVersionRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dialogflow/cx/apiv3/cxpb#DeleteVersionRequest.
	}
	err = c.DeleteVersion(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
}

func ExampleVersionsClient_LoadVersion() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &cxpb.LoadVersionRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dialogflow/cx/apiv3/cxpb#LoadVersionRequest.
	}
	op, err := c.LoadVersion(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	err = op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
}

func ExampleVersionsClient_CompareVersions() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &cxpb.CompareVersionsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dialogflow/cx/apiv3/cxpb#CompareVersionsRequest.
	}
	resp, err := c.CompareVersions(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleVersionsClient_GetLocation() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &locationpb.GetLocationRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/location#GetLocationRequest.
	}
	resp, err := c.GetLocation(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleVersionsClient_ListLocations() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &locationpb.ListLocationsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/location#ListLocationsRequest.
	}
	it := c.ListLocations(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp
	}
}

func ExampleVersionsClient_CancelOperation() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.CancelOperationRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#CancelOperationRequest.
	}
	err = c.CancelOperation(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
}

func ExampleVersionsClient_GetOperation() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.GetOperationRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#GetOperationRequest.
	}
	resp, err := c.GetOperation(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleVersionsClient_ListOperations() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := cx.NewVersionsClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.ListOperationsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#ListOperationsRequest.
	}
	it := c.ListOperations(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp
	}
}


text:
<?php get_header(); ?>

<?php single_cat_title(); ?>

<?php get_header(); ?>

		<?php
		if(have_posts()): while(have_posts()): the_post();
		include(locate_template('portfolio_list_item.php'));
		endwhile; endif;
		?>

	<?PHP get_template_part('pagination'); ?>

<?php get_footer(); ?>


text:
from sklearn.naive_bayes import BernoulliNB
from sklearn import model_selection

def data_generate(data, size, target):
    data_train, data_test, target_train, target_test = model_selection.train_test_split(data, target, test_size=size, random_state=43)
    return data_train, data_test, target_train, target_test

def learn(data, target):
    classifier = BernoulliNB().fit(data, target)
    return classifier

def predict(data, classifier,):
    return classifier.predict(data)


text:
function Controller() {
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "index";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.index = Ti.UI.createTabGroup({
        id: "index"
    });
    $.__views.__alloyId2 = Alloy.createController("mapwin", {
        id: "__alloyId2"
    });
    $.__views.index.addTab($.__views.__alloyId2.getViewEx({
        recurse: true
    }));
    $.__views.__alloyId4 = Alloy.createController("messageswin", {
        id: "__alloyId4"
    });
    $.__views.index.addTab($.__views.__alloyId4.getViewEx({
        recurse: true
    }));
    $.__views.index && $.addTopLevelView($.__views.index);
    $.__views.__alloyId5 = Alloy.createController("newmessagewin", {
        id: "__alloyId5"
    });
    $.__views.__alloyId5 && $.addTopLevelView($.__views.__alloyId5);
    exports.destroy = function() {};
    _.extend($, $.__views);
    $.index.open();
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
layout: page

title: Events
subtitle: "Past and future plans for the club"
#cover_image: blog-cover.jpg

#excerpt: "Incorporated provides a great typography, responsive design, author details, semantic markup and more."

---

### Upcoming events:

{% for post in site.posts reversed %}
{% unless post.draft or post.categories contains 'archives'%}

{{ post.title }}

{{ post.excerpt }}

              {{ post.location }} —
              <time pubdate datetime="{{ post.date | date: "%Y-%d-%B" }}" title="{{ post.date | date: "%B %d, %Y" }}">{{ post.date | date: "%B %d, %Y" }}</time>

  {% endunless %}
  {% endfor %}

### Calendar:


text: Experimental 3D game engine that has a hexagonal grid. It is written in C++11 and it uses Allegro5.


text:
<?php
declare(strict_types=1);

namespace GpsLab\Bundle\GeoIP2Bundle\DependencyInjection;

use GeoIp2\Database\Reader;
use GpsLab\Bundle\GeoIP2Bundle\Command\DownloadDatabaseCommand;
use GpsLab\Bundle\GeoIP2Bundle\Command\UpdateDatabaseCommand;
use GpsLab\Bundle\GeoIP2Bundle\Downloader\Downloader;
use GpsLab\Bundle\GeoIP2Bundle\Downloader\MaxMindDownloader;
use GpsLab\Bundle\GeoIP2Bundle\Reader\ReaderFactory;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class GpsLabGeoIP2Extension extends Extension
{
    /**
     * Pattern of database service name.
     */
    private const SERVICE_NAME = 'geoip2.database.%s_reader';

    /**
     * @param array[]          $configs
     * @param ContainerBuilder $container
     */
    public function load(array $configs, ContainerBuilder $container): void
    {
        $configuration = $this->getConfiguration($configs, $container);
        $config = $this->processConfiguration($configuration, $configs);

        $default_database = $config['default_database'];
        $databases = $config['databases'];

        // aliases for default database
        if (array_key_exists($default_database, $databases)) {
            $container->setAlias('geoip2.reader', sprintf(self::SERVICE_NAME, $default_database));
            $container->getAlias('geoip2.reader')->setPublic(true);
            $container->setAlias(Reader::class, sprintf(self::SERVICE_NAME, $default_database));
            $container->getAlias(Reader::class)->setPublic(true);
        }

        // define database services
        foreach ($databases as $name => $database) {
            $container
                ->setDefinition(sprintf(self::SERVICE_NAME, $name), new Definition(Reader::class))
                ->setPublic(true)
                ->setLazy(true)
                ->setArguments([
                    $database['path'],
                    $database['locales'],
                ]);
        }

        // define MaxMind downloader service
        $container
            ->setDefinition(MaxMindDownloader::class, new Definition(MaxMindDownloader::class))
            ->setPublic(false)
            ->setArguments([
                new Reference('filesystem'),
                new Reference('logger'),
            ]);

        $container->setAlias(Downloader::class, MaxMindDownloader::class);
        $container->getAlias(Downloader::class)->setPublic(true);

        // configure update database console command
        $container
            ->setDefinition(UpdateDatabaseCommand::class, new Definition(UpdateDatabaseCommand::class))
            ->setPublic(false)
            ->setArguments([
                new Reference(Downloader::class),
                $databases,
            ])
            ->addTag('console.command');

        // configure download database console command
        $container
            ->setDefinition(DownloadDatabaseCommand::class, new Definition(DownloadDatabaseCommand::class))
            ->setPublic(false)
            ->setArguments([
                new Reference(Downloader::class),
            ])
            ->addTag('console.command');

        // configure reader factory service
        $container
            ->setDefinition(ReaderFactory::class, new Definition(ReaderFactory::class))
            ->setPublic(false)
            ->setArguments([
                $databases,
            ]);
    }

    /**
     * @param array[]          $config
     * @param ContainerBuilder $container
     *
     * @return Configuration
     */
    public function getConfiguration(array $config, ContainerBuilder $container): Configuration
    {
        $cache_dir = null;

        if ($container->hasParameter('kernel.cache_dir')) {
            $cache_dir = $container->getParameter('kernel.cache_dir');
        }

        return new Configuration(is_string($cache_dir) ? $cache_dir : null);
    }

    /**
     * @return string
     */
    public function getAlias(): string
    {
        return 'gpslab_geoip';
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>BaraBaraDark</title>
    <link href="assets/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="assets/main.css" rel="stylesheet" type="text/css" />
    <link href="assets/font-awesome.css" rel="stylesheet" type="text/css" />

Starting up...

 [
        debug]

BaraBaraDark

Messages

 Nothing to see here...

			[debug]

Tor hiddenservice address:

			Force update BarBaraDark

This will download latest BBD version from github

List of subscriptions

Subscribtion name: <input name="sub_address" type="text" length="90" id="sub_address" style="width: 400px;"><input type="button" value="Add" id="add_sub_key">

Добро пожаловать. Снова.

    <input style="display:none;" id="saveFileDialog" type="file" />


text:
<?php
namespace CodeOrders\V1\Rest\Users;

class UsersEntity
{

    protected $id;
    protected $username;
    protected $password;
    protected $first_name;
    protected $last_name;
    protected $role;

    /**
     * @return mixed
     */
    public function getFirstName()
    {
        return $this->first_name;
    }

    /**
     * @param mixed $first_name
     * @return UsersEntity
     */
    public function setFirstName($first_name)
    {
        $this->first_name = $first_name;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     * @return UsersEntity
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getLastName()
    {
        return $this->last_name;
    }

    /**
     * @param mixed $last_name
     * @return UsersEntity
     */
    public function setLastName($last_name)
    {
        $this->last_name = $last_name;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param mixed $password
     * @return UsersEntity
     */
    public function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getRole()
    {
        return $this->role;
    }

    /**
     * @param mixed $role
     * @return UsersEntity
     */
    public function setRole($role)
    {
        $this->role = $role;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     * @return UsersEntity
     */
    public function setUsername($username)
    {
        $this->username = $username;
        return $this;
    }

}


text:
class CreateFeedbacks < ActiveRecord::Migration
  def change
    create_table :feedbacks do |t|
      t.text :body, null: false

      t.boolean :anonymous, default: false
      t.integer :project_id, null: false

      # identify the user with one of these
      t.integer :user_id
      t.string :session_id

      t.timestamps null: false
    end

    # TODO: need some indexes here
  end
end


text:
FROM sameersbn/ubuntu:14.04.20151117
MAINTAINER sameer@damagehead.com

ENV SQUID_VERSION=3.3.8 \
    SQUID_CACHE_DIR=/var/spool/squid3 \
    SQUID_LOG_DIR=/var/log/squid3 \
    SQUID_USER=proxy

# Install Ruby.
RUN \
  apt-get update && \
  apt-get install -y ruby ruby-dev ruby-bundler && \
  rm -rf /var/lib/apt/lists/*

RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 80F70E11F0F0D5F10CB20E62F5DA5F09C3173AA6 \
 && echo "deb http://ppa.launchpad.net/brightbox/squid-ssl/ubuntu trusty main" >> /etc/apt/sources.list \
 && apt-get update \
 && DEBIAN_FRONTEND=noninteractive apt-get install -y squid3-ssl=${SQUID_VERSION}* \
 && mv /etc/squid3/squid.conf /etc/squid3/squid.conf.dist \
 && rm -rf /var/lib/apt/lists/*

COPY rewrite.rb /etc/squid3/rewrite.rb
RUN chmod 755 /etc/squid3/rewrite.rb

COPY squid.conf /etc/squid3/squid.conf
COPY entrypoint.sh /sbin/entrypoint.sh
RUN chmod 755 /sbin/entrypoint.sh

EXPOSE 3128/tcp
VOLUME ["${SQUID_CACHE_DIR}"]
ENTRYPOINT ["/sbin/entrypoint.sh"]


text:
class Test {
   public boolean foo() {
        Object o = null;
        return (<warning descr="Casting 'o' to 'String' is redundant">String</warning>) o == null;
    }
}


text:
@class NSLayoutConstraint;

@interface IDEDistributionManifestStepViewController : IDEDistributionStepViewController
{
    NSLayoutConstraint *_centeredViewHeightConstraint;
}

+ (id)keyPathsForValuesAffectingCanGoNext;
+ (BOOL)skipStepForContext:(id)arg1 assistantDirection:(int)arg2;
@property __weak NSLayoutConstraint *centeredViewHeightConstraint; // @synthesize centeredViewHeightConstraint=_centeredViewHeightConstraint;
- (void)learnMore:(id)arg1;
- (BOOL)canGoNext;
- (id)nextButtonTitle;
- (id)title;
- (void)viewDidLoad;

@end


text:
/**
 * Halo sombre de survival horror
 */
O2.extendClass('HOTD.GX.GunFlash', O876_Raycaster.GXEffect, {
	sClass: 'DarkHaze',
	oCanvas: null,
	bOver: false,
	nTime: 3,

	__construct: function(oRaycaster) {
		__inherited(oRaycaster);
		this.oCanvas = O876.CanvasFactory.cloneCanvas(oRaycaster.getRenderCanvas());
	},

	isOver: function() {
		return this.bOver;
	},

	process: function() {
		if (this.nTime-- < 0) {
			this.terminate();
		}
	},

	render: function() {
		var c = this.oCanvas;
		var ctx = c.getContext('2d');
		ctx.drawImage(this.oRaycaster.getRenderCanvas(), 0, 0);
		ctx = this.oRaycaster.getRenderContext();
		var fGCO = ctx.globalCompositeOperation;
		ctx.globalCompositeOperation = 'lighter';
		ctx.drawImage(c, 0, 0);
		ctx.globalCompositeOperation = fGCO;
	},

	done: function() {
		this.terminate();
	},

	terminate: function() {
		this.bOver = true;
	}
});


text:
import React from 'react';
import App from './App.js';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import coreReducers from './reducers';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import { getTeachers } from './actions';

const loggerMiddleware = createLogger();

const store = createStore(
  coreReducers,
  applyMiddleware( thunkMiddleware, loggerMiddleware )
);

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

store.dispatch(getTeachers());


text:
/*
Calendar JS
*/

var dateNow = new Date();
var currDay = dateNow.getDate();
var currMon = dateNow.getMonth();
var currYear = dateNow.getFullYear();
var cellDay = document.getElementsByTagName('td');
var listMon = document.getElementById("select-months");
var listYear = document.getElementById("select-years");
drawCalender(currYear, currMon);
showlistYear();
selectDay();

// Draw Calendar
function drawCalender(year, month) {
	parseInt(year);
	parseInt(month);
	var firstDay = new Date(year, month, 1).getDay();
	var lastDate = new Date(year, month + 1, 0).getDate();
	var i, day;
	day = 13 + firstDay;

	for (i = 13; i < 55; i++) {
		cellDay[i].innerHTML = "";
		cellDay[i].style.backgroundColor = "#fff";
	}

	for (i = 1; i <= lastDate; i++) {
		cellDay[day].innerHTML = i;
		day++;
	}

	if (year === dateNow.getFullYear()) {
		if (month === dateNow.getMonth()) {
			var showCurdate = 12 + firstDay + dateNow.getDate();
			cellDay[showCurdate].style.backgroundColor = "#00f3ff";
		}
	}
	 showTimeBox();
}

//show list Year in combobox
function showlistYear() {
	for (var i = 1954; i < 2100; i++) {
		listYear.innerHTML += "<option value='" + i + "'>" + i + "</option>";
	}
	drawCalender(currYear, currMon);
}

function showTimeBox() {
	listMon.value = currMon;
	listYear.value = currYear;
}

function chooseMonth(month) {
	currMon += month;
	if (currMon < 0) {
		currMon = 11;
		currYear -= 1;
	}
	if (currMon > 11) {
		currMon = 0;
		currYear += 1;
	}
	checkTime();
	drawCalender(currYear, currMon);
}
// Check the year is between 1954 and 2100
function checkTime() {
	if (currYear < 1954) {
		currYear = 1954;
	}
	if (currYear >= 2100) {
		currYear = 2099;
	}
}

function chooseYear(year) {
	currYear = parseInt(currYear) + parseInt(year);
	checkTime();
	drawCalender(currYear, currMon);
}

function selectMonth() {
	currMon = parseInt(listMon.value);
	drawCalender(currYear, currMon);
}

function selectYear() {
	currYear = parseInt(listYear.value);
	drawCalender(currYear, currMon);
}

function selectDay() {
	var dayAnyNow = document.getElementById("day-now");
	dayAnyNow.value = currDay + "/" + (currMon + 1) + "/" + currYear;

	for (var i = 13; i < 55; i++) {
		cellDay[i].addEventListener("click", function () {
			var dayCheck = this.innerHTML;

			for (var j = 13; j < 55; j++) {
				cellDay[j].style.border = "";
			}
			if (dayCheck != "") {
				dayAnyNow.value = dayCheck + "/" + (currMon + 1) + "/" + currYear;
				this.style.border = "1px solid ";
			}
		});
	}
}


text:
import keyMirror from 'keymirror';

export default keyMirror({
  PUSH_NOTIFICATIONS_SUBSCRIBE: null,
  PUSH_NOTIFICATIONS_UNSUBSCRIBE: null,
});


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Blog1729 - Dynamic Programming algorithm for Longest Common Subsequence</title>
        <link rel="stylesheet" type="text/css" href="../css/default.css" />

                Blog1729

                Home
                About
                Contact
                Archive

Dynamic Programming algorithm for Longest Common Subsequence

    Posted on April  7, 2015

Given a sequence $X = x_1, x_2, , x_n $, another sequence \(Z = \langle z_1, \cdots, z_k \rangle\) is said to be subsequence of \(X\) if there exists a strictly increasing sequence \(\langle i_1, \cdots, i_k \rangle\) of indices of \(X\) such that \(j=1, 2, \cdots, k\) such that \(x_{i_j} = z_j\).

In the longest common subsequence problem, given two sequences \(X\) and \(Y\), we wish find a maximum length common subsequence of \(X\) and \(Y\).

Theorem Let \(X= \langle x_1, \cdots, x_n \rangle\) and \(Y = \langle y_1, y_2, \cdots, y_m\rangle\) be sequences, and let \(Z = \langle z_1, \cdots, z_k \rangle\) be any Longest Common Subsequence of \(X\) and \(Y\). Then

If \(x_m = y_n\), then \(z_k = x_m = y_n\) and \(Z_{k-1}\) is a LCS of \(X_{m-1}\) and \(Y_{m-1}\).

If \(x_m \neq y_n\), then \(z_k \neq x_m\) implies that \(Z\) is a LCS of \(X_{m-1}\) and \(Y_n\).

If \(x_m \neq y_n\), then \(z_k \neq y_n\) implies that \(Z\) is a LCS of \(X_{m}\) and \(Y_{n-1}\)

The above theorem paves road for an optimal substructure.

Recursive solution: Let \(c[i,j]\) denote the length of the LCS for sequences \(X_i\) and \(Y_i\), then \(c[i,j]\) will follow the following recursion: \[c[i,j] = \left \{ \begin{array}{c c}
  0 & \text{if } i = 0 \text{ or } j=0, \\
  c[i-1, j-1] + 1 & \text{if } i,j >0 \text{ and } x_i = y_i \\
  \max \{ c[i,j-1], c[i-1, j] \} & \text{if } i,j>0 \text{ and } x_i \neq y_j.
  \end{array} \right.\]

Using dynamic programming, we can easily construct a solution to the problem that takes a time complexity of \(\Theta(mn)\). To re-construct the solutions to the problem, one can create an additional array that stores if the \(c[i,j]\) was formed by adding 1 or points to the maximum element in the sub-structure. But in fact, as an optimization, one can avoid this and this detail can be re-constructed from the table.

Notes

To find the longest monotonically increasing subsequence of a sequence of \(n\) numbers, one can implement a \(\mathcal O(n^2)\) algorithm that simply finds the LCS of the given sequence and the same sequence after sorting. (I'm told that one can improve the complexity to \(O(n \lg n)\).)

The algorithm to reconstruct the LCS takes a complexity of \(\mathcal O(m+n)\).

            Site proudly generated by
            Hakyll


text:
<form name="loginForm"
      layout="row"
      layout-align="center"
      ng-controller="AuthCtrl"
      >

    <md-card class="form-wrapper"
             flex="60"
             flex-md="95"
             flex-sm="95">

        <md-card-content>

请填写登录信息

        </md-card-content>

        <md-divider></md-divider>

        <md-card-content>

            <md-input-container>
                邮箱
                <input type="email" name="email" ng-model="user.email" required>

邮箱不能为空

邮箱格式不正确

            </md-input-container>

            <md-input-container>
                密码
                <input type="password" name="password" ng-model="user.password" minlength="6" required>

密码不能为空

密码最少6位

            </md-input-container>

        </md-card-content>

        <md-divider></md-divider>

        <md-card-content
           layout="row"
           layout-align="end">

            <md-button class="md-raised md-primary"
                       flex="15"
                       flex-md="20"
                       flex-sm="30"
                       ng-disabled="submitting"
                       ng-click="login()">登录</md-button>
        </md-card-content>

    </md-card>
</form>


text:
package com.xin.framework.xinframwork.utils.common.assist;

import java.util.Collection;
import java.util.Map;

/**
 * 辅助判断
 */
public class EmptyCheck {

	public static boolean isEmpty(CharSequence str) {
		return isNull(str) || str.length() == 0;
	}

	public static boolean isEmpty(Object[] os) {
		return isNull(os) || os.length == 0;
	}

	public static boolean isEmpty(Collection<?> l) {
		return isNull(l) || l.isEmpty();
	}

	public static boolean isEmpty(Map<?, ?> m) {
		return isNull(m) || m.isEmpty();
	}

	public static boolean isNull(Object o) {
		return o == null;
	}
}


text:
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Category } from './category';
import { Note } from './note';
import { DataService } from './data.service';

@Component({
  selector: 'note-form',
  templateUrl : './noteform.component.html',
  providers: [DataService]
})

export class NoteFormComponent {
  successSave:boolean;
  noteForm: FormGroup;
  categories: Category[];

  constructor(fb: FormBuilder, private _dataService:DataService){
    this.successSave=false;
    this.categories = this._dataService.getCategories();
    this.noteForm = fb.group({
      'id' : 10,
      'title' : [null, Validators.compose([Validators.required, Validators.minLength(4)])],
      'date': [null, Validators.compose([Validators.required, Validators.pattern('[0-9]{4}\-[0-9]{2}\-[0-9]{2}')])],
      'category' : [null, Validators.required],
      'content' : [null, Validators.required]
    })
  }

  submitForm(value: any){
    this.successSave = true;
    console.log(value);
    this._dataService.addNote(value);
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

  Copyright 2003 - 2013 The eFaps Team

  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.

  Author:          The eFaps Team
  Revision:        $Rev$
  Last Changed:    $Date$
  Last Changed By: $Author$

-->
<install xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <application>eFapsApp-HumanResource</application>
    <dependencies>
        <dependency order="0">
            <groupId>org.efaps</groupId>
            <artifactId>efaps-kernel-install</artifactId>
            <version>5.0.0-SNAPSHOT</version>
        </dependency>
        <dependency order="1">
            <groupId>org.efaps</groupId>
            <artifactId>efaps-webapp-install</artifactId>
            <version>5.0.0-SNAPSHOT</version>
        </dependency>
        <dependency order="2">
            <groupId>org.efaps.apps</groupId>
            <artifactId>commons</artifactId>
            <version>5.0.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <version number="1" reloadCache="false" login="true" compile="true">
        <description>Install Human Resource Basic Modul.</description>
        <script type="groovy">
            import java.io.File;
            import java.util.UUID;
            import org.efaps.admin.runlevel.RunLevel;
            import org.efaps.admin.user.JAASSystem;
            import org.efaps.admin.user.Role;
            import org.efaps.db.Context;
            import org.efaps.db.QueryBuilder;
            import org.efaps.db.InstanceQuery;
            import org.efaps.esjp.admin.ui.UIUpdate;
            import org.efaps.esjp.admin.user.RoleUpdate;

            EFAPS_LOGGER.info("Importing Data for eFapsApp-HumanResource");

            RunLevel.init("shell");
            RunLevel.execute();

            UIUpdate update = new UIUpdate();
            <!-- connect the HumanResource_MyDesk Menu to the main menu from efaps -->
            update.add2Menu("95a2cfe0-92f0-432b-bbfb-6dee6e91a181", "87001cc3-c45c-44de-b8f1-776df507f268", 2);

            <!-- connect HR_Locations_LocationTree_Employee Menu to Locations_LocationTree -->
            update.add2Menu("8721159f-fd61-4a4c-996c-abb350bf773a", "385eb1af-ca21-47ca-a9ce-b37b6969e8ea", 2);

            <!-- Define attribute definition -->
            <!-- HumanResource_AttributeDefinitionAbstractMyDesk_Menu_Action, ERP_AttributeDefinitionMyDesk_Menu-->
            update.add2Menu("e02c020f-6418-4f22-a5b7-49459212cc27", "69e0b34a-2483-4662-9a45-1ce5d4e420e6", 1);

            <!-- add to HumanResource_Admin role -->
            RoleUpdate rolUp = new RoleUpdate("c3ff7ad7-da2b-4219-8b18-aa671fdb2113");
            <!-- ERP_AttributeDefinitionMyDesk -->
            rolUp.addUI("1c506850-7e64-439f-ad65-9c82dc762db8");
        </script>
    </version>
</install>


text:
set -euv

cd peacoqtop/plugin
eval `opam config env`
ocamlc -v
make -B


text:
require 'spec_helper'
require 'rspec_api_documentation/dsl'
require 'net/http'
require "rack/test"

describe "Non-api documentation specs" do
  it "should not be polluted by the rspec api dsl" do |example|
    expect(example.example_group).to_not include(RspecApiDocumentation::DSL)
  end
end

resource "Order" do
  explanation "Order resource explanation"

  describe "example metadata" do
    subject { |example| example.metadata }

    its([:resource_name]) { should eq("Order") }
    its([:resource_explanation]) { should eq("Order resource explanation") }
    its([:document]) { should be_truthy }
  end

  describe "example context" do
    it "should provide a client" do
      expect(client).to be_a(RspecApiDocumentation::RackTestClient)
    end

    it "should return the same client every time" do
      expect(client).to equal(client)
    end
  end

  [:post, :get, :put, :delete, :head, :patch].each do |http_method|
    send(http_method, "/path") do
      specify { |example| expect(example.example_group.description).to eq("#{http_method.to_s.upcase} /path") }

      describe "example metadata" do
        subject { |example| example.metadata }

        its([:method]) { should eq(http_method) }
        its([:route]) { should eq("/path") }
      end

      describe "example context" do
        subject { self }

        its(:method) { should eq(http_method) }
        its(:path) { should eq("/path") }

        describe "do_request" do
          it "should call the correct method on the client" do
            expect(client).to receive(http_method)
            do_request
          end
        end
      end
    end
  end

  post "/orders" do
    parameter :type, "The type of drink you want.", :required => true
    parameter :size, "The size of drink you want.", :required => true
    parameter :note, "Any additional notes about your order.", method: :custom_note
    parameter :name, :scope => :order, method: :custom_order_name
    parameter :quantity, "The quantity of drinks you want.", value: '3'

    response_field :type, "The type of drink you ordered.", :scope => :order
    response_field :size, "The size of drink you ordered.", :scope => :order
    response_field :note, "Any additional notes about your order.", :scope => :order
    response_field :name, :scope => :order
    response_field :id, "The order id"

    let(:type) { "coffee" }
    let(:size) { "medium" }

    let(:note) { "Made in Brazil" }
    let(:custom_note) { "Made in India" }

    let(:order_name) { "Nescoffee" }
    let(:custom_order_name) { "Jakobz" }

    describe "example metadata" do
      subject { |example| example.metadata }

      it "should include the documentated parameters" do
        expect(subject[:parameters]).to eq(
          [
            { :name => "type", :description => "The type of drink you want.", :required => true },
            { :name => "size", :description => "The size of drink you want.", :required => true },
            { :name => "note", :description => "Any additional notes about your order.", method: :custom_note },
            { :name => "name", :description => "Order name", :scope => :order, method: :custom_order_name },
            { :name => "quantity", :description => "The quantity of drinks you want.", value: '3' }
          ]
        )
      end

      it "should include the documentated response fields" do
        expect(subject[:response_fields]).to eq (
          [
            { :name => "type", :description => "The type of drink you ordered.", :scope => :order },
            { :name => "size", :description => "The size of drink you ordered.", :scope => :order },
            { :name => "note", :description => "Any additional notes about your order.", :scope => :order },
            { :name => "name", :description => "Order name", :scope => :order },
            { :name => "id", :description => "The order id" },
          ]
        )
      end
    end

    describe "example context" do
      subject { self }

      describe "params" do
        it "should equal the assigned parameter values" do
          expect(params).to eq({
            "type" => "coffee",
            "size" => "medium",
            "note" => "Made in India",
            "order" => { "name" => "Jakobz" },
            "quantity" => "3"
          })
        end
      end
    end
  end

  put "/orders/:id" do
    parameter :type, "The type of drink you want.", :required => true
    parameter :size, "The size of drink you want.", :required => true
    parameter :id, 'The ID of the resource.', :required => true, scope: :data
    parameter :note, "Any additional notes about your order."

    let(:type) { "coffee" }
    let(:size) { "medium" }
    let(:data_id) { 2 }

    let(:id) { 1 }

    describe "do_request" do
      context "when raw_post is defined" do
        let(:raw_post) { { :bill => params }.to_json }

        it "should send the raw post body" do
          expect(client).to receive(method).with(path, raw_post, nil)
          do_request
        end
      end

      context "when raw_post is not defined" do
        it "should send the params hash" do
          expect(client).to receive(method).with(path, params, nil)
          do_request
        end
      end

      it 'should set the scoped data ID' do
        expect(params['data']).to eq({'id' => 2})
      end

      it "should allow extra parameters to be passed in" do
        expect(client).to receive(method).with(path, params.merge("extra" => true), nil)
        do_request(:extra => true)
      end

      it "should overwrite parameters" do
        expect(client).to receive(method).with(path, params.merge("size" => "large"), nil)
        do_request(:size => "large")
      end

      it "should overwrite path variables" do
        expect(client).to receive(method).with("/orders/2", params, nil)
        do_request(:id => 2)
      end
    end

    describe "no_doc" do
      it "should not add requests" do |example|
        example.metadata[:requests] = ["first request"]

        no_doc do
          expect(example.metadata[:requests]).to be_empty
          example.metadata[:requests] = ["not documented"]
        end

        expect(example.metadata[:requests]).to eq(["first request"])
      end
    end
  end

  put "/orders/{id}" do
    describe "url params with curly braces" do
      it "should overwrite path variables" do
        expect(client).to receive(method).with("/orders/2", params, nil)
        do_request(:id => 2)
      end
    end
  end

  get "/orders/:order_id/line_items/:id" do
    parameter :type, "The type document you want"

    describe "do_request" do
      it "should correctly set path variables and other parameters" do
        expect(client).to receive(method).with("/orders/3/line_items/2?type=short", nil, nil)
        do_request(:id => 2, :order_id => 3, :type => 'short')
      end
    end
  end

  get "/orders/{order_id}/line_items/{id}" do
    describe "url params with curly braces" do
      it "should overwrite path variables and other parameters" do
        expect(client).to receive(method).with("/orders/3/line_items/2?type=short", nil, nil)
        do_request(:id => 2, :order_id => 3, :type => 'short')
      end
    end
  end

  get "/orders/:order_id" do
    let(:order) { double(:id => 1) }

    describe "path" do
      subject { self.path }

      context "when id has been defined" do
        let(:order_id) { order.id }

        it "should have the value of id subtituted for :id" do
          expect(subject).to eq("/orders/1")
        end
      end

      context "when id has not been defined" do
        it "should be unchanged" do
          expect(subject).to eq("/orders/%3Aorder_id")
        end
      end
    end
  end

  describe "nested parameters" do
    parameter :per_page, "Number of results on a page"

    it "should only have 1 parameter" do |example|
      expect(example.metadata[:parameters].length).to eq(1)
    end

    context "another parameter" do
      parameter :page, "Current page"

      it 'should have 2 parameters' do |example|
        expect(example.metadata[:parameters].length).to eq(2)
      end
    end
  end

  describe "nested response_fields" do
    response_field :per_page, "Number of results on a page"

    context "another response field" do
      response_field :page, "Current page"

      it "should have 2 response fields" do |example|
        expect(example.metadata[:response_fields].length).to eq(2)
      end
    end
  end

  callback "Order creation notification callback" do
    it "should provide a destination" do
      expect(destination).to be_a(RspecApiDocumentation::TestServer)
    end

    it "should return the same destination every time" do
      expect(destination).to equal(destination)
    end

    describe "trigger_callback" do
      let(:callback_url) { "http://example.com/callback-url" }
      let(:callbacks_triggered) { [] }

      trigger_callback do
        callbacks_triggered << nil
      end

      it "should get called once when do_callback is called" do
        do_callback
        expect(callbacks_triggered.length).to eq(1)
      end
    end

    describe "do_callback" do
      trigger_callback do
        uri = URI.parse(callback_url)
        Net::HTTP.start(uri.host, uri.port) do |http|
          http.request Net::HTTP::Post.new(uri.path)
        end
      end

      context "when callback_url is defined" do
        let(:callback_url) { "http://www.example.net/callback" }

        it "should mock requests to the callback url to be handled by the destination" do
          called = false
          allow(destination).to receive(:call) do
            called = true
            [200, {}, []]
          end
          do_callback
          expect(called).to be_truthy
        end
      end

      context "when callback_url is not defined" do
        it "should raise an exception" do
          expect { do_callback }.to raise_error("You must define callback_url")
        end
      end
    end

    describe "post vs get data" do
      parameter :id, "User id"
      parameter :page, "Page to list"
      parameter :message, "Message on the order"

      let(:message) { "Thank you" }
      let(:page) { 2 }
      let(:id) { 1 }

      get "/users/:id/orders" do
        example "Page should be in the query string" do
          expect(client).to receive(method) do |path, data, headers|
            expect(path).to match(/^\/users\/1\/orders\?/)
            expect(path.split("?")[1].split("&").sort).to eq("page=2&message=Thank+you".split("&").sort)
            expect(data).to be_nil
            expect(headers).to be_nil
          end
          do_request
        end
      end

      post "/users/:id/orders" do
        example "Page should be in the post body" do
          expect(client).to receive(method).with("/users/1/orders", {"page" => 2, "message" => "Thank you"}, nil)
          do_request
        end
      end
    end
  end

  context "#app" do
    it "should provide access to the configurations app" do
      expect(app).to eq(RspecApiDocumentation.configuration.app)
    end

    context "defining a new app, in an example" do
      let(:app) { "Sinatra" }

      it "should use the user defined app" do
        expect(app).to eq("Sinatra")
      end
    end
  end

  context "#explanation" do
    post "/orders" do
      route_summary "Route summary"
      route_description "Route description"

      example "Creating an order" do |example|
        explanation "By creating an order..."
        expect(example.metadata[:explanation]).to eq("By creating an order...")
        expect(example.metadata[:route_summary]).to eq("Route summary")
        expect(example.metadata[:route_description]).to eq("Route description")
      end

      context "Nested context" do
        example "Inner example" do |example|
          expect(example.metadata[:explanation]).to be_nil
          expect(example.metadata[:route_summary]).to eq("Route summary")
          expect(example.metadata[:route_description]).to eq("Route description")
        end
      end
    end
  end

  context "proper query_string serialization" do
    get "/orders" do
      context "with an array parameter" do
        parameter :id_eq, "List of IDs"

        let(:id_eq) { [1, 2] }

        example "parsed properly" do
          expect(client).to receive(:get) do |path, data, headers|
            expect(Rack::Utils.parse_nested_query(path.gsub('/orders?', ''))).to eq({"id_eq"=>['1', '2']})
          end
          do_request
        end
      end

      context "with a deep nested parameter, including Hashes and Arrays" do
        parameter :within_id, "Fancy search condition", :scope => :search

        let(:within_id) { {"first" => 1, "last" => 10, "exclude" => [3,5,7]} }

        example "parsed properly" do
          expect(client).to receive(:get) do |path, data, headers|
            expect(Rack::Utils.parse_nested_query(path.gsub('/orders?', ''))).to eq({
              "search" => { "within_id" => {"first" => '1', "last" => '10', "exclude" => ['3','5','7']}}
            })
          end
          do_request
        end
      end

      context "with reserved name parameter" do
        context "without custom method name" do
          parameter :status, "Filter order by status"

          example "does not work as expected" do
            expect { do_request }.to raise_error Rack::Test::Error, /No response yet/
          end
        end

        context "with custom method name" do
          parameter :status, "Filter order by status", method: :status_param

          context "when parameter value is not specified" do
            example "does not serialize param" do
              expect(client).to receive(method).with("/orders", anything, anything)
              do_request
            end
          end

          context "when parameter value is specified" do
            let(:status_param) { "pending" }

            example "serializes param" do
              expect(client).to receive(method).with("/orders?status=pending", anything, anything)
              do_request
            end
          end
        end
      end
    end
  end

  context "auto request" do
    post "/orders" do
      parameter :order_type, "Type of order"
      parameter :amount, "Amount of order", scope: :order
      parameter :name, "Name of order", scope: :order
      parameter :street, "order location country", scope: [:order,:location,:address]

      context "no extra params" do
        before do
          expect(client).to receive(:post).with("/orders", {}, nil)
        end

        example_request "Creating an order"

        example_request "should take a block" do
          params
        end
      end

      context "extra options for do_request" do
        before do
          expect(client).to receive(:post).with("/orders", {"order_type" => "big"}, nil)
        end

        example_request "should take an optional parameter hash", :order_type => "big"
      end

      context "extra options for do_request with scoped hash" do
        before do
          expect(client).to receive(:post).with("/orders", {"order_type" => "big", "order" => {"amount" => "19.99", "name" => "Friday Order"}}, nil)
        end

        let(:amount) { '19.99' }
        let(:name) { 'Monday Order' }

        example_request "should deep merge the optional parameter hash", {:order_type => 'big', :order => {:name => 'Friday Order'}}
      end

      context "extra options for do_request with nested scope" do
        before do
          expect(client).to receive(:post).with("/orders", {"order" => {"location" => {"address" => {"street" => "123 Main St"}}}}, nil)
        end

        let(:street) { '123 Main St' }

        example_request "should deep merge the optional parameter hash with nested scope"
      end
    end
  end

  context "request with only extra params" do
    post "/orders" do
      context "extra options for do_request" do
        before do
          expect(client).to receive(:post).with("/orders", {"order_type" => "big"}, nil)
        end

        example_request "should take an optional parameter hash", :order_type => "big"
      end
    end
  end

  context "last_response helpers" do
    put "/orders" do
      it "status" do
        allow(client).to receive(:last_response).and_return(double(:status => 200))
        expect(status).to eq(200)
      end

      it "response_body" do
        allow(client).to receive(:last_response).and_return(double(:body => "the body"))
        expect(response_body).to eq("the body")
      end
    end
  end

  context "headers" do
    put "/orders" do
      header "Accept", "application/json"

      it "should be sent with the request" do |example|
        expect(example.metadata[:headers]).to eq({ "Accept" => "application/json" })
      end

      context "nested headers" do
        header "Content-Type", "application/json"

        it "does not affect the outer context's assertions" do
          # pass
        end
      end
    end

    put "/orders" do
      context "setting header in example level" do
        before do
          header "Accept", "application/json"
          header "Content-Type", "application/json"
        end

        it "adds to headers" do
          expect(headers).to eq({ "Accept" => "application/json", "Content-Type" => "application/json" })
        end
      end
    end

    put "/orders" do
      header "Accept", :accept

      let(:accept) { "application/json" }

      it "should be sent with the request" do |example|
        expect(example.metadata[:headers]).to eq({ "Accept" => :accept })
      end

      it "should fill out into the headers" do
        expect(headers).to eq({ "Accept" => "application/json" })
      end

      context "nested headers" do
        header "Content-Type", "application/json"

        it "does not affect the outer context's assertions" do
          expect(headers).to eq({ "Accept" => "application/json", "Content-Type" => "application/json" })
        end
      end

      context "header was not let" do
        header "X-My-Header", :my_header

        it "should not be in the headers hash" do
          expect(headers).to eq({ "Accept" => "application/json" })
        end
      end
    end
  end

  context "authentications" do
    put "/orders" do
      authentication :apiKey, "Api Key", :name => "API_AUTH"
      authentication :basic, "Api Key"

      it "should be sent with the request" do |example|
        expect(example.metadata[:authentications]).to eq(
          {
            "API_AUTH" => {
              :in => :header,
              :type => :apiKey,
              :name => "API_AUTH"
            },
            "Authorization" => {
              :type => :basic
            }
          })
      end

      context "nested authentications" do
        authentication :apiKey, "Api Key", :name => "API_AUTH"

        it "does not affect the outer context's assertions" do
          # pass
        end
      end
    end

    put "/orders" do
      context "setting authentication in example level" do
        before do
          authentication :apiKey, "Api Key", :name => "API_AUTH"
        end

        it "adds to headers" do |example|
          expect(example.metadata[:authentications]).to eq({"API_AUTH" => {
            :in => :header,
            :type => :apiKey,
            :name => "API_AUTH"
          }})
        end
      end
    end

    put "/orders" do
      authentication :apiKey, :api_key, :name => "API_AUTH"

      let(:api_key) { "API_KEY_TOKEN" }

      it "should be sent with the request" do |example|
        expect(example.metadata[:authentications]).to eq({"API_AUTH" => {
          :in => :header,
          :type => :apiKey,
          :name => "API_AUTH"
        }})
      end

      it "should fill out into the headers" do
        expect(headers).to eq({ "API_AUTH" => "API_KEY_TOKEN" })
      end

      context "nested authentications" do
        authentication :apiKey, :api_key, :name => "API_AUTH"

        it "does not affect the outer context's assertions" do
          expect(headers).to eq({ "API_AUTH" => "API_KEY_TOKEN" })
        end
      end
    end
  end

  context "post body formatter" do
    after do
      RspecApiDocumentation.instance_variable_set(:@configuration, RspecApiDocumentation::Configuration.new)
    end

    get "/orders" do
      specify "formatting by json without parameters" do
        RspecApiDocumentation.configure do |config|
          config.request_body_formatter = :json
        end

        expect(client).to receive(method).with(path, nil, nil)

        do_request
      end
    end

    post "/orders" do
      parameter :page, "Page to view"

      let(:page) { 1 }

      specify "formatting by json" do
        RspecApiDocumentation.configure do |config|
          config.request_body_formatter = :json
        end

        expect(client).to receive(method).with(path, { :page => 1 }.to_json , nil)

        do_request
      end

      specify "formatting by json via legacy config" do
        RspecApiDocumentation.configure do |config|
          config.post_body_formatter = :json
        end

        expect(client).to receive(method).with(path, { :page => 1 }.to_json , nil)

        do_request
      end

      specify "formatting by xml" do
        RspecApiDocumentation.configure do |config|
          config.request_body_formatter = :xml
        end

        expect(client).to receive(method).with(path, { :page => 1 }.to_xml , nil)

        do_request
      end

      specify "formatting by proc" do
        RspecApiDocumentation.configure do |config|
          config.request_body_formatter = Proc.new do |params|
            { :from => "a proc" }.to_json
          end
        end

        expect(client).to receive(method).with(path, { :from => "a proc" }.to_json , nil)

        do_request
      end
    end
  end

  route "/orders{?application_id=:some_id}", "Orders Collection" do
    attribute :description, "Order description"

    it "saves the route URI" do |example|
      expect(example.metadata[:route_uri]).to eq "/orders"
    end

    it "saves the route optionals" do |example|
      expect(example.metadata[:route_optionals]).to eq "{?application_id=:some_id}"
    end

    it "saves the route name" do |example|
      expect(example.metadata[:route_name]).to eq "Orders Collection"
    end

    it "has 1 attribute" do |example|
      expect(example.metadata[:attributes]).to eq [{
        name: "description",
        description: "Order description"
      }]
    end

    get("Returns all orders") do
      it "uses the route URI" do
        expect(example.metadata[:route]).to eq "/orders"
      end

      it "bubbles down the parent group metadata" do
        expect(example.metadata[:method]).to eq :get
      end
    end
  end

  get "parameter with custom method only" do
    parameter :custom, "Custom name parameter", method: :custom_method, scope: :some

    context do
      let(:custom) { "Should not be taken" }
      let(:some_custom) { "Should not be taken" }

      it "not uses custom as value" do
        expect(params).to eq({})
      end
    end

    context do
      let(:custom_method) { "Should be taken" }

      it "uses custom_method as value" do
        expect(params).to eq("some" => {"custom" => "Should be taken"})
      end
    end
  end
end

resource "top level parameters" do
  parameter :page, "Current page"

  it 'should have 1 parameter' do |example|
    expect(example.metadata[:parameters].length).to eq(1)
  end
end

resource "top level response fields" do
  response_field :page, "Current page"

  it 'should have 1 response field' do |example|
    expect(example.metadata[:response_fields].length).to eq(1)
  end
end

resource "passing in document to resource", :document => :not_all do
  it "should have the correct tag" do |example|
    expect(example.metadata[:document]).to eq(:not_all)
  end
end

class Order; end
resource Order do
  it 'should have a string resource_name' do |example|
    expect(example.metadata[:resource_name]).to eq(Order.to_s)
  end
end


text:
package io.mandrel.cluster.discovery.zookeeper;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import org.apache.curator.RetryPolicy;
import org.apache.curator.ensemble.EnsembleProvider;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.details.InstanceSerializer;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(value = "discovery.zookeeper.enabled", matchIfMissing = false)
@EnableConfigurationProperties
@Slf4j
public class ZookeeperAutoConfiguration {

	@Autowired(required = false)
	private EnsembleProvider ensembleProvider;

	@Autowired
	private ZookeeperDiscoveryProperties zookeeperProperties;

	@Bean
	public InstanceSerializer<ZookeeperInstance> instanceSerializer() {
		return new JsonInstanceSerializer<>(ZookeeperInstance.class);
	}

	@Bean(destroyMethod = "close")
	@ConditionalOnMissingBean
	@SneakyThrows
	public CuratorFramework curatorFramework(RetryPolicy retryPolicy, ZookeeperDiscoveryProperties properties) {
		CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
		if (ensembleProvider != null) {
			builder.ensembleProvider(ensembleProvider);
		}
		CuratorFramework curator = builder.retryPolicy(retryPolicy).connectString(zookeeperProperties.getConnectString()).build();
		curator.start();

		log.trace("blocking until connected to zookeeper for " + properties.getBlockUntilConnectedWait() + properties.getBlockUntilConnectedUnit());
		curator.blockUntilConnected(properties.getBlockUntilConnectedWait(), properties.getBlockUntilConnectedUnit());
		log.trace("connected to zookeeper");
		return curator;
	}

	@Bean
	@SneakyThrows
	public ServiceDiscovery<ZookeeperInstance> serviceDiscovery(CuratorFramework curatorFramework, InstanceSerializer<ZookeeperInstance> instanceSerializer,
			ZookeeperDiscoveryProperties zookeeperProperties) {
		ServiceDiscovery<ZookeeperInstance> serviceDiscovery = ServiceDiscoveryBuilder.builder(ZookeeperInstance.class).client(curatorFramework)
				.basePath(zookeeperProperties.getRoot()).serializer(instanceSerializer).build();
		serviceDiscovery.start();
		return serviceDiscovery;
	}

	@Bean
	@ConditionalOnMissingBean
	public RetryPolicy exponentialBackoffRetry() {
		return new ExponentialBackoffRetry(zookeeperProperties.getBaseSleepTimeMs(), zookeeperProperties.getMaxRetries(), zookeeperProperties.getMaxSleepMs());
	}
}