text:
 <title>Release 14.12 ("Caterpillar", 2014/12/30)</title>

 <para>
  In addition to numerous new and upgraded packages, this release has the
  following highlights:
  <itemizedlist>
   <listitem>
    <para>
     Systemd has been updated to version 217, which has numerous
     <link xlink:href="http://lists.freedesktop.org/archives/systemd-devel/2014-October/024662.html">improvements.</link>
    </para>
   </listitem>
   <listitem>
    <para>
     <link xlink:href="https://www.mail-archive.com/nix-dev@lists.science.uu.nl/msg13957.html">
     Nix has been updated to 1.8.</link>
    </para>
   </listitem>
   <listitem>
    <para>
     NixOS is now based on Glibc 2.20.
    </para>
   </listitem>
   <listitem>
    <para>
     KDE has been updated to 4.14.
    </para>
   </listitem>
   <listitem>
    <para>
     The default Linux kernel has been updated to 3.14.
    </para>
   </listitem>
   <listitem>
    <para>
     If <option>users.mutableUsers</option> is enabled (the default), changes
     made to the declaration of a user or group will be correctly realised when
     running <command>nixos-rebuild</command>. For instance, removing a user
     specification from <filename>configuration.nix</filename> will cause the
     actual user account to be deleted. If <option>users.mutableUsers</option>
     is disabled, it is no longer necessary to specify UIDs or GIDs; if
     omitted, they are allocated dynamically.
    </para>
   </listitem>
  </itemizedlist>
 </para>

 <para>
  Following new services were added since the last release:
  <itemizedlist>
   <listitem>
    <para>
     <literal>atftpd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>bosun</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>bspwm</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>chronos</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>collectd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>consul</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>cpuminer-cryptonight</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>crashplan</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>dnscrypt-proxy</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>docker-registry</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>docker</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>etcd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>fail2ban</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>fcgiwrap</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>fleet</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>fluxbox</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>gdm</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>geoclue2</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>gitlab</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>gitolite</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>gnome3.gnome-documents</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>gnome3.gnome-online-miners</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>gnome3.gvfs</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>gnome3.seahorse</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>hbase</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>i2pd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>influxdb</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>kubernetes</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>liquidsoap</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>lxc</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>mailpile</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>mesos</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>mlmmj</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>monetdb</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>mopidy</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>neo4j</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>nsd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>openntpd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>opentsdb</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>openvswitch</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>parallels-guest</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>peerflix</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>phd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>polipo</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>prosody</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>radicale</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>redmine</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>riemann</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>scollector</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>seeks</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>siproxd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>strongswan</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>tcsd</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>teamspeak3</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>thermald</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>torque/mrom</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>torque/server</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>uhub</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>unifi</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>znc</literal>
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>zookeeper</literal>
    </para>
   </listitem>
  </itemizedlist>
 </para>

 <para>
  When upgrading from a previous release, please be aware of the following
  incompatible changes:
  <itemizedlist>
   <listitem>
    <para>
     The default version of Apache httpd is now 2.4. If you use the
     <option>extraConfig</option> option to pass literal Apache configuration
     text, you may need to update it — see
     <link
xlink:href="http://httpd.apache.org/docs/2.4/upgrading.html">Apache's
     documentation</link> for details. If you wish to continue to use httpd
     2.2, add the following line to your NixOS configuration:
<programlisting>
services.httpd.package = pkgs.apacheHttpd_2_2;
</programlisting>
    </para>
   </listitem>
   <listitem>
    <para>
     PHP 5.3 has been removed because it is no longer supported by the PHP
     project. A <link
xlink:href="http://php.net/migration54">migration
     guide</link> is available.
    </para>
   </listitem>
   <listitem>
    <para>
     The host side of a container virtual Ethernet pair is now called
     <literal>ve-<replaceable>container-name</replaceable></literal> rather
     than <literal>c-<replaceable>container-name</replaceable></literal>.
    </para>
   </listitem>
   <listitem>
    <para>
     GNOME 3.10 support has been dropped. The default GNOME version is now
     3.12.
    </para>
   </listitem>
   <listitem>
    <para>
     VirtualBox has been upgraded to 4.3.20 release. Users may be required to
     run <command>rm -rf /tmp/.vbox*</command>. The line <literal>imports = [
     <nixpkgs/nixos/modules/programs/virtualbox.nix> ]</literal> is no
     longer necessary, use <literal>services.virtualboxHost.enable =
     true</literal> instead.
    </para>
    <para>
     Also, hardening mode is now enabled by default, which means that unless
     you want to use USB support, you no longer need to be a member of the
     <literal>vboxusers</literal> group.
    </para>
   </listitem>
   <listitem>
    <para>
     Chromium has been updated to 39.0.2171.65.
     <option>enablePepperPDF</option> is now enabled by default.
     <literal>chromium*Wrapper</literal> packages no longer exist, because
     upstream removed NSAPI support. <literal>chromium-stable</literal> has
     been renamed to <literal>chromium</literal>.
    </para>
   </listitem>
   <listitem>
    <para>
     Python packaging documentation is now part of nixpkgs manual. To override
     the python packages available to a custom python you now use
     <literal>pkgs.pythonFull.buildEnv.override</literal> instead of
     <literal>pkgs.pythonFull.override</literal>.
    </para>
   </listitem>
   <listitem>
    <para>
     <literal>boot.resumeDevice = "8:6"</literal> is no longer supported. Most
     users will want to leave it undefined, which takes the swap partitions
     automatically. There is an evaluation assertion to ensure that the string
     starts with a slash.
    </para>
   </listitem>
   <listitem>
    <para>
     The system-wide default timezone for NixOS installations changed from
     <literal>CET</literal> to <literal>UTC</literal>. To choose a different
     timezone for your system, configure <literal>time.timeZone</literal> in
     <literal>configuration.nix</literal>. A fairly complete list of possible
     values for that setting is available at
     <link
xlink:href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones"/>.
    </para>
   </listitem>
   <listitem>
    <para>
     GNU screen has been updated to 4.2.1, which breaks the ability to connect
     to sessions created by older versions of screen.
    </para>
   </listitem>
   <listitem>
    <para>
     The Intel GPU driver was updated to the 3.x prerelease version (used by
     most distributions) and supports DRI3 now.
    </para>
   </listitem>
  </itemizedlist>
 </para>


text:
package scheduling

import (
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"k8s.io/api/core/v1"
	extensions "k8s.io/api/extensions/v1beta1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/uuid"
	utilyaml "k8s.io/apimachinery/pkg/util/yaml"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/test/e2e/framework"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const (
	testPodNamePrefix = "nvidia-gpu-"
	testCUDAImage     = "gcr.io/google_containers/cuda-vector-add:v0.1"
	cosOSImage        = "Container-Optimized OS from Google"
	// Nvidia driver installation can take upwards of 5 minutes.
	driverInstallTimeout = 10 * time.Minute
	// Nvidia COS driver installer daemonset.
	cosNvidiaDriverInstallerUrl = "https://raw.githubusercontent.com/ContainerEngine/accelerators/stable/cos-nvidia-gpu-installer/daemonset.yaml"
)

func makeCudaAdditionTestPod() *v1.Pod {
	podName := testPodNamePrefix + string(uuid.NewUUID())
	testPod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name: podName,
		},
		Spec: v1.PodSpec{
			RestartPolicy: v1.RestartPolicyNever,
			Containers: []v1.Container{
				{
					Name:  "vector-addition",
					Image: testCUDAImage,
					Resources: v1.ResourceRequirements{
						Limits: v1.ResourceList{
							v1.ResourceNvidiaGPU: *resource.NewQuantity(1, resource.DecimalSI),
						},
					},
					VolumeMounts: []v1.VolumeMount{
						{
							Name:      "nvidia-libraries",
							MountPath: "/usr/local/nvidia/lib64",
						},
					},
				},
			},
			Volumes: []v1.Volume{
				{
					Name: "nvidia-libraries",
					VolumeSource: v1.VolumeSource{
						HostPath: &v1.HostPathVolumeSource{
							Path: "/home/kubernetes/bin/nvidia/lib",
						},
					},
				},
			},
		},
	}
	return testPod
}

func isClusterRunningCOS(f *framework.Framework) bool {
	nodeList, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{})
	framework.ExpectNoError(err, "getting node list")
	for _, node := range nodeList.Items {
		if !strings.Contains(node.Status.NodeInfo.OSImage, cosOSImage) {
			return false
		}
	}
	return true
}

func areGPUsAvailableOnAllSchedulableNodes(f *framework.Framework) bool {
	framework.Logf("Getting list of Nodes from API server")
	nodeList, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{})
	framework.ExpectNoError(err, "getting node list")
	for _, node := range nodeList.Items {
		if node.Spec.Unschedulable {
			continue
		}
		if node.Status.Capacity.NvidiaGPU().Value() == 0 {
			framework.Logf("Nvidia GPUs not available on Node: %q", node.Name)
			return false
		}
	}
	framework.Logf("Nvidia GPUs exist on all schedulable nodes")
	return true
}

func getGPUsAvailable(f *framework.Framework) int64 {
	nodeList, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{})
	framework.ExpectNoError(err, "getting node list")
	var gpusAvailable int64
	for _, node := range nodeList.Items {
		gpusAvailable += node.Status.Capacity.NvidiaGPU().Value()
	}
	return gpusAvailable
}

func testNvidiaGPUsOnCOS(f *framework.Framework) {
	// Skip the test if the base image is not COS.
	// TODO: Add support for other base images.
	// CUDA apps require host mounts which is not portable across base images (yet).
	framework.Logf("Checking base image")
	if !isClusterRunningCOS(f) {
		Skip("Nvidia GPU tests are supproted only on Container Optimized OS image currently")
	}
	framework.Logf("Cluster is running on COS. Proceeding with test")
	// GPU drivers might have already been installed.
	if !areGPUsAvailableOnAllSchedulableNodes(f) {
		// Install Nvidia Drivers.
		ds := dsFromManifest(cosNvidiaDriverInstallerUrl)
		ds.Namespace = f.Namespace.Name
		_, err := f.ClientSet.Extensions().DaemonSets(f.Namespace.Name).Create(ds)
		framework.ExpectNoError(err, "failed to create daemonset")
		framework.Logf("Successfully created daemonset to install Nvidia drivers. Waiting for drivers to be installed and GPUs to be available in Node Capacity...")
		// Wait for Nvidia GPUs to be available on nodes
		Eventually(func() bool {
			return areGPUsAvailableOnAllSchedulableNodes(f)
		}, driverInstallTimeout, time.Second).Should(BeTrue())
	}
	framework.Logf("Creating as many pods as there are Nvidia GPUs and have the pods run a CUDA app")
	podList := []*v1.Pod{}
	for i := int64(0); i < getGPUsAvailable(f); i++ {
		podList = append(podList, f.PodClient().Create(makeCudaAdditionTestPod()))
	}
	framework.Logf("Wait for all test pods to succeed")
	// Wait for all pods to succeed
	for _, po := range podList {
		f.PodClient().WaitForSuccess(po.Name, 5*time.Minute)
	}
}

