text:
package org.kuali.kpme.pm.position;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.kuali.kpme.core.bo.HrBusinessObject;
import org.kuali.kpme.pm.PMConstants;
import org.kuali.kpme.pm.api.pstnqlfrtype.PstnQlfrTypeContract;
import org.kuali.kpme.pm.service.base.PmServiceLocator;
import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.krad.uif.control.UifKeyValuesFinderBase;
import org.kuali.rice.krad.uif.field.InputField;
import org.kuali.rice.krad.uif.view.ViewModel;
import org.kuali.rice.krad.web.form.MaintenanceDocumentForm;

public class PositionQualifierValueKeyValueFinder  extends UifKeyValuesFinderBase {

	private static final long serialVersionUID = 1L;

	@Override
	public List<KeyValue> getKeyValues(ViewModel model) {
		MaintenanceDocumentForm docForm = (MaintenanceDocumentForm) model;
		List<KeyValue> options = new ArrayList<KeyValue>();

		PositionQualificationBo aQualification = (PositionQualificationBo) docForm.getNewCollectionLines().get("document.newMaintainableObject.dataObject.qualificationList");
		if(aQualification != null) {
			String aTypeId = aQualification.getQualificationType();
			PstnQlfrTypeContract aTypeObj = PmServiceLocator.getPstnQlfrTypeService().getPstnQlfrTypeById(aTypeId);
			if(aTypeObj != null) {
				if(aTypeObj.getTypeValue().equals(PMConstants.PSTN_QLFR_SELECT)){
					String[] aCol = aTypeObj.getSelectValues().split(",");
					for(String aString : aCol){
						aString = StringUtils.strip(aString);
						options.add(new ConcreteKeyValue(aString, aString));
					}
				} else{
					return new ArrayList<KeyValue>();
				}
			}
		}
        return options;
	}

	// KPME-2958
	@Override
    public List<KeyValue> getKeyValues(ViewModel model, InputField field){

		MaintenanceDocumentForm docForm = (MaintenanceDocumentForm) model;
		HrBusinessObject anHrObject = (HrBusinessObject) docForm.getDocument().getNewMaintainableObject().getDataObject();
		List<KeyValue> options = new ArrayList<KeyValue>();

		if (field.getId().contains("add")) {
			// For "add" line, just delegate to getKeyValues(model) method as it is working correctly
			options = getKeyValues(model);
		} else {
			// Strip index off field id
			String fieldId = field.getId();
			int line_index = fieldId.indexOf("line");
			int index = Integer.parseInt(fieldId.substring(line_index+4));

			PositionBo aPosition = (PositionBo)anHrObject;
			List<PositionQualificationBo> qualificationList = aPosition.getQualificationList(); // holds "added" lines
			PositionQualificationBo posQualification = (PositionQualificationBo)qualificationList.get(index);
			String aTypeId = posQualification.getQualificationType();

			PstnQlfrTypeContract aTypeObj = PmServiceLocator.getPstnQlfrTypeService().getPstnQlfrTypeById(aTypeId);;
			if(aTypeObj != null) {
				if(aTypeObj.getTypeValue().equals(PMConstants.PSTN_QLFR_SELECT)){
					String[] aCol = aTypeObj.getSelectValues().split(",");
					for(String aString : aCol){
						aString = StringUtils.strip(aString);
						options.add(new ConcreteKeyValue(aString, aString));
					}
				} else{
					return new ArrayList<KeyValue>();
				}
			}
		}

		return options;

	}

}


