text:
namespace arrow {
namespace r {
struct symbols {
  static SEXP units;
  static SEXP xp;
  static SEXP dot_Internal;
  static SEXP inspect;
  static SEXP row_names;
};

struct data {
  static SEXP classes_POSIXct;
};

}  // namespace r
}  // namespace arrow

#define STOP_IF_NOT(TEST, MSG)    \
  do {                            \
    if (!(TEST)) Rcpp::stop(MSG); \
  } while (0)

#define STOP_IF_NOT_OK(s) STOP_IF_NOT(s.ok(), s.ToString())

#define ARROW_ASSIGN_OR_STOP_IMPL(status_name, lhs, rexpr) \
  auto status_name = (rexpr);                              \
  if (!status_name.status().ok()) {                        \
    Rcpp::stop(status_name.status().ToString());           \
  }                                                        \
  lhs = std::move(status_name).ValueOrDie();

#define ARROW_ASSIGN_OR_STOP(lhs, rexp)                                               \
  ARROW_ASSIGN_OR_STOP_IMPL(ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), \
                            lhs, rexp)

template <typename T>
struct NoDelete {
  inline void operator()(T* ptr) {}
};

namespace Rcpp {
namespace internal {

template <typename Pointer>
Pointer r6_to_smart_pointer(SEXP self) {
  return reinterpret_cast<Pointer>(
      EXTPTR_PTR(Rf_findVarInFrame(self, arrow::r::symbols::xp)));
}

}  // namespace internal

template <typename T>
class ConstReferenceSmartPtrInputParameter {
 public:
  using const_reference = const T&;

  explicit ConstReferenceSmartPtrInputParameter(SEXP self)
      : ptr(internal::r6_to_smart_pointer<const T*>(self)) {}

  inline operator const_reference() { return *ptr; }

 private:
  const T* ptr;
};

namespace traits {

template <typename T>
struct input_parameter<const std::shared_ptr<T>&> {
  typedef typename Rcpp::ConstReferenceSmartPtrInputParameter<std::shared_ptr<T>> type;
};

template <typename T>
struct input_parameter<const std::unique_ptr<T>&> {
  typedef typename Rcpp::ConstReferenceSmartPtrInputParameter<std::unique_ptr<T>> type;
};

struct wrap_type_shared_ptr_tag {};
struct wrap_type_unique_ptr_tag {};

template <typename T>
struct wrap_type_traits<std::shared_ptr<T>> {
  using wrap_category = wrap_type_shared_ptr_tag;
};

template <typename T>
struct wrap_type_traits<std::unique_ptr<T>> {
  using wrap_category = wrap_type_unique_ptr_tag;
};

}  // namespace traits

namespace internal {

template <typename T>
inline SEXP wrap_dispatch(const T& x, Rcpp::traits::wrap_type_shared_ptr_tag);

template <typename T>
inline SEXP wrap_dispatch(const T& x, Rcpp::traits::wrap_type_unique_ptr_tag);

}  // namespace internal
}  // namespace Rcpp

#include <Rcpp.h>

namespace Rcpp {
namespace internal {

template <typename T>
inline SEXP wrap_dispatch(const T& x, Rcpp::traits::wrap_type_shared_ptr_tag) {
  return Rcpp::XPtr<std::shared_ptr<typename T::element_type>>(
      new std::shared_ptr<typename T::element_type>(x));
}

template <typename T>
inline SEXP wrap_dispatch(const T& x, Rcpp::traits::wrap_type_unique_ptr_tag) {
  return Rcpp::XPtr<std::unique_ptr<typename T::element_type>>(
      new std::unique_ptr<typename T::element_type>(const_cast<T&>(x).release()));
}

}  // namespace internal

}  // namespace Rcpp

namespace Rcpp {
using NumericVector_ = Rcpp::Vector<REALSXP, Rcpp::NoProtectStorage>;
using IntegerVector_ = Rcpp::Vector<INTSXP, Rcpp::NoProtectStorage>;
using LogicalVector_ = Rcpp::Vector<LGLSXP, Rcpp::NoProtectStorage>;
using StringVector_ = Rcpp::Vector<STRSXP, Rcpp::NoProtectStorage>;
using CharacterVector_ = StringVector_;
using RawVector_ = Rcpp::Vector<RAWSXP, Rcpp::NoProtectStorage>;
using List_ = Rcpp::Vector<VECSXP, Rcpp::NoProtectStorage>;

template <int RTYPE>
inline constexpr typename Rcpp::Vector<RTYPE>::stored_type default_value() {
  return Rcpp::Vector<RTYPE>::get_na();
}
template <>
inline constexpr Rbyte default_value<RAWSXP>() {
  return 0;
}

}  // namespace Rcpp

namespace arrow {
namespace r {

template <typename T>
inline std::shared_ptr<T> extract(SEXP x) {
  return Rcpp::ConstReferenceSmartPtrInputParameter<std::shared_ptr<T>>(x);
}

}  // namespace r
}  // namespace arrow

#if defined(ARROW_R_WITH_ARROW)
#include <arrow/api.h>
#include <arrow/compute/api.h>
#include <arrow/csv/reader.h>
#include <arrow/filesystem/filesystem.h>
#include <arrow/filesystem/localfs.h>
#include <arrow/io/compressed.h>
#include <arrow/io/file.h>
#include <arrow/io/memory.h>
#include <arrow/ipc/feather.h>
#include <arrow/ipc/reader.h>
#include <arrow/ipc/writer.h>
#include <arrow/json/reader.h>
#include <arrow/type.h>
#include <arrow/util/compression.h>
#include <parquet/arrow/reader.h>
#include <parquet/arrow/writer.h>
#include <parquet/exception.h>

RCPP_EXPOSED_ENUM_NODECL(arrow::Type::type)
RCPP_EXPOSED_ENUM_NODECL(arrow::DateUnit)
RCPP_EXPOSED_ENUM_NODECL(arrow::TimeUnit::type)
RCPP_EXPOSED_ENUM_NODECL(arrow::StatusCode)
RCPP_EXPOSED_ENUM_NODECL(arrow::io::FileMode::type)
RCPP_EXPOSED_ENUM_NODECL(arrow::ipc::Message::Type)
RCPP_EXPOSED_ENUM_NODECL(arrow::Compression::type)
RCPP_EXPOSED_ENUM_NODECL(arrow::fs::FileType)
RCPP_EXPOSED_ENUM_NODECL(parquet::ParquetVersion::type)

SEXP ChunkedArray__as_vector(const std::shared_ptr<arrow::ChunkedArray>& chunked_array);
SEXP Array__as_vector(const std::shared_ptr<arrow::Array>& array);
std::shared_ptr<arrow::Array> Array__from_vector(SEXP x, SEXP type);
std::shared_ptr<arrow::RecordBatch> RecordBatch__from_arrays(SEXP, SEXP);
std::shared_ptr<arrow::RecordBatch> RecordBatch__from_dataframe(Rcpp::DataFrame tbl);

namespace arrow {
namespace r {

Status count_fields(SEXP lst, int* out);

std::shared_ptr<arrow::Array> Array__from_vector(
    SEXP x, const std::shared_ptr<arrow::DataType>& type, bool type_infered);

template <typename T>
std::vector<std::shared_ptr<T>> List_to_shared_ptr_vector(SEXP x) {
  std::vector<std::shared_ptr<T>> vec;
  R_xlen_t n = Rf_xlength(x);
  for (R_xlen_t i = 0; i < n; i++) {
    Rcpp::ConstReferenceSmartPtrInputParameter<std::shared_ptr<T>> ptr(VECTOR_ELT(x, i));
    vec.push_back(ptr);
  }
  return vec;
}

void inspect(SEXP obj);

// the integer64 sentinel
constexpr int64_t NA_INT64 = std::numeric_limits<int64_t>::min();

template <int RTYPE, typename Vec = Rcpp::Vector<RTYPE>>
class RBuffer : public MutableBuffer {
 public:
  explicit RBuffer(Vec vec)
      : MutableBuffer(reinterpret_cast<uint8_t*>(vec.begin()),
                      vec.size() * sizeof(typename Vec::stored_type)),
        vec_(vec) {}

 private:
  // vec_ holds the memory
  Vec vec_;
};

}  // namespace r
}  // namespace arrow

#endif


text:
"use strict";

module.exports = require("./src/adapter");

redpajama_set_name: RedPajamaGithub


text:
#include <media/lirc.h>
#include <media/lirc_dev.h>

/* hardware address */
#define ENE_STATUS		0	 /* hardware status - unused */
#define ENE_ADDR_HI		1	 /* hi byte of register address */
#define ENE_ADDR_LO		2	 /* low byte of register address */
#define ENE_IO			3	 /* read/write window */
#define ENE_MAX_IO		4

/* 8 bytes of samples, divided in 2 halfs*/
#define ENE_SAMPLE_BUFFER	0xF8F0	 /* regular sample buffer */
#define ENE_SAMPLE_SPC_MASK	(1 << 7) /* sample is space */
#define ENE_SAMPLE_VALUE_MASK	0x7F
#define ENE_SAMPLE_OVERFLOW	0x7F
#define ENE_SAMPLES_SIZE	4

/* fan input sample buffer */
#define ENE_SAMPLE_BUFFER_FAN	0xF8FB	 /* this buffer holds high byte of */
					 /* each sample of normal buffer */

#define ENE_FAN_SMPL_PULS_MSK	0x8000	 /* this bit of combined sample */
					 /* if set, says that sample is pulse */
#define ENE_FAN_VALUE_MASK	0x0FFF   /* mask for valid bits of the value */

/* first firmware register */
#define ENE_FW1			0xF8F8
#define	ENE_FW1_ENABLE		(1 << 0) /* enable fw processing */
#define ENE_FW1_TXIRQ		(1 << 1) /* TX interrupt pending */
#define ENE_FW1_WAKE		(1 << 6) /* enable wake from S3 */
#define ENE_FW1_IRQ		(1 << 7) /* enable interrupt */