// dsFromManifest reads a .json/yaml file and returns the daemonset in it.
func dsFromManifest(url string) *extensions.DaemonSet {
	var controller extensions.DaemonSet
	framework.Logf("Parsing ds from %v", url)

	var response *http.Response
	var err error
	for i := 1; i <= 5; i++ {
		response, err = http.Get(url)
		if err == nil && response.StatusCode == 200 {
			break
		}
		time.Sleep(time.Duration(i) * time.Second)
	}
	Expect(err).NotTo(HaveOccurred())
	Expect(response.StatusCode).To(Equal(200))
	defer response.Body.Close()

	data, err := ioutil.ReadAll(response.Body)
	Expect(err).NotTo(HaveOccurred())

	json, err := utilyaml.ToJSON(data)
	Expect(err).NotTo(HaveOccurred())

	Expect(runtime.DecodeInto(api.Codecs.UniversalDecoder(), json, &controller)).NotTo(HaveOccurred())
	return &controller
}

var _ = SIGDescribe("[Feature:GPU]", func() {
	f := framework.NewDefaultFramework("gpus")
	It("run Nvidia GPU tests on Container Optimized OS only", func() {
		testNvidiaGPUsOnCOS(f)
	})
})

redpajama_set_name: RedPajamaGithub


text:
package hcl2shim

import (
	"github.com/zclconf/go-cty/cty"
)

// ValuesSDKEquivalent returns true if both of the given values seem equivalent
// as far as the legacy SDK diffing code would be concerned.
//
// Since SDK diffing is a fuzzy, inexact operation, this function is also
// fuzzy and inexact. It will err on the side of returning false if it
// encounters an ambiguous situation. Ambiguity is most common in the presence
// of sets because in practice it is impossible to exactly correlate
// nonequal-but-equivalent set elements because they have no identity separate
// from their value.
//
// This must be used _only_ for comparing values for equivalence within the
// SDK planning code. It is only meaningful to compare the "prior state"
// provided by Terraform Core with the "planned new state" produced by the
// legacy SDK code via shims. In particular it is not valid to use this
// function with their the config value or the "proposed new state" value
// because they contain only the subset of data that Terraform Core itself is
// able to determine.
func ValuesSDKEquivalent(a, b cty.Value) bool {
	if a == cty.NilVal || b == cty.NilVal {
		// We don't generally expect nils to appear, but we'll allow them
		// for robustness since the data structures produced by legacy SDK code
		// can sometimes be non-ideal.
		return a == b // equivalent if they are _both_ nil
	}
	if a.RawEquals(b) {
		// Easy case. We use RawEquals because we want two unknowns to be
		// considered equal here, whereas "Equals" would return unknown.
		return true
	}
	if !a.IsKnown() || !b.IsKnown() {
		// Two unknown values are equivalent regardless of type. A known is
		// never equivalent to an unknown.
		return a.IsKnown() == b.IsKnown()
	}
	if aZero, bZero := valuesSDKEquivalentIsNullOrZero(a), valuesSDKEquivalentIsNullOrZero(b); aZero || bZero {
		// Two null/zero values are equivalent regardless of type. A non-zero is
		// never equivalent to a zero.
		return aZero == bZero
	}

	// If we get down here then we are guaranteed that both a and b are known,
	// non-null values.

	aTy := a.Type()
	bTy := b.Type()
	switch {
	case aTy.IsSetType() && bTy.IsSetType():
		return valuesSDKEquivalentSets(a, b)
	case aTy.IsListType() && bTy.IsListType():
		return valuesSDKEquivalentSequences(a, b)
	case aTy.IsTupleType() && bTy.IsTupleType():
		return valuesSDKEquivalentSequences(a, b)
	case aTy.IsMapType() && bTy.IsMapType():
		return valuesSDKEquivalentMappings(a, b)
	case aTy.IsObjectType() && bTy.IsObjectType():
		return valuesSDKEquivalentMappings(a, b)
	case aTy == cty.Number && bTy == cty.Number:
		return valuesSDKEquivalentNumbers(a, b)
	default:
		// We've now covered all the interesting cases, so anything that falls
		// down here cannot be equivalent.
		return false
	}
}

// valuesSDKEquivalentIsNullOrZero returns true if the given value is either
// null or is the "zero value" (in the SDK/Go sense) for its type.
func valuesSDKEquivalentIsNullOrZero(v cty.Value) bool {
	if v == cty.NilVal {
		return true
	}

	ty := v.Type()
	switch {
	case !v.IsKnown():
		return false
	case v.IsNull():
		return true

	// After this point, v is always known and non-null
	case ty.IsListType() || ty.IsSetType() || ty.IsMapType() || ty.IsObjectType() || ty.IsTupleType():
		return v.LengthInt() == 0
	case ty == cty.String:
		return v.RawEquals(cty.StringVal(""))
	case ty == cty.Number:
		return v.RawEquals(cty.Zero)
	case ty == cty.Bool:
		return v.RawEquals(cty.False)
	default:
		// The above is exhaustive, but for robustness we'll consider anything
		// else to _not_ be zero unless it is null.
		return false
	}
}

// valuesSDKEquivalentSets returns true only if each of the elements in a can
// be correlated with at least one equivalent element in b and vice-versa.
// This is a fuzzy operation that prefers to signal non-equivalence if it cannot
// be certain that all elements are accounted for.
func valuesSDKEquivalentSets(a, b cty.Value) bool {
	if aLen, bLen := a.LengthInt(), b.LengthInt(); aLen != bLen {
		return false
	}

	// Our methodology here is a little tricky, to deal with the fact that
	// it's impossible to directly correlate two non-equal set elements because
	// they don't have identities separate from their values.
	// The approach is to count the number of equivalent elements each element
	// of a has in b and vice-versa, and then return true only if each element
	// in both sets has at least one equivalent.
	as := a.AsValueSlice()
	bs := b.AsValueSlice()
	aeqs := make([]bool, len(as))
	beqs := make([]bool, len(bs))
	for ai, av := range as {
		for bi, bv := range bs {
			if ValuesSDKEquivalent(av, bv) {
				aeqs[ai] = true
				beqs[bi] = true
			}
		}
	}

	for _, eq := range aeqs {
		if !eq {
			return false
		}
	}
	for _, eq := range beqs {
		if !eq {
			return false
		}
	}
	return true
}

// valuesSDKEquivalentSequences decides equivalence for two sequence values
// (lists or tuples).
func valuesSDKEquivalentSequences(a, b cty.Value) bool {
	as := a.AsValueSlice()
	bs := b.AsValueSlice()
	if len(as) != len(bs) {
		return false
	}

	for i := range as {
		if !ValuesSDKEquivalent(as[i], bs[i]) {
			return false
		}
	}
	return true
}

// valuesSDKEquivalentMappings decides equivalence for two mapping values
// (maps or objects).
func valuesSDKEquivalentMappings(a, b cty.Value) bool {
	as := a.AsValueMap()
	bs := b.AsValueMap()
	if len(as) != len(bs) {
		return false
	}

	for k, av := range as {
		bv, ok := bs[k]
		if !ok {
			return false
		}
		if !ValuesSDKEquivalent(av, bv) {
			return false
		}
	}
	return true
}

// valuesSDKEquivalentNumbers decides equivalence for two number values based
// on the fact that the SDK uses int and float64 representations while
// cty (and thus Terraform Core) uses big.Float, and so we expect to lose
// precision in the round-trip.
//
// This does _not_ attempt to allow for an epsilon difference that may be
// caused by accumulated innacuracy in a float calculation, under the
// expectation that providers generally do not actually do compuations on
// floats and instead just pass string representations of them on verbatim
// to remote APIs. A remote API _itself_ may introduce inaccuracy, but that's
// a problem for the provider itself to deal with, based on its knowledge of
// the remote system, e.g. using DiffSuppressFunc.
func valuesSDKEquivalentNumbers(a, b cty.Value) bool {
	if a.RawEquals(b) {
		return true // easy
	}

	af := a.AsBigFloat()
	bf := b.AsBigFloat()

	if af.IsInt() != bf.IsInt() {
		return false
	}
	if af.IsInt() && bf.IsInt() {
		return false // a.RawEquals(b) test above is good enough for integers
	}

	// The SDK supports only int and float64, so if it's not an integer
	// we know that only a float64-level of precision can possibly be
	// significant.
	af64, _ := af.Float64()
	bf64, _ := bf.Float64()
	return af64 == bf64
}


text:
/**
 * Created by Julian on 28.05.2017.
 */
