text:
\section{Termination}\label{sec:termination}

Program divergence is, more often than not,
a bug rather than a feature.
%
To account for the common cases,
by default, \toolname proves termination of each recursive function.
%
Fortunately, refinements make this onerous task quite straightforward.
We need simply associate a \emph{well-founded termination metric} % $\mu$
on the function's parameters, and then use refinement typing to check
that the metric strictly decreases at each recursive call. In practice,
due to a careful choice of defaults, this amounts to about a line
of termination-related hints per hundred lines of source.
%
In Chapter~\ref{chapter:refinedhaskell}
we prove soundness of our refinement type based termination checker
and also we explain how soundness of \toolname crucially depends on
the termination checker.
%
Here, we provide an overview on how one can use \toolname
to prove termination.

\mypara{Simple Metrics}
As a starting example, consider the @fac@ function
%
\begin{code}
  fac :: n:Nat -> Nat / [n]
  fac 0 = 1
  fac n = n * fac (n-1)
\end{code}
%
The termination metric is simply the parameter @n@;
as @n@ is non-negative and decreases at the recursive
call, \toolname verifies that @fac@ will terminate.
%
We specify the termination metric in the type signature
with the @/[n]@.

Termination checking is performed at the same
time as regular type checking, as it can be
reduced to refinement type checking with a
special terminating fixpoint combinator~\ref{chapter:refinedhaskell}.
Thus, if \toolname fails to prove that a given
termination metric is well-formed and decreasing,
it will report a @Termination Check@ @Error@.
%% \RJ{Seems untrue -- I just get a plain old liquid type error?
%% NV: IF you provide termination metrics, you DO get termination check error}.
At this point, the user can either debug
the specification, or mark the function
as non-terminating.

%%\mypara{Refinements Enable Termination}
%%Consider Euclid's GCD:
%%%
%%\begin{code}
%%  gcd :: a:Nat -> {v:Nat | v < a} -> Nat
%%  gcd a 0 = a
%%  gcd a b = gcd b (a `mod` b)
%%\end{code}
%%%
%%Here, the termination metric is the first parameter @a@.
%%To prove that @a@ is decreasing requires
%%the fact that the second parameter is smaller than the first
%%and that @mod@ returns results smaller than its second
%%parameter. Both facts are easily expressed as refinements,
%%but elude non-extensible checkers~\cite{Giesl11}.
%%
%%\mypara{Explicit Termination Metrics}
%%The termination metric can be some parameter \emph{other} than the first
%%argument.
%%For example, consider: % As an example, consider the tail-recursive factorial:
%%%
%%\begin{code}
%%  tfac     :: Nat -> n:Nat -> Nat / [n]
%%  tfac x 0 = if n == 0 then x
%%                       else tfac (n*x) (n-1)
%%\end{code}
%%%
%%%
%%It can be checked that @n@, \ie, the second argument is decreasing at each recursive call.
%%
\mypara{Termination Expressions}
Sometimes, no single parameter decreases across recursive calls,
but there is some \emph{expression} that forms the decreasing
metric.
%
For example recall @range lo hi@ (from \S~\ref{sec:tool:verification})
which returns the list of @Int@s from @lo@ to @hi@:
%
\begin{code}
  range lo hi
    | lo < hi   = lo : range (lo+1) hi
    | otherwise = []
\end{code}
%
Here, neither parameter is decreasing (indeed, the first
one is increasing) but @hi-lo@ decreases across each call.
To account for such cases, we can specify as the termination
metric a (refinement logic) expression over the function
parameters. Thus, to prove termination, we could type @range@ as:
\begin{code}
  lo:Int -> hi:Int -> [(Btwn lo hi)] / [hi-lo]
\end{code}

\mypara{Lexicographic Termination}
The Ackermann function
%
\begin{code}
  ack m n
    | m == 0    = n + 1
    | n == 0    = ack (m-1) 1
    | otherwise = ack (m-1) (ack m (n-1))
\end{code}
%
is curious as there exists no simple, natural-valued,
termination metric that decreases at each recursive call.
%
However @ack@ terminates because at each call \emph{either}
@m@ decreases \emph{or} @m@ remains the same and @n@ decreases.
%
In other words, the pair @(m,n)@ strictly decreases according to a
\emph{lexicographic} ordering.
%
Thus \toolname supports termination metrics that are a
\emph{sequence of} termination expressions. For example,
we can type @ack@ as:
%
\begin{code}
  ack :: m:Nat -> n:Nat -> Nat / [m, n]
\end{code}
%
At each recursive call \toolname uses a lexicographic
ordering to check that the sequence of termination
expressions is decreasing (and well-founded in each component).

\mypara{Mutual Recursion}
%
The lexicographic mechanism lets us check termination of
mutually recursive functions, \eg @isEven@ and @isOdd@
%
\begin{code}
  isEven 0 = True
  isEven n = isOdd $ n-1

  isOdd n  = not $ isEven n
\end{code}
%
Each call terminates as either @isEven@ calls @isOdd@ with a
decreasing parameter, \emph{or} @isOdd@ calls @isEven@ with
the same parameter, expecting the latter to do the decreasing.
%
For termination, we type:
%
\begin{code}
  isEven :: n:Nat -> Bool / [n, 0]
  isOdd  :: n:Nat -> Bool / [n, 1]
\end{code}
%
To check termination, \toolname verifies that at each recursive
call the metric of the caller is less than the metric of the
callee.
%
When @isEven@ calls @isOdd@, it proves that the caller's
metric, namely @[n,0]@ is greater than the callee's @[n-1,1]@.
When \hbox{@isOdd@} calls @isEven@, it proves that the
caller's metric @[n,1]@ is greater than the callee's @[n,0]@,
thereby proving the mutual recursion always terminates.

\mypara{Recursion over Data Types}
The above strategies generalize easily to functions that recurse
over (finite) data structures like arrays, lists, and trees.
In these cases, we simply use \emph{measures} to project the
structure onto @Nat@, thereby reducing the verification to
the previously seen cases.
For example, we can prove that @map@
%
\begin{code}
  map f (x:xs) = f x : map f xs
  map f []     = []
\end{code}
%
terminates, by typing @map@ as
%
\begin{code}
  (a -> b) -> xs:[a] -> [b] / [len xs]
\end{code}
%
\ie, by using the measure @len xs@, from \S~\ref{sec:tool:measures},
as the metric.

%%% %
%%% \begin{code}
%%%   data L [sz] a = N | C a (L a)
%%% \end{code}
%%% %
%%% we can define a \emph{measure}
%%% %
%%% \begin{code}
%%%   measure sz  :: L a -> Nat
%%%   sz (C x xs) = 1 + (sz xs)
%%%   sz N        = 0
%%% \end{code}
%%% %
%%% We prove that @map@ terminates using the type:
%%% %
%%% \begin{code}
%%%   map :: (a -> b) -> xs:L a -> L b / [sz xs]
%%%   map f (C x xs) = C (f x) (map f xs)
%%%   map f N        = N
%%% \end{code}
%%% %
%%% That is, by simply using @(sz xs)@  as the
%%% decreasing metric.

\mypara{Generalized Metrics Over Datatypes}
In many functions there is no single argument
whose measure provably decreases. Consider
%
\begin{code}
  merge (x:xs) (y:ys)
    | x < y     = x : merge xs (y:ys)
    | otherwise = y : merge (x:xs) ys
\end{code}
%
from the homonymous sorting routine. Here, neither
parameter decreases, but the \emph{sum} of their
sizes does. To prove termination, we can type @merge@ as:
%
\begin{code}
  xs:[a] -> ys:[a] -> [a] / [len xs + len ys]
\end{code}

%%%% \begin{figure*}[!t]
%%%% 	\begin{code}
%%%% 	type OL  a   =  [a]<{\fld v -> (v >= fld)}>
%%%%
%%%% 	qsort :: (Ord a) => xs:[a] -> OL a / [(len xs), 0]
%%%% 	qsort []         = []
%%%% 	qsort (x:xs)     = qpart x xs [] []
%%%%
%%%% 	qpart :: (Ord a) => x:a -> q:[a] -> r: [{v:a|v<x}] -> p: [{v:a|v>=x}] -> OL a
%%%% 	       / [((len q) + (len r) + (len p)), ((len q) + 1)]
%%%% 	qpart x []     rlt rge             = app x (qsort rlt) (x:qsort rge)
%%%% 	qpart x (y:ys) rlt rge | x > y     = qpart x ys (y:rlt) rge
%%%% 	                       | otherwise = qpart x ys rlt (y:rge)
%%%%
%%%% 	app k []     ys = ys
%%%% 	app k (x:xs) ys = x : (app k xs ys)
%%%% 	\end{code}
%%%% \caption{Mutual-recursive qsort}
%%%% \label{fig:code:qsort}
%%%% \end{figure*}

\mypara{Putting it all Together}
The above techniques can be combined to prove
termination of the mutually recursive quick-sort (from~\citep{XiTerminationLICS01})% \RJ{from where?}
%
\begin{code}
  qsort (x:xs)   = qpart x xs [] []
  qsort []       = []

  qpart x (y:ys) l r
    | x > y      = qpart x ys (y:l) r
    | otherwise  = qpart x ys l (y:r)
  qpart x [] l r = app x (qsort l) (qsort r)

  app k []     z = k : z
  app k (x:xs) z = x : app k xs z
\end{code}
%
@qsort (x:xs)@ calls @qpart x xs@ to partition @xs@
into two lists @l@ and @r@ that have elements less
and greater or equal than the pivot @x@, respectively.
%
When @qpart@ finishes partitioning it mutually recursively
calls @qsort@ to sort the two list and appends the results
with @app@.
%
\toolname proves sortedness as well~\cite{vazou13} but let us
focus here on termination. To this end, we type the functions
as:
%
\begin{code}
  qsort :: xs:_ -> _
        / [len xs, 0]

  qpart :: _ -> ys:_ -> l:_ -> r:_ -> _
        / [len ys + len l + len r, 1 + len ys]
\end{code}
%
As before, \toolname checks that at each recursive call
the caller's metric is less than the callee's.
%
When @qsort@ calls @qpart@ the length of the unsorted
list @len (x:xs)@ exceeds the \hbox{@len xs + len [] + len []@}.
%
When @qpart@ recursively calls itself the first component
of the metric is the same, but the length of the unpartitioned
list decreases, \ie @1 + len y:ys@ exceeds \hbox{@1 + len ys@}.
%
Finally, when @qpart@ calls @qsort@ we have \hbox{@len ys + len l + len r@}
exceeds both @len l@ and @len r@, thereby ensuring termination.

%%% Before we dive into proving termination, note that the
%%% type alias @OL a@ uses Abstract Refinements~\citep{vazou13} to describe
%%% Ordered Lists.
%%% Thus, when \toolname decides that the @qsort@ is SAFE,
%%% it proves both termination and sortedness.
%%%%Note that classical appending @rlt ++ rge@ of the two sorted lists will lose
%%%%the crucial for sorting information that every element of @rlt@ is less than each element of @rge@.
%%%%%
%%%%Thus we defined a new version of list appending @app@ that uses the pivot element @k@
%%%%as a ghost-parameter.
%%%%%
%%%%Good news is that \toolname will automatically infer the appropriate type of @app@!