/* second firmware register */
#define ENE_FW2			0xF8F9
#define ENE_FW2_BUF_HIGH	(1 << 0) /* which half of the buffer to read */
#define ENE_FW2_IRQ_CLR		(1 << 2) /* clear this on IRQ */
#define ENE_FW2_GP40_AS_LEARN	(1 << 4) /* normal input is used as */
					 /* learning input */
#define ENE_FW2_FAN_AS_NRML_IN	(1 << 6) /* fan is used as normal input */
#define ENE_FW2_LEARNING	(1 << 7) /* hardware supports learning and TX */

/* fan as input settings - only if learning capable */
#define ENE_FAN_AS_IN1		0xFE30   /* fan init reg 1 */
#define ENE_FAN_AS_IN1_EN	0xCD
#define ENE_FAN_AS_IN2		0xFE31   /* fan init reg 2 */
#define ENE_FAN_AS_IN2_EN	0x03
#define ENE_SAMPLE_PERIOD_FAN   61	 /* fan input has fixed sample period */

/* IRQ registers block (for revision B) */
#define ENEB_IRQ		0xFD09	 /* IRQ number */
#define ENEB_IRQ_UNK1		0xFD17	 /* unknown setting = 1 */
#define ENEB_IRQ_STATUS		0xFD80	 /* irq status */
#define ENEB_IRQ_STATUS_IR	(1 << 5) /* IR irq */

/* IRQ registers block (for revision C,D) */
#define ENEC_IRQ		0xFE9B	 /* new irq settings register */
#define ENEC_IRQ_MASK		0x0F	 /* irq number mask */
#define ENEC_IRQ_UNK_EN		(1 << 4) /* always enabled */
#define ENEC_IRQ_STATUS		(1 << 5) /* irq status and ACK */

/* CIR block settings */
#define ENE_CIR_CONF1		0xFEC0
#define ENE_CIR_CONF1_ADC_ON	0x7	 /* receiver on gpio40 enabled */
#define ENE_CIR_CONF1_LEARN1	(1 << 3) /* enabled on learning mode */
#define ENE_CIR_CONF1_TX_ON	0x30	 /* enabled on transmit */
#define ENE_CIR_CONF1_TX_CARR	(1 << 7) /* send TX carrier or not */

#define ENE_CIR_CONF2		0xFEC1	 /* unknown setting = 0 */
#define ENE_CIR_CONF2_LEARN2	(1 << 4) /* set on enable learning */
#define ENE_CIR_CONF2_GPIO40DIS	(1 << 5) /* disable normal input via gpio40 */

#define ENE_CIR_SAMPLE_PERIOD	0xFEC8	 /* sample period in us */
#define ENE_CIR_SAMPLE_OVERFLOW	(1 << 7) /* interrupt on overflows if set */

/* transmitter - not implemented yet */
/* KB3926C and higher */
/* transmission is very similar to receiving, a byte is written to */
/* ENE_TX_INPUT, in same manner as it is read from sample buffer */
/* sample period is fixed*/

/* transmitter ports */
#define ENE_TX_PORT1		0xFC01	 /* this enables one or both */
#define ENE_TX_PORT1_EN		(1 << 5) /* TX ports */
#define ENE_TX_PORT2		0xFC08
#define ENE_TX_PORT2_EN		(1 << 1)

#define ENE_TX_INPUT		0xFEC9	 /* next byte to transmit */
#define ENE_TX_SPC_MASK		(1 << 7) /* Transmitted sample is space */
#define ENE_TX_UNK1		0xFECB	 /* set to 0x63 */
#define ENE_TX_SMPL_PERIOD	50	 /* transmit sample period */

#define ENE_TX_CARRIER		0xFECE	 /* TX carrier * 2 (khz) */
#define ENE_TX_CARRIER_UNKBIT	0x80	 /* This bit set on transmit */
#define ENE_TX_CARRIER_LOW	0xFECF	 /* TX carrier / 2 */

/* Hardware versions */
#define ENE_HW_VERSION		0xFF00	 /* hardware revision */
#define ENE_HW_UNK		0xFF1D
#define ENE_HW_UNK_CLR		(1 << 2)
#define ENE_HW_VER_MAJOR	0xFF1E	 /* chip version */
#define ENE_HW_VER_MINOR	0xFF1F
#define ENE_HW_VER_OLD		0xFD00

#define same_sign(a, b) ((((a) > 0) && (b) > 0) || ((a) < 0 && (b) < 0))

#define ENE_DRIVER_NAME		"enecir"
#define ENE_MAXGAP		250000	 /* this is amount of time we wait
					 before turning the sampler, chosen
					 arbitry */

#define space(len)	       (-(len))	 /* add a space */

/* software defines */
#define ENE_IRQ_RX		1
#define ENE_IRQ_TX		2

#define  ENE_HW_B		1	/* 3926B */
#define  ENE_HW_C		2	/* 3926C */
#define  ENE_HW_D		3	/* 3926D */