const Command = require('../../structures/command');
const regs = {user: /<?(?:@|@!)([0-9]+)>/, channel: /<?(?:#)([0-9]+)>/, role: /<?(?:@&)([0-9]+)>/};
let argParser = require('../../structures/argumentParser');
const utils = require('../../structures/utilities');
const searcher = require('../../structures/searcher');
const winston = require('winston');
class AddPermission extends Command {
    constructor({t, mod}) {
        super();
        this.cmd = 'ap';
        this.cat = 'permission';
        this.needGuild = true;
        this.hidden = true;
        this.t = t;
        this.accessLevel = 0;
        this.p = mod.getMod('pm');
    }

    async run(msg) {
        let messageSplit = msg.content.split(' ').splice(1);
        if (messageSplit.length === 0) {
            return msg.channel.createMessage(this.t('ap.missing-args', {lngs: msg.lang, prefix: msg.prefix}));
        } else {
            let categories = utils.getCategoriesFromCommands(msg.cmds, true);
            let args = argParser.parse(messageSplit);
            try {
                let parsedArgs = this.parseArgs(args, categories, msg.cmds, msg.prefix);
                // console.log(parsedArgs);
                let target;
                if (parsedArgs.args.r) {
                    target = await this.resolveRole(parsedArgs, msg);
                } else if (parsedArgs.args.u) {
                    target = await this.resolveUser(parsedArgs, msg);
                } else if (parsedArgs.args.c) {
                    target = await this.resolveChannel(parsedArgs, msg)
                }
                if (!target) {
                    target = {type: 'guild', id: msg.channel.guild.id};
                }
                // console.log(target);
                let perm = this.p.createPermission(parsedArgs.permNode, target.type, target.id, parsedArgs.allow);
                try {
                    await this.p.addPermission(msg.channel.guild.id, perm);
                    let targetName = this.getNameForPermId(perm, msg);
                    return msg.channel.createMessage(this.t('ap.success', {
                        lngs: msg.lang,
                        node: `${perm.cat}.${perm.perm}`,
                        allowed: perm.use,
                        type: this.t(`ap.type.${perm.type}`, {lngs: msg.lang}),
                        name: targetName
                    }));
                } catch (e) {
                    if (e.message === 'add_defaults') {
                        let defaultPerms = this.p.getDefaultPerms();
                        let permString = defaultPerms.map(p => {
                            return `${p.cat}.${p.perm} (${p.use})`
                        }).join('\n');
                        let permQuestion = this.t('ap.add-defaults', {lngs: msg.lang, perm_list: permString});
                        permQuestion += '\n' + this.t('menu.yes-no-question', {lngs: msg.lang});
                        let menuMsg = await msg.channel.createMessage(permQuestion);
                        this.awaitDefaults(msg, perm, menuMsg);
                    } else {
                        winston.error(e);
                        return msg.channel.createMessage(this.t('generic.error', {lngs: msg.lang}));
                    }

                }
            } catch (e) {
                console.log(e);
                return msg.channel.createMessage(this.t(e.t, {lngs: msg.lang, node: e.node, prefix: msg.prefix}));
            }
        }
    }

    async awaitDefaults(msg, perm, menuMsg) {
        let collector = msg.CON.addCollector(msg.channel.id, {
            filter: (filterMsg) => {
                return filterMsg.author.id === msg.author.id;
            }
        });
        let stopTimeout = setTimeout(() => {
            collector.end();
            try {
                menuMsg.delete();
            } catch (e) {
                winston.error(e);
            }
        }, 1000 * 60 * 5); //5 mins
        collector.on('message', async (collMsg) => {
            collMsg.content = collMsg.content.trim();
            if (collMsg.content !== 'yes' && collMsg.content !== 'no') {
                if (collMsg.content.startsWith(msg.prefix) || collMsg.content === 'c') {
                    collector.end();
                    try {
                        menuMsg.delete();
                    } catch (e) {
                        winston.error(e);
                    }
                    clearTimeout(stopTimeout);
                    return msg.channel.createMessage(this.t('generic.cancelled-command', {lngs: msg.lang}));
                }
            } else {
                collector.end();
                try {
                    menuMsg.delete();
                } catch (e) {
                    winston.error(e);
                }
                let addDefaults = collMsg.content === 'yes';
                await this.p.addPermission(msg.channel.guild.id, perm, addDefaults);
                let tString = addDefaults ? 'ap.success-defaults' : 'ap.success';
                let targetName = this.getNameForPermId(perm, collMsg);
                return msg.channel.createMessage(this.t(tString, {
                    lngs: msg.lang,
                    node: `${perm.cat}.${perm.perm}`,
                    allowed: perm.use,
                    type: this.t(`ap.type.${perm.type}`, {lngs: msg.lang}),
                    name: targetName
                }))
            }
        });
    }

    getNameForPermId(perm, msg) {
        let targetName;
        switch (perm.type) {
            case 'guild':
                targetName = msg.channel.guild.name;
                break;
            case 'channel':
                targetName = msg.channel.guild.channels.find(c => c.id === perm.id).name;
                break;
            case 'role':
                targetName = msg.channel.guild.roles.find(r => r.id === perm.id).name;
                break;
            case 'user':
                let member = msg.channel.guild.members.find(m => m.id === perm.id);
                targetName = `${member.user.username}#${member.user.discriminator}` + (member.nick ? `(${member.nick})` : '');
                break;
        }
        return targetName;
    }

    async resolveRole(parsedArgs, msg) {
        let fullArgs = this.addOverleftArgs(parsedArgs.args.r, parsedArgs.args._);
        fullArgs = fullArgs.trim();
        if (regs.role.test(fullArgs)) {
            fullArgs = fullArgs.substring(3);
            return {type: 'role', id: fullArgs.substring(0, fullArgs.length - 1)};
        } else {
            let roles = utils.searchRoles(msg.channel.guild.roles, fullArgs);
            let pick = await searcher.roleSearchMenu(msg, [fullArgs], this.t);
            if (pick === -1) {
                throw new TranslatableError({
                    t: 'generic.cancelled-command',
                    message: 'User entered a wrong response to menu'
                })
            }
            if (pick === -2) {
                throw new TranslatableError({t: 'search.no-results', message: 'No matching roles could be found'})
            }
            if (pick > -1) {
                let targetRole = roles[pick];
                return {type: 'role', id: targetRole.id};
            }
        }
    }

    async resolveUser(parsedArgs, msg) {
        let fullArgs = this.addOverleftArgs(parsedArgs.args.u, parsedArgs.args._);
        fullArgs = fullArgs.trim();
        if (regs.user.test(fullArgs)) {
            if (fullArgs.startsWith('<@!')) {
                fullArgs = fullArgs.substring(3);
            } else {
                fullArgs = fullArgs.substring(2);
            }
            return {type: 'user', id: fullArgs.substring(0, fullArgs.length - 1)};
        } else {
            let users = utils.searchUser(msg.channel.guild.members, fullArgs);
            let pick = await searcher.userSearchMenu(msg, [fullArgs], this.t);
            if (pick === -1) {
                throw new TranslatableError({
                    t: 'generic.cancelled-command',
                    message: 'User entered a wrong response to menu'
                })
            }
            if (pick === -2) {
                throw new TranslatableError({t: 'search.no-results', message: 'No matching members could be found'})
            }
            if (pick > -1) {
                let targetUser = users[pick];
                return {type: 'user', id: targetUser.id};
            }
        }
    }

    async resolveChannel(parsedArgs, msg) {
        let fullArgs = this.addOverleftArgs(parsedArgs.args.c, parsedArgs.args._, true);
        fullArgs = fullArgs.trim();
        if (regs.user.test(fullArgs)) {
            fullArgs = fullArgs.substring(2);
            return {type: 'channel', id: fullArgs.substring(0, fullArgs.length - 1)};
        } else {
            let channels = utils.searchChannel(msg.channel.guild.channels, fullArgs);
            let pick = await searcher.channelSearchMenu(msg, [fullArgs], this.t);
            if (pick === -1) {
                throw new TranslatableError({
                    t: 'generic.cancelled-command',
                    message: 'User entered a wrong response to menu'
                })
            }
            if (pick === -2) {
                throw new TranslatableError({t: 'search.no-results', message: 'No matching channels could be found'})
            }
            if (pick > -1) {
                let targetRole = channels[pick];
                return {type: 'channel', id: targetRole.id};
            }
        }
    }

    addOverleftArgs(coreArgs, overlefts, dash = false) {
        let separator = dash ? '-' : ' ';
        if (overlefts.length > 0) {
            for (let i = 0; i < overlefts.length; i++) {
                coreArgs += separator + overlefts[i];
            }
        }
        return coreArgs;
    }

    parseArgs(args, categories, cmds, prefix) {
        console.log(args);
        if (args._.length > 0) {
            let parsedPermnode = this.parsePermNode(args, categories, cmds, prefix);
            let permNode = parsedPermnode.permNode;
            args = parsedPermnode.args;
            let parsedAllow = this.parseAllow(args);
            args = parsedAllow.args;
            let allow = parsedAllow.allow;
            return {
                permNode,
                allow,
                args
            }
        }
        throw new TranslatableError({
            t: 'ap.missing-args',
            message: 'not enough arguments were passed with the message'
        })
    }

    parseAllow(args) {
        let res = {allow: false, args};
        for (let i = 0; i < args._.length; i++) {
            let allow = args._[i];
            if (allow === 'true') {
                res.allow = true;
                res.args._.splice(i, 1);
                return res;
            }
            if (allow === 'false') {
                res.allow = false;
                res.args._.splice(i, 1);
                return res;
            }
        }
        throw new TranslatableError({
            t: 'ap.no-allowance-set',
            message: 'no false or true found in the args'
        })
    }

    parsePermNode(args, categories, cmds, prefix) {
        let res = {permNode: '', args};
        for (let i = 0; i < args._.length; i++) {
            let nodeSplit = args._[i].split(".");
            let permNode = "";
            let node = "";
            if (nodeSplit.length === 2) {
                if (typeof(categories[nodeSplit[0]]) !== 'undefined') {
                    if (typeof (cmds[nodeSplit[1]]) !== 'undefined') {
                        let cmd = cmds[nodeSplit[1]];
                        res.args._.splice(i, 1);
                        res.permNode = `${cmd.cat}.${cmd.cmd}`;
                        return res;
                    }
                    if (nodeSplit.join('.') === 'fun.cleverbot') {
                        res.args._.splice(i, 1);
                        res.permNode = `fun.cleverbot`;
                        return res;
                    }
                    if (nodeSplit[1] === '*') {
                        res.args._.splice(i, 1);
                        res.permNode = `${nodeSplit[0]}.*`;
                        return res;
                    }
                }
                if (typeof (cmds[nodeSplit[1]]) !== 'undefined') {
                    let cmd = cmds[nodeSplit[1]];
                    res.args._.splice(i, 1);
                    res.permNode = `${cmd.cat}.${cmd.cmd}`;
                    return res;
                }
                if (nodeSplit[0] === '*' && nodeSplit[1] === '*') {
                    res.args._.splice(i, 1);
                    res.permNode = "*.*";
                    return res;
                }
            } else {
                if (nodeSplit.length === 1) {
                    permNode = nodeSplit[0];
                    if (permNode === "*") {
                        res.args._.splice(i, 1);
                        res.permNode = "*.*";
                        return res;
                    }
                    if (permNode.startsWith(prefix)) {
                        let cmd = cmds[permNode.substring(prefix.length)];
                        if (typeof (cmd) === 'undefined') {
                            throw new TranslatableError({
                                t: 'ap.wrong-node',
                                message: 'Length of split of first argument did not equal 1 or 2'
                            });
                        }
                        res.args._.splice(i, 1);
                        res.permNode = `${cmd.cat}.${cmd.cmd}`;
                        return res;
                    }
                    if (typeof (cmds[permNode]) !== 'undefined') {
                        let cmd = cmds[permNode];
                        res.args._.splice(i, 1);
                        res.permNode = `${cmd.cat}.${cmd.cmd}`;
                        return res;
                    }
                }
            }
        }
        throw new TranslatableError({
            t: 'ap.wrong-node',
            message: 'Length of split of first argument did not equal 1 or 2',
            node: args._[0]
        });
    }
}
module.exports = AddPermission;


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class NOMXP extends StdCommand
{
	public NOMXP(){}

	private final String[] access=_i(new String[]{"NOMXP"});
	@Override public String[] getAccessWords(){return access;}
	@Override
	public boolean execute(MOB mob, Vector commands, int metaFlags)
		throws java.io.IOException
	{
		if(!mob.isMonster())
		{
			if((CMath.bset(mob.getBitmap(),MOB.ATT_MXP))
			||(mob.session().getClientTelnetMode(Session.TELNET_MXP)))
			{
				if(mob.session().getClientTelnetMode(Session.TELNET_MXP))
					mob.session().rawOut("\033[3z \033[7z");
				mob.setBitmap(CMath.unsetb(mob.getBitmap(),MOB.ATT_MXP));
				mob.session().changeTelnetMode(Session.TELNET_MXP,false);
				mob.session().setClientTelnetMode(Session.TELNET_MXP,false);
				mob.tell(_("MXP codes are disabled.\n\r"));
			}
			else
				mob.tell(_("MXP codes are already disabled.\n\r"));
		}
		return false;
	}

	@Override public boolean canBeOrdered(){return true;}
	@Override public boolean securityCheck(MOB mob){return super.securityCheck(mob)&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.MXP));}
}