text:
[#]: subject: "SparkyLinux 6.0 Release is based on Debian 11 and Includes a Built-in VPN"
[#]: via: "https://news.itsfoss.com/sparkylinux-6-0-release/"
[#]: author: "Ankush Das https://news.itsfoss.com/author/ankush/"
[#]: collector: "lujun9972"
[#]: translator: " "
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "

SparkyLinux 6.0 Release is based on Debian 11 and Includes a Built-in VPN
======

SparkyLinux 6.0 is a major stable update that utilizes Debian 11 'Bullseye' as its base now.

While you can go through the [features of Debian 11][1], SparkyLinux 6.0 should reflect some of the perks associated with it.

Here, we shall take a quick look at what SparkyLinux 6.0 has to offer.

### SparkyLinux 6.0 "Po Tolo": What's New?

The major highlight of the release is the latest Debian 11 'Bullseye' as its base. The repositories have also been updated to get the latest packages.

SparkyAPTus AppCenter has replaced the original SparkyAPTus, which is no longer developed.

![][2]

You can install, reinstall, and remove applications easily. Not just limited to the applications, but you also get the ability to tweak the pre-configured desktops using it.

In addition to that, you can remove and install Linux Kernels as well. You can choose from Debian Kernel, Liquorix, Sparky, and XanMod.

![][3]

It is worth noting that you will still be able to access all the tools from the old APTus.

To enhance privacy and security, SparkyLinux has decided to include the non-profit [RiseUp VPN][4] application pre-installed.

It is a VPN service that relies on donations to keep the network alive and comes with cross-platform support. You can also find it available for Android devices.

So, this makes it an interesting addition to the distribution. If you are not using any VPN service, this should make things easy.

The FirstRun app has been replaced with an improved welcome app that guides you through some basic pointers.

![][5]

### Other Improvements

With the latest release, you can also find new wallpapers and updated application packages that include:

  * Thunderbird 78.13.0
  * VLC 3.0.16
  * LibreOffice 7.0.4
  * Calamares Installer 3.2.41.1

To know more about the release, you can refer to the [official announcement][6].

### Download Sparky 6.0

SparkyLinux 6.0 is available to download with Xfce and KDE Plasma desktop environments. It supports 32-bit systems as well, which is a good thing.

If you are already running SparkLinux "Po Tolo" rolling release, you need to update your system to get Sparky 6.0.

Do note that the rolling version will switch to a stable release. So, if you want to stay on the rolling release, you need to wait for a few days.

[SparkyLinux 6.0][7]

#### Big Tech Websites Get Millions in Revenue, It's FOSS Got You!

If you like what we do here at It's FOSS, please consider making a donation to support our independent publication. Your support will help us keep publishing content focusing on desktop Linux and open source software.

I'm not interested

--------------------------------------------------------------------------------

via: https://news.itsfoss.com/sparkylinux-6-0-release/

作者:[Ankush Das][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://news.itsfoss.com/author/ankush/
[b]: https://github.com/lujun9972
[1]: https://news.itsfoss.com/debian-11-feature/
[2]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjU4NyIgd2lkdGg9Ijc4MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiLz4=
[3]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjU4NSIgd2lkdGg9Ijc4MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiLz4=
[4]: https://riseup.net/en/vpn
[5]: data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjU2MyIgd2lkdGg9Ijc4MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiLz4=
[6]: https://sparkylinux.org/sparky-6-0-po-tolo/
[7]: https://sparkylinux.org/download/

redpajama_set_name: RedPajamaGithub


text:
   def testProfileWriteToFile(self):
        numVertices = 100
        numFeatures = 10
        vList = VertexList(numVertices, numFeatures)
        sGraph = SparseGraph(vList, True)
        pw = PajekWriter()

        p = 0.1 #The re-wiring probability
        k = 15 #default number of neighbours for each vertex
        edgeWeight = 1 #The weight on each edge (currently has no meaning)

        #Create the graph edges according to the small world model
        graphGen = SmallWorldGenerator(sGraph)
        sGraph = graphGen.generateGraph(p, k, edgeWeight)

        directory = "output/test/"
        fileName = directory + "tempGraph.net"
        profileFileName = "profile.cprof"

        cProfile.runctx('pw.writeToFile(fileName, sGraph)', globals(), locals(), profileFileName)
        stats = pstats.Stats(profileFileName)
        stats.strip_dirs().sort_stats("cumulative").print_stats(20)

        os.remove(fileName + ".net")
        os.remove(profileFileName)


text:
package org.diirt.vtype.next;

/**
 * Immutable VInt implementation.
 *
 * @author carcassi
 */
class IVInt extends VInt {

    private final Integer value;
    private final Alarm alarm;
    private final Time time;
    private final Display display;

    IVInt(Integer value, Alarm alarm, Time time, Display display) {
        this.value = value;
        this.alarm = alarm;
        this.time = time;
        this.display = display;
    }

    @Override
    public Integer getValue() {
        return value;
    }

    @Override
    public Alarm getAlarm() {
        return alarm;
    }

    @Override
    public Time getTime() {
        return time;
    }

    @Override
    public Display getDisplay() {
        return display;
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <link href="../images/vl_blue.ico" type="image/x-icon" rel="icon"></link>
  <link href="../images/vl_blue.ico" type="image/x-icon" rel="shortcut icon"></link>

  <title>VLFeat - Tutorials - Utils</title>

  <link href="../vlfeat.css" type="text/css" rel="stylesheet"></link>
  <link href="../pygmentize.css" type="text/css" rel="stylesheet"></link>

VLFeat.org

      Tutorials - Utils

Home

Download

Tutorials

Covdet

HOG

SIFT

DSIFT/PHOW

LIOP

MSER

GMM

KMeans

Encodings

IKM

HIKM

AIB

Quick shift

SLIC

kd-tree

Distance transf.

Utils

SVM

Plots: rank

Applications

Documentation

This is a list of other notable MATLAB functions included
in VLFeat

vl_imsmooth smoothes an image by a Gaussian kernel
  (simple but very useful as it is generally much faster than MATLAB's
  general purpose smoothing functions).

vl_plotframe plots a variety of feature frame types (such as oriented ellipses).

vl_binsum performs binned summations, useful as a
  building block for the fast computation of
  histograms. vl_whistc computes weighed histograms.

vl_imarray and vl_imarraysc arrange and visualize multiple
images in a grid

vl_imsc scales the image range;

vl_tightsubplot is similar to built-in
subplot, but produces narrower margins.

vl_cf makes a copy of a figure.

vl_rodr and vl_irodr compute the Rodrigues' formula and
  its inverse

vl_override overrides members of a structure with members of
  another structure.

vl_imwbackward warps an image by the inverse mapping method
  (generally much faster than MATLAB general purpose warping
  functions).

vl_waffine computes the affine warp of a set of
  points. vl_tps, vl_tpsu, vl_wtps
  compute the thin-plate spline warp of a set of points. vl_witps
  computes the inverse thin plate warp of a set of point (by
  numerically inverting the transformation). They may be used in
  combination with vl_imwbackward.

vl_xyz2lab,
  vl_xyz2luv, vl_xyz2rgb, vl_rgb2xyz
  convert color spaces.

vl_rcos, vl_gaussian, vl_dgaussian,
vl_ddgaussian
compute some useful special functions.

      © 2007-13 The authors of VLFeat


text:
import unittest

import numpy as np
import paddle
from paddle import fluid
from paddle.distribution import Categorical, Distribution, Normal, Uniform
from paddle.fluid import layers

from test_distribution import DistributionNumpy

np.random.seed(2022)

class CategoricalNumpy(DistributionNumpy):
    def __init__(self, logits):
        self.logits = np.array(logits).astype('float32')

    def entropy(self):
        logits = self.logits - np.max(self.logits, axis=-1, keepdims=True)
        e_logits = np.exp(logits)
        z = np.sum(e_logits, axis=-1, keepdims=True)
        prob = e_logits / z
        return -1.0 * np.sum(prob * (logits - np.log(z)), axis=-1)

    def kl_divergence(self, other):
        logits = self.logits - np.max(self.logits, axis=-1, keepdims=True)
        other_logits = other.logits - np.max(
            other.logits, axis=-1, keepdims=True
        )
        e_logits = np.exp(logits)
        other_e_logits = np.exp(other_logits)
        z = np.sum(e_logits, axis=-1, keepdims=True)
        other_z = np.sum(other_e_logits, axis=-1, keepdims=True)
        prob = e_logits / z
        return np.sum(
            prob * (logits - np.log(z) - other_logits + np.log(other_z)),
            axis=-1,
            keepdims=True,
        )

class CategoricalTest(unittest.TestCase):
    def setUp(self, use_gpu=False, batch_size=3, dims=5):
        self.use_gpu = use_gpu
        if not use_gpu:
            self.place = fluid.CPUPlace()
            self.gpu_id = -1
        else:
            self.place = fluid.CUDAPlace(0)
            self.gpu_id = 0

        self.batch_size = batch_size
        self.dims = dims
        self.init_numpy_data(batch_size, dims)

        paddle.disable_static(self.place)
        self.init_dynamic_data(batch_size, dims)

        paddle.enable_static()
        self.test_program = fluid.Program()
        self.executor = fluid.Executor(self.place)
        self.init_static_data(batch_size, dims)

    def init_numpy_data(self, batch_size, dims):
        # input logtis is 2-D Tensor
        # value used in probs and log_prob method is 1-D Tensor
        self.logits_np = np.random.rand(batch_size, dims).astype('float32')
        self.other_logits_np = np.random.rand(batch_size, dims).astype(
            'float32'
        )
        self.value_np = np.array([2, 1, 3]).astype('int64')

        self.logits_shape = [batch_size, dims]
        # dist_shape = logits_shape[:-1], it represents the number of
        #  different distributions.
        self.dist_shape = [batch_size]
        # sample shape represents the number of samples
        self.sample_shape = [2, 4]
        # value used in probs and log_prob method
        # If value is 1-D and logits is 2-D or higher dimension, value will be
        #  broadcasted to have the same number of distributions with logits.
        # If value is 2-D or higher dimentsion, it should have the same number
        #  of distributions with logtis. ``value[:-1] = logits[:-1]
        self.value_shape = [3]

    def init_dynamic_data(self, batch_size, dims):
        self.logits = paddle.to_tensor(self.logits_np)
        self.other_logits = paddle.to_tensor(self.other_logits_np)
        self.value = paddle.to_tensor(self.value_np)

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
            self.logits_static = fluid.data(
                name='logits', shape=self.logits_shape, dtype='float32'
            )
            self.other_logits_static = fluid.data(
                name='other_logits', shape=self.logits_shape, dtype='float32'
            )
            self.value_static = fluid.data(
                name='value', shape=self.value_shape, dtype='int64'
            )

    def get_numpy_selected_probs(self, probability):
        np_probs = np.zeros(self.dist_shape + self.value_shape)
        for i in range(self.batch_size):
            for j in range(3):
                np_probs[i][j] = probability[i][self.value_np[j]]
        return np_probs

    def compare_with_numpy(self, fetch_list, tolerance=1e-6):
        sample, entropy, kl, probs, log_prob = fetch_list
        log_tolerance = 1e-4

        np.testing.assert_equal(
            sample.shape, self.sample_shape + self.dist_shape
        )

        np_categorical = CategoricalNumpy(self.logits_np)
        np_other_categorical = CategoricalNumpy(self.other_logits_np)
        np_entropy = np_categorical.entropy()
        np_kl = np_categorical.kl_divergence(np_other_categorical)

        np.testing.assert_allclose(
            entropy, np_entropy, rtol=log_tolerance, atol=log_tolerance
        )
        np.testing.assert_allclose(
            kl, np_kl, rtol=log_tolerance, atol=log_tolerance
        )

        sum_dist = np.sum(self.logits_np, axis=-1, keepdims=True)
        probability = self.logits_np / sum_dist
        np_probs = self.get_numpy_selected_probs(probability)
        np_log_prob = np.log(np_probs)

        np.testing.assert_allclose(
            probs, np_probs, rtol=tolerance, atol=tolerance
        )
        np.testing.assert_allclose(
            log_prob, np_log_prob, rtol=tolerance, atol=tolerance
        )

    def test_categorical_distribution_dygraph(self, tolerance=1e-6):
        paddle.disable_static(self.place)
        categorical = Categorical(self.logits)
        other_categorical = Categorical(self.other_logits)

        sample = categorical.sample(self.sample_shape).numpy()
        entropy = categorical.entropy().numpy()
        kl = categorical.kl_divergence(other_categorical).numpy()
        probs = categorical.probs(self.value).numpy()
        log_prob = categorical.log_prob(self.value).numpy()

        fetch_list = [sample, entropy, kl, probs, log_prob]
        self.compare_with_numpy(fetch_list)

    def test_categorical_distribution_static(self, tolerance=1e-6):
        paddle.enable_static()
        with fluid.program_guard(self.test_program):
            categorical = Categorical(self.logits_static)
            other_categorical = Categorical(self.other_logits_static)

            sample = categorical.sample(self.sample_shape)
            entropy = categorical.entropy()
            kl = categorical.kl_divergence(other_categorical)
            probs = categorical.probs(self.value_static)
            log_prob = categorical.log_prob(self.value_static)

            fetch_list = [sample, entropy, kl, probs, log_prob]

        feed_vars = {
            'logits': self.logits_np,
            'other_logits': self.other_logits_np,
            'value': self.value_np,
        }

        self.executor.run(fluid.default_startup_program())
        fetch_list = self.executor.run(
            program=self.test_program, feed=feed_vars, fetch_list=fetch_list
        )

        self.compare_with_numpy(fetch_list)

class CategoricalTest2(CategoricalTest):
    def init_numpy_data(self, batch_size, dims):
        # input logtis is 2-D Tensor with dtype Float64
        # value used in probs and log_prob method is 1-D Tensor
        self.logits_np = np.random.rand(batch_size, dims).astype('float64')
        self.other_logits_np = np.random.rand(batch_size, dims).astype(
            'float64'
        )
        self.value_np = np.array([2, 1, 3]).astype('int64')

        self.logits_shape = [batch_size, dims]
        self.dist_shape = [batch_size]
        self.sample_shape = [2, 4]
        self.value_shape = [3]

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
            self.logits_static = fluid.data(
                name='logits', shape=self.logits_shape, dtype='float64'
            )
            self.other_logits_static = fluid.data(
                name='other_logits', shape=self.logits_shape, dtype='float64'
            )
            self.value_static = fluid.data(
                name='value', shape=self.value_shape, dtype='int64'
            )

class CategoricalTest3(CategoricalTest):
    def init_dynamic_data(self, batch_size, dims):
        # input logtis is 2-D numpy.ndarray with dtype Float32
        # value used in probs and log_prob method is 1-D Tensor
        self.logits = self.logits_np
        self.other_logits = self.other_logits_np
        self.value = paddle.to_tensor(self.value_np)

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
            self.logits_static = self.logits_np
            self.other_logits_static = self.other_logits_np
            self.value_static = fluid.data(
                name='value', shape=self.value_shape, dtype='int64'
            )

class CategoricalTest4(CategoricalTest):
    def init_numpy_data(self, batch_size, dims):
        # input logtis is 2-D numpy.ndarray with dtype Float64
        # value used in probs and log_prob method is 1-D Tensor
        self.logits_np = np.random.rand(batch_size, dims).astype('float64')
        self.other_logits_np = np.random.rand(batch_size, dims).astype(
            'float64'
        )
        self.value_np = np.array([2, 1, 3]).astype('int64')

        self.logits_shape = [batch_size, dims]
        self.dist_shape = [batch_size]
        self.sample_shape = [2, 4]
        self.value_shape = [3]

    def init_dynamic_data(self, batch_size, dims):
        self.logits = self.logits_np
        self.other_logits = self.other_logits_np
        self.value = paddle.to_tensor(self.value_np)

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
            self.logits_static = self.logits_np
            self.other_logits_static = self.other_logits_np
            self.value_static = fluid.data(
                name='value', shape=self.value_shape, dtype='int64'
            )

# test shape of logits and value used in probs and log_prob method
class CategoricalTest5(CategoricalTest):
    def init_numpy_data(self, batch_size, dims):
        # input logtis is 1-D Tensor
        # value used in probs and log_prob method is 1-D Tensor
        self.logits_np = np.random.rand(dims).astype('float32')
        self.other_logits_np = np.random.rand(dims).astype('float32')
        self.value_np = np.array([2, 1, 3]).astype('int64')

        self.logits_shape = [dims]
        self.dist_shape = []
        self.sample_shape = [2, 4]
        self.value_shape = [3]

    def get_numpy_selected_probs(self, probability):
        np_probs = np.zeros(self.value_shape)
        for i in range(3):
            np_probs[i] = probability[self.value_np[i]]
        return np_probs

class CategoricalTest6(CategoricalTest):
    def init_numpy_data(self, batch_size, dims):
        # input logtis is 2-D Tensor
        # value used in probs and log_prob method has the same number of batches with input
        self.logits_np = np.random.rand(3, 5).astype('float32')
        self.other_logits_np = np.random.rand(3, 5).astype('float32')
        self.value_np = np.array([[2, 1], [0, 3], [2, 3]]).astype('int64')

        self.logits_shape = [3, 5]
        self.dist_shape = [3]
        self.sample_shape = [2, 4]
        self.value_shape = [3, 2]

    def get_numpy_selected_probs(self, probability):
        np_probs = np.zeros(self.value_shape)
        for i in range(3):
            for j in range(2):
                np_probs[i][j] = probability[i][self.value_np[i][j]]
        return np_probs

class CategoricalTest7(CategoricalTest):
    def init_numpy_data(self, batch_size, dims):
        # input logtis is 3-D Tensor
        # value used in probs and log_prob method has the same number of distribuions with input
        self.logits_np = np.random.rand(3, 2, 5).astype('float32')
        self.other_logits_np = np.random.rand(3, 2, 5).astype('float32')
        self.value_np = np.array([2, 1, 3]).astype('int64')

        self.logits_shape = [3, 2, 5]
        self.dist_shape = [3, 2]
        self.sample_shape = [2, 4]
        self.value_shape = [3]

    def get_numpy_selected_probs(self, probability):
        np_probs = np.zeros(self.dist_shape + self.value_shape)
        for i in range(3):
            for j in range(2):
                for k in range(3):
                    np_probs[i][j][k] = probability[i][j][self.value_np[k]]
        return np_probs

class CategoricalTest8(CategoricalTest):
    def init_dynamic_data(self, batch_size, dims):
        # input logtis is 2-D list
        # value used in probs and log_prob method is 1-D Tensor
        self.logits = self.logits_np.tolist()
        self.other_logits = self.other_logits_np.tolist()
        self.value = paddle.to_tensor(self.value_np)

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
            self.logits_static = self.logits_np.tolist()
            self.other_logits_static = self.other_logits_np.tolist()
            self.value_static = fluid.data(
                name='value', shape=self.value_shape, dtype='int64'
            )

class CategoricalTest9(CategoricalTest):
    def init_dynamic_data(self, batch_size, dims):
        # input logtis is 2-D tuple
        # value used in probs and log_prob method is 1-D Tensor
        self.logits = tuple(self.logits_np.tolist())
        self.other_logits = tuple(self.other_logits_np.tolist())
        self.value = paddle.to_tensor(self.value_np)

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
            self.logits_static = tuple(self.logits_np.tolist())
            self.other_logits_static = tuple(self.other_logits_np.tolist())
            self.value_static = fluid.data(
                name='value', shape=self.value_shape, dtype='int64'
            )

class DistributionTestError(unittest.TestCase):
    def test_distribution_error(self):
        distribution = Distribution()

        self.assertRaises(NotImplementedError, distribution.sample)
        self.assertRaises(NotImplementedError, distribution.entropy)

        normal = Normal(0.0, 1.0)
        self.assertRaises(
            NotImplementedError, distribution.kl_divergence, normal
        )

        value_npdata = np.array([0.8], dtype="float32")
        value_tensor = layers.create_tensor(dtype="float32")
        self.assertRaises(
            NotImplementedError, distribution.log_prob, value_tensor
        )
        self.assertRaises(NotImplementedError, distribution.probs, value_tensor)

    def test_normal_error(self):
        paddle.enable_static()
        normal = Normal(0.0, 1.0)

        value = [1.0, 2.0]
        # type of value must be variable
        self.assertRaises(TypeError, normal.log_prob, value)

        value = [1.0, 2.0]
        # type of value must be variable
        self.assertRaises(TypeError, normal.probs, value)

        shape = 1.0
        # type of shape must be list
        self.assertRaises(TypeError, normal.sample, shape)

        seed = 1.0
        # type of seed must be int
        self.assertRaises(TypeError, normal.sample, [2, 3], seed)

        normal_other = Uniform(1.0, 2.0)
        # type of other must be an instance of Normal
        self.assertRaises(TypeError, normal.kl_divergence, normal_other)

    def test_uniform_error(self):
        paddle.enable_static()
        uniform = Uniform(0.0, 1.0)

        value = [1.0, 2.0]
        # type of value must be variable
        self.assertRaises(TypeError, uniform.log_prob, value)

        value = [1.0, 2.0]
        # type of value must be variable
        self.assertRaises(TypeError, uniform.probs, value)

        shape = 1.0
        # type of shape must be list
        self.assertRaises(TypeError, uniform.sample, shape)

        seed = 1.0
        # type of seed must be int
        self.assertRaises(TypeError, uniform.sample, [2, 3], seed)

    def test_categorical_error(self):
        paddle.enable_static()

        categorical = Categorical([0.4, 0.6])

        value = [1, 0]
        # type of value must be variable
        self.assertRaises(AttributeError, categorical.log_prob, value)

        value = [1, 0]
        # type of value must be variable
        self.assertRaises(AttributeError, categorical.probs, value)

        shape = 1.0
        # type of shape must be list
        self.assertRaises(TypeError, categorical.sample, shape)

        categorical_other = Uniform(1.0, 2.0)
        # type of other must be an instance of Categorical
        self.assertRaises(
            TypeError, categorical.kl_divergence, categorical_other
        )

        def test_shape_not_match_error():
            # shape of value must match shape of logits
            # value_shape[:-1] == logits_shape[:-1]
            paddle.disable_static()
            logits = paddle.rand([3, 5])
            cat = Categorical(logits)
            value = paddle.to_tensor([[2, 1, 3], [3, 2, 1]], dtype='int64')
            cat.log_prob(value)

        self.assertRaises(ValueError, test_shape_not_match_error)

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


text:
"""Set-up script for installing extension modules."""
from Cython.Build import cythonize
import numpy
from setuptools import Extension
from setuptools import setup

# Get the numpy include directory.
numpy_include_dir = numpy.get_include()

# mise (efficient mesh extraction)
mise_module = Extension(
    "lib.libmise.mise",
    sources=["lib/libmise/mise.pyx"],
)

# Gather all extension modules
ext_modules = [
    mise_module,
]

setup(ext_modules=cythonize(ext_modules),)


text:
body {background-color: #CCCC66;}
.eb {background-color: #CCCCFF;}


text: © Cristiano Casella - {{ site.time | slice: 0,4 }}


text:
(function() {
    var app = angular.module('exp', ['ui.router']);

    app.controller('ExperienceController', function() {
      console.log("Went here");

      app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {

        // For unmatched URLs
        $urlRouterProvider.otherwise("/home");

        $stateProvider
          .state('experience.entry', {
            templateUrl: templateUrl + '/src/html/experience_entry.html'
          });
      });

    })();


text:
class CRC_Result : public QObject
{
    Q_OBJECT

    public:
        explicit CRC_Result(QObject *parent = Q_NULLPTR);

        // for QML bindings
        Q_PROPERTY(QString result_hex READ get_result_hex NOTIFY resultChanged)
        Q_PROPERTY(QString result_dec READ get_result_dec NOTIFY resultChanged)
        Q_PROPERTY(QString result_oct READ get_result_oct NOTIFY resultChanged)
        Q_PROPERTY(QString result_bin READ get_result_bin NOTIFY resultChanged)
        Q_PROPERTY(QString result_base READ get_result_base NOTIFY resultChanged)

        Q_PROPERTY(int base READ get_base WRITE set_base NOTIFY baseChanged)

    signals:
        void resultChanged();
        void baseChanged();

    public slots:
        QString get_result_hex() { return get_result(16);    }
        QString get_result_dec() { return get_result(10);    }
        QString get_result_oct() { return get_result(8);     }
        QString get_result_bin() { return get_result(2);     }
        QString get_result_base(){ return get_result(_base); }

        QString get_result(int base) { return QString::number(_result, base).toUpper(); }

        bool get_result_bit(int num_bit){ return (bool)(_result & ((quint64)1 << num_bit)); }

        void set_result(quint64 value);
        quint64 get_result() { return _result; }

        int set_base(int value);
        int get_base() { return _base; }

    private:
        quint64 _result;
        int     _base;
};

#endif // CRC_RESULT_H


text:
#include "base/format_macros.h"
#include "base/time/time.h"
#include "base/memory/singleton.h"
#include "base/strings/stringprintf.h"
#include "content/child/webstathub_impl.h"
#include "third_party/WebKit/public/platform/WebData.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"

//Enable IPC API
#define STAT_HUB_API_BY_IPC

#include "net/stat_hub/stat_hub_api.h"
#include "net/stat_hub/stat_hub_cmd_api.h"
#include "net/http/http_response_headers.h"

//Disable IPC API
#undef STAT_HUB_API_BY_IPC

namespace content {

WebStatHubImpl::WebStatHubImpl():
  inspector_spy_on_(0) {
}

WebStatHubImpl::~WebStatHubImpl() {
}

WebStatHubImpl* WebStatHubImpl::GetInstance() {
  return Singleton<WebStatHubImpl>::get();
}

blink::WebStatHubCmd WebStatHubImpl::cmdCreate(blink::WebStatHubCmdId cmdId) {
    StatHubCmdType cmd;
    StatHubActionType action;

    switch(cmdId) {
        case blink::WEBSH_CMD_MM_CACHE_CLEAR:
            cmd = SH_CMD_WK_MEMORY_CACHE;
            action = SH_ACTION_CLEAR;
            break;
        case blink::WEBSH_CMD_MM_CACHE_SET_STATUS:
            cmd = SH_CMD_WK_MEMORY_CACHE;
            action = SH_ACTION_STATUS;
            break;
        case blink::WEBSH_CMD_MAIN_URL_WILL_START:
            cmd = SH_CMD_WK_MAIN_URL;
            action = SH_ACTION_WILL_START;
            break;
        case blink::WEBSH_CMD_MAIN_URL_DID_FINISH:
            cmd = SH_CMD_WK_MAIN_URL;
            action = SH_ACTION_DID_FINISH;
            break;
        case blink::WEBSH_CMD_RESOURCE_WILL_START_LOAD:
            cmd = SH_CMD_WK_RESOURCE;
            action = SH_ACTION_WILL_START_LOAD;
            break;
        case blink::WEBSH_CMD_RESOURCE_DID_FINISH_LOAD:
            cmd = SH_CMD_WK_RESOURCE;
            action = SH_ACTION_DID_FINISH_LOAD;
            break;
        case blink::WEBSH_CMD_RESOURCE_JS_SEQ:
            cmd = SH_CMD_WK_RESOURCE;
            action = SH_ACTION_JS_SEQ;
            break;
        case blink::WEBSH_CMD_RESOURCE_WILL_SEND_REQUEST:
            cmd = SH_CMD_WK_RESOURCE;
            action = SH_ACTION_WILL_SEND_REQUEST;
            break;
        case blink::WEBSH_CMD_PAGE_WILL_START_LOAD:
            cmd = SH_CMD_WK_PAGE;
            action = SH_ACTION_WILL_START_LOAD;
            break;
        case blink::WEBSH_CMD_PAGE_DID_START_LOAD:
            cmd = SH_CMD_WK_PAGE;
            action = SH_ACTION_DID_START_LOAD;
            break;
        case blink::WEBSH_CMD_PAGE_DID_FINISH_LOAD:
            cmd = SH_CMD_WK_PAGE;
            action = SH_ACTION_DID_FINISH_LOAD;
            break;
        case blink::WEBSH_CMD_PAGE_ON_LOAD:
            cmd = SH_CMD_WK_PAGE;
            action = SH_ACTION_ON_LOAD;
            break;
        case blink::WEBSH_CMD_PAGE_FIRST_PIXEL:
            cmd = SH_CMD_WK_PAGE;
            action = SH_ACTION_FIRST_PIXEL;
            break;
        case blink::WEBSH_CMD_PAGE_PROGRESS_UPDATE:
            cmd = SH_CMD_WK_PAGE;
            action = SH_ACTION_PROGRESS_UPDATE;
            break;
        case blink::WEBSH_CMD_INSPECTOR_SPY_TL_MSG:
            cmd = SH_CMD_WK_INSPECTOR_RECORD;
            action = SH_ACTION_NONE;
            break;
        default:
            return NULL;
    }
    return (blink::WebStatHubCmd)STAT_HUB_API(CmdCreate)(cmd, action, 0);
}

void WebStatHubImpl::cmdAddParamAsString(blink::WebStatHubCmd cmd, const char* param) {
    if(cmd) {
        StatHubCmd* stat_hub_cmd = (StatHubCmd*)cmd;
        stat_hub_cmd->AddParamAsString(param);
    }
}

void WebStatHubImpl::cmdAddParamAsBool(blink::WebStatHubCmd cmd, bool param) {
    if(cmd) {
        StatHubCmd* stat_hub_cmd = (StatHubCmd*)cmd;
        stat_hub_cmd->AddParamAsBool(param);
    }
}

void WebStatHubImpl::cmdAddParamAsUint32(blink::WebStatHubCmd cmd, unsigned int param) {
    if(cmd) {
        StatHubCmd* stat_hub_cmd = (StatHubCmd*)cmd;
        stat_hub_cmd->AddParamAsUint32(param);
    }
}

void WebStatHubImpl::cmdAddParamAsPtr(blink::WebStatHubCmd cmd, void* param) {
    if(cmd) {
        StatHubCmd* stat_hub_cmd = (StatHubCmd*)cmd;
        stat_hub_cmd->AddParamAsPtr(param);
    }
}

void WebStatHubImpl::cmdAddParamAsBuf(blink::WebStatHubCmd cmd, const void* param, unsigned int size) {
    if(cmd) {
        StatHubCmd* stat_hub_cmd = (StatHubCmd*)cmd;
        stat_hub_cmd->AddParamAsBuf(param, size);
    }
}

bool WebStatHubImpl::cmdCommit(blink::WebStatHubCmd cmd) {
    return STAT_HUB_API(CmdCommit)((StatHubCmd*)cmd);
}

bool WebStatHubImpl::cmdCommitDelayed (blink::WebStatHubCmd cmd, unsigned int delay) {
    return STAT_HUB_API(CmdCommitDelayed)((StatHubCmd*)cmd, delay);
}

unsigned long WebStatHubImpl::hash(const blink::WebURL& url){
  return STAT_HUB_API(Hash)(url.spec().data());
}

unsigned int WebStatHubImpl::isPreloaded(const blink::WebURL& url) {
  return STAT_HUB_API(IsPreloaded)(url.spec().data());
}

bool WebStatHubImpl::getPreloaded(const blink::WebURL& url, unsigned int get_from,
    blink::WebURLResponse& response, blink::WebData& data) {
  std::string data_tmp;
  unsigned int size;
  std::string headers;

  if (STAT_HUB_API(GetPreloaded)(url.spec().data(), get_from, headers, data_tmp, size)) {
      scoped_refptr<net::HttpResponseHeaders> responseHeaders;
      responseHeaders = new net::HttpResponseHeaders(headers);

      std::string mime;
      std::string encoding;
      responseHeaders->GetMimeType(&mime);
      responseHeaders->GetCharset(&encoding);

      response.initialize();
      response.setURL(url);
      response.setMIMEType(blink::WebString::fromUTF8(mime));
      response.setTextEncodingName(blink::WebString::fromUTF8(encoding));
      response.setExpectedContentLength(size);

      blink::WebURLResponse::HTTPVersion version = blink::WebURLResponse::Unknown;
      if (responseHeaders->GetHttpVersion() == net::HttpVersion(0, 9))
        version = blink::WebURLResponse::HTTP_0_9;
      else if (responseHeaders->GetHttpVersion() == net::HttpVersion(1, 0))
        version = blink::WebURLResponse::HTTP_1_0;
      else if (responseHeaders->GetHttpVersion() == net::HttpVersion(1, 1))
        version = blink::WebURLResponse::HTTP_1_1;
      int httpStatusCode = responseHeaders->response_code();
      std::string httpStatusText = responseHeaders->GetStatusText();
      response.setHTTPVersion(version);
      response.setHTTPStatusCode(httpStatusCode);
      response.setHTTPStatusText(blink::WebString::fromUTF8(httpStatusText));

      base::Time time_val;
      if (responseHeaders->GetLastModifiedValue(&time_val)) {
        response.setLastModifiedDate(time_val.ToDoubleT());
      }

      // Build up the header map.
      void* iter = NULL;
      std::string value;
      std::string name;
      while (responseHeaders->EnumerateHeaderLines(&iter, &name, &value)) {
          response.addHTTPHeaderField(blink::WebString::fromUTF8(name),
              blink::WebString::fromUTF8(value));
      }

      data.assign(data_tmp.data(), size);
      return true;
  }
  return false;
}

bool WebStatHubImpl::releasePreloaded(const blink::WebURL& url) {
    return STAT_HUB_API(ReleasePreloaded)(url.spec().data());
}

bool WebStatHubImpl::isPreloaderEnabled() {
    return STAT_HUB_API(IsPreloaderEnabled)();
}

bool WebStatHubImpl::isPerfEnabled() {
    return STAT_HUB_API(IsPerfEnabled)();
}

bool WebStatHubImpl::isInspectorSpyEnabled() {
    unsigned int mask = STAT_HUB_API(GetCmdMask)();
    return (mask & (1<<SH_CMD_WK_INSPECTOR_RECORD));
}

 class MyData : public base::trace_event::ConvertableToTraceFormat {
public:
     MyData() {}
     virtual void AppendAsTraceFormat(std::string* out) const override {
       out->append("{\"foo\":1}");
     }
private:
     virtual ~MyData() {}
     DISALLOW_COPY_AND_ASSIGN(MyData);
};

typedef std::map<std::string, std::string> TraceMsgMapType;
static TraceMsgMapType* trace_msg_map = NULL;

static void inspectorSpyCallback(base::TraceTicks timestamp,
        char phase,
        const unsigned char* category_group_enabled,
        const char* name,
        unsigned long long id,
        int num_args,
        const char* const arg_names[],
        const unsigned char arg_types[],
        const unsigned long long arg_values[],
        const scoped_refptr<base::trace_event::ConvertableToTraceFormat>* convertable_values,
        unsigned int flags) {

    if (!trace_msg_map) {
        return;
    }

    std::string msg;
    std::string out;

    msg += "";
    std::string name_str = name;
    std::replace(name_str.begin(), name_str.end(), ' ', '_');
    base::StringAppendF(&msg, "\"type\":\"%s\",", name_str.c_str());

    //TBD: base::StringAppendF(&msg, "\"startTime\":%" PRId64, timestamp.ToInternalValue());
    StatHubTimeStamp start_timestamp = StatHubTimeStamp::NowFromSystemTime();
    base::StringAppendF(&msg, "\"startTime\":%f", start_timestamp.ToDoubleT()*1000);

    base::trace_event::TraceEvent::TraceValue arg_value;
    for (int i = 0; i < num_args; ++i) {
        name_str = arg_names[i];
        std::replace(name_str.begin(), name_str.end(), ' ', '_');
        msg += ",";
        out = "";
        if (arg_types[i] == TRACE_VALUE_TYPE_CONVERTABLE) {
            convertable_values[i]->AppendAsTraceFormat(&out);
        }
        else {
            arg_value.as_uint = arg_values[i];
            base::trace_event::TraceEvent::TraceEvent::AppendValueAsJSON(arg_types[i], arg_value, &out);
        }
        base::StringAppendF(&msg, "\"%s\":", arg_names[i]);
        msg += out;
    }
    //base::TimeTicks end_timestamp = timestamp;
    StatHubTimeStamp end_timestamp = StatHubTimeStamp::NowFromSystemTime();

    switch(phase) {
        case TRACE_EVENT_PHASE_BEGIN:
            //push message
            trace_msg_map->insert(std::pair<std::string, std::string>(
                    name, msg));
            break;
        case TRACE_EVENT_PHASE_END:
            //pop message
            {
                TraceMsgMapType::iterator trace_msg_iter = trace_msg_map->find(name);
                if (trace_msg_iter == trace_msg_map->end() ) {
                    break;
                }
                msg = trace_msg_iter->second;
                trace_msg_map->erase(trace_msg_iter);
            }
        case TRACE_EVENT_PHASE_INSTANT:
            //TBD: base::StringAppendF(&msg, ",\"endTime\":%" PRId64, end_timestamp.ToInternalValue());
            base::StringAppendF(&msg, ",\"endTime\":%f", end_timestamp.ToDoubleT()*1000);

            {
                StatHubCmd* cmd = STAT_HUB_API(CmdCreate)(SH_CMD_WK_INSPECTOR_RECORD, SH_ACTION_NONE, 0);
                if (NULL!=cmd) {
                    cmd->AddParamAsString(msg.c_str());
                    STAT_HUB_API(CmdCommit)(cmd);
                }
            }
            break;
        default:
            break;
    }

}

bool WebStatHubImpl::inspectorSpyEnable() {
    if (isInspectorSpyEnabled()) {
        if (!inspector_spy_on_) {
            if (!trace_msg_map) {
                trace_msg_map = new TraceMsgMapType;
            }
            std::string filter;
            //-*,disabled-by-default-devtools.timeline,disabled-by-default-devtools.timeline.frame,blink.console,disabled-by-default-devtools.timeline.stack
            filter += "*-,";
            filter += TRACE_DISABLED_BY_DEFAULT("devtools.timeline");
            filter += ",";
            filter += TRACE_DISABLED_BY_DEFAULT("devtools.timeline.frame");
            filter += ",";
            filter += "blink.console";
            filter += ",";
            filter += TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack");
            base::trace_event::TraceLog::GetInstance()->SetEventCallbackEnabled(
                    base::trace_event::TraceConfig(filter,""),
                    inspectorSpyCallback
            );
        }
        inspector_spy_on_++;
    }
    return true;
}

bool WebStatHubImpl::inspectorSpyDisable() {
    if (isInspectorSpyEnabled() && inspector_spy_on_) {
        inspector_spy_on_--;
        if(!inspector_spy_on_) {
            base::trace_event::TraceLog::GetInstance()->SetEventCallbackDisabled();
            if (!trace_msg_map) {
                delete trace_msg_map;
                trace_msg_map = NULL;
            }
        }
    }
    return true;
}

}


text:
namespace Azure.ResourceManager.Resources.Models
{
    /// <summary> The value of a parameter. </summary>
    public partial class ParameterValuesValue
    {
        /// <summary> Initializes a new instance of ParameterValuesValue. </summary>
        public ParameterValuesValue()
        {
        }

        /// <summary> Initializes a new instance of ParameterValuesValue. </summary>
        /// <param name="value"> The value of the parameter. </param>
        internal ParameterValuesValue(object value)
        {
            Value = value;
        }

        /// <summary> The value of the parameter. </summary>
        public object Value { get; set; }
    }
}


text:
package org.batfish.datamodel;

import static com.google.common.base.Preconditions.checkArgument;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.datamodel.route.nh.NextHop;
import org.batfish.datamodel.route.nh.NextHopDiscard;

/** OSPF intra-area route. Must stay within a single OSPF area. */
@ParametersAreNonnullByDefault
public class OspfInternalSummaryRoute extends OspfInternalRoute {

  private static final Interner<OspfInternalSummaryRoute> _cache = Interners.newWeakInterner();
  private int _hashCode;

  @JsonCreator
  private static OspfInternalSummaryRoute jsonCreator(
      @Nullable @JsonProperty(PROP_NETWORK) Prefix network,
      @Nullable @JsonProperty(PROP_ADMINISTRATIVE_COST) Integer admin,
      @Nullable @JsonProperty(PROP_METRIC) Long metric,
      @Nullable @JsonProperty(PROP_NEXT_HOP_IP) Ip nextHopIp,
      @Nullable @JsonProperty(PROP_NEXT_HOP_INTERFACE) String nextHopInterface,
      @Nullable @JsonProperty(PROP_AREA) Long area,
      @JsonProperty(PROP_TAG) long tag) {
    assert NextHop.legacyConverter(nextHopInterface, nextHopIp).equals(NextHopDiscard.instance());
    checkArgument(network != null, "%s must be specified", PROP_NETWORK);
    checkArgument(admin != null, "%s must be specified", PROP_ADMINISTRATIVE_COST);
    checkArgument(metric != null, "%s must be specified", PROP_METRIC);
    checkArgument(area != null, "%s must be specified", PROP_AREA);
    return new OspfInternalSummaryRoute(network, admin, metric, area, tag);
  }

  public OspfInternalSummaryRoute(Prefix network, int admin, long metric, long area, long tag) {
    super(network, NextHopDiscard.instance(), admin, metric, area, tag, false, false);
  }

  @Nonnull
  @Override
  public RoutingProtocol getProtocol() {
    return RoutingProtocol.OSPF_IS;
  }

  public static Builder builder() {
    return new Builder();
  }

  public static final class Builder
      extends AbstractRouteBuilder<Builder, OspfInternalSummaryRoute> {

    private long _area;

    @Nonnull
    @Override
    public OspfInternalSummaryRoute build() {
      OspfInternalSummaryRoute r =
          new OspfInternalSummaryRoute(getNetwork(), getAdmin(), getMetric(), _area, getTag());
      return _cache.intern(r);
    }

    @Nonnull
    @Override
    protected Builder getThis() {
      return this;
    }

    public Builder setArea(long area) {
      _area = area;
      return this;
    }

    private Builder() {}
  }

  /////// Keep #toBuilder, #equals, and #hashCode in sync ////////

  @Override
  public Builder toBuilder() {
    return builder()
        // AbstractRoute properties
        .setNetwork(getNetwork())
        .setNextHop(NextHopDiscard.instance())
        .setAdmin(_admin)
        .setMetric(_metric)
        .setTag(_tag)
        // OspfInternalSummaryRoute properties
        .setArea(getArea());
  }

  @Override
  public boolean equals(@Nullable Object o) {
    if (o == this) {
      return true;
    } else if (!(o instanceof OspfInternalSummaryRoute)) {
      return false;
    }
    OspfInternalSummaryRoute other = (OspfInternalSummaryRoute) o;
    return _network.equals(other._network)
        && _admin == other._admin
        && _area == other._area
        && _metric == other._metric
        && _tag == other._tag;
  }

  @Override
  public int hashCode() {
    int h = _hashCode;
    if (h == 0) {
      h = _network.hashCode();
      h = 31 * h + _admin;
      h = 31 * h + Long.hashCode(_area);
      h = 31 * h + Long.hashCode(_metric);
      h = 31 * h + Long.hashCode(_tag);

      _hashCode = h;
    }
    return h;
  }
}


text:
function showNewDiv(){
	$('#new-address').slideDown();
}

function hideNewDiv(){
	$('#new-address').slideUp();
}

function showInput(id){
	var d = $("#"+id);
	$('.viewContent',d).hide();
	$('.editContent',d).show();
}

function hideInput(id){
	var d = $("#"+id);
	$('.viewContent',d).show();
	$('.editContent',d).hide();
}


text:
#ifdef __cplusplus
extern "C" {
#endif

#ifndef Oep_H
#define Oep_H

#include "OEK.h"
#include "oec_values.h"
#include "OepClient.h"
#include "Oed_Dispatcher.h"
#include "OeNet.h"
#include "SecurityContext.h"
#include "LoginModule.h"

#define T OepServer
struct server_T {

    Table_T kernels;
    SecurityContext security_context;
    Oed_Dispatcher dispatcher;
    OeNet net;

    oep_client_read_msg  *read_fun;
    oep_client_write_msg *write_fun;
};

typedef struct server_T *T;

extern T OepServer_new(Oed_Dispatcher, OeNet);

extern int OepServer_listen(T _this_, char *hostifc, int port);

extern void OepServer_free(T*);
extern void OepServer_stats(T);

extern void OepServer_add_login_module(T, LoginModule);
extern void OepServer_add_kernel(T, oe_scalar, OEK);

extern void OepServer_configure(T _this_,
                         oep_client_read_msg  read_fun,
                         oep_client_write_msg write_fun,
                         oe_id (* idfun) (void *),
                         void *idfun_arg );

#undef T

#endif

#ifdef __cplusplus
}
#endif


text:
Angular JS directive for Google AdSense advertisements. With ngAdsense, you can place your ads onto your website, or an Angular JS template as well.

## Requirements

 - A modern browser
 - AngularJS 1.2+

## Installation

This module contains only one file (ngAdsense.js), so you have to download it from GitHub.

Now you have to do is add the scripts to your application. Just make sure the `ng-adsense.js` file is inserted **after** the `angular.js` script:

```html
<script src="angular.js"></script>
<script src="ng-adsense.js"></script>
```

And finally, include it in your angular app

```javascript

app.module('myApp', ['ngAdsense']);

```

## Usage

 1. Add the `ngAdsense` module as a dependency in your AngularJS app;
 2. Add the custom directive `<adsense-directive>` to your html page or template.
 3. Setup all three mandatory fields.
 4. Ready!

## Example

```html
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.min.js"></script>
		<script type="text/javascript" src="ng-adsense.js"></script>
		<script type="text/javascript">
			var ngAdSenseDemoApp = angular.module('DemoApp', ['ngAdsense']);
		</script>
	</head>
	<body ng-app="DemoApp">
		<adsense-directive
			ad-client="YOUR_CLIENT_ID"
			ad-slot="YOUR_SLOT_ID"
			css-style="display:inline-block;width:320px;height:50px;">
		</adsense-directive>
	</body>
</html>
```

## License

See the [LICENSE](https://github.com/szrnka-peter/ngAdsense/blob/master/LICENSE) file.

## Changelog

See the [CHANGELOG](https://github.com/szrnka-peter/ngAdsense/blob/master/CHANGELOG.md) file.


text:
'use strict';

var expect = require('chai').expect
  , rules  = require('../lib/parse_rules')
  , Token  = require('../lib/token').Token
  , State  = require('../lib/state').State;

describe('State', function () {
    describe('hasCodeStart', function () {
        it('returns true if it contains a code-start token', function () {
            var state = new State()
              , token = new Token('text', '		Example: >\n');

            state.tokens.push(token);
            rules.names.forEach(function (rule) {
                rules.applyRule(rule, state);
            });

            expect(state.hasCodeStart()).to.be.true;
        });
    });
});


text:
izi.TRAVEL Android API
======================

An android wrapper around the [izi.TRAVEL API][api-docs] using [Retrofit][retrofit]. Remote services are grouped into local service objects which can be centrally managed by a `IZITravel` instance. It will act as a factory for all of the services and will automatically initialize them with your credentials and API key.

Usage
-----

Create a `IZITravel` instance which is an adapter for the library functionality.

```java
IZITravel iziTravel = IZITravel.withApiKey("api_key");
```

Create a service instance to execute the request. F.e. to search content you need to create `SearchService`:

```java
SearchService service = iziTravel.searchService();
```

Then you can execute request synchronously or asynchronously.

```java
Call<List<CompactMtgObject>> call = service.search(...);
Response<List<CompactMtgObject>> response = call.execute();
```

```java
Call<List<CompactMtgObject>> call = service.search(...);
call.enqueue(new Callback<List<CompactMtgObject>>() {
    @Override
    public void onResponse(Call<List<CompactMtgObject>> call, Response<List<CompactMtgObject>> response) {
        // ...
    }

    @Override
    public void onFailure(Call<List<CompactMtgObject>> call, Throwable t) {
        // ...
    }
});
```

Download
--------

```groovy
compile 'travel.izi.api:android-api:0.2.1'
```

Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap].

License
-------

    Copyright (C) 2015 IZITEQ B.V.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

[api-docs]: http://api-docs.izi.travel/
[retrofit]: http://square.github.io/retrofit/

[snap]: https://oss.sonatype.org/content/repositories/snapshots/


text:
package zooowner
package actor

import zooowner.message._

import akka.actor.{Actor, ActorRef, Stash, Props}
import akka.actor.Actor.Receive
import akka.util.Timeout
import akka.pattern.{ask, pipe}

import scala.util.{Success, Failure}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext

object ZooownerActor {
  val StashTimeout = 3.seconds
  case object StashTimedOut

  def props(
    watcher: ActorRef,
    server: String,
    timeout: FiniteDuration) =
  {
    Props {
      new ZooownerActor(
        watcher,
        server,
        timeout)
    }
  }

  private type Recovery = PartialFunction[Throwable, ZKFailure]

  private def failureFor(path: ZKPath)(recover: Recovery): Recovery = {
    recover orElse {
      case _: ConnectionLossException => ConnectionLost(path, Disconnected)
      case _: SessionExpiredException => ConnectionLost(path, Expired)
      case other: ZKException => UnexpectedFailure(path, Failure(other))
    }
  }
}

class ZooownerActor(
    watcher: ActorRef,
    server: String,
    timeout: FiniteDuration)
  extends Actor
  with Stash
  with ZKPathDSL
  with DefaultSerializers
{
  import ZooownerActor._
  import context.dispatcher
  import context.system

  val connectionWatcher = ZKConnectionWatcher {
    // forward all connection events to current actor's
    // mailbox in order to preserve absolute order of events
    case event =>
      self ! event
      watcher ! event
  }

  val connection = ZKConnection(
    connectionString = server,
    sessionTimeout = timeout,
    connectionWatcher = connectionWatcher)

  val zk = AsyncZooowner(connection)

  private var stashActive = true

  def receive = connecting

  /**
   * Waits for connection to ZooKeeper ensamble.
   */
  def connecting: Receive = {
    case Connected => {
      unstashAll()
      context become active
    }

    case StashTimedOut => {
      unstashAll()
      stashActive = false
    }

    case other => {
      if (stashActive && active.isDefinedAt(other)) {
        stash()
      }
    }
  }

  /**
   * Implements ZooownerActor primary API.
   */
  def active: Receive = {
    case Disconnected => {
      // since events are being processed via mailbox we need to
      // make sure that connection is still down
      if (!zk.isConnected) {
        stashActive = true
        system.scheduler.scheduleOnce(StashTimeout, self, StashTimedOut)
        context become connecting
      }
    }

    /*
     * Creates new node.
     *
     * @param path Path of node to be created.
     * @param data Data that should be stored in created node.
     * @param persistent Specifies whether created node should be persistent.
     * @param sequential Specifies whether created node should be sequential.
     */
    case CreateNode(path, data, persistent, sequential) => {
      val result = zk.async.create[RawZKData](path, data, persistent, sequential)

      result map { name =>
        NodeCreated(name, None)
      } recover failureFor(path) {
        case _: NodeExistsException => NodeExists(path)
        case _: ChildrenNotAllowedException => ChildrenNotAllowed(path)
      } pipeTo sender
    }

    /*
     * Deletes node.
     *
     * @param path Path of node to be deleted.
     * @param version Provides version to be checked against before deletion.
     */
    case DeleteNode(path, version) => {
      val result = zk.async.delete(path, version = version)

      result map { _ =>
        NodeDeleted(path)
      } recover failureFor(path) {
        case _: NoNodeException => NodeNotExists(path)
        case _: NodeNotEmptyException => NodeNotEmpty(path)
        case _: BadVersionException => BadVersion(path, version)
      } pipeTo sender
    }

    /*
     * Sets a new value for the node.
     *
     * @param path Path of the node to be updated.
     * @param data New value of the node.
     */
    case SetNodeValue(path, data, version) => {
      val result = zk.async.set(path, data, version)

      result map { meta =>
        NodeMeta(path, meta)
      } recover failureFor(path) {
        case _: NoNodeException => NodeNotExists(path)
        case _: BadVersionException => BadVersion(path, version)
      } pipeTo sender
    }

    /*
     * Requests current value of the node.
     *
     * @param path Path of the node which value is requested.
     */
    case GetNodeValue(path) => {
      val result = zk.async.get(path)

      result map { node =>
        Node(path, node)
      } recover failureFor(path) {
        case _: NoNodeException => NodeNotExists(path)
      } pipeTo sender
    }

    /*
     * Request children list of the node.
     *
     * @param path Path of the node which children are requested.
     */
    case GetNodeChildren(path) => {
      val result = zk.async.children(path)

      result map { children =>
        NodeChildren(path, children)
      } recover failureFor(path) {
        case _: NoNodeException => NodeNotExists(path)
      } pipeTo sender
    }

    /*
     * Sets up a watcher on a node.
     *
     * @param path Path of the node to be watched.
     * @param persistent Whether watch should be persistent.
     */
    case WatchNode(path, persistent) => {
      val client = sender

      val wrapFailure = failureFor(path) {
        case _: NoNodeException => NodeNotExists(path)
      }

      zk.watch(path) {
        case Success(message) => client ! message
        case Failure(failure) => client ! wrapFailure(failure)
      }
    }
  }
}

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


text:
package ru.test.struts2.service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ru.test.struts2.dao.DAO;
import ru.test.struts2.entity.Person;

import java.util.List;

/**
 * @author artem.pronchakov@calisto.email
 */
public class UserServiceImpl implements UserService {

    private DAO dao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Person getPerson(Long id, boolean readonly) {
        return dao.get(Person.class, new Long(id), readonly);
    }

    public DAO getDao() {
        return dao;
    }

    public void setDao(DAO dao) {
        this.dao = dao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public List<Person> findAllPersons(boolean readonly) {
        return dao.findAllPersons(readonly);
    }

}


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public enum VirtualMachineGuestOsIdentifier
{
  dosGuest ("dosGuest"),
  win31Guest ("win31Guest"),
  win95Guest ("win95Guest"),
  win98Guest ("win98Guest"),
  winMeGuest ("winMeGuest"),
  winNTGuest ("winNTGuest"),
  win2000ProGuest ("win2000ProGuest"),
  win2000ServGuest ("win2000ServGuest"),
  win2000AdvServGuest ("win2000AdvServGuest"),
  winXPHomeGuest ("winXPHomeGuest"),
  winXPProGuest ("winXPProGuest"),
  winXPPro64Guest ("winXPPro64Guest"),
  winNetWebGuest ("winNetWebGuest"),
  winNetStandardGuest ("winNetStandardGuest"),
  winNetEnterpriseGuest ("winNetEnterpriseGuest"),
  winNetDatacenterGuest ("winNetDatacenterGuest"),
  winNetBusinessGuest ("winNetBusinessGuest"),
  winNetStandard64Guest ("winNetStandard64Guest"),
  winNetEnterprise64Guest ("winNetEnterprise64Guest"),
  winLonghornGuest ("winLonghornGuest"),
  winLonghorn64Guest ("winLonghorn64Guest"),
  winNetDatacenter64Guest ("winNetDatacenter64Guest"),
  winVistaGuest ("winVistaGuest"),
  winVista64Guest ("winVista64Guest"),
  windows7Guest ("windows7Guest"),
  windows7_64Guest ("windows7_64Guest"),
  windows7Server64Guest ("windows7Server64Guest"),
  freebsdGuest ("freebsdGuest"),
  freebsd64Guest ("freebsd64Guest"),
  redhatGuest ("redhatGuest"),
  rhel2Guest ("rhel2Guest"),
  rhel3Guest ("rhel3Guest"),
  rhel3_64Guest ("rhel3_64Guest"),
  rhel4Guest ("rhel4Guest"),
  rhel4_64Guest ("rhel4_64Guest"),
  rhel5Guest ("rhel5Guest"),
  rhel5_64Guest ("rhel5_64Guest"),
  rhel6Guest ("rhel6Guest"),
  rhel6_64Guest ("rhel6_64Guest"),
  centosGuest ("centosGuest"),
  centos64Guest ("centos64Guest"),
  oracleLinuxGuest ("oracleLinuxGuest"),
  oracleLinux64Guest ("oracleLinux64Guest"),
  suseGuest ("suseGuest"),
  suse64Guest ("suse64Guest"),
  slesGuest ("slesGuest"),
  sles64Guest ("sles64Guest"),
  sles10Guest ("sles10Guest"),
  sles10_64Guest ("sles10_64Guest"),
  sles11Guest ("sles11Guest"),
  sles11_64Guest ("sles11_64Guest"),
  nld9Guest ("nld9Guest"),
  oesGuest ("oesGuest"),
  sjdsGuest ("sjdsGuest"),
  mandrivaGuest ("mandrivaGuest"),
  mandriva64Guest ("mandriva64Guest"),
  turboLinuxGuest ("turboLinuxGuest"),
  turboLinux64Guest ("turboLinux64Guest"),
  ubuntuGuest ("ubuntuGuest"),
  ubuntu64Guest ("ubuntu64Guest"),
  debian4Guest ("debian4Guest"),
  debian4_64Guest ("debian4_64Guest"),
  debian5Guest ("debian5Guest"),
  debian5_64Guest ("debian5_64Guest"),
  asianux3Guest ("asianux3Guest"),
  asianux3_64Guest ("asianux3_64Guest"),
  asianux4Guest ("asianux4Guest"),
  asianux4_64Guest ("asianux4_64Guest"),
  other24xLinuxGuest ("other24xLinuxGuest"),
  other26xLinuxGuest ("other26xLinuxGuest"),
  otherLinuxGuest ("otherLinuxGuest"),
  other24xLinux64Guest ("other24xLinux64Guest"),
  other26xLinux64Guest ("other26xLinux64Guest"),
  otherLinux64Guest ("otherLinux64Guest"),
  solaris6Guest ("solaris6Guest"),
  solaris7Guest ("solaris7Guest"),
  solaris8Guest ("solaris8Guest"),
  solaris9Guest ("solaris9Guest"),
  solaris10Guest ("solaris10Guest"),
  solaris10_64Guest ("solaris10_64Guest"),
  os2Guest ("os2Guest"),
  eComStationGuest ("eComStationGuest"),
  netware4Guest ("netware4Guest"),
  netware5Guest ("netware5Guest"),
  netware6Guest ("netware6Guest"),
  openServer5Guest ("openServer5Guest"),
  openServer6Guest ("openServer6Guest"),
  unixWare7Guest ("unixWare7Guest"),
  darwinGuest ("darwinGuest"),
  darwin64Guest ("darwin64Guest"),
  otherGuest ("otherGuest"),
  otherGuest64 ("otherGuest64");

  private final String val;
  private VirtualMachineGuestOsIdentifier(String val)
  {
    this.val = val;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"

	>
<channel>
	<title>Comments on: The Tribune: A Hands Up to Reviving Crafts</title>
	<atom:link href="http://happyhands.in/media-coverage/a-hands-up-to-reviving-crafts/feed/" rel="self" type="application/rss+xml" />
	<link>http://happyhands.in/media-coverage/a-hands-up-to-reviving-crafts/</link>
	<description>Conserve the Arts. Preserve our Culture</description>
	<lastBuildDate></lastBuildDate>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.13</generator>
</channel>
</rss>


text:
require 'spec_helper'

describe PgTriggers, 'counter_cache' do
  before do
    DB.drop_table?(:counter_table)
    DB.drop_table?(:counted_table)
  end

  it "should increment and decrement the count of related items in the associated table as rows are inserted and updated and deleted" do
    DB.create_table :counter_table do
      integer :id, null: false
      integer :counted_count, null: false, default: 0
    end

    DB.create_table :counted_table do
      integer :id, null: false
      integer :counter_id, null: false
    end

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :counted_count,
        counted_table: :counted_table,
        relationship: {id: :counter_id},
      )

    DB[:counter_table].insert(id: 1)
    DB[:counter_table].insert(id: 2)
    DB[:counter_table].where(id: 1).get(:counted_count).should == 0

    DB[:counted_table].insert(id: 1, counter_id: 1)
    DB[:counter_table].where(id: 1).get(:counted_count).should == 1

    DB[:counted_table].insert(id: 2, counter_id: 1)
    DB[:counter_table].where(id: 1).get(:counted_count).should == 2

    DB[:counted_table].insert(id: 3, counter_id: 2)
    DB[:counter_table].where(id: 1).get(:counted_count).should == 2
    DB[:counter_table].where(id: 2).get(:counted_count).should == 1

    DB[:counted_table].insert(id: 4, counter_id: 1)
    DB[:counter_table].where(id: 1).get(:counted_count).should == 3

    DB[:counted_table].where(id: 4).update(counter_id: 2).should == 1
    DB[:counter_table].where(id: 1).get(:counted_count).should == 2
    DB[:counter_table].where(id: 2).get(:counted_count).should == 2

    DB[:counted_table].where(counter_id: 1).delete.should == 2
    DB[:counter_table].where(id: 1).get(:counted_count).should == 0
  end

  it "should work when the tables are related by multiple columns" do
    DB.create_table :counter_table do
      integer :id1, null: false
      integer :id2, null: false
      integer :counted_count, null: false, default: 0
    end

    DB.create_table :counted_table do
      integer :id, null: false
      integer :counter_id1, null: false
      integer :counter_id2, null: false
    end

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :counted_count,
        counted_table: :counted_table,
        relationship: {id1: :counter_id1, id2: :counter_id2},
      )

    DB[:counter_table].insert(id1: 1, id2: 1)
    DB[:counter_table].insert(id1: 2, id2: 1)
    DB[:counter_table].where(id1: 1).get(:counted_count).should == 0

    DB[:counted_table].insert(id: 1, counter_id1: 1, counter_id2: 1)
    DB[:counter_table].where(id1: 1).get(:counted_count).should == 1

    DB[:counted_table].insert(id: 2, counter_id1: 1, counter_id2: 1)
    DB[:counter_table].where(id1: 1).get(:counted_count).should == 2

    DB[:counted_table].insert(id: 3, counter_id1: 2, counter_id2: 1)
    DB[:counter_table].where(id1: 1).get(:counted_count).should == 2
    DB[:counter_table].where(id1: 2).get(:counted_count).should == 1

    DB[:counted_table].insert(id: 4, counter_id1: 1, counter_id2: 1)
    DB[:counter_table].where(id1: 1).get(:counted_count).should == 3

    DB[:counted_table].where(id: 4).update(counter_id1: 2).should == 1
    DB[:counter_table].where(id1: 1).get(:counted_count).should == 2
    DB[:counter_table].where(id1: 2).get(:counted_count).should == 2

    DB[:counted_table].where(counter_id1: 1).delete.should == 2
    DB[:counter_table].where(id1: 1).get(:counted_count).should == 0
  end

  it "should work as expected when any of the columns are set to null or an unknown value" do
    DB.create_table :counter_table do
      integer :id1, null: false
      integer :id2, null: false
      integer :counted1_count, null: false, default: 0
      integer :counted2_count, null: false, default: 0
    end

    DB.create_table :counted_table do
      integer :id, null: false
      integer :counter_id1
      integer :counter_id2
    end

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :counted1_count,
        counted_table: :counted_table,
        relationship: {id1: :counter_id1},
      )

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :counted2_count,
        counted_table: :counted_table,
        relationship: {id1: :counter_id1, id2: :counter_id2},
      )

    DB[:counter_table].insert(id1: 1, id2: 1)
    DB[:counted_table].insert(id: 1, counter_id1: 1, counter_id2: 1)
    DB[:counted_table].insert(id: 2, counter_id1: 1, counter_id2: 1)
    DB[:counted_table].insert(id: 3, counter_id1: 1, counter_id2: 1)
    DB[:counted_table].insert(id: 4, counter_id1: 1, counter_id2: 1)
    DB[:counter_table].where(id1: 1, id2: 1).get([:counted1_count, :counted2_count]).should == [4, 4]

    DB[:counted_table].where(id: 1).update(counter_id1: nil).should == 1
    DB[:counter_table].where(id1: 1, id2: 1).get([:counted1_count, :counted2_count]).should == [3, 3]

    DB[:counted_table].where(id: 2).update(counter_id2: nil).should == 1
    DB[:counter_table].where(id1: 1, id2: 1).get([:counted1_count, :counted2_count]).should == [3, 2]

    DB[:counted_table].where(id: 3).update(counter_id1: 90000000).should == 1
    DB[:counter_table].where(id1: 1, id2: 1).get([:counted1_count, :counted2_count]).should == [2, 1]

    DB[:counted_table].where(id: 4).update(counter_id2: 90000000).should == 1
    DB[:counter_table].where(id1: 1, id2: 1).get([:counted1_count, :counted2_count]).should == [2, 0]

    DB[:counted_table].insert(id: 5, counter_id1: 1, counter_id2: nil)
    DB[:counter_table].where(id1: 1, id2: 1).get([:counted1_count, :counted2_count]).should == [3, 0]

    DB[:counted_table].insert(id: 6, counter_id1: nil, counter_id2: nil)
    DB[:counter_table].where(id1: 1, id2: 1).get([:counted1_count, :counted2_count]).should == [3, 0]
  end

  it "should accept a :where clause to filter the rows that are counted" do
    DB.create_table :counter_table do
      integer :id, null: false

      integer :condition_count,       null: false, default: 0
      integer :value_count,           null: false, default: 0
      integer :condition_value_count, null: false, default: 0
    end

    DB.create_table :counted_table do
      integer :id, null: false
      integer :counter_id, null: false

      boolean :condition
      integer :value
    end

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :condition_count,
        counted_table: :counted_table,
        relationship: {id: :counter_id},
        where: "ROW.condition",
      )

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :value_count,
        counted_table: :counted_table,
        relationship: {id: :counter_id},
        where: "ROW.value > 5",
      )

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :condition_value_count,
        counted_table: :counted_table,
        relationship: {id: :counter_id},
        where: "ROW.condition AND ROW.value > 5",
      )

    def values
      DB[:counter_table].where(id: 1).get([:condition_count, :value_count, :condition_value_count])
    end

    DB[:counter_table].insert(id: 1)

    values.should == [0, 0, 0]
    DB[:counted_table].insert(id: 1, counter_id: 1, condition: true,  value: 4)
    values.should == [1, 0, 0]
    DB[:counted_table].insert(id: 2, counter_id: 1, condition: false, value: 4)
    values.should == [1, 0, 0]
    DB[:counted_table].insert(id: 3, counter_id: 1, condition: true,  value: 6)
    values.should == [2, 1, 1]
    DB[:counted_table].insert(id: 4, counter_id: 1, condition: false, value: 6)
    values.should == [2, 2, 1]
    DB[:counted_table].insert(id: 5, counter_id: 1, condition: nil,   value: 4)
    values.should == [2, 2, 1]
    DB[:counted_table].insert(id: 6, counter_id: 1, condition: false, value: nil)
    values.should == [2, 2, 1]
    DB[:counted_table].insert(id: 7, counter_id: 1, condition: true,  value: nil)
    values.should == [3, 2, 1]
    DB[:counted_table].insert(id: 8, counter_id: 1, condition: nil,   value: 6)
    values.should == [3, 3, 1]

    DB[:counted_table].where(id: 3).update(counter_id: 2).should == 1
    values.should == [2, 2, 0]
    DB[:counted_table].where(id: [4, 7]).delete.should == 2
    values.should == [1, 1, 0]
    DB[:counted_table].where(id: 3).update(counter_id: 1).should == 1
    values.should == [2, 2, 1]
    DB[:counted_table].where(id: 1).update(value: 6).should == 1
    values.should == [2, 3, 2]
  end

  it "should silently replace another counter cache trigger on the same set of columns" do
    DB.create_table :counter_table do
      integer :id, null: false

      integer :condition_count, null: false, default: 0
    end

    DB.create_table :counted_table do
      integer :id, null: false
      integer :counter_id, null: false

      boolean :condition
    end

    def value
      DB[:counter_table].where(id: 1).get(:condition_count)
    end

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :condition_count,
        counted_table: :counted_table,
        relationship: {id: :counter_id},
      )

    DB[:counter_table].insert(id: 1)

    DB[:counted_table].insert(id: 1, counter_id: 1, condition: true)
    value.should == 1
    DB[:counted_table].insert(id: 2, counter_id: 1, condition: false)
    value.should == 2
    DB[:counted_table].insert(id: 3, counter_id: 1, condition: true)
    value.should == 3
    DB[:counted_table].insert(id: 4, counter_id: 1, condition: false)
    value.should == 4

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :condition_count,
        counted_table: :counted_table,
        relationship: {id: :counter_id},
        where: "ROW.condition",
      )

    DB[:counted_table].insert(id: 5, counter_id: 1, condition: nil)
    value.should == 4
    DB[:counted_table].insert(id: 6, counter_id: 1, condition: false)
    value.should == 4
    DB[:counted_table].insert(id: 7, counter_id: 1, condition: true)
    value.should == 5
    DB[:counted_table].insert(id: 8, counter_id: 1, condition: nil)
    value.should == 5
  end

  it "should support a custom value to increment and decrement the count by" do
    DB.create_table :counter_table do
      integer :id, null: false
      integer :counted_count, null: false, default: 0
    end

    DB.create_table :counted_table do
      integer :id, null: false
      integer :counter_id, null: false
    end

    DB.run \
      PgTriggers.counter_cache(
        counting_table: :counter_table,
        counting_column: :counted_count,
        counted_table: :counted_table,
        relationship: {id: :counter_id},
        increment: 5,
      )

    DB[:counter_table].insert(id: 1)
    DB[:counter_table].where(id: 1).get(:counted_count).should == 0

    DB[:counted_table].insert(id: 1, counter_id: 1)
    DB[:counter_table].where(id: 1).get(:counted_count).should == 5

    DB[:counted_table].insert(id: 2, counter_id: 1)
    DB[:counter_table].where(id: 1).get(:counted_count).should == 10

    DB[:counted_table].where(id: 1).delete.should == 1
    DB[:counter_table].where(id: 1).get(:counted_count).should == 5
  end
end


text:
#include "cg_local.h"

static float* GetGameStageColor(void) {
    if (cgs.gameStage == FORMING_TEAMS) {
        return colorGreen;
    } else if (cgs.gameStage == MAKING_BETS) {
        return colorRed;
    } else if (cgs.gameStage == PLAYING) {
        return colorYellow;
    }
    return NULL;
}

static dictEntry_t currencyToShaderIndex[] = {
    {"OAC", 0},
    {"BTC", 1}
};

static dictEntry_t horseToFlagShaderIndex[] = {
    {"red", 1},
    {"blue", 2}
};

static dictEntry_t currencyToBalanceY[] = {
    {"OAC", 210},
    {"BTC", 255}
};

static dictEntry_t currencyToBetSumY[] = {
    {"OAC", 80}
    // {"BTC", 125} Do not draw BTC here for now.
};

// Space between value and currency coin image.
#define VALUE_SPACE_LEN 15

static int GetValueLength(int amount) {
    int val_len = strlen(va("%d", amount)) * SMALLCHAR_WIDTH;
    int coin_len = CHAR_WIDTH;
    return val_len + VALUE_SPACE_LEN + coin_len;
}

static int GetMaxAmountLength(void) {
    int max_len = 0, len = 0, i = 0;
    for (i = 0; i < cgs.clientinfo[cg.clientNum].betsN; i++) {
        len = strlen(va("%d", cgs.clientinfo[cg.clientNum].activeBets[i].amount));
        if (len > max_len) {
            max_len = len;
        }
    }
    return max_len * SMALLCHAR_WIDTH;
}

static int BetSumXByHorse(const char* horse, int value) {
    // Dirty solution for now.
    // With more horses, diff positions will be needed.
    if (!strcmp(horse, "red")) {
        return 0;
    } else if (!strcmp(horse, "blue")) {
        return 640 - GetValueLength(value);
    } else {
        // No horse.
        return -1;
    }
}

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

/*
=================
CG_DrawValue
=================
 */
static void CG_DrawValue(int x, int y, int amount, int shift, const char* currency) {
    int shader_index;
    char* val_str = va("%d", amount);
    CG_DrawSmallString(x, y, val_str, 1.0F);
    if (shift == -1) {
        shift = strlen(val_str) * SMALLCHAR_WIDTH;
    }
    if (DictFind(currencyToShaderIndex, CURRENCIES_N, currency, &shader_index)) {
        qhandle_t currencyShader = cgs.media.currencyShader[shader_index];
        CG_DrawPic(x + shift + VALUE_SPACE_LEN, y - 10, CHAR_WIDTH, CHAR_WIDTH, currencyShader);
    }
}

/*
=================
CG_DrawBet
=================
 */
static void CG_DrawBet(int x, int y, int shift, activeBet_t bet) {
    int flag_shader_index;
    if (DictFind(horseToFlagShaderIndex, HORSES_N, bet.horse, &flag_shader_index)) {
        CG_DrawPic(x, y - 10, CHAR_WIDTH, CHAR_WIDTH, cgs.media.flagShader[flag_shader_index]);
        CG_DrawValue(x + CHAR_WIDTH + VALUE_SPACE_LEN, y, bet.amount, shift, bet.currency);
    }
}

/*
=================
CG_DrawGameStageInfo
=================
 */
static void CG_DrawGameStageInfo(void) {
    if (cgs.gameStage == FORMING_TEAMS) {
        CG_DrawBigString(320 - 7 * BIGCHAR_WIDTH, 50, "^2FORMING TEAMS", 1.0F);
        CG_DrawSmallString(320 - 24 * SMALLCHAR_WIDTH, 100, "Type ^2/help ^7to get help, ^2/ready ^7to start betting.", 1.0F);
    } else if (cgs.gameStage == MAKING_BETS) {
        CG_DrawPic(270, 0, 100, 100, cgs.media.lockShader);
        CG_DrawBigString(320 - 6 * BIGCHAR_WIDTH, 50, "^1MAKING BETS", 1.0F);
        CG_DrawSmallString(320 - 20 * SMALLCHAR_WIDTH, 100, "Press ^1ESC --> OATOT MENU ^7to make a bet.", 1.0F);
    } else if (cgs.gameStage == PLAYING) {
        CG_DrawPic(270, 0, 100, 100, cgs.media.lockShader);
        CG_DrawBigString(320 - 4 * BIGCHAR_WIDTH, 50, "^3PLAYING", 1.0F);
        CG_DrawSmallString(320 - 12 * SMALLCHAR_WIDTH, 100, "Type ^2/help ^7to get help.", 1.0F);
    }
}

/*
=================
CG_DrawOatotTimer
=================
 */
static void CG_DrawOatotTimer(void) {
    int msec, mins, seconds, tens;
    msec = cgs.levelStartTime + cgs.makingBetsTime * 60000 - cg.time + cgs.timeoutsDelay;
    seconds = msec / 1000;
    mins = seconds / 60;
    seconds -= mins * 60;
    tens = seconds / 10;
    seconds -= tens * 10;
    if (cgs.gameStage == MAKING_BETS) {
        CG_DrawSmallString(
            320 - 17 * SMALLCHAR_WIDTH,
            120,
            va("^3The match will be started in: ^1%i:%i%i", mins, tens, seconds),
            1.0F
        );
    }
}

/*
=================
CG_DrawBalanceBar
=================
 */
void CG_DrawBalanceBar(int left_side) {
    CG_DrawRect(left_side, 160, 640 - left_side, 125, 2, GetGameStageColor());
}

/*
=================
CG_DrawBalance
=================
 */
void CG_DrawBalance(void) {
    char* currency;
    int i, value, value_x, value_y, left_side, string_pos;
    int max_value = 0;
    int min_x = 640;
    for (i = 0; i < CURRENCIES_N; i++) {
        // Some data needed for drawing.
        value = cgs.clientinfo[cg.clientNum].balances[i].freeMoney;
        value_x = 640 - GetValueLength(value);
        currency = cgs.clientinfo[cg.clientNum].balances[i].currency;
        // Draw actual value for this currency.
        if (DictFind(currencyToBalanceY, CURRENCIES_N, currency, &value_y)) {
            CG_DrawValue(value_x, value_y, value, -1, currency);
        }
        // For Balance Bar and Balace string positions.
        if (value > max_value) {
            max_value = value;
        }
        if (value_x < min_x) {
            min_x = value_x;
        }
    }
    // Balance heading string position.
    string_pos = 640 - (GetValueLength(max_value) / 2) - 3 * SMALLCHAR_WIDTH;
    if ((string_pos + 7 * SMALLCHAR_WIDTH) > 640) {
        // Adjust if needed.
        string_pos = 640 - 8 * SMALLCHAR_WIDTH;
    }
    // The left side of the whole balance bar.
    left_side = string_pos - 5;
    if (min_x < left_side) {
        // Adjust if needed.
        left_side = min_x - 5;
    }
    // Draw balance bar and balance heading.
    CG_DrawBalanceBar(left_side);
    CG_DrawSmallStringColor(string_pos, 170, "^2Balance ", GetGameStageColor());
}

/*
=================
CG_DrawActiveBetsSumsHorses
=================
 */
static void CG_DrawActiveBetsSumsHorses(dictEntry_t* max_amounts) {
    // TODO: think what can be done with more than 2 horses.
    int red_amount, blue_amount, red_str_pos, blue_str_pos;
    DictFind(max_amounts, HORSES_N, "red", &red_amount);
    DictFind(max_amounts, HORSES_N, "blue", &blue_amount);
    red_str_pos = (GetValueLength(red_amount) / 2) - 3 * SMALLCHAR_WIDTH;
    blue_str_pos = 640 - (GetValueLength(blue_amount) / 2) - 3 * SMALLCHAR_WIDTH;
    if (red_str_pos < 0) {
        red_str_pos = 0;
    }
    if ((blue_str_pos + 7 * SMALLCHAR_WIDTH) > 640) {
        blue_str_pos = 640 - 7 * SMALLCHAR_WIDTH;
    }
    CG_DrawSmallString(blue_str_pos, 50, "^4On Blue", 1.0F);
    CG_DrawSmallString(red_str_pos, 50, "^1On Red", 1.0F);
}

/*
=================
CG_DrawActiveBetsSums
=================
 */
void CG_DrawActiveBetsSums(void) {
    int i, value, value_y, max_value_index;
    char* currency;
    char* horse;
    // Max amount for given horse.
    dictEntry_t max_amounts[HORSES_N];
    // Initialize max_amounts.
    for (i = 0; i < HORSES_N; i++) {
        max_amounts[i].value = 0;
        max_amounts[i].key = horseToFlagShaderIndex[i].key;
    }
    for (i = 0; i < CURRENCIES_N * HORSES_N; i++) {
        value = cgs.betSums[i].amount;
        currency = cgs.betSums[i].currency;
        horse = cgs.betSums[i].horse;
        // Max value for the given horse.
        max_value_index = DictFindIndex(max_amounts, HORSES_N, horse);
        if (max_value_index != -1) {
            if (value > max_amounts[max_value_index].value) {
                // Need to update max value for the given horse.
                max_amounts[max_value_index].value = value;
            }
        }
        // CURRENCIES_N - 1 because no BTC yet.
        if (DictFind(currencyToBetSumY, CURRENCIES_N - 1, currency, &value_y)) {
            // Draw value for current bet sum.
            CG_DrawValue(
                BetSumXByHorse(horse, value),
                value_y,
                value,
                -1,
                currency
            );
        }
    }
    CG_DrawActiveBetsSumsHorses(max_amounts);
}

/*
=================
CG_DrawActiveBets
=================
 */
void CG_DrawActiveBets(void) {
    int i = 0;
    int init_y = 190;
    int shift = GetMaxAmountLength();
    int max_len = 20 + shift + CHAR_WIDTH * 2 + VALUE_SPACE_LEN * 2;
    int bets_n = cgs.clientinfo[cg.clientNum].betsN;
    for (i = 0; i < bets_n; i++) {
        if (bets_n > 1) {
            CG_DrawRect(0, init_y + 40 * i - 15, max_len, 40, 2, GetGameStageColor());
        }
        CG_DrawSmallString(3, init_y + 40 * i, va("^2%d", i), 1.0F);
        CG_DrawBet(20, init_y + 40 * i, shift, cgs.clientinfo[cg.clientNum].activeBets[i]);
    }
}

/*
=================
CG_DrawResults
=================
 */
void CG_DrawResults(int prize, int balance_change) {
    // TODO: is only implemented for OAC.
    if (balance_change > 0) {
        if (prize > 0) {
            CG_CenterPrint(va("^6Congrats! You won ^3%d OAC^6!\n^2Score prize is ^3%d OAC^6.", balance_change, prize), SCREEN_HEIGHT * 0.50, BIGCHAR_WIDTH);
        } else {
            CG_CenterPrint(va("^6Congrats! You won ^3%d OAC^6!", balance_change), SCREEN_HEIGHT * 0.50, BIGCHAR_WIDTH);
        }
    } else {
        if (prize > 0) {
            CG_CenterPrint(va("^6Maybe next time...\n^2Score prize is ^3%d OAC^6.", prize), SCREEN_HEIGHT * 0.50, BIGCHAR_WIDTH);
        } else {
            CG_CenterPrint("^6Maybe next time...", SCREEN_HEIGHT * 0.50, BIGCHAR_WIDTH);
        }
    }
}

/*
=================
CG_DrawOatotStuff
=================
 */
void CG_DrawOatotStuff(void) {
    CG_DrawGameStageInfo();
    CG_DrawOatotTimer();
    CG_DrawBalance();
    CG_DrawActiveBetsSums();
    CG_DrawActiveBets();
}


text:
package gosquared

import "github.com/dghubble/sling"

type TransactionOpts struct {
	Revenue  int `json:"revenue,omitempty"`
	Quantity int `json:"quantity,omitempty"`
}

type TransactionItem struct {
	Name       string   `json:"name"`
	Categories []string `json:"categories"`
	Revenue    int      `json:"revenue,omitempty"`
	Price      int      `json:"price"`
	Quantity   int      `json:"quantity"`
}

type TransactionRequest struct {
	PersonID    string `json:"person_id,omitempty"`
	Transaction struct {
		ID    string            `json:"id"`
		Opts  *TransactionOpts  `json:"opts"`
		Items []TransactionItem `json:"items"`
	} `json:"transaction"`
}

type TransactionService struct {
	sling *sling.Sling
}

func NewTransactionServicee(sling *sling.Sling) *TransactionService {
	return &TransactionService{
		sling: sling.Path("transaction/"),
	}
}


text:
package com.hudson.donglingmusic.ui.recyclerview.ViewHolder;

import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hudson.donglingmusic.R;
import com.hudson.donglingmusic.bean.HotRecyclerViewItemMusic;
import com.hudson.donglingmusic.global.XUtilsManager;
import com.hudson.donglingmusic.ui.recyclerview.Adapter.HotItemRecyclerViewAdapter;
import com.hudson.donglingmusic.ui.view.RatioImageView;

/**
 * Created by Hudson on 2017/3/18.
 * 对应的布局文件是R.layout.item_recyclerview_hot
 */

public class HotNormalViewHolder extends BaseRecyclerViewHolder<HotRecyclerViewItemMusic> {
    private TextView mTitle;
    private TextView mMoreTextView;
    private RelativeLayout mSong1,mSong2,mSong3;
    private RatioImageView mSong1Bg,mSong2Bg,mSong3Bg;
    private TextView mSong1Singer,mSong2Singer,mSong3Singer;
    private TextView mSong1Title,mSong2Title,mSong3Title;

    public HotNormalViewHolder(View itemView, final HotItemRecyclerViewAdapter.OnItemClickListener listener) {
        super(itemView);
        mTitle = (TextView) itemView.findViewById(R.id.tv_title);
        mMoreTextView = (TextView) itemView.findViewById(R.id.tv_more);
        mMoreTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onItemClick(v,getLayoutPosition()-1);
                }
            }
        });
        itemView.findViewById(R.id.ll_hot_item_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onItemClick(v,getLayoutPosition()-1);
                }
            }
        });
        mSong1 = (RelativeLayout) itemView.findViewById(R.id.rl_song1);
        mSong1Bg = (RatioImageView) itemView.findViewById(R.id.iv_music_bg);
        mSong1Singer = (TextView) itemView.findViewById(R.id.tv_singer);
        mSong1Title = (TextView) itemView.findViewById(R.id.tv_song_title);

        mSong2 = (RelativeLayout) itemView.findViewById(R.id.rl_song2);
        mSong2Bg = (RatioImageView) itemView.findViewById(R.id.iv_music_bg2);
        mSong2Singer = (TextView) itemView.findViewById(R.id.tv_singer2);
        mSong2Title = (TextView) itemView.findViewById(R.id.tv_song_title2);

        mSong3 = (RelativeLayout) itemView.findViewById(R.id.rl_song3);
        mSong3Bg = (RatioImageView) itemView.findViewById(R.id.iv_music_bg3);
        mSong3Singer = (TextView) itemView.findViewById(R.id.tv_singer3);
        mSong3Title = (TextView) itemView.findViewById(R.id.tv_song_title3);
    }

    @Override
    public void refreshView(HotRecyclerViewItemMusic data) {
        mTitle.setText(data.title);
//        mSong1Bg
        mSong1Singer.setText(data.mSongInfos.get(0).singerName);
        mSong2Singer.setText(data.mSongInfos.get(1).singerName);
        mSong3Singer.setText(data.mSongInfos.get(2).singerName);
        XUtilsManager.getBitmapUtilsInstance().display(mSong1Bg,data.mSongInfos.get(0).bgUrl);
        XUtilsManager.getBitmapUtilsInstance().display(mSong2Bg,data.mSongInfos.get(1).bgUrl);
        XUtilsManager.getBitmapUtilsInstance().display(mSong3Bg,data.mSongInfos.get(2).bgUrl);
        mSong1Title.setText(data.mSongInfos.get(0).songTitle);
        mSong2Title.setText(data.mSongInfos.get(1).songTitle);
        mSong3Title.setText(data.mSongInfos.get(2).songTitle);

    }
}