#define ene_printk(level, text, ...) \
	printk(level ENE_DRIVER_NAME ": " text, ## __VA_ARGS__)

struct ene_device {
	struct pnp_dev *pnp_dev;
	struct lirc_driver *lirc_driver;

	/* hw settings */
	unsigned long hw_io;
	int irq;

	int hw_revision;			/* hardware revision */
	int hw_learning_and_tx_capable;		/* learning capable */
	int hw_gpio40_learning;			/* gpio40 is learning */
	int hw_fan_as_normal_input;	/* fan input is used as regular input */

	/* device data */
	int idle;
	int fan_input_inuse;

	int sample;
	int in_use;

	struct timeval gap_start;
};


text:
/**
 * Module dependencies.
 */

var connect = require('../../lib/connect');

connect.createServer(
    connect.staticProvider(__dirname + '/../public')
).listen(3000);


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Challenge: Write a bouncy window manager)
[#]: via: (https://jvns.ca/blog/2019/11/25/challenge--make-a-bouncy-window-manager/)
[#]: author: (Julia Evans https://jvns.ca/)

Challenge: Write a bouncy window manager
======

Hello! I'm writing a short series of programming challenges with [Julian][1], and this is the first one!

### the challenge

![][2]

**requirements**

The goal here is to make a very silly Linux window manager that bounces its windows around the screen, like in the gif above.

**anti-requirements**

The window manager doesn't need to do anything else! It doesn't need to support:

  * moving or resizing windows
  * switching between windows
  * minimizing windows
  * literally any of the other things you might normally expect a window manager to do

It turns out implementing this kind of toy window manager is surprisingly approachable!

### the setup: start with tinywm

All the instructions here only work on Linux (since this is about writing a Linux window manager).

**starter kit: tinywm**

Writing a window manager from scratch seems intimidating (at first I didn't even know how to start!). But then I found **[tinywm][3]**, which is a tiny window manager written in only **50 lines of C**. This is a GREAT starting point and there's an annotated version of the source code which explains a lot of the details. There's a Python version of tinywm too, but I wasn't able to get it to work.

I did this challenge by modifying [tinywm][3] and it worked really well.

**tools**

  * **Xephyr** lets you embed an X session in a window in your regular desktop, so that you can develop your toy window manager without breaking your usual desktop. I ran it like this: `Xephyr -ac -screen 1280x1024 -br -reset -terminate 2> /dev/null :1 &`
  * You can start an xterm in the Xephyr desktop with `xterm -display :1`
  * I compiled my window manager with `gcc bouncewm.c -g -o bouncewm -lX11` and ran it with `env DISPLAY=:1 ./bouncewm`
  * **xtrace** lets you trace all requests to the X windows system that your window manager is making. I found it really helpful when debugging. (run it like `xtrace ./bouncewm`)

**documentation**

Some useful references:

  * the [dwm source code][4] (dwm is a 2000-line-of-C window manager)
  * the [Xlib programming manual][5]

If you're not comfortable writing C, there are also libraries that let you work with X in other languages. I personally found C easier to use because a lot of the window manager documentation and examples I found were for the Xlib C library.

### my experience: 5 hours, 50 lines of code

To give you a very rough idea of the difficulty of this exercise: I did this in 4 or 5 hours this morning and last night, producing the window manager you see in the gif at the top of the blog post (which is 50 lines of code). I'd never looked at the source code for a window manager before yesterday.

As usual when working with a new library I spent most of that time being confused about various basic things about how X works. (and as a result I learned several new things about X!)

For me this challenge was a fun way to:

  * learn some basics about the X window system protocol (I've been using window managers for 15 years, today I got to write one!)
  * research an unfamiliar library ("ooh, what does this function do?")
  * use a C library, since I don't usually write C

### send me your solution if you do this!

I'll post the solution I came up in a week. If you think this window manager challenge sounds fun and end up doing it, I'd love it if you sent me your solution (to [[email protected]][6])!

I'd be delighted to post any solutions you send me in the solutions blog post.

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

via: https://jvns.ca/blog/2019/11/25/challenge--make-a-bouncy-window-manager/

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

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

[a]: https://jvns.ca/
[b]: https://github.com/lujun9972
[1]: http://www.cipht.net/2017/10/03/are-jump-tables-always-fastest.html
[2]: https://jvns.ca/images/bouncewm.gif
[3]: http://incise.org/tinywm.html
[4]: https://git.suckless.org/dwm/file/dwm.c.html
[5]: https://tronche.com/gui/x/xlib/
[6]: https://jvns.ca/cdn-cgi/l/email-protection


text:
<?php
	class Index extends CoreApp\Controller {

		public function __construct() {
			parent::__construct(__CLASS__);
			$this->loadModel(__CLASS__);
			$this->viewInit("Index", function() {
				$this->view->shops = $this->model->getShops();
				$this->view->products = $this->model->getProducts();
				$this->view->partners = $this->model->getPartners();
			});
		}
	}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
  <!--
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
   -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.sakaiproject.nakamura</groupId>
    <artifactId>base</artifactId>
    <version>1.3-SNAPSHOT</version>
  </parent>
  <artifactId>org.sakaiproject.nakamura.registry</artifactId>
  <packaging>bundle</packaging>
  <name>Sakai Nakamura Registry Bundle</name>
  <description>Registry Service.</description>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-scr-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Bundle-Category> sakai-nakamura </Bundle-Category>
            <Export-Package> org.sakaiproject.nakamura.api.registry, org.sakaiproject.nakamura.api.registry.utils </Export-Package>
            <!--
              WARNING, these had to be excluded from the imports to get the bundle to activate there
              may be classcast exceptions
            -->
            <Import-Package>!sun.misc.*, *
            </Import-Package>
            <Private-Package>org.sakaiproject.nakamura.registry.*</Private-Package>
            <DynamicImport-Package>sun.misc.*</DynamicImport-Package>
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  <dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
  </dependency>
    <dependency>
      <groupId>com.google.code.guice</groupId>
      <artifactId>guice</artifactId>
    </dependency>
    <dependency>
      <groupId>org.sakaiproject.nakamura</groupId>
      <artifactId>org.sakaiproject.nakamura.utils</artifactId>
      <version>1.3-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
  </dependencies>
</project>


text:
package organizations

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/client"
	"github.com/aws/aws-sdk-go/aws/client/metadata"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/aws/signer/v4"
	"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
)

// AWS Organizations is a web service that enables you to consolidate your multiple
// AWS accounts into an organization and centrally manage your accounts and
// their resources.
//
// This guide provides descriptions of the Organizations API. For more information
// about using this service, see the AWS Organizations User Guide (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html).
//
// API Version
//
// This version of the Organizations API Reference documents the Organizations
// API version 2016-11-28.
//
// As an alternative to using the API directly, you can use one of the AWS SDKs,
// which consist of libraries and sample code for various programming languages
// and platforms (Java, Ruby, .NET, iOS, Android, and more). The SDKs provide
// a convenient way to create programmatic access to AWS Organizations. For
// example, the SDKs take care of cryptographically signing requests, managing
// errors, and retrying requests automatically. For more information about the
// AWS SDKs, including how to download and install them, see Tools for Amazon
// Web Services (http://aws.amazon.com/tools/).
//
// We recommend that you use the AWS SDKs to make programmatic API calls to
// Organizations. However, you also can use the Organizations Query API to make
// direct calls to the Organizations web service. To learn more about the Organizations
// Query API, see Making Query Requests (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_query-requests.html)
// in the AWS Organizations User Guide. Organizations supports GET and POST
// requests for all actions. That is, the API does not require you to use GET
// for some actions and POST for others. However, GET requests are subject to
// the limitation size of a URL. Therefore, for operations that require larger
// sizes, use a POST request.
//
// Signing Requests
//
// When you send HTTP requests to AWS, you must sign the requests so that AWS
// can identify who sent them. You sign requests with your AWS access key, which
// consists of an access key ID and a secret access key. We strongly recommend
// that you do not create an access key for your root account. Anyone who has
// the access key for your root account has unrestricted access to all the resources
// in your account. Instead, create an access key for an IAM user account that
// has administrative privileges. As another option, use AWS Security Token
// Service to generate temporary security credentials, and use those credentials
// to sign requests.
//
// To sign requests, we recommend that you use Signature Version 4 (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
// If you have an existing application that uses Signature Version 2, you do
// not have to update it to use Signature Version 4. However, some operations
// now require Signature Version 4. The documentation for operations that require
// version 4 indicate this requirement.
//
// When you use the AWS Command Line Interface (AWS CLI) or one of the AWS SDKs
// to make requests to AWS, these tools automatically sign the requests for
// you with the access key that you specify when you configure the tools.
//
// In this release, each organization can have only one root. In a future release,
// a single organization will support multiple roots.
//
// Support and Feedback for AWS Organizations
//
// We welcome your feedback. Send your comments to feedback-awsorganizations@amazon.com
// (mailto:feedback-awsorganizations@amazon.com) or post your feedback and questions
// in our private AWS Organizations support forum (http://forums.aws.amazon.com/forum.jspa?forumID=219).
// If you don't have access to the forum, send a request for access to the email
// address, along with your forum user ID. For more information about the AWS
// support forums, see Forums Help (http://forums.aws.amazon.com/help.jspa).
//
// Endpoint to Call When Using the CLI or the AWS API
//
// For the current release of Organizations, you must specify the us-east-1
// region for all AWS API and CLI calls. You can do this in the CLI by using
// these parameters and commands:
//
//    * Use the following parameter with each command to specify both the endpoint
//    and its region:
//
// --endpoint-url https://organizations.us-east-1.amazonaws.com
//
//    * Use the default endpoint, but configure your default region with this
//    command:
//
// aws configure set default.region us-east-1
//
//    * Use the following parameter with each command to specify the endpoint:
//
// --region us-east-1
//
// For the various SDKs used to call the APIs, see the documentation for the
// SDK of interest to learn how to direct the requests to a specific endpoint.
// For more information, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region)
// in the AWS General Reference.
//
// How examples are presented
//
// The JSON returned by the AWS Organizations service as response to your requests
// is returned as a single long string without line breaks or formatting whitespace.
// Both line breaks and whitespace are included in the examples in this guide
// to improve readability. When example input parameters also would result in
// long strings that would extend beyond the screen, we insert line breaks to
// enhance readability. You should always submit the input as a single JSON
// text string.
//
// Recording API Requests
//
// AWS Organizations supports AWS CloudTrail, a service that records AWS API
// calls for your AWS account and delivers log files to an Amazon S3 bucket.
// By using information collected by AWS CloudTrail, you can determine which
// requests were successfully made to Organizations, who made the request, when
// it was made, and so on. For more about AWS Organizations and its support
// for AWS CloudTrail, see Logging AWS Organizations Events with AWS CloudTrail
// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_cloudtrail-integration.html)
// in the AWS Organizations User Guide. To learn more about CloudTrail, including
// how to turn it on and find your log files, see the AWS CloudTrail User Guide
// (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html).
// The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
// Please also see https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28
type Organizations struct {
	*client.Client
}

// Used for custom client initialization logic
var initClient func(*client.Client)

// Used for custom request initialization logic
var initRequest func(*request.Request)

// Service information constants
const (
	ServiceName = "organizations" // Service endpoint prefix API calls made to.
	EndpointsID = ServiceName     // Service ID for Regions and Endpoints metadata.
)

// New creates a new instance of the Organizations client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
//     // Create a Organizations client from just a session.
//     svc := organizations.New(mySession)
//
//     // Create a Organizations client with additional configuration
//     svc := organizations.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *Organizations {
	c := p.ClientConfig(EndpointsID, cfgs...)
	return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)
}

// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *Organizations {
	svc := &Organizations{
		Client: client.New(
			cfg,
			metadata.ClientInfo{
				ServiceName:   ServiceName,
				SigningName:   signingName,
				SigningRegion: signingRegion,
				Endpoint:      endpoint,
				APIVersion:    "2016-11-28",
				JSONVersion:   "1.1",
				TargetPrefix:  "AWSOrganizationsV20161128",
			},
			handlers,
		),
	}

	// Handlers
	svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
	svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
	svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
	svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
	svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)

	// Run custom client initialization if present
	if initClient != nil {
		initClient(svc.Client)
	}

	return svc
}

// newRequest creates a new request for a Organizations operation and runs any
// custom request initialization.
func (c *Organizations) newRequest(op *request.Operation, params, data interface{}) *request.Request {
	req := c.NewRequest(op, params, data)

	// Run custom request initialization if present
	if initRequest != nil {
		initRequest(req)
	}

	return req
}


text:
require 'spec_helper'

describe Nature::Service do
  include FakeFS::SpecHelpers

  before(:each) do
    # Bug in FakeFS, we dont need to worry about it here
    File.stub(:chmod)
  end

  describe ".new" do
    it "sets up the class propery" do
      path        = Pathname.new('/etc/sv/test-service')
      cwd         = Pathname.new('/apps/fake_app')
      command     = "cat foo"
      environment = Hash["FOO" => 'bar', "BAZ" => 'bat']

      result = Nature::Service.new(path, :command => command,
                                         :cwd => cwd,
                                         :environment => environment)

      result.cwd.should == '/apps/fake_app'
      result.environment.should == environment
      result.command.should == command

      result.path.should == '/etc/sv/test-service'
      result.active_path.should == '/service'

      result.run_script_path.should == '/etc/sv/test-service/run'
      result.log_script_path.should == '/etc/sv/test-service/log/run'
      result.log_dir.should == '/var/log/test-service'
    end
  end

  it "creates the necessary files and folders" do
    service = Nature::Service.new(Pathname.new('/etc/sv/test-service'), :command => 'ls -lah',
                                                                        :cwd => Pathname.new('/tmp/app'),
                                                                        :environment => {})
    service.create!

    File.exists?(service.run_script_path).should be_true
    File.exists?(service.log_script_path).should be_true
    File.directory?(service.log_dir).should be_true
  end

  it "can symlink the service to make it active" do
    FileUtils.should_receive(:ln_sf).with('/etc/sv/test-service', '/service')
    Nature::Service.new(Pathname.new('/etc/sv/test-service'), :command => 'ls -lah',
                                                              :cwd => Pathname.new('/tmp/app'),
                                                              :environment => {}).activate!
  end
end


text:
Golang API and server for TouchOSC to control Avid™ VENUE software

- <https://www.avid.com/US/products/venue-software>
- <http://hexler.net/software/touchosc>

This software package enables audio engineers to control an Avid™ VENUE system
using a mobile device. The initial version focuses on the workflow of a
monitoring engineer needing to quickly set and maintain levels for multiple
monitor mixes, while having the freedom to stand on the stage with the
performers while doing so.

Although an engineer can always use a VNC client to perform this function,
doing so is cumbersome due to the small UI elements and lack of design for
mobile usage. This software should make that easier.

## Project links