text:
namespace base {

class SequencedTaskRunner;

namespace trace_event {

// Wraps a MemoryDumpProvider (MDP), which is registered via
// MemoryDumpManager(MDM)::RegisterDumpProvider(), holding the extra information
// required to deal with it (which task runner it should be invoked onto,
// whether it has been disabled, etc.)
// More importantly, having a refptr to this object guarantees that a MDP that
// is not thread-bound (hence which can only be unregistered via
// MDM::UnregisterAndDeleteDumpProviderSoon()) will stay alive as long as the
// refptr is held.
//
// Lifetime:
// At any time, there is at most one instance of this class for each instance
// of a given MemoryDumpProvider, but there might be several scoped_refptr
// holding onto each of this. Specifically:
// - In nominal conditions, there is a refptr for each registered MDP in the
//   MDM's |dump_providers_| list.
// - In most cases, the only refptr (in the |dump_providers_| list) is destroyed
//   by MDM::UnregisterDumpProvider().
// - However, when MDM starts a dump, the list of refptrs is copied into the
//   ProcessMemoryDumpAsyncState. That list is pruned as MDP(s) are invoked.
// - If UnregisterDumpProvider() is called on a non-thread-bound MDP while a
//   dump is in progress, the extar extra of the handle is destroyed in
//   MDM::SetupNextMemoryDump() or MDM::InvokeOnMemoryDump(), when the copy
//   inside ProcessMemoryDumpAsyncState is erase()-d.
// - The PeakDetector can keep extra refptrs when enabled.
struct BASE_EXPORT MemoryDumpProviderInfo
    : public RefCountedThreadSafe<MemoryDumpProviderInfo> {
 public:
  // Define a total order based on the |task_runner| affinity, so that MDPs
  // belonging to the same SequencedTaskRunner are adjacent in the set.
  struct Comparator {
    bool operator()(const scoped_refptr<MemoryDumpProviderInfo>& a,
                    const scoped_refptr<MemoryDumpProviderInfo>& b) const;
  };
  using OrderedSet =
      std::set<scoped_refptr<MemoryDumpProviderInfo>, Comparator>;

  MemoryDumpProviderInfo(MemoryDumpProvider* dump_provider,
                         const char* name,
                         scoped_refptr<SequencedTaskRunner> task_runner,
                         const MemoryDumpProvider::Options& options,
                         bool whitelisted_for_background_mode);

  // It is safe to access the const fields below from any thread as they are
  // never mutated.

  MemoryDumpProvider* const dump_provider;

  // The |options| arg passed to MDM::RegisterDumpProvider().
  const MemoryDumpProvider::Options options;

  // Human readable name, not unique (distinct MDP instances might have the same
  // name). Used for debugging, testing and whitelisting for BACKGROUND mode.
  const char* const name;

  // The task runner on which the MDP::OnMemoryDump call should be posted onto.
  // Can be nullptr, in which case the MDP will be invoked on a background
  // thread handled by MDM.
  const scoped_refptr<SequencedTaskRunner> task_runner;

  // True if the dump provider is whitelisted for background mode.
  const bool whitelisted_for_background_mode;

  // These fields below, instead, are not thread safe and can be mutated only:
  // - On the |task_runner|, when not null (i.e. for thread-bound MDPS).
  // - By the MDM's background thread (or in any other way that guarantees
  //   sequencing) for non-thread-bound MDPs.

  // Used to transfer ownership for UnregisterAndDeleteDumpProviderSoon().
  // nullptr in all other cases.
  std::unique_ptr<MemoryDumpProvider> owned_dump_provider;

  // For fail-safe logic (auto-disable failing MDPs).
  int consecutive_failures;

  // Flagged either by the auto-disable logic or during unregistration.
  bool disabled;

 private:
  friend class base::RefCountedThreadSafe<MemoryDumpProviderInfo>;
  ~MemoryDumpProviderInfo();

  DISALLOW_COPY_AND_ASSIGN(MemoryDumpProviderInfo);
};

}  // namespace trace_event
}  // namespace base

#endif  // BASE_TRACE_EVENT_MEMORY_DUMP_PROVIDER_INFO_H_


text:
<?php
namespace Cogitoweb\SystemMessagesBundle\Services;

use Doctrine\ORM\EntityManager;
use Cogitoweb\SystemMessagesBundle\Entity\SystemMessage;

/**
 * Description of SystemMessagesService
 *
 * @author Daniele Artico <daniele.artico@cogitoweb.it>
 */
class SystemMessagesService
{
	protected $em;

	/**
	 * Constructor
	 *
	 * @param EntityManager $em
	 */
	public function __construct(EntityManager $em) {
		$this->em = $em;
	}

	/**
	 * Write message into database
	 *
	 * @param string  $message
	 * @param integer $code
	 */
	public function write($message, $code = null)
	{
		$sm = new SystemMessage();

		$sm
			->setMessage($message)
			->setCode($code)
		;

		$this->em->persist($sm);
		$this->em->flush();
	}
}


text:
using Gedcomx.File;
using Gx.Agent;
using Gx.Common;
using Gx.Conclusion;
using Gx.Source;
using Gx.Types;
using NUnit.Framework;
using System;
using System.Xml.Serialization;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gedcomx.Rs.Api.Test.Examples
{
    [TestFixture(Category = "Examples")]
    public class WongAloiauExampleTest
    {
        private DefaultXmlSerialization xmlSerializer;
        private DefaultJsonSerialization jsonSerializer;

        [OneTimeSetUp]
        public void Initialize()
        {
            xmlSerializer = new DefaultXmlSerialization();
            jsonSerializer = new DefaultJsonSerialization();
        }

        [Test]
        public void TestExample()
        {
            //Jane Doe, the researcher.
            Agent janeDoe = (Agent)new Agent().SetName("Jane Doe").SetEmail("example@example.org").SetId("A-1");

            //Lin Yee Chung Cemetery
            Agent cemetery = (Agent)new Agent().SetName("Lin Yee Chung Cemetery").SetAddress(new Address().SetCity("Honolulu").SetStateOrProvince("Hawaii")).SetId("A-2");

            //Hanyu Pinyin, the translator.
            Agent hanyuPinyin = (Agent)new Agent().SetName("HANYU Pinyin 王大年").SetEmail("example@example.org").SetId("A-3");

            //The attribution for this research.
            Attribution researchAttribution = new Attribution().SetContributor(janeDoe).SetModified(DateTime.Parse("2014-03-27"));

            //The attribution for the translation.
            Attribution translationAttribution = new Attribution().SetContributor(hanyuPinyin).SetModified(DateTime.Parse("2014-03-27"));

            //The grave stone.
            SourceDescription gravestoneDescription = (SourceDescription)new SourceDescription()
              .SetTitle("Grave Marker of WONG Aloiau, Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii")
              .SetCitation(new SourceCitation().SetValue("WONG Aloiau gravestone, Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii; visited May 1975 by Jane Doe."))
              .SetResourceType(ResourceType.PhysicalArtifact)
              .SetRepository(cemetery)
              .SetId("S-1");

            //The image of the grave stone.
            SourceDescription gravestoneImageDescription = (SourceDescription)new SourceDescription()
              .SetTitle("Grave Marker of WONG Aloiau, Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii")
              .SetCitation(new SourceCitation().SetValue("WONG Aloiau gravestone (digital photograph), Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii; visited May 1975 by Jane Doe."))
              .SetResourceType(ResourceType.DigitalArtifact)
              .SetSource(new SourceReference().SetDescription(gravestoneDescription))
              .SetId("S-2");

            //The transcription of the grave stone.
            Document transcription = (Document)new Document()
              .SetText("WONG ALOIAU\n" +
                      "NOV. 22, 1848 – AUG. 3, 1920\n" +
                      "中山  大字都  泮沙鄉\n" +
                      "生  於  前  清 戊申 年 十一 月 廿二(日)子   時\n" +
                      "終  於  民國  庚申 年     七月    十二 (日)    午    時\n" +
                      "先考  諱 羅有  字 容康 王 府 君 之 墓")
              .SetSource(gravestoneImageDescription)
              .SetLang("zh")
              .SetId("D-1");

            //The transcription described as a source.
            SourceDescription transcriptionDescription = (SourceDescription)new SourceDescription()
              .SetAbout("#" + transcription.Id)
              .SetTitle("Transcription of Grave Marker of WONG Aloiau, Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii")
              .SetCitation(new SourceCitation().SetValue("WONG Aloiau gravestone (transcription), Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii; visited May 1975 by Jane Doe."))
              .SetResourceType(ResourceType.DigitalArtifact)
              .SetSource(new SourceReference().SetDescription(gravestoneImageDescription))
              .SetId("S-3");

            //The translation of the grave stone.
            Document translation = (Document)new Document()
              .SetText("WONG ALOIAU\n" +
                      "NOV. 22, 1848 – AUG. 3, 1920 [lunar dates]\n" +
                      "[Birthplace] [China, Guandong, ]Chung Shan, See Dai Doo, Pun Sha village\n" +
                      "[Date of birth] Born at former Qing 1848 year 11th month 22nd day 23-1 hour.\n" +
                      "[Life] ended at Republic of China year 1920 year 7th mo. 12th day 11-13 hour.\n" +
                      "Deceased father avoid [mention of] Lo Yau also known as Young Hong Wong [noble]residence ruler's grave.")
              .SetSource(transcriptionDescription)
              .SetId("D-2");

            //The translation described as a source.
            SourceDescription translationDescription = (SourceDescription)new SourceDescription()
              .SetAbout("#" + translation.Id)
              .SetTitle("Translation of Grave Marker of WONG Aloiau, Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii")
              .SetCitation(new SourceCitation().SetValue("WONG Aloiau gravestone, Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii; visited May 1975 by Jane Doe. Translation by HANYU Pinyin 王大年."))
              .SetAttribution(translationAttribution)
              .SetResourceType(ResourceType.DigitalArtifact)
              .SetSource(new SourceReference().SetDescription(transcriptionDescription))
              .SetId("S-4");

            //the birth.
            Fact birth = new Fact()
              .SetType(FactType.Birth)
              .SetDate(new DateInfo().SetOriginal("former Qing 1848 year 11th month 22nd day 23-1 hour").SetFormal("+1848-11-22"))
              .SetPlace(new PlaceReference().SetOriginal("Pun Sha Village, See Dai Doo, Chung Shan, Guangdong, China"));

            //the death.
            Fact death = new Fact()
              .SetType(FactType.Death)
              .SetDate(new DateInfo().SetOriginal("Republic of China year 1920 year 7th mo. 12th day 11-13 hour").SetFormal("+1920-08-03"));

            //the burial.
            Fact burial = new Fact()
              .SetType(FactType.Burial)
              .SetPlace(new PlaceReference().SetOriginal("Lin Yee Chung Cemetery, Honolulu, Oahu, Hawaii"));

            //the principal person
            Person aloiau = (Person)new Person().SetName("WONG Aloiau").SetGender(GenderType.Male).SetFact(birth).SetFact(death).SetFact(burial).SetExtracted(true).SetSource(translationDescription).SetId("P-1");

            //the father of the principal (with an aka name).
            Person father = (Person)new Person().SetName("Lo Yau").SetName(new Name().SetType(NameType.AlsoKnownAs).SetNameForm(new NameForm().SetFullText("Young Hong Wong"))).SetExtracted(true).SetSource(translationDescription).SetId("P-2");

            //the relationship.
            Relationship fatherRelationship = new Relationship().SetType(RelationshipType.ParentChild).SetPerson1(father).SetPerson2(aloiau);

            //Jane Doe's analysis.
            Document analysis = (Document)new Document().SetText("...Jane Doe's analysis document...").SetId("D-3");

            //Jane Doe's conclusions about a person.
            Person aloiauConclusion = (Person)new Person().SetEvidence(aloiau).SetAnalysis(analysis).SetId("C-1");

            Gx.Gedcomx gx = new Gx.Gedcomx()
              .SetAgent(janeDoe)
              .SetAgent(cemetery)
              .SetAgent(hanyuPinyin)
              .SetAttribution(researchAttribution)
              .SetSourceDescription(gravestoneDescription)
              .SetSourceDescription(gravestoneImageDescription)
              .SetDocument(transcription)
              .SetSourceDescription(transcriptionDescription)
              .SetDocument(translation)
              .SetSourceDescription(translationDescription)
              .SetPerson(aloiau)
              .SetPerson(father)
              .SetRelationship(fatherRelationship)
              .SetDocument(analysis)
              .SetPerson(aloiauConclusion);

            xmlSerializer.Deserialize<Gx.Gedcomx>(xmlSerializer.Serialize(gx));
            jsonSerializer.Deserialize<Gx.Gedcomx>(jsonSerializer.Serialize(gx));
        }
    }
}