%% Let \mus{xs} and \mup{q}{r}{p} be the (well-founded) termination pairs
%% for @qsort xs@ and @qpart x q r p@ respectively, as annotated in the type signatures.
%% %
%%%$\mu_s(x:xs) = (1 + len xs, 0) > (len xs + 0 + 0, len xs + 1) = \mu_p(xs, [], [])$
%%%$\mu_p(y:ys, rlt, rge) = ((1 + (len ys)) + (len rlt) + (len rge), (1 + len ys) + 1) >
%%%(len ys + (1 + (len rlt)) + (len rge), ((len ys) + 1)) = \mu_p(ys, y:rlt, rge) $
%%%$\mu_p([], rlt, rge) = (0 + len rlt + len rge, 1) > (len rlt, 0) = \mu_s(rlt)$

%% Existing techniques~\citep{CookPR11} could be used to
%% come up with termination metrics.
%% We leave embedding these techniques into \toolname as a future work, and instead
%% we use some defaults to automate termination proving
%% on functions with trivial metrics.

\mypara{Automation: Default Size Measures}
%
The @qsort@ example illustrates that while \toolname is
very expressive, devising appropriate termination metrics
can be tricky.
%
Fortunately, such patterns are very uncommon, and the vast
majority of cases in real world programs are just structural
recursion on a datatype.
%
\toolname automates termination proofs for this common case,
by allowing users to specify a \emph{default size measure}
for each data type, \eg @len@ for @[a]@.
%
Now, if no explicit termination metric is given, by default
\toolname assumes that the \emph{first} argument whose type
has an associated size measure decreases.
%
Thus, in the above, we need not specify metrics for @fac@
or @map@ as the size measure is automatically
used to prove termination.
%
This heuristic suffices to \emph{automatically}
prove 67\% of recursive functions terminating.

