text:
package org.seqcode.math.diff;

import java.util.ArrayList;
import java.util.Collections;

import org.seqcode.gseutils.Pair;
import org.seqcode.math.stats.Lowess;
import org.seqcode.math.stats.NegativeBinomialDistrib;

import Jama.Matrix;

/**
 * DESeqDifferentialEnrichment: implements the differential enrichment method proposed by Anders & Huber (Genome Biology 2010).
 * i.e. The DESeq method
 *
 * @author Shaun Mahony
 * @version	%I%, %G%
 */
public class DESeqDifferentialEnrichment extends DifferentialEnrichment{

	protected Normalization normalizer; //DESeq requires a separate normalization method
	protected CountsDataset data;
	protected Lowess[] lowess; //Local regression models. Indexed by condition
	protected double lowessBandwidthPct = (double)0.2;
	//DESeq parameters
	protected double[][] q; 	//Strength parameters (i.e. estimates on condition means). Indexed by unit & condition
	protected double[][] w; 	//Sample variances. Indexed by unit & condition
	protected double[][] z;		//Variance correction parameters. Indexed by unit & condition
	protected double[][] v;		//Variance estimates. Indexed by unit & condition
	protected double[] m; 	//Number of replicates for each condition. Indexed by condition

	public DESeqDifferentialEnrichment(Normalization norm){
		super();
		normalizer = norm;
	}

	@Override
	public CountsDataset execute(CountsDataset data) {
		this.data = data;
		int ref = data.getFocalCondition();
		//Normalize
		normalizer.normalize(data);
		normalizer.savePairwiseMAPlots(data, true);

		//Initialize DESeq variables
		double[][] k = data.getCounts().getArray();
		double [] scaling = data.scaling;
		int numConds = data.numConds;
		int numUnits = data.numUnits;
		int numSamples = data.numSamples;
		int [] design = data.design;
		m = new double[numConds];
		q = new double[numUnits][numConds];
		w = new double[numUnits][numConds];
		z = new double[numUnits][numConds];
		v = new double[numUnits][numConds];
		lowess = new Lowess[numConds];
		for(int c=0; c<numConds; c++){
			m[c]=0;
			for(int u=0; u<numUnits; u++){
				q[u][c]=0; w[u][c]=0; z[u][c]=0; v[u][c]=0;
			}
		}
		for(int samp=0; samp<numSamples; samp++)
			m[design[samp]]++;

		//q: Strength parameters
		for(int u=0; u<numUnits; u++){
			for(int c=0; c<numConds; c++){
				double currQ=0;
				for(int samp=0; samp<numSamples; samp++){
					if(design[samp]==c){
						currQ+=k[u][samp]/scaling[samp];
					}
				}currQ/=m[c];
				q[u][c] = currQ;
			}
		}

		//w & z: sample variance estimates
		for(int u=0; u<numUnits; u++){
			for(int c=0; c<numConds; c++){
				if(m[c]>1){
					double currW=0, currInvS=0;
					for(int samp=0; samp<numSamples; samp++){
						if(design[samp]==c){
							currW+=((k[u][samp]/scaling[samp])-q[u][c])*((k[u][samp]/scaling[samp])-q[u][c]);
							currInvS+=1/scaling[samp];
						}
					}
					currW/=(m[c]-1);
					w[u][c] = currW;
					z[u][c] = (q[u][c]/m[c])*currInvS;
				}
			}
		}

		//Construct graph of (q,w) and estimate smooth local function
		//The function is built here only for conditions that have >1 replicate
		for(int c=0; c<numConds; c++){
			if(m[c]>1){
				ArrayList<QWItem> vals = new ArrayList<QWItem>();
				for(int u=0; u<numUnits; u++)
					vals.add(new QWItem(u, q[u][c], w[u][c], z[u][c]));
				//xval must be monotonically increasing for loess method
				Collections.sort(vals);
				double[] xval = new double[numUnits];
				double[] yval = new double[numUnits];
				Matrix xy = new Matrix(numUnits,2);
				int u=0;
				for(QWItem item : vals){
					xval[u]=(double)item.q;
					yval[u]=(double)item.w;
					xy.set(u,0,item.q);
					xy.set(u,1,item.w);
					u++;
				}

				//Run Lowess
				lowess[c]= new Lowess(xval, yval, lowessBandwidthPct);
				double [] fityval = lowess[c].getYEst();

				//Variance estimates
				u=0;
				for(QWItem item : vals){
					item.v = fityval[u] - item.z;
					v[item.index][c] = item.v;
					u++;
				}

				//Print charts & data
				this.printMeanVarData(xy, data.getCondName(c));
				this.saveMeanVarPlot(xy, fityval, data.getCondName(c), true);
			}
		}

		//If the reference condition has replicates, and other conditions don't, use the reference function for those.
		if(m[ref]>1){
			for(int c=0; c<numConds; c++){
				if(m[c]==1){
					lowess[c] = lowess[ref];
		}}}

		//If reference condition has only a single replicate, pool all counts and build a single shared reference function.
		if(m[ref]==1){
			ArrayList<QWItem> vals = new ArrayList<QWItem>();
			for(int c=0; c<numConds; c++)
				for(int u=0; u<numUnits; u++)
					vals.add(new QWItem(u, q[u][c], w[u][c], z[u][c]));
			//xval must be monotonically increasing for loess method
			Collections.sort(vals);
			double[] xval = new double[numUnits];
			double[] yval = new double[numUnits];
			Matrix xy = new Matrix(numUnits,2);
			int u=0;
			for(QWItem item : vals){
				xval[u]=(double)item.q;
				yval[u]=(double)item.w;
				xy.set(u,0,item.q);
				xy.set(u,1,item.w);
				u++;
			}

			//Run Lowess
			for(int c=0; c<numConds; c++){
				lowess[c]= new Lowess(xval, yval, lowessBandwidthPct);
				double [] fityval = lowess[c].getYEst();

				//Variance estimates
				u=0;
				for(QWItem item : vals){
					item.v = fityval[u] - item.z;
					v[item.index][c] = item.v;
					u++;
				}
			}
		}

		//Update data to include mean & variance estimates
		data.setCondMeans(new Matrix(q));
		data.setCondRawVars(new Matrix(v));

		//Calculate p-values for each gene, each condition vs reference
		double[] Kref=new double[numUnits];
		double[] Kx=new double[numUnits]; //Total counts for conditions REF and X
		double[] Qzero=new double[numUnits];   //Pooled mean (under null hypothesis)
		double[] MUref=new double[numUnits];
		double[] MUx=new double[numUnits]; //Mean for conditions REF and X
		double[] SIGMAref; double[] SIGMAx; //Variance for conditions REF and X
		double[] rawSCVref=new double[numUnits];
		double[] rawSCVx=new double[numUnits]; //raw SCV
		double[] Pref=new double[numUnits]; double[] Px=new double[numUnits];
		double[] Rref=new double[numUnits]; double[] Rx=new double[numUnits];
		double[] fullVarRef = new double[numUnits];
		double[] fullVarX = new double[numUnits];

		//Iterate through each condition
		for(int x=0; x<numConds; x++){
			if(x!=ref){
				for(int u=0; u<numUnits; u++){
					//Kref
					Kref[u]=0;
					for(int samp=0; samp<numSamples; samp++){if(design[samp]==ref){Kref[u]+=k[u][samp];}}

					//Kx
					Kx[u]=0;
					for(int samp=0; samp<numSamples; samp++){if(design[samp]==x){Kx[u]+=k[u][samp];}}

					//Qzero
					Qzero[u]=0;
					for(int samp=0; samp<numSamples; samp++){
						if(design[samp]==x || design[samp]==ref){Qzero[u]+=k[u][samp]/scaling[samp];}
					}Qzero[u]/=(m[ref]+m[x]);

					//Means
					MUref[u] = Qzero[u]*(scaling[ref]*m[ref]);
					MUx[u] = Qzero[u]*(scaling[x]*m[x]);

					//Set fold
					double fold = q[u][x]>0 ? q[u][ref]/q[u][x] : q[u][ref];
					data.setCondFold(u, x, fold);
					data.setCondMean(u, x, Qzero[u]);
				}
				//Variance
				SIGMAref = lowess[ref].estimateValues(Qzero);
				SIGMAx = lowess[x].estimateValues(Qzero);
				for(int u=0; u<numUnits; u++){

					rawSCVref[u] = SIGMAref[u]/(Qzero[u]*Qzero[u]);
					rawSCVx[u] = SIGMAx[u]/(Qzero[u]*Qzero[u]);

					fullVarRef[u] = Math.max( MUref[u] + (rawSCVref[u] * Qzero[u] * Qzero[u] * (scaling[ref]*scaling[ref]*m[ref])), MUref[u] * (1+1e-8) );
					fullVarX[u] = Math.max( MUx[u] + (rawSCVx[u] * Qzero[u] * Qzero[u] * (scaling[x]*scaling[x]*m[x])), MUx[u] * (1+1e-8) );

					Pref[u] = MUref[u]/fullVarRef[u];
					Px[u] = MUx[u]/fullVarX[u];
					Rref[u] = (MUref[u]*MUref[u])/(fullVarRef[u]-MUref[u]);
					Rx[u] = (MUx[u]*MUx[u])/(fullVarX[u]-MUx[u]);

					if(Pref[u]>0 && Px[u]>0 && Rref[u]>0 && Rx[u]>0){
						Double pObs = 	NegativeBinomialDistrib.pdf( (int)Kref[u], Rref[u], Pref[u] ) *
										NegativeBinomialDistrib.pdf( (int)Kx[u], Rx[u], Px[u] );

						if(pObs.isInfinite() || pObs.isNaN()){
							data.setDEpval(u, x, 1.0);
						}else{
							Pair<Double,Double> totalAbove = addFromMiddle((int)(Kref[u]+Kx[u]), pObs, MUref[u], fullVarRef[u], MUx[u], fullVarX[u], true, 1e-4);
							Pair<Double,Double> totalBelow = addFromMiddle((int)(Kref[u]+Kx[u]), pObs, MUref[u], fullVarRef[u], MUx[u], fullVarX[u], false, 1e-4);

							double p = (totalAbove.cdr()+totalBelow.cdr())/(totalAbove.car()+totalBelow.car());
							data.setDEpval(u, x, p);
						}
					}else{
						data.setDEpval(u, x, 1.0);
					}
				}
			}
		}

		return data;
	}

	/**
	 * Method used to evaluate the upper or lower half of the p(a,b) distribution.
	 * The P value of a pair of observed count sums (kA, kB) is the sum of
	 * all probabilities less or equal to p(kA, kB), given that the overall sum is kS.
	 *
	 * This method is ported from pval.c in the DESeq code.
	 *
	 * @param kS
	 * @param pobs
	 * @param muA
	 * @param vA
	 * @param muB
	 * @param vB
	 * @param upwards
	 * @param eps
	 * @return
	 */
	private Pair<Double,Double> addFromMiddle( int kS, double pobs, double muA, double vA,
		      double muB, double vB, boolean upwards, double eps){
		int k = (int)((double)kS * muA / (muA+muB));
		if( !upwards )
			k++;
		double total = 0;
		double esttotal = NegativeBinomialDistrib.pdf(kS, (muA+muB)*(muA+muB) / (vA+vB-muA-muB), (muA+muB) / (vA+vB));
		double obstotal = 0;
		int step = 1;
		double val = 0;
		double sizeA = muA*muA / (vA-muA);
		double probA = muA/vA;
		double sizeB = muB*muB / (vB-muB);
		double probB = muB/vB;
		int knew;
		double prevval;
		while( upwards ? (k < kS) : (k > 0) ) {
			prevval = val;
			while(true){
				if( upwards ) {
					if( k + step > kS )
						step = kS - k;
					knew = k + step;
				} else {
					if( k - step < 0 )
						step = k;
					knew = k - step;
				}
				val = NegativeBinomialDistrib.pdf( knew, sizeA, probA) * NegativeBinomialDistrib.pdf( kS - knew, sizeB, probB);
				if( (step == 1) || (Math.abs( val - prevval ) < eps * esttotal/kS)  )
					break;
				step >>= 1;
			}
			k = knew;
			total += val * step;

			if( val <= pobs ) {
				if( prevval <= pobs ) {
					obstotal += val * step;
				} else {
					obstotal += val * ( 1 + (step-1) * ( pobs - val ) / ( prevval - val ) );
				}
			}
			if( (step < Integer.MAX_VALUE) && (Math.abs( val - prevval ) < eps * esttotal/kS / 4) ) {
				step <<= 1;
			}
		}
		return(new Pair<Double,Double>(total, obstotal));
	}