text: export var __esModule = false;


text:
"""The Hierarchical File System (HFS) file-like object implementation."""

import os

from dfvfs.file_io import file_io
from dfvfs.resolver import resolver

class HFSFile(file_io.FileIO):
  """File input/output (IO) object using pyfshfs.file_entry"""

  def __init__(self, resolver_context, path_spec):
    """Initializes a file input/output (IO) object.

    Args:
      resolver_context (Context): resolver context.
      path_spec (PathSpec): a path specification.
    """
    super(HFSFile, self).__init__(resolver_context, path_spec)
    self._file_system = None
    self._fshfs_data_stream = None
    self._fshfs_file_entry = None

  def _Close(self):
    """Closes the file-like object."""
    self._fshfs_data_stream = None
    self._fshfs_file_entry = None

    self._file_system = None

  def _Open(self, mode='rb'):
    """Opens the file-like object defined by path specification.

    Args:
      mode (Optional[str]): file access mode.

    Raises:
      AccessError: if the access to open the file was denied.
      IOError: if the file-like object could not be opened.
      NotSupported: if a data stream, like the resource or named fork, is
          requested to be opened.
      OSError: if the file-like object could not be opened.
      PathSpecError: if the path specification is incorrect.
    """
    data_stream_name = getattr(self._path_spec, 'data_stream', None)

    self._file_system = resolver.Resolver.OpenFileSystem(
        self._path_spec, resolver_context=self._resolver_context)

    file_entry = self._file_system.GetFileEntryByPathSpec(self._path_spec)
    if not file_entry:
      raise IOError('Unable to open file entry.')

    fshfs_data_stream = None
    fshfs_file_entry = file_entry.GetHFSFileEntry()
    if not fshfs_file_entry:
      raise IOError('Unable to open HFS file entry.')

    if data_stream_name == 'rsrc':
      fshfs_data_stream = fshfs_file_entry.get_resource_fork()
    elif data_stream_name:
      raise IOError(f'Unable to open data stream: {data_stream_name:s}.')

    self._fshfs_data_stream = fshfs_data_stream
    self._fshfs_file_entry = fshfs_file_entry

  # Note: that the following functions do not follow the style guide
  # because they are part of the file-like object interface.
  # pylint: disable=invalid-name

  def read(self, size=None):
    """Reads a byte string from the file-like object at the current offset.

    The function will read a byte string of the specified size or
    all of the remaining data if no size was specified.

    Args:
      size (Optional[int]): number of bytes to read, where None is all
          remaining data.

    Returns:
      bytes: data read.

    Raises:
      IOError: if the read failed.
      OSError: if the read failed.
    """
    if not self._is_open:
      raise IOError('Not opened.')

    if self._fshfs_data_stream:
      return self._fshfs_data_stream.read(size=size)
    return self._fshfs_file_entry.read(size=size)

  def seek(self, offset, whence=os.SEEK_SET):
    """Seeks to an offset within the file-like object.

    Args:
      offset (int): offset to seek to.
      whence (Optional(int)): value that indicates whether offset is an absolute
          or relative position within the file.

    Raises:
      IOError: if the seek failed.
      OSError: if the seek failed.
    """
    if not self._is_open:
      raise IOError('Not opened.')

    if self._fshfs_data_stream:
      self._fshfs_data_stream.seek(offset, whence)
    else:
      self._fshfs_file_entry.seek(offset, whence)

  def get_offset(self):
    """Retrieves the current offset into the file-like object.

    Return:
      int: current offset into the file-like object.

    Raises:
      IOError: if the file-like object has not been opened.
      OSError: if the file-like object has not been opened.
    """
    if not self._is_open:
      raise IOError('Not opened.')

    if self._fshfs_data_stream:
      return self._fshfs_data_stream.get_offset()
    return self._fshfs_file_entry.get_offset()

  def get_size(self):
    """Retrieves the size of the file-like object.

    Returns:
      int: size of the file-like object data.

    Raises:
      IOError: if the file-like object has not been opened.
      OSError: if the file-like object has not been opened.
    """
    if not self._is_open:
      raise IOError('Not opened.')

    if self._fshfs_data_stream:
      return self._fshfs_data_stream.get_size()
    return self._fshfs_file_entry.get_size()


text:
	#foreach($identity in $identities)
		$r.escapeHtml($identity.name)$r.render($identity.removeLinkName)
	#end

	$r.render("choose.identity")


text:
'use strict';

const SYMBOL_BUILDER = Symbol();

class QueryBuilderUserContext {
  constructor(builder) {
    // This should never ever be accessed outside this class. We only
    // store it so that we can access builder.knex() lazily.
    this[SYMBOL_BUILDER] = builder;
  }

  get transaction() {
    return this[SYMBOL_BUILDER].knex();
  }

  newFromObject(builder, obj) {
    const ctx = new this.constructor(builder);
    Object.assign(ctx, obj);
    return ctx;
  }

  newMerge(builder, obj) {
    const ctx = new this.constructor(builder);
    Object.assign(ctx, this, obj);
    return ctx;
  }
}

module.exports = {
  QueryBuilderUserContext,
};


text:
{% load hq_shared_tags %}
{% load compress %}
{% load i18n %}
<!DOCTYPE html>

    <title>{% block title %}CommCareHQ Mobile{% endblock %}</title>

    {% compress css %}
    <link type="text/less" rel="stylesheet" media="all" href="{% static 'style/less/hqstyle-mobile-c2.less' %}"/>
    {% block stylesheets %}
    {% endblock %}
    {% endcompress %}

    <link rel="shortcut icon" href="{% static 'hqwebapp/img/favicon2.png' %}" />
{% block head %}{% endblock %}

    {% block content %}{% endblock %}
    {% block mobile-footer %}

        {% trans "CommCare HQ Mobile is Copyright" %} © {% now "Y" %} Dimagi, Inc.

        {% trans "Logout" %}

    {% endblock %}

{% block js %}{% endblock %}


text:
<!DOCTYPE html>

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


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Nettiers.AdventureWorks.Entities.Validation
{
   /// <summary>
   /// Delegate providing the signature of all methods that will process validation rules.
   /// </summary>
   /// <remarks>
   /// <para>
   /// The method handler should set the Description attribute of the
   /// <see cref="ValidationRuleArgs"/> parameter so that a meaningful
   /// error is returned.
   /// </para><para>
   /// If the data is valid, the method must return true.  If the data is invalid,
   /// the Description should be set the false should be returned.
   /// </para>
   /// </remarks>
   public delegate bool ValidationRuleHandler(object target, ValidationRuleArgs e);

}


text:
void content_screen(WINDOW *win, std::string txt);
void intro_splash(WINDOW *win, PlayerData p);
void win_splash(WINDOW *win);
void success_splash(WINDOW *win, const int count);

#endif


text:
//
//  UIImageView+CDAAsset.h
//  ContentfulSDK
//
//  Created by Boris Bügling on 13/03/14.
//
//

@import UIKit;

#import <ContentfulDeliveryAPI/CDAPersistedAsset.h>

@class CDAAsset;

/**
 Convenience category on `UIImageView` which allows asynchronously setting its image from a given
 Asset.

 Attempting non-sensical operations like using an Asset pointing to a video will throw exceptions.
 */
@interface UIImageView (CDAAsset)

/**
 *  Set this image view's image to the image file retrieved from the given Asset.
 *
 *  This will happen asynchronously in the background.
 *
 *  @param asset An Asset pointing to an image.
 *  @exception NSIllegalArgumentException If the Asset is pointing to an image.
 */
-(void)cda_setImageWithAsset:(CDAAsset* __nonnull)asset;

/**
 *  Set this image view's image to the image file retrieved from the given Asset.
 *
 *  This will happen asynchronously in the background.
 *
 *  @param asset An Asset pointing to an image.
 *  @param size             The desired size of the image. It will be resized by the server.
 *  @exception NSIllegalArgumentException If the Asset is pointing to an image.
 */
-(void)cda_setImageWithAsset:(CDAAsset* __nonnull)asset size:(CGSize)size;

/**
 *  Set this image view's image to the image file retrieved from the given Asset.
 *
 *  This will happen asynchronously in the background. Until the image is loaded,
 *  the `placeholderImage` is displayed.
 *
 *  @param asset            An Asset pointing to an image.
 *  @param placeholderImage An alternative image which will be displayed until `asset` is loaded.
 *  @exception NSIllegalArgumentException If the Asset is pointing to an image.
 */
-(void)cda_setImageWithAsset:(CDAAsset* __nonnull)asset
            placeholderImage:(UIImage* __nullable)placeholderImage;

/**
 *  Set this image view's image to the image file retrieved from the given Asset.
 *
 *  This will happen asynchronously in the background. Until the image is loaded,
 *  the `placeholderImage` is displayed.
 *
 *  @param asset            An Asset pointing to an image.
 *  @param size             The desired size of the image. It will be resized by the server.
 *  @param placeholderImage An alternative image which will be displayed until `asset` is loaded.
 *  @exception NSIllegalArgumentException If the Asset is pointing to an image.
 */