[![GoDoc](https://godoc.org/github.com/kward/venue?status.svg)](https://godoc.org/github.com/kward/venue)
[![Travis CI](https://travis-ci.org/kward/venue.png?branch=master)](https://travis-ci.org/kward/venue)
[![Coverage Status](https://coveralls.io/repos/github/kward/venue/badge.svg?branch=master)](https://coveralls.io/github/kward/venue?branch=master)

Design doc: <https://docs.google.com/document/d/1RZKLrLeaKxsrjHwHxDp2NOQgQHE1-Px-9bGcWrq0g6E/pub>

## Requirements

This software requires ONE of the following:

- A real VENUE console, with remote access via Ethernet (e.g. via an add-on
  Ethernet card).
- A Windows machine running the free [Avid VENUE Software][VENUE], and a VNC
  server to export the display. The Windows instance can easily be run as a
  virtual machine so that a separate physical machine is not required.

Software was tested on the following:

- An [Avid VENUE Profile][Profile] System.
- Windows 7, running on [VMware Fusion][Fusion] (which provides a built-in VNC
  server) on OS X Yosemite.

## Setup

These instructions assume no knowledge of writing software with the Go language.
If you have  experience, feel free to follow your preferred standards.

### Installation

This code is written in Golang (<http://golang.org/>).

1. Install Golang. Follow the instructions at <http://golang.org/doc/install>.
2. Setup environment. Note, the exports must either be run each time the
   software will be used, or they can be added to your `~/.bashrc` file.
   (Examples are for OS X or Linux.)

    ```sh
    $ mkdir -p "${HOME}/opt/go/bin"
    $ export GOPATH="${HOME}/opt/go"
    $ export GOBIN="${GOPATH}/bin"
    $ export PATH="${PATH}:/usr/local/go/bin:${GOBIN}"
    ```

3. Download software.

    ```sh
    $ go get github.com/kward/venue
    $ go get github.com/kward/go-osc
    $ go get github.com/kward/go-vnc
    $ go get github.com/golang/glog
    $ go get github.com/howeyc/gopass
    ```

4. Test the client software. This will "randomly" select an input channel every
   few seconds. It is simply to test that a connection can be made and that the
   console can be controlled.

    ```sh
    $ cd "${GOPATH}/src/github.com/kward/venue"
    $ go run client/rand_inputs/main.go --venue_host <hostname/IP> --venue_passwd <passwd>
    Press CTRL-C to exit.
    ```

5. Install the TouchOSC layout. TODO(kward): Document this.

6. Test the server software. Configure TouchOSC to connect to the hostname/IP
   of your machine (not the host running VENUE).

   ```sh
   $ go run venue.go --venue_host <hostname/IP> --venue_passwd <passwd>
   ```

Notes:

- If you are not using the default VNC port of 5900, the `--venue_port` option
  should be added.
- If you are not using the default TouchOSC port of 8000, the
  `--osc_server_port` option should be added for `venue.go`.

### Updates

To update the software, repeat Installation step 3, with slight modifications.
Here's a simple script to do the updates.

```sh
$ for pkg in \
  github.com/howeyc/gopass \
  github.com/kward/{go-osc,go-vnc,venue}
  github.com/golang/glog
do
  go get -u ${pkg}
done
```

_Avid™ is a registered trademark of Avid, Inc._

<!--- Links -->
[Fusion]: http://www.vmware.com/products/fusion/
[Profile]: https://www.avid.com/US/products/profile-system
[VENUE]: http://www.avid.com/us/products/venue-software


text: python getSubXdatats_eens.py


text:
/* jshint qunit: true */
/* global JSZip,JSZipTestUtils */
'use strict';

QUnit.module("stream", function () {

    QUnit.module("internal");

    test("A stream is pausable", function () {
        // let's get a stream that generates a lot of chunks
        var zip = new JSZip();
        var txt = "a text";
        for(var i = 0; i < 10; i++) {
            zip.file(i + ".txt", txt);
        }

        var allowChunks = true;
        var chunkCount = 0;

        var helper = zip.generateInternalStream({streamFiles:true, type:"binarystring"});
        helper
        .on("data", function () {
            chunkCount++;
            equal(allowChunks, true, "be sure to get chunks only when allowed");
        })
        .on("error", function (e) {
            start();
            ok(false, e.message);
        })
        .on("end", function () {
            start();
        });
        stop();
        helper.resume();
        setTimeout(function () {
            allowChunks = false;
            ok(chunkCount > 0, "the stream emitted at least 1 chunk before pausing it");
            helper.pause();
        }, 10);
        setTimeout(function () {
            allowChunks = true;
            helper.resume();
        }, 40);

    });

    QUnit.module("nodejs");
    if (JSZip.support.nodestream) {
        var fs = require('fs');
    }

    function generateStreamTest(name, ref, createFunction, generateOptions, updateStream) {
        JSZipTestUtils.testZipFile(name,ref, function(expected) {
            stop();

            var tempFile = require('tmp').tmpNameSync({postfix:".zip"});

            var zip = createFunction();

            zip.generateNodeStream(generateOptions)
            .pipe(fs.createWriteStream(tempFile))
            .on("close", function () {
                fs.readFile(tempFile, function (e, data) {
                    var actual = JSZipTestUtils.toString(data);
                    ok(JSZipTestUtils.similar(actual, expected, 3 * JSZipTestUtils.MAX_BYTES_DIFFERENCE_PER_ZIP_ENTRY) , "generated ZIP matches reference ZIP");
                    start();
                    fs.unlink(tempFile);
                });
            })
            .on("error", function (e) {
                ok(false, e.message);
                start();
                fs.unlink(tempFile);
            });
        });
    }
    function zipObjectStreamTest(name, createFunction) {
        test(name, function(assert) {
            var tempFile = require('tmp').tmpNameSync({postfix:".txt"});
            var done = assert.async();
            createFunction().pipe(fs.createWriteStream(tempFile))
            .on("close", function () {
                fs.readFile(tempFile, function (e, data) {
                    var actual = JSZipTestUtils.toString(data);
                    equal(actual, "Hello World\n", "the generated content is ok");
                    done();
                    fs.unlink(tempFile);
                });
            })
            .on("error", function (e) {
                ok(false, e.message);
                done();
                fs.unlink(tempFile);
            });
        });
    }

    if (JSZip.support.nodestream) {

        generateStreamTest(
            "generateNodeStream(type:nodebuffer / !streamFiles) generates a working stream", "ref/all.zip",
            JSZipTestUtils.createZipAll,
            {type:'nodebuffer',streamFiles:false}
        );
        generateStreamTest(
            "generateNodeStream(type:<default> / !streamFiles) generates a working stream", "ref/all.zip",
            JSZipTestUtils.createZipAll,
            {streamFiles:false}
        );
        generateStreamTest(
            "generateNodeStream(<no options>) generates a working stream", "ref/all.zip",
            JSZipTestUtils.createZipAll
        );
        generateStreamTest(
            "generateNodeStream(type:nodebuffer / streamFiles) generates a working stream", "ref/all-stream.zip",
            JSZipTestUtils.createZipAll,
            {type:'nodebuffer',streamFiles:true}
        );
        generateStreamTest(
            "generateNodeStream(type:<default> / streamFiles) generates a working stream", "ref/all-stream.zip",
            JSZipTestUtils.createZipAll,
            {streamFiles:true}
        );

        generateStreamTest(
            "generateNodeStream(type:nodebuffer / !streamFiles) generates a working stream from other streams", "ref/all.zip",
            function () {
                var helloStream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();
                var imgStream = JSZipTestUtils.createZipAll().file("images/smile.gif").nodeStream();
                var zip = new JSZip();
                zip.file("Hello.txt", helloStream);
                zip.folder("images").file("smile.gif", imgStream);

                return zip;
            },
            {type:'nodebuffer',streamFiles:false}
        );
        generateStreamTest(
            "generateNodeStream(type:nodebuffer / streamFiles) generates a working stream from other streams", "ref/all-stream.zip",
            function () {
                var helloStream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();
                var imgStream = JSZipTestUtils.createZipAll().file("images/smile.gif").nodeStream();
                var zip = new JSZip();
                zip.file("Hello.txt", helloStream);
                zip.folder("images").file("smile.gif", imgStream);

                return zip;
            },
            {type:'nodebuffer',streamFiles:true}
        );

        zipObjectStreamTest("ZipObject#nodeStream generates a working stream[nodebuffer]", function() {
            var zip = JSZipTestUtils.createZipAll();
            return zip.file("Hello.txt").nodeStream('nodebuffer');
        });
        zipObjectStreamTest("ZipObject#nodeStream generates a working stream[default]", function() {
            var zip = JSZipTestUtils.createZipAll();
            return zip.file("Hello.txt").nodeStream();
        });

        test("a ZipObject containing a stream can be read with async", function(assert) {
            var done = assert.async();
            var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();
            var zip = new JSZip();
            zip.file("Hello.txt", stream);
            zip.file("Hello.txt").async("text").then(function(actual) {
                equal(actual, "Hello World\n", "the stream has been read correctly");
                done();
            })['catch'](JSZipTestUtils.assertNoError);
        });

        test("a ZipObject containing a stream can't be read with async 2 times", function(assert) {
            var done = assert.async();

            var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();
            var zip = new JSZip();
            zip.file("Hello.txt", stream);

            // first time, consume the node stream
            zip.file("Hello.txt").async("text");
            // second time, it shouldn't work
            zip.file("Hello.txt").async("text")
            .then(function ok(data) {
                assert.ok(false, "calling 2 times a stream should generate an error");
                done();
            }, function ko(e) {
                assert.ok(e.message.match("has already been used"), "the error message is useful");
                done();
            });
        });

        test("a ZipObject containing a stream can't be read with nodeStream 2 times", function(assert) {
            var done = assert.async();

            var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();
            var zip = new JSZip();
            zip.file("Hello.txt", stream);

            // first time, consume the node stream
            zip.file("Hello.txt").nodeStream().resume();
            // second time, it shouldn't work
            zip.file("Hello.txt").nodeStream()
            .on("error", function (e) {
                assert.ok(e.message.match("has already been used"), "the error message is useful");
                done();
            })
            .on ("end", function () {
                assert.ok(false, "calling 2 times a stream should generate an error");
                done();
            })
            .resume();
        });

        test("generateAsync with a stream can't be read 2 times", function(assert) {
            var done = assert.async();

            var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();
            var zip = new JSZip();
            zip.file("Hello.txt", stream);

            // first time, consume the node stream
            zip.generateAsync({type:"string"});
            // second time, it shouldn't work
            zip.generateAsync({type:"string"})
            .then(function ok(data) {
                assert.ok(false, "calling 2 times a stream should generate an error");
                done();
            }, function ko(e) {
                assert.ok(e.message.match("has already been used"), "the error message is useful");
                done();
            });
        });

        test("generateNodeStream with a stream can't be read 2 times", function(assert) {
            var done = assert.async();

            var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();
            var zip = new JSZip();
            zip.file("Hello.txt", stream);

            // first time, consume the node stream
            zip.generateNodeStream().resume();
            // second time, it shouldn't work
            zip.generateNodeStream()
            .on("error", function (e) {
                assert.ok(e.message.match("has already been used"), "the error message is useful");
                done();
            })
            .on ("end", function () {
                assert.ok(false, "calling 2 times a stream should generate an error");
                done();
            })
            .resume();
        });

        test("loadAsync ends with an error when called with a stream", function(assert) {
            var done = assert.async();
            var stream = JSZipTestUtils.createZipAll().generateNodeStream({"type":"nodebuffer"});
            JSZip.loadAsync(stream).then(function () {
                assert.ok(false, "loading a zip file from a stream is impossible");
                done();
            }, function (e) {
                assert.ok(e.message.match("can't accept a stream when loading"), "the error message is useful");
                done();
            });

        });

    } else {
        test("generateNodeStream generates an error", function(assert) {
            try {
                var zip = new JSZip();
                zip.generateNodeStream({type:'nodebuffer',streamFiles:true});
                assert.ok(false, "generateNodeStream should generate an error");
            } catch(err) {
                assert.ok(err.message.match("not supported by this platform"), "the error message is useful");
            }
        });

        test("ZipObject#nodeStream generates an error", function(assert) {
            try {
                var zip = JSZipTestUtils.createZipAll();
                zip.file("Hello.txt").nodeStream('nodebuffer');
                assert.ok(false, "nodeStream should generate an error");
            } catch(err) {
                assert.ok(err.message.match("not supported by this platform"), "the error message is useful");
            }
        });
    }
});


text:
<!DOCTYPE html>
<html lang="en" class="mdl-js">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title><%= APP_TITLE %></title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://storage.googleapis.com/code.getmdl.io/1.0.4/material.min.js"></script>
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700" type="text/css">

  <!-- inject:css -->
  <link rel="stylesheet" href="node_modules/ng2-material/dist/ng2-material.css">
  <link rel="stylesheet" href="node_modules/ng2-material/dist/font.css">
  <!-- endinject -->

</head>
<body class="no-sidebar">
<app></app>

<!-- shims:js -->
<!-- endinject -->

<script>System.config(<%= JSON.stringify(SYSTEM_CONFIG) %>)</script>

<!-- libs:js -->
<script src="node_modules/webcamjs/webcam.js"></script>
<!-- endinject -->

<script>
  System.import('bootstrap')
    .catch(function (e) {
      console.error(e,
        'Report this error at https://github.com/mgechev/angular2-seed/issues');
    });
</script>

<!-- inject:js -->
<!-- endinject -->
</body>
</html>


text:
require 'rest-client'
require 'cgi'
require 'json'
require 'fyber/errors'
require 'fyber/offers'

module Fyber
  class Client
    include Fyber::Offers

    API_URL = 'http://api.sponsorpay.com/feed'
    API_VERSION = 1

    attr_accessor :logger, :api_key, :appid, :format, :locale, :ip, :device

    def initialize(options = {})
      configurables.each do |key|
        # issue an error for missing parameters unless they're optional
        check_required_parameter(key, options[key]) unless [:format, :locale].include?(key)
        instance_variable_set(:"@#{key}", options[key])
      end
    end

    def get(endpoint, params)
      uri = api_uri(endpoint)
      log("GET #{uri} parameters: #{parameters(params)}")
      begin
        response = RestClient.get(uri, params: parameters(params))
      rescue => e
        raise Fyber::ServerError, e.message
      end
      response
    end

    private
      def api_uri(endpoint)
        "#{API_URL}/v#{API_VERSION}/#{endpoint}.#{format}"
      end

      def parameters(list = {})
        configurables.each do |key|
          list[key] = instance_variable_get(:"@#{key}") unless key == :format
        end
        # sort alphabetically
        list = Hash[list.sort]
        params_string = list.collect { |k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}" }.join('&')
        params_string = "#{params_string}&#{api_key}"
        list[:hashkey] = Digest::SHA1.hexdigest(params_string)
        list
      end

      def configurables
        [:api_key, :appid, :format, :locale, :ip, :device]
      end

      # Standardize error behavior across all client methods
      def check_required_parameter(key, value)
        if value.nil?
          raise Fyber::ClientError, "Required parameter not set: #{key.to_s}"
        end
      end

      def log(message)
        logger.info message
      end

      def logger
        @logger ||= ::Logger.new(STDOUT)
      end

      def logger=(logger)
        @logger = logger
      end

      # default configuration
      def format
        @format || :json
      end

      def locale
        @locale || :de
      end
  end
end


text:
package sshagent

// see https://github.com/Yasushi/putty/blob/master/windows/winpgntc.c#L155
// see https://github.com/paramiko/paramiko/blob/master/paramiko/win_pageant.py

import (
	"encoding/binary"
	"errors"
	"fmt"
	"sync"
	"syscall"
	"unsafe"
)

// Maximum size of message can be sent to pageant
const MaxMessageLen = 8192

var (
	ErrPageantNotFound = errors.New("pageant process not found")
	ErrSendMessage     = errors.New("error sending message")

	ErrMessageTooLong       = errors.New("message too long")
	ErrInvalidMessageFormat = errors.New("invalid message format")
	ErrResponseTooLong      = errors.New("response too long")
)

const (
	agentCopydataID = 0x804e50ba
	wmCopydata      = 74
)

type copyData struct {
	dwData uintptr
	cbData uint32
	lpData unsafe.Pointer
}

var (
	lock sync.Mutex

	winFindWindow         = winAPI("user32.dll", "FindWindowW")
	winGetCurrentThreadID = winAPI("kernel32.dll", "GetCurrentThreadId")
	winSendMessage        = winAPI("user32.dll", "SendMessageW")
)

func winAPI(dllName, funcName string) func(...uintptr) (uintptr, uintptr, error) {
	proc := syscall.MustLoadDLL(dllName).MustFindProc(funcName)
	return func(a ...uintptr) (uintptr, uintptr, error) { return proc.Call(a...) }
}

// Query sends message msg to Pageant and returns response or error.
// 'msg' is raw agent request with length prefix
// Response is raw agent response with length prefix
func query(msg []byte) ([]byte, error) {
	if len(msg) > MaxMessageLen {
		return nil, ErrMessageTooLong
	}

	msgLen := binary.BigEndian.Uint32(msg[:4])
	if len(msg) != int(msgLen)+4 {
		return nil, ErrInvalidMessageFormat
	}

	lock.Lock()
	defer lock.Unlock()

	paWin := pageantWindow()

	if paWin == 0 {
		return nil, ErrPageantNotFound
	}

	thID, _, _ := winGetCurrentThreadID()
	mapName := fmt.Sprintf("PageantRequest%08x", thID)
	pMapName, _ := syscall.UTF16PtrFromString(mapName)

	mmap, err := syscall.CreateFileMapping(syscall.InvalidHandle, nil, syscall.PAGE_READWRITE, 0, MaxMessageLen+4, pMapName)
	if err != nil {
		return nil, err
	}
	defer syscall.CloseHandle(mmap)

	ptr, err := syscall.MapViewOfFile(mmap, syscall.FILE_MAP_WRITE, 0, 0, 0)
	if err != nil {
		return nil, err
	}
	defer syscall.UnmapViewOfFile(ptr)

	mmSlice := (*(*[MaxMessageLen]byte)(unsafe.Pointer(ptr)))[:]

	copy(mmSlice, msg)

	mapNameBytesZ := append([]byte(mapName), 0)

	cds := copyData{
		dwData: agentCopydataID,
		cbData: uint32(len(mapNameBytesZ)),
		lpData: unsafe.Pointer(&(mapNameBytesZ[0])),
	}

	resp, _, _ := winSendMessage(paWin, wmCopydata, 0, uintptr(unsafe.Pointer(&cds)))

	if resp == 0 {
		return nil, ErrSendMessage
	}

	respLen := binary.BigEndian.Uint32(mmSlice[:4])
	if respLen > MaxMessageLen-4 {
		return nil, ErrResponseTooLong
	}

	respData := make([]byte, respLen+4)
	copy(respData, mmSlice)

	return respData, nil
}

func pageantWindow() uintptr {
	nameP, _ := syscall.UTF16PtrFromString("Pageant")
	h, _, _ := winFindWindow(uintptr(unsafe.Pointer(nameP)), uintptr(unsafe.Pointer(nameP)))
	return h
}


text:
require 'spec_helper'

describe Dandelion::Deployer do
  let(:adapter) { double('adapter') }
  let(:deployer) { Dandelion::Deployer.new(adapter) }

  describe '#deploy_changeset!' do
    let(:changeset) {[
      double(path: 'foo', data: 'bar', type: :write),
      double(path: 'bar/baz', data: 'baz', type: :write),
      double(path: 'qux', type: :delete)
    ]}

    it 'perfoms writes and deletions on adapter' do
      expect(adapter).to receive(:write).with('foo', 'bar')
      expect(adapter).to receive(:write).with('bar/baz', 'baz')
      expect(adapter).to receive(:delete).with('qux')

      deployer.deploy_changeset!(changeset)
    end

    context 'excluded' do
      let(:deployer) { Dandelion::Deployer.new(adapter, exclude: ['foo']) }

      it 'perfoms writes and deletions on adapter' do
        expect(adapter).to receive(:write).with('bar/baz', 'baz')
        expect(adapter).to receive(:delete).with('qux')

        deployer.deploy_changeset!(changeset)
      end
    end
  end

  describe '#deploy_files!' do
    before(:each) do
      allow(IO).to receive(:binread).with('a.txt').and_return('A')
      allow(IO).to receive(:binread).with('b.txt').and_return('B')
      allow(IO).to receive(:binread).with('c/a.txt').and_return('cA')
      allow(IO).to receive(:binread).with('c/b.txt').and_return('cB')
    end

    context 'local paths' do
      let(:files) { ['a.txt', 'b.txt'] }

      it 'performs writes on adapter' do
        expect(adapter).to receive(:write).with('a.txt', 'A')
        expect(adapter).to receive(:write).with('b.txt', 'B')

        deployer.deploy_files!(files)
      end
    end

    context 'local and remote paths' do
      let(:files) {[
        { 'a.txt' => 'files/a.txt' },
        { 'b.txt' => 'files/b.txt' }
      ]}

      it 'performs writes on adapter' do
        expect(adapter).to receive(:write).with('files/a.txt', 'A')
        expect(adapter).to receive(:write).with('files/b.txt', 'B')

        deployer.deploy_files!(files)
      end
    end

    context 'directory' do
      let(:files) {[
        { 'c/' => 'C/' }
      ]}

      before(:each) do
        allow(File).to receive(:directory?).with('c/').and_return(true)
        allow(File).to receive(:directory?).with('c/a.txt').and_return(false)
        allow(File).to receive(:directory?).with('c/b.txt').and_return(false)
        allow(Dir).to receive(:glob).with('c/**/*').and_return(['c/a.txt', 'c/b.txt'])
      end

      it 'performs writes on adapter' do
        expect(adapter).to receive(:write).with('C/a.txt', 'cA')
        expect(adapter).to receive(:write).with('C/b.txt', 'cB')

        deployer.deploy_files!(files)
      end
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Linn. Soc. London 158: 33 (1947)

#### Original name
Meliola maesopsidis Hansf.

### Remarks
null


text:
<?php

class LanguageTranslator
    {
        // this is the API endpoint, as specified by Google
        const ENDPOINT = 'https://www.googleapis.com/language/translate/v2';
        const ENDPOINTDETECT = 'https://www.googleapis.com/language/translate/v2/detect';
        const ENDPOINTLANG = 'https://www.googleapis.com/language/translate/v2/languages';

        // holder for you API key, specified when an instance is created
        protected $_apiKey;
        public $languages;

        // constructor, accepts Google API key as its only argument
        public function __construct($apiKey)
        {
            $this->_apiKey = $apiKey;
            $this->languages = $this->languages();
        }

        public function detect($data){
            if (strlen($data) >= 100){
                $length = 100;
            }else{
                $length = strlen($data);
            }
            $small_data = substr($data, 0, $length);
            $values = array(
                'key'    => $this->_apiKey,
                'q'      => $small_data
            );
            $language = 'en';
            // turn the form data array into raw format so it can be used with cURL
            $formData = http_build_query($values);

            // create a connection to the API endpoint
            $ch = curl_init(self::ENDPOINTDETECT);

            // tell cURL to return the response rather than outputting it
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            //for the problems of SSL
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            // write the form data to the request in the post body
            curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);

            // include the header to make Google treat this post request as a get request
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));

            // execute the HTTP request
            $json = curl_exec($ch);

            curl_close($ch);

            // decode the response data
            $data = json_decode($json, true);
            // ensure the returned data is valid
            if (!is_array($data) || !array_key_exists('data', $data)) {
                throw new Exception('Unable to find data key');
            }

            // ensure the returned data is valid
            if (!array_key_exists('detections', $data['data'])) {
                throw new Exception('Unable to find detections key');
            }

            if (!is_array($data['data']['detections'])) {
                throw new Exception('Expected array for detections');
            }
            // loop over the translations and return the first one.
            // if you wanted to handle multiple translations in a single call
            // you would need to modify how this returns data
            $conf = $data['data']['detections'][0][0]['confidence'];
            foreach ($data['data']['detections'] as $detection) {
                if ($detection[0]['confidence'] >= $conf){
                    $conf = $detection[0]['confidence'];
                    $language = $detection[0]['language'];
                }
            }
            return $language;
            // assume failure since success would've returned just above
            throw new Exception('Translation failed');

        }
        public function getLanguageName($language){
            $languages = array();
            $values = array(
                'key'    => $this->_apiKey,
                'target' => 'en'
            );

            // turn the form data array into raw format so it can be used with cURL
            $formData = http_build_query($values);

            // create a connection to the API endpoint
            $ch = curl_init(self::ENDPOINTLANG);

            // tell cURL to return the response rather than outputting it
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            //for the problems of SSL
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            // write the form data to the request in the post body
            curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);

            // include the header to make Google treat this post request as a get request
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));

            // execute the HTTP request
            $json = curl_exec($ch);

            curl_close($ch);

            // decode the response data
            $data = json_decode($json, true);
            // ensure the returned data is valid
            if (!is_array($data) || !array_key_exists('data', $data)) {
                throw new Exception('Unable to find data key');
            }else{
                $languages = $data['data']['languages'];
                foreach ($languages as $full_lang){
                    if ($full_lang['language'] == $language){
                        return $full_lang['name'];
                    }
                }
            }
        }
        public function languages(){
            $languages = array();
            $values = array(
                'key'    => $this->_apiKey
            );

            // turn the form data array into raw format so it can be used with cURL
            $formData = http_build_query($values);

            // create a connection to the API endpoint
            $ch = curl_init(self::ENDPOINTLANG);

            // tell cURL to return the response rather than outputting it
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            //for the problems of SSL
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            // write the form data to the request in the post body
            curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);

            // include the header to make Google treat this post request as a get request
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));

            // execute the HTTP request
            $json = curl_exec($ch);

            curl_close($ch);

            // decode the response data
            $data = json_decode($json, true);
            // ensure the returned data is valid
            if (!is_array($data) || !array_key_exists('data', $data)) {
                throw new Exception('Unable to find data key');
            }else{
                foreach ($data['data']['languages'] as $language) {
                    $languages[] = $language['language'];
                }
                return $languages;
            }
        }

        // translate the text/html in $data. Translates to the language
        // in $target. Can optionally specify the source language
        public function translate($data, $target, $source = ''){
            if (!$source || !in_array($source, $this->languages)){
                return -1;
            }
            // this is the form data to be included with the request
            $values = array(
                'key'    => $this->_apiKey,
                'target' => $target,
                'q'      => $data
            );
            // only include the source data if it's been specified
            if (strlen($source) > 0) {
                $values['source'] = $source;
            }

            // turn the form data array into raw format so it can be used with cURL
            $formData = http_build_query($values);

            // create a connection to the API endpoint
            $ch = curl_init(self::ENDPOINT);

            // tell cURL to return the response rather than outputting it
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            //for the problems of SSL
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            // write the form data to the request in the post body
            curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);

            // include the header to make Google treat this post request as a get request
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));

            // execute the HTTP request
            $json = curl_exec($ch);
            curl_close($ch);

            // decode the response data
            $data = json_decode($json, true);
            // ensure the returned data is valid
            if (!is_array($data) || !array_key_exists('data', $data)) {

                throw new Exception('Unable to find data key');
            }

            // ensure the returned data is valid
            if (!array_key_exists('translations', $data['data'])) {
                throw new Exception('Unable to find translations key');
            }

            if (!is_array($data['data']['translations'])) {
                throw new Exception('Expected array for translations');
            }

            // loop over the translations and return the first one.
            // if you wanted to handle multiple translations in a single call
            // you would need to modify how this returns data
            foreach ($data['data']['translations'] as $translation) {
                return $translation['translatedText'];
            }

            // assume failure since success would've returned just above
            throw new Exception('Translation failed');
        }
    }