	/**
	 * QWItem: separate class is necessary because the Lowess class requires a sorted list of points, and
	 * we need a way to map back to the original data structure.
	 * @author Shaun Mahony
	 * @version	%I%, %G%
	 */
	public class QWItem implements Comparable<QWItem>{
		public int index;
		public double q, w;
		public double z, v;

		public QWItem(int index, double q, double w, double z){
			this.index=index;
			this.q=q;
			this.w=w;
			this.z=z;
		}

		@Override
		public int compareTo(QWItem x) {
			if(this.q<x.q){return -1;}
			else if(this.q>x.q){return 1;}
			return 0;
		}
	}
}


text:
错误消息可以直接在验证规则中指定,同时可以在 `v-show` 和 `v-if` 中使用错误消息:
```html
<validator name="validation1">
  <div class="username">
    <label for="username">username:</label>
    <input id="username" type="text" v-validate:username="{
      required: { rule: true, message: 'required you name !!' }
    }">
    <span v-if="$validation1.username.required">{{ $validation1.username.required }}</span>
  </div>
  <div class="password">
    <label for="password">password:</label>
    <input id="password" type="password" v-validate:password="{
      required: { rule: true, message: 'required you password !!' },
      minlength: { rule: 8, message: 'your password short too !!' }
    }"/>
    <span v-if="$validation1.password.required">{{ $validation1.password.required }}</span>
    <span v-if="$validation1.password.minlength">{{ $validation1.password.minlength }}</span>
  </div>
</validator>
```

也可以在 `v-for` 指令中使用错误消息:

```html
<validator name="validation1">
  <div class="username">
    <label for="username">username:</label>
    <input id="username" type="text" v-validate:username="{
      required: { rule: true, message: 'required you name !!' }
    }">
  </div>
  <div class="password">
    <label for="password">password:</label>
    <input id="password" type="password" v-validate:password="{
      required: { rule: true, message: 'required you password !!' },
      minlength: { rule: 8, message: 'your password short too !!' }
    }"/>
  </div>
  <div class="errors">
    <ul>
      <li v-for="error in $validation1.errors">
        <p>{{error.field}}: {{error.mesage}}</p>
      </li>
    </ul>
  </div>
</validator>
```

使用数据属性或计算属性来指定验证规则比使用内联验证规则更简洁。

## 错误消息枚举组件

在上例中,我们使用 `v-for` 指令来枚举验证器的 `errors`。但是,我们可以让它更简单。本验证器提供了非常易用的 `validator-errors` 组件来枚举错误消息,如下例所示:

```html
<validator name="validation1">
  <div class="username">
    <label for="username">username:</label>
    <input id="username" type="text" v-validate:username="{
      required: { rule: true, message: 'required you name !!' }
    }">
  </div>
  <div class="password">
    <label for="password">password:</label>
    <input id="password" type="password" v-validate:password="{
      required: { rule: true, message: 'required you password !!' },
      minlength: { rule: 8, message: 'your password short too !!' }
    }"/>
  </div>
  <div class="errors">
    <validator-errors :validation="$validation1"></validator-errors>
  </div>
</validator>
```

上例的代码渲染出的界面如下:

```html
<div class="username">
  <label for="username">username:</label>
  <input id="username" type="text">
</div>
<div class="password">
  <label for="password">password:</label>
  <input id="password" type="password">
</div>
<div class="errors">
  <div>
    <p>password: your password short too !!</p>
  </div>
  <div>
    <p>password: required you password !!</p>
  </div>
  <div>
    <p>username: required you name !!</p>
  </div>
</div>
```

## 自定义错误消息模版

如果你不喜欢 `validator-errors` 默认的错误消息格式,可以指定自定义的组件或 partial 作为消息模版。

### 组件模版

下例中展示了使用组件作为模版:

```html
<div id="app">
  <validator name="validation1">
    <div class="username">
      <label for="username">username:</label>
      <input id="username" type="text" v-validate:username="{
        required: { rule: true, message: 'required you name !!' }
      }">
    </div>
    <div class="password">
      <label for="password">password:</label>
      <input id="password" type="password" v-validate:password="{
        required: { rule: true, message: 'required you password !!' },
        minlength: { rule: 8, message: 'your password short too !!' }
      }"/>
    </div>
    <div class="errors">
      <validator-errors :component="'custom-error'" :validation="$validation1">
      </validator-errors>
    </div>
  </validator>
</div>
```

```javascript
// register the your component with Vue.component
Vue.component('custom-error', {
  props: ['field', 'validator', 'message'],
  template: '<p class="error-{{field}}-{{validator}}">{{message}}</p>'
})

new Vue({ el: '#app' })
```

### Partial 模版

下例中展示了使用 partial 作为模版:

```html
<div id="app">
  <validator name="validation1">
    <div class="username">
      <label for="username">username:</label>
      <input id="username" type="text" v-validate:username="{
        required: { rule: true, message: 'required you name !!' }
      }">
    </div>
    <div class="password">
      <label for="password">password:</label>
      <input id="password" type="password" v-validate:password="{
        required: { rule: true, message: 'required you password !!' },
        minlength: { rule: 8, message: 'your password short too !!' }
      }"/>
    </div>
    <div class="errors">
      <validator-errors partial="myErrorTemplate" :validation="$validation1">
      </validator-errors>
    </div>
  </validator>
</div>
```

```javascript
// register custom error template
Vue.partial('myErrorTemplate', '<p>{{field}}: {{validator}}: {{message}}</p>')
new Vue({ el: '#app' })
```

### 指定错误消息

有时候你只需要输出部分错误消息,此时你可以通过 `group` 或 `field` 属性来指定这部分验证结果。

- `group`: 指定组的错误消息 (例如 $validation.group1.errors)
- `field`: 指定字段的错误消息 (例如 $validation.field1.errors)

下例中展示了 `group` 属性的使用:

```html
<div id="app">
  <validator :groups="['profile', 'password']" name="validation1">
    <div class="username">
      <label for="username">username:</label>
      <input id="username" type="text" group="profile" v-validate:username="{
        required: { rule: true, message: 'required you name !!' }
      }">
    </div>
    <div class="url">
      <label for="url">url:</label>
      <input id="url" type="text" group="profile" v-validate:url="{
        required: { rule: true, message: 'required you name !!' },
        url: { rule: true, message: 'invalid url format' }
      }">
    </div>
     <div class="old">
     <label for="old">old password:</label>
      <input id="old" type="password" group="password" v-validate:old="{
        required: { rule: true, message: 'required you old password !!' },
        minlength: { rule: 8, message: 'your old password short too !!' }
      }"/>
    </div>
    <div class="new">
      <label for="new">new password:</label>
      <input id="new" type="password" group="password" v-validate:new="{
        required: { rule: true, message: 'required you new password !!' },
        minlength: { rule: 8, message: 'your new password short too !!' }
      }"/>
    </div>
    <div class="confirm">
      <label for="confirm">confirm password:</label>
      <input id="confirm" type="password" group="password" v-validate:confirm="{
        required: { rule: true, message: 'required you confirm password !!' },
        minlength: { rule: 8, message: 'your confirm password short too !!' }
      }"/>
    </div>
    <div class="errors">
      <validator-errors group="profile" :validation="$validation1">
      </validator-errors>
    </div>
  </validator>
</div>
```

```javascript
Vue.validator('url', function (val) {
  return /^(http\:\/\/|https\:\/\/)(.{4,})$/.test(val)
})
new Vue({ el: '#app' })
```

## 手动设置错误消息

有时候你需要手动设置验证错误的消息,如从服务器端得到的验证错误消息。这时你可以通过 `$setValidationErrors` 方法设置错误消息,如下例:

```html
<div id="app">
  <validator name="validation">
    <div class="username">
      <label for="username">username:</label>
      <input id="username" type="text" v-model="username" v-validate:username="{
        required: { rule: true, message: 'required you name !!' }
      }">
    </div>
    <div class="old">
      <label for="old">old password:</label>
      <input id="old" type="password" v-model="passowrd.old" v-validate:old="{
        required: { rule: true, message: 'required you old password !!' }
      }"/>
    </div>
    <div class="new">
      <label for="new">new password:</label>
      <input id="new" type="password" v-model="password.new" v-validate:new="{
        required: { rule: true, message: 'required you new password !!' },
        minlength: { rule: 8, message: 'your new password short too !!' }
      }"/>
    </div>
    <div class="confirm">
      <label for="confirm">confirm password:</label>
      <input id="confirm" type="password" v-validate:confirm="{
        required: { rule: true, message: 'required you confirm password !!' },
        confirm: { rule: passowd.new, message: 'your confirm password incorrect !!' }
      }"/>
    </div>
    <div class="errors">
      <validator-errors :validation="$validation"></validator-errors>
    </div>
    <button type="button" v-if="$validation.valid" @click.prevent="onSubmit">update</button>
  </validator>
</div>
```
```javascript
new Vue({
  el: '#app',
  data: {
    id: 1,
    username: '',
    password: {
      old: '',
      new: ''
    }
  },
  validators: {
    confirm: function (val, target) {
      return val === target
    }
  },
  methods: {
    onSubmit: function () {
      var self = this
      var resource = this.$resource('/user/:id')
      resource.save({ id: this.id }, {
        username: this.username,
        passowrd: this.new
      }, function (data, stat, req) {
        // something handle success ...
        // ...
      }).error(function (data, stat, req) {
        // handle server error
        self.$setValidationErrors([
          { field: data.field, message: data.message }
        ])
      })
    }
  }
})
```

redpajama_set_name: RedPajamaGithub


text:
package controllers

import (
	"github.com/revel/revel"
	"net/url"
	"rssify/app/models"
)

type Api struct {
	App
}

func (c Api) Show() revel.Result {
	u, err := url.ParseRequestURI(c.Request.RequestURI)

	if err != nil {

	}

	q := u.Query()

	vk := &models.VKFeed{q.Get("g")}
	posts, err := vk.GetFeed()

	if err != nil {

	}

	c.Response.ContentType = "application/xml"
	return c.RenderText(posts)
}


text:
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { repeat } from 'vs/base/common/strings';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorCommand, registerEditorCommand, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { CompletionItem, CompletionItemKind } from 'vs/editor/common/modes';
import { Choice } from 'vs/editor/contrib/snippet/snippetParser';
import { showSimpleSuggestions } from 'vs/editor/contrib/suggest/suggest';
import { ContextKeyExpr, IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ILogService } from 'vs/platform/log/common/log';
import { SnippetSession } from './snippetSession';

