text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ixaris.ope</groupId>
  <artifactId>ope-applications-java-client</artifactId>
  <packaging>jar</packaging>
  <name>ope-applications-java-client</name>
  <version>1.0.0</version>
  <url>https://github.com/swagger-api/swagger-codegen</url>
  <description>Swagger Java</description>
  <scm>
    <connection>scm:git:git://github.com/ixaris/ope-applicationclients.git</connection>
    <developerConnection>scm:git:git@github.com:ixaris/ope-applicationclients.git</developerConnection>
    <url>https://github.com/ixaris/ope-applicationclients</url>
  </scm>
  <prerequisites>
    <maven>2.2.0</maven>
  </prerequisites>

  <licenses>
    <license>
      <name>MIT License</name>
      <url>http://www.opensource.org/licenses/mit-license.php</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <developers>
    <developer>
      <name>Aldrin Seychell</name>
      <email>aldrin.seychell@ixaris.com</email>
      <organization>Ixaris Ltd.</organization>
      <organizationUrl>http://ixaris.com</organizationUrl>
    </developer>
  </developers>

  <distributionManagement>
    <snapshotRepository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
  </distributionManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.sonatype.plugins</groupId>
        <artifactId>nexus-staging-maven-plugin</artifactId>
        <version>1.6.7</version>
        <extensions>true</extensions>
        <configuration>
           <serverId>ossrh</serverId>
           <nexusUrl>https://oss.sonatype.org/</nexusUrl>
           <autoReleaseAfterClose>true</autoReleaseAfterClose>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12</version>
        <configuration>
          <systemProperties>
            <property>
              <name>loggerPath</name>
              <value>conf/log4j.properties</value>
            </property>
          </systemProperties>
          <argLine>-Xms512m -Xmx1500m</argLine>
          <parallel>methods</parallel>
          <forkMode>pertest</forkMode>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <!-- attach test jar -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.2</version>
        <executions>
          <execution>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.10</version>
        <executions>
          <execution>
            <id>add_sources</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>add-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>src/main/java</source>
              </sources>
            </configuration>
          </execution>
          <execution>
            <id>add_test_sources</id>
            <phase>generate-test-sources</phase>
            <goals>
              <goal>add-test-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>src/test/java</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.10.4</version>
        <executions>
          <execution>
            <id>attach-javadocs</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.2.1</version>
        <executions>
          <execution>
            <id>attach-sources</id>
            <goals>
              <goal>jar-no-fork</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>sign-artifacts</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <version>1.5</version>
            <executions>
              <execution>
                <id>sign-artifacts</id>
                <phase>verify</phase>
                <goals>
                  <goal>sign</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

  <dependencies>
    <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-annotations</artifactId>
      <version>${swagger-core-version}</version>
    </dependency>
    <dependency>
      <groupId>com.squareup.okhttp</groupId>
      <artifactId>okhttp</artifactId>
      <version>${okhttp-version}</version>
    </dependency>
    <dependency>
      <groupId>com.squareup.okhttp</groupId>
      <artifactId>logging-interceptor</artifactId>
      <version>${okhttp-version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>${gson-version}</version>
    </dependency>
    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>${jodatime-version}</version>
    </dependency>
    <!-- test dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit-version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <properties>
    <java.version>1.7</java.version>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    <swagger-core-version>1.5.12</swagger-core-version>
    <okhttp-version>2.7.5</okhttp-version>
    <gson-version>2.6.2</gson-version>
    <jodatime-version>2.9.3</jodatime-version>
    <maven-plugin-version>1.0.0</maven-plugin-version>
    <junit-version>4.12</junit-version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>


text:
/*	$NetBSD: clnp_timer.c,v 1.8 1997/06/24 02:26:08 thorpej Exp $	*/

/*-
 * Copyright (c) 1991, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)clnp_timer.c	8.1 (Berkeley) 6/10/93
 */

/***********************************************************
		Copyright IBM Corporation 1987

                      All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of IBM not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

******************************************************************/

/*
 * ARGO Project, Computer Sciences Dept., University of Wisconsin - Madison
 */

#include <sys/param.h>
#include <sys/mbuf.h>
#include <sys/domain.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/errno.h>

#include <net/if.h>
#include <net/route.h>

#include <netiso/iso.h>
#include <netiso/clnp.h>
#include <netiso/clnp_stat.h>
#include <netiso/argo_debug.h>

extern struct clnp_fragl *clnp_frags;

/*
 * FUNCTION:		clnp_freefrags
 *
 * PURPOSE:			Free the resources associated with a fragment
 *
 * RETURNS:			pointer to next fragment in list of fragments
 *
 * SIDE EFFECTS:
 *
 * NOTES:
 *			TODO: send ER back to source
 */
struct clnp_fragl *
clnp_freefrags(cfh)
	register struct clnp_fragl *cfh;	/* fragment header to delete */
{
	struct clnp_fragl *next = cfh->cfl_next;
	struct clnp_frag *cf;

	/* free any frags hanging around */
	cf = cfh->cfl_frags;
	while (cf != NULL) {
		struct clnp_frag *cf_next = cf->cfr_next;
		INCSTAT(cns_fragdropped);
		m_freem(cf->cfr_data);
		cf = cf_next;
	}

	/* free the copy of the header */
	INCSTAT(cns_fragdropped);
	m_freem(cfh->cfl_orighdr);

	if (clnp_frags == cfh) {
		clnp_frags = cfh->cfl_next;
	} else {
		struct clnp_fragl *scan;

		for (scan = clnp_frags; scan != NULL; scan = scan->cfl_next) {
			if (scan->cfl_next == cfh) {
				scan->cfl_next = cfh->cfl_next;
				break;
			}
		}
	}

	/* free the fragment header */
	FREE(cfh, M_FTABLE);

	return (next);
}

/*
 * FUNCTION:		clnp_slowtimo
 *
 * PURPOSE:			clnp timer processing; if the ttl expires on a
 *					packet on the reassembly queue, discard it.
 *
 * RETURNS:			none
 *
 * SIDE EFFECTS:
 *
 * NOTES:
 */
void
clnp_slowtimo()
{
	register struct clnp_fragl *cfh = clnp_frags;
	int             s = splsoftnet();

	while (cfh != NULL) {
		if (--cfh->cfl_ttl == 0) {
			cfh = clnp_freefrags(cfh);
			INCSTAT(cns_fragtimeout);
		} else {
			cfh = cfh->cfl_next;
		}
	}
	splx(s);
}

/*
 * FUNCTION:		clnp_drain
 *
 * PURPOSE:			drain off all datagram fragments
 *
 * RETURNS:			none
 *
 * SIDE EFFECTS:
 *
 * NOTES:
 *	TODO: should send back ER
 */
void
clnp_drain()
{
	register struct clnp_fragl *cfh = clnp_frags;

	while (cfh != NULL)
		cfh = clnp_freefrags(cfh);
}

redpajama_set_name: RedPajamaGithub


text:
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils
from copy import deepcopy

def main(filename, mode):

    raw_text = ''
    with open(filename) as fp:
        raw_text = fp.read()

    raw_text = raw_text.lower()

    # create mapping of unique chars to integers

    chars = sorted(list(set(raw_text)))
    char_to_int = dict((c, i) for i, c in enumerate(chars))
    int_to_char = dict((i, c) for i, c in enumerate(chars))

    n_chars = len(raw_text)
    n_vocab = len(chars)
    print('Total characters: {}'.format(n_chars))
    print('Total vocab: {}'.format(n_vocab))

    # prepare the dataset of input to output pairs encoded as integers

    seq_length = 50
    dataX = []
    dataY = []
    for i in range(0, n_chars - seq_length, 1):
        seq_in = raw_text[i:i+seq_length]
        seq_out = raw_text[i + seq_length]
        dataX.append([char_to_int[char] for char in seq_in])
        dataY.append(char_to_int[seq_out])
    n_patterns = len(dataX)

    print('Total patterns: {}'.format(n_patterns))

    # reshape X to be [samples, time steps, features]

    X = numpy.reshape(dataX, (n_patterns, seq_length, 1))

    # normalize

    X = X / float(n_vocab)

    # one hot encode the output variable

    y = np_utils.to_categorical(dataY)

    # define the LSTM model

    model = Sequential()
    model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(256))
    model.add(Dropout(0.2))
    model.add(Dense(y.shape[1], activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam')

    if mode == 'create':
        create_rnn(X, y, model)
    elif mode == 'predict':
        generate(dataX, int_to_char, n_vocab, model)

def create_rnn(X, y, model):

    # define the checkpoint

    filepath = 'checkpoints/weights-improvement-{epoch:02d}-{loss:.4f}.hdf5'
    checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
    callbacks_list = [checkpoint]

    model.fit(X, y, validation_split=0.1, epochs=50, batch_size=50, callbacks=callbacks_list)

def generate(dataX, int_to_char, n_vocab, model):

    # load the network weights
    filename = "checkpoints/weights-improvement-12-1.0078.hdf5"
    model.load_weights(filename)
    model.compile(loss='categorical_crossentropy', optimizer='adam')
    # pick a random seed
    start = numpy.random.randint(0, len(dataX)-1)

    for diversity in [0.3]:
        pattern = deepcopy(dataX[start])

        # print("Diversity: {} Seed:".format(diversity))
        # print("\"" + ''.join([int_to_char[value] for value in pattern]) + "\"")

        # generate characters
        for i in range(10000):
            x = numpy.reshape(pattern, (1, len(pattern), 1))
            x = x / float(n_vocab)
            prediction = model.predict(x, verbose=0)
            index = sample(prediction, diversity)
            result = int_to_char[index]
            seq_in = [int_to_char[value] for value in pattern]
            print(result, end='')
            pattern.append(index)
            pattern = pattern[1:len(pattern)]
        # print("\nDone.")

def sample(preds, temperature=1.0):
    # helper function to sample an index from a probability array
    preds = numpy.asarray(preds).astype('float64')
    preds = numpy.log(preds) / temperature
    exp_preds = numpy.exp(preds)
    preds = exp_preds / numpy.sum(exp_preds)
    probas = numpy.random.multinomial(1, preds[0], 1)
    return numpy.argmax(probas)

if __name__=='__main__':
    import sys
    sys.exit(main(sys.argv[1], sys.argv[2]))


text:
class ValidateNamePresenceOnSubjects < ActiveRecord::Migration
  def change
    change_column :subjects, :name, :string, null: false
  end
end


text:
namespace boost { namespace mpl {

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    >
struct size
    : aux::msvc_eti_base<
        typename size_impl< typename sequence_tag<Sequence>::type >
            ::template apply< Sequence >::type
      >::type
{
    BOOST_MPL_AUX_LAMBDA_SUPPORT(1, size, (Sequence))
};

BOOST_MPL_AUX_NA_SPEC(1, size)

}}

#endif // BOOST_MPL_SIZE_HPP_INCLUDED


text:
Download and install [tt-rss-mobilete](https://github.com/hugosenari/tt-rss-mobilete/) at your Tiny Tiny Rss OpenShift instalation as /mobilete/index.html.

# Install

Use webconsole or command below

```
rhc add-cartridge https://raw.githubusercontent.com/hugosenari/tt-rss-mobilete-cart/master/metadata/manifest.yml --app APP_NAME
```


text:
> The Fishshell Framework

[![MIT License](https://img.shields.io/badge/license-MIT-007EC7.svg?style=flat-square)](/LICENSE.md) [![Fish Shell Version](https://img.shields.io/badge/fish-v2.2.0-007EC7.svg?style=flat-square)](http://fishshell.com) [![Travis Build Status](http://img.shields.io/travis/oh-my-fish/oh-my-fish.svg?style=flat-square)](https://travis-ci.org/oh-my-fish/oh-my-fish) [![Slack Status](https://oh-my-fish-slack.herokuapp.com/badge.svg)](https://oh-my-fish-slack.herokuapp.com)

Oh My Fish provides core infrastructure to allow you to install packages which extend or modify the look of your shell. It's fast, extensible and easy to use.

> Also in
> 🇷🇺
> 🇨🇳

## Installation

You can get started right away with the default setup by running this in your terminal:

```fish
curl -L http://get.oh-my.fish | fish
```

This will download the installer script and start the installation. Alternatively, you can download the installer and customize your install:

```fish
curl -L http://get.oh-my.fish > install
fish install --path=~/.local/share/omf --config=~/.config/omf
```

You can also install Oh My Fish with Git or with an offline source tarball downloaded from the [releases page][releases]:

```fish
# with git
$ git clone https://github.com/oh-my-fish/oh-my-fish
$ cd oh-my-fish
$ bin/install --offline
# with a tarball
$ curl -L http://get.oh-my.fish > install
$ fish install --offline=omf.tar.gz
```

Run `install --help` for a complete list of install options you can customize.

## Getting Started

Oh My Fish includes a small utility `omf` to fetch and install new packages and themes.

#### `omf update` _`[omf]`_ _`[<package>...]`_

Update the framework and installed packages.

- When called without arguments, update core and all installed packages.
- You can choose to update only the core, by running `omf update omf`.
- For selective package update, list only the names of packages you wish to
  update. You may still include "omf" in the list to update the core as well.

#### `omf install` _`[<name>|<url>]`_

Install one _or more_ packages.

- You can install packages directly by URL via `omf install URL`
- When called without arguments, install missing packages from [bundle](#dotfiles).

#### `omf list`

List installed packages.

#### `omf theme` _`<theme>`_

Apply a theme. To list available themes, type `omf theme`. You can also [preview available themes](./docs/Themes.md) before installing.

#### `omf remove` _`<name>`_

Remove a theme or package.

> Packages can use uninstall hooks, so custom cleanup of resources can be done when uninstalling it. See [Uninstall](/docs/en-US/Packages.md#uninstall) for more information.

#### `omf reload`

Reload Oh My Fish and all plugins by using `exec` to replace current shell process with a brand new.

> This command tries to be as safe as possible, mitigating side-effects caused by `exec` and preventing the reload in case of background processes.

#### `omf new pkg | theme` _`<name>`_

Scaffold out a new package or theme.

> This creates a new directory under `$OMF_CONFIG/{pkg | themes}/` with a template.

#### `omf search` _`-t|--theme / -pkg|--package`_ _`<name>`_

Searches Oh My Fish's database for a given package, theme or both. It also supports fuzzy search, so if you are not sure of the name you can simply `omf search simple`.

#### `omf submit` _`pkg/<name>`_ _`[<url>]`_

Add a new package. To add a theme, use `omf submit` _`themes/<name>`_ _`<url>`_.
Please note that the _`[<url>]`_ portion of the command should be the url to your repo on github. For example, with the `example` plugin, the command run should be `omf submit pkg/example https://github.com/oh-my-fish/example`.

Make sure to [send us a PR][omf-pulls-link] to update the registry.

#### `omf channel`

Gets or changes the update channel.

Two channels are available by default: the `stable` channel provides stable updates with the latest tagged version of Oh My Fish, and `dev` which provides the latest changes under development. The update channel currently set determines what version `omf update` will upgrade to.

#### `omf doctor`

Use to troubleshoot before [opening an issue][omf-issues-new].

#### `omf destroy`

Uninstall Oh My Fish.

## Advanced

Oh My Fish installer places its startup code in your fish config file (`~/.config/fish/config.fish`).

### Startup

Every time you open a new shell, the startup code initializes Oh My Fish installation path and the _config_ path (`~/.config/omf` by default), sourcing the [`init.fish`](init.fish) script afterwards, which autoloads packages, themes and your custom init files.

For more information check the [FAQ](docs/en-US/FAQ.md#what-does-oh-my-fish-do-exactly).

### Dotfiles

The `$OMF_CONFIG` directory represents the user state of Oh My Fish. It is the perfect
candidate for being added to your dotfiles and/or checked out to version control. There are four important files:

- __`theme`__ - The current theme
- __`bundle`__ - List of currently installed packages/themes
- __`init.fish`__ - Custom script sourced after shell start
- __`before.init.fish`__ - Custom script sourced before shell start
- __`key_bindings.fish`__ - Custom key bindings where you can use the `bind` command freely

It's highly recommended that your custom startup commands go into `init.fish` file instead of `~/.config/fish/config.fish`, as this allows you to keep the whole `$OMF_CONFIG` directory under version control.

If you need startup commands to be run *before* Oh My Fish begins loading plugins, place them in `before.init.fish` instead. If you're unsure, it is usually best to put things in `init.fish`.

#### About the bundle

Every time a package/theme is installed or removed, the `bundle` file is updated. You can also edit it manually and run `omf install` afterwards to satisfy the changes. Please note that while packages/themes added to the bundle get automatically installed, a package/theme removed from bundle isn't removed from user installation.

## Creating Packages

Oh My Fish uses an advanced and well defined plugin architecture to ease plugin development, including init/uninstall hooks, function and completion autoloading. [See the packages documentation](docs/en-US/Packages.md) for more details.

[fishshell]: http://fishshell.com
[contributors]: https://github.com/oh-my-fish/oh-my-fish/graphs/contributors
[omf-pulls-link]: https://github.com/oh-my-fish/oh-my-fish/pulls
[omf-issues-new]: https://github.com/oh-my-fish/oh-my-fish/issues/new
[releases]: https://github.com/oh-my-fish/oh-my-fish/releases


text:
package md5viewer
import utils._
import scala.util.parsing.combinator._
import scala.util.matching.Regex
import scala.util.parsing.combinator.lexical._
import scala.collection.mutable.HashSet
import scala.io.Source
import collection.immutable.HashMap
import scala.util.parsing.combinator.syntactical.TokenParsers
import scala.util.parsing.combinator.token.Tokens
import scala.util.parsing.input.CharArrayReader.EofCh

object MD5Loader {
  class LoadingError(cause: String) extends RuntimeException(cause.toString)

  def removeComments (text: String) : String = {
    val regexp = """(?m)//[^"\r\n]*$""".r
    return regexp.replaceAllIn(text, "")
  }

  //Helper function, checks that expected == loaded.length and throw exception if not. Returns loaded on success
  def checkNum[T] (what: String, expected: Int, loaded: List[T]) : List[T] = {
    if (expected != loaded.length) {
      throw new LoadingError("Inconsistent "+what+"("+expected+") and loaded number: " + loaded.length)
    }
    loaded
  }

  def loadModel (file: String) : MD5Model = {
    val lines = io.Source.fromFile(file).mkString
    val p = new MD5ModelParser
    val model = p.parse(lines) match {
      case p.Success(m,_) => m
      case x => throw new Exception("Error loading : " + x)
    }
    model
  }

  def loadAnim (file: String) : MD5Anim = {
    val lines = io.Source.fromFile(file).mkString
    val p = new MD5AnimParser
    val anim = p.parse(lines) match {
      case p.Success(a,_) => a
      case x => throw new Exception("Error loading : " + x)
    }
    anim
  }

  class MD5GenericParser extends TokenParsers {
    override type Tokens = MD5Tokens
    override val lexical = new MD5Lexical

    protected val keywordCache : collection.mutable.HashMap[String, Parser[String]] = collection.mutable.HashMap.empty

    import lexical.{StringLit, NumericLit, Keyword}

    implicit def keyword(chars: String): Parser[String] =
      keywordCache.getOrElseUpdate(chars, accept(Keyword(chars)) ^^ (_.chars))

    def LBRACE = Keyword("{")
    def RBRACE = Keyword("}")
    def LPAREN = Keyword("(")
    def RPAREN = Keyword(")")
    def braces[T](p: => Parser[T]): Parser[T] = LBRACE ~> p <~ RBRACE
    def parens[T](p: => Parser[T]): Parser[T] = LPAREN ~> p <~ RPAREN

    def numericLit: Parser[String] =
      elem("number", _.isInstanceOf[NumericLit]) ^^ (_.chars)

    def stringLit: Parser[String] =
      elem("string literal", _.isInstanceOf[StringLit]) ^^ (_.chars)

    def version = keyword("MD5Version") ~> intNumber

    def commandline = keyword("commandline") ~> stringLit

    def floatNumber = numericLit ^^ { case lit => java.lang.Float.parseFloat(lit) }
    def intNumber = numericLit ^^ { _.toInt }

    def vector3 = parens(floatNumber ~ floatNumber ~ floatNumber) ^^ {
      case x ~ y ~ z => {
        new Vector3(x,y,z)
      }
    }
  }

  //A parser for MD5 model files. Calling parseAll(model, ...) will return a Model
  class MD5ModelParser extends MD5GenericParser {
    def parse(s:String) = {
      val tokens = new lexical.Scanner(s)
      phrase(model)(tokens)
    }

    def model = version ~ commandline ~ numJoints ~ numMeshes ~ joints ~ meshes ^^ {
      case v ~ cl ~ numJoints ~ numMeshes ~ joints ~ meshes => {
        new MD5Model(v, cl, checkNum("numJoints", numJoints, joints), checkNum("numMeshes", numMeshes, meshes))
      }
    }

    def numJoints = keyword("numJoints") ~> intNumber

    def numMeshes = keyword("numMeshes") ~> intNumber

    def joints = keyword("joints") ~> braces(rep(joint))

    var jointCnt = 0
    def joint = stringLit ~ intNumber ~ vector3 ~ vector3 ^^ {
      case name ~ parent ~ pos ~ compressedQuat => {
        val r = new Joint(jointCnt, name, parent, pos, new Quaternion(compressedQuat.x, compressedQuat.y, compressedQuat.z))
        jointCnt += 1
        r
      }
    }

    def meshes = rep(mesh)

    def mesh = keyword("mesh") ~> braces(shader ~ verts ~ tris ~ weights) ^^ {
      case shader ~ verts ~ tris ~ weights => {
        new Mesh(shader, verts, tris, weights)
      }
    }

    def shader = keyword("shader") ~> stringLit

    def verts = keyword("numverts") ~> intNumber ~ rep(vert) ^^ { case numVerts ~ verts =>
      checkNum("numVerts", numVerts, verts);
    }

    def vert = keyword("vert") ~> intNumber ~> parens(floatNumber ~ floatNumber) ~ intNumber ~ intNumber ^^ {
      case u ~ v ~ firstWeight ~ numWeights => {
        new Vert(u, v, firstWeight, numWeights)
      }
    }

    def tris = keyword("numtris") ~> intNumber ~ rep(tri) ^^ { case numTris ~ tris =>
      checkNum("numTris", numTris, tris);
    }
    def tri = keyword("tri") ~> intNumber ~ intNumber ~ intNumber ~ intNumber ^^ {
      case triNum ~ i1 ~ i2 ~ i3 => {
        new Tri(List(i1,i2,i3).toArray)
      }
    }

    def weights = keyword("numweights") ~> intNumber ~ rep(weight) ^^ { case numWeights ~ weights =>
      checkNum("numWeights", numWeights, weights)
    }
    def weight = keyword("weight") ~> intNumber ~ intNumber ~ floatNumber ~ vector3 ^^ {
      case weightNum ~ boneIndex ~ bias ~ w => {
        new Weight(boneIndex, bias, w)
      }
    }
  }

  class MD5AnimParser extends MD5GenericParser {
    def parse(s:String) = {
      val tokens = new lexical.Scanner(s)
      phrase(anim)(tokens)
    }

    def anim = version ~ commandline ~ numFrames ~ numJoints ~ frameRate ~ numAnimatedComponents ~ hierarchy ~ bounds ~ baseframe ~ rep(frame) ^^ {
      case version ~ commandline ~ numFrames ~ numJoints ~ frameRate ~ numAnimatedComponents ~ hierarchy ~ bounds ~ baseFrame ~ frames => {
        new MD5Anim(version, commandline, hierarchy, baseFrame, frames, frameRate)
      }
    }

    def numFrames = keyword("numFrames") ~> intNumber
    def numJoints = keyword("numJoints") ~> intNumber
    def frameRate = keyword("frameRate") ~> intNumber
    def numAnimatedComponents = keyword("numAnimatedComponents") ~> intNumber

    def hierarchy = keyword("hierarchy") ~> braces(rep(jointInfo))
    def jointInfo = stringLit ~ intNumber ~ intNumber ~ intNumber ^^ {
      case jointName ~ parent ~ flags ~ frameIndex => new JointInfo(parent, flags, frameIndex)
    }

    def bounds = keyword("bounds") ~> braces(rep(bound))
    def bound = vector3 ~ vector3

    def baseframe = keyword("baseframe") ~> braces(rep(bframe)) ^^ {
      new BaseFrame(_)
    }
    def bframe = vector3 ~ vector3 ^^ {
      case pos ~ rot => new JointBaseFrame(pos, new Quaternion(rot.x, rot.y, rot.z))
    }

    def frame = keyword("frame") ~> intNumber ~ braces(rep(floatNumber)) ^^ { case frameNum ~ comps => new Frame(comps.toArray) }
  }
}

// vim: set ts=2 sw=2 et:


text:
!function(Foundation, $) {
  'use strict';

  /**
   * Creates a new instance of Equalizer.
   * @class
   * @fires Equalizer#init
   * @param {Object} element - jQuery object to add the trigger to.
   * @param {Object} options - Overrides to the default plugin settings.
   */
  function Equalizer(element, options) {
    this.$element = element;
    this.options  = $.extend({}, Equalizer.defaults, this.$element.data(), options);
    this.$window  = $(window);
    this.name     = 'equalizer';
    this.attr     = 'data-equalizer';

    this._init();
    this._events();

    Foundation.registerPlugin(this);
  }

  /**
   * Default settings for plugin
   */
  Equalizer.defaults = {
    /**
     * Enable height equalization when stacked on smaller screens.
     * @option
     * @example true
     */
    equalizeOnStack: true,
    /**
     * Amount of time, in ms, to debounce the size checking/equalization. Lower times mean smoother transitions/less performance on mobile.
     * @option
     * @example 50
     */
    throttleInterval: 50
  };

  /**
   * Initializes the Equalizer plugin and calls functions to get equalizer functioning on load.
   * @private
   */
  Equalizer.prototype._init = function() {
    this._reflow();
  };

  /**
   * Initializes events for Equalizer.
   * @private
   */
  Equalizer.prototype._events = function() {
    var self = this;

    this.$window
      .off('.equalizer')
      .on('resize.fndtn.equalizer', Foundation.util.throttle(function () {
        self._reflow();
      }, self.options.throttleInterval));
  };

  /**
   * A noop version for the plugin
   * @private
   */
  Equalizer.prototype._killswitch = function() {
    return;
  };
  /**
   * Calls necessary functions to update Equalizer upon DOM change
   * @private
   */
  Equalizer.prototype._reflow = function() {
    var self = this;

    $('[' + this.attr + ']').each(function() {
      var $eqParent       = $(this),
          adjustedHeights = [],
          $images = $eqParent.find('img');

      if ($images.length) {
        Foundation.onImagesLoaded($images, function() {
          adjustedHeights = self.getHeights($eqParent);
          self.applyHeight($eqParent, adjustedHeights);
        });
      }
      else {
        adjustedHeights = self.getHeights($eqParent);
        self.applyHeight($eqParent, adjustedHeights);
      }
    });
  };
  /**
   * Finds the outer heights of children contained within an Equalizer parent and returns them in an array
   * @param {Object} $eqParent A jQuery instance of an Equalizer container
   * @returns {Array} heights An array of heights of children within Equalizer container
   */
  Equalizer.prototype.getHeights = function($eqParent) {
    var eqGroupName = $eqParent.data('equalizer'),
        eqGroup     = eqGroupName ? $eqParent.find('[' + this.attr + '-watch="' + eqGroupName + '"]:visible') : $eqParent.find('[' + this.attr + '-watch]:visible'),
        heights;

    eqGroup.height('inherit');
    heights = eqGroup.map(function () { return $(this).outerHeight(false);}).get();
    console.log(heights);
    return heights;
  };
  /**
   * Changes the CSS height property of each child in an Equalizer parent to match the tallest
   * @param {Object} $eqParent - A jQuery instance of an Equalizer container
   * @param {array} heights - An array of heights of children within Equalizer container
   * @fires Equalizer#preEqualized
   * @fires Equalizer#postEqualized
   */
  Equalizer.prototype.applyHeight = function($eqParent, heights) {
    var eqGroupName = $eqParent.data('equalizer'),
        eqGroup     = eqGroupName ? $eqParent.find('['+this.attr+'-watch="'+eqGroupName+'"]:visible') : $eqParent.find('['+this.attr+'-watch]:visible'),
        max         = Math.max.apply(null, heights);

    /**
     * Fires before the heights are applied
     * @event Equalizer#preEqualized
     */
    $eqParent.trigger('preEqualized.zf.Equalizer');

    // for now, apply the max height found in the array
    for (var i = 0; i < eqGroup.length; i++) {
      $(eqGroup[i]).css('height', max);
    }
    // console.log(max);
    /**
     * Fires when the heights have been applied
     * @event Equalizer#postEqualized
     */
    $eqParent.trigger('postEqualized.zf.Equalizer');
  };
  /**
   * Destroys an instance of Equalizer.
   * @function
   */
  Equalizer.prototype.destroy = function(){
    //TODO this.
  };

  Foundation.plugin(Equalizer);

  // Exports for AMD/Browserify
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
    module.exports = Equalizer;
  if (typeof define === 'function')
    define(['foundation'], function() {
      return Equalizer;
    });

}(Foundation, jQuery);


text:
package kilobyte.simulator.ui;

import kilobyte.simulator.ui.utils.Radix;

public interface ChangeRadixDisplayCapable {
  void setRadix(Radix r);
}


text:
class Order < ActiveRecord::Base
  belongs_to :quotation
  has_many :invoices, :order => 'id'
  has_many :delivery_slips

  # Détermine si toute la commande a été livrée
  # Cette fonction se base sur la présence de bons de livraison
  def fully_delivered?
    q_items = QItem.find :all,
    	:conditions => ["quotation_id = ? and product_id IS NOT NULL", self.quotation.id]
    for item in q_items
      ordered = item.qty
      delivered = ActiveRecord::Base.connection.select_value("
		select sum(qty) from ds_items
		where q_item_id = #{item.id}
      ").to_i
      undelivered = ordered - delivered
      return false if (undelivered > 0)
    end
    return true
  end

  def fully_charged?
    # 1. facture globale ?
    invoice = Invoice.find :first,
	  :conditions => ['order_id = ? and ds_id IS NULL', self.id]
    return true unless invoice.nil?

    # 2. plusieurs factures:
    invoices = self.invoices
    q_items = QItem.find :all, :conditions => ["
		quotation_id = ? and qty >= 1
		and product_id IS NOT NULL", self.quotation.id]
    for item in q_items
      ordered = item.qty
      charged = ActiveRecord::Base.connection.select_value("
		select sum(qty) from ds_items
		where delivery_slip_id in (
		  select ds_id from invoices
		  where invoices.order_id = #{self.id}
		)
		and ds_items.q_item_id = #{item.id}
      ").to_i
      next if (charged == ordered)

      # 3. Tout n'a pas été facturé, on vérifie si il y a des abandons
      cancelled = ActiveRecord::Base.connection.select_value("
	    SELECT SUM(qty) FROM ds_items dsi, delivery_slips ds
		WHERE dsi.q_item_id = #{item.id}
		AND dsi.delivery_slip_id = ds.id
		AND ds.cancelled = TRUE
      ").to_i

      uncharged = ordered - charged - cancelled
      return false if (uncharged > 0)
    end
    return true
  end

  # undelivered(): retourne une liste de Items non livrés
  def undelivered
    q_items = QItem.find :all,
    	:conditions => ["quotation_id = ? and product_id IS NOT NULL", self.quotation.id]
    undelivered_items = []
    for qi in q_items
      ordered = qi.qty
      delivered = ActiveRecord::Base.connection.select_value("
		select sum(qty) from ds_items
		where q_item_id = #{qi.id}
      ").to_i
      undelivered = ordered - delivered
      if (undelivered > 0)
        item = Item.new
        item.description = qi.description
        item.product_id  = qi.product_id
        item.undelivered = undelivered
        undelivered_items << item
      end
    end
    undelivered_items
  end

end


text:
package io.jitstatic;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import io.jitstatic.utils.LinkedException;

public class LinkedExceptionTest {

	@Test
	public void testLinkedException() {
		LinkedException le = new LinkedException();
		le.add(new Exception("OK test Message"));
		le.add(null);
		String message = le.getLocalizedMessage();
		assertTrue(message.startsWith("java.lang.Exception: OK test Message"));
	}
}


text:
This is a War Robots simulator CLI (command line interface) program that simulates opening gold and super chests in the War Robots (3 year anniversary) event.
(Bronze and Silver chests are not included because the prizes are not interesting enough.)

**Disclaimer:** It is just for fun, and in no way intended to be accurate.
The results you get in the simulator game cannot be guaranteed to be the same as in the real game.

The drop rates came from an online forum, and there is no way of knowing if they are accurate, as this information is proprietary and owned by Pixonic.

This program is **not** affiliated with Pixonic in any way, shape, or form.

To build:

Clone the repo

`git clone git@github.com:titanandrews/wr-event-chest.git`

Change your GOPATH environment variable to your workspace root

`export GOPATH=<workspace root>`

`cd src/github.com/titanandrews/wr-event-chest`

`make`

The executable will be in the `bin` folder

Have fun!

![alt text](https://github.com/titanandrews/wr-event-chest/blob/master/img/screen-shot.png)


text:
..
    Warning: Do not edit this file. It is automatically generated from the
    software project's code and your changes will be overwritten.

    The tool to generate this file lives in openstack-doc-tools repository.

    Please make any changes needed in the code, then run the
    autogenerate-config-doc tool from the openstack-doc-tools repository, or
    ask for help on the documentation mailing list, IRC channel or meeting.

.. _zaqar-wsgi:

.. list-table:: Description of WSGI configuration options
   :header-rows: 1
   :class: config-ref-table

   * - Configuration option = Default value
     - Description
   * - **[drivers:transport:wsgi]**
     -
   * - ``bind`` = ``127.0.0.1``
     - (Unknown) Address on which the self-hosting server will listen.
   * - ``port`` = ``8888``
     - (Port number) Port on which the self-hosting server will listen.


text:
"""optimal_test.py - tests for optimization based control

RMM, 17 Apr 2019 check the functionality for optimization based control.
RMM, 30 Dec 2020 convert to pytest
"""

import pytest
import warnings
import numpy as np
import scipy as sp
import math
import control as ct
import control.optimal as opt
import control.flatsys as flat
from control.tests.conftest import slycotonly
from numpy.lib import NumpyVersion

def test_finite_horizon_simple():
    # Define a linear system with constraints
    # Source: https://www.mpt3.org/UI/RegulationProblem

    # LTI prediction model
    sys = ct.ss2io(ct.ss([[1, 1], [0, 1]], [[1], [0.5]], np.eye(2), 0, 1))

    # State and input constraints
    constraints = [
        (sp.optimize.LinearConstraint, np.eye(3), [-5, -5, -1], [5, 5, 1]),
    ]

    # Quadratic state and input penalty
    Q = [[1, 0], [0, 1]]
    R = [[1]]
    cost = opt.quadratic_cost(sys, Q, R)

    # Set up the optimal control problem
    time = np.arange(0, 5, 1)
    x0 = [4, 0]

    # Retrieve the full open-loop predictions
    res = opt.solve_ocp(
        sys, time, x0, cost, constraints, squeeze=True,
        terminal_cost=cost)     # include to match MPT3 formulation
    t, u_openloop = res.time, res.inputs
    np.testing.assert_almost_equal(
        u_openloop, [-1, -1, 0.1393, 0.3361, -5.204e-16], decimal=4)

    # Make sure the final cost is correct
    assert math.isclose(res.cost, 32.4898, rel_tol=1e-5)

    # Convert controller to an explicit form (not implemented yet)
    # mpc_explicit = opt.explicit_mpc();

    # Test explicit controller
    # u_explicit = mpc_explicit(x0)
    # np.testing.assert_array_almost_equal(u_openloop, u_explicit)

#
# Compare to LQR solution
#
# The next unit test is intended to confirm that a finite horizon
# optimal control problem with terminal cost set to LQR "cost to go"
# gives the same answer as LQR.
#
@slycotonly
def test_discrete_lqr():
    # oscillator model defined in 2D
    # Source: https://www.mpt3.org/UI/RegulationProblem
    A = [[0.5403, -0.8415], [0.8415, 0.5403]]
    B = [[-0.4597], [0.8415]]
    C = [[1, 0]]
    D = [[0]]

    # Linear discrete-time model with sample time 1
    sys = ct.ss2io(ct.ss(A, B, C, D, 1))

    # Include weights on states/inputs
    Q = np.eye(2)
    R = 1
    K, S, E = ct.dlqr(A, B, Q, R)

    # Compute the integral and terminal cost
    integral_cost = opt.quadratic_cost(sys, Q, R)
    terminal_cost = opt.quadratic_cost(sys, S, None)

    # Solve the LQR problem
    lqr_sys = ct.ss2io(ct.ss(A - B @ K, B, C, D, 1))

    # Generate a simulation of the LQR controller
    time = np.arange(0, 5, 1)
    x0 = np.array([1, 1])
    _, _, lqr_x = ct.input_output_response(
        lqr_sys, time, 0, x0, return_x=True)

    # Use LQR input as initial guess to avoid convergence/precision issues
    lqr_u = np.array(-K @ lqr_x[0:time.size]) # convert from matrix

    # Formulate the optimal control problem and compute optimal trajectory
    optctrl = opt.OptimalControlProblem(
        sys, time, integral_cost, terminal_cost=terminal_cost,
        initial_guess=lqr_u)
    res1 = optctrl.compute_trajectory(x0, return_states=True)

    # Compare to make sure results are the same
    np.testing.assert_almost_equal(res1.inputs, lqr_u[0])
    np.testing.assert_almost_equal(res1.states, lqr_x)

    # Add state and input constraints
    trajectory_constraints = [
        (sp.optimize.LinearConstraint, np.eye(3), [-5, -5, -.5], [5, 5, 0.5]),
    ]

    # Re-solve
    res2 = opt.solve_ocp(
        sys, time, x0, integral_cost, trajectory_constraints,
        terminal_cost=terminal_cost, initial_guess=lqr_u)

    # Make sure we got a different solution
    assert np.any(np.abs(res1.inputs - res2.inputs) > 0.1)

def test_mpc_iosystem_aircraft():
    # model of an aircraft discretized with 0.2s sampling time
    # Source: https://www.mpt3.org/UI/RegulationProblem
    A = [[0.99, 0.01, 0.18, -0.09,   0],
         [   0, 0.94,    0,  0.29,   0],
         [   0, 0.14, 0.81,  -0.9,   0],
         [   0, -0.2,    0,  0.95,   0],
         [   0, 0.09,    0,     0, 0.9]]
    B = [[ 0.01, -0.02],
         [-0.14,     0],
         [ 0.05,  -0.2],
         [ 0.02,     0],
         [-0.01, 0]]
    C = [[0, 1, 0, 0, -1],
         [0, 0, 1, 0,  0],
         [0, 0, 0, 1,  0],
         [1, 0, 0, 0,  0]]
    model = ct.ss2io(ct.ss(A, B, C, 0, 0.2))

    # For the simulation we need the full state output
    sys = ct.ss2io(ct.ss(A, B, np.eye(5), 0, 0.2))

    # compute the steady state values for a particular value of the input
    ud = np.array([0.8, -0.3])
    xd = np.linalg.inv(np.eye(5) - A) @ B @ ud
    yd = C @ xd

    # provide constraints on the system signals
    constraints = [opt.input_range_constraint(sys, [-5, -6], [5, 6])]

    # provide penalties on the system signals
    Q = model.C.transpose() @ np.diag([10, 10, 10, 10]) @ model.C
    R = np.diag([3, 2])
    cost = opt.quadratic_cost(model, Q, R, x0=xd, u0=ud)

    # online MPC controller object is constructed with a horizon 6
    ctrl = opt.create_mpc_iosystem(
        model, np.arange(0, 6) * 0.2, cost, constraints)

    # Define an I/O system implementing model predictive control
    loop = ct.feedback(sys, ctrl, 1)

    # Choose a nearby initial condition to speed up computation
    X0 = np.hstack([xd, np.kron(ud, np.ones(6))]) * 0.99

    Nsim = 12
    tout, xout = ct.input_output_response(
        loop, np.arange(0, Nsim) * 0.2, 0, X0)

    # Make sure the system converged to the desired state
    np.testing.assert_allclose(
        xout[0:sys.nstates, -1], xd, atol=0.1, rtol=0.01)

def test_mpc_iosystem_continuous():
    # Create a random state space system
    sys = ct.rss(2, 1, 1)
    T, _ = ct.step_response(sys)

    # provide penalties on the system signals
    Q = np.eye(sys.nstates)
    R = np.eye(sys.ninputs)
    cost = opt.quadratic_cost(sys, Q, R)

    # Continuous time MPC controller not implemented
    with pytest.raises(NotImplementedError):
        ctrl = opt.create_mpc_iosystem(sys, T, cost)

# Test various constraint combinations; need to use a somewhat convoluted
# parametrization due to the need to define sys instead the test function
@pytest.mark.parametrize("constraint_list", [
    [(sp.optimize.LinearConstraint, np.eye(3), [-5, -5, -1], [5, 5, 1],)],
    [(opt.state_range_constraint, [-5, -5], [5, 5]),
      (opt.input_range_constraint, [-1], [1])],
    [(opt.state_range_constraint, [-5, -5], [5, 5]),
      (opt.input_poly_constraint, np.array([[1], [-1]]), [1, 1])],
    [(opt.state_poly_constraint,
      np.array([[1, 0], [0, 1], [-1, 0], [0, -1]]), [5, 5, 5, 5]),
     (opt.input_poly_constraint, np.array([[1], [-1]]), [1, 1])],
    [(opt.output_range_constraint, [-5, -5], [5, 5]),
      (opt.input_poly_constraint, np.array([[1], [-1]]), [1, 1])],
    [(opt.output_poly_constraint,
      np.array([[1, 0], [0, 1], [-1, 0], [0, -1]]), [5, 5, 5, 5]),
     (opt.input_poly_constraint, np.array([[1], [-1]]), [1, 1])],
    [(sp.optimize.NonlinearConstraint,
      lambda x, u: np.array([x[0], x[1], u[0]]), [-5, -5, -1], [5, 5, 1])],
])
def test_constraint_specification(constraint_list):
    sys = ct.ss2io(ct.ss([[1, 1], [0, 1]], [[1], [0.5]], np.eye(2), 0, 1))

    """Test out different forms of constraints on a simple problem"""
    # Parse out the constraint
    constraints = []
    for constraint_setup in constraint_list:
        if constraint_setup[0] in \
           (sp.optimize.LinearConstraint, sp.optimize.NonlinearConstraint):
            # No processing required
            constraints.append(constraint_setup)
        else:
            # Call the function in the first argument to set up the constraint
            constraints.append(constraint_setup[0](sys, *constraint_setup[1:]))

    # Quadratic state and input penalty
    Q = [[1, 0], [0, 1]]
    R = [[1]]
    cost = opt.quadratic_cost(sys, Q, R)

    # Create a model predictive controller system
    time = np.arange(0, 5, 1)
    optctrl = opt.OptimalControlProblem(
        sys, time, cost, constraints,
        terminal_cost=cost)     # include to match MPT3 formulation

    # Compute optimal control and compare against MPT3 solution
    x0 = [4, 0]
    res = optctrl.compute_trajectory(x0, squeeze=True)
    t, u_openloop = res.time, res.inputs
    np.testing.assert_almost_equal(
        u_openloop, [-1, -1, 0.1393, 0.3361, -5.204e-16], decimal=3)

@pytest.mark.parametrize("sys_args", [
    pytest.param(
        ([[1, 0], [0, 1]], np.eye(2), np.eye(2), 0, True),
        id = "discrete, no timebase"),
    pytest.param(
        ([[1, 0], [0, 1]], np.eye(2), np.eye(2), 0, 1),
        id = "discrete, dt=1"),
    pytest.param(
        (np.zeros((2, 2)), np.eye(2), np.eye(2), 0),
        id = "continuous"),
])
def test_terminal_constraints(sys_args):
    """Test out the ability to handle terminal constraints"""
    # Create the system
    sys = ct.ss2io(ct.ss(*sys_args))

    # Shortest path to a point is a line
    Q = np.zeros((2, 2))
    R = np.eye(2)
    cost = opt.quadratic_cost(sys, Q, R)

    # Set up the terminal constraint to be the origin
    final_point = [opt.state_range_constraint(sys, [0, 0], [0, 0])]

    # Create the optimal control problem
    time = np.arange(0, 3, 1)
    optctrl = opt.OptimalControlProblem(
        sys, time, cost, terminal_constraints=final_point)

    # Find a path to the origin
    x0 = np.array([4, 3])
    res = optctrl.compute_trajectory(x0, squeeze=True, return_x=True)
    t, u1, x1 = res.time, res.inputs, res.states

    # Bug prior to SciPy 1.6 will result in incorrect results
    if NumpyVersion(sp.__version__) < '1.6.0':
        pytest.xfail("SciPy 1.6 or higher required")

    np.testing.assert_almost_equal(x1[:,-1], 0, decimal=4)

    # Make sure it is a straight line
    Tf = time[-1]
    if ct.isctime(sys):
        # Continuous time is not that accurate on the input, so just skip test
        pass
    else:
        # Final point doesn't affect cost => don't need to test
        np.testing.assert_almost_equal(
            u1[:, 0:-1],
            np.kron((-x0/Tf).reshape((2, 1)), np.ones(time.shape))[:, 0:-1])
    np.testing.assert_allclose(
        x1, np.kron(x0.reshape((2, 1)), time[::-1]/Tf), atol=0.1, rtol=0.01)

    # Re-run using initial guess = optional and make sure nothing changes
    res = optctrl.compute_trajectory(x0, initial_guess=u1)
    np.testing.assert_almost_equal(res.inputs, u1)

    # Re-run using a basis function and see if we get the same answer
    res = opt.solve_ocp(sys, time, x0, cost, terminal_constraints=final_point,
                        basis=flat.BezierFamily(8, Tf))

    # Final point doesn't affect cost => don't need to test
    np.testing.assert_almost_equal(
        res.inputs[:, :-1], u1[:, :-1], decimal=2)

    # Impose some cost on the state, which should change the path
    Q = np.eye(2)
    R = np.eye(2) * 0.1
    cost = opt.quadratic_cost(sys, Q, R)
    optctrl = opt.OptimalControlProblem(
        sys, time, cost, terminal_constraints=final_point)

    # Turn off warning messages, since we sometimes don't get convergence
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore", message="unable to solve", category=UserWarning)
        # Find a path to the origin
        res = optctrl.compute_trajectory(
            x0, squeeze=True, return_x=True, initial_guess=u1)
        t, u2, x2 = res.time, res.inputs, res.states

        # Not all configurations are able to converge (?)
        if res.success:
            np.testing.assert_almost_equal(x2[:,-1], 0)

            # Make sure that it is *not* a straight line path
            assert np.any(np.abs(x2 - x1) > 0.1)
            assert np.any(np.abs(u2) > 1)       # Make sure next test is useful

        # Add some bounds on the inputs
        constraints = [opt.input_range_constraint(sys, [-1, -1], [1, 1])]
        optctrl = opt.OptimalControlProblem(
            sys, time, cost, constraints, terminal_constraints=final_point)
        res = optctrl.compute_trajectory(x0, squeeze=True, return_x=True)
        t, u3, x3 = res.time, res.inputs, res.states

        # Check the answers only if we converged
        if res.success:
            np.testing.assert_almost_equal(x3[:,-1], 0, decimal=4)

            # Make sure we got a new path and didn't violate the constraints
            assert np.any(np.abs(x3 - x1) > 0.1)
            np.testing.assert_array_less(np.abs(u3), 1 + 1e-6)

    # Make sure that infeasible problems are handled sensibly
    x0 = np.array([10, 3])
    with pytest.warns(UserWarning, match="unable to solve"):
        res = optctrl.compute_trajectory(x0, squeeze=True, return_x=True)
        assert not res.success

def test_optimal_logging(capsys):
    """Test logging functions (mainly for code coverage)"""
    sys = ct.ss2io(ct.ss(np.eye(2), np.eye(2), np.eye(2), 0, 1))

    # Set up the optimal control problem
    cost = opt.quadratic_cost(sys, 1, 1)
    state_constraint = opt.state_range_constraint(
        sys, [-np.inf, 1], [10, 1])
    input_constraint = opt.input_range_constraint(sys, [-100, -100], [100, 100])
    time = np.arange(0, 3, 1)
    x0 = [-1, 1]

    # Solve it, with logging turned on (with warning due to mixed constraints)
    with pytest.warns(sp.optimize.optimize.OptimizeWarning,
                        match="Equality and inequality .* same element"):
        res = opt.solve_ocp(
            sys, time, x0, cost, input_constraint, terminal_cost=cost,
            terminal_constraints=state_constraint, log=True)

    # Make sure the output has info available only with logging turned on
    captured = capsys.readouterr()
    assert captured.out.find("process time") != -1

@pytest.mark.parametrize("fun, args, exception, match", [
    [opt.quadratic_cost, (np.zeros((2, 3)), np.eye(2)), ValueError,
     "Q matrix is the wrong shape"],
    [opt.quadratic_cost, (np.eye(2), 1), ValueError,
     "R matrix is the wrong shape"],
])
def test_constraint_constructor_errors(fun, args, exception, match):
    """Test various error conditions for constraint constructors"""
    sys = ct.ss2io(ct.rss(2, 2, 2))
    with pytest.raises(exception, match=match):
        fun(sys, *args)

@pytest.mark.parametrize("fun, args, exception, match", [
    [opt.input_poly_constraint, (np.zeros((2, 3)), [0, 0]), ValueError,
     "polytope matrix must match number of inputs"],
    [opt.output_poly_constraint, (np.zeros((2, 3)), [0, 0]), ValueError,
     "polytope matrix must match number of outputs"],
    [opt.state_poly_constraint, (np.zeros((2, 3)), [0, 0]), ValueError,
     "polytope matrix must match number of states"],
    [opt.input_poly_constraint, (np.zeros((2, 2)), [0, 0, 0]), ValueError,
     "number of bounds must match number of constraints"],
    [opt.output_poly_constraint, (np.zeros((2, 2)), [0, 0, 0]), ValueError,
     "number of bounds must match number of constraints"],
    [opt.state_poly_constraint, (np.zeros((2, 2)), [0, 0, 0]), ValueError,
     "number of bounds must match number of constraints"],
    [opt.input_poly_constraint, (np.zeros((2, 2)), [[0, 0, 0]]), ValueError,
     "number of bounds must match number of constraints"],
    [opt.output_poly_constraint, (np.zeros((2, 2)), [[0, 0, 0]]), ValueError,
     "number of bounds must match number of constraints"],
    [opt.state_poly_constraint, (np.zeros((2, 2)), 0), ValueError,
     "number of bounds must match number of constraints"],
    [opt.input_range_constraint, ([1, 2, 3], [0, 0]), ValueError,
     "input bounds must match"],
    [opt.output_range_constraint, ([2, 3], [0, 0, 0]), ValueError,
     "output bounds must match"],
    [opt.state_range_constraint, ([1, 2, 3], [0, 0, 0]), ValueError,
     "state bounds must match"],
])
def test_constraint_constructor_errors(fun, args, exception, match):
    """Test various error conditions for constraint constructors"""
    sys = ct.ss2io(ct.rss(2, 2, 2))
    with pytest.raises(exception, match=match):
        fun(sys, *args)

def test_ocp_argument_errors():
    sys = ct.ss2io(ct.ss([[1, 1], [0, 1]], [[1], [0.5]], np.eye(2), 0, 1))

    # State and input constraints
    constraints = [
        (sp.optimize.LinearConstraint, np.eye(3), [-5, -5, -1], [5, 5, 1]),
    ]

    # Quadratic state and input penalty
    Q = [[1, 0], [0, 1]]
    R = [[1]]
    cost = opt.quadratic_cost(sys, Q, R)

    # Set up the optimal control problem
    time = np.arange(0, 5, 1)
    x0 = [4, 0]

    # Trajectory constraints not in the right form
    with pytest.raises(TypeError, match="constraints must be a list"):
        res = opt.solve_ocp(sys, time, x0, cost, np.eye(2))

    # Terminal constraints not in the right form
    with pytest.raises(TypeError, match="constraints must be a list"):
        res = opt.solve_ocp(
            sys, time, x0, cost, constraints, terminal_constraints=np.eye(2))

    # Initial guess in the wrong shape
    with pytest.raises(ValueError, match="initial guess is the wrong shape"):
        res = opt.solve_ocp(
            sys, time, x0, cost, constraints, initial_guess=np.zeros((4,1,1)))

    # Unrecognized arguments
    with pytest.raises(TypeError, match="unrecognized keyword"):
        res = opt.solve_ocp(
            sys, time, x0, cost, constraints, terminal_constraint=None)

    # Unrecognized trajectory constraint type
    constraints = [(None, np.eye(3), [0, 0, 0], [0, 0, 0])]
    with pytest.raises(TypeError, match="unknown constraint type"):
        res = opt.solve_ocp(
            sys, time, x0, cost, trajectory_constraints=constraints)

    # Unrecognized terminal constraint type
    with pytest.raises(TypeError, match="unknown constraint type"):
        res = opt.solve_ocp(
            sys, time, x0, cost, terminal_constraints=constraints)

def test_optimal_basis_simple():
    sys = ct.ss2io(ct.ss([[1, 1], [0, 1]], [[1], [0.5]], np.eye(2), 0, 1))

    # State and input constraints
    constraints = [
        (sp.optimize.LinearConstraint, np.eye(3), [-5, -5, -1], [5, 5, 1]),
    ]

    # Quadratic state and input penalty
    Q = [[1, 0], [0, 1]]
    R = [[1]]
    cost = opt.quadratic_cost(sys, Q, R)

    # Set up the optimal control problem
    Tf = 5
    time = np.arange(0, Tf, 1)
    x0 = [4, 0]

    # Basic optimal control problem
    res1 = opt.solve_ocp(
        sys, time, x0, cost, constraints,
        basis=flat.BezierFamily(4, Tf), return_x=True)
    assert res1.success

    # Make sure the constraints were satisfied
    np.testing.assert_array_less(np.abs(res1.states[0]), 5 + 1e-6)
    np.testing.assert_array_less(np.abs(res1.states[1]), 5 + 1e-6)
    np.testing.assert_array_less(np.abs(res1.inputs[0]), 1 + 1e-6)

    # Pass an initial guess and rerun
    res2 = opt.solve_ocp(
        sys, time, x0, cost, constraints, initial_guess=0.99*res1.inputs,
        basis=flat.BezierFamily(4, Tf), return_x=True)
    assert res2.success
    np.testing.assert_allclose(res2.inputs, res1.inputs, atol=0.01, rtol=0.01)

    # Run with logging turned on for code coverage
    res3 = opt.solve_ocp(
        sys, time, x0, cost, constraints,
        basis=flat.BezierFamily(4, Tf), return_x=True, log=True)
    assert res3.success
    np.testing.assert_almost_equal(res3.inputs, res1.inputs, decimal=3)

def test_equality_constraints():
    """Test out the ability to handle equality constraints"""
    # Create the system (double integrator, continuous time)
    sys = ct.ss2io(ct.ss(np.zeros((2, 2)), np.eye(2), np.eye(2), 0))

    # Shortest path to a point is a line
    Q = np.zeros((2, 2))
    R = np.eye(2)
    cost = opt.quadratic_cost(sys, Q, R)

    # Set up the terminal constraint to be the origin
    final_point = [opt.state_range_constraint(sys, [0, 0], [0, 0])]

    # Create the optimal control problem
    time = np.arange(0, 3, 1)
    optctrl = opt.OptimalControlProblem(
        sys, time, cost, terminal_constraints=final_point)

    # Find a path to the origin
    x0 = np.array([4, 3])
    res = optctrl.compute_trajectory(x0, squeeze=True, return_x=True)
    t, u1, x1 = res.time, res.inputs, res.states

    # Bug prior to SciPy 1.6 will result in incorrect results
    if NumpyVersion(sp.__version__) < '1.6.0':
        pytest.xfail("SciPy 1.6 or higher required")

    np.testing.assert_almost_equal(x1[:,-1], 0, decimal=4)

    # Set up terminal constraints as a nonlinear constraint
    def final_point_eval(x, u):
        return x
    final_point = [
        (sp.optimize.NonlinearConstraint, final_point_eval, [0, 0], [0, 0])]

    optctrl = opt.OptimalControlProblem(
        sys, time, cost, terminal_constraints=final_point)

    # Find a path to the origin
    x0 = np.array([4, 3])
    res = optctrl.compute_trajectory(x0, squeeze=True, return_x=True)
    t, u2, x2 = res.time, res.inputs, res.states
    np.testing.assert_almost_equal(x2[:,-1], 0, decimal=4)
    np.testing.assert_almost_equal(u1, u2)
    np.testing.assert_almost_equal(x1, x2)

    # Try passing and unknown constraint type
    final_point = [(None, final_point_eval, [0, 0], [0, 0])]
    with pytest.raises(TypeError, match="unknown constraint type"):
        optctrl = opt.OptimalControlProblem(
            sys, time, cost, terminal_constraints=final_point)
        res = optctrl.compute_trajectory(x0, squeeze=True, return_x=True)

def test_optimal_doc():
    """Test optimal control problem from documentation"""
    def vehicle_update(t, x, u, params):
        # Get the parameters for the model
        l = params.get('wheelbase', 3.)         # vehicle wheelbase
        phimax = params.get('maxsteer', 0.5)    # max steering angle (rad)

        # Saturate the steering input
        phi = np.clip(u[1], -phimax, phimax)

        # Return the derivative of the state
        return np.array([
            np.cos(x[2]) * u[0],            # xdot = cos(theta) v
            np.sin(x[2]) * u[0],            # ydot = sin(theta) v
            (u[0] / l) * np.tan(phi)        # thdot = v/l tan(phi)
        ])

    def vehicle_output(t, x, u, params):
        return x                            # return x, y, theta (full state)

    # Define the vehicle steering dynamics as an input/output system
    vehicle = ct.NonlinearIOSystem(
        vehicle_update, vehicle_output, states=3, name='vehicle',
        inputs=('v', 'phi'), outputs=('x', 'y', 'theta'))

    # Define the initial and final points and time interval
    x0 = [0., -2., 0.]; u0 = [10., 0.]
    xf = [100., 2., 0.]; uf = [10., 0.]
    Tf = 10

    # Define the cost functions
    Q = np.diag([0, 0, 0.1])          # don't turn too sharply
    R = np.diag([1, 1])               # keep inputs small
    P = np.diag([1000, 1000, 1000])   # get close to final point
    traj_cost = opt.quadratic_cost(vehicle, Q, R, x0=xf, u0=uf)
    term_cost = opt.quadratic_cost(vehicle, P, 0, x0=xf)

    # Define the constraints
    constraints = [ opt.input_range_constraint(vehicle, [8, -0.1], [12, 0.1]) ]

    # Solve the optimal control problem
    horizon = np.linspace(0, Tf, 3, endpoint=True)
    result = opt.solve_ocp(
        vehicle, horizon, x0, traj_cost, constraints,
        terminal_cost= term_cost, initial_guess=u0)

    # Make sure the resulting trajectory generate a good solution
    resp = ct.input_output_response(
        vehicle, horizon, result.inputs, x0,
        t_eval=np.linspace(0, Tf, 10))
    t, y = resp
    assert (y[0, -1] - xf[0]) / xf[0] < 0.01
    assert (y[1, -1] - xf[1]) / xf[1] < 0.01
    assert y[2, -1] < 0.1


text:
import { moduleForComponent } from 'ember-qunit';

moduleForComponent('instrument/i-oscillator', 'Integration | Component | instrument/i oscillator', {
  integration: true
});


text:
{
    'name' : 'Knowledge Management System',
    'version' : '1.0',
    'depends' : ['base','base_setup'],
    'author' : 'OpenERP SA',
    'category': 'Hidden/Dependency',
    'description': """
Installer for knowledge-based Hidden.
=====================================

Makes the Knowledge Application Configuration available from where you can install
document and Wiki based Hidden.
    """,
    'website': 'https://www.odoo.com',
    'data': [
        'security/knowledge_security.xml',
        'security/ir.model.access.csv',
        'knowledge_view.xml',
        'res_config_view.xml',
    ],
    'demo': ['knowledge_demo.xml'],
    'installable': True,
    'auto_install': False,
    'images': ['images/1_config_knowledge.jpeg'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
// Code generated by go-swagger; DO NOT EDIT.

package prefilter

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

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/cilium/cilium/api/v1/models"
)

// GetPrefilterReader is a Reader for the GetPrefilter structure.
type GetPrefilterReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *GetPrefilterReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewGetPrefilterOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 500:
		result := NewGetPrefilterFailure()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		return nil, runtime.NewAPIError("unknown error", response, response.Code())
	}
}

// NewGetPrefilterOK creates a GetPrefilterOK with default headers values
func NewGetPrefilterOK() *GetPrefilterOK {
	return &GetPrefilterOK{}
}

/*GetPrefilterOK handles this case with default header values.

Success
*/
type GetPrefilterOK struct {
	Payload *models.CIDRList
}

func (o *GetPrefilterOK) Error() string {
	return fmt.Sprintf("[GET /prefilter][%d] getPrefilterOK  %+v", 200, o.Payload)
}

func (o *GetPrefilterOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.CIDRList)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewGetPrefilterFailure creates a GetPrefilterFailure with default headers values
func NewGetPrefilterFailure() *GetPrefilterFailure {
	return &GetPrefilterFailure{}
}

/*GetPrefilterFailure handles this case with default header values.

CIDR list get failed
*/
type GetPrefilterFailure struct {
	Payload models.Error
}

func (o *GetPrefilterFailure) Error() string {
	return fmt.Sprintf("[GET /prefilter][%d] getPrefilterFailure  %+v", 500, o.Payload)
}

func (o *GetPrefilterFailure) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	// response payload
	if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}


text:
package org.piraso.server.dispatcher;

import org.piraso.api.Level;
import org.piraso.api.entry.MessageEntry;
import org.piraso.server.AbstractLoggerListenerTest;
import org.piraso.server.GroupChainId;
import org.piraso.server.PirasoContextHolder;
import org.junit.Test;
import org.mockito.Matchers;

import static junit.framework.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

/**
 * Test for {@link ContextLogDispatcher} class.
 */
public class ContextLogDispatcherTest extends AbstractLoggerListenerTest {

    @Test
    public void testAddRemoveListener() throws Exception {
        DispatcherForwardListener listener = mock(DispatcherForwardListener.class);

        ContextLogDispatcher.addListener(listener);

        assertEquals(1, ContextLogDispatcher.getListeners().size());

        ContextLogDispatcher.removeListener(listener);
        assertTrue(ContextLogDispatcher.getListeners().isEmpty());

        ContextLogDispatcher.addListener(listener);
        assertEquals(1, ContextLogDispatcher.getListeners().size());

        ContextLogDispatcher.clearListeners();
        assertTrue(ContextLogDispatcher.getListeners().isEmpty());
    }

    @Test
    public void testForwardNoContext() throws Exception {
        PirasoContextHolder.removeContext();
        DispatcherForwardListener listener = spy(new DispatcherHandler());

        ContextLogDispatcher.addListener(listener);
        ContextLogDispatcher.forward("simpleMessage");

        verify(listener, times(0)).forwarded(Matchers.<DispatcherForwardEvent>any());
        verify(context, times(0)).log(Matchers.<Level>any(), any(GroupChainId.class), any(MessageEntry.class));
    }

    @Test
    public void testForwardWithListener() throws Exception {
        DispatcherForwardListener listener = spy(new DispatcherHandler());

        ContextLogDispatcher.addListener(listener);
        ContextLogDispatcher.forward("simpleMessage");

        verify(listener, times(1)).forwarded(Matchers.<DispatcherForwardEvent>any());
        assertTrue(MessageEntry.class.isInstance(caughtEntry));
        verify(context, times(1)).log(Matchers.<Level>any(), any(GroupChainId.class), any(MessageEntry.class));
    }

    @Test
    public void testForwardWithoutListener() throws Exception {
        ContextLogDispatcher.forward("simpleMessage");

        assertTrue(MessageEntry.class.isInstance(caughtEntry));
        verify(context, times(1)).log(Matchers.<Level>any(), any(GroupChainId.class), any(MessageEntry.class));
    }

    private class DispatcherHandler implements DispatcherForwardListener {

        public void forwarded(DispatcherForwardEvent evt) {
            assertNotNull(evt.getEntry());
            assertNotNull(evt.getId());
        }
    }
}


text:
Comments = new Meteor.Collection('comments');

Meteor.methods({
  comment: function(commentAttributes) {
    var user = Meteor.user();
    var post = Posts.findOne(commentAttributes.postId);
    // ensure the user is logged in
    if (!user)
      throw new Meteor.Error(401, "You need to login to make comments");

    if (!commentAttributes.body)
      throw new Meteor.Error(422, 'Please write some content');

    if (!post)
      throw new Meteor.Error(422, 'You must comment on a post');

    comment = _.extend(_.pick(commentAttributes, 'postId', 'body'), {
      userId: user._id,
      author: user.username,
      submitted: new Date().getTime()
    });

    // update the post with the number of comments
    Posts.update(comment.postId, {$inc: {commentsCount: 1}});

    // create the comment, save the id
    comment._id = Comments.insert(comment);

    // now create a notification, informing the user that there's been a comment
    createCommentNotification(comment);

    return comment._id;
  }
});


text:
#import "MUConnectSheetController.h"

@interface MUConnectSheetController () {
    IBOutlet NSWindow                     *_connectSheet;
    IBOutlet NSTextField                  *_hostnameField;
    IBOutlet NSTextField                  *_portField;
    IBOutlet NSTextField                  *_usernameField;
    IBOutlet NSTextField                  *_passwordField;
    IBOutlet NSButton                     *_connectButton;
    IBOutlet NSButton                     *_cancelButton;
    id<MUConnectSheetControllerDelegate>  _delegate;
}
@end

@implementation MUConnectSheetController

- (id) init {
    return [self initWithHostname:nil port:-1 username:nil];
}

- (id) initWithHostname:(NSString *)hostname port:(NSInteger)port username:(NSString *)username {
    if ((self = [super init])) {
        [NSBundle loadNibNamed:@"MUConnectSheet" owner:self];

        [_connectSheet setDefaultButtonCell:[_connectButton cell]];

        [_connectButton setTarget:self];
        [_connectButton setAction:@selector(connectButtonClicked:)];

        [_cancelButton setTarget:self];
        [_cancelButton setAction:@selector(cancelButtonClicked:)];

        if (hostname)
            [_hostnameField setStringValue:hostname];
        if (port > 0)
            [_portField setIntegerValue:port];
        if (username)
            [_usernameField setStringValue:username];
    }
    return self;
}

- (void) setDelegate:(id<MUConnectSheetControllerDelegate>)delegate {
    _delegate = delegate;
}

- (id<MUConnectSheetControllerDelegate>) delegate {
    return _delegate;
}

- (void) connectButtonClicked:(id)sender {
    [NSApp stopModal];
    [NSApp endSheet:_connectSheet];
    [_connectSheet orderOut:self];
    [_delegate connectSheetShouldConnect:self];
}

- (void) cancelButtonClicked:(id)sender {
    [NSApp stopModal];
    [NSApp endSheet:_connectSheet];
    [_connectSheet orderOut:self];
}

- (void) showModalConnectSheetForWindow:(NSWindow *)win {
    [NSApp beginSheet:_connectSheet modalForWindow:win modalDelegate:nil didEndSelector:nil contextInfo:NULL];
    [NSApp runModalForWindow:_connectSheet];
}

- (NSString *) hostname {
    return [_hostnameField stringValue];
}

- (NSInteger) port {
    return [_portField integerValue];
}

- (NSString *) username {
    return [_usernameField stringValue];
}

- (NSString *) password {
    return [_passwordField stringValue];
}

@end


text:
let warning = require('../util/warning');

module.exports = (props, children, loc, types, name) => {
  let defaults = {
    radius: ['1', types.numericLiteral(1)],
    position: ['[0,0]', types.arrayExpression([types.numericLiteral(0), types.numericLiteral(0)])],
    sides: ['3', types.numericLiteral(3)]
  };

  Object.getOwnPropertyNames(defaults).forEach(
    (prop) => {
      if (!props[prop]) {
        warning(prop, 'e2d', name, loc, defaults[prop][0]);
        props[prop] = defaults[prop][1];
      }
    }
  );
};


text:
if (APPLE)
  file(GLOB plugins "bin/plugins/*.dylib")
  install(FILES ${plugins} DESTINATION share/musikcube/plugins)
else ()
  file(GLOB plugins "bin/plugins/*.so")
  install(FILES ${plugins} DESTINATION share/musikcube/plugins)
endif ()

if (${BUILD_STANDALONE} MATCHES "true")
  file(GLOB libraries "bin/lib/*")
  install(FILES ${libraries} DESTINATION share/musikcube/lib)
  file(GLOB_RECURSE share "bin/share/*")
  install(FILES ${share} DESTINATION share/musikcube/share)
endif()

# sdk header files
file(GLOB sdk_headers "src/musikcore/sdk/*.h")
install(FILES ${sdk_headers} DESTINATION include/musikcube/musikcore/sdk)

# resources
file(GLOB themes "src/musikcube/data/themes/*.json")
file(COPY ${themes} DESTINATION bin/themes)
install(FILES ${themes} DESTINATION share/musikcube/themes)

file(GLOB locales "src/musikcube/data/locales/*.json")
file(COPY ${locales} DESTINATION bin/locales)
install(FILES ${locales} DESTINATION share/musikcube/locales)

# linux desktop shortcuts
if (CMAKE_SYSTEM_NAME MATCHES "Linux")
  file(GLOB linux_share_applications "src/musikcube/data/linux/share/applications/musikcube.desktop")
  install(FILES ${linux_share_applications} DESTINATION share/applications/)
  file(GLOB linux_share_icons_48 "src/musikcube/data/linux/share/icons/hicolor/48x48/apps/*")
  install(FILES ${linux_share_icons_48} DESTINATION share/icons/hicolor/48x48/apps/)
  file(GLOB linux_share_icons_64 "src/musikcube/data/linux/share/icons/hicolor/64x64/apps/*")
  install(FILES ${linux_share_icons_64} DESTINATION share/icons/hicolor/64x64/apps/)
  file(GLOB linux_share_icons_128 "src/musikcube/data/linux/share/icons/hicolor/128x128/apps/*")
  install(FILES ${linux_share_icons_128} DESTINATION share/icons/hicolor/128x128/apps/)
endif()

# libmusikcore shared library
if (APPLE)
  install(FILES "bin/libmusikcore.dylib" DESTINATION share/musikcube)
else()
  install(FILES "bin/libmusikcore.so" DESTINATION share/musikcube)
endif()

# executable and shell script for musikcube
install(
  FILES bin/musikcube
  DESTINATION share/musikcube
  PERMISSIONS
    OWNER_EXECUTE OWNER_READ OWNER_WRITE
    GROUP_EXECUTE GROUP_READ GROUP_WRITE
    WORLD_EXECUTE WORLD_READ)

install(
  FILES "${CMAKE_CURRENT_BINARY_DIR}/src/musikcube/musikcube"
  DESTINATION bin/
  PERMISSIONS
    OWNER_EXECUTE OWNER_READ OWNER_WRITE
    GROUP_EXECUTE GROUP_READ GROUP_WRITE
    WORLD_EXECUTE WORLD_READ)

# executable and shell script for daemon
install(
  FILES bin/musikcubed
  DESTINATION share/musikcube
  PERMISSIONS
    OWNER_EXECUTE OWNER_READ OWNER_WRITE
    GROUP_EXECUTE GROUP_READ GROUP_WRITE
    WORLD_EXECUTE WORLD_READ)

install(
  FILES "${CMAKE_CURRENT_BINARY_DIR}/src/musikcubed/musikcubed"
  DESTINATION bin/
  PERMISSIONS
    OWNER_EXECUTE OWNER_READ OWNER_WRITE
    GROUP_EXECUTE GROUP_READ GROUP_WRITE
    WORLD_EXECUTE WORLD_READ)


text:
Jump Hash is a fast, minimal memory consistent hash algorithm that can
be expressed in a fairly compact code base.  As such it is well suited
to rapid-iteration hashing requirements.  This implementation makes use
of ctypes and numpy to mimic the behavior of integers in the original C
implementation.  It is based off the work described here:
http://arxiv.org/pdf/1406.2294v1.pdf

It's also a short project in conversion and is stated to be in no way
suitable for production use.  Currently supports Python 2.6 and Python 2.7

## Installation

* install numpy
* python setup.py build
* sudo python setup.py install

## Documentation

## Example
Here is the most simple example of use, sending a message with the BlockingConnection adapter:

    import jumphash
    # h_id is an integer representation of the id to consistent-hash
    h_id = 43838
    buckets = 64
    bucket_assignment = jumphash.hash(h_id, buckets)

## License
pyjumphash is licensed under the Apache 2.0 license.


text:
This script allows you to Embed Youtube and Vimeo thumbs, and when click on element ,
it put Video in `<iframe>` tag
#### Instalation

```sh
$ npm i
```
```sh
$ bower install
```
For dev release:
```sh
$ gulp && gulp watch
```
For production release:
```sh
$ gulp --production
```
### Examples

See in example folder

https://k-zakhariy.github.io/embed-video/examples/

### Usage

```html
<div class="VideoEmbed" data-url="https://www.youtube.com/watch?v=6FeJySGOqhA"></div>
<div class="VideoEmbed" data-url="https://www.youtube.com/watch?v=owLDqhB90gk"></div>
<div class="VideoEmbed" data-url="https://vimeo.com/181553695"></div>
```
``` js
$('.VideoEmbed').each(function (i, el) {
    var obj = new VideoEmbed($(this));
});
```

Then you will see `thumbnails`


text:
@extends('app')
@section('metatag')
<meta name="description" content="{{ $metadescription }}">
<title>{{ $metatitle }}</title>
@stop

@section('carousel')

Caption 1

Caption 2

Caption 3

@stop
@section('content')

            {{ $service->name }}

    @foreach( array_chunk($service->customers->all(), 4) as $row )

        @foreach( $row as $customer)

id }}">

{{ $customer->name }}

                    logo }}" alt="">

        @endforeach

    @endforeach

{{ $service->body }}

@stop

@section('script_footer')

@endsection


text:
class Payment
  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :order
  field :uuid, type: String
  field :gateway_transaction_id, type: String
  field :status, type: Symbol
  field :tracking_id, type: Integer
  field :amount, type: BigDecimal
  field :succeeded_at, type: DateTime
  field :details, type: Hash

  validates :uuid, presence: true

  before_validation :set_uuid

  # These attributes map to TouchNet uPay parameters
  alias_attribute :ext_trans_id, :uuid
  alias_attribute :tpg_trans_id, :gateway_transaction_id
  alias_attribute :pmt_status, :status
  alias_attribute :sys_tracking_id, :tracking_id
  alias_attribute :pmt_amt, :amount

  def pending?
    gateway_transaction_id.nil?
  end

  def successful?
    status == :success
  end

  def self.generate_uuid
    SecureRandom.uuid
  end

  private

  def set_uuid
    self.uuid = self.class.generate_uuid if uuid.blank?
  end
end


text:
Creates a new cluster in the current database. The cluster can be "physical" or "memory".

## Syntax

```
CREATE CLUSTER <cluster-name> <cluster-type> <data-segment> <location> <position>
```

Where:

- **cluster-name**   The name of the cluster to create
- **cluster-type**   Cluster type: 'PHYSICAL' or 'LOGICAL'
- **data-segment**   Data segment to use. 'DEFAULT' will use the default one
- **location**       Location where to place the new cluster files, if applicable. use 'DEFAULT' to leave into the database directory
- **position**       'APPEND' to add as last cluster, otherwise the empty position to replace

## Example

```sql
orientdb> CREATE CLUSTER documents PHYSICAL DEFAULT DEFAULT APPEND

Creating cluster [documents] of type 'PHYSICAL' in database demo as last one...
PHYSICAL cluster created correctly with id #68
```

## See also

To display all the cluster configured in the current database use the command [CLUSTERS](Console-Command-Clusters.md).

To delete a cluster use the command [DROP CLUSTER](Console-Command-Drop-Cluster.md).

This is a command of the Orient console. To know all the commands go to [Console-Commands](Console-Commands.md).


text:
"""
Verifies that compile-time flags work.
"""

import TestGyp

import sys

if sys.platform == 'darwin':
  test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
  CHDIR = 'cflags'
  test.run_gyp('test.gyp', chdir=CHDIR)
  test.build('test.gyp', test.ALL, chdir=CHDIR)
  test.pass_test()


text:
{// 引入标签库 }
<tagLib name="html" />
<include file="Public:header" />
<load href='__TMPL__Common/js/database.js' />
<load href='__TMPL__Common/js/jquery.bgiframe.js' />
<load href='__TMPL__Common/js/jquery.weebox.js' />
<load href='__TMPL__Common/style/weebox.css' />

{$main_title}

	<input type="button" class="button" value="{%BACKUP}" onclick="backup();" />

		{$Think.lang.BACKUP_FILE}
		{$Think.lang.CREATE_TIME}

		{$Think.lang.TAG_LANG_OPERATE}

	<foreach name="sql_list" item="sql_item" key="groupname">

			{$groupname}({:sprintf(l("TOTAL_COUNT_VOL"),count($sql_item))})
			{$groupname|to_date}
			{$Think.lang.RESTORE} {$Think.lang.DEL}

	</foreach>

<include file="Public:footer" />


text:
var register = angular.module('registerModule');

register.factory('registerFactory', function($http,$window,seshkeys){

	var factory = {};

	factory.createUser = function(data){
		return $http.post($window.sessionStorage.getItem(seshkeys.serviceurl) + '/createUser', data);
	};

	return factory;
});


text:
layout: post
title:  "10 Reasons to travel the world"
date: 2015-02-11 08:50:28
categories: travel storytime
author_name : Michelle Jones
author_url : /author/michelle
author_avatar: michelle
show_avatar : true
read_time : 34
feature_image: feature-wolf
show_related_posts: false
square_related: recommend-wolf
---

Ask yourself, why not? What is the number one reason you wouldn't. If the reason you get back is fear, you should just do it.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati doloribus, culpa, et suscipit praesentium incidunt, libero officiis ipsum fugiat odit aperiam commodi unde dignissimos veritatis accusamus molestias iste magni nobis?

![Fire image]({{site.url}}/{{site.baseurl}}img/post-assets/fire.jpg)

Kale chips bespoke church-key American Apparel flannel pickled. Mlkshk High Life Blue Bottle, leggings gastropub four dollar toast post-ironic fap American Apparel VHS. Cliche cold-pressed single-origin coffee mlkshk retro distillery. 3 wolf moon Tumblr selvage semiotics food truck. Intelligentsia Pitchfork meh sriracha chambray, fanny pack lomo irony fap pickled stumptown. Twee +1 artisan, cred ethical gluten-free 90's four loko Odd Future cronut small batch organic. Seitan hashtag jean shorts art party messenger bag.

> Scenester Echo Park tilde

Locavore brunch kale chips vegan selvage High Life you probably haven't heard of them before they sold out pork belly. Flexitarian organic wayfarers, cronut food truck bicycle rights drinking vinegar bespoke meditation mustache swag mumblecore semiotics locavore. Whatever kogi readymade, jean shorts pork belly chia distillery wayfarers. Art party single-origin coffee four dollar toast VHS, try-hard hoodie kogi normcore Neutra actually church-key flexitarian swag.

[jekyll]:      http://jekyllrb.com
[jekyll-gh]:   https://github.com/jekyll/jekyll
[jekyll-help]: https://github.com/jekyll/jekyll-help


text:
package org.seasar.doma.it.criteria;

import java.util.ArrayList;
import java.util.List;
import org.seasar.doma.Entity;
import org.seasar.doma.Id;
import org.seasar.doma.Metamodel;
import org.seasar.doma.Transient;

@Entity(metamodel = @Metamodel)
public class Team {
  @Id private Integer id;
  private String name;

  public Team() {}

  public Team(Integer id, String name) {
    this();
    this.id = id;
    this.name = name;
  }

  @Transient private final List<Player> players = new ArrayList<>();

  @Transient private final List<Coach> coaches = new ArrayList<>();

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public List<Player> getPlayers() {
    return players;
  }

  public List<Coach> getCoaches() {
    return coaches;
  }
}