?>


text:
import AppCollection from "./app-collection";
import Employee from "../models/employee";

const Employees = AppCollection.extend( {
	model: Employee,
	url() {
		return `${ this.baseURL }employees`;
	}
} );

export default Employees;


text:
package trees_and_graphs;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static trees_and_graphs.BinaryNode.*;
import static trees_and_graphs.BinaryNode.leafOf;

/**
 * Created by mjhamrick on 12/24/16.
 */
public class _5Test {

    @Test
    public void test() {

        BinaryNode<Integer> tree = _2.bstFromSortedArray(new Integer[]{1, 2, 3, 4, 5, 6});
        assertTrue(_5.isBinarySearchTreeNoDupes(tree));
        assertTrue(_5.isBSTWithDupes(tree));
        assertFalse(_5.isBSTWithDupes(treeOf(leafOf(3), 4, leafOf(4))));
    }
}


text:
package spn

import (
	"bytes"
	"fmt"
	"github.com/RenatoGeh/gospn/utils"
)

// Indicator is an indicator node of a variable value X=x. Its value is 1 if X=x or is not set, and
// 0 otherwise.
type Indicator struct {
	Node
	// Variable ID
	varid int
	// Value of variable
	v int
}

// NewIndicator constructs a new indicator node.
func NewIndicator(varid int, v int) *Indicator {
	return &Indicator{Node{nil, []int{varid}}, varid, v}
}