export class SnippetController2 implements IEditorContribution {

	static get(editor: ICodeEditor): SnippetController2 {
		return editor.getContribution<SnippetController2>('snippetController2');
	}

	static InSnippetMode = new RawContextKey('inSnippetMode', false);
	static HasNextTabstop = new RawContextKey('hasNextTabstop', false);
	static HasPrevTabstop = new RawContextKey('hasPrevTabstop', false);

	private readonly _inSnippet: IContextKey<boolean>;
	private readonly _hasNextTabstop: IContextKey<boolean>;
	private readonly _hasPrevTabstop: IContextKey<boolean>;

	private _session?: SnippetSession;
	private _snippetListener: IDisposable[] = [];
	private _modelVersionId: number;
	private _currentChoice?: Choice;

	constructor(
		private readonly _editor: ICodeEditor,
		@ILogService private readonly _logService: ILogService,
		@IContextKeyService contextKeyService: IContextKeyService
	) {
		this._inSnippet = SnippetController2.InSnippetMode.bindTo(contextKeyService);
		this._hasNextTabstop = SnippetController2.HasNextTabstop.bindTo(contextKeyService);
		this._hasPrevTabstop = SnippetController2.HasPrevTabstop.bindTo(contextKeyService);
	}

	dispose(): void {
		this._inSnippet.reset();
		this._hasPrevTabstop.reset();
		this._hasNextTabstop.reset();
		dispose(this._session);
	}

	getId(): string {
		return 'snippetController2';
	}

	insert(
		template: string,
		overwriteBefore: number = 0, overwriteAfter: number = 0,
		undoStopBefore: boolean = true, undoStopAfter: boolean = true,
		adjustWhitespace: boolean = true,
	): void {
		// this is here to find out more about the yet-not-understood
		// error that sometimes happens when we fail to inserted a nested
		// snippet
		try {
			this._doInsert(template, overwriteBefore, overwriteAfter, undoStopBefore, undoStopAfter, adjustWhitespace);

		} catch (e) {
			this.cancel();
			this._logService.error(e);
			this._logService.error('snippet_error');
			this._logService.error('insert_template=', template);
			this._logService.error('existing_template=', this._session ? this._session._logInfo() : '<no_session>');
		}
	}

	private _doInsert(
		template: string,
		overwriteBefore: number = 0, overwriteAfter: number = 0,
		undoStopBefore: boolean = true, undoStopAfter: boolean = true,
		adjustWhitespace: boolean = true,
	): void {
		if (!this._editor.hasModel()) {
			return;
		}

		// don't listen while inserting the snippet
		// as that is the inflight state causing cancelation
		this._snippetListener = dispose(this._snippetListener);

		if (undoStopBefore) {
			this._editor.getModel().pushStackElement();
		}

		if (!this._session) {
			this._modelVersionId = this._editor.getModel().getAlternativeVersionId();
			this._session = new SnippetSession(this._editor, template, overwriteBefore, overwriteAfter, adjustWhitespace);
			this._session.insert();
		} else {
			this._session.merge(template, overwriteBefore, overwriteAfter, adjustWhitespace);
		}

		if (undoStopAfter) {
			this._editor.getModel().pushStackElement();
		}

		this._updateState();

		this._snippetListener = [
			this._editor.onDidChangeModelContent(e => e.isFlush && this.cancel()),
			this._editor.onDidChangeModel(() => this.cancel()),
			this._editor.onDidChangeCursorSelection(() => this._updateState())
		];
	}

	private _updateState(): void {
		if (!this._session || !this._editor.hasModel()) {
			// canceled in the meanwhile
			return;
		}

		if (this._modelVersionId === this._editor.getModel().getAlternativeVersionId()) {
			// undo until the 'before' state happened
			// and makes use cancel snippet mode
			return this.cancel();
		}

		if (!this._session.hasPlaceholder) {
			// don't listen for selection changes and don't
			// update context keys when the snippet is plain text
			return this.cancel();
		}

		if (this._session.isAtLastPlaceholder || !this._session.isSelectionWithinPlaceholders()) {
			return this.cancel();
		}

		this._inSnippet.set(true);
		this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder);
		this._hasNextTabstop.set(!this._session.isAtLastPlaceholder);

		this._handleChoice();
	}

	private _handleChoice(): void {
		if (!this._session || !this._editor.hasModel()) {
			this._currentChoice = undefined;
			return;
		}

		const { choice } = this._session;
		if (!choice) {
			this._currentChoice = undefined;
			return;
		}
		if (this._currentChoice !== choice) {
			this._currentChoice = choice;

			this._editor.setSelections(this._editor.getSelections()
				.map(s => Selection.fromPositions(s.getStartPosition()))
			);

			const [first] = choice.options;

			showSimpleSuggestions(this._editor, choice.options.map((option, i) => {

				// let before = choice.options.slice(0, i);
				// let after = choice.options.slice(i);

				return <CompletionItem>{
					kind: CompletionItemKind.Value,
					label: option.value,
					insertText: option.value,
					// insertText: `\${1|${after.concat(before).join(',')}|}$0`,
					// snippetType: 'textmate',
					sortText: repeat('a', i),
					range: Range.fromPositions(this._editor.getPosition()!, this._editor.getPosition()!.delta(0, first.value.length))
				};
			}));
		}
	}

	finish(): void {
		while (this._inSnippet.get()) {
			this.next();
		}
	}

	cancel(): void {
		this._inSnippet.reset();
		this._hasPrevTabstop.reset();
		this._hasNextTabstop.reset();
		dispose(this._snippetListener);
		dispose(this._session);
		this._session = undefined;
		this._modelVersionId = -1;
	}

	prev(): void {
		if (this._session) {
			this._session.prev();
		}
		this._updateState();
	}

	next(): void {
		if (this._session) {
			this._session.next();
		}
		this._updateState();
	}

	isInSnippet(): boolean {
		return Boolean(this._inSnippet.get());
	}

	getSessionEnclosingRange(): Range | undefined {
		if (this._session) {
			return this._session.getEnclosingRange();
		}
		return undefined;
	}
}

registerEditorContribution(SnippetController2);

const CommandCtor = EditorCommand.bindToContribution<SnippetController2>(SnippetController2.get);

registerEditorCommand(new CommandCtor({
	id: 'jumpToNextSnippetPlaceholder',
	precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop),
	handler: ctrl => ctrl.next(),
	kbOpts: {
		weight: KeybindingWeight.EditorContrib + 30,
		kbExpr: EditorContextKeys.editorTextFocus,
		primary: KeyCode.Tab
	}
}));
registerEditorCommand(new CommandCtor({
	id: 'jumpToPrevSnippetPlaceholder',
	precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop),
	handler: ctrl => ctrl.prev(),
	kbOpts: {
		weight: KeybindingWeight.EditorContrib + 30,
		kbExpr: EditorContextKeys.editorTextFocus,
		primary: KeyMod.Shift | KeyCode.Tab
	}
}));
registerEditorCommand(new CommandCtor({
	id: 'leaveSnippet',
	precondition: SnippetController2.InSnippetMode,
	handler: ctrl => ctrl.cancel(),
	kbOpts: {
		weight: KeybindingWeight.EditorContrib + 30,
		kbExpr: EditorContextKeys.editorTextFocus,
		primary: KeyCode.Escape,
		secondary: [KeyMod.Shift | KeyCode.Escape]
	}
}));

registerEditorCommand(new CommandCtor({
	id: 'acceptSnippet',
	precondition: SnippetController2.InSnippetMode,
	handler: ctrl => ctrl.finish(),
	// kbOpts: {
	// 	weight: KeybindingWeight.EditorContrib + 30,
	// 	kbExpr: EditorContextKeys.textFocus,
	// 	primary: KeyCode.Enter,
	// }
}));


text:
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AngularTagHelperTest.Models
{
    public class MyDbContext : DbContext
    {
        public DbSet<MyEntity> MyEntities { get; set; }
    }
}


text:
using System;
using System.IO;
using System.Runtime.CompilerServices;
#if !NETSTANDARD
using System.Runtime.Remoting;
#endif
using System.Text;
using System.Threading.Tasks;

namespace YAF.Lucene.Net.Support.IO
{

    /// <summary>
    /// Decorates a <see cref="TextWriter"/> instance and
    /// makes no assumptions about whether <see cref="IDisposable.Dispose"/>
    /// has been called on the inner instance or not. Acts like a circuit breaker -
    /// the first <see cref="ObjectDisposedException"/> caught turns it off and
    /// the rest of the calls are ignored after that point until <see cref="Reset"/>
    /// is called.
    /// <para/>
    /// The primary purpose is for using a <see cref="TextWriter"/> instance within a non-disposable
    /// parent object. Since the creator of the <see cref="TextWriter"/> ultimately is responsible for
    /// disposing it, our non-disposable object has no way of knowing whether it is safe to use the <see cref="TextWriter"/>.
    /// Wraping the <see cref="TextWriter"/> within a <see cref="SafeTextWriterWrapper"/> ensures the
    /// non-disposable object can continue to make calls to the <see cref="TextWriter"/> without raising
    /// exceptions (it is presumed that the <see cref="TextWriter"/> functionality is optional).
    /// </summary>
    internal class SafeTextWriterWrapper : TextWriter
    {
        private readonly TextWriter textWriter;
        private bool isDisposed = false;

        public SafeTextWriterWrapper(TextWriter textWriter)
        {
            this.textWriter = textWriter ?? throw new ArgumentNullException(nameof(textWriter));
        }

        public override Encoding Encoding
        {
            get
            {
                return Run(() => textWriter.Encoding);
            }
        }

        public override IFormatProvider FormatProvider
        {
            get
            {
                return Run(() => textWriter.FormatProvider);
            }
        }

        public override string NewLine
        {
            get
            {
                return Run(() => textWriter.NewLine);
            }

            set
            {
                Run(() => textWriter.NewLine = value);
            }
        }

#if !NETSTANDARD1_6
        public override void Close()
        {
            Run(() => textWriter.Close());
        }
#endif
#if !NETSTANDARD
        public override ObjRef CreateObjRef(Type requestedType)
        {
            return Run(() => textWriter.CreateObjRef(requestedType));
        }
#endif