-(void)cda_setImageWithAsset:(CDAAsset* __nonnull)asset
                        size:(CGSize)size
            placeholderImage:(UIImage* __nullable)placeholderImage;

/**
 *  Set this image view's image to the image file retrieved from the given Asset.
 *
 *  This will happen asynchronously in the background. Until the image is loaded,
 *  the `placeholderImage` is displayed.
 *
 *  @param asset            An Asset pointing to an image.
 *  @param client           The client object to use for requests to Contentful.
 *  @param size             The desired size of the image. It will be resized by the server.
 *  @param placeholderImage An alternative image which will be displayed until `asset` is loaded.
 *  @exception NSIllegalArgumentException If the Asset is pointing to an image.
 */
-(void)cda_setImageWithPersistedAsset:(id<CDAPersistedAsset> __nonnull)asset
                               client:(CDAClient* __nonnull)client
                                 size:(CGSize)size
                     placeholderImage:(UIImage * __nullable)placeholderImage;

/** @name Use Offline Caching */

/** Enable automatic disk caching of any image loaded by one of the Asset category methods. */
@property (nonatomic) BOOL offlineCaching_cda;

@end


text:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import _ from 'lodash'
import { postData } from '../actions'
import DevicesTable from '../components/devices/devicesTable'

class Devices extends Component {
  render() {
    const { dispatch } = this.props
    return (

 Device List

            <button className="btn btn-primary-outline btn-sm" onClick={() => dispatch(postData('/devices/reset', {}))}>
              검  색
            </button>
            <button className="btn btn-primary-outline btn-sm" onClick={() => dispatch(postData('/devices/reload', {}))}>
              중복검색
            </button>

          <DevicesTable devices={this.props.devices} />

    )
  }
}

Devices.propTypes = {
  devices: PropTypes.object.isRequired,
  dispatch: PropTypes.func.isRequired
}

function mapStateToProps(state) {
  const { devices } = state
  return { devices }
}

export default connect(mapStateToProps)(Devices)


text:
<?php

namespace Mmoreram\ControllerExtraBundle\Resolver;

use Mmoreram\ControllerExtraBundle\ValueObject\FormRouteAttributes;
use ReflectionMethod;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormRegistryInterface;
use Symfony\Component\HttpFoundation\Request;

use Mmoreram\ControllerExtraBundle\Annotation\Abstracts\Annotation;
use Mmoreram\ControllerExtraBundle\Annotation\Form as AnnotationForm;
use Mmoreram\ControllerExtraBundle\Resolver\Abstracts\AbstractAnnotationResolver;
use Mmoreram\ControllerExtraBundle\Resolver\Interfaces\AnnotationResolverInterface;
use Symfony\Component\Routing\RouterInterface;

/**
 * FormAnnotationResolver, an implementation of  AnnotationResolverInterface
 */
class FormAnnotationResolver extends AbstractAnnotationResolver implements AnnotationResolverInterface
{
    /**
     * @var FormRegistryInterface
     *
     * FormRegistry
     */
    protected $formRegistry;

    /**
     * @var FormRegistryInterface
     *
     * FormRegistry
     */
    protected $formFactory;

    /**
     * @var RouterInterface
     *
     * Router
     */
    protected $router;

    /**
     * @var string
     *
     * Default field name
     */
    protected $defaultName;

    /**
     * @var FormRouteAttributes
     *
     * Route attributes
     */
    protected $routeAttributes;

    /**
     * Construct method
     *
     * @param FormRegistryInterface $formRegistry Form Registry
     * @param FormFactoryInterface  $formFactory  Form Factory
     * @param string                $defaultName  Default name
     */
    public function __construct(
        FormRegistryInterface $formRegistry,
        FormFactoryInterface $formFactory,
        $defaultName
    ) {
        $this->formRegistry = $formRegistry;
        $this->formFactory = $formFactory;
        $this->defaultName = $defaultName;
    }

    /**
     * Specific annotation evaluation.
     *
     * @param Request          $request    Request
     * @param Annotation       $annotation Annotation
     * @param ReflectionMethod $method     Method
     *
     * @return FormAnnotationResolver self Object
     */
    public function evaluateAnnotation(
        Request $request,
        Annotation $annotation,
        ReflectionMethod $method
    ) {
        /**
         * Annotation is only laoded if is typeof WorkAnnotation
         */
        if ($annotation instanceof AnnotationForm) {

            /**
             * Once loaded Annotation info, we just instanced Service name
             */
            $annotationValue = $annotation->getClass();

            /**
             * Get FormType object given a service name
             */
            $type = class_exists($annotationValue)
                ? new $annotationValue()
                : $this
                    ->formRegistry
                    ->getType($annotationValue)
                    ->getInnerType();

            /**
             * Get the parameter name. If not defined, is set as $form
             */
            $parameterName = $annotation->getName() ?: $this->defaultName;
            $parameterClass = $this->getParameterType(
                $method,
                $parameterName,
                'Symfony\\Component\\Form\\FormInterface'
            );

            $this->routeAttributes = new FormRouteAttributes();
            $this->routeAttributes
                ->setMethod($annotation->getMethod())
                ->setName($annotation->getRouteName())
                ->setParameters($annotation->getRouteParameters());

            /**
             * Requiring result with calling getBuiltObject(), set as request
             * attribute desired element
             */
            $request->attributes->set(
                $parameterName,
                $this->getBuiltObject(
                    $request,
                    $this->formFactory,
                    $annotation,
                    $parameterClass,
                    $type
                )
            );
        }

        return $this;
    }

    /**
     * Set router
     *
     * @param RouterInterface $router Router service
     *
     * @return FormAnnotationResolver
     */
    public function setRouter($router)
    {
        $this->router = $router;

        return $this;
    }

    /**
     * Built desired object.
     *
     * @param Request              $request        Request
     * @param FormFactoryInterface $formFactory    Form Factory
     * @param AnnotationForm       $annotation     Annotation
     * @param string               $parameterClass Class type of  method parameter
     * @param AbstractType         $type           Built Type object
     *
     * @return Mixed object to inject as a method parameter
     */
    protected function getBuiltObject(
        Request $request,
        FormFactoryInterface $formFactory,
        AnnotationForm $annotation,
        $parameterClass,
        AbstractType $type
    ) {
        /**
         * Checks if parameter typehinting is AbstractType
         * In this case, form type as defined method parameter
         */
        if ('Symfony\\Component\\Form\\AbstractType' == $parameterClass) {
            return $type;
        }

        $entity = $request->attributes->get($annotation->getEntity());

        /**
         * Creates form object from type
         */
        $form = $formFactory->create($type, $entity, $this->getFormOptions($request));

        /**
         * Handling request if needed
         */
        if ($annotation->getHandleRequest()) {
            $form->handleRequest($request);

            if ($annotation->getValidate()) {
                $request->attributes->set(
                    $annotation->getValidate(),
                    $form->isValid()
                );
            }
        }

        /**
         * Checks if parameter typehinting is Form
         * In this case, inject form as defined method parameter
         */
        if (in_array(
            $parameterClass, array(
                'Symfony\\Component\\Form\\Form',
                'Symfony\\Component\\Form\\FormInterface',
            )
        )) {
            return $form;
        }

        /**
         * Checks if parameter typehinting is FormView
         * In this case, inject form's view as defined method parameter
         */
        if ('Symfony\\Component\\Form\\FormView' == $parameterClass) {
            return $form->createView();
        }
    }

    /**
     * Built form builder options.
     *
     * @param Request             $request    Request
     *
     * @return array
     */
    protected function getFormOptions(Request $request) {
        $options = array();
        if (null !== $this->router && null !== $this->routeAttributes->getName()) {
            $routeParameters = array();
            foreach ($this->routeAttributes->getParameters() as $parameterName => $parameterValue) {
                if (is_array($parameterValue)) {
                    if (array_key_exists('entity', $parameterValue) && array_key_exists('method', $parameterValue)) {
                        $entity = $request->attributes->get($parameterValue['entity']);
                        $method = $parameterValue['method'];
                        if (is_callable(array($entity, $method))) {
                            $routeParameters[$parameterName] = $entity->$method();
                        }
                    }
                } else {
                    $routeParameters[$parameterName] = $parameterValue;
                }
            }
            $options['action'] = $this->router->generate($this->routeAttributes->getName(), $routeParameters);
        }
        $options['method'] = $this->routeAttributes->getMethod();

        return $options;
    }
}


text:
var $ = require('jquery');
var Backbone = require('backbone');
Backbone.Marionette = require('backbone.marionette');

module.exports = Backbone.Marionette.Controller.extend({

  getUrl: function(callback) {
    chrome.tabs.query({ currentWindow: true, active: true }, function(tabs) {
      callback(tabs[0].url);
    });
  },

  getHtml: function(callback) {
    chrome.tabs.query({ currentWindow: true, active: true }, function(tabs) {
      // Set the message responsder on the target page
      chrome.tabs.executeScript(tabs[0].id, { file: 'content.js' }, function() {

        // Wait for the response from the tab with the HTML
        chrome.tabs.sendMessage(tabs[0].id, { method: 'getText' }, function(response) {

          // Send the page source to getRecommendations
          if (response.method == 'getText') {
            callback(response.data);
          }

        });
      });
    });
  }
})


text:
'use strict';

var angularMeteorCollection = angular.module('angular-meteor.collection',
  ['angular-meteor.stopper', 'angular-meteor.subscribe', 'angular-meteor.utils', 'diffArray']);