\mypara{Disabling Termination Checking}
In \texttt{Haskell}'s lazy setting not all functions are terminating.
%
\toolname provides two mechanisms the disable termination proving.
%
A user can disable checking a single function by marking
that function as lazy. For example, specifying @lazy repeat@
tells the tool to not prove @repeat@ terminates.
%
Optionally, a user can disable termination checking for a whole
module by using the command line argument \cmdnotermination
for the entire file.


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    PDAutoSlideScrollView *autoScrollView = [[PDAutoSlideScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    autoScrollView.dataSource = @[[UIImage imageNamed:@"banner_0.jpeg"],[UIImage imageNamed:@"banner_1.jpeg"],[UIImage imageNamed:@"banner_2.jpeg"],[UIImage imageNamed:@"banner_3.jpeg"],[UIImage imageNamed:@"banner_4.jpeg"],[UIImage imageNamed:@"banner_5.jpeg"]];

    autoScrollView.selectionHandle = ^(NSInteger selectedIndex) {
        NSLog(@"selectedIndex:%li",selectedIndex);
    };
    [self.view addSubview:autoScrollView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "Jekyll Clean"
date:   2014-08-23 15:31:11
homepage: http://github.com/scotte/jekyll-clean
download: https://github.com/scotte/jekyll-clean/zipball/gh-pages
demo: http://scotte.github.io/jekyll-clean
author: Scott Emmons
thumbnail: jekyll-clean.png
license: Creative Commons Attribution International 4.0
license_link: https://creativecommons.org/licenses/by/4.0/legalcode
---

A simple and clean Jekyll theme that's easy to modify and very modular in component
and element reuse. The theme works well on mobile devices as well, using bootstrap
for much of the heavy lifting.

This theme uses Disqus for comments and includes Google Analytics support (both are
disabled out of the box).

Check out the demo - that's the live github branch and exactly what you'll get when
you clone it.

Enjoy!


text:
package kocha

// Flash represents a container of flash messages.
// Flash is for the one-time messaging between requests. It useful for
// implementing the Post/Redirect/Get pattern.
type Flash map[string]FlashData

// Get gets a value associated with the given key.
// If there is the no value associated with the key, Get returns "".
func (f Flash) Get(key string) string {
	if f == nil {
		return ""
	}
	data, exists := f[key]
	if !exists {
		return ""
	}
	data.Loaded = true
	f[key] = data
	return data.Data
}

// Set sets the value associated with key.
// It replaces the existing value associated with key.
func (f Flash) Set(key, value string) {
	if f == nil {
		return
	}
	data := f[key]
	data.Loaded = false
	data.Data = value
	f[key] = data
}

// Len returns a length of the dataset.
func (f Flash) Len() int {
	return len(f)
}

// deleteLoaded delete the loaded data.
func (f Flash) deleteLoaded() {
	for k, v := range f {
		if v.Loaded {
			delete(f, k)
		}
	}
}

// FlashData represents a data of flash messages.
type FlashData struct {
	Data   string // flash message.
	Loaded bool   // whether the message was loaded.
}


text:
package main

/*
	This is a translation of the example code in
	"experimental/c-api-example/skia-c-example.c" to test the
	go-skia package.
*/

import (
	"log"
	"os"

	skia "skia.googlesource.com/skia/experimental/go-skia"
)

func main() {
	imgInfo := &skia.ImageInfo{
		Width:     640,
		Height:    480,
		ColorType: skia.GetDefaultColortype(),
		AlphaType: skia.PREMUL_ALPHATYPE,
	}

	surface, err := skia.NewRasterSurface(imgInfo)
	if err != nil {
		log.Fatalln(err)
	}

	canvas := surface.Canvas()

	fillPaint := skia.NewPaint()
	fillPaint.SetColor(0xFF0000FF)
	canvas.DrawPaint(fillPaint)
	fillPaint.SetColor(0xFF00FFFF)

	rect := skia.NewRect(100, 100, 540, 380)
	canvas.DrawRect(rect, fillPaint)

	strokePaint := skia.NewPaint()
	strokePaint.SetColor(0xFFFF0000)
	strokePaint.SetAntiAlias(true)
	strokePaint.SetStroke(true)
	strokePaint.SetStrokeWidth(5.0)

	path := skia.NewPath()
	path.MoveTo(50, 50)
	path.LineTo(590, 50)
	path.CubicTo(-490, 50, 1130, 430, 50, 430)
	path.LineTo(590, 430)
	canvas.DrawPath(path, strokePaint)

	fillPaint.SetColor(0x8000FF00)
	canvas.DrawOval(skia.NewRect(120, 120, 520, 360), fillPaint)

	// // Get a skia image from the surface.
	skImg := surface.Image()

	// Write new image to file if we have one.
	if skImg != nil {
		out, err := os.Create("testimage.png")
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()

		if err := skImg.WritePNG(out); err != nil {
			log.Fatalf("Unable to write png: %s", err)
		}
	}
}


text:
var Tarsy = require("../src/tarsy.js")

// For larger examples, its best to define these oft-used functions
var assert = Tarsy.assert,
	test = Tarsy.test,
	section = Tarsy.section

function delayPromise(ms)
{
	return new Promise(function(resolve,reject) {
			setTimeout(resolve,ms)
		})
}

test("1 second test, then error", function() {
		return delayPromise(1000).then(function() {
				assert(false)
			})
	})

test("immediate pass", function() {
		assert(true)
	})

Tarsy.showResults()


text:
Ext.define('OPF.prototype.component.ContentPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.opf.prototype.component.content-panel',

    margin: 5,
    cls: 'content-panel',
    border: false,

    entityLookup: null,
    titleLookup: null,
    contentLookup: null,
    maxTitleLength: null,
    maxContentLength: null,

    initComponent: function() {

        this.titleLookup = this.titleLookup || this.entityLookup + '.panel-title';
        this.contentLookup = this.contentLookup || this.entityLookup + '.panel-text';

        this.items = [
            {
                xtype: 'text-resource-control',
                textResourceLookup: this.titleLookup,
                cls: 'content-panel-title',
                textInnerCls: 'content-panel-title-text',
                maxTextLength: this.maxTitleLength,
                autoInit: true
            },
            {
                xtype: 'splitter'
            },
            {
                xtype: 'text-resource-control',
                textResourceLookup: this.contentLookup,
                cls: 'content-panel-content',
                textInnerCls: 'content-panel-content-text',
                maxTextLength: this.maxContentLength,
                autoInit: true
            }
        ];

        this.callParent(arguments);
    }
});


text:
package org.drools.base;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import org.drools.WorkingMemory;
import org.drools.spi.KnowledgeHelper;
import org.drools.spi.Salience;
import org.drools.spi.Tuple;
import org.kie.definition.rule.Rule;

public class SalienceInteger
    implements
    Salience, Externalizable {

    private static final long serialVersionUID = 510l;

    public static final Salience DEFAULT_SALIENCE = new SalienceInteger( 0 );

    private int value;

    public SalienceInteger() {
    }

    public SalienceInteger(int value) {
        this.value = value;
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        value   = in.readInt();
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(value);
    }
    public int getValue(final KnowledgeHelper khelper,
                        final Rule rule,
                        final WorkingMemory workingMemory) {
        return this.value;
    }

    public String toString() {
        return String.valueOf( this.value );
    }

}


text:
if defined?(SimpleForm)

  class EffectiveRadioButtonsInput < SimpleForm::Inputs::CollectionRadioButtonsInput
    def input(wrapper_options = nil)
      label_method, value_method = (detect_collection_methods rescue [:first, :last])

      options[:collection] = collection
      options[:label_method] = label_method
      options[:value_method] = value_method
      options[:nested_boolean_style] = :nested if nested_boolean_style?

      # Wrapper
      options[:wrapper_html] ||= {}
      options[:wrapper_html][:class] = Array(options[:wrapper_html][:class])

      if options[:images]
        options[:wrapper_html][:class] << 'image_radio_buttons'
      end

      if options[:buttons]
        options[:wrapper_html][:class] << 'button_radio_buttons btn-group inline_radio_buttons'
        options[:wrapper_html][:data] = { toggle: 'buttons' }
      end

      if options[:inline] && !options[:buttons]
        options[:wrapper_html][:class] << 'inline_radio_buttons'
      end

      options[:wrapper_html][:class] = options[:wrapper_html][:class].join(' ')

      Effective::FormBuilderInputs::EffectiveRadioButtons.new(object, object_name, template, attribute_name, input_options, (merge_wrapper_options(input_html_options, wrapper_options) || {})).to_html
    end

  end

end


text:
package org.jasig.portal.events.aggr.tabrender;

import org.jasig.portal.events.aggr.BaseAggregation;
import org.jasig.portal.events.aggr.TimedAggregationStatistics;
import org.jasig.portal.events.aggr.tabs.AggregatedTabMapping;

/**
 * Tracks tab render stats, all times are in nanoseconds.
 *
 * @author Eric Dalquist
 */
public interface TabRenderAggregation
        extends BaseAggregation<TabRenderAggregationKey, TabRenderAggregationDiscriminator>, TimedAggregationStatistics {

    /**
     * @return Number of times the tab was rendered
     */
    int getRenderCount();

    /**
     * @return The name of the tab
     */
    AggregatedTabMapping getTabMapping();
}


text:
[![Build Status](https://travis-ci.org/xiris/xuds.svg?branch=master)](https://travis-ci.org/xiris/xuds)

Maintainer: [Christopher Silva](https://github.com/xiris) ([@xiris_](http://twitter.com/xiris_))

> Lib to update/upgrade database according system version.

## Contribute

todo

## License

[MIT license](http://opensource.org/licenses/MIT)


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BlackIris;
using BlackIris.Services;
using BlackIris.Attributes;

namespace UnitTestFile.Tests
{
    [TestClass]
    public class ArgStashTests
    {
        /* *************************************************************************************************************************************************
         * Tests the ArgStash class (A class representing a stash of command-line arguments.
         *
         *  - Once reset, the arguments are available to grab.
         *  - Find them by their switch keys, pull the switch and the value back (key value)
         *  - Once pulled, the applicable arguments (key and value) should no longer exist in the stash, so it cannot be found again.
         *
         * ORDER IS IMPORTANT !!!
         *  - Must pull by longest switches first!
         *
         ************************************************************************************************************************************************* */

        [TestMethod]
        public void ArgsStash_PopArg_Standalone_Next_Is_Switch()
        {
            /*
             * Order is important!
             * Although we've found the switch, it doesn't have a value, because the
             * next arg is also a switch. In this case can only return the switch but
             * this should never actually happen with switches that expect values.
             * */
            string[] args = new string[] { "-h", "-hdatabase", "-userpass" };
            ArgsStash argStash = new ArgsStash(args, ContractKeyValuePattern.Default, '-');
            Assert.AreEqual("-hdatabase", argStash.Pop("-hdatabase"));
            Assert.AreEqual("-userpass", argStash.Pop("-userpass"));
            Assert.AreEqual("-h", argStash.Pop("-h"));

            Assert.IsTrue(argStash.Empty);
        }

        [TestMethod]
        public void ArgsStash_PopArg_SingleArgIndexes()
        {
            /*
             * The order is important! Must insure that the longer switches are fetched before the
             * short switches in order for this to work. Perhaps in the future can find a clever method
             * but for now this will have to do.
             *
             * If more than one match is found, then an error will be generated.
             * */
            string[] args = new string[] { "-hZACTN51", "-hdatabasetblTableName", "-hdatabaseCMDB", "-userpassPassword", "-userRob", "-tr2010/09/02", "-t200" };
            ArgsStash argStash = new ArgsStash(args, ContractKeyValuePattern.Squashed, '-');

            Assert.IsTrue(argStash.Exists("-userpass"));
            Assert.AreEqual("-userpassPassword", argStash.Pop("-userpass"));
            Assert.IsFalse(argStash.Exists("-userpass"));

            argStash.Pop("-user");

            Assert.AreEqual("-hdatabasetblTableName", argStash.Pop("-hdatabasetbl"));
            argStash.Pop("-hdatabase");
            Assert.AreEqual("-hZACTN51", argStash.Pop("-h"));

            argStash.Pop("-tr");
            argStash.Pop("-t");

            Assert.IsTrue(argStash.Empty);

            Assert.IsNull(argStash.Pop("-tr"));

            argStash.Reset();

            Assert.IsTrue(argStash.Exists("-userpass"));

            Assert.IsFalse(argStash.Empty);

        }

        [TestMethod]
        public void ArgsStash_PopArg_SeperateArgIndexes()
        {
            /*
             * The order is important! Must insure that the longer switches are fetched before the
             * short switches in order for this to work. Perhaps in the future can find a clever method
             * but for now this will have to do.
             *
             * If more than one match is found, then an error will be generated.
             * */
            string[] args = new string[] { "-h", "ZACTN51", "-hdatabasetbl", "TableName", "-hdatabase", "CMDB", "-userpass", "Password", "-user", "Rob", "-tr", "2010/09/02", "-t", "200" };
            ArgsStash argStash = new ArgsStash(args, ContractKeyValuePattern.Default, '-');

            Assert.IsTrue(argStash.Exists("-userpass"));
            Assert.AreEqual("-userpassPassword", argStash.Pop("-userpass"));
            Assert.IsFalse(argStash.Exists("-userpass"));

            argStash.Pop("-user");

            Assert.AreEqual("-hdatabasetblTableName", argStash.Pop("-hdatabasetbl"));
            argStash.Pop("-hdatabase");
            Assert.AreEqual("-hZACTN51", argStash.Pop("-h"));

            argStash.Pop("-tr");
            argStash.Pop("-t");

            Assert.IsTrue(argStash.Empty);

            Assert.IsNull(argStash.Pop("-tr"));

            argStash.Reset();

            Assert.IsTrue(argStash.Exists("-userpass"));

            Assert.IsFalse(argStash.Empty);

        }
    }
}


text:
package DDG::Goodie::PrimeFactors;
# ABSTRACT: Returns all the prime factors of the entered number

use strict;
use DDG::Goodie;

use Math::Prime::Util 'factor_exp', 'is_prime';

use utf8;

zci answer_type => "prime_factors";
zci is_cached => 1;

use bignum;

triggers startend => (
    'prime factors',
    'prime factors of',
    'the prime factors of',
    'factorization of',
    'prime factorization',
    'prime factorization of',
    'factorize',
    'prime factorize',
);

sub convert_to_superscripts (_) {
    my $string = $_[0];
    $string =~ tr[+−=()0123456789]
                [⁺⁻⁼⁽⁾⁰¹²³⁴⁵⁶⁷⁸⁹ⵯ];
    return $string;
}

# This adds exponents to the prime numbers.
# It outputs both plaintext and the number that will be displayed:
# - 2^2
# - 2²
sub format_exp {
    my $factor = shift;

    if($factor->[1] > 1) {
        return "$factor->[0]^$factor->[1]", "$factor->[0]".convert_to_superscripts($factor->[1]);
    }
    return $factor->[0], $factor->[0];
}

# This goes through all the prime factors and formats them in an "n × m" format.
# It outputs both plaintext and the text that will be used in the answer.
sub format_prime {
    my @factors = @_;
    my @text_result = ();
    my @answer_result = ();

    foreach my $factor (@factors) {
        my ($text, $exp) = format_exp($factor);

        push(@text_result, $text);
        push(@answer_result, $exp);
    }

    return join(" × ", @text_result), join(" × ", @answer_result);
}

# This adds commas to the number.
# It converts 10000000 to 10,000,000.
# It was copied from http://perldoc.perl.org/perlfaq5.html#How-can-I-output-my-numbers-with-commas-added%3f
sub commify {
    no bignum;
    local $_  = shift;
    1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
    return $_;
}

# Structured answer that will be returned
sub format_answer {
    my ($plaintext, $title, $subtitle) = @_;

    return $plaintext,
    structured_answer => {
        data => {
            title => $title || $plaintext,
            subtitle => $subtitle
        },
        templates => {
            group => 'text'
        }
    };
}

handle remainder => sub {
    # Exit if it's not a digit.
    # TODO: We should accept different number formats.
    return unless /^\d+$/;

    my @factors = factor_exp($_);

    # Exit if we didn't find anything.
    if(@factors == 0) {
        return;
    }

    my $formatted = commify($_);

    # If it has only one factor then it is a prime. Except if it's 0 or 1.
    my @result;
    if(is_prime($_)) {
        @result = format_answer("$formatted is a prime number");
    } else {
        my ($text, $answer) = format_prime(@factors);
        my $subtitle = "$formatted - Prime Factors";
        my $plaintext = "The prime factorization of $formatted is $text";

        @result = format_answer($plaintext, $answer, $subtitle);
    }

    return @result;
};

1;


text:
"""
Unused functions.

Authors:
    - Arno Klein, 2015  (arno@sagebase.org)  http://binarybottle.com

Copyright 2015,  Sage Bionetworks (http://sagebase.org), Apache v2.0 License

"""

def rename_file(old_file, new_filename='', new_path='', file_append='',
                create_file=False):
    """
    Rename (and optionally copy) a file / path / file_append.

    Parameters
    ----------
    old_file : string
        old file name (full path)
    new_filename : string
        new file name (not the full path)
    new_path : string
        replacement path
    file_append : string
        append to file names
    create_file : Boolean
        copy file (or just create a string)?

    Returns
    -------
    new_filepath : string
        new file name (full path, if remove_path not set)

    Examples
    --------
    >>> from mhealthx.utils import rename_file
    >>> old_file = '/homedir/wav/test1.wav'
    >>> new_filename = ''
    >>> new_path = '.'
    >>> file_append = '.csv'
    >>> create_file = True
    >>> new_filepath = rename_file(old_file, new_filename, new_path, file_append, create_file)
    """
    import os
    from shutil import copyfile

    old_path, base_file_name = os.path.split(old_file)

    if new_filename:
        base_file_name = new_filename

    if new_path:
        new_filepath = os.path.join(new_path, base_file_name)
    else:
        new_filepath = os.path.join(old_path, base_file_name)

    if file_append:
        new_filepath = ''.join((new_filepath, file_append))

    if create_file:
        copyfile(old_file, new_filepath)

    return new_filepath

def copy_synapse_table(synapse_table_id, synapse_project_id, table_name='',
                       remove_columns=[], username='', password=''):
    """
    Copy Synapse table to another Synapse project.

    Parameters
    ----------
    synapse_table_id : string
        Synapse ID for table to copy
    synapse_project_id : string
        copy table to project with this Synapse ID
    table_name : string
        schema name of table
    remove_columns : list of strings
        column headers for columns to be removed
    username : string
        Synapse username (only needed once on a given machine)
    password : string
        Synapse password (only needed once on a given machine)

    Returns
    -------
    table_data : Pandas DataFrame
        Synapse table contents
    table_name : string
        schema name of table
    synapse_project_id : string
        Synapse ID for project within which table is to be written

    Examples
    --------
    >>> from mhealthx.xtra import copy_synapse_table
    >>> synapse_table_id = 'syn4590865'
    >>> synapse_project_id = 'syn4899451'
    >>> table_name = 'Copy of ' + synapse_table_id
    >>> remove_columns = ['audio_audio.m4a', 'audio_countdown.m4a']
    >>> username = ''
    >>> password = ''
    >>> table_data, table_name, synapse_project_id = copy_synapse_table(synapse_table_id, synapse_project_id, table_name, remove_columns, username, password)

    """
    import synapseclient
    from synapseclient import Schema
    from synapseclient.table import Table, as_table_columns

    syn = synapseclient.Synapse()

    # Log in to Synapse:
    if username and password:
        syn.login(username, password)
    else:
        syn.login()

    # Download Synapse table as a dataframe:
    results = syn.tableQuery("select * from {0}".format(synapse_table_id))
    table_data = results.asDataFrame()

    # Remove specified columns:
    if remove_columns:
        for remove_column in remove_columns:
            del table_data[remove_column]

    # Upload to Synapse table:
    table_data.index = range(table_data.shape[0])
    schema = Schema(name=table_name, columns=as_table_columns(table_data),
                    parent=synapse_project_id,
                    includeRowIdAndRowVersion=False)
    table = syn.store(Table(schema, table_data))

    return table_data, table_name, synapse_project_id

def feature_file_to_synapse_table(feature_file, raw_feature_file,
                                  source_file_id, provenance_activity_id,
                                  command, command_line,
                                  synapse_table_id, username='', password=''):
    """
    Upload files and file handle IDs to Synapse.

    Parameters
    ----------
    feature_file : string
        path to file to upload to Synapse
    raw_feature_file : string
        path to file to upload to Synapse
    source_file_id : string
        Synapse file handle ID to source file used to generate features
    provenance_activity_id : string
        Synapse provenance activity ID
    command : string
        name of command run to generate raw feature file
    command_line : string
        full command line run to generate raw feature file
    synapse_table_id : string
        Synapse table ID for table to store file handle IDs, etc.
    username : string
        Synapse username (only needed once on a given machine)
    password : string
        Synapse password (only needed once on a given machine)

    Examples
    --------
    >>> from mhealthx.xtra import feature_file_to_synapse_table
    >>> feature_file = '/Users/arno/Local/wav/test1.wav'
    >>> raw_feature_file = '/Users/arno/Local/wav/test1.wav'
    >>> source_file_id = ''
    >>> provenance_activity_id = ''
    >>> command_line = 'SMILExtract -C blah -I blah -O blah'
    >>> synapse_table_id = 'syn4899451'
    >>> username = ''
    >>> password = ''
    >>> feature_file_to_synapse_table(feature_file, raw_feature_file, source_file_id, provenance_activity_id, command_line, synapse_table_id, username, password)

    """
    import synapseclient
    from synapseclient.table import Table

    syn = synapseclient.Synapse()

    # Log in to Synapse:
    if username and password:
        syn.login(username, password)
    else:
        syn.login()

    # Store feature and raw feature files and get file handle IDs:
    file_handle = syn._chunkedUploadFile(feature_file)
    file_id = file_handle['id']
    raw_file_handle = syn._chunkedUploadFile(raw_feature_file)
    raw_file_id = raw_file_handle['id']

    # Add new row to Synapse table:
    new_rows = [[file_id, raw_file_id, source_file_id,
                 provenance_activity_id, command, command_line]]
    schema = syn.get(synapse_table_id)
    table = syn.store(Table(schema, new_rows))

    return synapse_table_id

def arff_to_csv(arff_file, output_csv_file=None):
    """
    Convert an arff file to a row.

    Column headers include lines that start with '@attribute ',
    include 'numeric', and whose intervening string is not exception_string.
    The function raises an error if the number of resulting columns does
    not equal the number of numeric values.

    Example input: arff output from openSMILE's SMILExtract command

    Adapted some formatting from:
    http://biggyani.blogspot.com/2014/08/
    converting-back-and-forth-between-weka.html

    Parameters
    ----------
    arff_file : string
        arff file (full path)
    output_csv_file : string or None
        output table file (full path)

    Returns
    -------
    row_data : Pandas Series
        output table data
    output_csv_file : string or None
        output table file (full path)

    Examples
    --------
    >>> from mhealthx.xtra import arff_to_csv
    >>> arff_file = '/Users/arno/csv/test1.csv'
    >>> output_csv_file = None #'test.csv'
    >>> row_data, output_csv_file = arff_to_csv(arff_file, output_csv_file)

    """
    import pandas as pd

    if arff_file is None:
        row_data = None
        output_csv_file = None
    else:
        try:
            # String not included as a header:
            exception_string = 'class'
            # Remove items from the left and right in the '@data' row:
            data_from_left = 1
            data_from_right = 1

            # Open arff_file:
            with open(arff_file, 'r') as fid:
                lines = fid.readlines()

            # Loop through lines of the arff file:
            columns = []
            first_numeric = False
            for iline, line in enumerate(lines):
                if '@data' in line:
                    break
                else:

                    # If line starts with '@attribute' and contains 'numeric',
                    # append intervening string as a column name,
                    # and store index as first line of column names:
                    if line.startswith('@attribute ') and 'numeric' in line:
                        if '{' in line:
                            interstring = line[11:line.index('{') - 1]
                        else:
                            interstring = line[11:line.index('numeric') - 1]

                        # If intervening string between '@attribute '
                        # and 'numeric' is not the exception_string,
                        # include as a column header:
                        if interstring != exception_string:
                            columns.append(interstring)
                            if not first_numeric:
                                first_numeric = True

                    # Else break if past first line
                    # that has '@attribute ' and 'numeric':
                    elif first_numeric:
                        break

            # Remove left and right (first and last) data items:
            data = lines[len(lines)-1].split(',')
            data = data[data_from_left:-data_from_right]

            if len(data) != len(columns):
                raise Warning("arff file doesn't conform to expected format.")

            # Construct a pandas Series:
            row_data = pd.Series(data, index=columns)

            # Save output_csv_file:
            if output_csv_file:
                row_data.to_csv(output_csv_file)

        except:
            row_data = None
            output_csv_file = None

    return row_data, output_csv_file

def concatenate_tables_vertically(tables, output_csv_file=None):
    """
    Vertically concatenate multiple table files or pandas DataFrames
    with the same column names and store as a csv table.

    Parameters
    ----------
    tables : list of table files or pandas DataFrames
        each table or dataframe has the same column names
    output_csv_file : string or None
        output table file (full path)

    Returns
    -------
    table_data : Pandas DataFrame
        output table data
    output_csv_file : string or None
        output table file (full path)

    Examples
    --------
    >>> import pandas as pd
    >>> from mhealthx.xtra import concatenate_tables_vertically
    >>> df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
    >>>                     'B': ['B0', 'B1', 'B2', 'B3'],
    >>>                     'C': ['C0', 'C1', 'C2', 'C3']},
    >>>                    index=[0, 1, 2, 3])
    >>> df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
    >>>                     'B': ['B4', 'B5', 'B6', 'B7'],
    >>>                     'C': ['C4', 'C5', 'C6', 'C7']},
    >>>                     index=[0, 1, 2, 3])
    >>> tables = [df1, df2]
    >>> tables = ['/Users/arno/csv/table1.csv', '/Users/arno/csv/table2.csv']
    >>> output_csv_file = None #'./test.csv'
    >>> table_data, output_csv_file = concatenate_tables_vertically(tables, output_csv_file)
    """
    import os
    import pandas as pd

    if not tables:
        table_data = None
        output_csv_file = None
    else:
        try:
            # pandas DataFrames:
            if type(tables[0]) == pd.DataFrame:
                tables_no_Nones = []
                for table in tables:
                    if table is not None and type(table) == pd.DataFrame:
                        tables_no_Nones.append(table)
                tables = tables_no_Nones
            # file strings:
            elif type(tables[0]) == str:
                tables_from_files = []
                for table in tables:
                    if os.path.isfile(table):
                        tables_from_files.append(pd.read_csv(table))
                    else:
                        raise Warning('{0} is not a file.'.format(table))
                tables = tables_from_files
            else:
                raise Warning("'tables' should contain strings or "
                              "pandas DataFrames.")

            # Vertically concatenate tables:
            table_data = pd.concat(tables, ignore_index=True)

            # Store as csv file:
            if output_csv_file:
                table_data.to_csv(output_csv_file, index=False)
        except:
            table_data = None
            output_csv_file = None

    return table_data, output_csv_file

def concatenate_tables_horizontally(tables, output_csv_file=None):
    """
    Horizontally concatenate multiple table files or pandas DataFrames
    that have the same number of rows and store as a csv table.

    If any one of the members of the tables list is itself a list,
    call concatenate_tables_vertically() on this list.

    Parameters
    ----------
    tables : list of strings or pandas DataFrames
        each component table has the same number of rows
    output_csv_file : string or None
        output table file (full path)

    Returns
    -------
    table_data : Pandas DataFrame
        output table data
    output_csv_file : string or None
        output table file (full path)

    Examples
    --------
    >>> import pandas as pd
    >>> from mhealthx.xtra import concatenate_tables_horizontally
    >>> df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
    >>>                     'B': ['B0', 'B1', 'B2', 'B3'],
    >>>                     'C': ['C0', 'C1', 'C2', 'C3']},
    >>>                    index=[0, 1, 2, 3])
    >>> df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
    >>>                     'B': ['B4', 'B5', 'B6', 'B7'],
    >>>                     'C': ['C4', 'C5', 'C6', 'C7']},
    >>>                     index=[0, 1, 2, 3])
    >>> tables = [df1, df2]
    >>> output_csv_file = None #'./test.csv'
    >>> table_data, output_csv_file = concatenate_tables_horizontally(tables, output_csv_file)
    """
    import os
    import pandas as pd

    from mhealthx.xtra import concatenate_tables_vertically as cat_vert

    if tables is None:
        table_data = None
        output_csv_file = None
    else:
        try:
            # Create a list of pandas DataFrames:
            tables_to_combine = []
            for table in tables:
                # pandas DataFrame:
                if type(table) == pd.DataFrame:
                    tables_to_combine.append(table)
                # file string:
                elif type(table) == str:
                    if os.path.isfile(table):
                        table_from_file = pd.read_csv(table)
                        tables_to_combine.append(table_from_file)
                    else:
                        raise Warning('{0} is not a file.'.format(table))
                # list of tables to be vertically concatenated:
                elif type(table) == list:
                    out_file = None
                    subtable, out_file = cat_vert(table, out_file)
                    tables_to_combine.append(subtable)
                else:
                    raise Warning("'tables' members are not the right types.")
            tables = tables_to_combine

            # Raise an error if tables are not equal height pandas DataFrames:
            table0 = tables[0]
            nrows = table0.shape[0]
            for table in tables:
                if table.shape[0] != nrows:
                    raise Warning("The tables have different numbers"
                                  " of rows!")

            # Horizontally concatenate tables:
            table_data = pd.concat(tables, axis=1)

            # Store as csv file:
            if output_csv_file:
                table_data.to_csv(output_csv_file, index=False)
        except:
            table_data = None
            output_csv_file = None

    return table_data, output_csv_file

def concatenate_two_tables_horizontally(table1, table2, output_csv_file=None):
    """
    Horizontally concatenate two table files or pandas DataFrames
    that have the same number of rows and store as a csv table.

    If either of the tables is itself a list,
    concatenate_two_tables_horizontally() will call
    concatenate_tables_vertically() on this list.

    Parameters
    ----------
    table1 : string or pandas DataFrame
    table2 : string or pandas DataFrame
        same number of rows as table1
    output_csv_file : string or None
        output table file (full path)

    Returns
    -------
    table_data : Pandas DataFrame
        output table data
    output_csv_file : string or None
        output table file (full path)

    Examples
    --------
    >>> import pandas as pd
    >>> from mhealthx.xtra import concatenate_two_tables_horizontally
    >>> table1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
    >>>                     'B': ['B0', 'B1', 'B2', 'B3'],
    >>>                     'C': ['C0', 'C1', 'C2', 'C3']},
    >>>                    index=[0, 1, 2, 3])
    >>> table2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
    >>>                     'B': ['B4', 'B5', 'B6', 'B7'],
    >>>                     'C': ['C4', 'C5', 'C6', 'C7']},
    >>>                     index=[0, 1, 2, 3])
    >>> output_csv_file = None #'./test.csv'
    >>> table_data, output_csv_file = concatenate_two_tables_horizontally(table1, table2, output_csv_file)
    """
    from mhealthx.xtra import concatenate_tables_horizontally as cat_horz

    tables = [table1, table2]
    table_data, output_csv_file = cat_horz(tables, output_csv_file)

    return table_data, output_csv_file

# ============================================================================
# Run above functions to convert all voice files to wav and upload to Synapse:
# ============================================================================
if __name__ == '__main__':

    pass


text:
@echo off
bundler\SqlBundler.exe ..\..\..\..\ "db/PostgreSQL/1.x/1.0" false
copy core.sql core-blank.sql
del core.sql
copy core-blank.sql ..\..\core-blank.sql


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.taverna.server.master.common.RunReference (Apache Taverna Server 3.1.0-incubating API)</title>
<meta name="date" content="2018-01-18">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.taverna.server.master.common.RunReference

Packages that use RunReference

Package
Description

org.apache.taverna.server.master

The core of the implementation of Taverna Server, including the
 implementations of the SOAP and REST interfaces.

org.apache.taverna.server.master.rest

This package contains the RESTful interface to Taverna Server.

org.apache.taverna.server.master.soap

This package contains the SOAP interface to Taverna Server.

Uses of RunReference in org.apache.taverna.server.master

Methods in org.apache.taverna.server.master that return RunReference

Modifier and Type
Method and Description

RunReference[]
TavernaServer.listRuns()

RunReference
TavernaServer.submitWorkflow(Workflow workflow)

RunReference
TavernaServer.submitWorkflowByURI(URI workflowURI)

RunReference
TavernaServer.submitWorkflowMTOM(WrappedWorkflow workflow)

Uses of RunReference in org.apache.taverna.server.master.rest

Fields in org.apache.taverna.server.master.rest with type parameters of type RunReference

Modifier and Type
Field and Description

List<RunReference>
TavernaServerREST.RunList.run

The references to the workflow runs.

Uses of RunReference in org.apache.taverna.server.master.soap

Methods in org.apache.taverna.server.master.soap that return RunReference

Modifier and Type
Method and Description

RunReference[]
TavernaServerSOAP.listRuns()

Get the list of existing runs owned by the user.

RunReference
TavernaServerSOAP.submitWorkflow(Workflow workflow)

Make a run for a particular workflow.

RunReference
TavernaServerSOAP.submitWorkflowByURI(URI workflowURI)

Make a run for a particular workflow, where that workflow will be
 downloaded from elsewhere.

RunReference
TavernaServerSOAP.submitWorkflowMTOM(WrappedWorkflow workflow)

Make a run for a particular workflow.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015–2018 The Apache Software Foundation. All rights reserved.


text:
<?php

/**
 * This is the model class for table "ENTITY_CONTACT".
 *
 * The followings are the available columns in table 'ENTITY_CONTACT':
 * @property integer $ID
 * @property string $CONTACT_TYPE
 * @property string $LINE1
 * @property string $LINE2
 * @property string $LINE3
 * @property string $LINE4
 * @property string $LINE5
 * @property string $CITY
 * @property string $COUNTRY
 * @property string $MOBILE_PHONE
 * @property string $REGISTRED_MOBILE
 * @property string $TELEPHONE
 * @property string $FAX
 * @property string $EMAIL
 * @property string $REGISTRED_EMAIL
 * @property string $URL
 * @property string $WEF
 * @property string $WET
 * @property integer $ENTITY_ID
 * @property integer $PARTY_ID
 *
 * The followings are the available model relations:
 * @property ENTITY $eNTITY
 * @property PARTY $pARTY
 */
class Entity_Contact extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Entity_Contact the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'ENTITY_CONTACT';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('CONTACT_TYPE, COUNTRY', 'required'),
			array('ENTITY_ID, PARTY_ID', 'numerical', 'integerOnly'=>true),
			array('CONTACT_TYPE, COUNTRY', 'length', 'max'=>30),
			array('LINE1, LINE2, LINE3, LINE4, LINE5', 'length', 'max'=>60),
			array('CITY, MOBILE_PHONE, FAX', 'length', 'max'=>50),
			array('REGISTRED_MOBILE', 'length', 'max'=>1),
			array('TELEPHONE, EMAIL, REGISTRED_EMAIL, URL', 'length', 'max'=>100),
			array('WEF, WET', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('ID, CONTACT_TYPE, LINE1, LINE2, LINE3, LINE4, LINE5, CITY, COUNTRY, MOBILE_PHONE, REGISTRED_MOBILE, TELEPHONE, FAX, EMAIL, REGISTRED_EMAIL, URL, WEF, WET, ENTITY_ID, PARTY_ID', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'eNTITY' => array(self::BELONGS_TO, 'ENTITY', 'ENTITY_ID'),
			'pARTY' => array(self::BELONGS_TO, 'PARTY', 'PARTY_ID'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'ID' => 'ID',
			'CONTACT_TYPE' => 'Contact Type',
			'LINE1' => 'Line1',
			'LINE2' => 'Line2',
			'LINE3' => 'Line3',
			'LINE4' => 'Line4',
			'LINE5' => 'Line5',
			'CITY' => 'City',
			'COUNTRY' => 'Country',
			'MOBILE_PHONE' => 'Mobile Phone',
			'REGISTRED_MOBILE' => 'Registred Mobile',
			'TELEPHONE' => 'Telephone',
			'FAX' => 'Fax',
			'EMAIL' => 'Email',
			'REGISTRED_EMAIL' => 'Registred Email',
			'URL' => 'Url',
			'WEF' => 'Wef',
			'WET' => 'Wet',
			'ENTITY_ID' => 'Entity',
			'PARTY_ID' => 'Party',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('ID',$this->ID);
		$criteria->compare('CONTACT_TYPE',$this->CONTACT_TYPE,true);
		$criteria->compare('LINE1',$this->LINE1,true);
		$criteria->compare('LINE2',$this->LINE2,true);
		$criteria->compare('LINE3',$this->LINE3,true);
		$criteria->compare('LINE4',$this->LINE4,true);
		$criteria->compare('LINE5',$this->LINE5,true);
		$criteria->compare('CITY',$this->CITY,true);
		$criteria->compare('COUNTRY',$this->COUNTRY,true);
		$criteria->compare('MOBILE_PHONE',$this->MOBILE_PHONE,true);
		$criteria->compare('REGISTRED_MOBILE',$this->REGISTRED_MOBILE,true);
		$criteria->compare('TELEPHONE',$this->TELEPHONE,true);
		$criteria->compare('FAX',$this->FAX,true);
		$criteria->compare('EMAIL',$this->EMAIL,true);
		$criteria->compare('REGISTRED_EMAIL',$this->REGISTRED_EMAIL,true);
		$criteria->compare('URL',$this->URL,true);
		$criteria->compare('WEF',$this->WEF,true);
		$criteria->compare('WET',$this->WET,true);
		$criteria->compare('ENTITY_ID',$this->ENTITY_ID);
		$criteria->compare('PARTY_ID',$this->PARTY_ID);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}


text:
package org.apache.shardingsphere.underlying.executor.kernel.fixture;

import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.underlying.executor.kernel.ExecutorCallback;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@RequiredArgsConstructor
public final class ExecutorCallbackFixture implements ExecutorCallback<Object, String> {

    private final CountDownLatch latch;

    @Override
    public Collection<String> execute(final Collection<Object> inputs, final boolean isTrunkThread, final Map<String, Object> dataMap) {
        List<String> result = new LinkedList<>();
        for (Object each : inputs) {
            latch.countDown();
            result.add("succeed");
        }
        return result;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Mastermind.Web.Models;
using Microsoft.AspNetCore.Mvc;
using MasterMind.Logic;
using System.Net.Http;
using System.IO;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Net.WebSockets;
using System.Threading;
using System.Text;
using System.Collections.Concurrent;

namespace Mastermind.Web
{
    /// <summary>
    /// A controller intercepts the incoming browser request and returns
    /// an HTML view (.cshtml file) or any other type of data.
    /// </summary>
    public class HomeController : Controller
    {
        //static string m_pendingGame = null;
        static Dictionary<Guid, GameBoard> m_openGames = new Dictionary<Guid, GameBoard>() { /*{ Guid.NewGuid(), new GameBoard(DifficultyLevels.Beginner)}, { Guid.NewGuid(), new GameBoard(DifficultyLevels.Beginner) }*/ };
        static Dictionary<Guid, GameBoard> m_existingGames = new Dictionary<Guid, GameBoard>();
        static Dictionary<Guid, QueueContainer> m_connections = new Dictionary<Guid, QueueContainer>();

        public IActionResult Index()
        {
            return View();
        }

        public JsonResult GetGames()
        {
            var games = new List<Guid>();
            foreach(var gameId in m_openGames.Keys)
            {
                games.Add(gameId);
            }

            var json = this.Json(games);
            return json;
        }

        [HttpPost]
        public JsonResult CreateNewGame([FromBody] DifficultyLevels difficulty)
        {
            var newGame = new GameBoard(difficulty);
            m_openGames.Add(newGame.GameId, newGame);
            var json = this.Json(new GameSession(newGame.GameId, PlayerRole.CodeSetter));
            return json;
        }

        [HttpPost]
        public JsonResult JoinGame([FromBody] GameSession session)
        {
            var id = session.SessionId;
            var game = m_openGames[id];
            m_openGames.Remove(id);
            m_existingGames.Add(id, game);
            session.Role = PlayerRole.CodeBreaker;
            var json = this.Json(session);
            return json;
        }

        [HttpPost]
        public HttpResponseMessage SetSecretCode([FromBody] SetCodeContainer container)
        {
            GameBoard game;
            if (m_openGames.ContainsKey(container.SessionInfo.SessionId))
            {
                game = m_openGames[container.SessionInfo.SessionId];
            }
            else
            {
                game = m_existingGames[container.SessionInfo.SessionId];
            }

            game.SetCode(container.Code);

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            return response;
        }

        public JsonResult MakeGuess([FromBody] GuessContainer guess)
        {
            var game = m_existingGames[guess.SessionInfo.SessionId];
            var result = game.MakeGuess(guess.Guess);

            var queue = m_connections[guess.SessionInfo.SessionId];
            queue.Turn.TryAdd(result);
            queue.WaitHandle.Set();

            var json = this.Json(result.GuessResults);
            return json;
        }

        public async Task LiveConnection(HttpContext context, WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

            var message = Encoding.ASCII.GetString(buffer, 0, result.Count);
            var session = JsonConvert.DeserializeObject<GameSession>(message);
            var collectionQueue = new QueueContainer();
            m_connections.Add(session.SessionId, collectionQueue);

            while (!result.CloseStatus.HasValue)
            {
                if (collectionQueue.WaitHandle.WaitOne() && collectionQueue.Turn.TryTake(out GameTurn turn))
                {
                    var turnJson = JsonConvert.SerializeObject(turn);
                    buffer = Encoding.ASCII.GetBytes(turnJson);
                    await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
                }
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }

    }

    public class QueueContainer
    {
        public AutoResetEvent WaitHandle { get; set; } = new AutoResetEvent(false);
        public BlockingCollection<GameTurn> Turn { get; set; } = new BlockingCollection<GameTurn>();
    }

    public class SetCodeContainer
    {
        public DifficultyLevels DifficultyLevel { get; set; }
        public List<GamePieces> Code { get; set; }
        public GameSession SessionInfo { get; set; }
    }

    public class GuessContainer
    {
        public List<GamePieces> Guess { get; set; }
        public GameSession SessionInfo { get; set; }
    }

    public class GameSession
    {
        public Guid SessionId { get; set; }
        public PlayerRole Role { get; set; }

        public GameSession(Guid id, PlayerRole role)
        {
            this.SessionId = id;
            this.Role = role;
        }
    }
}


text:
<!-- ********************************** start include_footer.htm ***************************************************-->
<script type="text/javascript" src='/includes/js/modernizr.js'></script>
<script type="text/javascript" src='/includes/js/jquery.js'></script>
<script type="text/javascript" src="/includes/js/foundation/foundation.js"></script>
<script type="text/JavaScript">

    $(document).foundation().foundation();

</script>
<!-- ********************************** end include_footer.htm ***************************************************-->


text:
#pragma once
#include <aws/pinpoint-sms-voice-v2/PinpointSMSVoiceV2_EXPORTS.h>
#include <aws/pinpoint-sms-voice-v2/model/ConfigurationSetFilterName.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace PinpointSMSVoiceV2
{
namespace Model
{

  /**
   *
The information for configuration sets that meet a specified
   * criteria.

See Also:
   AWS
   * API Reference

   */
  class AWS_PINPOINTSMSVOICEV2_API ConfigurationSetFilter
  {
  public:
    ConfigurationSetFilter();
    ConfigurationSetFilter(Aws::Utils::Json::JsonView jsonValue);
    ConfigurationSetFilter& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The name of the attribute to filter on.

     */
    inline const ConfigurationSetFilterName& GetName() const{ return m_name; }

    /**
     *
The name of the attribute to filter on.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The name of the attribute to filter on.

     */
    inline void SetName(const ConfigurationSetFilterName& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The name of the attribute to filter on.

     */
    inline void SetName(ConfigurationSetFilterName&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The name of the attribute to filter on.

     */
    inline ConfigurationSetFilter& WithName(const ConfigurationSetFilterName& value) { SetName(value); return *this;}

    /**
     *
The name of the attribute to filter on.

     */
    inline ConfigurationSetFilter& WithName(ConfigurationSetFilterName&& value) { SetName(std::move(value)); return *this;}

    /**
     *
An array values to filter for.

     */
    inline const Aws::Vector<Aws::String>& GetValues() const{ return m_values; }

    /**
     *
An array values to filter for.

     */
    inline bool ValuesHasBeenSet() const { return m_valuesHasBeenSet; }

    /**
     *
An array values to filter for.

     */
    inline void SetValues(const Aws::Vector<Aws::String>& value) { m_valuesHasBeenSet = true; m_values = value; }

    /**
     *
An array values to filter for.

     */
    inline void SetValues(Aws::Vector<Aws::String>&& value) { m_valuesHasBeenSet = true; m_values = std::move(value); }

    /**
     *
An array values to filter for.

     */
    inline ConfigurationSetFilter& WithValues(const Aws::Vector<Aws::String>& value) { SetValues(value); return *this;}

    /**
     *
An array values to filter for.

     */
    inline ConfigurationSetFilter& WithValues(Aws::Vector<Aws::String>&& value) { SetValues(std::move(value)); return *this;}

    /**
     *
An array values to filter for.

     */
    inline ConfigurationSetFilter& AddValues(const Aws::String& value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }

    /**
     *
An array values to filter for.

     */
    inline ConfigurationSetFilter& AddValues(Aws::String&& value) { m_valuesHasBeenSet = true; m_values.push_back(std::move(value)); return *this; }

    /**
     *
An array values to filter for.

     */
    inline ConfigurationSetFilter& AddValues(const char* value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }

  private:

    ConfigurationSetFilterName m_name;
    bool m_nameHasBeenSet;

    Aws::Vector<Aws::String> m_values;
    bool m_valuesHasBeenSet;
  };

} // namespace Model
} // namespace PinpointSMSVoiceV2
} // namespace Aws


text:
import unittest
from collections import deque

from ..import *

# ---- Queuing

class TestQueue(unittest.TestCase):
    def test_queue_simple(self):
        kernel = get_kernel()
        results = []
        async def consumer(queue, label):
              while True:
                  item = await queue.get()
                  if item is None:
                      break
                  results.append((label, item))
                  await queue.task_done()
              await queue.task_done()
              results.append(label + ' done')

        async def producer():
            queue = Queue()
            results.append('producer_start')
            await new_task(consumer(queue, 'cons1'))
            await new_task(consumer(queue, 'cons2'))
            await sleep(0.1)
            for n in range(4):
                await queue.put(n)
                await sleep(0.1)
            for n in range(2):
                await queue.put(None)
            results.append('producer_join')
            await queue.join()
            results.append('producer_done')

        kernel.add_task(producer())
        kernel.run()

        self.assertEqual(results, [
                'producer_start',
                ('cons1', 0),
                ('cons2', 1),
                ('cons1', 2),
                ('cons2', 3),
                'cons1 done',
                'cons2 done',
                'producer_join',
                'producer_done',
                ])

    def test_queue_unbounded(self):
        kernel = get_kernel()
        results = []
        async def consumer(queue, label):
              while True:
                  item = await queue.get()
                  if item is None:
                      break
                  results.append((label, item))
                  await queue.task_done()
              await queue.task_done()
              results.append(label + ' done')

        async def producer():
            queue = Queue()
            results.append('producer_start')
            await new_task(consumer(queue, 'cons1'))
            await sleep(0.1)
            for n in range(4):
                await queue.put(n)
            await queue.put(None)
            results.append('producer_join')
            await queue.join()
            results.append('producer_done')

        kernel.add_task(producer())
        kernel.run()

        self.assertEqual(results, [
                'producer_start',
                ('cons1', 0),
                ('cons1', 1),
                ('cons1', 2),
                ('cons1', 3),
                'cons1 done',
                'producer_join',
                'producer_done',
                ])

    def test_queue_bounded(self):
        kernel = get_kernel()
        results = []
        async def consumer(queue, label):
              while True:
                  item = await queue.get()
                  if item is None:
                      break
                  results.append((label, item))
                  await sleep(0.1)
                  await queue.task_done()
              await queue.task_done()
              results.append(label + ' done')

        async def producer():
            queue = Queue(maxsize=2)
            results.append('producer_start')
            await new_task(consumer(queue, 'cons1'))
            await sleep(0.1)
            for n in range(4):
                await queue.put(n)
                results.append(('produced', n))
            await queue.put(None)
            results.append('producer_join')
            await queue.join()
            results.append('producer_done')

        kernel.add_task(producer())
        kernel.run()

        self.assertEqual(results, [
                'producer_start',
                ('cons1', 0),
                ('produced', 0),
                ('produced', 1),
                ('produced', 2),
                ('produced', 3),
                ('cons1', 1),
                'producer_join',
                ('cons1', 2),
                ('cons1', 3),
                'producer_done',
                'cons1 done',
                ])

    def test_queue_get_cancel(self):
        # Make sure a blocking get can be cancelled
        kernel = get_kernel()
        results = []
        async def consumer():
              queue = Queue()
              try:
                  results.append('consumer waiting')
                  item = await queue.get()
                  results.append('not here')
              except CancelledError:
                  results.append('consumer cancelled')

        async def driver():
            task = await new_task(consumer())
            await sleep(0.5)
            await task.cancel()

        kernel.add_task(driver())
        kernel.run()
        self.assertEqual(results, [
                'consumer waiting',
                'consumer cancelled'
                ])

    def test_queue_put_cancel(self):
        # Make sure a blocking put() can be cancelled
        kernel = get_kernel()
        results = []

        async def producer():
            queue = Queue(1)
            results.append('producer_start')
            await queue.put(0)
            try:
                await queue.put(1)
                results.append('not here')
            except CancelledError:
                results.append('producer_cancel')

        async def driver():
            task = await new_task(producer())
            await sleep(0.5)
            await task.cancel()

        kernel.add_task(driver())
        kernel.run()
        self.assertEqual(results, [
                'producer_start',
                'producer_cancel'
                ])

    def test_queue_get_timeout(self):
        # Make sure a blocking get respects timeouts
        kernel = get_kernel()
        results = []
        async def consumer():
              queue = Queue()
              try:
                  results.append('consumer waiting')
                  item = await queue.get(timeout=0.5)
                  results.append('not here')
              except TimeoutError:
                  results.append('consumer timeout')

        kernel.add_task(consumer())
        kernel.run()
        self.assertEqual(results, [
                'consumer waiting',
                'consumer timeout'
                ])

    def test_queue_put_timeout(self):
        # Make sure a blocking put() respects timeouts
        kernel = get_kernel()
        results = []

        async def producer():
            queue = Queue(1)
            results.append('producer start')
            await queue.put(0)
            try:
                await queue.put(1, timeout=0.5)
                results.append('not here')
            except TimeoutError:
                results.append('producer timeout')

        kernel.add_task(producer())
        kernel.run()
        self.assertEqual(results, [
                'producer start',
                'producer timeout'
                ])

    '''
    def test_queue_put_nowait(self):
        q = Queue(1)
        q.put_nowait(1)
        self.assertTrue(q.full())
        self.assertEqual(q.qsize(), 1)
        with self.assertRaises(QueueFull):
            q.put_nowait(2)

    def test_queue_get_nowait(self):
        q = Queue()
        self.assertTrue(q.empty())
        with self.assertRaises(QueueEmpty):
            q.get_nowait()
    '''

if __name__ == '__main__':
    unittest.main()


text:
package org.dbpedia.spotlight.common.candidates;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
@NoArgsConstructor
public class SurfaceForm {

    @JsonProperty("@name")
    @SerializedName("@name")
    private String name;

    @JsonProperty("@offset")
    @SerializedName("@offset")
    private String offSet;

    @JsonProperty("resource")
    @SerializedName("resource")
    private List<CandidateResourceItem> candidateResourceItem;

    public Integer beginIndex() {
        try {
            return Integer.valueOf(offSet);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    public Integer endIndex() {
        if (name != null) {
            return beginIndex() + name.length();
        }

        return 0;
    }
}


text:
package org.jtransfo.internal;

import org.jtransfo.ConvertInterceptor;
import org.jtransfo.ConvertSourceTarget;
import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

/**
 * Test for ConvertInterceptorChainPiece.
 */
public class ConvertInterceptorChainPieceTest {

    @Test
    public void testChain() throws Exception {
        ConvertInterceptor interceptor = mock(ConvertInterceptor.class);
        ConvertSourceTarget next = mock(ConvertSourceTarget.class);
        ConvertInterceptorChainPiece chainPiece = new ConvertInterceptorChainPiece(interceptor, next);
        Object source = mock(Object.class);
        Object target = mock(Object.class);
        String[] tags = new String[] { "bla" };

        chainPiece.convert(source, target, true, tags);

        verify(interceptor).convert(source, target, true, next, tags);
    }
}


text:
star-manager
============

The management web app of the Star project.


text:
@interface BTCountlySession : NSObject

@property (nonatomic, retain, readonly) NSString *appToken;
@property (nonatomic, retain, readonly) NSURL *baseUrl;
@property (nonatomic, assign, readonly) BOOL isActive;
@property (nonatomic, retain, readonly) BTCountlyDevice *currentDevice;
@property (nonatomic, retain, readonly) NSDate *lastReportedSessionTime;

- (instancetype)initWithURL:(NSURL *)baseUrl appToken:(NSString *)appToken;

- (BOOL)beginSession;
- (BOOL)endSession;

- (BOOL)addEvent:(BTCountlyEvent *)event;

@end


text:
import math
import random
import MatrixString

count = 0

wallNum = 1
groundNum = 0
notBuildNum = -1

steps = 22
seedPower = 8
seedType = 2

## Procedurally create maps
procMap = []

def printMapRegular(newMap):
	for row in newMap:
		string = ""
		for cell in row:
			string += str(cell)
		print string

def makeRow():
	matrix = [[], []]
	appendedOnce = False
	for i in range(steps):
		# Generate matrix
		string = MatrixString.makeMatrixString(seedType, seedPower)
		newMatrix = MatrixString.makeMatrixFromString(string, seedType, seedPower, wallNum, groundNum)

		# Check new matrix
		if appendedOnce:
			height = len(matrix) - 1
			if matrix[height][len(matrix[height]) - 1] == groundNum:
				newMatrix[1][0] = groundNum
			else:
				newMatrix[0][0] = groundNum
		else:
			appendedOnce = True

		# Append new matrix
		for i in range(len(newMatrix)):
			for j in range(len(newMatrix[0])):
				matrix[i].append(newMatrix[i][j])

	return matrix

def appendToProcMap(matrix):
	for i in range(len(matrix)):
		procMap.append(matrix[i])

def connectFarRow():
	found = False

	## Look for paths
	for i in range(seedPower):
		if procMap[len(procMap) - 2][len(procMap[0]) - seedPower + i] == groundNum and procMap[len(procMap) - 3][len(procMap[0]) - seedPower + i]:
			found = True
			break

	## No path found
	if found == False:
		procMap[len(procMap) - 2][len(procMap[0]) - 1 - int(random.random() * (seedPower - 1))] = groundNum

def connectCloseRow():
	found = False

	## Look for paths
	for i in range(seedPower):
		if procMap[len(procMap) - 2][i] == groundNum and procMap[len(procMap) - 3][i]:
			found = True
			break

	## No path found
	if found == False:
		procMap[len(procMap) - 2][int(random.random() * (seedPower - 1))] = groundNum

def makeMatrix():
	appendToProcMap(makeRow())
	for i in range(steps - 1):
		appendToProcMap(makeRow())
		if i %2 == 0:
			connectFarRow()
		else:
			connectCloseRow()
makeMatrix()
printMapRegular(procMap)


text:
const error = require('sergeant/error')
const streamPromise = require('stream-to-promise')
const fs = require('fs')
const createReadStream = fs.createReadStream
const postcss = require('postcss')
const cssimport = require('postcss-import')
const presetEnv = require('postcss-preset-env')
const cssnano = require('cssnano')

module.exports = async (config) => {
  try {
    const css = await streamPromise(createReadStream(config.input, 'utf-8'))

    const plugins = [
      cssimport(),
      presetEnv({
        browsers: config.browsers,
        stage: 0,
        features: {
          'custom-properties': {
            preserve: false
          }
        }
      })
    ]

    if (!config.noMin) {
      plugins.push(cssnano({ autoprefixer: false }))
    }

    const parsed = await postcss(plugins).process(css, {
      from: config.input,
      to: config.output,
      map: { inline: false }
    })

    config.code.end(parsed.css)

    config.map.end(String(parsed.map))
  } catch (err) {
    error(err)
  }
}


text:
package com.example.android.sunshine.app;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.android.sunshine.app.data.WeatherContract;
import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry;

/**
 * A placeholder fragment containing a simple view.
 */
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String LOG_TAG = DetailFragment.class.getSimpleName();
    static final String DETAIL_URI = "URI";
    static final String DETAIL_TRANSITION_ANIMATION = "DTA";

    private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";

    private String mForecast;
    private Uri mUri;
    private boolean mTransitionAnimation;

    private static final int DETAIL_LOADER = 0;

    public static final String[] DETAIL_COLUMNS = {
            WeatherEntry.TABLE_NAME + "." + WeatherEntry._ID,
            WeatherEntry.COLUMN_DATE,
            WeatherEntry.COLUMN_SHORT_DESC,
            WeatherEntry.COLUMN_MAX_TEMP,
            WeatherEntry.COLUMN_MIN_TEMP,
            WeatherEntry.COLUMN_HUMIDITY,
            WeatherEntry.COLUMN_PRESSURE,
            WeatherEntry.COLUMN_WIND_SPEED,
            WeatherEntry.COLUMN_DEGREES,
            WeatherEntry.COLUMN_WEATHER_ID,
            // This works because the WeatherProvider returns location data joined with
            // weather data, even though they're stored in two different tables.
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING
    };

    // These indices are tied to DETAIL_COLUMNS.  If DETAIL_COLUMNS changes, these
    // must change.
    public static final int COL_WEATHER_ID = 0;
    public static final int COL_WEATHER_DATE = 1;
    public static final int COL_WEATHER_DESC = 2;
    public static final int COL_WEATHER_MAX_TEMP = 3;
    public static final int COL_WEATHER_MIN_TEMP = 4;
    public static final int COL_WEATHER_HUMIDITY = 5;
    public static final int COL_WEATHER_PRESSURE = 6;
    public static final int COL_WEATHER_WIND_SPEED = 7;
    public static final int COL_WEATHER_DEGREES = 8;
    public static final int COL_WEATHER_CONDITION_ID = 9;

    private ImageView mIconView;
    private TextView mDateView;
    private TextView mDescriptionView;
    private TextView mHighTempView;
    private TextView mLowTempView;
    private TextView mHumidityView;
    private TextView mHumidityLabelView;
    private TextView mWindView;
    private TextView mWindLabelView;
    private TextView mPressureView;
    private TextView mPressureLabelView;

    public DetailFragment() {
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle arguments = getArguments();
        if (arguments != null) {
            mUri = arguments.getParcelable(DetailFragment.DETAIL_URI);
            mTransitionAnimation = arguments.getBoolean(DetailFragment.DETAIL_TRANSITION_ANIMATION, false);
        }

        View rootView = inflater.inflate(R.layout.fragment_detail_start, container, false);
        mIconView = (ImageView) rootView.findViewById(R.id.detail_icon);
        mDateView = (TextView) rootView.findViewById(R.id.detail_date_textview);
        mDescriptionView = (TextView) rootView.findViewById(R.id.detail_forecast_textview);
        mHighTempView = (TextView) rootView.findViewById(R.id.detail_high_textview);
        mLowTempView = (TextView) rootView.findViewById(R.id.detail_low_textview);
        mHumidityView = (TextView) rootView.findViewById(R.id.detail_humidity_textview);
        mHumidityLabelView = (TextView) rootView.findViewById(R.id.detail_humidity_label_textview);
        mWindView = (TextView) rootView.findViewById(R.id.detail_wind_textview);
        mWindLabelView = (TextView) rootView.findViewById(R.id.detail_wind_label_textview);
        mPressureView = (TextView) rootView.findViewById(R.id.detail_pressure_textview);
        mPressureLabelView = (TextView) rootView.findViewById(R.id.detail_pressure_label_textview);
        return rootView;
    }

    private void finishCreatingMenu(Menu menu) {
        // Retrieve the share menu item
        MenuItem menuItem = menu.findItem(R.id.action_share);
        menuItem.setIntent(createShareForecastIntent());
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if ( getActivity() instanceof DetailActivity ){
            // Inflate the menu; this adds items to the action bar if it is present.
            inflater.inflate(R.menu.detailfragment, menu);
            finishCreatingMenu(menu);
        }
    }

    private Intent createShareForecastIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast + FORECAST_SHARE_HASHTAG);
        return shareIntent;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        getLoaderManager().initLoader(DETAIL_LOADER, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    void onLocationChanged( String newLocation ) {
        // replace the uri, since the location has changed
        Uri uri = mUri;
        if (null != uri) {
            long date = WeatherContract.WeatherEntry.getDateFromUri(uri);
            Uri updatedUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(newLocation, date);
            mUri = updatedUri;
            getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        if ( null != mUri ) {
            // Now create and return a CursorLoader that will take care of
            // creating a Cursor for the data being displayed.
            return new CursorLoader(
                    getActivity(),
                    mUri,
                    DETAIL_COLUMNS,
                    null,
                    null,
                    null
            );
        }
        ViewParent vp = getView().getParent();
        if ( vp instanceof CardView ) {
            ((View)vp).setVisibility(View.INVISIBLE);
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null && data.moveToFirst()) {
            ViewParent vp = getView().getParent();
            if ( vp instanceof CardView ) {
                ((View)vp).setVisibility(View.VISIBLE);
            }

            // Read weather condition ID from cursor
            int weatherId = data.getInt(COL_WEATHER_CONDITION_ID);

            if ( Utility.usingLocalGraphics(getActivity()) ) {
                mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId));
            } else {
                // Use weather art image
                Glide.with(this)
                        .load(Utility.getArtUrlForWeatherCondition(getActivity(), weatherId))
                        .error(Utility.getArtResourceForWeatherCondition(weatherId))
                        .crossFade()
                        .into(mIconView);
            }

            // Read date from cursor and update views for day of week and date
            long date = data.getLong(COL_WEATHER_DATE);
            String dateText = Utility.getFullFriendlyDayString(getActivity(),date);
            mDateView.setText(dateText);

            // Get description from weather condition ID
            String description = Utility.getStringForWeatherCondition(getActivity(), weatherId);
            mDescriptionView.setText(description);
            mDescriptionView.setContentDescription(getString(R.string.a11y_forecast, description));

            // For accessibility, add a content description to the icon field. Because the ImageView
            // is independently focusable, it's better to have a description of the image. Using
            // null is appropriate when the image is purely decorative or when the image already
            // has text describing it in the same UI component.
            mIconView.setContentDescription(getString(R.string.a11y_forecast_icon, description));

            // Read high temperature from cursor and update view
            boolean isMetric = Utility.isMetric(getActivity());

            double high = data.getDouble(COL_WEATHER_MAX_TEMP);
            String highString = Utility.formatTemperature(getActivity(), high);
            mHighTempView.setText(highString);
            mHighTempView.setContentDescription(getString(R.string.a11y_high_temp, highString));

            // Read low temperature from cursor and update view
            double low = data.getDouble(COL_WEATHER_MIN_TEMP);
            String lowString = Utility.formatTemperature(getActivity(), low);
            mLowTempView.setText(lowString);
            mLowTempView.setContentDescription(getString(R.string.a11y_low_temp, lowString));

            // Read humidity from cursor and update view
            float humidity = data.getFloat(COL_WEATHER_HUMIDITY);
            mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity));
            mHumidityView.setContentDescription(getString(R.string.a11y_humidity, mHumidityView.getText()));
            mHumidityLabelView.setContentDescription(mHumidityView.getContentDescription());

            // Read wind speed and direction from cursor and update view
            float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED);
            float windDirStr = data.getFloat(COL_WEATHER_DEGREES);
            mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));
            mWindView.setContentDescription(getString(R.string.a11y_wind, mWindView.getText()));
            mWindLabelView.setContentDescription(mWindView.getContentDescription());

            // Read pressure from cursor and update view
            float pressure = data.getFloat(COL_WEATHER_PRESSURE);
            mPressureView.setText(getString(R.string.format_pressure, pressure));
            mPressureView.setContentDescription(getString(R.string.a11y_pressure, mPressureView.getText()));
            mPressureLabelView.setContentDescription(mPressureView.getContentDescription());

            // We still need this for the share intent
            mForecast = String.format("%s - %s - %s/%s", dateText, description, high, low);

        }
        AppCompatActivity activity = (AppCompatActivity)getActivity();
        Toolbar toolbarView = (Toolbar) getView().findViewById(R.id.toolbar);

        // We need to start the enter transition after the data has loaded
        if ( mTransitionAnimation ) {
            activity.supportStartPostponedEnterTransition();

            if ( null != toolbarView ) {
                activity.setSupportActionBar(toolbarView);

                activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
                activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }
        } else {
            if ( null != toolbarView ) {
                Menu menu = toolbarView.getMenu();
                if ( null != menu ) menu.clear();
                toolbarView.inflateMenu(R.menu.detailfragment);
                finishCreatingMenu(toolbarView.getMenu());
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) { }
}


text:
#include "dreal/optimization/nlopt_optimizer.h"

#include <cmath>
#include <utility>

#include "dreal/util/assert.h"
#include "dreal/util/exception.h"
#include "dreal/util/logging.h"

namespace dreal {

using std::make_unique;
using std::ostream;
using std::vector;

namespace {
/// A function passed to nlopt (type = nlopt_func). Given a vector @p
/// x, returns the evaluation of @p f_data at @p x and updates @p grad
/// which is the gradient of the function @p f_data with respect to @p
/// x.
///
/// @see
/// http://nlopt.readthedocs.io/en/latest/NLopt_Reference/#objective-function.
double NloptOptimizerEvaluate(const unsigned n, const double* x, double* grad,
                              void* const f_data) {
  DREAL_ASSERT(f_data);
  auto& expression = *static_cast<CachedExpression*>(f_data);
  const Box& box{expression.box()};
  DREAL_ASSERT(n == static_cast<size_t>(box.size()));
  DREAL_ASSERT(n > 0);
  // Set up an environment.
  Environment& env{expression.mutable_environment()};
  for (size_t i = 0; i < n; ++i) {
    const Variable& var{box.variable(i)};
    if (std::isnan(x[i])) {
      throw DREAL_RUNTIME_ERROR(
          "NloptOptimizer: x[{}] = nan is detected during evaluation", i);
    }
    env[var] = x[i];
  }
  // Set up gradients.
  if (grad) {
    for (int i = 0; i < box.size(); ++i) {
      const Variable& var{box.variable(i)};
      grad[i] = expression.Differentiate(var).Evaluate(env);
    }
  }
  // Return evaluation.
  return expression.Evaluate(env);
}
}  // namespace

// ----------------
// CachedExpression
// ----------------
CachedExpression::CachedExpression(Expression e, const Box& box)
    : expression_{std::move(e)}, box_{&box} {
  DREAL_ASSERT(box_);
}

const Box& CachedExpression::box() const {
  DREAL_ASSERT(box_);
  return *box_;
}

Environment& CachedExpression::mutable_environment() { return environment_; }

const Environment& CachedExpression::environment() const {
  return environment_;
}

double CachedExpression::Evaluate(const Environment& env) const {
  return expression_.Evaluate(env);
}

const Expression& CachedExpression::Differentiate(const Variable& x) {
  auto it = gradient_.find(x);
  if (it == gradient_.end()) {
    // Not found.
    return gradient_.emplace_hint(it, x, expression_.Differentiate(x))->second;
  } else {
    return it->second;
  }
}

ostream& operator<<(ostream& os, const CachedExpression& expression) {
  return os << expression.expression_;
}

// --------------
// NloptOptimizer
// --------------
NloptOptimizer::NloptOptimizer(const nlopt::algorithm algorithm, Box bound,
                               const Config& config)
    : opt_{algorithm, static_cast<unsigned>(bound.size())},
      box_{std::move(bound)},
      delta_{config.precision()} {
  DREAL_ASSERT(delta_ > 0.0);
  DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: Box = \n{}", box_);

  // Set tolerance.
  opt_.set_ftol_rel(config.nlopt_ftol_rel());
  opt_.set_ftol_abs(config.nlopt_ftol_abs());
  opt_.set_maxeval(config.nlopt_maxeval());
  opt_.set_maxtime(config.nlopt_maxtime());
  DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: ftol_rel = {}",
                  config.nlopt_ftol_rel());
  DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: ftol_abs = {}",
                  config.nlopt_ftol_abs());
  DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: maxeval = {}",
                  config.nlopt_maxeval());
  DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: maxtime = {}",
                  config.nlopt_maxtime());

  // Set bounds.
  vector<double> lower_bounds(box_.size(), 0.0);
  vector<double> upper_bounds(box_.size(), 0.0);
  for (int i = 0; i < box_.size(); ++i) {
    lower_bounds[i] = box_[i].lb();
    upper_bounds[i] = box_[i].ub();
    DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer {} ∈ [{}, {}]",
                    box_.variable(i), lower_bounds[i], upper_bounds[i]);
  }
  opt_.set_lower_bounds(lower_bounds);
  opt_.set_upper_bounds(upper_bounds);
}

void NloptOptimizer::SetMinObjective(const Expression& objective) {
  DREAL_LOG_DEBUG("NloptOptimizer::SetMinObjective({})", objective);
  objective_ = CachedExpression{objective, box_};
  opt_.set_min_objective(NloptOptimizerEvaluate,
                         static_cast<void*>(&objective_));
}

void NloptOptimizer::AddConstraint(const Formula& formula) {
  DREAL_LOG_DEBUG("NloptOptimizer::AddConstraint({})", formula);
  if (is_conjunction(formula)) {
    for (const Formula& f : get_operands(formula)) {
      AddConstraint(f);
    }
    return;
  }
  if (is_relational(formula)) {
    return AddRelationalConstraint(formula);
  }
  if (is_negation(formula)) {
    const Formula& negated_formula{get_operand(formula)};
    if (is_relational(negated_formula)) {
      return AddRelationalConstraint(nnfizer_.Convert(negated_formula));
    }
  }
  throw DREAL_RUNTIME_ERROR(
      "NloptOptimizer::AddConstraint: Unsupported formula {}.", formula);
}

void NloptOptimizer::AddRelationalConstraint(const Formula& formula) {
  DREAL_ASSERT(is_relational(formula));
  DREAL_LOG_DEBUG("NloptOptimizer::AddRelationalconstraint({})", formula);
  bool equality{false};
  if (is_greater_than(formula) || is_greater_than_or_equal_to(formula)) {
    // f := e₁ > e₂  –>  e₂ - e₁ < 0.
    const Expression& e1{get_lhs_expression(formula)};
    const Expression& e2{get_rhs_expression(formula)};
    auto cached_expression = make_unique<CachedExpression>(e2 - e1, box_);
    constraints_.push_back(std::move(cached_expression));
  } else if (is_less_than(formula) || is_less_than_or_equal_to(formula)) {
    // f := e₁ < e₂  –>  e₁ - e₂ < 0.
    const Expression& e1{get_lhs_expression(formula)};
    const Expression& e2{get_rhs_expression(formula)};
    auto cached_expression = make_unique<CachedExpression>(e1 - e2, box_);
    constraints_.push_back(std::move(cached_expression));
  } else if (is_equal_to(formula)) {
    // f := e₁ == e₂  -> e₁ - e₂ == 0
    auto cached_expression = make_unique<CachedExpression>(
        get_lhs_expression(formula) - get_rhs_expression(formula), box_);
    constraints_.push_back(std::move(cached_expression));
    equality = true;
  } else {
    throw DREAL_RUNTIME_ERROR(
        "NloptOptimizer::AddRelationalConstraint: Unsupported formula {}.",
        formula);
  }

  if (equality) {
    opt_.add_equality_constraint(NloptOptimizerEvaluate,
                                 static_cast<void*>(constraints_.back().get()),
                                 delta_);
  } else {
    opt_.add_inequality_constraint(
        &NloptOptimizerEvaluate, static_cast<void*>(constraints_.back().get()),
        delta_);
  }
}

void NloptOptimizer::AddConstraints(const vector<Formula>& formulas) {
  for (const Formula& formula : formulas) {
    AddConstraint(formula);
  }
}

nlopt::result NloptOptimizer::Optimize(vector<double>* const x,
                                       double* const opt_f) {
  return opt_.optimize(*x, *opt_f);
}

nlopt::result NloptOptimizer::Optimize(vector<double>* const x,
                                       double* const opt_f,
                                       const Environment& env) {
  // Update objective_ and constraints_ with env.
  objective_.mutable_environment() = env;
  for (auto& constraint_ptr : constraints_) {
    constraint_ptr->mutable_environment() = env;
  }
  return Optimize(x, opt_f);
}

}  // namespace dreal


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 50(2): 372 (1972)

#### Original name
Pleurage heterochaeta Griffiths

### Remarks
null