        public override bool Equals(object obj)
        {
            return Run(() => textWriter.Equals(obj));
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public override void Flush()
        {
            Run(() => textWriter.Flush());
        }

        public override Task FlushAsync()
        {
            return Run(() => textWriter.FlushAsync());
        }

        public override int GetHashCode()
        {
            return Run(() => textWriter.GetHashCode());
        }

#if !NETSTANDARD1_6
        public override object InitializeLifetimeService()
        {
            return Run(() => textWriter.InitializeLifetimeService());
        }
#endif

        public override string ToString()
        {
            return Run(() => textWriter.ToString());
        }

        public override void Write(bool value)
        {
            Run(() => textWriter.Write(value));
        }

        public override void Write(char value)
        {
            Run(() => textWriter.Write(value));
        }

        public override void Write(char[] buffer)
        {
            Run(() => textWriter.Write(buffer));
        }

        public override void Write(char[] buffer, int index, int count)
        {
            Run(() => textWriter.Write(buffer, index, count));
        }

        public override void Write(decimal value)
        {
            Run(() => textWriter.Write(value));
        }

        public override void Write(double value)
        {
            Run(() => textWriter.Write(value));
        }

        public override void Write(float value)
        {
            Run(() => textWriter.Write(value));
        }

        public override void Write(int value)
        {
            Run(() => textWriter.Write(value));
        }

        public override void Write(long value)
        {
            Run(() => textWriter.Write(value));
        }

        public override void Write(object value)
        {
            Run(() => textWriter.Write(value));
        }

        public override void Write(string format, object arg0)
        {
            Run(() => textWriter.Write(format, arg0));
        }

        public override void Write(string format, object arg0, object arg1)
        {
            Run(() => textWriter.Write(format, arg0, arg1));
        }

        public override void Write(string format, object arg0, object arg1, object arg2)
        {
            Run(() => textWriter.Write(format, arg0, arg1, arg2));
        }

        public override void Write(string format, params object[] arg)
        {
            Run(() => textWriter.Write(format, arg));
        }

        public override void Write(string value)
        {
            Run(() => textWriter.Write(value));
        }

        //[CLSCompliant(false)]
        public override void Write(uint value)
        {
            Run(() => textWriter.Write(value));
        }

        //[CLSCompliant(false)]
        public override void Write(ulong value)
        {
            Run(() => textWriter.Write(value));
        }

        public override Task WriteAsync(char value)
        {
            return Run(() => textWriter.WriteAsync(value));
        }

        public override Task WriteAsync(char[] buffer, int index, int count)
        {
            return Run(() => textWriter.WriteAsync(buffer, index, count));
        }

        public override Task WriteAsync(string value)
        {
            return Run(() => textWriter.WriteAsync(value));
        }

        public override void WriteLine()
        {
            Run(() => textWriter.WriteLine());
        }

        public override void WriteLine(bool value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override void WriteLine(char value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override void WriteLine(char[] buffer)
        {
            Run(() => textWriter.WriteLine(buffer));
        }

        public override void WriteLine(char[] buffer, int index, int count)
        {
            Run(() => textWriter.WriteLine(buffer, index, count));
        }

        public override void WriteLine(decimal value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override void WriteLine(double value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override void WriteLine(float value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override void WriteLine(int value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override void WriteLine(long value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override void WriteLine(object value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override void WriteLine(string format, object arg0)
        {
            Run(() => textWriter.WriteLine(format, arg0));
        }

        public override void WriteLine(string format, object arg0, object arg1)
        {
            Run(() => textWriter.WriteLine(format, arg0, arg1));
        }

        public override void WriteLine(string format, object arg0, object arg1, object arg2)
        {
            Run(() => textWriter.WriteLine(format, arg0, arg1, arg2));
        }

        public override void WriteLine(string format, params object[] arg)
        {
            Run(() => textWriter.WriteLine(format, arg));
        }

        public override void WriteLine(string value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        //[CLSCompliant(false)]
        public override void WriteLine(uint value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        //[CLSCompliant(false)]
        public override void WriteLine(ulong value)
        {
            Run(() => textWriter.WriteLine(value));
        }

        public override Task WriteLineAsync()
        {
            return Run(() => textWriter.WriteLineAsync());
        }

        public override Task WriteLineAsync(char value)
        {
            return Run(() => textWriter.WriteLineAsync(value));
        }

        public override Task WriteLineAsync(char[] buffer, int index, int count)
        {
            return Run(() => textWriter.WriteLineAsync(buffer, index, count));
        }

        public override Task WriteLineAsync(string value)
        {
            return Run(() => textWriter.WriteLineAsync(value));
        }

        private void Run(Action method)
        {
            if (isDisposed) return;

            try
            {
                method();
            }
            catch (ObjectDisposedException)
            {
                isDisposed = true;
            }
        }

        private T Run<T>(Func<T> method)
        {
            if (isDisposed) return default(T);

            try
            {
                return method();
            }
            catch (ObjectDisposedException)
            {
                isDisposed = true;
                return default(T);
            }
        }

        public virtual void Reset()
        {
            isDisposed = false;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                textWriter.Dispose();
            }
        }
    }
}


text:
A replacement for process.exit that ensures stdio are fully drained before exiting.

To make a long story short, if `process.exit` is called on Windows, script output is often truncated when pipe-redirecting `stdout` or `stderr`. This module attempts to work around this issue by waiting until those streams have been completely drained before actually calling `process.exit`.

See [Node.js issue #3584](https://github.com/joyent/node/issues/3584) for further reference.

Tested in OS X 10.8, Windows 7 on Node.js 0.8.25 and 0.10.18.

Based on some code by [@vladikoff](https://github.com/vladikoff).

## Getting Started
Install the module with: `npm install exit`

```javascript
var exit = require('exit');

// These lines should appear in the output, EVEN ON WINDOWS.
console.log("omg");
console.error("yay");

// process.exit(5);
exit(5);

// These lines shouldn't appear in the output.
console.log("wtf");
console.error("bro");
```

## Don't believe me? Try it for yourself.

In Windows, clone the repo and cd to the `test\fixtures` directory. The only difference between [log.js](test/fixtures/log.js) and [log-broken.js](test/fixtures/log-broken.js) is that the former uses `exit` while the latter calls `process.exit` directly.

This test was done using cmd.exe, but you can see the same results using `| grep "std"` in either PowerShell or git-bash.

```
C:\node-exit\test\fixtures>node log.js 0 10 stdout stderr 2>&1 | find "std"
stdout 0
stderr 0
stdout 1
stderr 1
stdout 2
stderr 2
stdout 3
stderr 3
stdout 4
stderr 4
stdout 5
stderr 5
stdout 6
stderr 6
stdout 7
stderr 7
stdout 8
stderr 8
stdout 9
stderr 9

C:\node-exit\test\fixtures>node log-broken.js 0 10 stdout stderr 2>&1 | find "std"

C:\node-exit\test\fixtures>
```

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).

## Release History
2013-11-26 - v0.1.2 - Fixed a bug with hanging processes.
2013-09-26 - v0.1.1 - Fixed some bugs. It seems to actually work now!
2013-09-20 - v0.1.0 - Initial release.

## License
Copyright (c) 2013 "Cowboy" Ben Alman
Licensed under the MIT license.


text:
import React, { PropTypes } from 'react'
import classnames from 'classnames'
import {
  Button,
  Glyphicon,
  InputGroup,
  FormControl,
} from 'react-bootstrap'
import { Addon } from 'react-bootstrap/lib/InputGroup'

import * as STATIONS from '../../../constants/stations'
import classes from './SearchBar.scss'

const AccountSuggestion = (props) => {
  const handleClick = () => {
    if (!props.fetching) {
      if (props.station === STATIONS.CHECK_IN) {
        props.loadAccountData(props.accountId)
      } else if (props.station === STATIONS.CHECK_OUT) {
        props.loadEventRegistration(props.accountId)
      }
    }
  }

  return (
    <Button
      bsSize="small"
      className={classes.suggestionItem}
      onClick={handleClick}
      disabled={props.fetching}
      block
    >
      {props.name}
      {props.birthdate}
    </Button>
  )
}

AccountSuggestion.propTypes = {
  accountId: PropTypes.string,
  birthdate: PropTypes.string,
  fetching: PropTypes.bool,
  loadAccountData: PropTypes.func,
  loadEventRegistration: PropTypes.func,
  name: PropTypes.string,
  station: PropTypes.string,
}

class SearchBar extends React.Component {
  static propTypes = {
    searchForAccount: PropTypes.func,
    searching: PropTypes.bool,
    searchResults: PropTypes.arrayOf(PropTypes.object),
    loadAccountData: PropTypes.func,
    loadEventRegistration: PropTypes.func,
    fetching: PropTypes.bool,
  }

  state = {
    value: '',
  }

  handleChange = (e) => {
    this.setState({value: e.target.value})
  }

  suggest = () => {
    this.props.searchForAccount(this.state.value)
  }

  handleKeyPress = (e) => {
    // TODO: Don't persist this event, probably unnecessary
    e.persist()

    if (e.key === 'Enter') {
      this.suggest()
    }
  }

  render() {
    return (

          <InputGroup>
            <Addon>
              <Glyphicon glyph="search" />
            </Addon>
            <FormControl
              className={classnames(classes.searchInput, 'textInput')}
              type="text"
              value={this.state.value}
              onChange={this.handleChange}
              onKeyPress={this.handleKeyPress}
            />
          </InputGroup>

          <Button
            bsStyle="primary"
            onClick={this.suggest}
            disabled={this.props.searching}
            className={classes.searchButton}
          >
            {this.props.searching ? 'Searching...' : 'Search'}
          </Button>

            Search Results (Name, Date of Birth)

          {this.props.searchResults.length === 0 ? 'No results.' : null}

            {this.props.searchResults.map(result => (
              <AccountSuggestion
                accountId={result.accountId}
                birthdate={result.birthdate}
                eventRegistrationId={result.eventRegistrationId}
                fetching={this.props.fetching}
                key={result.accountId}
                loadAccountData={this.props.loadAccountData}
                loadEventRegistration={this.props.loadEventRegistration}
                name={result.name}
                station={this.props.station}
              />
            ))}

    )
  }
}

export default SearchBar


text:
<?php

/**
 * Roles collection
 *
 * @category    Mage
 * @package     Mage_Api
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Api_Model_Mysql4_Acl_Role_Collection extends Mage_Api_Model_Resource_Acl_Role_Collection
{
}


text:
import sys
import decimal
from decimal import Decimal
import PyQt4
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import pyqtSlot
import traderthread
from traderthread import Tops, ArbData
import ui_mainwindow
from ui_mainwindow import Ui_MainWindow

class MainWindow(QtGui.QMainWindow):
  def __init__(self, exchangeName):
    QtGui.QMainWindow.__init__(self)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)

    self.setWindowTitle('PyArbitrageTrader - ' + exchangeName)

    self.maxProfit = Decimal('-1')

    self.model = QtGui.QStandardItemModel()
    self.model.setHorizontalHeaderLabels(["Time",
      "TradeDirection",
      "Ask1",
      "Ask1 amount",
      "Bid1",
      "Bid1 amount",
      "Ask2",
      "Ask2 amount",
      "Bid2",
      "Bid2 amount",
      "Ask3",
      "Ask3 amount",
      "Bid3",
      "Bid3 amount",
      "ProfitPercent",
      "USD profit"])
    self.ui.tableView_history.setModel(self.model)

  @pyqtSlot(int)
  def receiveLag(self, lag):
    self.ui.spinBox_lag.setValue(lag)

  @pyqtSlot(Tops, ArbData, ArbData)
  def receiveUpdate(self, tops, a1, a2):
    self.ui.doubleSpinBox_sec1_ask.setValue(float(tops.ask1))
    self.ui.doubleSpinBox_sec1_bid.setValue(float(tops.bid1))
    self.ui.doubleSpinBox_sec2_ask.setValue(float(tops.ask2))
    self.ui.doubleSpinBox_sec2_bid.setValue(float(tops.bid2))
    self.ui.doubleSpinBox_sec3_ask.setValue(float(tops.ask3))
    self.ui.doubleSpinBox_sec3_bid.setValue(float(tops.bid3))

    self.ui.doubleSpinBox_sec1_askAmount.setValue(float(tops.ask1_amount))
    self.ui.doubleSpinBox_sec1_bidAmount.setValue(float(tops.bid1_amount))
    self.ui.doubleSpinBox_sec2_askAmount.setValue(float(tops.ask2_amount))
    self.ui.doubleSpinBox_sec2_bidAmount.setValue(float(tops.bid2_amount))
    self.ui.doubleSpinBox_sec3_askAmount.setValue(float(tops.ask3_amount))
    self.ui.doubleSpinBox_sec3_bidAmount.setValue(float(tops.bid3_amount))

    self.maxProfit = max(self.maxProfit, a1.profit, a2.profit)

    result_text = "profit1 = %s\nprofit2 = %s\nmaxProfit = %s" % (a1.profit, a2.profit, self.maxProfit)
    self.ui.label_result.setText(result_text)

    lastItem = None

    if a1.profit > 0 or a2.profit > 0:
      a = a1 if a1.profit > 0 else a2

      #print("Got arbitrage opportunity with profit %s" % a.profit)

      lastItem = QtGui.QStandardItem()
      lastItem.setText(str(a.usdProfit))
      lastItem.setToolTip(str(a.usdInvestment))

      self.model.appendRow([QtGui.QStandardItem(str(QtCore.QDateTime.currentDateTime().toString())),
      QtGui.QStandardItem(a.tradeDirection),
      QtGui.QStandardItem(str(tops.ask1)),
      QtGui.QStandardItem(str(tops.ask1_amount)),
      QtGui.QStandardItem(str(tops.bid1)),
      QtGui.QStandardItem(str(tops.bid1_amount)),
      QtGui.QStandardItem(str(tops.ask2)),
      QtGui.QStandardItem(str(tops.ask2_amount)),
      QtGui.QStandardItem(str(tops.bid2)),
      QtGui.QStandardItem(str(tops.bid2_amount)),
      QtGui.QStandardItem(str(tops.ask3)),
      QtGui.QStandardItem(str(tops.ask3_amount)),
      QtGui.QStandardItem(str(tops.bid3)),
      QtGui.QStandardItem(str(tops.bid3_amount)),
      QtGui.QStandardItem(str(a.profit * Decimal('100')) + "%"),
      lastItem])

      self.model.reset()

  #todo


text:
"""
Small utility functions.
"""

import datetime
import serial

CURSOR_HOME = chr(0x45)
CURSOR_LEFT = chr(0x15)
CURSOR_MAGIC_1 = chr(0x59)
CURSOR_MAGIC_2 = chr(0x2a)
ESCAPE = chr(0x1b)

def create_serial_connection(port):
    """Return a serial connection with the correct settings for the real sign.

    Args:
      port: Device name to connect to (eg. '/dev/ttyUSB0').

    Returns:
      Connection object.
    """
    return serial.Serial(port,
                         4800,
                         timeout=1,
                         bytesize=serial.SEVENBITS,
                         parity=serial.PARITY_ODD,
                         stopbits=serial.STOPBITS_TWO,
                         xonxoff=False,
                         rtscts=False,
                         dsrdtr=False)

def hexify(buf):
    """Return a sequence of bytes as a hexified string.

    Args:
      buf: Bytes to convert.

    Returns:
      String with the hex value of each byte, separated with colons.
    """
    return ':'.join('{0:02x}'.format(ord(c)) for c in buf)

def seconds_into_year(now):
    """Compute the number of seconds into the current year.

    Args:
      now: Current time.

    Returns:
      Number of seconds since January 1 at midnight on the same year as now.
    """
    year_start = datetime.datetime(now.year, 1, 1, 0, 0, 0, tzinfo=now.tzinfo)
    return (now - year_start).total_seconds()


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description viewport" content="A front-end template that helps you build fast, modern mobile web apps.">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Material Design Lite</title>
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css">

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/mdb.min.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet"

    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="img/android-desktop.png">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Health Tracker - RecipeFinder">
    <link rel="apple-touch-icon-precomposed" href="img/ios-desktop.png">

    <meta name="msapplication-TileImage" content="img/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <link rel="shortcut icon" href="img/favicon.ico">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.light_green-orange.min.css" />
    <link rel="stylesheet" href="css/styles.css">

	<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />

          Health Log

            hello@example.com

            <button id="accbtn" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">
              arrow_drop_down
              Accounts
            </button>

dmodi@example.com

info@example.com

addAdd another account...

          account_circleUser Profile
          restaurant_menuRecipes
          bookSaved Recipes
          assignment7 Day Planner
          assessmentHealth Tracker
          groupGroup Meal Planner
          help_outlineHelp & Support

          cancelLog Out
            <dialog class="mdl-dialog">

Are you sure you want to log out?

                <button type="button" class="mdl-button mdl-button--accent" onclick="dialog.close()">No</button>
                <button type="button" class="mdl-button close">Yes</button>

            </dialog>

                Summary

                <button  style="background-color:#FFA500; width:98.9%;" class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" >

SODIUM IntakeHIGH

                </button>

                Option 1
                Option 2
                More Options

                <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"  style="background-color:#FFA500; width:98.9%;" >

VITAMIN A IntakeMEDIUM

                </button>

                Option 1
                Option 2
                More Options

                <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"  style="background-color:#FFA500; width:98.9%;">

CARB IntakeLOW

                </button>

                Option 1
                Option 2
                More Options

                <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"  style="background-color:#FFA500; width:98.9%;" >

SUGAR IntakeLOW

                </button>

                Option 1
                Option 2
                More Options

                <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"  style="background-color:#FFA500; width:98.9%;" >

PROTEIN IntakeMEDIUM

                </button>

                Option 1
                Option 2
                More Options

                <button class="btn btn-primary" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"  style="background-color:darkorange; width:98.9%;" >

+

                </button>

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" style="position: fixed; left: -1000px; height: -1000px;">
        <defs>
          <mask id="piemask" maskContentUnits="objectBoundingBox">
            <circle cx=0.5 cy=0.5 r=0.49 fill="white" />
            <circle cx=0.5 cy=0.5 r=0.40 fill="black" />
          </mask>
          <g id="piechart">
            <circle cx=0.5 cy=0.5 r=0.5 />
            <path d="M 0.5 0.5 0.5 0 A 0.5 0.5 0 0 1 0.95 0.28 z" stroke="none" fill="rgba(255, 255, 255, 0.75)" />
          </g>
        </defs>
      </svg>
      <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 250" style="position: fixed; left: -1000px; height: -1000px;">
        <defs>
          <g id="chart">
            <g id="Gridlines">
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="27.3" x2="468.3" y2="27.3" />
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="66.7" x2="468.3" y2="66.7" />
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="105.3" x2="468.3" y2="105.3" />
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="144.7" x2="468.3" y2="144.7" />
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="184.3" x2="468.3" y2="184.3" />
            </g>
            <g id="Numbers">
              <text transform="matrix(1 0 0 1 485 29.3333)" fill="#888888" font-family="'Roboto'" font-size="9">500</text>
              <text transform="matrix(1 0 0 1 485 69)" fill="#888888" font-family="'Roboto'" font-size="9">400</text>
              <text transform="matrix(1 0 0 1 485 109.3333)" fill="#888888" font-family="'Roboto'" font-size="9">300</text>
              <text transform="matrix(1 0 0 1 485 149)" fill="#888888" font-family="'Roboto'" font-size="9">200</text>
              <text transform="matrix(1 0 0 1 485 188.3333)" fill="#888888" font-family="'Roboto'" font-size="9">100</text>
              <text transform="matrix(1 0 0 1 0 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">1</text>
              <text transform="matrix(1 0 0 1 78 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">2</text>
              <text transform="matrix(1 0 0 1 154.6667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">3</text>
              <text transform="matrix(1 0 0 1 232.1667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">4</text>
              <text transform="matrix(1 0 0 1 309 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">5</text>
              <text transform="matrix(1 0 0 1 386.6667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">6</text>
              <text transform="matrix(1 0 0 1 464.3333 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">7</text>
            </g>
            <g id="Layer_5">
              <polygon opacity="0.36" stroke-miterlimit="10" points="0,223.3 48,138.5 154.7,169 211,88.5
              294.5,80.5 380,165.2 437,75.5 469.5,223.3 	"/>
            </g>
            <g id="Layer_4">
              <polygon stroke-miterlimit="10" points="469.3,222.7 1,222.7 48.7,166.7 155.7,188.3 212,132.7
              296.7,128 380.7,184.3 436.7,125 	"/>
            </g>
          </g>
        </defs>
      </svg>


text:
package calculator;

public class ButtonPresser {

	public static void main(String[] args) {
		String result = null;
		Calculator calc = new Calculator();
		calc.printOperators();

		System.out.println("Number 1: ");
		String num1 = calc.getInput();
		System.out.println("Number 2: ");
		String num2 = calc.getInput();

		System.out.println("Operator: ");
		char operator = calc.getInput().charAt(0);

		int num1Int = Integer.parseInt(num1);
		int num2Int = Integer.parseInt(num2);
		double num1Double = Double.parseDouble(num1);
		double num2Double = Double.parseDouble(num2);

		switch (operator) {
		case '+': {
			result = Integer.toString(calc.add(num1Int, num2Int));
			break;
		}
		case '-': {
			result = Integer.toString(calc.subtract(num1Int, num2Int));
			break;
		}
		case '*': {
			result = Integer.toString(calc.multiply(num1Int, num2Int));
			break;
		}
		case '/': {
			result = Double.toString(calc.divide(num1Double, num2Double));
			break;
		}
		case '^': {
			result = Double.toString(calc.powerOf(num1Double, num2Double));
			break;
		}
		}

		System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
	}
}


text:
#!/bin/bash
# Copyright (c) 2013 The Machinecoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

if [ -d "$1" ]; then
  cd "$1" || exit 1
else
  echo "Usage: $0 <datadir>" >&2
  echo "Removes obsolete Machinecoin database files" >&2
  exit 1
fi

LEVEL=0
if [ -f wallet.dat -a -f addr.dat -a -f blkindex.dat -a -f blk0001.dat ]; then LEVEL=1; fi
if [ -f wallet.dat -a -f peers.dat -a -f blkindex.dat -a -f blk0001.dat ]; then LEVEL=2; fi
if [ -f wallet.dat -a -f peers.dat -a -f coins/CURRENT -a -f blktree/CURRENT -a -f blocks/blk00000.dat ]; then LEVEL=3; fi
if [ -f wallet.dat -a -f peers.dat -a -f chainstate/CURRENT -a -f blocks/index/CURRENT -a -f blocks/blk00000.dat ]; then LEVEL=4; fi

case $LEVEL in
  0)
    echo "Error: no Machinecoin datadir detected."
    exit 1
    ;;
  1)
    echo "Detected old Machinecoin datadir (before 0.7)."
    echo "Nothing to do."
    exit 0
    ;;
  2)
    echo "Detected Machinecoin 0.7 datadir."
    ;;
  3)
    echo "Detected Machinecoin pre-0.8 datadir."
    ;;
  4)
    echo "Detected Machinecoin 0.8 datadir."
    ;;
esac

FILES=""
DIRS=""

if [ $LEVEL -ge 3 ]; then FILES=$(echo $FILES blk????.dat blkindex.dat); fi
if [ $LEVEL -ge 2 ]; then FILES=$(echo $FILES addr.dat); fi
if [ $LEVEL -ge 4 ]; then DIRS=$(echo $DIRS coins blktree); fi

for FILE in $FILES; do
  if [ -f $FILE ]; then
    echo "Deleting: $FILE"
    rm -f $FILE
  fi
done

for DIR in $DIRS; do
  if [ -d $DIR ]; then
    echo "Deleting: $DIR/"
    rm -rf $DIR
  fi
done

echo "Done."


text:
<!--  bake includes:  bake ../includes/header.html -->

<!doctype html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><%= projectName %></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
    <link rel="stylesheet" href="./assets/stylesheets/<%= _.slugify(projectName) %>.css">
  </head>
  <body>

  </body>
</html>


text:
namespace chromeos {

class DBusThreadManager;

// PowerPolicyController is responsible for sending Chrome's assorted power
// management preferences to the Chrome OS power manager.
class CHROMEOS_EXPORT PowerPolicyController
    : public DBusThreadManagerObserver,
      public PowerManagerClient::Observer {
 public:
  // Note: Do not change these values; they are used by preferences.
  enum Action {
    ACTION_SUSPEND      = 0,
    ACTION_STOP_SESSION = 1,
    ACTION_SHUT_DOWN    = 2,
    ACTION_DO_NOTHING   = 3,
  };

  PowerPolicyController(DBusThreadManager* manager, PowerManagerClient* client);
  virtual ~PowerPolicyController();

  // Sends an updated policy to the power manager based on the current
  // values of the passed-in prefs.
  void UpdatePolicyFromPrefs(
      const PrefService::Preference& ac_screen_dim_delay_ms_pref,
      const PrefService::Preference& ac_screen_off_delay_ms_pref,
      const PrefService::Preference& ac_screen_lock_delay_ms_pref,
      const PrefService::Preference& ac_idle_warning_delay_ms_pref,
      const PrefService::Preference& ac_idle_delay_ms_pref,
      const PrefService::Preference& battery_screen_dim_delay_ms_pref,
      const PrefService::Preference& battery_screen_off_delay_ms_pref,
      const PrefService::Preference& battery_screen_lock_delay_ms_pref,
      const PrefService::Preference& battery_idle_warning_delay_ms_pref,
      const PrefService::Preference& battery_idle_delay_ms_pref,
      const PrefService::Preference& idle_action_pref,
      const PrefService::Preference& lid_closed_action_pref,
      const PrefService::Preference& use_audio_activity_pref,
      const PrefService::Preference& use_video_activity_pref,
      const PrefService::Preference& presentation_idle_delay_factor_pref);

  // Registers a request to temporarily prevent the screen from getting
  // dimmed or turned off or the system from suspending in response to user
  // inactivity.  Returns a unique ID that can be passed to RemoveBlock()
  // later.
  int AddScreenBlock(const std::string& reason);
  int AddSuspendBlock(const std::string& reason);

  // Unregisters a request previously created via AddScreenBlock() or
  // AddSuspendBlock().
  void RemoveBlock(int id);

  // DBusThreadManagerObserver implementation:
  virtual void OnDBusThreadManagerDestroying(DBusThreadManager* manager)
      OVERRIDE;

  // PowerManagerClient::Observer implementation:
  virtual void PowerManagerRestarted() OVERRIDE;

 private:
  typedef std::map<int, std::string> BlockMap;

  // Sends a policy based on |prefs_policy_| to the power manager.
  void SendCurrentPolicy();

  // Sends an empty policy to the power manager to reset its configuration.
  void SendEmptyPolicy();

  DBusThreadManager* manager_;  // not owned
  PowerManagerClient* client_;  // not owned

  // Policy specified by the prefs that were last passed to
  // UpdatePolicyFromPrefs().
  power_manager::PowerManagementPolicy prefs_policy_;

  // Are one or more fields set in |prefs_policy_|?
  bool prefs_were_set_;

  // Maps from an ID representing a request to prevent the screen from
  // getting dimmed or turned off or to prevent the system from suspending
  // to the reason for the request.
  BlockMap screen_blocks_;
  BlockMap suspend_blocks_;

  // Next ID to be used by AddScreenBlock() or AddSuspendBlock().
  int next_block_id_;

  DISALLOW_COPY_AND_ASSIGN(PowerPolicyController);
};

}  // namespace chromeos

#endif  // CHROMEOS_DBUS_POWER_POLICY_CONTROLLER_H_


text:
FROM leanprovercommunity/lean:debian

# ssh to github once to bypass the unknown fingerprint warning
RUN ssh -o StrictHostKeyChecking=no github.com || true
# clone a copy of mathlib, and download precompiled oleans
RUN leanproject get mathlib


text:
The ATRSHMLOG signal writer program.  {#files_atrshmlogsignalwriter_c}
====================================

This program uses the writer field to communicate
with a program that uses them.

Its name is

      atrshmlogsignalwriter

This is a kind of morse code tool here.

Use it as a prototype how to communicate via the
shared memory buffer and see also the fork examples.


text:
An ember-css-modules plugin is really just an Ember addon with two additional characteristics:
 - it has the `ember-css-modules-plugin` keyword in its `package.json`
 - it implements a `createCssModulesPlugin` hook in its base `index.js`

The first point is hopefully self explanatory, so let's dig in on the second. The simplest possible implementation of an ECM plugin would look something like this:

```js
// index.js
const Plugin = require('ember-css-modules/lib/plugin');

module.exports = {
  name: 'ember-css-modules-super-cool-plugin',

  createCssModulesPlugin(parent) {
    return new Plugin(parent);
  }
}
```

The `createCssModulesPlugin` method receives a reference to the plugin's parent, which is either a [`Project`](https://ember-cli.com/api/classes/Project.html) or an [`Addon`](https://ember-cli.com/api/classes/Addon.html), depending on whether the plugin was included by an app or an addon, respectively.

This isn't a particularly exciting example, though, as it doesn't actually do anything. To have any impact on the build, a plugin needs to implement one or more of the available hooks.

## Hooks

### `config(env, baseOptions)`
Very similar to an addon's [`config`](https://ember-cli.com/api/classes/Addon.html#method_config) hook, a plugin's `config` hook is invoked with the current build environment and its parent's base ember-css-modules configuration. Also like the `Addon#config` hook, a plugin can return a hash of configuration options which will be deeply merged with the base config, with the parent's own values always winning out when there's a conflict. For more complex changes, the plugin can directly mutate the `baseOptions` hash.

### `buildStart()`
Invoked each time a build or rebuild of the parent's styles begins.

### `buildEnd()`
Invoked each time a build or rebuild of the parent's styles ends, regardless of whether it succeeded or failed.

### `buildSuccess()`
Invoked each time a build or rebuild of the parent's styles successfully completes.

### `buildError()`
Invoked each time a build or rebuild of the parent's styles fails for any reason.

## Predefined Plugin Methods

### `isForAddon()`
Indicates whether this plugin's parent is an addon (which may be useful when determining things such as output paths).

### `isForApp()`
The inverse of `isForAddon()` — indicates whether this plugin's parent is an app.

### `addPostcssPlugin(config, type, ...plugins)`
Given a config hash, adds the given PostCSS plugins to that configuration, either as a `before`, `after` or `postprocess` plugin. Particularly useful within the `config` hook.

`after` and `postprocess` plugins are inserted after already registered plugins. `before` plugins are prepended to already registered plugins.
This means for `before` that if you called this method with plugins that are dependent on order of execution, you would either have to register the plugin that needs to be executed _last_ as the _first_ plugin, like so:

```js
class ExamplePlugin extends Plugin {
  config(env, baseConfig) {
    this.addPostcssPlugin(baseConfig, 'before', require('postcss-nested'));

    // needs to be executed *before* `postcss-nested` and is thus registered, *after* it
    this.addPostcssPlugin(baseConfig, 'before', require('postcss-nested-ancestors'));
  }
}
```

Because this is confusing, you should rather pass both plugins in one go, like so:

```js
class ExamplePlugin extends Plugin {
  config(env, baseConfig) {
    this.addPostcssPlugin(
      baseConfig,
      'before',
      require('postcss-nested-ancestors'),
      require('postcss-nested')
    );
  }
}
```

`addPostcssPlugin` is variadic and accepts as many plugins as you like. The order _is preserved_, when passing all plugins in one go.

## Lint Plugins

Normally, an ember-css-modules plugin will activate in exactly the same scenario a normal addon would: for apps when it's a `devDependency`, and for addons when it's a `dependency`. However, for addons this may cause an issue with plugins that provide development-time support, such as code linting. As an addon author, you wouldn't want to declare a production dependency on these plugins, but you _do_ want them to apply to your addon code while you're developing it.

To handle this case, ECM plugins may provide an additonal package keyword: `ember-css-modules-lint-plugin`. This will cause the plugin to activate for addon code **even if it's only in the dummy app's `devDependencies`** as long as that addon's `isDevelopingAddon()` hook returns `true`. Plugins like [ember-css-modules-stylelint](https://github.com/dfreeman/ember-css-modules-stylelint) take advantage of this so they can be used with addons and engines without weighing down downstream consumers with extra dependencies.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class paginas_GridResponderAvaliacao : System.Web.UI.Page
{
    void Page_PreInit(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session["PERFIL"] != null)
            {
                if (Session["PERFIL"].ToString() == "avaliador")
                    MasterPageFile = "~/paginas/MasterPageAvaliador.master";
                else
                    Response.Redirect("EscolherPerfil.aspx");
            }
            else
                Response.Redirect("EscolherPerfil.aspx");
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            carregagrid();
        }
    }

    public void carregagrid()
    {
        string ano = DateTime.Now.Year.ToString();
        string dia = DateTime.Now.Day.ToString();
        string mes = DateTime.Now.Month.ToString();
        string apos = "'";
        Usu_Usuario usuario = (Usu_Usuario)Session["usuario"];
        DataSet ava = Ava_AvaliacaoDB.SelectAvaliacaoAtivaAvaliador(usuario.Usu_codigo);
        int qtd = ava.Tables[0].Rows.Count;
        if (qtd > 0)
        {
            gdvResponderAvaliacao.DataSource = ava.Tables[0].DefaultView;
            gdvResponderAvaliacao.DataBind();
        }

    }
}


text:
package com.example.wifisharer;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;

public class ProgressActivity extends Activity{
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_redirect);

		SharedPreferences mPrefs;
		final String welcomeScreenShownPref = "welcomeScreenShown";

		    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

		    // second argument is the default to use if the preference can't be found
		    Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);

		    if (!welcomeScreenShown) {
		    	setContentView(R.layout.activity_redirect);
		        SharedPreferences.Editor editor = mPrefs.edit();
		        editor.putBoolean(welcomeScreenShownPref, true);
		        editor.commit();
		    }
		    else
		    {
		    	startActivity(new Intent(this, MainActivity.class));
		    }

		}

}


text:
import org.chasen.crfpp.Tagger;

public class test {

public static void main(String[] argv) {
  Tagger tagger = new Tagger("-m ../model -v 3 -n2");
  // clear internal context
  tagger.clear();

  // add context
  tagger.add("Confidence NN");
  tagger.add("in IN");
  tagger.add("the DT");
  tagger.add("pound NN");
  tagger.add("is VBZ");
  tagger.add("widely RB");
  tagger.add("expected VBN");
  tagger.add("to TO");
  tagger.add("take VB");
  tagger.add("another DT");
  tagger.add("sharp JJ");
  tagger.add("dive NN");
  tagger.add("if IN");
  tagger.add("trade NN");
  tagger.add("figures NNS");
  tagger.add("for IN");
  tagger.add("September NNP");

  System.out.println("column size: " + tagger.xsize());
  System.out.println("token size: " + tagger.size());
  System.out.println("tag size: " + tagger.ysize());

  System.out.println("tagset information:");
  for (int i = 0; i < tagger.ysize(); ++i) {
    System.out.println("tag " + i + " " + tagger.yname(i));
  }

  // parse and change internal stated as 'parsed'
  if (!tagger.parse())
    return;

  System.out.println("conditional prob=" + tagger.prob()
                     + " log(Z)=" + tagger.Z());

  for (int i = 0; i < tagger.size(); ++i) {
    for (int j = 0; j < tagger.xsize(); ++j) {
        System.out.print(tagger.x(i, j) + "\t");
    }
    System.out.print(tagger.y2(i) + "\t");
    System.out.print("\n");

    System.out.print("Details");
    for (int j = 0; j < tagger.ysize(); ++j) {
      System.out.print("\t" + tagger.yname(j) + "/prob=" + tagger.prob(i,j)
                       + "/alpha=" + tagger.alpha(i, j)
                       + "/beta=" + tagger.beta(i, j));
    }
    System.out.print("\n");
  }

  // when -n20 is specified, you can access nbest outputs
  System.out.println("nbest outputs:");
  for (int n = 0; n < 10; ++n) {
    if (! tagger.next()) break;
    System.out.println("nbest n=" + n + "\tconditional prob=" + tagger.prob());
    // you can access any information using tagger.y()...
  }
  System.out.println("Done");
}

static {
  try {
    System.loadLibrary("CRFPP");
  } catch (UnsatisfiedLinkError e) {
    System.err.println("Cannot load the example native code.\nMake sure your LD_LIBRARY_PATH contains \'.\'\n" + e);
    System.exit(1);
  }
}

}


text:
'use strict';
// Entry point for browser
require('./libs/react-patches');
var React = require('react');
var ReactMount = require('react/lib/ReactMount');
ReactMount.allowFullPageRender = true;

var App = require('./components');
var domready = require('domready');

// Treat domready function as the entry point to the application.
// Inside this function, kick-off all initialization, everything up to this
// point should be definitions.
if (!window.TEST_RUNNER) domready(function ready() {
    console.log('ready');
    // Set <html> class depending on browser features
    var BrowserFeat = require('./components/browserfeat').BrowserFeat;
    BrowserFeat.setHtmlFeatClass();
    var props = App.getRenderedProps(document);
    var server_stats = require('querystring').parse(window.stats_cookie);
    App.recordServerStats(server_stats, 'html');

    var app = React.render(<App {...props} />, document);

    // Simplify debugging
    window.app = app;
    window.React = React;
});


text:
<?php

namespace MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use MainBundle\Entity\Tank;
use MainBundle\Entity\Product;

/**
 * Inventory
 *
 * @ORM\Table(name="inventories")
 * @ORM\Entity(repositoryClass="MainBundle\Entity\InventoryRepository")
 * @UniqueEntity("date")
 */
class Inventory
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     * @Assert\NotBlank()
     * @ORM\Column(name="date", type="datetime", unique=true)
     */
    private $date;

    /**
     * @var float
     * @ORM\Column(name="vacuum", type="float", nullable=true)
     */
    private $vacuum;

    /**
     * @var float
     * @Assert\NotBlank()
     * @ORM\Column(name="liter", type="float")
     */
    private $liter;

        /**
     * @var string
     * @ORM\Column(name="observation", type="text", nullable=true)
     */
    private $observation;

    /**
     * @ORM\ManyToOne(targetEntity="Tank", inversedBy="inventories", cascade={"persist"})
     * @ORM\JoinColumn(name="tank_id", referencedColumnName="id", onDelete="CASCADE")
     **/
    protected $tank;

    /**
     * @ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="inventory")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     **/
    private $users;

    /**
     * @ORM\ManyToOne(targetEntity="Product", inversedBy="inventory")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     **/
    protected $product;

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

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return Inventory
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * Set vacuum
     *
     * @param float $vacuum
     * @return Inventory
     */
    public function setVacuum($vacuum)
    {
        $this->vacuum = $vacuum;

        return $this;
    }

    /**
     * Get vacuum
     *
     * @return float
     */
    public function getVacuum()
    {
        return $this->vacuum;
    }

    /**
     * Set liter
     *
     * @param float $liter
     * @return Inventory
     */
    public function setLiter($liter)
    {
        $this->liter = $liter;

        return $this;
    }

    /**
     * Get liter
     *
     * @return float
     */
    public function getLiter()
    {
        return $this->liter;
    }

    /**
     * Set observation
     *
     * @param string $observation
     * @return Inventory
     */
    public function setObservation($observation)
    {
        $this->observation = $observation;
        return $this;
    }

    /**
     * Get observation
     * @return string
     */
    public function getObservation()
    {
        return $this->observation;
    }

    /**
     * Set tank
     *
     * @param \MainBundle\Entity\Tank $tank
     * @return Inventory
     */
    public function setTank(\MainBundle\Entity\Tank $tank = null)
    {
        $this->tank = $tank;

        return $this;
    }

    /**
     * Get tank
     *
     * @return \MainBundle\Entity\Tank
     */
    public function getTank()
    {
        return $this->tank;
    }

    /**
     * Set users
     *
     * @param \UserBundle\Entity\User $users
     * @return Inventory
     */
    public function setUsers(\UserBundle\Entity\User $users = null)
    {
        $this->users = $users;

        return $this;
    }

    /**
     * Get users
     *
     * @return \UserBundle\Entity\User
     */
    public function getUsers()
    {
        return $this->users;
    }

    /**
     * Set product
     *
     * @param \MainBundle\Entity\Product $product
     * @return Inventory
     */
    public function setProduct(\MainBundle\Entity\Product $product = null)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get product
     *
     * @return \MainBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }
}


text:
package com.tkmtwo.sarapi.interpolate;

import com.bmc.arsys.api.Value;
import com.tkmtwo.interpolate.PositionalInterpolatorCallback;
import com.tkmtwo.sarapi.support.QueryStringValueFormatter;
import com.tkmtwo.sarapi.support.ValueFormatter;
import java.util.List;

/**
 *
 */
public class PositionalQualifierCallback
  extends PositionalInterpolatorCallback<Value> {

  ValueFormatter formatter;

  /**
   * Creates a new PositionalInterpolatorCallback instance.
   *
   * @param vs a List of T values
   */
  public PositionalQualifierCallback(List<Value> vs) {
    super(vs);
    setFormatter(new QueryStringValueFormatter());
  }

  /**
   * Creates a new PositionalInterpolatorCallback instance.
   *
   * @param tokenPrefix
   * @param vs a List of T values
   */
  public PositionalQualifierCallback(String tokenPrefix,
                                     List<Value> vs) {
    super(tokenPrefix, vs);
    setFormatter(new QueryStringValueFormatter());
  }

  public ValueFormatter getFormatter() { return formatter; }
  public void setFormatter(ValueFormatter vf) { formatter = vf; }

  protected String formatValue(Value value) {
    return getFormatter().formatValue(value);
  }

}


text:
<!DOCTYPE>

    <link href="/stylesheet/bootstrap.min.css" rel="stylesheet">
    <link href="/stylesheet/style.css" rel=stylesheet>
    <link href="/stylesheet/stylePost.css" rel="stylesheet">

Hot

Trending

Random

                        Tags

Funny

Animals

Anime and manga

Movies and TV

WTF

Savage

                <form class="navbar-form navbar-left" role="search" action="/search" method="POST">

                        <input type="text" class="form-control" placeholder="Type to search" name="searchedPost">

                    <button type="submit" class="btn btn-default">  </button>
                </form>

Add post

                        {{#currentUser}}
                        {{username}}
                        {{/currentUser}}

Profile

Tools

Log out

E-mail {{numEmail}}

	{{#currentUser}}

{{username}}

    {{/currentUser}}

Settings

Security

Password

 Notifications

My profile and activity:

                                    <input type="checkbox" aria-label="...">
                                    <input type="checkbox" aria-label="..."> When someone start to follow me

                                    <input type="checkbox" aria-label="...">
                                    <input type="checkbox" aria-label="..."> When my post become popular

                                    <input type="checkbox" aria-label="...">
                                    <input type="checkbox" aria-label="..."> When a friend of Facebook start an account in La fila de atrás

Updates:

                                    <input type="checkbox" aria-label="...">
                                    <input type="checkbox" aria-label="..."> When there is a special event

                                    <input type="checkbox" aria-label="...">
                                    <input type="checkbox" aria-label="..."> When a friend post something

                                    <input type="checkbox" aria-label="...">
                                    <input type="checkbox" aria-label="..."> When I receive an email

                <button type="button" class="btn btn-default save-profile-button">Save changes</button>


text:
package com.evolveum.midpoint.model.intest.sync;

import com.evolveum.icf.dummy.resource.DummyGroup;
import com.evolveum.icf.dummy.resource.DummyResource;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchema;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl;
import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.schema.SearchResultList;
import com.evolveum.midpoint.schema.internals.InternalCounters;
import com.evolveum.midpoint.schema.internals.InternalMonitor;
import com.evolveum.midpoint.schema.internals.InternalOperationClasses;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.DummyResourceContoller;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.Test;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.testng.AssertJUnit.assertEquals;

/**
 * Tests the parallel discovery of accounts with entitlements.
 *
 * Do not use in regular tests (for now).
 *
 * See MID-5237.
 *
 * ------------------------------------------------------------------------------
 *
 * Setup:
 *  - synchronizing accounts from SteelBlue to SteelGrey (using user template that assigns a role for SteelGrey)
 *  - starting with N user accounts on SteelBlue and SteelGrey; M groups on SteelGrey
 *  - during SteelGrey account creation, account+groups are discovered there
 *  - because that occurs in multiple threads, we expect that duplicate group shadows are created
 *
 */
@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestParallelDiscovery extends AbstractInitializedModelIntegrationTest {

    // --- START of test configuration ---
    private static final SyncKind KIND = SyncKind.IMPORT;
    private static final Distribution DISTRIBUTION = Distribution.MULTITHREADED;
    // --- END of test configuration ---

    private static final File TEST_DIR = new File("src/test/resources/sync");

    private static final File ROLE_STEELGREY_FILE = new File(TEST_DIR, "role-steelgrey.xml");
    private static final File USER_TEMPLATE_STEELGREY_FILE = new File(TEST_DIR, "user-template-steelgrey.xml");
    private static final String USER_TEMPLATE_STEELGREY_OID = "a7745154-c9c4-43d3-89c1-8de89e615baf";

    private static final File RESOURCE_DUMMY_STEELBLUE_FILE = new File(TEST_DIR, "resource-dummy-steelblue.xml");
    private static final String RESOURCE_DUMMY_STEELBLUE_OID = "8d97261a-ef5e-4199-9700-670577441c7f";
    private static final String RESOURCE_DUMMY_STEELBLUE_NAME = "steelblue";

    private static final File RESOURCE_DUMMY_STEELGREY_FILE = new File(TEST_DIR, "resource-dummy-steelgrey.xml");
    private static final String RESOURCE_DUMMY_STEELGREY_OID = "ff5899c7-8b02-4a0e-8f7d-74c154721d5d";
    private static final String RESOURCE_DUMMY_STEELGREY_NAME = "steelgrey";

    private static final File TASK_IMPORT_DUMMY_STEELBLUE_MULTITHREADED_FILE = new File(TEST_DIR, "task-import-dummy-steelblue-multithreaded.xml");
    private static final String TASK_IMPORT_DUMMY_STEELBLUE_MULTITHREADED_OID = "d553eec5-0e03-4efd-80ba-18e6715c26aa";

    private static final File TASK_RECONCILE_DUMMY_STEELBLUE_MULTITHREADED_FILE = new File(TEST_DIR, "task-reconcile-dummy-steelblue-multithreaded.xml");
    private static final String TASK_RECONCILE_DUMMY_STEELBLUE_MULTITHREADED_OID = "c1351099-eabf-4ca3-b157-9a7b6c16b960";

    private static final File TASK_RECONCILE_DUMMY_STEELBLUE_PARTITIONED_FILE = new File(TEST_DIR, "task-reconcile-dummy-steelblue-partitioned.xml");
    private static final String TASK_RECONCILE_DUMMY_STEELBLUE_PARTITIONED_OID = "0e1f67e2-45b3-4fd9-b193-e1a5fea1d315";

    private DummyResource dummyResourceSteelBlue;
    private DummyResourceContoller dummyResourceCtlSteelBlue;
    private ResourceType resourceDummySteelBlueType;
    private PrismObject<ResourceType> resourceDummySteelBlue;

    private DummyResource dummyResourceSteelGrey;
    private DummyResourceContoller dummyResourceCtlSteelGrey;
    private ResourceType resourceDummySteelGreyType;
    private PrismObject<ResourceType> resourceDummySteelGrey;

    private static final int NUMBER_OF_GROUPS = 10;

    private static final int NUMBER_OF_USERS = 20;
    private final List<String> userNames = new ArrayList<>();

    private static final double GROUP_ASSIGNMENT_PROBABILITY = 0.3;

    enum SyncKind { IMPORT, RECONCILIATION }
    enum Distribution { MULTITHREADED, PARTITIONED }

    private String getSyncTaskOid() {
        if (KIND == SyncKind.IMPORT) {
            if (DISTRIBUTION == Distribution.MULTITHREADED) {
                return TASK_IMPORT_DUMMY_STEELBLUE_MULTITHREADED_OID;
            } else {
                throw new AssertionError("unsupported");
            }
        } else {
            if (DISTRIBUTION == Distribution.MULTITHREADED) {
                return TASK_RECONCILE_DUMMY_STEELBLUE_MULTITHREADED_OID;
            } else {
                return TASK_RECONCILE_DUMMY_STEELBLUE_PARTITIONED_OID;
            }
        }
    }

    private File getSyncTaskFile() {
        if (KIND == SyncKind.IMPORT) {
            if (DISTRIBUTION == Distribution.MULTITHREADED) {
                return TASK_IMPORT_DUMMY_STEELBLUE_MULTITHREADED_FILE;
            } else {
                throw new AssertionError("unsupported");
            }
        } else {
            if (DISTRIBUTION == Distribution.MULTITHREADED) {
                return TASK_RECONCILE_DUMMY_STEELBLUE_MULTITHREADED_FILE;
            } else {
                return TASK_RECONCILE_DUMMY_STEELBLUE_PARTITIONED_FILE;
            }
        }
    }

    @Override
    public void initSystem(Task initTask, OperationResult initResult) throws Exception {
        super.initSystem(initTask, initResult);

        repoAddObjectFromFile(ROLE_STEELGREY_FILE, initResult);
        repoAddObjectFromFile(USER_TEMPLATE_STEELGREY_FILE, initResult);
        setDefaultUserTemplate(USER_TEMPLATE_STEELGREY_OID);

        dummyResourceCtlSteelBlue = DummyResourceContoller.create(RESOURCE_DUMMY_STEELBLUE_NAME, resourceDummySteelBlue);
        dummyResourceCtlSteelBlue.extendSchemaPirate();
        dummyResourceSteelBlue = dummyResourceCtlSteelBlue.getDummyResource();
        resourceDummySteelBlue = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_STEELBLUE_FILE, RESOURCE_DUMMY_STEELBLUE_OID, initTask, initResult);
        resourceDummySteelBlueType = resourceDummySteelBlue.asObjectable();
        dummyResourceCtlSteelBlue.setResource(resourceDummySteelBlue);

        dummyResourceCtlSteelGrey = DummyResourceContoller.create(RESOURCE_DUMMY_STEELGREY_NAME, resourceDummySteelGrey);
        dummyResourceCtlSteelGrey.extendSchemaPirate();
        dummyResourceSteelGrey = dummyResourceCtlSteelGrey.getDummyResource();
        resourceDummySteelGrey = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_STEELGREY_FILE, RESOURCE_DUMMY_STEELGREY_OID, initTask, initResult);
        resourceDummySteelGreyType = resourceDummySteelGrey.asObjectable();
        dummyResourceCtlSteelGrey.setResource(resourceDummySteelGrey);

        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            String userName = String.format("user%06d", i);
            dummyResourceCtlSteelBlue.addAccount(userName);
            dummyResourceCtlSteelGrey.addAccount(userName);
            userNames.add(userName);
        }

        for (int i = 0; i < NUMBER_OF_GROUPS; i++) {
            String groupName = String.format("group%06d", i);
            DummyGroup group = dummyResourceCtlSteelGrey.addGroup(groupName);
            for (String name : userNames) {
                if (Math.random() < GROUP_ASSIGNMENT_PROBABILITY) {
                    group.addMember(name);
                }
            }
        }

        InternalMonitor.reset();
        InternalMonitor.setTrace(InternalOperationClasses.SHADOW_FETCH_OPERATIONS, true);
    }

    @Override
    protected int getNumberOfUsers() {
        return super.getNumberOfUsers() + NUMBER_OF_USERS;
    }

    protected PrismObject<UserType> getDefaultActor() {
        return userAdministrator;
    }

    @Test
    public void test001Sanity() throws Exception {
        final String TEST_NAME = "test001Sanity";
        displayTestTitle(TEST_NAME);

        display("Dummy resource azure", dummyResourceSteelBlue);

        // WHEN
        ResourceSchema resourceSchemaSteelBlue = RefinedResourceSchemaImpl.getResourceSchema(resourceDummySteelBlueType, prismContext);
        ResourceSchema resourceSchemaSteelGrey = RefinedResourceSchemaImpl.getResourceSchema(resourceDummySteelGreyType, prismContext);

        display("Dummy steel blue resource schema", resourceSchemaSteelBlue);
        display("Dummy steel grey resource schema", resourceSchemaSteelGrey);

        // THEN
        dummyResourceCtlSteelBlue.assertDummyResourceSchemaSanityExtended(resourceSchemaSteelBlue);
        dummyResourceCtlSteelGrey.assertDummyResourceSchemaSanityExtended(resourceSchemaSteelGrey);
    }

    @Test
    public void test002SanityRefined() throws Exception {
        final String TEST_NAME = "test002SanityRefined";
        displayTestTitle(TEST_NAME);

        // WHEN
        RefinedResourceSchema refinedSchemaSteelBlue = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummySteelBlueType, prismContext);
        RefinedResourceSchema refinedSchemaSteelGrey = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummySteelGreyType, prismContext);

        display("Dummy steel blue refined schema", refinedSchemaSteelBlue);
        display("Dummy steel grey refined schema", refinedSchemaSteelGrey);

        // THEN
        dummyResourceCtlSteelBlue.assertRefinedSchemaSanity(refinedSchemaSteelBlue);
        dummyResourceCtlSteelGrey.assertRefinedSchemaSanity(refinedSchemaSteelGrey);
    }

    @Test
    public void test100Synchronize() throws Exception {
        final String TEST_NAME = "test100Synchronize";
        displayTestTitle(TEST_NAME);

        // GIVEN
        Task task = createTask(TEST_NAME);
        OperationResult result = task.getResult();
        assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE);

        // Preconditions
        List<PrismObject<UserType>> usersBefore = modelService.searchObjects(UserType.class, null, null, task, result);
        display("Users before", usersBefore);
        ObjectQuery onSteelBlueQuery = prismContext.queryFor(ShadowType.class)
                .item(ShadowType.F_RESOURCE_REF).ref(RESOURCE_DUMMY_STEELBLUE_OID)
                .build();
        ObjectQuery onSteelGreyQuery = prismContext.queryFor(ShadowType.class)
                .item(ShadowType.F_RESOURCE_REF).ref(RESOURCE_DUMMY_STEELGREY_OID)
                .build();
        SearchResultList<PrismObject<ShadowType>> shadowsBlueBefore = repositoryService.searchObjects(ShadowType.class, onSteelBlueQuery, null, result);
        display("Shadows on blue before", shadowsBlueBefore);
        SearchResultList<PrismObject<ShadowType>> shadowsGreyBefore = repositoryService.searchObjects(ShadowType.class, onSteelGreyQuery, null, result);
        display("Shadows on grey before", shadowsGreyBefore);

        loginAdministrator();

        dummyAuditService.clear();
        rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT);

        // WHEN
        displayWhen(TEST_NAME);
        addObject(getSyncTaskFile(), task, result);

        // THEN
        displayThen(TEST_NAME);

        if (DISTRIBUTION == Distribution.MULTITHREADED) {
            waitForTaskFinish(getSyncTaskOid(), true, 600000);
        } else {
            waitForTaskTreeNextFinishedRun(getSyncTaskOid(), 600000);
        }

        // THEN
        displayThen(TEST_NAME);
        result.computeStatus();
        TestUtil.assertSuccess(result);

        List<PrismObject<UserType>> usersAfter = modelService.searchObjects(UserType.class, null, null, task, result);
        display("Users after", usersAfter);
        SearchResultList<PrismObject<ShadowType>> shadowsBlueAfter = repositoryService.searchObjects(ShadowType.class, onSteelBlueQuery, null, result);
        display("Shadows on blue after", shadowsBlueAfter);
        SearchResultList<PrismObject<ShadowType>> shadowsGreyAfter = repositoryService.searchObjects(ShadowType.class, onSteelGreyQuery, null, result);
        display("Shadows on grey after", shadowsGreyAfter);

        List<String> shadowNames = shadowsGreyAfter.stream().map(o -> o.getName().getOrig()).collect(Collectors.toList());
        Set<String> uniqueNames = new HashSet<>();
        List<String> duplicateNames = shadowNames.stream()
                .filter(e -> !uniqueNames.add(e))
                .collect(Collectors.toList());
        System.out.println("Shadow (grey) names: " + shadowNames.size());
        System.out.println("Unique (grey) shadow names: " + uniqueNames.size());
        System.out.println("Duplicate (grey) names: " + duplicateNames);
        assertEquals("Duplicate (grey) names: " + duplicateNames, 0, duplicateNames.size());

        PrismObject<ShadowType> account0 = shadowsGreyAfter.stream()
                .filter(o -> o.asObjectable().getName().getOrig().equals(userNames.get(0))).findFirst().orElseThrow(AssertionError::new);
        PrismObject<ShadowType> shadow = modelService.getObject(ShadowType.class, account0.getOid(), null, task, result);
        display("user0 shadow", shadow);
    }

}


text:
require File.expand_path("#{File.dirname __FILE__}/../command")
require File.expand_path("#{File.dirname __FILE__}/../http_method_command")
require File.expand_path("#{File.dirname __FILE__}/follow")
require File.expand_path("#{File.dirname __FILE__}/http_delete")
require File.expand_path("#{File.dirname __FILE__}/http_get")
require File.expand_path("#{File.dirname __FILE__}/http_post")
require File.expand_path("#{File.dirname __FILE__}/http_put")

module HTTY; end

class HTTY::CLI; end

module HTTY::CLI::Commands; end

# Encapsulates the _http-patch_ command.
class HTTY::CLI::Commands::HttpPatch < HTTY::CLI::Command

  include HTTY::CLI::HTTPMethodCommand

  # Returns the help text for the _http-patch_ command.
  def self.help
    'Issues an HTTP PATCH using the current request'
  end

  # Returns related command classes for the _http-patch_ command.
  def self.see_also_commands
    [HTTY::CLI::Commands::HttpGet,
     HTTY::CLI::Commands::Follow,
     HTTY::CLI::Commands::HttpPost,
     HTTY::CLI::Commands::HttpPut,
     HTTY::CLI::Commands::HttpDelete]
  end

end


text:
import React from 'react'
import test from 'tape'
import { shallow } from 'enzyme'

const DummyComponent = (props) =>
{props.content}

test('Dummy component', assert => {
  const msg = 'should render dummy content'

  const expected = '
dummy content
'

  const props = {
    content: 'dummy content'
  }

  const $ = shallow(<DummyComponent {...props} />)
  const output = $.html()

  assert.equal(output, expected, msg)

  assert.end()
})