// The reason angular meteor collection is a factory function and not something
// that inherit from array comes from here:
// http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/
// We went with the direct extensions approach.
angularMeteorCollection.factory('AngularMeteorCollection', [
  '$q', '$meteorSubscribe', '$meteorUtils', '$rootScope', '$timeout', 'diffArray',
  function($q, $meteorSubscribe, $meteorUtils, $rootScope, $timeout, diffArray) {
    function AngularMeteorCollection(curDefFunc, collection, diffArrayFunc, autoClientSave) {
      var data = [];
      // Server backup data to evaluate what changes come from client
      // after each server update.
      data._serverBackup = [];
      // Array differ function.
      data._diffArrayFunc = diffArrayFunc;
      // Handler of the cursor observer.
      data._hObserve = null;
      // On new cursor autorun handler
      // (autorun for reactive variables).
      data._hNewCurAutorun = null;
      // On new data autorun handler
      // (autorun for cursor.fetch).
      data._hDataAutorun = null;

      if (angular.isDefined(collection)) {
        data.$$collection = collection;
      } else {
        var cursor = curDefFunc();
        data.$$collection = $meteorUtils.getCollectionByName(cursor.collection.name);
      }

      _.extend(data, AngularMeteorCollection);
      data._startCurAutorun(curDefFunc, autoClientSave);

      return data;
    }

    AngularMeteorCollection._startCurAutorun = function(curDefFunc, autoClientSave) {
      var self = this;

      self._hNewCurAutorun = Tracker.autorun(function() {
        // When the reactive func gets recomputated we need to stop any previous
        // observeChanges.
        Tracker.onInvalidate(function() {
          self._stopCursor();
        });

        if (autoClientSave) self._setAutoClientSave();
        self._updateCursor(curDefFunc(), autoClientSave);
      });
    };

    AngularMeteorCollection.subscribe = function() {
      $meteorSubscribe.subscribe.apply(this, arguments);
      return this;
    };

    AngularMeteorCollection.save = function(docs, useUnsetModifier) {
      // save whole collection
      if (!docs) docs = this;
      // save single doc
      docs = [].concat(docs);

      var promises = docs.map(function(doc) {
        return this._upsertDoc(doc, useUnsetModifier);
      }, this);

      return $meteorUtils.promiseAll(promises);
    };

    AngularMeteorCollection._upsertDoc = function(doc, useUnsetModifier) {
      var deferred = $q.defer();
      var collection = this.$$collection;
      var createFulfill = _.partial($meteorUtils.fulfill, deferred, null);

      // delete $$hashkey
      doc = $meteorUtils.stripDollarPrefixedKeys(doc);
      var docId = doc._id;
      var isExist = collection.findOne(docId);

      // update
      if (isExist) {
        // Deletes _id property (from the copy) so that
        // it can be $set using update.
        delete doc._id;
        var modifier = useUnsetModifier ? {$unset: doc} : {$set: doc};
        // NOTE: do not use #upsert() method, since it does not exist in some collections
        collection.update(docId, modifier, createFulfill(function() {
          return {_id: docId, action: 'updated'};
        }));
      }
      // insert
      else {
        collection.insert(doc, createFulfill(function(id) {
          return {_id: id, action: 'inserted'};
        }));
      }

      return deferred.promise;
    };

    // performs $pull operations parallely.
    // used for handling splice operations returned from getUpdates() to prevent conflicts.
    // see issue: https://github.com/Urigo/angular-meteor/issues/793
    AngularMeteorCollection._updateDiff = function(selector, update, callback) {
      callback = callback || angular.noop;
      var setters = _.omit(update, '$pull');
      var updates = [setters];

      _.each(update.$pull, function(pull, prop) {
        var puller = {};
        puller[prop] = pull;
        updates.push({ $pull: puller });
      });

      this._updateParallel(selector, updates, callback);
    };

    // performs each update operation parallely
    AngularMeteorCollection._updateParallel = function(selector, updates, callback) {
      var self = this;
      var done = _.after(updates.length, callback);

      var next = function(err, affectedDocsNum) {
        if (err) return callback(err);
        done(null, affectedDocsNum);
      };

      _.each(updates, function(update) {
        self.$$collection.update(selector, update, next);
      });
    };

    AngularMeteorCollection.remove = function(keyOrDocs) {
      var keys;

      // remove whole collection
      if (!keyOrDocs) {
        keys = _.pluck(this, '_id');
      }
      // remove docs
      else {
        keyOrDocs = [].concat(keyOrDocs);

        keys = _.map(keyOrDocs, function(keyOrDoc) {
          return keyOrDoc._id || keyOrDoc;
        });
      }

      // Checks if all keys are correct.
      check(keys, [Match.OneOf(String, Mongo.ObjectID)]);

      var promises = keys.map(function(key) {
        return this._removeDoc(key);
      }, this);

      return $meteorUtils.promiseAll(promises);
    };

    AngularMeteorCollection._removeDoc = function(id) {
      var deferred = $q.defer();
      var collection = this.$$collection;
      var fulfill = $meteorUtils.fulfill(deferred, null, { _id: id, action: 'removed' });
      collection.remove(id, fulfill);
      return deferred.promise;
    };

    AngularMeteorCollection._updateCursor = function(cursor, autoClientSave) {
      var self = this;
      // XXX - consider adding an option for a non-orderd result for faster performance
      if (self._hObserve) self._stopObserving();

      self._hObserve = cursor.observe({
        addedAt: function(doc, atIndex) {
          self.splice(atIndex, 0, doc);
          self._serverBackup.splice(atIndex, 0, doc);
          self._setServerUpdateMode();
        },

        changedAt: function(doc, oldDoc, atIndex) {
          diffArray.deepCopyChanges(self[atIndex], doc);
          diffArray.deepCopyRemovals(self[atIndex], doc);
          self._serverBackup[atIndex] = self[atIndex];
          self._setServerUpdateMode();
        },

        movedTo: function(doc, fromIndex, toIndex) {
          self.splice(fromIndex, 1);
          self.splice(toIndex, 0, doc);
          self._serverBackup.splice(fromIndex, 1);
          self._serverBackup.splice(toIndex, 0, doc);
          self._setServerUpdateMode();
        },

        removedAt: function(oldDoc) {
          var removedIndex = $meteorUtils.findIndexById(self, oldDoc);

          if (removedIndex != -1) {
            self.splice(removedIndex, 1);
            self._serverBackup.splice(removedIndex, 1);
            self._setServerUpdateMode();
          } else {
            // If it's been removed on client then it's already not in collection
            // itself but still is in the _serverBackup.
            removedIndex = $meteorUtils.findIndexById(self._serverBackup, oldDoc);

            if (removedIndex != -1) {
              self._serverBackup.splice(removedIndex, 1);
            }
          }
        }
      });

      self._hDataAutorun = Tracker.autorun(function() {
        cursor.fetch();
        if (self._serverMode) self._unsetServerUpdateMode(autoClientSave);
      });
    };

    AngularMeteorCollection._stopObserving = function() {
      this._hObserve.stop();
      this._hDataAutorun.stop();
      delete this._serverMode;
      delete this._hUnsetTimeout;
    };

    AngularMeteorCollection._setServerUpdateMode = function(name) {
      this._serverMode = true;
      // To simplify server update logic, we don't follow
      // updates from the client at the same time.
      this._unsetAutoClientSave();
    };

    // Here we use $timeout to combine multiple updates that go
    // each one after another.
    AngularMeteorCollection._unsetServerUpdateMode = function(autoClientSave) {
      var self = this;

      if (self._hUnsetTimeout) {
        $timeout.cancel(self._hUnsetTimeout);
        self._hUnsetTimeout = null;
      }

      self._hUnsetTimeout = $timeout(function() {
        self._serverMode = false;
        // Finds updates that was potentially done from the client side
        // and saves them.
        var changes = diffArray.getChanges(self, self._serverBackup, self._diffArrayFunc);
        self._saveChanges(changes);
        // After, continues following client updates.
        if (autoClientSave) self._setAutoClientSave();
      }, 0);
    };

    AngularMeteorCollection.stop = function() {
      this._stopCursor();
      this._hNewCurAutorun.stop();
    };

    AngularMeteorCollection._stopCursor = function() {
      this._unsetAutoClientSave();

      if (this._hObserve) {
        this._hObserve.stop();
        this._hDataAutorun.stop();
      }

      this.splice(0);
      this._serverBackup.splice(0);
    };

    AngularMeteorCollection._unsetAutoClientSave = function(name) {
      if (this._hRegAutoBind) {
        this._hRegAutoBind();
        this._hRegAutoBind = null;
      }
    };

    AngularMeteorCollection._setAutoClientSave = function() {
      var self = this;

      // Always unsets auto save to keep only one $watch handler.
      self._unsetAutoClientSave();

      self._hRegAutoBind = $rootScope.$watch(function() {
        return self;
      }, function(nItems, oItems) {
        if (nItems === oItems) return;

        var changes = diffArray.getChanges(self, oItems, self._diffArrayFunc);
        self._unsetAutoClientSave();
        self._saveChanges(changes);
        self._setAutoClientSave();
      }, true);
    };

    AngularMeteorCollection._saveChanges = function(changes) {
      var self = this;

      // Saves added documents
      // Using reversed iteration to prevent indexes from changing during splice
      var addedDocs = changes.added.reverse().map(function(descriptor) {
        self.splice(descriptor.index, 1);
        return descriptor.item;
      });

      if (addedDocs.length) self.save(addedDocs);

      // Removes deleted documents
      var removedDocs = changes.removed.map(function(descriptor) {
        return descriptor.item;
      });

      if (removedDocs.length) self.remove(removedDocs);

      // Updates changed documents
      changes.changed.forEach(function(descriptor) {
        self._updateDiff(descriptor.selector, descriptor.modifier);
      });
    };

    return AngularMeteorCollection;
}]);

angularMeteorCollection.factory('$meteorCollectionFS', [
  '$meteorCollection', 'diffArray',
  function($meteorCollection, diffArray) {
    function $meteorCollectionFS(reactiveFunc, autoClientSave, collection) {
      return new $meteorCollection(reactiveFunc, autoClientSave, collection, diffArray.shallow);
    }

    return $meteorCollectionFS;
}]);

angularMeteorCollection.factory('$meteorCollection', [
  'AngularMeteorCollection', '$rootScope', 'diffArray',
  function(AngularMeteorCollection, $rootScope, diffArray) {
    function $meteorCollection(reactiveFunc, autoClientSave, collection, diffFn) {
      // Validate parameters
      if (!reactiveFunc) {
        throw new TypeError('The first argument of $meteorCollection is undefined.');
      }

      if (!(angular.isFunction(reactiveFunc) || angular.isFunction(reactiveFunc.find))) {
        throw new TypeError(
          'The first argument of $meteorCollection must be a function or\
            a have a find function property.');
      }

      if (!angular.isFunction(reactiveFunc)) {
        collection = angular.isDefined(collection) ? collection : reactiveFunc;
        reactiveFunc = _.bind(reactiveFunc.find, reactiveFunc);
      }

      // By default auto save - true.
      autoClientSave = angular.isDefined(autoClientSave) ? autoClientSave : true;
      diffFn = diffFn || diffArray;
      return new AngularMeteorCollection(reactiveFunc, collection, diffFn, autoClientSave);
    }

    return $meteorCollection;
}]);

angularMeteorCollection.run([
  '$rootScope', '$meteorCollection', '$meteorCollectionFS', '$meteorStopper',
  function($rootScope, $meteorCollection, $meteorCollectionFS, $meteorStopper) {
    var scopeProto = Object.getPrototypeOf($rootScope);
    scopeProto.$meteorCollection = $meteorStopper($meteorCollection);
    scopeProto.$meteorCollectionFS = $meteorStopper($meteorCollectionFS);
}]);


text:
import {FormControl, FormGroup} from '@angular/forms';
export class PasswordValidator{

    static passwordMatch(control: FormGroup){
        console.log(control);
        const newValue = control.root.root.get('newPassword') == null ? '' : control.root.root.get('newPassword').value;
              if (control.value != newValue){
                    return {
                      passwordMatch: true
                    };
                  }

                    return null;

    }
    static minimumLengthValidate(control: FormControl){
        console.log(control.value);

        if (control.value.length < 5){
            return {
                minimumLengthValidate: true,
                minLength: 5
            };
        }
    return null;
    }

}


text:
seguimos probando git

Fksjdksjd


text:
The Filo binary vector wire format is mostly based on FlatBuffer chunks, with some extra stuff around it.

