text:
import responses
import unittest

from . import utils
from contiamo.resources import Client
from contiamo.public import query
from contiamo.data import DataClient
from contiamo.utils import query_url_from_identifier, contract_url_template_from_identifier
from contiamo.errors import (
    APIConnectionError, APIError, AuthenticationError, DataSourceError, NotFoundError, QueryError, ResponseError,
    UpdateError)

# the only meaningful parameter is api_base, which should not resolve
api_base = 'http://xyz.wrong-domain-name.123'
resource_id = '456'
contiamo_client = Client('some_api_key', api_base=api_base)
project = contiamo_client.Project(id='123')
resource = project.Dashboard(resource_id)

# resources module

def mock_erroneous_request(method, response_body, status, payload=None):
    url = resource.class_url() if method == 'create' else resource.instance_url()
    verb = {'retrieve': responses.GET, 'create': responses.POST, 'modify': responses.PUT}.get(method)
    responses.add(verb, url, body=response_body, status=status, content_type='application/json')

    argument = payload if payload else resource_id
    request_method = getattr(resource, method)
    request_method(argument)

def mock_erroneous_retrieve(response_body, status):
    mock_erroneous_request('retrieve', response_body, status)

def mock_erroneous_create(response_body, status):
    mock_erroneous_request('create', response_body, status, payload={'name': 'ResourceName'})

def mock_erroneous_update(response_body, status):
    mock_erroneous_request('modify', response_body, status, payload={'name': 'AnotherName'})

# public module

def mock_erroneous_query(response_body, status):
    query_id = 'query:olap:48590200:21237:randomquerytoken'
    query_url, token = query_url_from_identifier(query_id, api_base)
    responses.add(responses.GET, query_url, body=response_body, status=status, content_type='application/json')
    query(query_id, api_base=api_base)

# data module

def mock_erroneous_upload(response_body, status):
    contract_id = 'contract:48590121:666570779:test'
    contract_url = contract_url_template_from_identifier(contract_id, api_base).format(action='upload/process')
    responses.add(responses.POST, contract_url, body=response_body, status=status, content_type='application/json')
    data_client = DataClient(contract_id, 'contract_token', api_base=api_base)
    data_client.upload(filename=utils.file_test_data('mock_data.csv'))

class ErrorTestCase(unittest.TestCase):

    def test_connection_error(self):
        with self.assertRaises(APIConnectionError):
            resource.retrieve(resource_id)

    @responses.activate
    def test_auth_error(self):
        with self.assertRaises(AuthenticationError):
            mock_erroneous_retrieve('{"error":"not_found","logged_in":false}', 404)
        with self.assertRaises(AuthenticationError):
            mock_erroneous_retrieve('{"error":"server_error","logged_in":false}', 500)

    @responses.activate
    def test_notfound_error(self):
        with self.assertRaises(NotFoundError):
            mock_erroneous_retrieve('{"error":"not_found","logged_in":true}', 404)

    @responses.activate
    def test_api_error(self):
        with self.assertRaises(APIError):
            mock_erroneous_retrieve('{}', 500)

    @responses.activate
    def test_create_error(self):
        with self.assertRaises(UpdateError):
            mock_erroneous_create('{}', 422)

    @responses.activate
    def test_update_error(self):
        with self.assertRaises(UpdateError):
            mock_erroneous_update('{}', 409)
        with self.assertRaises(UpdateError):
            mock_erroneous_update('{}', 422)

    @responses.activate
    def test_invalid_response(self):
        with self.assertRaises(ResponseError):
            mock_erroneous_retrieve('{"invalid":"json"', 200)
        with self.assertRaises(ResponseError):
            mock_erroneous_upload('{"invalid":"json"', 200)
        with self.assertRaises(ResponseError):
            mock_erroneous_query('{"invalid":"json"', 200)

    @responses.activate
    def test_data_source_error(self):
        with self.assertRaises(DataSourceError):
            mock_erroneous_upload('{}', 412)
        with self.assertRaises(DataSourceError):
            mock_erroneous_query('{}', 412)

    @responses.activate
    def test_query_error(self):
        with self.assertRaises(QueryError):
            mock_erroneous_query('{}', 410)
        with self.assertRaises(QueryError):
            mock_erroneous_query('{}', 424)

    @responses.activate
    def test_include_error(self):
        error_message = 'This is an error message.'
        with self.assertRaises(UpdateError) as cm:
            mock_erroneous_update('{"error": "%s"}' % error_message, 409)
        self.assertTrue(error_message in str(cm.exception))

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


text:
package io.hydrosphere.mist.master.logging

import java.nio.file.{Files, Paths}

import akka.actor.ActorSystem
import akka.pattern.ask
import akka.testkit.{TestActorRef, TestKit}
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import io.hydrosphere.mist.core.logging.LogEvent
import io.hydrosphere.mist.master.LogStoragePaths
import org.apache.commons.io.FileUtils
import org.scalatest.{BeforeAndAfterAll, FunSpecLike, Matchers}

import scala.concurrent.Await
import scala.concurrent.duration._