// Type returns the type of this node.
func (i *Indicator) Type() string { return "leaf" }

// Value returns the probability of a certain valuation. In the case of an indicator node, 1 if X=x
// or is not set and 0 otherwise.
func (i *Indicator) Value(val VarSet) float64 {
	u, e := val[i.varid]
	if !e || u == i.v {
		return 0
	}
	return utils.LogZero
}

// Max returns the MAP.
func (i *Indicator) Max(val VarSet) float64 {
	u, e := val[i.varid]
	if !e || u == i.v {
		return 0
	}
	return utils.LogZero
}

// ArgMax returns the MAP and the MAP state.
func (i *Indicator) ArgMax(val VarSet) (VarSet, float64) {
	retval := make(VarSet)
	u, e := val[i.varid]
	if !e || u == i.v {
		retval[i.varid] = u
		return retval, 0
	}
	return retval, utils.LogZero
}

// Sc returns the scope of this node.
func (i *Indicator) Sc() []int {
	if len(i.sc) == 0 {
		i.sc = []int{i.varid}
	}
	return i.sc
}

func (i *Indicator) GobEncode() ([]byte, error) {
	var b bytes.Buffer
	fmt.Fprintln(&b, i.varid, i.v)
	return b.Bytes(), nil
}

func (i *Indicator) GobDecode(data []byte) error {
	b := bytes.NewBuffer(data)
	_, err := fmt.Fscanf(b, "%d %d", &i.varid, &i.v)
	return err
}