## Header bytes

The first four bytes of any Filo chunk indicates the type of binary vector and structure following it.  This allows for future evolution.

| Offset | Type  | Description     |
|--------|-------|-----------------|
| +0     | u32   | Vector type     |

The valid values of the vector type:

| Value       | Vector Type    |  Description   |
|-------------|----------------|----------------|
| 0xnnnnnn01  | EmptyVector    | Every value in vector of length nnnnnn is NA |
| 0x00000002  | SimplePrimitiveVector | FlatBuffer Vector with fixed bit size per element |
| 0x00000102  | SimpleStringVector | FlatBuffer Vector with variable-size string elements |
| 0x00000103  | DictStringVector   | FlatBuffer Vector with dictionary-encoded strings |
| 0x00000004  | ConstPrimitiveVector  | A SimplePrimitiveVector for representing primitives holding the same value for entire vector
| 0x00000104  | ConstStringVector     | Same string vector for entire vector |
| 0x00000005  | DiffPrimitiveVector   | Stores base + deltas for primitives for more compact representation |
| 0x00000405  | DiffDateTimeVector   | Delta-encoded timestamp with TZ info for joda.time.DateTime |
| 0x00000006  | Primitive bitmap-mask vector | New-style BinaryVector with fixed bit size (primitives) per element and bitmask for NA |
| 0x00000206  | UTF8Vector | New-style BinaryVector with variable sized UTF8 strings or binary blobs |
| 0x00000306  | FixedMaxUTF8Vector | Actually a PrimitiveVector for UTF8/blob elements with a fixed max size and a size byte |
| 0x00000506  | PrimitiveAppendableVector | New-style BinaryVector with fixed bit size (primitives) per element and no NA mask |
| 0x00000207  | DictUTF8Vector  | New-style BinaryVector with dictionary-encoded UTF8/blobs |

See `WireFormat.scala` for code definitions.

## Data vector type

Many of the vectors consists of at least one fixed-size element arrays.  These data vectors are, for flexibility and compactness, not represented with the native FlatBuffer arrays, but rather with two elements:

* info - a struct with the following elements:
    * nbits - a u8 representing the number of bits per element
    * signed - a bool, true if the vector contains signed integers
* data - a u8 array with each element aligned to every nbits, stored in little endian order.
    - For example, if nbits was 4, and the array was [1, 2, 3, 4], then in file byte order, the bytes would be 0x21 0x43

The following types and standard nbits sizes should be supported by all Filo implementations:

| nbits |  Types supported   |
|-------|--------------------|
| 1     | bit vector         |
| 8     | byte / u8          |
| 16    | short int          |
| 32    | int, uint, IEEE Float |
| 64    | long, IEEE Double  |

## EmptyVector

Nothing follows the 4 header bytes since the length is already captured there.

## Simple*Vector

The FlatBuffers buffer for each type follows the header bytes.  See the *.fbs files for exact definition.

SimplePrimitiveVector contains a data vector as described above with nbits and signed struct, with a separate len field, while SimpleStringVector simply contains a [string].

Note that when implementing custom types, if the binary blobs are all fixed size, it is probably more efficient to use SimplePrimitiveVector - assuming the blobs are less than 256 bytes long each.

## FixedMaxUTF8Vector

`SimpleStringVector` is actually inefficient for strings less than about 16 chars long, or string columns where the strings are all the same size.  This is because a `[string]` vector has 8 bytes of overhead compared to a primitive fixed array: a string vector is an array of int offsets to a `[byte]` vector, which is itself a 4-byte length element plus the bytes.

`UTF8Vector` is much more space efficient than `SimpleStringVector` -- it stores 20 bits for offset and 11 bits for string length, and the strings are packed together and not word-aligned -- thus when strings fit into 1MB and are less than 2^11 bytes long, the overhead is just 4 bytes per string.  For fixed length strings though we can do better.

The `FixedMaxUTF8Vector` uses a `PrimitiveAppendableVector` for short strings and stores them inline in the data vector itself.  The first byte is a length field, followed by the UTF8 bytes.  `nbits` is set to `(longest string length + 1) * 8`.  Another benefit is better cache efficiency.

The actual equation for determining when simpleFixedString works well is this:

    (maxStringLen + 1) < (4 + 4 + avgStringLen)

## SimpleConstVector

This is really a SimplePrimitiveVector, in which the data vector contains one element only.  This vector logically represents this single element repeated *len* times.  The NA bitmask is still available.

## DictStringVector

Here, each unique string is given a number, or code, starting from 1.
There are two inner vectors within DictStringVector:

* codes - represents the UTF8 string for each dictionary code.  The code 0 is reserved for null or NA, and represented with the empty string, so the code vector looks like this: `["", "firstUnique", ...]`
* data - represents the code for each string in the vector

## Diff*Vector

Stores the base value as a separate single element vector, and all other elements as a vector of deltas from the base value.

DiffDateTimeVector is similar, storing the millis since Epoch as the data vector with a base value (since many timestamp vectors contains values relatively close together), with an optional TZ vector if the DateTimes differ in timezone.  Timezones are encoded as integer increments of 15 minute offsets from UTC (eg, UTC+1hr = 4).

## Double Encoding

If all the doubles are integers and within the int32 range, then an `IntBinaryVector` is used to take advantage of more compact integer encodings, including diff, delta-delta, and less bit width encodings.

## Future Formats

See the [Prometheus TSDB Video](https://promcon.io/2016-berlin/talks/the-prometheus-time-series-database/) for lots of ideas:

* Integer Delta-Delta encoding (use Prometheus's clever idea of a linear slope: delta for index i = i * deltadelta, where deltadelta is the initial delta between index 0 and 1.  This allows random access)
* Float/Double XOR Delta encoding - encode the XOR between initial value and subsequent values
* XOR + delta or delta delta?


text:
@implementation SupportScene

+ (id) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];

	// 'layer' is an autorelease object.
	SupportScene *layer = [SupportScene node];

	// add layer as a child to scene
	[scene addChild: layer];

	// return the scene
	return scene;
}

- (id) init
{
    self = [super init];
    if (self != nil)
	{
        CGSize winSize = [[CCDirector sharedDirector] winSize];

        menuButtonsPath = [SkinsManager menuButtonsPath];
		gameFieldPath = [SkinsManager gameFieldPath];
		menuPath = [SkinsManager menuPath];

        CCSprite *background = [CCSprite spriteWithFile:[NSString stringWithFormat:@"%@/%@",gameFieldPath ,@"background.png"]];
		[background setPosition:ccp(winSize.width/2, winSize.height/2)];
		[self addChild:background z:-1];

        CCSprite *about = [CCSprite spriteWithFile:@"About.png"];
        about.position = ccp(winSize.width/2, winSize.height/2);
        [self addChild:about z:2];

        CCMenuItem *nextItem = [CCMenuItemImage itemFromNormalImage:[NSString stringWithFormat:@"%@/%@", menuPath, @"arrow_r.png"]
										   selectedImage:[NSString stringWithFormat:@"%@/%@", menuPath, @"arrow_r2.png"]
										   disabledImage:[NSString stringWithFormat:@"%@/%@", menuPath, @"arrow_r3.png"]
												  target:self
												selector:@selector(next:)];
        [nextItem setIsEnabled:NO];
		nextItem.tag = 1;

		CCMenuItem *previousItem = [CCMenuItemImage itemFromNormalImage:[NSString stringWithFormat:@"%@/%@", menuPath, @"arrow_l.png"]
											   selectedImage:[NSString stringWithFormat:@"%@/%@", menuPath, @"arrow_l2.png"]
											   disabledImage:[NSString stringWithFormat:@"%@/%@", menuPath, @"arrow_l3.png"]
													  target:self
													selector:@selector(previous:)];
        [previousItem setIsEnabled:NO];
		previousItem.tag = 2;

		CCMenuItem *goBackItem = [CCMenuItemImage itemFromNormalImage:[NSString stringWithFormat:@"%@/%@", menuButtonsPath, @"menu.png"]
                                             selectedImage:[NSString stringWithFormat:@"%@/%@", menuButtonsPath, @"menu2.png"]
                                                    target:self
                                                  selector:@selector(goBack:)];
		goBackItem.tag = 3;

		CCMenu *arrowsMenu = [CCMenu menuWithItems:previousItem, goBackItem, nextItem, nil];
		[arrowsMenu alignItemsHorizontallyWithPadding:10];
		arrowsMenu.position = ccp(winSize.width/2, 40);
		[self addChild:arrowsMenu z:0];

    }
    return self;
}

- (void)next:(id)sender
{

}

- (void)previous:(id)sender
{

}

- (void)goBack:(id)sender
{
    [[CCDirector sharedDirector] popSceneWithTransition:[CCTransitionShrinkGrow class] duration:.5f];
}

- (void)dealloc
{
	[super dealloc];
}

@end


text:
background_mode :simultaneous

simultaneous_connection "/tmp/simultaneous.test_com.sock"

# ensures that schema classes are reloaded with every request
reload_classes true

# This provides you with login-less access to the CMS interface while in
# development mode. Change this value to automatically login as a different
# user or comment it out to reproduce the production environment.
# DO NOT set this value in production.
auto_login '__SPONTANEOUS_ROOT_USER_INSERT__'

host 'localhost'

# This sets the port that the editing interface runs under
back do
  port 2011
end

# This sets the port that the published/live version of the development
# site runs under.
front do
  port 2012
end


text:
require 'spec_helper'

describe Ticket do
  describe "validations" do
    it { should validate_presence_of :name }
    it { should validate_uniqueness_of :name }
    it { should validate_presence_of :client }
  end

  describe "associations" do
  end

  it "defaults archived to false" do
    expect(Ticket.new).to_not be_archived
  end
end


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

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="servletContext" class="org.springframework.mock.web.MockServletContext"/>
</beans>


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

namespace Sabre\Xml;

use
    Exception;

class ParseException extends Exception {

}


text:
extern crate rustc_serialize;
extern crate docopt;

mod deqnap;

use docopt::Docopt;
use std::path::Path;
use deqnap::walk_and_remove_extraneous_files;

const USAGE: &'static str = "
DEQNAPify your directory tree.

Usage:
    deqnap <path>
    deqnap (-h | --help)
    deqnap --version

Options:
    -h --help   Prints this message.
    --version   Prints version.
";

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_path: String,
}

fn main() {
    // Parse arguments
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.decode())
                            .unwrap_or_else(|e| e.exit());
    let path = Path::new(&args.arg_path);
    let mut count_removed = 0u64;
    match walk_and_remove_extraneous_files(path, &mut count_removed) {
        Err(err) => panic!("Unexpected error occurred: {}", err),
        Ok(()) => {
            if count_removed > 0 {
                println!("Finished. Removed {} extraneous files.", count_removed);
            } else {
                println!("No extraneous files found.");
            }
        }
    }
}


text:
WebJar of Angular Schema Form
=============================

WebJar of Textalk's [Angular Schema Form](https://github.com/Textalk/angular-schema-form) directives.