text:
import { createSelector } from 'reselect'
import { connect } from 'react-redux'

import { noop, logout, inputChange, getUserList } from '../modules/userList'

/*  This is a container component. Notice it does not contain any JSX,
    nor does it import React. This component is **only** responsible for
    wiring in the actions and state necessary to render a presentational
    component - in this case, the formList:   */

import UserList from '../components/UserList'

/*  Object of action creators (can also be function that returns object).
    Keys will be passed as props to presentational components. Here we are
    implementing our wrapper around increment; the component doesn't care   */

const mapDispatchToProps = {
  noop,
  logout,
  inputChange,
  getUserList,
}

const api = (state) => state.api
const token = createSelector(api, (a) => a.getIn(['token','id']))
const user = createSelector(api, (a) => a.getIn(['token','user']))

const userList = (state) => state.userList
// const users = createSelector(formList, (t) => t.get('users'))
const users = createSelector(userList, (t) => {
  try {
    console.log('users', t.get('users').toArray())
    return t.get('users').sortBy((e) => e.get('email')).toArray()
  }
  catch (e) {
    return []
  }
})

const mapStateToProps = (state) => ({
  user: user(state),
  token: token(state),
  users: users(state),
})

/*  Note: mapStateToProps is where you should use `reselect` to create selectors, ie:

    import { createSelector } from 'reselect'
    const formList = (state) => state.formList
    const tripleCount = createSelector(formList, (count) => count * 3)
    const mapStateToProps = (state) => ({
      formList: tripleCount(state)
    })

    Selectors can compute derived data, allowing Redux to store the minimal possible state.
    Selectors are efficient. A selector is not recomputed unless one of its arguments change.
    Selectors are composable. They can be used as input to other selectors.
    https://github.com/reactjs/reselect    */