text:
package org.apache.vxquery.datamodel.accessors;

import org.apache.hyracks.data.std.util.ArrayBackedValueStorage;

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

public class ArrayBackedValueStoragePool {
    private final List<ArrayBackedValueStorage> abvsList;

    public ArrayBackedValueStoragePool() {
        abvsList = new ArrayList<>();
    }

    public ArrayBackedValueStorage takeOne() {
        if (abvsList.isEmpty()) {
            return new ArrayBackedValueStorage();
        }
        return abvsList.remove(abvsList.size() - 1);
    }

    public void giveBack(ArrayBackedValueStorage abvs) {
        abvsList.add(abvs);
    }
}


text:
layout: page
title: 关于
permalink: /about/
icon: heart
type: page
---

* content
{:toc}

## 关于我

## 联系我
* GitHub:[graphnj](https://github.com/graphnj)

## 关于本站
** 若您想使用这个 jekyll 博客主题,请访问:[https://github.com/Gaohaoyang/gaohaoyang.github.io](https://github.com/Gaohaoyang/gaohaoyang.github.io)**
## 友情链接
:[https://github.com/Gaohaoyang/gaohaoyang.github.io](https://github.com/Gaohaoyang/gaohaoyang.github.io)
## Comments

{% include comments.html %}


text:
@import url(http://fonts.googleapis.com/css?family=Londrina+Solid);
* {
padding: 0;
margin: 0;
}
body, html {
width: 100%;
background-size: 100px 100px;
font-family: "Londrina Solid";
font-size: 12px;
text-align: right;
}
.btn, .btnm {
letter-spacing:1px;
font-family: "Londrina Solid";
background-color: rgba(0, 0, 0, 0.5) ;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-o-border-radius: 5px;
-ms-border-radius: 5px;
border: 0;
padding: 5px 8px;
color: #eee;
margin: 1px;
font-size: 12px;
-webkit-appearance: none;
}
.btn:hover {
background-color: rgba(0, 0, 0, 0.6);
}
.btn:active {
background-color: rgba(0, 0, 0, 0.7);
}
.btnm {
display: inline-block;
border-bottom-left-radius: 20px;
border-top-left-radius: 20px;
-webkit-border-bottom-left-radius: 20px;
-webkit-border-top-left-radius: 20px;
-moz-border-bottom-left-radius: 20px;
-moz-border-top-left-radius: 20px;
-o-border-bottom-left-radius: 20px;
-o-border-top-left-radius: 20px;
-ms-border-bottom-left-radius: 20px;
-ms-border-top-left-radius: 20px;
}


text:
package com.daedafusion.security.audit.providers;

import com.daedafusion.sf.Provider;
import com.daedafusion.security.audit.Audit;

/**
 * Created by mphilpot on 8/12/14.
 */
public interface AuditProvider extends Provider, Audit
{

}


text:
using System.Linq;
using Content.Shared.Construction;
using Robust.Server.Containers;
using Robust.Shared.Containers;

namespace Content.Server.Construction.Completions
{
    [DataDefinition]
    public sealed class DeleteEntitiesInContainer : IGraphAction
    {
        [DataField("container")] public string Container { get; } = string.Empty;

        public void PerformAction(EntityUid uid, EntityUid? userUid, IEntityManager entityManager)
        {
            if (string.IsNullOrEmpty(Container))
                return;
            var containerSys = entityManager.EntitySysManager.GetEntitySystem<ContainerSystem>();

            if (!containerSys.TryGetContainer(uid, Container, out var container))
                return;

            foreach (var contained in container.ContainedEntities.ToArray())
            {
                if(container.Remove(contained))
                    entityManager.QueueDeleteEntity(contained);
            }
        }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
using Umbraco.Web.PropertyEditors.Validation;

namespace Umbraco.Web.PropertyEditors
{

    /// <summary>
    /// Represents a nested content property editor.
    /// </summary>
    [DataEditor(
        Constants.PropertyEditors.Aliases.NestedContent,
        "Nested Content",
        "nestedcontent",
        ValueType = ValueTypes.Json,
        Group = Constants.PropertyEditors.Groups.Lists,
        Icon = "icon-thumbnail-list")]
    public class NestedContentPropertyEditor : DataEditor
    {
        private readonly Lazy<PropertyEditorCollection> _propertyEditors;
        private readonly IDataTypeService _dataTypeService;
        private readonly IContentTypeService _contentTypeService;
        private readonly ILocalizedTextService _localizedTextService;
        internal const string ContentTypeAliasPropertyKey = "ncContentTypeAlias";

        [Obsolete("Use the constructor specifying all parameters instead")]
        public NestedContentPropertyEditor(ILogger logger, Lazy<PropertyEditorCollection> propertyEditors, IDataTypeService dataTypeService, IContentTypeService contentTypeService)
            : this(logger, propertyEditors, dataTypeService, contentTypeService, Current.Services.TextService) { }

        public NestedContentPropertyEditor(ILogger logger, Lazy<PropertyEditorCollection> propertyEditors, IDataTypeService dataTypeService, IContentTypeService contentTypeService, ILocalizedTextService localizedTextService)
            : base (logger)
        {
            _propertyEditors = propertyEditors;
            _dataTypeService = dataTypeService;
            _contentTypeService = contentTypeService;
            _localizedTextService = localizedTextService;
        }

        // has to be lazy else circular dep in ctor
        private PropertyEditorCollection PropertyEditors => _propertyEditors.Value;

        #region Pre Value Editor

        protected override IConfigurationEditor CreateConfigurationEditor() => new NestedContentConfigurationEditor();

        #endregion

        #region Value Editor

        protected override IDataValueEditor CreateValueEditor() => new NestedContentPropertyValueEditor(Attribute, PropertyEditors, _dataTypeService, _contentTypeService, _localizedTextService, Logger);

        internal class NestedContentPropertyValueEditor : DataValueEditor, IDataValueReference
        {
            private readonly PropertyEditorCollection _propertyEditors;
            private readonly IDataTypeService _dataTypeService;
            private readonly ILogger _logger;
            private readonly NestedContentValues _nestedContentValues;

            public NestedContentPropertyValueEditor(DataEditorAttribute attribute, PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IContentTypeService contentTypeService, ILocalizedTextService textService, ILogger logger)
                : base(attribute)
            {
                _propertyEditors = propertyEditors;
                _dataTypeService = dataTypeService;
                _logger = logger;
                _nestedContentValues = new NestedContentValues(contentTypeService);
                Validators.Add(new NestedContentValidator(_nestedContentValues, propertyEditors, dataTypeService, textService));
            }

            /// <inheritdoc />
            public override object Configuration
            {
                get => base.Configuration;
                set
                {
                    if (value == null)
                        throw new ArgumentNullException(nameof(value));
                    if (!(value is NestedContentConfiguration configuration))
                        throw new ArgumentException($"Expected a {typeof(NestedContentConfiguration).Name} instance, but got {value.GetType().Name}.", nameof(value));
                    base.Configuration = value;

                    HideLabel = configuration.HideLabel.TryConvertTo<bool>().Result;
                }
            }

            #region DB to String

            public override string ConvertDbToString(PropertyType propertyType, object propertyValue, IDataTypeService dataTypeService)
            {
                var rows = _nestedContentValues.GetPropertyValues(propertyValue);

                if (rows.Count == 0)
                    return string.Empty;

                foreach (var row in rows.ToList())
                {
                    foreach(var prop in row.PropertyValues.ToList())
                    {
                        try
                        {
                            // convert the value, and store the converted value
                            var propEditor = _propertyEditors[prop.Value.PropertyType.PropertyEditorAlias];
                            if (propEditor == null) continue;

                            var tempConfig = dataTypeService.GetDataType(prop.Value.PropertyType.DataTypeId).Configuration;
                            var valEditor = propEditor.GetValueEditor(tempConfig);
                            var convValue = valEditor.ConvertDbToString(prop.Value.PropertyType, prop.Value.Value, dataTypeService);

                            // update the raw value since this is what will get serialized out
                            row.RawPropertyValues[prop.Key] = convValue;
                        }
                        catch (InvalidOperationException ex)
                        {
                            // deal with weird situations by ignoring them (no comment)
                            row.RawPropertyValues.Remove(prop.Key);
                            _logger.Warn<NestedContentPropertyValueEditor>(
                                ex,
                                "ConvertDbToString removed property value {PropertyKey} in row {RowId} for property type {PropertyTypeAlias}",
                                prop.Key, row.Id, propertyType.Alias);
                        }
                    }
                }

                return JsonConvert.SerializeObject(rows).ToXmlString<string>();
            }

            #endregion

            #region Convert database // editor

            // note: there is NO variant support here

            /// <summary>
            /// Ensure that sub-editor values are translated through their ToEditor methods
            /// </summary>
            /// <param name="property"></param>
            /// <param name="dataTypeService"></param>
            /// <param name="culture"></param>
            /// <param name="segment"></param>
            /// <returns></returns>
            public override object ToEditor(Property property, IDataTypeService dataTypeService, string culture = null, string segment = null)
            {
                var val = property.GetValue(culture, segment);

                var rows = _nestedContentValues.GetPropertyValues(val);

                if (rows.Count == 0)
                    return string.Empty;

                foreach (var row in rows.ToList())
                {
                    foreach(var prop in row.PropertyValues.ToList())
                    {
                        try
                        {
                            // create a temp property with the value
                            // - force it to be culture invariant as NC can't handle culture variant element properties
                            prop.Value.PropertyType.Variations = ContentVariation.Nothing;
                            var tempProp = new Property(prop.Value.PropertyType);

                            tempProp.SetValue(prop.Value.Value);

                            // convert that temp property, and store the converted value
                            var propEditor = _propertyEditors[prop.Value.PropertyType.PropertyEditorAlias];
                            if (propEditor == null)
                            {
                                // update the raw value since this is what will get serialized out
                                row.RawPropertyValues[prop.Key] = tempProp.GetValue()?.ToString();
                                continue;
                            }

                            var tempConfig = dataTypeService.GetDataType(prop.Value.PropertyType.DataTypeId).Configuration;
                            var valEditor = propEditor.GetValueEditor(tempConfig);
                            var convValue = valEditor.ToEditor(tempProp, dataTypeService);

                            // update the raw value since this is what will get serialized out
                            row.RawPropertyValues[prop.Key] = convValue == null ? null : JToken.FromObject(convValue);
                        }
                        catch (InvalidOperationException ex)
                        {
                            // deal with weird situations by ignoring them (no comment)
                            row.RawPropertyValues.Remove(prop.Key);
                            _logger.Warn<NestedContentPropertyValueEditor>(
                                ex,
                                "ToEditor removed property value {PropertyKey} in row {RowId} for property type {PropertyTypeAlias}",
                                prop.Key, row.Id, property.PropertyType.Alias);
                        }
                    }
                }

                // return the object, there's a native json converter for this so it will serialize correctly
                return rows;
            }

            /// <summary>
            /// Ensure that sub-editor values are translated through their FromEditor methods
            /// </summary>
            /// <param name="editorValue"></param>
            /// <param name="currentValue"></param>
            /// <returns></returns>
            public override object FromEditor(ContentPropertyData editorValue, object currentValue)
            {
                if (editorValue.Value == null || string.IsNullOrWhiteSpace(editorValue.Value.ToString()))
                    return null;

                var rows = _nestedContentValues.GetPropertyValues(editorValue.Value);

                if (rows.Count == 0)
                    return string.Empty;

                foreach (var row in rows.ToList())
                {
                    foreach(var prop in row.PropertyValues.ToList())
                    {
                        // Fetch the property types prevalue
                        var propConfiguration = _dataTypeService.GetDataType(prop.Value.PropertyType.DataTypeId).Configuration;

                        // Lookup the property editor
                        var propEditor = _propertyEditors[prop.Value.PropertyType.PropertyEditorAlias];
                        if (propEditor == null) continue;

                        // Create a fake content property data object
                        var contentPropData = new ContentPropertyData(prop.Value.Value, propConfiguration);

                        // Get the property editor to do it's conversion
                        var newValue = propEditor.GetValueEditor().FromEditor(contentPropData, prop.Value.Value);

                        // update the raw value since this is what will get serialized out
                        row.RawPropertyValues[prop.Key] = (newValue == null) ? null : JToken.FromObject(newValue);
                    }
                }

                // return json
                return JsonConvert.SerializeObject(rows);
            }
            #endregion

            public IEnumerable<UmbracoEntityReference> GetReferences(object value)
            {
                var rawJson = value == null ? string.Empty : value is string str ? str : value.ToString();

                var result = new List<UmbracoEntityReference>();

                foreach (var row in _nestedContentValues.GetPropertyValues(rawJson))
                {
                    foreach(var prop in row.PropertyValues)
                    {
                        var propEditor = _propertyEditors[prop.Value.PropertyType.PropertyEditorAlias];

                        var valueEditor = propEditor?.GetValueEditor();
                        if (!(valueEditor is IDataValueReference reference)) continue;

                        var val = prop.Value.Value?.ToString();

                        var refs = reference.GetReferences(val);

                        result.AddRange(refs);
                    }
                }

                return result;
            }
        }

        /// <summary>
        /// Validator for nested content to ensure that all nesting of editors is validated
        /// </summary>
        internal class NestedContentValidator : ComplexEditorValidator
        {
            private readonly NestedContentValues _nestedContentValues;

            public NestedContentValidator(NestedContentValues nestedContentValues, PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, ILocalizedTextService textService)
                : base(propertyEditors, dataTypeService, textService)
            {
                _nestedContentValues = nestedContentValues;
            }

            protected override IEnumerable<ElementTypeValidationModel> GetElementTypeValidation(object value)
            {
                foreach (var row in _nestedContentValues.GetPropertyValues(value))
                {
                    var elementValidation = new ElementTypeValidationModel(row.ContentTypeAlias, row.Id);
                    foreach (var prop in row.PropertyValues)
                    {
                        elementValidation.AddPropertyTypeValidation(
                            new PropertyTypeValidationModel(prop.Value.PropertyType, prop.Value.Value));
                    }
                    yield return elementValidation;
                }
            }
        }

        /// <summary>
        /// Used to deserialize the nested content serialized value
        /// </summary>
        internal class NestedContentValues
        {
            private readonly Lazy<Dictionary<string, IContentType>> _contentTypes;

            public NestedContentValues(IContentTypeService contentTypeService)
            {
                _contentTypes = new Lazy<Dictionary<string, IContentType>>(() => contentTypeService.GetAll().ToDictionary(c => c.Alias));
            }

            private IContentType GetElementType(NestedContentRowValue item)
            {
                _contentTypes.Value.TryGetValue(item.ContentTypeAlias, out var contentType);
                return contentType;
            }

            /// <summary>
            /// Deserialize the raw json property value
            /// </summary>
            /// <param name="propertyValue"></param>
            /// <returns></returns>
            public IReadOnlyList<NestedContentRowValue> GetPropertyValues(object propertyValue)
            {
                if (propertyValue == null || string.IsNullOrWhiteSpace(propertyValue.ToString()))
                    return new List<NestedContentRowValue>();

                var rowValues = JsonConvert.DeserializeObject<List<NestedContentRowValue>>(propertyValue.ToString());

                // There was a note here about checking if the result had zero items and if so it would return null, so we'll continue to do that
                // The original note was: "Issue #38 - Keep recursive property lookups working"
                // Which is from the original NC tracker: https://github.com/umco/umbraco-nested-content/issues/38
                // This check should be used everywhere when iterating NC prop values, instead of just the one previous place so that
                // empty values don't get persisted when there is nothing, it should actually be null.
                if (rowValues == null || rowValues.Count == 0)
                    return new List<NestedContentRowValue>();

                var contentTypePropertyTypes = new Dictionary<string, Dictionary<string, PropertyType>>();

                foreach (var row in rowValues)
                {
                    var contentType = GetElementType(row);
                    if (contentType == null)
                        continue;

                    // get the prop types for this content type but keep a dictionary of found ones so we don't have to keep re-looking and re-creating
                    // objects on each iteration.
                    if (!contentTypePropertyTypes.TryGetValue(contentType.Alias, out var propertyTypes))
                        propertyTypes = contentTypePropertyTypes[contentType.Alias] = contentType.CompositionPropertyTypes.ToDictionary(x => x.Alias, x => x);

                    // find any keys that are not real property types and remove them
                    foreach(var prop in row.RawPropertyValues.ToList())
                    {
                        if (IsSystemPropertyKey(prop.Key)) continue;

                        // doesn't exist so remove it
                        if (!propertyTypes.TryGetValue(prop.Key, out var propType))
                        {
                            row.RawPropertyValues.Remove(prop.Key);
                        }
                        else
                        {
                            // set the value to include the resolved property type
                            row.PropertyValues[prop.Key] = new NestedContentPropertyValue
                            {
                                PropertyType = propType,
                                Value = prop.Value
                            };
                        }
                    }
                }

                return rowValues;
            }

            /// <summary>
            /// Used during deserialization to populate the property value/property type of a nested content row property
            /// </summary>
            internal class NestedContentPropertyValue
            {
                public object Value { get; set; }
                public PropertyType PropertyType { get; set; }
            }

            /// <summary>
            /// Used to deserialize a nested content row
            /// </summary>
            internal class NestedContentRowValue
            {
                [JsonProperty("key")]
                public Guid Id{ get; set; }

                [JsonProperty("name")]
                public string Name { get; set; }

                [JsonProperty("ncContentTypeAlias")]
                public string ContentTypeAlias { get; set; }

                /// <summary>
                /// The remaining properties will be serialized to a dictionary
                /// </summary>
                /// <remarks>
                /// The JsonExtensionDataAttribute is used to put the non-typed properties into a bucket
                /// http://www.newtonsoft.com/json/help/html/DeserializeExtensionData.htm
                /// NestedContent serializes to string, int, whatever eg
                ///   "stringValue":"Some String","numericValue":125,"otherNumeric":null
                /// </remarks>
                [JsonExtensionData]
                public IDictionary<string, object> RawPropertyValues { get; set; }

                /// <summary>
                /// Used during deserialization to convert the raw property data into data with a property type context
                /// </summary>
                [JsonIgnore]
                public IDictionary<string, NestedContentPropertyValue> PropertyValues { get; set; } = new Dictionary<string, NestedContentPropertyValue>();
            }
        }

        #endregion

        private static bool IsSystemPropertyKey(string propKey)
        {
            return propKey == "name" || propKey == "key" || propKey == ContentTypeAliasPropertyKey;
        }
    }
}