class LogWriterSpec extends TestKit(ActorSystem("log-writer-test", ConfigFactory.load("master")))
  with FunSpecLike
  with Matchers
  with BeforeAndAfterAll {

  val dirName = "log_writer_test"
  val dir = Paths.get(".", "target", dirName)

  override def beforeAll(): Unit = {
    Files.createDirectories(dir)
  }

  override def afterAll(): Unit = {
    FileUtils.deleteDirectory(dir.toFile)
    TestKit.shutdownActorSystem(system)
  }

  implicit val timeout = Timeout(5 second)

  describe("writer actor") {

    it("should write to file") {
      val path = dir.resolve("test")
      val f = path.toFile
      if (f.exists()) f.delete()
      Files.createFile(path)

      val actor = TestActorRef(WriterActor.props(path))

      val event = LogEvent.mkDebug("id", "message")
      val future = actor ? WriteRequest("id", Seq(event))
      val update = Await.result(future.mapTo[LogUpdate], Duration.Inf)

      update.jobId shouldBe "id"
      update.events shouldBe Seq(event)
      update.bytesOffset shouldBe (event.mkString + "\n").getBytes.length
    }
  }

  describe("writers group") {

    it("should proxy to writer") {
      val mappings = new LogStoragePaths(dir)
      val expectedPath = mappings.pathFor("id")
      if (Files.exists(expectedPath)) Files.delete(expectedPath)

      val actor = TestActorRef(WritersGroupActor.props(mappings))

      val event = LogEvent.mkDebug("id", "message")
      val future = actor ? WriteRequest("id", Seq(event))
      val update = Await.result(future.mapTo[LogUpdate], Duration.Inf)

      val expectedSize = (event.mkString + "\n").getBytes.length

      update.jobId shouldBe "id"
      update.events shouldBe Seq(event)
      update.bytesOffset shouldBe expectedSize

      Files.readAllBytes(expectedPath).length shouldBe expectedSize
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Zergatul.Cryptocurrency
{
    public interface ITransactionRepository<out T>
        where T : Base.TransactionBase
    {
        T GetTransaction(byte[] id);
        T GetTransaction(string id);
    }
}


text: This procedure creates a new JMS Activation Spec or updates an existing JMS Activation Spec.


text:
public class NaoPodeAlistarException extends Exception {
    public NaoPodeAlistarException() {
        super("Elfos do tipo normal não podem ser alistados!");
    }

    public NaoPodeAlistarException(String message) {
        super(message);
    }
}


text:
package com.dumu.housego.presenter;

public interface IGoudiListPresenter {
	void GoudiList(String userid);
	void GouDiDelete(String id,String userid);
}


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Introduction — Zend Framework 2 2.3.0dev documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="Zend Framework 2 2.3.0dev documentation" href="../index.html" />

Navigation

          index

Zend Framework 2 2.3.0dev documentation »

Introduction¶

<tt class="docutils literal">ZendQueue</tt> provides a factory function to create specific queue client objects.

A message queue is a method for distributed processing. For example, a Job Broker application may accept multiple
applications for jobs from a variety of sources.

You could create a queue “<tt class="docutils literal">/queue/applications</tt>” that would have a sender and a receiver. The sender would be any
available source that could connect to your message service or indirectly to an application (web) that could
connect to the message service.

The sender sends a message to the queue:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12

<resume>
    <name>John Smith</name>
    <location>
        <city>San Francisco</city>
        <state>California</state>
        <zip>00001</zip>
    </location>
    <skills>
        <programming>PHP</programming>
        <programming>Perl</programming>
    </skills>
</resume>

The recipient or consumer of the queue would pick up the message and process the resume.

There are many messaging patterns that can be applied to queues to abstract the flow of control from the code and
provide metrics, transformations, and monitoring of messages queues. A good book on messaging patterns is
Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions (Addison-Wesley Signature
Series) (ISBN-10 0321127420; ISBN-13 978-0321127426).

This Page

        Show Source

Edit Source

            Note: You need to stay logged into your GitHub account to contribute to the documentation.

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

Zend Framework 2 2.3.0dev documentation »

        © Copyright 2013, Zend Technologies Ltd..
      Created using Sphinx 1.2b3.

Edit this document

        The source code of this file is hosted on GitHub. Everyone can
        update and fix errors in this document with few clicks -
        no downloads needed.

            Login with your GitHub account.

            Go to

                Introduction
             on GitHub.

            Edit file contents using GitHub's text editor in your web browser

            Fill in the Commit message text box at the end of the page telling why
            you did the changes. Press Propose file change button next to it when done.

            On Send a pull request page you don't need to fill in text anymore. Just
            press Send pull request button.

            Your changes are now queued for review under project's Pull requests tab on GitHub.


text:
using System.Collections.Generic;
using Encog.ML.EA.Genome;
using Encog.ML.EA.Population;

namespace Encog.ML.EA.Species
{
    /// <summary>
    ///     Defines a species.
    /// </summary>
    public interface ISpecies
    {
        /// <summary>
        ///     The age of this species.
        /// </summary>
        int Age { get; set; }

        /// <summary>
        ///     The best score for this species.
        /// </summary>
        double BestScore { get; set; }

        /// <summary>
        ///     The number of generations with no imrpvement.
        /// </summary>
        int GensNoImprovement { get; set; }

        /// <summary>
        ///     The leader of this species.
        /// </summary>
        IGenome Leader { get; set; }

        /// <summary>
        ///     The members of this species.
        /// </summary>
        List<IGenome> Members { get; set; }

        /// <summary>
        ///     Get the offspring count.
        /// </summary>
        int OffspringCount { get; set; }

        /// <summary>
        ///     The offspring share for the next iteration's population.
        /// </summary>
        double OffspringShare { get; }

        /// <summary>
        ///     The population.
        /// </summary>
        IPopulation Population { get; set; }

        /// <summary>
        ///     Add a genome to this species.
        /// </summary>
        /// <param name="genome">The genome to add.</param>
        void Add(IGenome genome);

        /// <summary>
        ///     Calculate this genome's share of the next population.
        /// </summary>
        /// <param name="shouldMinimize">True if we see to minimize the score.</param>
        /// <param name="maxScore">The best score.</param>
        /// <returns>The share of this species, as a percent ratio.</returns>
        double CalculateShare(bool shouldMinimize, double maxScore);
    }
}


text:
There are different types of event interfaces. Some are of functional nature, some are purely for tagging purposes.
This file is just to describe the hierarchy between those events and what their benefits are. Also it gives a quick
overview about already implemented Events and what they should be used for.

##Event Interface Hierarchy
Indentation denotes inheritance.

* `EventLogEvent`: The base interface for all events
    * `ChangeEvent`: Events which indicate item attribute changes.
    * `CreateEvent`: Events which indicate item creations.
    * `ApplicationEvent`: Events which effect applications.
        * `ExperimentEvent`: Events which effect experiments.
            * `BucketEvent`: Events which effect buckets.

##Event Implementation Hierarchy
Indentation denotes inheritance.

* `AbstractEvent`: An event without a description which just handles the time and user.
    * `AbstractChangeEvent`: An event without a description which additionally handles property changes.
        * `BucketChangeEvent implements BucketEvent`: An event denoting bucket changes.
        * `ExperimentChangeEvent implements ExperimentEvent`: An event denoting experiment changes.
    * `BucketCreateEvent implements BucketEvent, CreateEvent`: An event denoting bucket creations.
    * `ExperimentCreateEvent implements ExperimentEvent, CreateEvent`: An event denoting experiment creations.
    * `SimpleEvent`: An arbitrary event. Allows for events with just a time, description and user.


text:
package mil.nga.giat.geowave.analytics.kmeans.mapreduce;

import java.io.IOException;
import java.util.List;

import mil.nga.giat.geowave.accumulo.mapreduce.GeoWaveWritableInputMapper;
import mil.nga.giat.geowave.accumulo.mapreduce.input.GeoWaveInputKey;
import mil.nga.giat.geowave.analytics.clustering.CentroidManagerGeoWave;
import mil.nga.giat.geowave.analytics.clustering.CentroidPairing;
import mil.nga.giat.geowave.analytics.clustering.NestedGroupCentroidAssignment;
import mil.nga.giat.geowave.analytics.extract.CentroidExtractor;
import mil.nga.giat.geowave.analytics.extract.SimpleFeatureCentroidExtractor;
import mil.nga.giat.geowave.analytics.kmeans.AssociationNotification;
import mil.nga.giat.geowave.analytics.parameters.CentroidParameters;
import mil.nga.giat.geowave.analytics.parameters.JumpParameters;
import mil.nga.giat.geowave.analytics.tools.AnalyticItemWrapper;
import mil.nga.giat.geowave.analytics.tools.AnalyticItemWrapperFactory;
import mil.nga.giat.geowave.analytics.tools.ConfigurationWrapper;
import mil.nga.giat.geowave.analytics.tools.SimpleFeatureItemWrapperFactory;
import mil.nga.giat.geowave.analytics.tools.mapreduce.CountofDoubleWritable;
import mil.nga.giat.geowave.analytics.tools.mapreduce.JobContextConfigurationWrapper;
import mil.nga.giat.geowave.index.StringUtils;

import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vividsolutions.jts.geom.Point;

/**
 * Calculate the distortation.
 *

 * See Catherine A. Sugar and Gareth M. James (2003).
 * "Finding the number of clusters in a data set: An information theoretic approach"
 * Journal of the American Statistical Association 98 (January): 750–763
 *
 * @formatter:off Context configuration parameters include:
 *

 *                "KMeansDistortionMapReduce.Common.DistanceFunctionClass" ->
 *                {@link mil.nga.giat.geowave.analytics.distance.DistanceFn}
 *                used to determine distance to centroid
 *

 *                "KMeansDistortionMapReduce.Centroid.WrapperFactoryClass" ->
 *                {@link AnalyticItemWrapperFactory} to extract wrap spatial
 *                objects with Centroid management functions
 *

 *                "KMeansDistortionMapReduce.Centroid.ExtractorClass" ->
 *                {@link mil.nga.giat.geowave.analytics.extract.CentroidExtractor}
 *

 *                "KMeansDistortionMapReduce.Jump.CountOfCentroids" -> May be
 *                different from actual.
 * @formatter:on
 * @see CentroidManagerGeoWave
 */
public class KMeansDistortionMapReduce
{

	protected static final Logger LOGGER = LoggerFactory.getLogger(KMeansDistortionMapReduce.class);

	public static class KMeansDistortionMapper extends
			GeoWaveWritableInputMapper<Text, CountofDoubleWritable>
	{

		private NestedGroupCentroidAssignment<Object> nestedGroupCentroidAssigner;
		private final Text outputKeyWritable = new Text(
				"1");
		private final CountofDoubleWritable outputValWritable = new CountofDoubleWritable();
		private CentroidExtractor<Object> centroidExtractor;
		private AnalyticItemWrapperFactory<Object> itemWrapperFactory;

		AssociationNotification<Object> centroidAssociationFn = new AssociationNotification<Object>() {
			@Override
			public void notify(
					final CentroidPairing<Object> pairing ) {
				outputKeyWritable.set(pairing.getCentroid().getGroupID());
				final double extraFromItem[] = pairing.getPairedItem().getDimensionValues();
				final double extraCentroid[] = pairing.getCentroid().getDimensionValues();
				final Point p = centroidExtractor.getCentroid(pairing.getPairedItem().getWrappedItem());

				final Point centroid = centroidExtractor.getCentroid(pairing.getCentroid().getWrappedItem());

				// calculate error for dp
				// using identity matrix for the common covariance, therefore
				// E[(p - c)^-1 * cov * (p - c)] => (px - cx)^2 + (py - cy)^2
				double expectation = 0.0;
				for (int i = 0; i < extraCentroid.length; i++) {
					expectation += Math.pow(
							extraFromItem[i] - extraCentroid[i],
							2);
				}
				expectation += (Math.pow(
						p.getCoordinate().x - centroid.getCoordinate().x,
						2) + Math.pow(
						p.getCoordinate().y - centroid.getCoordinate().y,
						2));
				// + Math.pow(
				// p.getCoordinate().z - centroid.getCoordinate().z,
				// 2));
				outputValWritable.set(
						expectation,
						1);
			}
		};

		@Override
		protected void mapNativeValue(
				final GeoWaveInputKey key,
				final Object value,
				final org.apache.hadoop.mapreduce.Mapper<GeoWaveInputKey, ObjectWritable, Text, CountofDoubleWritable>.Context context )
				throws IOException,
				InterruptedException {
			nestedGroupCentroidAssigner.findCentroidForLevel(
					itemWrapperFactory.create(value),
					centroidAssociationFn);
			context.write(
					outputKeyWritable,
					outputValWritable);
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void setup(
				final Mapper<GeoWaveInputKey, ObjectWritable, Text, CountofDoubleWritable>.Context context )
				throws IOException,
				InterruptedException {
			super.setup(context);
			final ConfigurationWrapper config = new JobContextConfigurationWrapper(
					context,
					KMeansDistortionMapReduce.LOGGER);

			try {
				nestedGroupCentroidAssigner = new NestedGroupCentroidAssignment<Object>(
						config);
			}
			catch (final Exception e1) {
				throw new IOException(
						e1);
			}

			try {
				centroidExtractor = config.getInstance(
						CentroidParameters.Centroid.EXTRACTOR_CLASS,
						KMeansDistortionMapReduce.class,
						CentroidExtractor.class,
						SimpleFeatureCentroidExtractor.class);
			}
			catch (final Exception e1) {
				throw new IOException(
						e1);
			}

			try {
				itemWrapperFactory = config.getInstance(
						CentroidParameters.Centroid.WRAPPER_FACTORY_CLASS,
						KMeansDistortionMapReduce.class,
						AnalyticItemWrapperFactory.class,
						SimpleFeatureItemWrapperFactory.class);
			}
			catch (final Exception e1) {
				throw new IOException(
						e1);
			}
		}
	}

	public static class KMeansDistorationCombiner extends
			Reducer<Text, CountofDoubleWritable, Text, CountofDoubleWritable>
	{
		final CountofDoubleWritable outputValue = new CountofDoubleWritable();

		@Override
		public void reduce(
				final Text key,
				final Iterable<CountofDoubleWritable> values,
				final Reducer<Text, CountofDoubleWritable, Text, CountofDoubleWritable>.Context context )
				throws IOException,
				InterruptedException {

			double expectation = 0;
			double ptCount = 0;
			for (final CountofDoubleWritable value : values) {
				expectation += value.getValue();
				ptCount += value.getCount();
			}
			outputValue.set(
					expectation,
					ptCount);
			context.write(
					key,
					outputValue);
		}
	}

	public static class KMeansDistortionReduce extends
			Reducer<Text, CountofDoubleWritable, Text, Mutation>
	{
		private String expectedK = null;
		final protected Text output = new Text(
				"");
		private CentroidManagerGeoWave<Object> centroidManager;

		@Override
		public void reduce(
				final Text key,
				final Iterable<CountofDoubleWritable> values,
				final Reducer<Text, CountofDoubleWritable, Text, Mutation>.Context context )
				throws IOException,
				InterruptedException {
			double expectation = 0.0;
			final List<AnalyticItemWrapper<Object>> centroids = centroidManager.getCentroidsForGroup(key.toString());
			// it is possible that the number of items in a group are smaller
			// than the cluster
			final String kCount = expectedK == null ? Integer.toString(centroids.size()) : expectedK;
			if (centroids.size() == 0) {
				return;
			}
			final double numDimesions = 2 + centroids.get(
					0).getExtraDimensions().length;

			double ptCount = 0;
			for (final CountofDoubleWritable value : values) {
				expectation += value.getValue();
				ptCount += value.getCount();
			}

			if (ptCount > 0) {
				expectation /= ptCount;

				final Double distortion = Math.pow(
						expectation / numDimesions,
						-(numDimesions / 2));

				// key: group ID | "DISTORTION" | K
				// value: distortion value
				final Mutation m = new Mutation(
						key.toString());
				m.put(
						new Text(
								"dt"),
						new Text(
								kCount),
						new Value(
								distortion.toString().getBytes(
										StringUtils.UTF8_CHAR_SET)));

				// write distortion to accumulo, defaults to table given to
				// AccumuloOutputFormat, in driver
				context.write(
						output, // default table
						m);
			}
		}

		@Override
		protected void setup(
				final Reducer<Text, CountofDoubleWritable, Text, Mutation>.Context context )
				throws IOException,
				InterruptedException {
			super.setup(context);
			final ConfigurationWrapper config = new JobContextConfigurationWrapper(
					context,
					KMeansDistortionMapReduce.LOGGER);

			final int k = config.getInt(
					JumpParameters.Jump.COUNT_OF_CENTROIDS,
					KMeansDistortionMapReduce.class,
					-1);
			if (k > 0) {
				expectedK = Integer.toString(k);
			}

			try {
				centroidManager = new CentroidManagerGeoWave<Object>(
						config);
			}
			catch (final Exception e) {
				KMeansDistortionMapReduce.LOGGER.warn(
						"Unable to initialize centroid manager",
						e);
				throw new IOException(
						"Unable to initialize centroid manager");
			}

		}
	}

}


text:
@interface PackageInfoMO : _PackageInfoMO {}

@property (weak, readonly) NSDictionary *dictValue;

@end


text:
/*
 * include/linux/memory.h - generic memory definition
 *
 * This is mainly for topological representation. We define the
 * basic "struct memory_block" here, which can be embedded in per-arch
 * definitions or NUMA information.
 *
 * Basic handling of the devices is done in drivers/base/memory.c
 * and system devices are handled in drivers/base/sys.c.
 *
 * Memory block are exported via sysfs in the class/memory/devices/
 * directory.
 *
 */
#ifndef _LINUX_MEMORY_H_
#define _LINUX_MEMORY_H_

#include <linux/sysdev.h>
#include <linux/node.h>
#include <linux/compiler.h>
#include <linux/mutex.h>

#define MIN_MEMORY_BLOCK_SIZE     (1UL << SECTION_SIZE_BITS)

struct memory_block {
	unsigned long start_section_nr;
	unsigned long end_section_nr;
	unsigned long state;
	int section_count;

	/*
	 * This serializes all state change requests.  It isn't
	 * held during creation because the control files are
	 * created long after the critical areas during
	 * initialization.
	 */
	struct mutex state_mutex;
	int phys_device;		/* to which fru does this belong? */
	void *hw;			/* optional pointer to fw/hw data */
	int (*phys_callback)(struct memory_block *);
	struct sys_device sysdev;
};

int arch_get_memory_phys_device(unsigned long start_pfn);

/* These states are exposed to userspace as text strings in sysfs */
#define	MEM_ONLINE		(1<<0) /* exposed to userspace */
#define	MEM_GOING_OFFLINE	(1<<1) /* exposed to userspace */
#define	MEM_OFFLINE		(1<<2) /* exposed to userspace */
#define	MEM_GOING_ONLINE	(1<<3)
#define	MEM_CANCEL_ONLINE	(1<<4)
#define	MEM_CANCEL_OFFLINE	(1<<5)

struct memory_notify {
	unsigned long start_pfn;
	unsigned long nr_pages;
	int status_change_nid;
};

/*
 * During pageblock isolation, count the number of pages within the
 * range [start_pfn, start_pfn + nr_pages) which are owned by code
 * in the notifier chain.
 */
#define MEM_ISOLATE_COUNT	(1<<0)

struct memory_isolate_notify {
	unsigned long start_pfn;	/* Start of range to check */
	unsigned int nr_pages;		/* # pages in range to check */
	unsigned int pages_found;	/* # pages owned found by callbacks */
};

struct notifier_block;
struct mem_section;

/*
 * Priorities for the hotplug memory callback routines (stored in decreasing
 * order in the callback chain)
 */
#define SLAB_CALLBACK_PRI       1
#define IPC_CALLBACK_PRI        10

#ifndef CONFIG_MEMORY_HOTPLUG_SPARSE
static inline int memory_dev_init(void)
{
	return 0;
}
static inline int register_memory_notifier(struct notifier_block *nb)
{
	return 0;
}
static inline void unregister_memory_notifier(struct notifier_block *nb)
{
}
static inline int memory_notify(unsigned long val, void *v)
{
	return 0;
}
static inline int register_memory_isolate_notifier(struct notifier_block *nb)
{
	return 0;
}
static inline void unregister_memory_isolate_notifier(struct notifier_block *nb)
{
}
static inline int memory_isolate_notify(unsigned long val, void *v)
{
	return 0;
}
#else
extern int register_memory_notifier(struct notifier_block *nb);
extern void unregister_memory_notifier(struct notifier_block *nb);
extern int register_memory_isolate_notifier(struct notifier_block *nb);
extern void unregister_memory_isolate_notifier(struct notifier_block *nb);
extern int register_new_memory(int, struct mem_section *);
extern int unregister_memory_section(struct mem_section *);
extern int memory_dev_init(void);
extern int remove_memory_block(unsigned long, struct mem_section *, int);
extern int memory_notify(unsigned long val, void *v);
extern int memory_isolate_notify(unsigned long val, void *v);
extern struct memory_block *find_memory_block_hinted(struct mem_section *,
							struct memory_block *);
extern struct memory_block *find_memory_block(struct mem_section *);
#define CONFIG_MEM_BLOCK_SIZE	(PAGES_PER_SECTION<<PAGE_SHIFT)
enum mem_add_context { BOOT, HOTPLUG };
#endif /* CONFIG_MEMORY_HOTPLUG_SPARSE */

#ifdef CONFIG_MEMORY_HOTPLUG
#define hotplug_memory_notifier(fn, pri) {			\
	static __meminitdata struct notifier_block fn##_mem_nb =\
		{ .notifier_call = fn, .priority = pri };	\
	register_memory_notifier(&fn##_mem_nb);			\
}
#else
#define hotplug_memory_notifier(fn, pri) do { } while (0)
#endif

/*
 * 'struct memory_accessor' is a generic interface to provide
 * in-kernel access to persistent memory such as i2c or SPI EEPROMs
 */
struct memory_accessor {
	ssize_t (*read)(struct memory_accessor *, char *buf, off_t offset,
			size_t count);
	ssize_t (*write)(struct memory_accessor *, const char *buf,
			 off_t offset, size_t count);
};

/*
 * Kernel text modification mutex, used for code patching. Users of this lock
 * can sleep.
 */
extern struct mutex text_mutex;

#endif /* _LINUX_MEMORY_H_ */


text:
import { InputWithOptionsUniDriver } from '../InputWithOptions/InputWithOptions.uni.driver';

export interface AutoCompleteUniDriver extends InputWithOptionsUniDriver {}


text:
package com.bt.pi.core.application.activation;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

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

import org.junit.Test;

public class RegionScopedApplicationRecordTest {
    RegionScopedApplicationRecord applicationRecord = new RegionScopedApplicationRecord();

    @Test
    public void shouldReturnValidUrl() {
        // setup
        applicationRecord.setApplicationName("anApp");

        // act
        String url = applicationRecord.getUrl();

        // assert
        assertEquals("regionapp:anApp", url);
    }

    @Test
    public void shouldReturnValidType() {
        // setup

        // act
        String type = applicationRecord.getType();

        // assert
        assertEquals(RegionScopedApplicationRecord.class.getSimpleName(), type);
    }

    @Test
    public void shouldConstructApplicationRecordWithApplicationName() {
        // act
        applicationRecord = new RegionScopedApplicationRecord("appName");

        // assert
        assertEquals("appName", applicationRecord.getApplicationName());
        assertEquals("regionapp:appName", applicationRecord.getUrl());
    }

    @Test
    public void shouldConstructApplicationRecordWithApplicationNameAndVersion() {
        // act
        applicationRecord = new RegionScopedApplicationRecord("anApp", 150);

        // assert
        assertEquals("anApp", applicationRecord.getApplicationName());
        assertEquals(150, applicationRecord.getVersion());
    }

    @Test
    public void shouldConstructApplicationRecordWithNumberOfRequiredActiveApps() {
        // act
        applicationRecord = new RegionScopedApplicationRecord("anApp", 100, 2);

        // assert
        assertEquals(2, applicationRecord.getRequiredActive());
    }

    @Test
    public void shouldConstructApplicationRecordWithListOfResources() {
        // setup
        List<String> resources = new ArrayList<String>();
        resources.add("res1");
        resources.add("res2");

        // act
        applicationRecord = new RegionScopedApplicationRecord("anApp", 101, resources);

        // assert
        assertEquals(2, applicationRecord.getRequiredActive());
        assertEquals(2, applicationRecord.getActiveNodeMap().size());
        assertTrue(applicationRecord.getActiveNodeMap().containsKey("res1"));
        assertTrue(applicationRecord.getActiveNodeMap().containsKey("res2"));
    }

    @Test
    public void shouldGetCorrectURIScheme() {
        // setup

        // act
        String uriScheme = applicationRecord.getUriScheme();

        // assert
        assertEquals("regionapp", uriScheme);
    }
}


text:
(function (ism) {
    "use strict";

    ism.wheel = function (element, onChange) {
        var wheel = {};
        // for w3c
        element.addEventListener("mousewheel", wheel, false);
        // for Firefox
        element.addEventListener("DOMMouseScroll", wheel, false);

        wheel.handleEvent = function (evt) {
            if (evt.type === "mousewheel" || evt.type === "DOMMouseScroll") {
                evt.preventDefault();
                var delta = 0;

                // Normalize the delta
                if (evt.wheelDelta) {
                    delta = evt.wheelDelta / 120;
                } else if (evt.detail) {
                    delta = -evt.detail / 3;
                }

                // Return delta and mouse position
                onChange(delta, {
                    "x": evt.pageX - element.getScreenCTM().e,
                    "y": evt.pageY - element.getScreenCTM().f
                });
            }
        };

        return wheel;
    };

    return ism;
}(ism));


text:
import { helper } from '@ember/component/helper';
import ISO6391 from 'iso-639-1';

export function formatLanguage([ language ]) {
  return ISO6391.getName(language);
}

export default helper(formatLanguage);


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2019-2022 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.client.editor.simple.components;

import org.pepstock.charba.client.data.ScatterDataset;

/**
 * Chart View for the Area Chart.
 *
 * <p>Responsible for the GUI of the Area Chart.
 */
public class MockAreaChartView extends MockLineChartViewBase<MockAreaChartView> {
  /**
   * Creates a new Mock Area Chart view instance.
   */
  public MockAreaChartView() {
    super();
  }

  @Override
  protected void initializeDefaultSettings() {
    super.initializeDefaultSettings();

    // Due to differing drawing orders of the Android and the
    // Mock Chart implementations, the Legend has to be reversed
    // in the Mock Area Chart and the Data Series have to be added
    // in reverse order as well to represent the Android data series
    // accurately.
    chartWidget.getOptions().getLegend().setReverse(true);
  }

  @Override
  public MockChartDataModel<ScatterDataset, MockAreaChartView> createDataModel() {
    return new MockAreaChartDataModel(this);
  }
}


text:
var app = require('./app_no_partials/app'),
    request = require('supertest');

describe('app', function () {
    describe('GET /helpers without partials', function () {
        it('should render html and show phone string', function (done) {
            request(app)
	      .get('/helpers')
	      .set('User-Agent', 'iPhone')
	      .expect(200)
	      .expect('<title>express-device</title>
phone
')
	      .end(done);
        });
    });

    describe('GET /helpers without partials', function () {
        it('should render html and show tablet string', function (done) {
            request(app)
	      .get('/helpers')
	      .set('User-Agent', 'iPad')
	      .expect(200)
	      .expect('<title>express-device</title>
tablet
')
	      .end(done);
        });
    });

    describe('GET /helpers without partials', function () {
        it('should render html and show tv string', function (done) {
            request(app)
	      .get('/helpers')
	      .set('User-Agent', 'GoogleTV')
	      .expect(200)
	      .expect('<title>express-device</title>
tv
')
	      .end(done);
        });
    });

    describe('GET /helpers without partials', function () {
        it('should render html and show bot string', function (done) {
            request(app)
	      .get('/helpers')
	      .set('User-Agent', 'Bot')
	      .expect(200)
	      .expect('<title>express-device</title>
bot
')
	      .end(done);
        });
    });

    describe('GET /helpers without partials', function () {
        it('should render html and show car string', function (done) {
            request(app)
	      .get('/helpers')
	      .set('User-Agent', 'QtCarBrowser')
	      .expect(200)
	      .expect('<title>express-device</title>
car
')
	      .end(done);
        });
    });

    describe('GET /helpers without partials', function () {
        it('should render html and show desktop string', function (done) {
            request(app)
	      .get('/helpers')
	      .set('User-Agent', 'Windows NT')
	      .expect(200)
	      .expect('<title>express-device</title>
desktop
')
	      .end(done);
        });
    });

    describe('GET /helpers without partials', function () {
        it('should render html and show phone string', function (done) {
            request(app)
	      .get('/helpers')
	      .expect(200)
	      .expect('<title>express-device</title>
phone
')
	      .end(done);
        });
    });
});


text:
package main

import (
	"errors"
)

type CommandHandler struct {
	cmdHandler map[string]func(args []string) error
}

func NewCommandHander() *CommandHandler {
	return &CommandHandler{
		cmdHandler: make(map[string](func(args []string) error)),
	}
}

func (ch *CommandHandler) SetHandler(cmd string, handler func(args []string) error) {
	ch.cmdHandler[cmd] = handler
}

func (ch *CommandHandler) GetHandler(cmd string) (func(args []string) error, error) {
	handler, exist := ch.cmdHandler[cmd]
	if !exist {
		return nil, errors.New("command not found: " + cmd)
	}
	return handler, nil
}


text:
<?php

/**
 *
 * @package BLW\DB
 * @version GIT: 0.2.0
 * @author  Walter Otsyula <wotsyula@mast3rpee.tk>
 */
namespace BLW\Model\DB;

use BLW\Model\InvalidArgumentException;
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\ResultSet\ResultSetInterface;
use Zend\Db\Adapter\Profiler\ProfilerInterface;
use Zend\Db\Adapter\Driver\Mysqli\Connection;
use Zend\Db\Adapter\Driver\Mysqli\Mysqli as Driver;

// @codeCoverageIgnoreStart
if (! defined('BLW')) {

    if (strstr($_SERVER['PHP_SELF'], basename(__FILE__))) {
        header("$_SERVER[SERVER_PROTOCOL] 404 Not Found");
        header('Status: 404 Not Found');

        $_SERVER['REDIRECT_STATUS'] = 404;

        echo "\r\n<title>404 Not Found</title>\r\n
404 Not Found
\r\n
\r\nnginx/1.5.9\r\n\r\n\r\n";
        exit();
    }

    return false;
}
// @codeCoverageIgnoreEnd

/**
 * Database that recieves a mysqli resource as its connection.
 *
 * @package BLW\DB
 * @api BLW
 * @since   1.0.0
 * @author  mAsT3RpEE <wotsyula@mast3rpee.tk>
 */
class MySQLi extends \Zend\Db\Adapter\Adapter implements \BLW\Type\DB\IDataBase
{
    /**
     * Constructor
     *
     * @throws \BLW\Model\InvalidArgumentException If an invalid argument is passed.
     *
     * @param resource $Connection
     *        PDO Object already connected to DB.
     * @param \Zend\Db\Adapter\Platform\PlatformInterface $platform
     *        [optional] Adaptor Platform (Mysql, Oracle, Postgre, Sqlite, etc).
     * @param \Zend\Db\ResultSet\ResultSetInterface $queryResultPrototype
     *        [optional] Result set class. NULL for default.
     * @param \Zend\Db\Adapter\Profiler\ProfilerInterface $profiler
     *        [optional] Adapter profiler.
     */
    public function __construct($Connection, PlatformInterface $platform = null, ResultSetInterface $queryResultPrototype = null, ProfilerInterface $profiler = null)
    {
        // Check connection
        if (! is_resource($Connection) ?: strpos(get_resource_type($Connection), 'mysql') === false) {
            // Exception
            throw new InvalidArgumentException(0, '%header% Argument 1 should be a myqli connection');

        } else {

            // Create driver
            $Driver = new Driver(new Connection($Connection));

            // Call parent
            try {
                parent::__construct($Driver, $platform, $queryResultPrototype, $profiler);

            // Invalid argument?
            } catch (\Zend\Db\Exception\InvalidArgumentException $e) {
                // Forward exception
                throw new InvalidArgumentException(-1, '%header% ' . $e->getMessage(), $e->getCode());
            }
        }
    }
}

// @codeCoverageIgnoreStart
return true;
// @codeCoverageIgnoreEnd


text:
Are you sure to delete this song(<?php echo $data["title"]; ?>)?

<form method="POST" action="">
	<input type="hidden" name="verfiy" value="1" >
	<input class="btn btn-success"  type="submit" value="OK">
	<a class="btn btn-danger" href="<?php echo site_url('playlist/playlist/index'); ?>">Cancel
</form>


text:
use strict;

use CGI;
use HTML::Template;
use JSON::XS;
use URI::Escape::JavaScript qw(unescape);
use File::Path;
use File::Copy qw(copy);
use File::Spec::Functions qw(catdir catfile);
use File::Touch;
use Sort::Versions;
use Data::Dumper;
use CoGeX;
use CoGe::Accessory::Web;
use CoGe::Accessory::TDS;
use CoGe::Accessory::Utils;
use CoGe::Core::Genome qw(genomecmp);
use CoGe::Core::Storage qw(get_workflow_paths get_upload_path);

no warnings 'redefine';

use vars qw(
  $CONF $PAGE_TITLE $TEMPDIR $USER $DB $FORM $LINK $EMBED
  %FUNCTION $LOAD_ID $WORKFLOW_ID
);

$PAGE_TITLE = 'LoadExp+';

$FORM = new CGI;
( $DB, $USER, $CONF, $LINK ) = CoGe::Accessory::Web->init(
    cgi => $FORM,
    page_title => $PAGE_TITLE
);

# Get workflow_id and load_id for previous load if specified.  Otherwise
# generate a new load_id for data upload.
$WORKFLOW_ID = $FORM->Vars->{'wid'} || $FORM->Vars->{'job_id'}; # wid is new name, job_id is legacy name
$LOAD_ID = ( defined $FORM->Vars->{'load_id'} ? $FORM->Vars->{'load_id'} : get_unique_id() );
$TEMPDIR = get_upload_path($USER->name, $LOAD_ID);

$EMBED = $FORM->param('embed');

%FUNCTION = (
    upload_file             => \&upload_file,
    get_sources             => \&get_sources,
    create_source           => \&create_source,
    send_error_report       => \&send_error_report
);

CoGe::Accessory::Web->dispatch( $FORM, \%FUNCTION, \&generate_html );

sub generate_html {
    # Check for finished result # mdb removed 3/4/15 no longer auto-redirect, make user select result
#    if ($LOAD_ID) {
#        my $log = get_load_log(workflow_id => $WORKFLOW_ID);
#        if ($log) {
#            my $res = decode_json($log);
#            if ($res->{experiment_id}) {
#                my $url = 'ExperimentView.pl?eid=' . $res->{experiment_id};
#                print $FORM->redirect(-url => $url);
#            }
#        }
#    }

    my $template;

    $EMBED = $FORM->param('embed');
    if ($EMBED) {
        $template = HTML::Template->new( filename => $CONF->{TMPLDIR} . 'embedded_page.tmpl' );
    }
    else {
        $template = HTML::Template->new( filename => $CONF->{TMPLDIR} . 'generic_page.tmpl' );
        $template->param( PAGE_TITLE => $PAGE_TITLE,
		                  TITLE      => "LoadExp+",
        	              PAGE_LINK  => $LINK,
			              HOME       => $CONF->{SERVER},
                          HELP       => 'LoadExp+',
                          WIKI_URL   => $CONF->{WIKI_URL} || '',
                          ADMIN_ONLY => $USER->is_admin,
                          USER       => $USER->display_name || '',
                          CAS_URL    => $CONF->{CAS_URL} || '',
                          COOKIE_NAME => $CONF->{COOKIE_NAME} || ''
        );
        $template->param( LOGON      => 1 ) unless $USER->is_public;
    }

    $template->param( BODY => generate_body() );
    return $template->output;
}

sub generate_body {
    my $template = HTML::Template->new( filename => $CONF->{TMPLDIR} . 'LoadExperiment.tmpl' );
    $template->param( PAGE_NAME => "LoadExperiment.pl" );

    # Force login
    if ( $USER->is_public ) {
        $template->param( LOGIN => 1 );
        return $template->output;
    }

    # Set genome ID if specified
    my $gid = $FORM->param('gid');
    if ($gid) {
        my $genome = $DB->resultset('Genome')->find($gid);
        if ($genome && $USER->has_access_to_genome($genome)) { # check permission
            $template->param(
                GENOME_NAME => $genome->info,
                GENOME_ID   => $genome->id
            );
        }
    }

    $template->param(
        MAIN          => 1,
        PAGE_TITLE    => $PAGE_TITLE,
        EMBED         => $EMBED,
    	LOAD_ID       => $LOAD_ID,
    	WORKFLOW_ID   => $WORKFLOW_ID,
        API_BASE_URL  => $CONF->{SERVER} . 'api/v1/', #TODO move into config file or module
        HELP_URL      => 'https://genomevolution.org/wiki/index.php/LoadExp+',
        SUPPORT_EMAIL => $CONF->{SUPPORT_EMAIL},
        DEFAULT_TAB              => 0,
        ENABLE_SRA               => 1,
        MAX_IRODS_LIST_FILES     => 1000,
        MAX_IRODS_TRANSFER_FILES => 30,
        MAX_FTP_FILES            => 30,
        USER                     => $USER->user_name,
        IS_POWERUSER             => $USER->is_poweruser,
        CUTADAPT_VERSION         => $CONF->{CUTADAPT_VERSION}
    );
    $template->param( SPLASH_COOKIE_NAME => $PAGE_TITLE . '_splash_disabled',
                      SPLASH_CONTENTS    => 'This page allows you to load quantitative, polymorphism, or alignment data onto a genome from a variety of file formats.' );
    $template->param( ADMIN_AREA => 1 ) if $USER->is_admin;

    return $template->output;
}

sub upload_file {
    my %opts      = @_;
    my $filename  = '' . $FORM->param('input_upload_file');
    my $fh        = $FORM->upload('input_upload_file');

    #	print STDERR "upload_file: $filename\n";

    my $size = 0;
    my $path;
    if ($fh) {
        my $tmpfilename = $FORM->tmpFileName( $filename );
        $path = catfile('upload', $filename);
        my $targetpath = catdir($TEMPDIR, 'upload');
        mkpath($targetpath);
        $targetpath = catfile($targetpath, $filename);

        #print STDERR "temp files: $tmpfilename $targetpath\n";
        copy( $tmpfilename, $targetpath );
        touch($targetpath . '.done'); # for JEX
        $size = -s $fh;

        # mdb added 2/9/17 -- delete temp file
        unlink($tmpfilename) or warn "Couldn't delete file '$tmpfilename': $!";
    }

    return encode_json(
        {
            filename  => $filename,
            path      => $path,
            size      => $size
        }
    );
}

sub get_debug_log {
    my %opts         = @_;
    my $workflow_id = $opts{workflow_id};
    return unless $workflow_id;
    #TODO authenticate user access to workflow

    my (undef, $results_path) = get_workflow_paths($USER->name, $workflow_id);
    return unless (-r $results_path);

    my $result_file = catfile($results_path, 'debug.log');
    return unless (-r $result_file);

    my $result = read_file($result_file);
    return $result;
}

sub get_sources {
    my %unique;
    foreach ( $DB->resultset('DataSource')->all() ) {
        $unique{ $_->name }++;
    }

    return encode_json( [ sort keys %unique ] );
}

sub create_source {
    my %opts = @_;
    my $name = $opts{name};
    return unless $name;
    my $desc = $opts{desc};
    my $link = $opts{link};
    $link =~ s/^\s+//;
    $link = 'http://' . $link if ( not $link =~ /^(\w+)\:\/\// );

    my $source =
      $DB->resultset('DataSource')
      ->find_or_create(
        { name => $name, description => $desc, link => $link } );
    return unless ($source);

    return $name;
}

sub send_error_report {
    my %opts = @_;
    my $load_id = $opts{load_id};
    my $job_id = $opts{job_id};
    unless ($load_id and $job_id) {
        print STDERR "LoadExp+::send_error_report: missing required params\n";
        return;
    }

    # Get the staging directory
    my ($staging_dir, $result_dir) = get_workflow_paths($USER->name, $job_id);

    my $url = $CONF->{SERVER} . "LoadExperiment.pl?";
    $url .= "job_id=$job_id;" if $job_id;
    $url .= "load_id=$load_id";

    my $email = $CONF->{SUPPORT_EMAIL};

    my $body =
        "Load failed\n\n"
        . 'For user: '
        . $USER->name . ' id='
        . $USER->id . ' '
        . $USER->date . "\n\n"
        . "staging_directory: $staging_dir\n\n"
        . "result_directory: $result_dir\n\n"
        . "tiny link: $url\n\n";

    my $log = get_debug_log(workflow_id => $job_id);
    $body .= $log if $log;

    CoGe::Accessory::Web::send_email(
        from    => $email,
        to      => $email,
        subject => "Load error notification from $PAGE_TITLE",
        body    => $body
    );
}


text:
// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;

namespace TiltBrush {

public class Stroke : StrokeData {
  public enum Type {
    /// Brush stroke has not been realized into geometry (or whatever else it turns into)
    /// so we don't yet know whether it is batched or unbatched
    NotCreated,
    /// Brush stroke geometry exists in the form of a GameObject
    BrushStroke,
    /// Brush stroke geoemtry exists in the form of a BatchSubset
    BatchedBrushStroke,
  }

  // Instance API

  /// How the geometry is contained (if there is any)
  public Type m_Type = Type.NotCreated;
  /// Valid only when type == NotCreated. May be null.
  public CanvasScript m_IntendedCanvas;
  /// Valid only when type == BrushStroke. Never null; will always have a BaseBrushScript.
  public GameObject m_Object;
  /// Valid only when type == BatchedBrushStroke.
  public BatchSubset m_BatchSubset;

  /// used by SketchMemoryScript.m_Instance.m_MemoryList (ordered by time)
  public LinkedListNode<Stroke> m_NodeByTime;
  /// used by one of the lists in ScenePlayback (ordered by time)
  public LinkedListNode<Stroke> m_PlaybackNode;

  /// A copy of the StrokeData part of the stroke.
  /// Used for the saving thread to serialize the sketch.
  private StrokeData m_CopyForSaveThread;

  /// The group this stroke is a part of. Cannot be null (as it is a struct).
  public SketchGroupTag Group {
    get => m_Group;
    set {
      var oldGroup = m_Group;
      m_Group = value;

      SelectionManager.m_Instance.OnStrokeRemovedFromGroup(this, oldGroup);
      SelectionManager.m_Instance.OnStrokeAddedToGroup(this);
    }
  }

  /// Which control points on the stroke should be dropped due to simplification
  public bool[] m_ControlPointsToDrop;

  /// The canvas this stroke is a part of.
  public CanvasScript Canvas {
    get {
      if (m_Type == Type.NotCreated) {
        return m_IntendedCanvas;
      } else if (m_Type == Type.BatchedBrushStroke) {
        return m_BatchSubset.Canvas;
      } else if (m_Type == Type.BrushStroke) {
        return m_Object.GetComponent<BaseBrushScript>().Canvas;
      } else {
        throw new InvalidOperationException();
      }
    }
  }

  /// True if stroke's geometry exists and is active.  E.g. prior to playback, strokes
  /// will not have a geometry representation in the scene.  Strokes which are erased
  /// but available for redo will have inactive geometry.
  public bool IsGeometryEnabled {
    get {
      return this.m_Object != null && this.m_Object.activeSelf ||
             m_Type == Type.BatchedBrushStroke &&
             m_BatchSubset.m_Active;
    }
  }

  /// True if this stroke should be displayed on playback (i.e. not an erased or undone stroke).
  /// TODO: the setter is never used -- is that a bug, or should we remove the field?
  public bool IsVisibleForPlayback { get; /*set;*/ } = true;

  public uint HeadTimestampMs {
    get { return this.m_ControlPoints[0].m_TimestampMs; }
  }

  public uint TailTimestampMs {
    get { return this.m_ControlPoints.Last().m_TimestampMs; }
  }

  public float SizeInLocalSpace {
    get {
      return m_BrushScale * m_BrushSize;
    }
  }

  public float SizeInRoomSpace {
    get {
      var localToRoom = Coords.AsRoom[this.StrokeTransform];
      return localToRoom.scale * SizeInLocalSpace;
    }
  }

  /// Could be a batch or an individual object
  public Transform StrokeTransform {
    get {
      if (m_Object != null) {
        return m_Object.transform;
      } else {
        return m_BatchSubset.m_ParentBatch.transform;
      }
    }
  }

  public Stroke() {
    m_NodeByTime = new LinkedListNode<Stroke>(this);
    m_PlaybackNode = new LinkedListNode<Stroke>(this);
  }

  /// Clones the passed stroke into a new NotCreated stroke.
  ///
  /// Group affiliation is copied, implying that the resulting stroke:
  /// - must be put into the same sketch as 'existing'
  /// - is selectable, meaning the caller is responsible for getting it out of NotCreated
  /// The caller is responsible for setting result.Group = SketchGroupTag.None if
  /// those things aren't both true.
  ///
  /// TODO: semantics are cleaner & safer if group affiliation is not copied;
  /// caller can do it explicitly if desired.
  public Stroke(Stroke existing) : base(existing) {
    m_ControlPointsToDrop = new bool[existing.m_ControlPointsToDrop.Length];
    Array.Copy(existing.m_ControlPointsToDrop, m_ControlPointsToDrop,
               existing.m_ControlPointsToDrop.Length);

    // Alas, we can't chain constructor to this() because we chain to base(existing).
    // And we can't use field initializers for the linked list creation.
    m_NodeByTime = new LinkedListNode<Stroke>(this);
    m_PlaybackNode = new LinkedListNode<Stroke>(this);
  }

  /// Makes a copy of stroke, if one has not already been made.
  /// Should only be called by the 'ThreadedSave' method of SaveLoadScript
  public StrokeData GetCopyForSaveThread() {
    if (m_CopyForSaveThread == null) {
      m_CopyForSaveThread = new StrokeData(this);
    }
    return m_CopyForSaveThread;
  }

  public void InvalidateCopy() {
    m_CopyForSaveThread = null;
  }

  /// Releases all resources owned by the stroke; consider the stroke unusable after this.
  ///
  /// It is important that this be called before trying to drop a Stroke
  /// into the garbage. Not doing so causes memory leaks:
  /// - Batch <-> BatchSubset link won't get torn down
  /// - BatchSubset <-> Stroke link won't get torn down
  /// - Batch will never become empty, and never get deallocated
  /// - Stroke will never become garbage because of the Batch -> Subset -> Stroke link
  public void DestroyStroke() {
    Uncreate();
    // The object is still in a valid state; we should probably purposely vandalize it,
    // but some code might still erroneously use Destroy() when they mean Uncreate()
    // TODO: Find and fix those places
    //   m_Type = StrokeType.Destroyed;
    //   m_ControlPoints = null;
    //   m_CopyForSaveThread = null;
  }

  /// Sets type to NotCreated, releasing render resources if applicable.
  /// This means the subset will be destroyed!
  public void Uncreate() {
    // Save off before we lose the object/batch that tells us what canvas we're in
    m_IntendedCanvas = Canvas;

    if (m_Object != null) {
      Object.Destroy(m_Object);
      m_Object = null;
    }

    // TODO: instead of destroying, reuse the previous batch space if possible
    // (but be careful because the brush may have changed). Excessive use of Recreate()
    // will swiss-cheese our batches.
    if (m_BatchSubset != null) {
      // Invalidates subset; tears down Batch <-> Subset link
      m_BatchSubset.m_ParentBatch.RemoveSubset(m_BatchSubset);
      // Tear down Subset <-> Stroke link. Removing the Subset <-- Stroke link is
      // more for cleanliness than correctness; the Subset should get GC'd soon.
      // Maybe one of these references should be weak?
      m_BatchSubset.m_Stroke = null;
      m_BatchSubset = null;
    }

    m_Type = Type.NotCreated;
  }

  /// Ensure there is geometry for this stroke, creating if necessary.
  /// Optionally also calls SetParent() or LeftTransformControlPoints() before creation.
  ///
  /// Assumes that any existing geometry is up-to-date with the data in the stroke;
  /// this assumption may be used for optimizations. Caller may therefore wish to
  /// call Uncreate() before calling Recreate().
  ///
  /// TODO: name is misleading because geo may be reused instead of recreated
  ///
  /// TODO: Consider moving the code from the "m_Type == StrokeType.BrushStroke"
  /// case of SetParentKeepWorldPosition() into here.
  public void Recreate(TrTransform? leftTransform = null, CanvasScript canvas = null) {
    // TODO: Try a fast-path that uses VertexLayout+GeometryPool to modify geo directly
    if (leftTransform != null || m_Type == Type.NotCreated) {
      // Uncreate first, or SetParent() will do a lot of needless work
      Uncreate();
      if (canvas != null) {
        SetParent(canvas);
      }
      if (leftTransform != null) {
        LeftTransformControlPoints(leftTransform.Value);
      }
      // PointerManager's pointer management is a complete mess.
      // "5" is the most-likely to be unused. It's terrible that this
      // needs to go through a pointer.
      var pointer = PointerManager.m_Instance.GetTransientPointer(5);
      pointer.RecreateLineFromMemory(this);
    } else if (canvas != null) {
      SetParent(canvas);
    } else {
      // It's already created, not being moved, not being reparented -- the only
      // reason the caller might have done this is they expected the geo to be destroyed
      // and recreated. They're not going to get that, so treat this as a logic error.
      // I expect this case will go away when the name/params get fixed to something
      // more reasonable
      throw new InvalidOperationException("Nothing to do");
    }
  }

  /// Similar to Recreate() but takes a fast path by copying geometry from another
  /// stroke, if possible.
  /// This only makes sense if the stroke has no geometry, so it's an error otherwise.
  public void CopyGeometry(CanvasScript targetCanvas, Stroke baseStroke) {
    if (m_Type != Type.NotCreated) {
      throw new InvalidOperationException("stroke must be NotCreated");
    }
    if (baseStroke.m_Type != Type.BatchedBrushStroke) {
      throw new InvalidOperationException("baseStroke must have batched geometry");
    }
    // Copy buffers directly.  Only works with batched brush stroke.
    m_BatchSubset = targetCanvas.BatchManager.CreateSubset(baseStroke.m_BatchSubset);
    m_BatchSubset.m_Stroke = this;
    m_Object = null;
    m_IntendedCanvas = null;
    m_Type = Type.BatchedBrushStroke;
  }

  // TODO: Possibly could optimize this in C++ for 11.5% of time in selection.
  private void LeftTransformControlPoints(TrTransform leftTransform) {
    for (int i = 0; i < m_ControlPoints.Length; i++) {
      var point = m_ControlPoints[i];
      var xfOld = TrTransform.TR(point.m_Pos, point.m_Orient);
      var xfNew = leftTransform * xfOld;
      point.m_Pos = xfNew.translation;
      point.m_Orient = xfNew.rotation;
      m_ControlPoints[i] = point;
    }

    m_BrushScale *= leftTransform.scale;
    InvalidateCopy();
  }

  /// Set the parent canvas of this stroke, preserving the _canvas_-relative position.
  /// There will be a pop if the previous and current canvases have different
  /// transforms.
  ///
  /// Directly analagous to Transform.SetParent, except strokes may not
  /// be parented to an arbitrary Transform, only to CanvasScript.
  public void SetParent(CanvasScript canvas) {
    CanvasScript prevCanvas = Canvas;
    if (prevCanvas == canvas) {
      return;
    }

    switch (m_Type) {
    case Type.BatchedBrushStroke: {
      // Shortcut: move geometry to new BatchManager rather than recreating from scratch
      BatchSubset newSubset = canvas.BatchManager.CreateSubset(m_BatchSubset);
      m_BatchSubset.m_ParentBatch.RemoveSubset(m_BatchSubset);
      m_BatchSubset = newSubset;
      m_BatchSubset.m_Stroke = this;
      break;
    }
    case Type.BrushStroke: {
      m_Object.transform.SetParent(canvas.transform, false);
      break;
    }
    case Type.NotCreated: {
      m_IntendedCanvas = canvas;
      break;
    }
    }
  }

  /// Set the parent canvas of this stroke, preserving the scene-relative position.
  ///
  /// Slower than the other SetParent(), since the stroke might be recreated from scratch or
  /// transformed.  There will *not* be a pop if the brush's geometry generation is not
  /// transform-invariant.  So production brushes need to be checked to be transform-invariant
  /// some other way.
  ///
  /// Directly analagous to Transform.SetParent, except strokes may not
  /// be parented to an arbitrary Transform, only to CanvasScript.
  public void SetParentKeepWorldPosition(CanvasScript canvas, TrTransform? leftTransform = null) {
    CanvasScript prevCanvas = Canvas;
    if (prevCanvas == canvas) {
      return;
    }

    // Invariant is:
    //   newCanvas.Pose * newCP = prevCanvas.Pose * prevCP
    // Solve for newCp:
    //   newCP = (newCanvas.Pose.inverse * prevCanvas.Pose) * prevCP
    TrTransform leftTransformValue = leftTransform ?? canvas.Pose.inverse * prevCanvas.Pose;
    bool bWasTransformed = leftTransform.HasValue &&
        !TrTransform.Approximately(App.ActiveCanvas.Pose, leftTransform.Value);
    if (m_Type == Type.NotCreated || !bWasTransformed) {
      SetParent(canvas);
      LeftTransformControlPoints(leftTransformValue);
    } else {
      if (m_Type == Type.BrushStroke) {
        Object.Destroy(m_Object);
        m_Object = null;

        m_Type = Type.NotCreated;
        m_IntendedCanvas = canvas;

        LeftTransformControlPoints(leftTransform.Value);
        // PointerManager's pointer management is a complete mess.
        // "5" is the most-likely to be unused. It's terrible that this
        // needs to go through a pointer.
        var pointer = PointerManager.m_Instance.GetTransientPointer(5);
        pointer.RecreateLineFromMemory(this);
      } else {
        Debug.Assert(m_Type == Type.BatchedBrushStroke);

        // Shortcut: modify existing geometry to new BatchManager rather than recreating from
        // scratch.
        BatchSubset newSubset = canvas.BatchManager.CreateSubset(m_BatchSubset, leftTransform);
        m_BatchSubset.m_ParentBatch.RemoveSubset(m_BatchSubset);
        m_BatchSubset = newSubset;
        m_BatchSubset.m_Stroke = this;
        LeftTransformControlPoints(leftTransform.Value);
      }
    }
  }
}
} // namespace TiltBrush


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Asplenium falcatum var. bipinnatum Sledge

### Remarks
null


text:
<?php

namespace Alpha\Test\Util\Http\Session;

use Alpha\Util\Service\ServiceFactory;
use PHPUnit\Framework\TestCase;

class SessionProviderInterfaceTest extends TestCase
{
    /**
     * @dataProvider getProviders
     */
    public function testSetAndGet($provider)
    {
        $provider->set('somekey', 'somevalue');

        $this->assertEquals('somevalue', $provider->get('somekey'), 'Testing setting and getting a value from the session');
    }

    /**
     * @dataProvider getProviders
     */
    public function testDelete($provider)
    {
        $provider->set('somekey', 'somevalue');

        $this->assertEquals('somevalue', $provider->get('somekey'), 'Testing setting and getting a value from the session');

        $provider->delete('somekey');

        $this->assertFalse($provider->get('somekey'), 'Testing deleting a value from the session');
    }

    /**
     * @dataProvider getProviders
     */
    public function testDestroy($provider)
    {
        $provider->set('somekey', 'somevalue');
        $provider->set('someotherkey', 'someothervalue');

        $this->assertEquals('somevalue', $provider->get('somekey'), 'Testing setting and getting a value from the session');
        $this->assertEquals('someothervalue', $provider->get('someotherkey'), 'Testing setting and getting a value from the session');

        $provider->destroy('somekey');

        $this->assertFalse($provider->get('somekey'), 'Testing destroying session');
        $this->assertFalse($provider->get('someotherkey'), 'Testing destroying session');
    }

    /**
     * @dataProvider getProviders
     */
    public function testInit($provider)
    {
        $provider->set('itisstillthere', 'stillhere');

        $this->assertEquals('stillhere', $provider->get('itisstillthere'), 'Testing values survive re-initialization of session');

        $provider = ServiceFactory::getInstance(get_class($provider), 'Alpha\Util\Http\Session\SessionProviderInterface');

        $this->assertEquals('stillhere', $provider->get('itisstillthere'), 'Testing values survive re-initialization of session');
    }

    public function getProviders()
    {
        $arrayProvider = ServiceFactory::getInstance('Alpha\Util\Http\Session\SessionProviderArray', 'Alpha\Util\Http\Session\SessionProviderInterface');
        $PHPSessionProvider = ServiceFactory::getInstance('Alpha\Util\Http\Session\SessionProviderPHP', 'Alpha\Util\Http\Session\SessionProviderInterface');

        return array(
            array($arrayProvider),
            array($PHPSessionProvider),
        );
    }
}


text:
use DNSCheck;
use YAML::XS;

my %hash = %{DNSCheck->new->config};
delete $hash{loglevels};
delete $hash{root_zone_data};
delete $hash{locale};
delete $hash{hostname};

print Dump(\%hash);


text:
from os.path import abspath, dirname, join

from fabric.api import abort, env, hide, local, settings, task
from fabric.contrib.console import confirm

from . import dependencies, migrations, pr, test
from .utils import git, ui

env.huxley_root = abspath(dirname(dirname(__file__)))
env.js_root = join(env.huxley_root, 'huxley/www/static/js')

@task
def feature(branch_name=None):
    '''Create a new feature branch.'''
    if branch_name:
        git.new_branch(branch_name)
        dependencies.check()
        migrations.check()
    else:
        print ui.error('No branch name given. Usage: fab feature:<branch_name>')

@task
def update():
    '''Rebase the current feature branch onto the latest version of upstream.'''
    print ui.info('Updating your local branch...')
    git.pull()
    print ui.info('Clearing old files...')
    local('git clean -xf *.css')
    dependencies.check()
    migrations.check()

@task
def authors():
    '''Update the AUTHORS file.'''
    authors_path = join(env.huxley_root, 'AUTHORS')
    with hide('running'):
        local('git log --format="%%aN <%%aE>" | sort -u > %s' % authors_path)
        if local('git diff --name-only %s' % authors_path, capture=True):
            print ui.info('Automatically updating the authors file...')
            local('git commit -m "Update AUTHORS." %s' % authors_path)
        else:
            print ui.success('No change to AUTHORS.')

@task
def submit(remote='origin', skip_tests=False):
    '''Push the current feature branch and create/update pull request.'''
    if not skip_tests:
        with settings(warn_only=True):
            if not test.run():
                if confirm(ui.warning('Tests failed. Continue anyway?')):
                    print ui.warning('Ignoring failed tests. Be careful.')
                else:
                    print ui.error('Terminating due to failed tests.')
                    return
            else:
                print ui.success('Tests OK!')

    first_submission = not git.remote_branch_exists(remote=remote)
    git.pull()
    authors()
    git.push()

    if not first_submission:
        print ui.success('Pull request sucessfully updated.')
    elif git.hub_installed():
        current_branch = git.current_branch()
        local('hub pull-request -b bmun:master -h %s -f' % current_branch)
        print ui.success('Pull request successfully issued.')
    else:
        print ui.success('Branch successfully pushed. Go to GitHub to issue a pull request.')

@task
def finish(branch_name=None, remote='origin'):
    '''Delete the current feature branch.'''
    prompt = ui.warning('This will delete your local and remote topic branches. '
                        'Make sure your pull request has been merged or closed. '
                        'Are you sure you want to finish this branch?')
    if not confirm(prompt):
        abort('Branch deletion canceled.')

    print ui.success('Branch %s successfully cleaned up.' % git.cleanup(branch_name,
                                                                   remote))

try:
    from deploy import deploy, restart
except ImportError:
    pass


text:
using Vapula.Model;

namespace Vapula.Flow
{
    public partial class Graph : ISyncable
    {
        private ISyncable _SyncTarget = null;

        public ISyncable SyncTarget
        {
            get { return _SyncTarget; }
            set { _SyncTarget = value; }
        }

        public object Sync(string cmd, object attach)
        {
            ISyncable target = attach as ISyncable;
            if (cmd == "add-link")
            {
                var link = AddLink();
                target.SyncTarget = link;
                link.SyncTarget = target;
            }
            else if (cmd == "remove-link")
            {
                var link = target.SyncTarget as Link;
                _Links.Remove(link);
                link.Dispose();
            }
            else if (cmd == "remove-node")
            {
                var node = target.SyncTarget as Node;
                _Nodes.Remove(node);
                node.Dispose();
            }
            else if (cmd == "remove-all")
            {
                foreach (var node in _Nodes)
                    node.Dispose();
                _Nodes.Clear();
                foreach (var link in _Links)
                    link.Dispose();
                _Links.Clear();
            }
            return null;
        }
    }
}


text:
URL=http://llvm.org/svn/llvm-project/

source ./helper.sh $*
set_stage
module load cs5220

svn co $URL/llvm/trunk llvm

pushd llvm/tools
svn co $URL/cfe/trunk clang
svn co $URL/lldb/trunk lldb
popd

pushd llvm/tools/clang/tools
svn co $URL/clang-tools-extra/trunk extra
svn co $URL/polly/trunk polly
popd

pushd llvm/projects
svn co $URL/compiler-rt/trunk compiler-rt
popd

cd llvm
mkdir build
cd build

module unload anaconda

../configure -prefix=$PREFIX/llvm-svn \
  --with-gcc-toolchain=$PREFIX/gcc-4.8.2 \
  --with-extra-ld-options=-Wl,-R$PREFIX/gcc-4.8.2/lib64 \
  --enable-cxx11

make
make install

mkdir -p $PREFIX/llvm-svn-analyzer/
cp -R ../tools/clang/tools/scan-build/* $PREFIX/llvm-$VER-analyzer/
cp -R ../tools/clang/tools/scan-view/*  $PREFIX/llvm-$VER-analyzer/

leave_stage


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>SoWhAt</title>
		<meta name="description" content="Craft your deck. Answer the SoWhAt">
		<meta name="viewport" content="width=device-width,
					initial-scale=1, maximum-scale=1, user-scalable=0">
		<link rel="stylesheet" href="dash.css">

# SoWhAt

---

## Craft your deck. Answer the SoWhAt.
More at [sowhat.amitkaps.com](http://sowhat.amitkaps.com)

---

## Strong opinions, Weakly held, Acted thoughtfully.

---

> Drink your tea slowly and reverently, as if it is the axis
on which the whole earth revolves - slowly, evenly, without rushing
toward the future. Live the actual moment. Only this actual moment
is life.

---

> The right attitude for learning and creativity is to
>	"argue as if you are right and listen as if you are wrong," which
>	strikes me as the right path for developing "strong opinions,
>	weakly held.

---

> Remember: when people tell you something's wrong or doesn't
> work for them, they are almost always right. When they tell you exactly
> what they think is wrong and how to fix it, they are almost always
> wrong.


text:
@implementation NSObject (RITLExtension)

+ (instancetype)ritl_object:(void (^)(__kindof id _Nonnull))initialHandler
{
    id object = [self new];

    initialHandler(object);

    return object;
}

@end


text:
#include <string.h>
#include "SBGC.h"

/* Packs command structure to SerialCommand object */
void SBGC_cmd_control_pack(SBGC_cmd_control_t &p, SerialCommand &cmd) {
	cmd.init(SBGC_CMD_CONTROL);
	#ifdef SBGC_CMD_STRUCT_ALIGNED
		memcpy(cmd.data, &p, sizeof(p));
		cmd.len = sizeof(p);
	#else
		cmd.writeByte(p.mode);
		cmd.writeWord(p.speedROLL);
		cmd.writeWord(p.angleROLL);
		cmd.writeWord(p.speedPITCH);
		cmd.writeWord(p.anglePITCH);
		cmd.writeWord(p.speedYAW);
		cmd.writeWord(p.angleYAW);
	#endif
}

/* Packs command structure to SerialCommand object */
void SBGC_cmd_control_ext_pack(SBGC_cmd_control_ext_t &p, SerialCommand &cmd) {
	cmd.init(SBGC_CMD_CONTROL);
	#ifdef SBGC_CMD_STRUCT_ALIGNED
		memcpy(cmd.data, &p, sizeof(p));
		cmd.len = sizeof(p);
	#else
		cmd.writeBuf(p.mode, 3);
		for(uint8_t i=0; i<3; i++) {
			cmd.writeWord(p.data[i].speed);
			cmd.writeWord(p.data[i].angle);
		}
	#endif
}

/* Packs command structure to SerialCommand object */
void SBGC_cmd_api_virt_ch_control_pack(SBGC_cmd_api_virt_ch_control_t &p, SerialCommand &cmd) {
	cmd.init(SBGC_CMD_API_VIRT_CH_CONTROL);
	#ifdef SBGC_CMD_STRUCT_ALIGNED
		memcpy(cmd.data, &p, sizeof(p));
		cmd.len = sizeof(p);
	#else
		for(uint8_t i=0; i<SBGC_API_VIRT_NUM_CHANNELS; i++) {
			cmd.writeWord(p.data[i]);
		}
	#endif
}

/* Packs command structure to SerialCommand object */
void SBGC_cmd_trigger_pack(SBGC_cmd_trigger_t &p, SerialCommand &cmd) {
	cmd.init(SBGC_CMD_TRIGGER_PIN);
	#ifdef SBGC_CMD_STRUCT_ALIGNED
		memcpy(cmd.data, &p, sizeof(p));
		cmd.len = sizeof(p);
	#else
		cmd.writeByte(p.pin);
		cmd.writeByte(p.state);
	#endif
}

/* Packs command structure to SerialCommand object */
void SBGC_cmd_servo_out_pack(SBGC_cmd_servo_out_t &p, SerialCommand &cmd) {
	cmd.init(SBGC_CMD_SERVO_OUT);
	#ifdef SBGC_CMD_STRUCT_ALIGNED
		memcpy(cmd.data, &p, sizeof(p));
		cmd.len = sizeof(p);
	#else
		for(uint8_t i=0; i<8; i++) {
			cmd.writeWord(p.servo[i]);
		}
	#endif
}

/* Packs command structure to SerialCommand object */
void SBGC_cmd_set_adj_vars_pack(SBGC_cmd_set_adj_vars_var_t vars[], uint8_t vars_num, SerialCommand &cmd) {
	cmd.init(SBGC_CMD_SET_ADJ_VARS_VAL);
	cmd.writeByte(vars_num); // number of variables

	#ifdef SBGC_CMD_STRUCT_ALIGNED
		cmd.writeBuf(vars, sizeof(SBGC_cmd_set_adj_vars_var_t)*vars_num);
	#else
		for(uint8_t i=0; i<vars_num; i++) {
			cmd.writeByte(vars[i].id);
			cmd.writeLong(vars[i].val);
		}
	#endif
}

/*
* Unpacks SerialCommand object to vars_buf[var_num].
* 'var_num' specifies the buffer capacity.
* On return, 'var_num' will be set to actual number of received variables.
* Returns 0 on success, PARSER_ERROR_XX code on fail.
*/
uint8_t SBGC_cmd_set_adj_vars_unpack(SBGC_cmd_set_adj_vars_var_t vars_buf[], uint8_t &vars_num, SerialCommand &cmd) {
	uint8_t num = cmd.readByte(); // actual number of variables
	if(num <= vars_num) {
		vars_num = num;
		#ifdef SBGC_CMD_STRUCT_ALIGNED
				cmd.readBuf(vars_buf, sizeof(SBGC_cmd_set_adj_vars_var_t)*vars_num);
		#else
			for(uint8_t i=0; i<num; i++) {
				vars_buf[i].id = cmd.readByte();
				vars_buf[i].val = cmd.readLong();
			}
		#endif

		if(cmd.checkLimit()) return 0;
		else return PARSER_ERROR_WRONG_DATA_SIZE;
	} else {
		return PARSER_ERROR_BUFFER_IS_FULL;
	}
}

/*
* Unpacks SerialCommand object to command structure.
* Returns 0 on success, PARSER_ERROR_XX code on fail.
*/
uint8_t SBGC_cmd_realtime_data_unpack(SBGC_cmd_realtime_data_t &p, SerialCommand &cmd) {
	#ifdef SBGC_CMD_STRUCT_ALIGNED
		if(cmd.len <= sizeof(p)) {
			memcpy(&p, cmd.data, cmd.len);
			return 0;
		} else {
			return PARSER_ERROR_WRONG_DATA_SIZE;
		}
	#else
		for(uint8_t i=0; i<3; i++) {
			p.sensor_data[i].acc_data = cmd.readWord();
			p.sensor_data[i].gyro_data = cmd.readWord();
		}
		p.serial_error_cnt = cmd.readWord();
		p.system_error = cmd.readWord();
		cmd.skipBytes(4); // reserved
		cmd.readWordArr(p.rc_raw_data, SBGC_RC_NUM_CHANNELS);
		cmd.readWordArr(p.imu_angle, 3);
		cmd.readWordArr(p.frame_imu_angle, 3);
		cmd.readWordArr(p.target_angle, 3);
		p.cycle_time_us = cmd.readWord();
		p.i2c_error_count = cmd.readWord();
		cmd.readByte(); // reserved
		p.battery_voltage = cmd.readWord();
		p.state_flags1 = cmd.readByte();
		p.cur_imu = cmd.readByte();
		p.cur_profile = cmd.readByte();
		cmd.readBuf(p.motor_power, 3);

		if(cmd.id == SBGC_CMD_REALTIME_DATA_4) {
			cmd.readWordArr(p.rotor_angle, 3);
			cmd.readByte(); // reserved
			cmd.readWordArr(p.balance_error, 3);
			p.current = cmd.readWord();
			cmd.readWordArr(p.magnetometer_data, 3);
			p.imu_temp_celcius = cmd.readByte();
			p.frame_imu_temp_celcius = cmd.readByte();
			cmd.skipBytes(38);
		}

		if(cmd.checkLimit()) return 0;
		else return PARSER_ERROR_WRONG_DATA_SIZE;
	#endif
}


text:
Template.home.onRendered(function() {
	this.subscribe('entity', 'communities');
})

Template.home.helpers({
	communities: function () {
		return orion.entities.communities.collection.find();
	}
});


text:
import datetime

from manila import exception as exc

FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
FAKE_UUIDS = {}

def stub_share(id, **kwargs):
    share = {
        'id': id,
        'share_proto': 'fakeproto',
        'export_location': 'fake_location',
        'user_id': 'fakeuser',
        'project_id': 'fakeproject',
        'host': 'fakehost',
        'size': 1,
        'availability_zone': 'fakeaz',
        'status': 'fakestatus',
        'name': 'vol name',
        'display_name': 'displayname',
        'display_description': 'displaydesc',
        'created_at': datetime.datetime(1, 1, 1, 1, 1, 1),
        'snapshot_id': '2',
    }
    share.update(kwargs)
    return share

def stub_snapshot(id, **kwargs):
    snapshot = {
        'id': id,
        'share_id': 'fakeshareid',
        'share_proto': 'fakesnapproto',
        'export_location': 'fakesnaplocation',
        'user_id': 'fakesnapuser',
        'project_id': 'fakesnapproject',
        'host': 'fakesnaphost',
        'share_size': 1,
        'size': 1,
        'status': 'fakesnapstatus',
        'share_name': 'fakesharename',
        'display_name': 'displaysnapname',
        'display_description': 'displaysnapdesc',
        'created_at': datetime.datetime(1, 1, 1, 1, 1, 1),
    }
    snapshot.update(kwargs)
    return snapshot

def stub_share_get(self, context, share_id):
    return stub_share(share_id)

def stub_share_get_notfound(self, context, share_id):
    raise exc.NotFound

def stub_share_create(self, context, share_proto, size, name, description,
                      **param):
    share = stub_share('1')
    share['status'] = 'creating'
    share['share_proto'] = share_proto
    share['size'] = size
    share['display_name'] = name
    share['display_description'] = description
    return share

def stub_share_delete(self, context, *args, **param):
    pass

def stub_share_update(self, context, *args, **param):
    share = stub_share('1')
    return share

def stub_snapshot_update(self, context, *args, **param):
    share = stub_share('1')
    return share

def stub_share_get_all_by_project(self, context, search_opts=None):
    return [stub_share_get(self, context, '1')]

def stub_get_all_shares(self, context):
    return [stub_share(100, project_id='fake'),
            stub_share(101, project_id='superfake'),
            stub_share(102, project_id='superduperfake')]

def stub_snapshot_get(self, context, snapshot_id):
    return stub_snapshot(snapshot_id)

def stub_snapshot_get_notfound(self, context, snapshot_id):
    raise exc.NotFound

def stub_snapshot_create(self, context, share, display_name,
                         display_description):
    return stub_snapshot(200,
                         share_id=share['id'],
                         display_name=display_name,
                         display_description=display_description)

def stub_snapshot_delete(self, context, *args, **param):
    pass

def stub_snapshot_get_all_by_project(self, context, search_opts=None):
    return [stub_snapshot_get(self, context, 2)]


text:
package com.pacific.domain.dto.report;

/**
 * Created by Fe on 16/7/20.
 */
public class JVMGcReportDto extends BaseReportDto {
    private GcCountDto gcCountDto;
    private GcTimeDto gcTimeDto;

    public GcCountDto getGcCountDto() {
        return gcCountDto;
    }

    public void setGcCountDto(GcCountDto gcCountDto) {
        this.gcCountDto = gcCountDto;
    }

    public GcTimeDto getGcTimeDto() {
        return gcTimeDto;
    }

    public void setGcTimeDto(GcTimeDto gcTimeDto) {
        this.gcTimeDto = gcTimeDto;
    }
}


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

<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:vm="http://www.mulesoft.org/schema/mule/vm"
      xmlns:http="http://www.mulesoft.org/schema/mule/http"
      xmlns:jms="http://www.mulesoft.org/schema/mule/jms"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/http
http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/jms
http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd
http://www.mulesoft.org/schema/mule/core
http://www.mulesoft.org/schema/mule/core/current/mule.xsd
">

    <notifications dynamic="true">
        <notification event="COMPONENT-MESSAGE"/>
    </notifications>

    <jms:activemq-connector name="jmsConnector"
                            specification="1.1"
                            brokerURL="vm://localhost"/>

    <!--<start id="ch05_idempotentOrderRouter_lis"/>-->
    <flow name="idempotentOrderRouter">
        <jms:inbound-endpoint topic="orders"
                              connector-ref="jmsConnector"/>
        <or-filter>
            <expression-filter
expression="xpath('/order/priority').text == 'HIGH'"/>
            <message-property-filter pattern="PD_PRIORITY='HIGH'"
              caseSensitive="true" scope="inbound"/>
        </or-filter>
        <idempotent-message-filter
                idExpression="xpath('/order/id').text"
                />
        <!--<co id="ch05-idempotent-receiver-1-cod"/>-->
        <component
class="com.prancingdonkey.service.HighPriorityOrderProcessingService"/>

    </flow>
    <!--<end id="ch05_idempotentOrderRouter_lis"/>-->

</mule>


text:
#import "NSObject.h"

@protocol DVTEditor <NSObject>
- (BOOL)commitEditingForAction:(int)arg1 errors:(id)arg2;
- (void)discardEditing;
@end


text:
package fromwsdl.mime.text_plain_754.client;

import junit.framework.TestCase;

import jakarta.xml.ws.Holder;

/**
 * Test case for issue: 754 - tests text/plain in mime binding
 *
 * @author Jitendra Kotamraju
 */
public class HelloLiteralTest extends TestCase {

    private static CatalogPortType port;

    public HelloLiteralTest(String name) throws Exception {
        super(name);
    }

    @Override
    public void setUp() {
        CatalogService service = new CatalogService();
        port = service.getCatalogPort();
    }

    public void testEchoString() throws Exception {
        Holder<String> outStr = new Holder<String>("output");
        Holder<String> att = new Holder<String>();
        port.echoString("input", "attInput", outStr, att);
        assertEquals("output", outStr.value);
        assertEquals("att", att.value);
    }

}


text:
#include <compiler.h>
#include <liballoc.h>
#include "kcstdlib.h"

#ifdef _MSC_VER

// Constructor prototypes
typedef void(__cdecl *_PVFV)(void);
typedef int(__cdecl *_PIFV)(void);

// Linker puts constructors between these sections, and we use them to locate constructor pointers.
#pragma section(".CRT$XIA",long,read)
#pragma section(".CRT$XIZ",long,read)
#pragma section(".CRT$XCA",long,read)
#pragma section(".CRT$XCZ",long,read)

// Put .CRT data into .rdata section
#pragma comment(linker, "/merge:.CRT=.rdata")

// Pointers surrounding constructors
__declspec(allocate(".CRT$XIA")) _PIFV __xi_a[] = { 0 };
__declspec(allocate(".CRT$XIZ")) _PIFV __xi_z[] = { 0 };
__declspec(allocate(".CRT$XCA")) _PVFV __xc_a[] = { 0 };
__declspec(allocate(".CRT$XCZ")) _PVFV __xc_z[] = { 0 };

extern __declspec(allocate(".CRT$XIA")) _PIFV __xi_a[];
extern __declspec(allocate(".CRT$XIZ")) _PIFV __xi_z[];    // C initializers
extern __declspec(allocate(".CRT$XCA")) _PVFV __xc_a[];
extern __declspec(allocate(".CRT$XCZ")) _PVFV __xc_z[];    // C++ initializers

// Call C constructors
static int _initterm_e(_PIFV * pfbegin, _PIFV * pfend) {
	int ret = 0;

	// walk the table of function pointers from the bottom up, until
	// the end is encountered.  Do not skip the first entry.  The initial
	// value of pfbegin points to the first valid entry.  Do not try to
	// execute what pfend points to.  Only entries before pfend are valid.
	while (pfbegin < pfend  && ret == 0)
	{
		// if current table entry is non-NULL, call thru it.
		if (*pfbegin != 0)
			ret = (**pfbegin)();
		++pfbegin;
	}

	return ret;
}

// Call C++ constructors
static void _initterm(_PVFV * pfbegin, _PVFV * pfend)
{
	// walk the table of function pointers from the bottom up, until
	// the end is encountered.  Do not skip the first entry.  The initial
	// value of pfbegin points to the first valid entry.  Do not try to
	// execute what pfend points to.  Only entries before pfend are valid.
	while (pfbegin < pfend)
	{
		// if current table entry is non-NULL, call thru it.
		if (*pfbegin != 0)
			(**pfbegin)();
		++pfbegin;
	}
}

// Call this function as soon as possible. Basically should be at the moment you
// jump into your C/C++ kernel. But keep in mind that kernel is not yet initialized,
// and you can't use a lot of stuff in your constructors!
bool CallConstructors() {
	// Do C initialization
	int initret = _initterm_e(__xi_a, __xi_z);
	if (initret != 0) {
		return false;
	}

	// Do C++ initialization
	_initterm(__xc_a, __xc_z);
	return true;
}

int __cdecl atexit(void(__cdecl*)(void))
{
	return 0;
}

void* __cdecl operator new(size_t size)
{
	return malloc(size);
}

void* __cdecl operator new[](size_t size)
{
	return malloc(size);
}

void __cdecl operator delete(void *p)
{
	if (p == 0) {
		return;
	}
	// Release allocated memory
	free(p);
}

void __cdecl operator delete[](void *p)
{
	if (p == 0) {
		return;
	}
	// Release allocated memory
	free(p);
}

EXTERN int __cdecl _purecall()
{
	return 0;
}

#if 1
#pragma function(memcpy)
EXTERN void* __cdecl memcpy(void* dest, const void* src, size_t len)
{
	for (int n = 0; n < len; n++)
	{
		((uint8_t*)dest)[n] = ((uint8_t*)src)[n];
	}
	return dest;
}
#endif

//RTTI
/*EXPORT_CLASS(type_info) {
public:
	virtual ~type_info();
	size_t hash_code() const;
	virtual bool operator==(const type_info& rhs) const;
	virtual bool operator!=(const type_info& rhs) const;
	virtual int before(const type_info& rhs) const;
	virtual const char* name() const;
	virtual const char* raw_name() const;
};

bool type_info::operator==(const type_info& rhs) const
{
	return rhs.hash_code() == hash_code();
}

typedef const struct _s__RTTIBaseClassDescriptor {
	_TypeDescriptor *pTypeDescriptor;
	unsigned long numContainedBases;
	_PMD where;
	unsigned long attributes;
} __RTTIBaseClassDescriptor;

#pragma warning (disable:4200)
typedef const struct _s__RTTIBaseClassArray {
	__RTTIBaseClassDescriptor *arrayOfBaseClassDescriptors[];
} __RTTIBaseClassArray;
#pragma warning (default:4200)

typedef const struct _s__RTTIClassHierarchyDescriptor {
	unsigned long signature;
	unsigned long attributes;
	unsigned long numBaseClasses;
	__RTTIBaseClassArray *pBaseClassArray;
} __RTTIClassHierarchyDescriptor;

typedef const struct _s__RTTICompleteObjectLocator {
	unsigned long signature;
	unsigned long offset;
	unsigned long cdOffset;
	_TypeDescriptor *pTypeDescriptor;
	__RTTIClassHierarchyDescriptor *pClassDescriptor;
} __RTTICompleteObjectLocator;*/

#endif


text:
module DbAgile
  module Core
    module Schema
      class Logical
        class Constraint < Schema::Part

          ############################################################################
          ### Constraint factory
          ############################################################################

          # Builds a constraint
          def self.factor(name, definition)
            case kind = definition[:type]
              when :primary_key, :candidate_key, :key
                Schema::Logical::CandidateKey.new(name, definition)
              when :foreign_key
                Schema::Logical::ForeignKey.new(name, definition)
              else
                raise ArgumentError, "Unexpected constraint kind #{kind}"
            end
          end

          ############################################################################
          ### Query interface
          ############################################################################

          # Returns true if this constraint is a candidate key (including a primary
          # key)
          def candidate_key?
            self.kind_of?(Logical::CandidateKey)
          end

          # Returns true if this constraint is a primary key, false otherwise
          def primary_key?
            candidate_key? and primary?
          end

          # Returns true if this constraint is a foreign key
          def foreign_key?
            self.kind_of?(Logical::ForeignKey)
          end

          ############################################################################
          ### Dependency control
          ############################################################################

          # @see DbAgile::Core::Schema::SchemaObject
          def dependencies(include_parent = false)
            include_parent ? [ parent ] : false
          end

        end # class Constraint
      end # module Logical
    end # module Schema
  end # module Core
end # module DbAgile
require 'dbagile/core/schema/logical/constraint/candidate_key'
require 'dbagile/core/schema/logical/constraint/foreign_key'


text:
"""This module adds a reST directive to sphinx that generates cyclus agent
documentation based on its annotations and schema. The user simply specifies
the normal cyclus agent spec for the agent that they wish to document.
For example,

    .. cyclus-agent:: tests:TestFacility:TestFacility

"""
from __future__ import print_function
import sys
import os.path
import re
import time
import warnings
import subprocess
from collections import OrderedDict, Mapping, Sequence

try:
    import simplejson as json
    JSONDecodeError = json.JSONDecodeError
except ImportError:
    import json
    JSONDecodeError = ValueError

from docutils import io, nodes, statemachine, utils
try:
    from docutils.utils.error_reporting import ErrorString  # the new way
except ImportError:
    from docutils.error_reporting import ErrorString        # the old way
from docutils.parsers.rst import Directive, convert_directive_function
from docutils.parsers.rst import directives, roles, states
from docutils.parsers.rst.roles import set_classes
from docutils.transforms import misc
from docutils.statemachine import ViewList

from sphinx.util.nodes import nested_parse_with_titles

if sys.version_info[0] == 2:
    STRING_TYPES = (str, unicode, basestring)
    IS_PY3 = False
elif sys.version_info[0] >= 3:
    STRING_TYPES = (str,)
    IS_PY3 = True

def contains_resbuf(type_str):
    bufs = ('cyclus::toolkit::ResBuf',
            'cyclus::toolkit::ResMap',
            'cyclus::toolkit::ResourceBuff')
    for buf in bufs:
        if buf in type_str:
            return True
    return False

def ensure_tuple_or_str(x):
    if isinstance(x, STRING_TYPES):
        return x
    else:
        return tuple(map(ensure_tuple_or_str, x))

def type_to_str(t):
    t = ensure_tuple_or_str(t)
    if isinstance(t, STRING_TYPES):
        return t
    else:
        s = t[0] + '<'
        s += type_to_str(t[1])
        for thing in t[2:]:
            s += ', ' + type_to_str(thing)
        s += '>'
        return s

def nicestr(x):
    if IS_PY3:
        newx = str(x)
    elif isinstance(x, STRING_TYPES):
        newx = str(x)
    elif isinstance(x, Sequence):
        newx = '[' + ', '.join(map(nicestr, x)) + ']'
    elif isinstance(x, Mapping):
        newx = '{'
        newxs = [nicestr(k) + ': ' + nicestr(v) for k, v in sorted(x.items())]
        newx += ', '.join(newxs)
        newx += '}'
    else:
        newx = str(x)
    return newx

class CyclusAgent(Directive):
    """The cyclus-agent directive, which is based on constructing a list of
    of string lines of restructured text and then parsing it into its own node.
    """
    required_arguments = 1
    optional_arguments = 1
    final_argument_whitespace = True
    option_spec = {'no-sep': directives.flag}
    has_content = False

    def load_schema(self):
        cmd = 'cyclus --agent-schema {0}'.format(self.agentspec)
        stdout = subprocess.check_output(cmd, shell=True)
        self.schema = stdout.decode()

    def load_annotations(self):
        cmd = 'cyclus --agent-annotations {0}'.format(self.agentspec)
        stdout = subprocess.check_output(cmd, shell=True)
        try:
            j = json.loads(stdout.decode())
        except JSONDecodeError:
            raise ValueError("Error reading agent annotations for "\
                             "{0}.".format(self.agentspec))

        self.annotations = j

    def append_name(self):
        path, lib, agent = self.agentspec.split(':')
        name = path + ':' + lib + ':**' + agent + '**'
        self.lines += [name, '~' * len(name), '']

    skipdoc = {'doc', 'tooltip', 'vars', 'entity', 'parents', 'all_parents'}

    def append_doc(self):
        if 'tooltip' in self.annotations:
            self.lines += ['*' + self.annotations['tooltip'] + '*', '']
        if 'doc' in self.annotations:
            self.lines += self.annotations['doc'].splitlines()
        self.lines.append('')
        for key in ('entity', 'parents', 'all_parents'):
            val = self.annotations.get(key, None)
            if val is None:
                continue
            self.lines.append(':{0}: {1}'.format(key, nicestr(val)))
        for key, val in sorted(self.annotations.items()):
            if key in self.skipdoc:
                continue
            self.lines.append(':{0}: {1}'.format(key, val))
        self.lines.append('')

    skipstatevar = {'type', 'index', 'shape', 'doc', 'tooltip', 'default', None}

    def _sort_statevars(self, item):
        key, val = item
        vars = self.annotations.get('vars', {})
        while not isinstance(val, Mapping):
            # resolves aliasing
            key = val
            val = vars[key]
        return val['index']

    def append_statevars(self):
        vars = OrderedDict(sorted(self.annotations.get('vars', {}).items(),
                           key=self._sort_statevars))
        if len(vars) == 0:
            return
        lines = self.lines
        lines += ['', '**State Variables:**', '']
        for name, info in vars.items():
            if isinstance(info, STRING_TYPES):
                # must be an alias entry - skip it
                continue
            elif contains_resbuf(type_to_str(info['type'])):
                # resbufs are not directly user accessible
                continue
            elif 'internal' in info:
                continue

            alias = info.get('alias', name)
            name = alias if isinstance(alias, STRING_TYPES) else alias[0]

            # add name
            n = ":{0}: ``{1}``" .format(name, type_to_str(info['type']))
            if 'default' in info:
                n += ', default={0}'.format(info['default'])
            if 'shape' in info:
                n += ', shape={0}'.format(info['shape'])
            lines += [n, '']

            # add docs
            ind = " " * 4
            if 'tooltip' in info:
                self.lines += [ind + '*' + info['tooltip'] + '*', '']
            if 'doc' in info:
                doc = ind + info['doc'].replace('\n', '\n'+ind)
                lines += doc.splitlines()
                lines.append('')

            # add everything else
            for key, val in info.items():
                if key in self.skipstatevar:
                    continue
                self.lines.append(ind + ':{0}: {1}'.format(key, val))
            self.lines.append('')

    def append_schema(self):
        lines = self.lines
        lines += ['', '**Schema:**', '', '.. code-block:: xml', '']
        ind = " " * 4
        s = ind + self.schema.replace('\n', '\n' + ind) + '\n'
        lines += s.splitlines()

    def append_sep(self):
        if 'no-sep' in self.options:
            return
        self.lines += ['', '--------', '']

    def run(self):
        # load agent
        self.agentspec = self.arguments[0]
        self.schema = ""
        self.annotations= {}
        try:
            self.load_schema()
        except OSError:
            warnings.warn("WARNING: Failed to load schema, proceeding without schema",
                          RuntimeWraning)
        try:
            self.load_annotations()
        except OSError:
            warnings.warn("WARNING: Failed to load annotations, proceeding without "
                          "annotations", RuntimeWraning)

        # set up list of rst stirngs
        self.lines = []
        self.append_name()
        self.append_doc()
        self.append_statevars()
        self.append_schema()
        self.append_sep()

        # hook to docutils
        src, lineno = self.state_machine.get_source_and_line(self.lineno)
        vl = ViewList(self.lines, source=src)
        node = nodes.paragraph()
        nested_parse_with_titles(self.state, vl, node)
        return node.children

def setup(app):
    app.add_directive('cyclus-agent', CyclusAgent)


text:
class EmailValidationsController < ApplicationController

  def show
    @user = User.find_by_email_validation_token!(params[:id])

		# Email validation only valid von XX hours
		# (There is no method to resend validation email implemented yet.)
		#
    # if @user.email_validation_sent_at < 48.hours.ago
    #   redirect_to new_password_reset_path, :alert => "Die Gültigkeit des Links ist abgelaufen."
    # elsif

    if @user.verify
      redirect_to signin_path, :notice => "Ihr Account wurde freigeschaltet. Sie können sich nun anmelden."
    else
      redirect_to root_path, :alert => "Die Aktion konnte nicht durchgeführt werden."
    end
  end

end


text:
#ifndef __UVWASI_UV_MAPPING_H__
#define __UVWASI_UV_MAPPING_H__

#include "uv.h"
#include "wasi_types.h"

#define NANOS_PER_SEC 1000000000

uvwasi_errno_t uvwasi__translate_uv_error(int err);
int uvwasi__translate_to_uv_signal(uvwasi_signal_t sig);
uvwasi_timestamp_t uvwasi__timespec_to_timestamp(const uv_timespec_t* ts);
uvwasi_filetype_t uvwasi__stat_to_filetype(const uv_stat_t* stat);
void uvwasi__stat_to_filestat(const uv_stat_t* stat, uvwasi_filestat_t* fs);
uvwasi_errno_t uvwasi__get_filetype_by_fd(uv_file fd, uvwasi_filetype_t* type);

#endif /* __UVWASI_UV_MAPPING_H__ */