export default connect(mapStateToProps, mapDispatchToProps)(UserList)


text:
class FileInfo
  def initialize(values)
    @values = values
  end

  def id
    @values["_id"]
  end
  def name
    @values["name"]
  end
  def content_type
    @values["contentType"]
  end
  def uploader
    @values["uploader"]
  end
  def size
    @values["size"]
  end
  def created_at
    @values["createdAt"]
  end
end


text:
var orentationLocked = false;

function currentOrientation () {
	return window.screen.orientation || window.screen.mozOrientation || window.screen.msOrientation;
}

function orentationLock (orientation) {
	var lockOrientation = window.screen.lockOrientation || window.screen.mozLockOrientation || window.screen.msLockOrientation;
	if (orentationLocked) Promise.resolve();
	if (currentOrientation() === orientation) Promise.resolve();
	if (!lockOrientation && screen.orientation.lock) {
		return window.screen.orientation.lock(orientation);
	} else if (lockOrientation) {
		var res = screen.mozLockOrientation(orientation);
		return new Promise (function (resolve, reject) {
			setTimeout(function() {
				console.log(currentOrientation(), orientation);
				if (!res) return reject(orientation);
				if (currentOrientation() === orientation) resolve(orientation); else reject(orientation);
				orentationLocked = true;
			}, 0);
		});
	} else {
		return Promise.reject();
	}
}

module.exports = orentationLock;