text:
<?php

namespace SilverStripe\TravisSupport;
use Composer\Semver\Semver;

/**
 * Given a set of environment variables, determine the appropriate composer script for this test run
 */
class ComposerGenerator {

	/**
	 * Denote that the build is against a branch
	 */
	const REF_BRANCH = 'Branch';

	/**
	 * Denote that the build is against a tag
	 */
	const REF_TAG = 'Tag';

	/**
	 * Framework version to use (CORE_RELEASE)
	 *
	 * @var string
	 */
	protected $coreVersion = null;

	/**
	 * Composer inline alias version to use for {@link coreVersion}.
	 * @see https://getcomposer.org/doc/articles/aliases.md
	 *
	 * @var string
	 */
	protected $coreAlias = null;

	/**
	 * Version of the module to use
	 *
	 * @var string
	 */
	protected $moduleVersion = null;

	/**
	 * Type of version of this module build, either a branch or tag
	 *
	 * @var string
	 */
	protected $moduleRef = null;

	/**
	 * Array form of framework composer information
	 *
	 * @var array
	 */
	protected $corePackageInfo = array();

	/**
	 * Array form of this module's composer information
	 *
	 * @var array
	 */
	protected $modulePackageInfo = array();

	/**
	 * @var array Packages that form part of a core release of SilverStripe
	 */
	protected $coreModules = array(
		'silverstripe/framework',
		'silverstripe/cms',
		'silverstripe/siteconfig',
		'silverstripe/reports',
	);

	/**
	 *
	 * @param string $coreVersion Framework version to use (CORE_RELEASE)
	 * @param string $moduleVersion Version of the module to use
	 * @param string $moduleRef Type of version of this module build, either a branch or tag
	 * @param array $corePackageInfo Decoded json for core package data
	 * @param array $modulePackageInfo Decoded json for module package data
	 */
	public function __construct($coreVersion, $moduleVersion, $moduleRef, $corePackageInfo = array(),
		$modulePackageInfo = array()
	) {
		$this->coreVersion = $coreVersion;
		$this->moduleVersion = $moduleVersion;
		$this->moduleRef = $moduleRef;
		$this->corePackageInfo = $corePackageInfo;
		$this->modulePackageInfo = $modulePackageInfo;
	}

	/**
	 * @param string $alias Support for inline aliases of {@link $coreVersion}.
	 * @see https://getcomposer.org/doc/articles/aliases.md
	 * @return self
	 */
	public function setCoreAlias($alias)
	{
		$this->coreAlias = $alias;

		return $this;
	}

	/**
	 * Parse a version in a form appropriate for a composer constraint
	 *
	 * @param string $version Version
	 * @param string $ref Reference type
	 * @return string
	 */
	public function parseComposerConstraint($version, $ref) {
		// Tags are given as literal constraints
		if($ref === self::REF_TAG) return $version;

		// Numeric branch (3.1, 3, 3.1.4.0) as (3.1.x-dev, 3.x-dev, 3.1.4.0.x-dev)
		if(preg_match('/^\d+(\.\d+)*$/', $version)) {
			return $version . '.x-dev';
		}

		// Non-numeric branch (master, develop) as dev-master, dev-develop as per composer rules
		return sprintf('dev-%s', $version);
	}

	/**
	 * Gets the version constraint to use for this module. E.g. 3.4.x-dev
	 *
	 * @return string
	 */
	public function getModuleComposerConstraint() {
		return $this->parseComposerConstraint($this->moduleVersion, $this->moduleRef);
	}

	/**
	 * Find the zipball of the version from the corePackageInfo
	 *
	 * @param string $version
	 * @return string
	 */
	public function getDistLocationForVersion($version) {
		$versions = $this->corePackageInfo['package']['versions'];
		$legitVersions = $this->buildValidVersions();
		$version = $legitVersions[$version];
		if (!array_key_exists($version, $versions)) {
			return;
		}
		return $versions[$version]['dist']['url'];
	}

	/**
	 * Build an array of valid versions from the corePackageInfo - this allows us to match to real versions of the core
	 * release so CORE_RELEASE=3.1 will match to a tag 3.1.x as the 3.1 branch is no more
	 *
	 * @return array
	 */
	public function buildValidVersions() {
		$validVersions = array();
		if (empty($this->corePackageInfo['package']['versions'])) {
			return $validVersions;
		}
		foreach ($this->corePackageInfo['package']['versions'] as $version => $versionInfo) {
			$validVersions[$version] = $version;
			if (!empty($versionInfo['extra']['branch-alias'])) {
				$aliases = $versionInfo['extra']['branch-alias'];
				foreach ($aliases as $real => $ghost) {
					if ($real == $version) {
						$validVersions[$ghost] = $real;
					}
				}
			}
		}
		return $validVersions;
	}

	/**
	 * Gets the version constraint to use for the framework.
	 * Note that major or minor versions are assumed to be branches, while
	 * constraints with patch version are assumed to be tags.
	 *
	 * @return string
	 */
	public function getCoreComposerConstraint() {
		$coreConstraint = $this->parseComposerConstraint($this->coreVersion, self::REF_BRANCH);
		$version = $coreConstraint;
		$validVersions = $this->buildValidVersions();
		$versions = false;

		// if we are looking for a branch ending with 'x-dev' try and find the best matching constraint (there might
		// not be a x-dev branch)
		if (substr($coreConstraint, -5) == 'x-dev') {
			$coreConstraint = substr($coreConstraint, 0, -5) . '*';
		}
		// find the versions that match our coreConstraint
		if (!empty($validVersions)) {
			$versions = Semver::satisfiedBy(Semver::sort(array_keys($this->buildValidVersions())), $coreConstraint);
		}
		// if we found some, use the most recent release that matches
		if ($versions) {
			$version = array_pop($versions);
		}

		// use the package alias if it exists
		if( isset( $this->corePackageInfo['package']['versions'][$version]['extra']['branch-alias'][$version])) {
			return $this->corePackageInfo['package']['versions'][$version]['extra']['branch-alias'][$version];
		}

		// Respect branch alias configured externally
		if ($this->coreAlias) {
			$version .= ' as ' . $this->coreAlias;
		}

		return $version;
	}

	/**
	 * Generate the package composer data reperesenting this module, to be included in the root config
	 *
	 * @param string $installFromPath Specify path to install local module from
	 * @return array Composer config in array format
	 */
	public function generatePackageComposerConfig($installFromPath = null) {
		if ($this->isCoreModule($this->modulePackageInfo['name'])) {
			$moduleConstraint = $this->getCoreComposerConstraint();
		}
		else {
			$moduleConstraint = $this->getModuleComposerConstraint();
		}

		// Set the module version
		$composerConfig = array_replace_recursive(
			$this->modulePackageInfo,
			array(
				'version' => $moduleConstraint
			)
		);

		// If installing from a local archive, specify it
		if($installFromPath !== null) {
			$composerConfig = array_replace_recursive(
				$composerConfig,
				array(
					'dist' => array(
						'type' => 'tar',
						'url' => "file://{$installFromPath}"
					)
				)
			);
		}
		return $composerConfig;
	}

	/**
	 * Generates a root composer config, linked to a nested sub-package
	 *
	 * @param array $packageComposer Data of sub-package to include
	 * @return array
	 */
	public function generateRootComposerConfig($packageComposer) {
		// Generate the root level composer
		$composer = array(
			'repositories' => array(
				// Require this module via a direct package
				array(
					'type' => 'package',
					'package' => $packageComposer
				)
			),
			'require' => array(
				$packageComposer['name'] => $packageComposer['version']
			),
			// Always include DBs, allow module specific version dependencies though
			'require-dev' => array(
				'silverstripe/postgresql' => '*',
				'silverstripe/sqlite3' => '*',
				'phpunit/phpunit' => '^3 || ^4 || ^5' // Default phpunit version if none specified
			),
			'minimum-stability' => 'dev',
			'config' => array(
				'notify-on-install' => false,
				'process-timeout' => 600, // double default timeout, github archive downloads tend to be slow
			)
		);

		// Promote repositories, require, and require-dev to the top level from the package
		foreach(array('repositories', 'require', 'require-dev') as $section) {
			if(!empty($packageComposer[$section])) {
				$composer[$section] = array_merge(
					array_change_key_case($composer[$section], CASE_LOWER),
					array_change_key_case($packageComposer[$section], CASE_LOWER)
				);
			}
		}

		return $composer;
	}

	/**
	 * Merge any custom options into the root composer config
	 *
	 * @param array $options Options in array form
	 * @param array $composer Root composer config
	 * @return array Updated composer config
	 */
	public function mergeCustomOptions($options, $composer) {
		// Add a custom requirement
		if(!empty($options['require'])) {
			// this allows for arguments like "silverstripe/behat-extension:dev-master" where "dev-master" would be the branch
			// to use for that requirement. If just specifying "silverstripe/behat-extension" without the separator, default
			// to the branch being "*"

			// If a single value is passed it's a string, if multiple then an array
			// In the string case check for commas, if so assume it's CSV splitting of packages
			// This ensure that $required is always an array
			$requiredPackages = $options['require'];
			if (is_string($options['require'])) {
				// if a comma is present expldoe the CSV
				if (strpos($options['require'], ',') !== false) {
					$options['require'] = explode(',', $options['require']);
				}
			} else {
				$requiredPackages = $options['require'];
			}
			$requiredPackages = is_string($options['require']) ? array($options['require']) : $options['require'];

			foreach ($requiredPackages as $requiredPackage) {
				$requireParts = explode(':', $requiredPackage);
				$requireName = $requireParts[0];
				$requireBranch = (isset($requireParts[1])) ? $requireParts[1] : '*';
				$composer['require'][$requireName] = $requireBranch;
			}
		}
		return $composer;
	}

	/**
	 * Generate a composer config appropriate for this build, given the additional constraints
	 *
	 * @param array $options custom options
	 * @param string $installFromPath Specify path to install local module from
	 * @return array Composer config in array format
	 */
	public function generateComposerConfig($options = array(), $installFromPath = null) {
		// Generate the sub-package config
		$moduleComposer = $this->generatePackageComposerConfig($installFromPath);

		// Merge this into the root package
		$rootComposer = $this->generateRootComposerConfig($moduleComposer);

		// Handle custom options
		$rootComposer = $this->mergeCustomOptions($options, $rootComposer);

		// Update framework / cms requirements
		$rootComposer = $this->mergeFrameworkRequirements($rootComposer, $moduleComposer);

		// Update theme requirements
		$rootComposer = $this->mergeThemeRequirements($rootComposer);

		return $rootComposer;
	}

	/**
	 * Adjust framework / cms reqirements as necessary
	 *
	 * @param array $rootComposer
	 * @param array $moduleComposer
	 */
	public function mergeFrameworkRequirements($rootComposer, $moduleComposer) {
		$coreConstraint = $this->getCoreComposerConstraint();

		// Force 2.x framework dependencies to also require cms.
		if($this->coreVersion != 'master'
			&& version_compare($this->coreVersion, '3') < 0
			&& $moduleComposer['name'] == 'silverstripe/framework'
		) {
			$rootComposer['require']['silverstripe/framework'] .= ' as ' . $coreConstraint;
			$rootComposer['require']['silverstripe/cms'] = $coreConstraint;
		}

		// Override module dependencies in order to test with specific core branch.
		// This might be older than the latest permitted version based on the module definition.
		// Its up to the module author to declare compatible CORE_RELEASE values in the .travis.yml.
		// Leave dependencies alone if we're testing either of those modules directly.
		if(isset($rootComposer['require']['silverstripe/framework']) && $moduleComposer['name'] != 'silverstripe/framework') {
			$rootComposer['require']['silverstripe/framework'] = $coreConstraint;
		}
		if(isset($rootComposer['require']['silverstripe/cms']) && $moduleComposer['name'] != 'silverstripe/cms') {
			$rootComposer['require']['silverstripe/cms'] = $coreConstraint;
		}

		return $rootComposer;
	}

	/**
	 * Merge the theme into composer
	 *
	 * @param array $rootComposer
	 */
	public function mergeThemeRequirements($rootComposer) {
		// Add theme based on version. Important for Behat testing.
		// TODO Determine dependency based on actual composer.json in silverstripe-installer
		if($this->coreVersion == 'master' || version_compare($this->coreVersion, '3') >= 0) {
			$rootComposer['require']['silverstripe-themes/simple'] = '*';
		} else {
			$rootComposer['require']['silverstripe-themes/blackcandy'] = '*';
		}

		return $rootComposer;
	}

	/**
	 * Determine if a package is part of the core release of SilverStripe packages
	 *
	 * @param $packageName string The name of a module to check (eg: silverstripe/framework)
	 * @return bool
	 */
	protected function isCoreModule($packageName) {
		return in_array($packageName, $this->coreModules);
	}

}


text:
/* SIP extension for UDP NAT alteration.
 *
 * (C) 2005 by Christian Hentschel <chentschel@arnet.com.ar>
 * based on RR's ip_nat_ftp.c and other modules.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/udp.h>

#include <net/netfilter/nf_nat.h>
#include <net/netfilter/nf_nat_helper.h>
#include <net/netfilter/nf_nat_rule.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <linux/netfilter/nf_conntrack_sip.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Christian Hentschel <chentschel@arnet.com.ar>");
MODULE_DESCRIPTION("SIP NAT helper");
MODULE_ALIAS("ip_nat_sip");

#if 0
#define DEBUGP printk
#else
#define DEBUGP(format, args...)
#endif

struct addr_map {
	struct {
		char		src[sizeof("nnn.nnn.nnn.nnn:nnnnn")];
		char		dst[sizeof("nnn.nnn.nnn.nnn:nnnnn")];
		unsigned int	srclen, srciplen;
		unsigned int	dstlen, dstiplen;
	} addr[IP_CT_DIR_MAX];
};

static void addr_map_init(struct nf_conn *ct, struct addr_map *map)
{
	struct nf_conntrack_tuple *t;
	enum ip_conntrack_dir dir;
	unsigned int n;

	for (dir = 0; dir < IP_CT_DIR_MAX; dir++) {
		t = &ct->tuplehash[dir].tuple;

		n = sprintf(map->addr[dir].src, "%u.%u.%u.%u",
			    NIPQUAD(t->src.u3.ip));
		map->addr[dir].srciplen = n;
		n += sprintf(map->addr[dir].src + n, ":%u",
			     ntohs(t->src.u.udp.port));
		map->addr[dir].srclen = n;

		n = sprintf(map->addr[dir].dst, "%u.%u.%u.%u",
			    NIPQUAD(t->dst.u3.ip));
		map->addr[dir].dstiplen = n;
		n += sprintf(map->addr[dir].dst + n, ":%u",
			     ntohs(t->dst.u.udp.port));
		map->addr[dir].dstlen = n;
	}
}

static int map_sip_addr(struct sk_buff **pskb, enum ip_conntrack_info ctinfo,
			struct nf_conn *ct, const char **dptr, size_t dlen,
			enum sip_header_pos pos, struct addr_map *map)
{
	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
	unsigned int matchlen, matchoff, addrlen;
	char *addr;

	if (ct_sip_get_info(ct, *dptr, dlen, &matchoff, &matchlen, pos) <= 0)
		return 1;

	if ((matchlen == map->addr[dir].srciplen ||
	     matchlen == map->addr[dir].srclen) &&
	    memcmp(*dptr + matchoff, map->addr[dir].src, matchlen) == 0) {
		addr    = map->addr[!dir].dst;
		addrlen = map->addr[!dir].dstlen;
	} else if ((matchlen == map->addr[dir].dstiplen ||
		    matchlen == map->addr[dir].dstlen) &&
		   memcmp(*dptr + matchoff, map->addr[dir].dst, matchlen) == 0) {
		addr    = map->addr[!dir].src;
		addrlen = map->addr[!dir].srclen;
	} else
		return 1;

	if (!nf_nat_mangle_udp_packet(pskb, ct, ctinfo,
				      matchoff, matchlen, addr, addrlen))
		return 0;
	*dptr = (*pskb)->data + (*pskb)->nh.iph->ihl*4 + sizeof(struct udphdr);
	return 1;

}

static unsigned int ip_nat_sip(struct sk_buff **pskb,
			       enum ip_conntrack_info ctinfo,
			       struct nf_conn *ct,
			       const char **dptr)
{
	enum sip_header_pos pos;
	struct addr_map map;
	int dataoff, datalen;

	dataoff = (*pskb)->nh.iph->ihl*4 + sizeof(struct udphdr);
	datalen = (*pskb)->len - dataoff;
	if (datalen < sizeof("SIP/2.0") - 1)
		return NF_DROP;

	addr_map_init(ct, &map);

	/* Basic rules: requests and responses. */
	if (strncmp(*dptr, "SIP/2.0", sizeof("SIP/2.0") - 1) != 0) {
		/* 10.2: Constructing the REGISTER Request:
		 *
		 * The "userinfo" and "@" components of the SIP URI MUST NOT
		 * be present.
		 */
		if (datalen >= sizeof("REGISTER") - 1 &&
		    strncmp(*dptr, "REGISTER", sizeof("REGISTER") - 1) == 0)
			pos = POS_REG_REQ_URI;
		else
			pos = POS_REQ_URI;

		if (!map_sip_addr(pskb, ctinfo, ct, dptr, datalen, pos, &map))
			return NF_DROP;
	}

	if (!map_sip_addr(pskb, ctinfo, ct, dptr, datalen, POS_FROM, &map) ||
	    !map_sip_addr(pskb, ctinfo, ct, dptr, datalen, POS_TO, &map) ||
	    !map_sip_addr(pskb, ctinfo, ct, dptr, datalen, POS_VIA, &map) ||
	    !map_sip_addr(pskb, ctinfo, ct, dptr, datalen, POS_CONTACT, &map))
		return NF_DROP;
	return NF_ACCEPT;
}

static unsigned int mangle_sip_packet(struct sk_buff **pskb,
				      enum ip_conntrack_info ctinfo,
				      struct nf_conn *ct,
				      const char **dptr, size_t dlen,
				      char *buffer, int bufflen,
				      enum sip_header_pos pos)
{
	unsigned int matchlen, matchoff;

	if (ct_sip_get_info(ct, *dptr, dlen, &matchoff, &matchlen, pos) <= 0)
		return 0;

	if (!nf_nat_mangle_udp_packet(pskb, ct, ctinfo,
				      matchoff, matchlen, buffer, bufflen))
		return 0;

	/* We need to reload this. Thanks Patrick. */
	*dptr = (*pskb)->data + (*pskb)->nh.iph->ihl*4 + sizeof(struct udphdr);
	return 1;
}

static int mangle_content_len(struct sk_buff **pskb,
			      enum ip_conntrack_info ctinfo,
			      struct nf_conn *ct,
			      const char *dptr)
{
	unsigned int dataoff, matchoff, matchlen;
	char buffer[sizeof("65536")];
	int bufflen;

	dataoff = (*pskb)->nh.iph->ihl*4 + sizeof(struct udphdr);

	/* Get actual SDP lenght */
	if (ct_sip_get_info(ct, dptr, (*pskb)->len - dataoff, &matchoff,
			    &matchlen, POS_SDP_HEADER) > 0) {

		/* since ct_sip_get_info() give us a pointer passing 'v='
		   we need to add 2 bytes in this count. */
		int c_len = (*pskb)->len - dataoff - matchoff + 2;

		/* Now, update SDP length */
		if (ct_sip_get_info(ct, dptr, (*pskb)->len - dataoff, &matchoff,
				    &matchlen, POS_CONTENT) > 0) {

			bufflen = sprintf(buffer, "%u", c_len);
			return nf_nat_mangle_udp_packet(pskb, ct, ctinfo,
							matchoff, matchlen,
							buffer, bufflen);
		}
	}
	return 0;
}

static unsigned int mangle_sdp(struct sk_buff **pskb,
			       enum ip_conntrack_info ctinfo,
			       struct nf_conn *ct,
			       __be32 newip, u_int16_t port,
			       const char *dptr)
{
	char buffer[sizeof("nnn.nnn.nnn.nnn")];
	unsigned int dataoff, bufflen;

	dataoff = (*pskb)->nh.iph->ihl*4 + sizeof(struct udphdr);

	/* Mangle owner and contact info. */
	bufflen = sprintf(buffer, "%u.%u.%u.%u", NIPQUAD(newip));
	if (!mangle_sip_packet(pskb, ctinfo, ct, &dptr, (*pskb)->len - dataoff,
			       buffer, bufflen, POS_OWNER_IP4))
		return 0;

	if (!mangle_sip_packet(pskb, ctinfo, ct, &dptr, (*pskb)->len - dataoff,
			       buffer, bufflen, POS_CONNECTION_IP4))
		return 0;

	/* Mangle media port. */
	bufflen = sprintf(buffer, "%u", port);
	if (!mangle_sip_packet(pskb, ctinfo, ct, &dptr, (*pskb)->len - dataoff,
			       buffer, bufflen, POS_MEDIA))
		return 0;

	return mangle_content_len(pskb, ctinfo, ct, dptr);
}

/* So, this packet has hit the connection tracking matching code.
   Mangle it, and change the expectation to match the new version. */
static unsigned int ip_nat_sdp(struct sk_buff **pskb,
			       enum ip_conntrack_info ctinfo,
			       struct nf_conntrack_expect *exp,
			       const char *dptr)
{
	struct nf_conn *ct = exp->master;
	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
	__be32 newip;
	u_int16_t port;

	DEBUGP("ip_nat_sdp():\n");

	/* Connection will come from reply */
	newip = ct->tuplehash[!dir].tuple.dst.u3.ip;

	exp->tuple.dst.u3.ip = newip;
	exp->saved_proto.udp.port = exp->tuple.dst.u.udp.port;
	exp->dir = !dir;

	/* When you see the packet, we need to NAT it the same as the
	   this one. */
	exp->expectfn = nf_nat_follow_master;

	/* Try to get same port: if not, try to change it. */
	for (port = ntohs(exp->saved_proto.udp.port); port != 0; port++) {
		exp->tuple.dst.u.udp.port = htons(port);
		if (nf_conntrack_expect_related(exp) == 0)
			break;
	}

	if (port == 0)
		return NF_DROP;

	if (!mangle_sdp(pskb, ctinfo, ct, newip, port, dptr)) {
		nf_conntrack_unexpect_related(exp);
		return NF_DROP;
	}
	return NF_ACCEPT;
}

static void __exit nf_nat_sip_fini(void)
{
	rcu_assign_pointer(nf_nat_sip_hook, NULL);
	rcu_assign_pointer(nf_nat_sdp_hook, NULL);
	synchronize_rcu();
}

static int __init nf_nat_sip_init(void)
{
	BUG_ON(rcu_dereference(nf_nat_sip_hook));
	BUG_ON(rcu_dereference(nf_nat_sdp_hook));
	rcu_assign_pointer(nf_nat_sip_hook, ip_nat_sip);
	rcu_assign_pointer(nf_nat_sdp_hook, ip_nat_sdp);
	return 0;
}

module_init(nf_nat_sip_init);
module_exit(nf_nat_sip_fini);

redpajama_set_name: RedPajamaGithub


text:
Given /^a mapping exists for '(.*)' to '(.*)' with tag '(.*)'$/ do |source, target, mapping_tag|
  @direction = {:from => source.to_sym, :to => target.to_sym}
  @tag = mapping_tag

  case @direction
  when {:from => :xml, :to => :hash}
    Babelicious::Mapper.config(@tag.to_sym) do |m|
      m.direction :from => :xml, :to => :hash

      m.map :from => "foo/bar", :to => "bar/foo"
      m.map :from => "foo/baz", :to => "bar/boo"
      m.map :from => "foo/cuk/coo", :to => "foo/bar/coo"
      m.map :from => "foo/cuk/doo", :to => "doo"
    end
  when {:from => :hash, :to => :xml}
    Babelicious::Mapper.config(@tag.to_sym) do |m|
      m.direction :from => :hash, :to => :xml

      m.map :from => "foo/bar", :to => "bar/foo"
      m.map :from => "foo/baz", :to => "bar/boo"
      m.map :from => "foo/cuk/coo", :to => "bar/cuk/coo"
      m.map :from => "foo/cuk/doo", :to => "bar/cuk/doo"
    end
  when {:from => :hash, :to => :hash}
    Babelicious::Mapper.config(@tag.to_sym) do |m|
      m.direction :from => :hash, :to => :hash

      m.map :from => "foo", :to => "zoo"
      m.map :from => "bar", :to => "yoo"
      m.map :from => "baz", :to => "too"
      m.map :from => "boo", :to => "soo/roo"
    end
  when {:from => :object, :to => :xml}
    Babelicious::Mapper.config(@tag.to_sym) do |m|
      m.direction :from => :object, :to => :xml

      m.map :from => "foo", :to => "foo/zoo"
      m.map :from => "bar", :to => "foo/yoo"
      m.map :from => "boo/coo", :to => "foo/soo/roo"
    end
  end
end

Given /^a mapping exists with '(.*)' condition$/ do |condition|
  case condition
  when /unless/
    Babelicious::Mapper.config(:ignore) do |m|
      m.direction :from => :xml, :to => :hash

      m.map :from => "foo/bar", :to => "bar/foo"
      m.map(:from => "foo/baz", :to => "bar/boo").unless(:empty)
    end
 when /when/
    Babelicious::Mapper.config(:when) do |m|
      m.direction :from => :xml, :to => :hash

      m.map(:from => "foo/bar", :to => "bar/foo").when do |value|
        value =~ /hubba/
      end
      m.map(:from => "foo/baz", :to => "bar/boo").when do |value|
        value =~ /bubba/
      end
    end
  end
end

Given /^a mapping exists with concatenation$/ do
  Babelicious::Mapper.config(:concatenation) do |m|
    m.direction :from => :xml, :to => :hash

    # <event><decision_request><target_factors><institutions><institution>FOO</institution><institution>BAR</institution><institution>BAZ</institution></institutions></target_factors></decision_request></event>
    m.map(:from => "event/decision_request/target_factors/institutions", :to => "event/new_update_status_code").customize do |node|
      node.concatenate_children("|")
    end
  end
end

Given /^a customized mapping exists for '(.*)' to '(.*)' with tag '(.*)'$/ do |source, target, tag|
  @mapping_tag = tag.to_sym
  @direction = {:from => source.to_sym, :to => target.to_sym}

  case @direction
  when {:from => :xml, :to => :hash}
    Babelicious::Mapper.config(@mapping_tag.to_sym) do |m|
      m.direction @direction

      m.map(:from => "event/progress/statuses", :to => "event/new_update_status_code").customize do |node|
        res = []
        node.elements.map { |nd| res << {"name" => nd.child_content("code"), "text" => nd.child_content("message")} }
        res
      end
    end
  when {:from => :hash, :to => :xml}
    Babelicious::Mapper.config(@mapping_tag.to_sym) do |m|
      m.direction @direction

      m.map(:from => "event/rankings", :to => "event/response").customize do |val|
        node = new_node("rankings") do |rankings|

          val.each do |rnk|
            rankings << new_node("ranking") do |ranking|

              ranking << new_node("rank", rnk["ranking"]["rank"])
              ranking << new_node("value", rnk["ranking"]["value"])

              ranking << new_node("rules") do |rules|
                rnk["ranking"]["rules"].each do |rl|
                  rule = new_node("rule") << rl["rule"]
                  rules << rule
                end
              end

              ranking << new_node("potential_event") do |potential_event|
                rnk["ranking"]["potential_event"].each do |e|
                  institution = new_node("institutions") << e["institutions"]
                  potential_event << institution
                end
              end

            end

          end
        end
      end
    end
  end

end

Given /^a mapping exists with a customized block$/ do
  Babelicious::Mapper.config(:customized) do |m|
    m.direction :from => :xml, :to => :hash

    # <event><progress><statuses><status>Abandoned<message>bad phone</message></status></statuses></progress></event>
    m.map(:from => "event/progress/statuses", :to => "event/new_update_status_code").customize do |node|
      res = []
      node.elements.map { |nd| res << {"name" => nd.child_content("code"), "text" => nd.child_content("message")} }
      res
    end
  end
end

Given /^a mapping exists with custom \.to method$/ do
  Babelicious::Mapper.config(:custom_to) do |m|
    m.direction :from => :xml, :to => :hash

    # xml = "<foo><bar>baz</bar></foo>"
    m.from("foo/bar").to do |value|
      if(value == "baz")
        "value/was/baz"
      else
        "value/was/not/baz"
      end
    end
  end
end

Given /^a mapping exists with include$/ do
  Babelicious::Mapper.config(:another_map) do |m|
    m.direction :from => :hash, :to => :hash

    m.map :from => "foo", :to => "zoo"
    m.map :from => "bar", :to => "yoo"
  end

  Babelicious::Mapper.config(:include_another_map) do |m|
    m.direction :from => :hash, :to => :hash

    m.include :another_map
    m.map :from => "baz", :to => "too"
    m.map :from => "boo", :to => "soo/roo"
  end
end

Given /^a contact mapping exists with nested include$/ do
  Babelicious::Mapper.config(:a_sample_person) do |m|
    m.direction :from => :hash, :to => :hash

    m.map :from => "name/first", :to => "first_name"
    m.map :from => "name/last", :to => "last_name"
  end

  Babelicious::Mapper.config(:a_sample_contact) do |m|
    m.direction :from => :hash, :to => :hash

    m.include :a_sample_person, :inside_of => "contact"
    m.map :from => "contact/phone/home", :to => "contact/home_phone"
  end
end

Given /^a mapping exists with prepopulate method$/ do
  Babelicious::Mapper.config(:api) do |m|
    m.direction :from => :hash, :to => :xml

    m.prepopulate("event/api_version").with("2.0.1")
    m.map :from => "name/first", :to => "event/first_name"
    m.map :from => "name/last", :to => "event/last_name"
  end
end

#
##
###
When /^the mapping is translated$/ do
  case @direction
  when {:from => :xml, :to => :hash}
    xml = <<-EOL
<foo>
 <bar>a</bar>
 <baz>b</baz>
 <cuk>
  <coo>c</coo>
  <doo>d</doo>
 </cuk>
</foo>
EOL
    @translation = Babelicious::Mapper.translate(@tag.to_sym, xml)
  when {:from => :hash, :to => :xml}
    source = {:foo => {:bar => "a", :baz => "b", :cuk => {:coo => "c", :doo => "d"}}}
    @translation = Babelicious::Mapper.translate(@tag.to_sym, source)
  when {:from => :hash, :to => :hash}
    source = {:foo => "a", :bar => "b", :baz => "c", :boo => "d"}
    @translation = Babelicious::Mapper.translate(@tag.to_sym, source)
  when {:from => :object, :to => :xml}
    source = {:foo => "a", :bar => "b", :baz => "c", :boo => "d"}
    class CooBar
      def coo;"c"; end
    end

    class FooBar
      def foo; "a"; end
      def bar; "b"; end
      def boo; CooBar.new; end
    end
    @translation = Babelicious::Mapper.translate(@tag.to_sym, FooBar.new)
  end
end

When /^the '(.*)' mapping is translated$/ do |condition|
  case condition
  when /unless/
    xml = '<foo><bar>a</bar><baz></baz></foo>'
    @translation = Babelicious::Mapper.translate(:ignore, xml)
  when /when/
    xml = '<foo><bar>cuk</bar><baz>hubbabubba</baz></foo>'
    @translation = Babelicious::Mapper.translate(:when, xml)
  end
end

When /^the mapping with concatenation is translated$/ do
#  xml = '<foo><bar>a</bar><baz>b</baz><cuk><coo>c</coo><coo>d</coo><coo>e</coo></cuk></foo>'
  xml = <<-EOL
<event>
 <decision_request>
 <target_factors>
  <institutions>
   <institution>FOO</institution>
   <institution>BAR</institution>
   <institution>BAZ</institution>
  </institutions>
 </target_factors>
 </decision_request>
</event>
EOL
  @translation = Babelicious::Mapper.translate(:concatenation, xml)
end

When /^the customized mapping is translated$/ do
#  xml = '<foo><bar>baz</bar><cuk>coo</cuk></foo>'
#  xml = '<statuses><status>Abandoned<message>bad phone</message></status><status>Rejected<message>bad word</message></status></statuses>'
  case @direction
  when {:from => :xml, :to => :hash}
    xml = <<-EOL
<event>
 <progress>
  <statuses>
   <status>
    Abandoned
    <message>bad phone</message>
   </status>
   <status>
    Rejected
    <message>bad word</message>
   </status>
  </statuses>
 </progress>
</event>
EOL
    @translation = Babelicious::Mapper.translate(@mapping_tag.to_sym, xml)
  when {:from => :hash, :to => :xml}
    hash =
    { "event" =>
      {"rankings"=>
        [
         {"ranking"=>{
             "rules"=> [
                        {"rule"=>"pace_adjusted_revenue"}
                       ],
             "rank"=>1,
             "value"=>0.0,
             "potential_event"=>[{"institutions"=>"AcmeU"}]
           }
         },
         {"ranking"=> {"rules"=>
             [
              {"rule"=>"clipped"}
             ],
             "rank"=>2,
             "value"=>0.0,
             "potential_event"=>[{"institutions"=>"BraUn"}]
           }
         }
        ],
        "decision_point"=>"LMP_Insti"
      }
    }
    @translation = Babelicious::Mapper.translate(@mapping_tag.to_sym, hash)
  end
end

When /^the mapping with custom \.to method is translated$/ do
  xml = "<foo><bar>baz</bar></foo>"
  @translation = Babelicious::Mapper.translate(:custom_to, xml)
end

When /^the mapping with include is translated$/ do
  hash = {:foo => "Dave", :bar => "Brady", :baz => "Liz", :boo => "Brady"}
  @translation = Babelicious::Mapper.translate(:include_another_map, hash)
end

When /^the mapping with nested include is translated$/ do
  hash = {:contact => {:name => {:first => "Dave", :last => "Brady"}, :phone => {:home => "1231231234"}}}
  @translation = Babelicious::Mapper.translate(:a_sample_contact, hash)
end

When /^the mapping with prepopulate method is translated$/ do
  hash = {:name => {:first => "Dave", :last => "Brady"}}
  @translation = Babelicious::Mapper.translate(:api, hash)
end

When /^the mapping is reversed$/ do
  xml = <<-EOL
<bar>
 <foo>a</foo>
 <boo>b</boo>
 <cuk>
  <coo>c</coo>
  <doo>d</doo>
 </cuk>
</bar>
EOL
  @translation = Babelicious::Mapper.reverse(@tag.to_sym, xml)
end

#
##
###
Then /^the xml should be correctly mapped$/ do
  case @direction
  when {:from => :xml, :to => :hash}
    @translation.should == {"doo"=>"d", "foo"=>{"bar"=>{"coo"=>"c"}}, "bar"=>{"boo"=>"b", "foo"=>"a"}}
  when {:from => :hash, :to => :xml}
    @translation.to_s.gsub(/\s/, '').should == '<?xmlversion="1.0"encoding="UTF-8"?><bar><foo>a</foo><boo>b</boo><cuk><coo>c</coo><doo>d</doo></cuk></bar>'
  when {:from => :hash, :to => :hash}
    @translation.should == {"zoo" => "a", "yoo" => "b", "too" => "c", "soo" => {"roo" => "d"}}
  when {:from => :object, :to => :xml}
    @translation.to_s.gsub(/\s/, '').should == '<?xmlversion="1.0"encoding="UTF-8"?><foo><zoo>a</zoo><yoo>b</yoo><soo><roo>c</roo></soo></foo>'
  end
end

Then /^the target should be correctly processed for condition '(.*)'$/ do |condition|
  case condition
  when /unless/
    @translation.should == {"bar" => {"foo" => "a"}}
  when /when/
    @translation.should == {"bar" => {"boo" => "hubbabubba"}}
  end
end

Then /^the target should be properly concatenated$/ do
  @translation.should == {"event"=>{"new_update_status_code"=>"FOO|BAR|BAZ"}}
#  @translation.should == {"foo"=>{"bar"=>"c|d|e"}}
end

Then /^the customized target should be correctly processed$/ do
  case @direction
  when {:from => :xml, :to => :hash}
    translation = {"event"=>{"new_update_status_code"=>[{"name"=>"Abandoned", "text"=>"bad phone"}, {"name"=>"Rejected", "text"=>"bad word"}]}}
    @translation.should == translation
  when {:from => :hash, :to => :xml}
 translation = <<-EOL
<?xml version="1.0" encoding="UTF-8"?>
<event>
  <response>
    <rankings>
      <ranking>
        <rank>1</rank>
        <value>0.0</value>
        <rules>
          <rule>pace_adjusted_revenue</rule>
        </rules>
        <potential_event>
          <institutions>AcmeU</institutions>
        </potential_event>
      </ranking>
      <ranking>
        <rank>2</rank>
        <value>0.0</value>
        <rules>
          <rule>clipped</rule>
        </rules>
        <potential_event>
          <institutions>BraUn</institutions>
        </potential_event>
      </ranking>
    </rankings>
  </response>
</event>
EOL
  end
    @translation.to_s.gsub(/\s/, '').should == translation.to_s.gsub(/\s/, '')

#  @translation.should == {"new_update_status_code"=>[{"name"=>"Abandoned", "text"=>"bad phone"}, {"name"=>"Rejected", "text"=>"bad word"}]}
#  @translation.should == {"boo" => [{"bum" => "baz", "dum" => "coo"}]}
end

Then /^the target should be correctly processed for custom \.to conditions$/ do
#  xml = "<foo><bar>baz</bar></foo>"
  @translation.should == { "value" => { "was" => { "baz" => "baz"}}}
end

Then /^the target should have mappings included from different map$/ do
  @translation.should == {"zoo" => "Dave", "yoo" => "Brady", "too" => "Liz", "soo" => { "roo" => "Brady"}}
end

Then /^the target should have nested mappings included from different map$/ do
  @translation.should == {"contact" => { "first_name" => "Dave", "last_name" => "Brady", "home_phone" => "1231231234"}}
end

Then /^the target should be correctly processed prepopulate conditions$/ do
  xml = <<-EOT
<?xml version="1.0" encoding="UTF-8"?>
<event>
  <api_version>2.0.1</api_version>
  <first_name>Dave</first_name>
  <last_name>Brady</last_name>
</event>
EOT

  @translation.to_s.should == xml
end

Then /^the target should be correctly reversed$/ do
  hash = {"foo" => {"bar" => "a", "baz" => "b", "cuk" => {"coo" => "c", "doo" => "d"}}}
  @translation.should == hash
end


text:
@class RSVerticallyCenteredTextFieldCell;

@interface RSGifRecordingStatusView : NSView {
	RSVerticallyCenteredTextFieldCell *_textFieldCell;
	NSString *_statusString;
}
@property (readwrite,copy,nonatomic) NSString *statusString;
@end


text:
using System;
using System.Collections.Generic;
using GeoAPI.Geometries;

namespace AppGeo.Clients.ArcIms.ArcXml
{
  [Serializable]
	public class Layer : ICloneable
	{
		public const string XmlName = "LAYER";

		public static Layer ReadFrom(ArcXmlReader reader)
		{
			try
			{
				Layer layer = new Layer();

				if (reader.HasAttributes)
				{
					while (reader.MoveToNextAttribute())
					{
						string value = reader.ReadContentAsString();

						if (value.Length > 0)
						{
							switch (reader.Name)
							{
								case "featurecount": layer.FeatureCount = Convert.ToInt32(value); break;
								case "id": layer.ID = value; break;
								case "name": layer.Name = value; break;
							}
						}
					}

					reader.MoveToElement();
				}

				return layer;
			}
			catch (Exception ex)
			{
				if (ex is ArcXmlException)
				{
					throw ex;
				}
				else
				{
					throw new ArcXmlException(String.Format("Could not read {0} element.", XmlName), ex);
				}
			}
		}

    public string ID = null;
    public string Name = null;

		public int FeatureCount = 0;
		public string MaxScale = null;
		public string MinScale = null;
		public LayerType Type = LayerType.Acetate;
		public bool Visible = true;

		public Dataset Dataset = null;
    public ImageProperties ImageProperties = null;
		public Query Query = null;
		public CoordSys CoordSys = null;
		public Renderer Renderer = null;

		public List<Object> Objects = null;

		public Layer() { }

		public Layer(string id)
		{
			ID = id;
		}

		public Layer(string id, LayerType type)
		{
      ID = id;
			Type = type;
		}

		public LayerDef ToLayerDef()
		{
			return new LayerDef(ID);
		}

		public void Add(Object o)
		{
			if (Type != LayerType.Acetate)
			{
				throw new ArcXmlException("Layer is not of type Acetate, cannot add graphical objects");
			}

			if (Objects == null)
			{
				Objects = new List<Object>();
			}

			Objects.Add(o);
		}

    public void Add(Envelope envelope, Symbol symbol)
    {
      Add(new Object(envelope, symbol));
    }

    public void Add(IGeometry shape, Symbol symbol)
		{
      Add(new Object(shape, symbol));
		}

		public void Add(NorthArrow northArrow)
		{
			Add(new Object(northArrow));
		}

		public void Add(ScaleBar scaleBar)
		{
			Add(new Object(scaleBar));
		}

    public void Add(Text text)
    {
      Add(new Object(text));
    }

    public void Add(Text text, TextMarkerSymbol symbol)
    {
      Add(new Object(text, symbol));
    }

		public object Clone()
		{
			Layer clone = (Layer)this.MemberwiseClone();

			if (CoordSys != null)
			{
				clone.CoordSys = (CoordSys)CoordSys.Clone();
			}

			if (Dataset != null)
			{
				clone.Dataset = (Dataset)Dataset.Clone();
			}

			if (Objects != null)
			{
			  clone.Objects = new List<Object>();

        foreach (Object obj in Objects)
				{
          clone.Objects.Add((Object)obj.Clone());
				}
			}

			if (Query != null)
			{
				clone.Query = (Query)Query.Clone();
			}

			if (Renderer != null)
			{
				clone.Renderer = (Renderer)Renderer.Clone();
			}

			return clone;
		}

		public void WriteTo(ArcXmlWriter writer)
		{
			try
			{
				writer.WriteStartElement(XmlName);

				if (!String.IsNullOrEmpty(ID))
				{
					writer.WriteAttributeString("id", ID);
				}

				if (Type != LayerType.None)
				{
					writer.WriteAttributeString("type", ArcXmlEnumConverter.ToArcXml(typeof(LayerType), Type));
				}

				if (!String.IsNullOrEmpty(MaxScale))
				{
					writer.WriteAttributeString("maxscale", MaxScale);
				}

				if (!String.IsNullOrEmpty(MinScale))
				{
					writer.WriteAttributeString("mincale", MinScale);
				}

        if (!String.IsNullOrEmpty(Name))
				{
					writer.WriteAttributeString("name", Name);
				}

				if (!Visible)
				{
					writer.WriteAttributeString("visible", "false");
				}

				if (CoordSys != null)
				{
					CoordSys.WriteTo(writer);
				}

				if (Dataset != null)
				{
					Dataset.WriteTo(writer);
				}

        if (ImageProperties != null)
        {
          ImageProperties.WriteTo(writer);
        }

				if (Objects != null)
				{
					foreach (Object obj in Objects)
					{
            obj.WriteTo(writer);
					}
				}

				if (Query != null)
				{
					Query.WriteTo(writer);
				}

				if (Renderer != null)
				{
					Renderer.WriteTo(writer);
				}

				writer.WriteEndElement();
			}
			catch (Exception ex)
			{
				if (ex is ArcXmlException)
				{
					throw ex;
				}
				else
				{
					throw new ArcXmlException(String.Format("Could not write {0} object.", GetType().Name), ex);
				}
			}
		}
	}
}


text:
angular.module('app').controller('ItemController',['$scope', '$rootScope', 'groceryList',
	function($scope, $rootScope, groceryList){

		var emptyItem = { name: ''};

		$scope.name = emptyItem.name;

		$scope.addItem = function(){
			var item = {
				name: $scope.name
			};
			groceryList.addItem(item);
		};

		$rootScope.$on('itemAdded', function(){
			$scope.name = emptyItem.name;
		});
	}]);


text:
RSVP

<form>

		Name
		<input type="text" name="name" id="name" placeholder="Name" />

		<input type="radio" name="attending" /> I’m coming!

		<input type="radio" name="attending" /> I can’t make it.

		Date’s Name (if applicable)
		<input type="text" name="date_name" id="date_name" placeholder="Guest Name" />

	<input type="submit" value="RSVP" class="submit" />
</form>


text:
package sv_linkedapp

import (
	"github.com/watermint/toolbox/domain/dropbox/api/dbx_client"
	"github.com/watermint/toolbox/quality/infra/qt_errors"
	"github.com/watermint/toolbox/quality/recipe/qtr_endtoend"
	"testing"
)

func TestLinkedAppImpl_List(t *testing.T) {
	qtr_endtoend.TestWithDbxClient(t, func(ctx dbx_client.Client) {
		sv := New(ctx)
		_, err := sv.List()
		if err != nil && err != qt_errors.ErrorMock {
			t.Error(err)
		}
	})
}


text:
using System;
using Melanchall.DryWetMidi.Common;
using Melanchall.DryWetMidi.Interaction;

namespace Melanchall.DryWetMidi.Tests.Utilities
{
    public sealed class ChordMethods : LengthedObjectMethods<Chord>
    {
        #region Fields

        private readonly Random _random = new Random();

        #endregion

        #region Overrides

        public override void SetTime(Chord obj, long time)
        {
            obj.Time = time;
        }

        public override void SetLength(Chord obj, long length)
        {
            obj.Length = length;
        }

        public override Chord Create(long time, long length)
        {
            var chord = new Chord(new Note((SevenBitNumber)_random.Next(SevenBitNumber.MaxValue)),
                                  new Note((SevenBitNumber)_random.Next(SevenBitNumber.MaxValue)));
            chord.Time = time;
            chord.Length = length;

            return chord;
        }

        public override Chord Clone(Chord obj)
        {
            return obj.Clone();
        }

        #endregion
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66a.c
Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml
Template File: source-sinks-66a.tmpl.c
*/
/*
 * @description
 * CWE: 761 Free Pointer not at Start of Buffer
 * BadSource: console Read input from the console
 * Sinks:
 *    GoodSink: free() memory correctly at the start of the buffer
 *    BadSink : free() memory not at the start of the buffer
 * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#define SEARCH_CHAR 'S'

#ifndef OMITBAD

/* bad function declaration */
void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66b_badSink(char * dataArray[]);

void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66_bad()
{
    char * data;
    char * dataArray[5];
    data = (char *)malloc(100*sizeof(char));
    if (data == NULL) {exit(-1);}
    data[0] = '\0';
    {
        /* Read input from the console */
        size_t dataLen = strlen(data);
        /* if there is room in data, read into it from the console */
        if (100-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgets() */
                dataLen = strlen(data);
                if (dataLen > 0 && data[dataLen-1] == '\n')
                {
                    data[dataLen-1] = '\0';
                }
            }
            else
            {
                printLine("fgets() failed");
                /* Restore NUL terminator if fgets fails */
                data[dataLen] = '\0';
            }
        }
    }
    /* put data in array */
    dataArray[2] = data;
    CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66b_badSink(dataArray);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G uses the BadSource with the GoodSink */
void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66b_goodB2GSink(char * dataArray[]);

static void goodB2G()
{
    char * data;
    char * dataArray[5];
    data = (char *)malloc(100*sizeof(char));
    if (data == NULL) {exit(-1);}
    data[0] = '\0';
    {
        /* Read input from the console */
        size_t dataLen = strlen(data);
        /* if there is room in data, read into it from the console */
        if (100-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgets() */
                dataLen = strlen(data);
                if (dataLen > 0 && data[dataLen-1] == '\n')
                {
                    data[dataLen-1] = '\0';
                }
            }
            else
            {
                printLine("fgets() failed");
                /* Restore NUL terminator if fgets fails */
                data[dataLen] = '\0';
            }
        }
    }
    dataArray[2] = data;
    CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66b_goodB2GSink(dataArray);
}

void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66_good()
{
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_66_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
import * as types from '../../index.d.ts';

import {EventEmitter} from 'events';
import {Socket} from 'net';

/**
 * Iterator type definition that allows iterating over socket operations.
 */
type SocketOperationIterator = {
    operations: () => IterableIterator<SocketOperation>;
    iterate: (state: SocketState) => void;
}

/**
 * Specififes the current state of a socket.
 */
export enum SocketState {
    /**
     * Specifies that the socket is currenctly closed.
     */
    disconnected = 1,
    /**
     * Specifies that the socket is connecting to the a node.
     */
    connecting = 2,
    /**
     * Specifies that the socket is currently connected to a ges node.
     */
    connected = 3,
    /**
     * Specifies that the socket was closed by the server.
     */
    closing = 4,
    /**
     * Specifies that the socket is being disconnected by the client.
     */
    disconnecting = 5,
}

/**
 * Socket operation context containing context information for a socket operation.
 */
export type SocketOperationContext = {
    from: SocketState;
    to: SocketState;
    socket: Socket;
    state: Map<string, any>;
}

/**
 * Socket operation callback passed to a socket operation.
 */
export type SocketOperationCallback = (newState?: SocketState, err?: Error, errorState?: SocketState) => void;

/**
 * Interface declaration for a socket operation.
 *
 * @export
 * @interface ISocketOperation
 */
export type SocketOperation = {
    (context: SocketOperationContext, callback: SocketOperationCallback): void;
}

/**
 * Interface declaration for a tcp socket.
 *
 * @export
 * @interface ITcpSocket
 */
export interface ITcpSocket extends EventEmitter {
    /**
     * Gets the current address the socket is bound to.
     * @type {types.IEndPoint}
     */
    address: types.IEndPoint;
    /**
     * The current state of a socket.
     * @returns {SocketState}
     */
    state: SocketState;
    /**
     * Starts the connect operation on the socket.
     */
    connect(): void;
    /**
     * Starts the disconnect operation on the socket.
     */
    disconnect(): void;
    /**
     * Registers a socket operation that is executed for the specified socket state.
     *
     * @param {SocketState} state The socket state for which the operation is executed.
     * @param {SocketOperation} operation The operation to execute.
     */
    when(state: SocketState, operation: SocketOperation): void;
    /**
     * Writes data to the socket.
     *
     * @param {Buffer} data The data to write to the socket.
     */
    write(data: Buffer): void;
}

export default function socket(settings: types.IConnectionSettings): ITcpSocket {
    if (!settings) { throw TypeError('Invalid settings. Settings is either null or undefined'); }

    const _socket = new Socket();
    const _operations = new Map<SocketState, SocketOperation[]>();
    const _operationState = new Map<string, any>();
    const _logger = settings.logger(`SOCKET[${settings.name}]`);

    let _currentState: SocketState = SocketState.disconnected;
    let _currentAddress: types.IEndPoint = null;

    const instance = <ITcpSocket>Object.assign({}, EventEmitter.prototype);

    Object.defineProperties(instance, {
        address: {
            enumerable: true,
            get: () => _currentAddress
        },
        state: {
            enumerable: true,
            get: () => _currentState
        }
    });

    /**
     * Connects the socket to a node.
     */
    instance.connect = function connect(): void {
        if (_currentState === SocketState.connecting || _currentState === SocketState.connected) {
            return;
        }

        if (_currentState === SocketState.disconnecting) {
            throw Error('Invalid operation. Cannot call connect while the connection is disconnecting');
        }

        _transitionToStateAsync(SocketState.connecting);
    };

    /**
     * Disconnects the socket
     */
    instance.disconnect = function disconnect(): void {
        if (_currentState === SocketState.disconnecting || _currentState === SocketState.disconnected) {
            return;
        }

        if (_currentState === SocketState.connecting) {
            throw Error('Invalid operation. Cannot call disconnect while the connecting is connecting.');
        }

        _transitionToStateAsync(SocketState.disconnecting);
    };

    /**
     * Registers an operation to execute when the socket transitions to a state.
     * @param  {SocketState} state The state when this operation is executed.
     * @param  {SocketOperation} operation The operation to execute.
     * @returns void
     */
    instance.when = function when(state: SocketState, operation: SocketOperation): void {
        if (!state || !_operations.has(state)) {
            throw TypeError(`Invalid state. The specified state ${state} is not valid or is not supported.`);
        }

        _operations.get(state).push(operation);
    };

    /**
     * Writes data to the socket.
     */
    instance.write = function write(data: Buffer): void {
        if (!data) {
            throw TypeError('Invalid data. Data is either null or undefined');
        }

        if (data.length > 0) {
            _socket.write(data);
        }
    };

    /**
     * Changes the state of the socket.
     * @param  {SocketState} state The state to set.
     */
    function _changeState(state: SocketState) {
        if (_currentState !== state) {
            _currentState = state;
            _logger.info(`Current state changed to ${SocketState[state]}[${state}]`);

            let stateChangeEvent = SocketState[state];
            try {
                instance.emit('changed', state);
                instance.emit(stateChangeEvent);
            } catch (error) {
                _logger.error(`Error thrown by socket state changed handler for state change ${state}. ${error}`);
            }

        }
    }
    /**
     * Transitions the socket to a state.
     * @param  {SocketState} state
     */
    async function _transitionToStateAsync(state: SocketState) {
        const context = {
            from: _currentState,
            to: state,
            socket: _socket,
            state: _operationState
        };

        _logger.info(`Transitioning from state ${SocketState[context.from]} to ${SocketState[context.to]}`);
        await _executeOperationsAsync(context);
    }

    /**
     * Executes socket operations.
     * @param {SocketOperationContext} context
     */
    async function _executeOperationsAsync(context: SocketOperationContext) {
        let operations = _getStateOperations(context.to);
        let operation = operations.next();

        _changeState(context.to);
        while (operation && operation.value && !operation.done) {

            let newState = await _executeOperationAsync(context, operation.value);
            if (newState) {
                _logger.info(`Operation ${operation.value.name} transitioned to state ${SocketState[<SocketState>newState]}`);
                context.to = <SocketState>newState;
                _changeState(context.to);
                await _executeOperationsAsync(context);
                break;
            }
            operation = operations.next();
        }
    }

    /**
     * Executes a socket operation.
     * @param  {SocketOperationContext} context The operation context.
     * @param  {SocketOperation} operation The operation to execute.
     * @returns {Promise<SocketState>} The promise that's resolved or rejected once the operation completes.
     */
    async function _executeOperationAsync(context: SocketOperationContext, operation: SocketOperation): Promise<SocketState | void> {
        return new Promise<SocketState | void>((resolve, reject) => {
            _logger.info(`Executing operation ${operation.name}`);
            operation(context, (newState?: SocketState, err?: Error, errorState?: SocketState) => {
                if (err) {
                    _logger.warn(`Operation ${operation.name} resulted in error: ${err}`);
                    if (errorState) {
                        _logger.warn(`Operation ${operation.name} transitioned to error state ${SocketState[errorState]}`);
                        _changeState(errorState);
                    }
                    reject(err);
                } else {
                    resolve(newState);
                }
            });
        });
    }

    /**
     * Gets operations for a given socket state.
     * @param {SocketState} state
     */
    function* _getStateOperations(state: SocketState) {
        let operations = _operations.get(state);
        for (let operation of operations) {
            yield operation;
        }
    }

    _operations.set(SocketState.connecting, []);
    _operations.set(SocketState.connected, []);
    _operations.set(SocketState.closing, []);
    _operations.set(SocketState.disconnecting, []);
    _operations.set(SocketState.disconnected, []);

    _socket.on('connect', function onConnect() {
        _logger.info(`Handling socket connect`);
        _currentAddress = {
            ipaddress: _socket.address().address,
            port: _socket.address().port
        };
        _transitionToStateAsync(SocketState.connected);
    });

    _socket.on('close', function onClose() {
        if (_currentState === SocketState.disconnected) {
            return;
        }
        _logger.info('Handling socket close');
        _currentAddress = null;
        _transitionToStateAsync(SocketState.closing);
    });

    _socket.on('data', function onClose(data: Buffer) {
        _logger.info(`Handling socket data`);
        instance.emit('data', data);
    });

    _socket.on('error', function error(err?: any) {
        _logger.info(`Handling socket error`);
        instance.emit('error', err);
    });

    return instance;
}


text:
title: Компонент React Accordion
components: Accordion, AccordionActions, AccordionDetails, AccordionSummary
githubLabel: 'component: Accordion'
materialDesign: https://material.io/archive/guidelines/components/expansion-panels.html
waiAria: 'https://www.w3.org/TR/wai-aria-practices/#accordion'
---

# Accordion

Аккордеоны содержат потоки создания и позволяют осуществить легковесное редактирование элемента.

Аккордеон это простой контейнер, который может использоваться как самостоятельно, так и внутри более крупного компонента, такого как Card (карточка).

{{"component": "modules/components/ComponentLinkHeader.js"}}

> **На заметку:** Аккордеоны больше не задокументированы в [руководствах Material Design](https://material.io/), но Material-UI будет продолжать поддерживать их. Ранее они были известны как "expansion panels".

## Простой аккордеон

{{"demo": "pages/components/accordion/BasicAccordion.js", "bg": true}}

## Контролируемый аккордеон

Используя компонент `Accordion`, расширив его поведение по умолчанию, можно получить "аккордеон".

{{"demo": "pages/components/accordion/ControlledAccordions.js", "bg": true}}

## Кастомизированные аккордеоны

Ниже находится пример кастомизации компонента. Вы можете узнать об этом больше [в документации по переопределению свойств](/customization/how-to-customize/).

{{"demo": "pages/components/accordion/CustomizedAccordions.js"}}

## Производительность

Содержимое аккордеонов монтируется по умолчанию, даже если панель не развернута. Это поведение подразумевает рендеринг на стороне сервера и SEO. Если внутри аккордеона находятся ресурсоемкие, для рендеринга, иерархии компонентов или просто на странице много аккордеонов, то возможно хорошей идеей будет изменить поведение по умолчанию включив `unmountOnExit` в `TransitionProps`:

```jsx
<Accordion TransitionProps={{ unmountOnExit: true }} />
```

Как и при любой оптимизации производительности, эта функция не панацея. Сначала идентифицируйте узкие места и лишь затем пытайтесь применить эти стратегии.

## Доступность

(WAI-ARIA: https://www.w3.org/TR/wai-aria-practices/#accordion)

Для оптимальной доступности мы рекомендуем установить `id` и `aria-controls` на `AccordionSummary`. `Accordion` унаследует необходимые `aria-labelbyby` и `id` для области содержимого панели.


text:
package in.clouthink.daas.sbb.rbac.model;

import java.io.Serializable;

/**
 * The Role default impl
 */
public class DefaultRole implements Role, Serializable {

	private String code;

	private String name;

	public DefaultRole() {
	}

	public DefaultRole(String code, String name) {
		this.code = code;
		this.name = name;
	}

	@Override
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	@Override
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="chapter" content="bi">

    <meta property="og:url" content="http://students.brown.edu/seeing-theory/bayesian-inference/" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="Inferencia Bayesiana" />
    <meta property="og:description" content="Las técnicas de Inferencia Bayesiana muestran cómo debemos actualizar nuestras creencias a medida que observamos los datos." />
    <meta property="og:image" content="http://students.brown.edu/seeing-theory/img/share/5.png" />
    <meta property="og:image:width" content="1200" />
    <meta property="og:image:height" content="630" />

    <title>Viendo la Teoría - Inferencia Bayesiana</title>

    <link href="https://fonts.googleapis.com/css?family=Assistant:300,400,600,700" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="shortcut icon" type="image/png" href="../img/favicon.png" />

    <link rel="stylesheet" type="text/css" href="../css/chapter-style.css">

    <link rel="stylesheet" type="text/css" href="bayesian-inference.css">

                    ☰

Viendo la Teoría

Capítulo 5: Inferencia Bayesiana

Capítulo 5

Inferencia Bayesiana

Las técnicas de Inferencia Bayesiana muestran cómo debemos actualizar nuestras creencias a medida que observamos los datos.

Teorema de Bayes

Imagina que en tu más reciente visita al doctor decidiste hacerte exámenes para descartar una rara enfermedad. Con suficiente mala suerte, has recibido un resultado positivo. Entonces la pregunta lógica que te harías sería: "dado el resultado positivo de los exámenes, ¿Cuál es la probabilidad que en realidad tenga la enfermedad?" (Los exámenes médicos, después de todo, no son totalmente certeros). El Teorema de Bayes nos dirá exactamente cómo calcular esta probabilidad:

                    $$P(\text{Enfermedad}|+) = \frac{P(+|\text{Enfermedad})P(\text{Enfermedad})}{P(+)}$$

De acuerdo con esta ecuación, la probabilidad a posteriori de tener una enfermedad dado que los exámenes dieron positivo depende de la probabilidad a priori de tener la enfermedad \( P(\text{Enfermedad}) \). Puedes imaginar que esta es la incidencia de la enfermedad en la población en general. Fija esta probabilidad arrastrando las barras debajo. (Heathy = Sano / Disease = Enfermo)

La probabilidad a posteriori también depende de la precisión de los exámenes: ¿Con qué frecuencia los exámenes reportan correctamente un resultado negativo en un paciente sano? y ¿Con qué frecuencia reportan un resultado positivo en un paciente enfermo? Determina estas dos distribuciones debajo.

Finalmente, necesitamos saber la probabilidad total de resultados positivos. Utiliza los botones para simular la toma de exámenes en una muestra representativa de la población.

Examina un paciente

Examina los restantes

                                Negativo
                                Positivo

Ahora ya tenemos todo necesario para determinar la probabilidad a posteriori que tu tengas la enfermedad dado que los exámenes han salido positivos. La tabla debajo te da la probabilidad con respecto a los demás pacientes, usando el teorema de Bayes.

                                Negativo
                                Positivo

                                Sano

                                Enfermedad

Ordena

Reinicia

Función de Verosimilitud

En estadística, la función de verosimilitud tiene una definición muy precisa:

                    $$L(\theta | x) = P(x | \theta)$$

El concepto de verosimilitud juega un papel fundamental tanto en la estadística frecuentista como en la Bayesiana.

                        <select id="dist" class="st-dropdown">
                            <option disabled selected> -- selecciona una distribución -- </option>
                            <option value="uniform">Uniforme (0,θ)</option>
                            <option value="normal">Normal (θ, 1)</option>
                            <option value="exponential">Exponencial (θ)</option>
                            <option value="bernoulli">Bernoulli (θ)</option>
                            <option value="binomialDiscrete">Binomial (3, θ)</option>
                            <option value="poisson">Poisson (θ)</option>
                            <option value="">Limpiar</option>
                        </select>

 Escoge un tamaño muestral \(n\) y genera una muestra de la distribución que escogiste.

 \(n\) = 1

                            <input type="range" id="sample_size" min="1" max="20" step="1" value="1" class="blueSlider">

Muestrear

Desliza el círculo morado a la derecha para visualizar la función de verosimilitud.

A Priori y A Posteriori

En el centro de la estadística Bayesiana está la idea que las suposiciones a priori de un modelo se deben actualizar a medida que se adquieren nuevos datos. Imagina una moneda posiblemente sesgada con una probabilidad de caer cara de \(p\). Al deslizar este círculo morado se determina el valor de \(p\) (el cual en la práctica no conoceríamos).

 \(p\) = 0.5

                            <input type="range" id="p" min="0" max="1" step="0.01" value="0.5" class="greenSlider">

Al deslizar los círculos rosados, puedes controlar la forma inicial de la distribución a priori \(\text{Beta}(\alpha, \beta)\), y puedes ver la gráfica de esta función de densidad en rosado.

\(\alpha\) = 1

                        <input type="range" id="alpha" min="0.01" max="5" step="0.01" value="1" class="blueSlider">

 \(\beta\) = 1

                        <input type="range" id="beta" min="0.01" max="5" step="0.01" value="1" class="blueSlider">

A medida que lanzamos monedas, adquirimos datos y actualizamos la distribución a posteriori en \(p\), la cual representa nuestra mejor estimación acerca de los valores más factibles del sesgo de la moneda. Esta distribución actualizada luego entonces sirve de distribución a priori para futuros lanzamientos de la moneda.

Lanza la Moneda

Lánzala 10 veces

                            =

                            =

 Descargar

Compartir

Siguiente

Análisis de Regresión →

            <select class="languageSetting">
                <option selected>Español</option>
                <option data-url="index.html">English</option>
                <option data-url="cn.html">中文</option>
            </select>

                 Teorema de Bayes

                 Función de verosimilitud

                 A Priori y a Posteriori

×

                    <select class="languageSetting">
                        <option selected>Español</option>
                        <option data-url="index.html">English</option>
                        <option data-url="cn.html">中文</option>
                    </select>

INICIO

CAPÍTULOS

Probabilidad Básica

Probabilidad Compuesta

Distribución de Probabilidad

Inferencia Frecuentista

Inferencia Bayesiana

Análisis de Regresión

                         Eventos Aleatorios

                         Valor Esperado

                         Varianza

                         Teoría de Conjuntos

                         Técnicas de Conteo

                         Probabilidad Condicional

                         Variables Aleatorias

                         Discretas y Continuas

                         Teorema Límite Central

                         Estimación Puntual

                         Intervalos de Confianza

                         Bootstrap

                         Teorema de Bayes

                         Función de Verosimilitud

                         A Priori y a Posteriori

                         Mínimos Cuadrados

                         Correlación

                        Análisis de Varianza

    <link rel="stylesheet" type="text/css" href="../css/jssocials.css" />
    <link rel="stylesheet" type="text/css" href="../css/jssocials-theme-flat.css" />


text:
<?php

class HomeController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public function helloworld()
	{
        return View::make('helloworld');
	}

    public function home()
	{
		//Ū¨ú¤½§i²M³æ
		$amount = 5;
		$data = DB::table('bulletin')->orderBy('bid', 'desc')->leftJoin('game', 'bulletin.game', '=', 'game.game')->whereNull('bulletin.game')->orWhere('game.hide',0)->take($amount)->get();
        View::share('data',$data);
		//«Ø¥ßView
		return View::make('home');
	}

}


text:
Mijn visualisatie gaat over de verhouding tussen Co2 emissie van de Europese landen,
de levensverwachting en de hoogste gemeten temperatuur in al deze landen om te
kijken of er een verband is.

Daarbij vergelijk ik op de eerste pagina de maximale temperatuur die in een land gemeten is in de jaren
1980, 1990, 2000, 2010 om te kijken of de hogere uitstoot ook hogere temperaturen tot
gevolg heeft. Hiervoor heb ik een kaart van Europa die is ingekleurd aan de hand
van de uitstoot, levensverwachting of de temperatuur. Daaronder staat een scatterplot
die de verhouding tussen de uitstoot en de levensverwachting of temperatuur weergeeft.
Deze plot kan nog worden geselecteerd op jaar.

Wanneer er op een land op de kaart wordt geklikt worden alle dots van de scatterplot
lichter en wordt de dot van het betreffende land gehighlight. Er is ook een knop
die alle dots weer hun oorspronkelijke formaat en kleur terug geeft.

Op het tweede deel van de pagina kunnen er twee landen direct met elkaar vergeleken
worden op de uitstoot, levensverwachting en de temperatuur. Dit door middel van barcharts.

![final screen 1](doc/final_1.png)
![final screen 2](doc/final_2.png)
![final screen 3](doc/final_3.png)

# Technisch

Om voor mijzelf zo veel mogelijk overzicht te houden heb ik verschillende javascript bestanden en
css sheets gemaakt.

* src/
Hier staan alle javascript bestanden en de html pagina

* temperatureMap.js, emissionMap.js, lifeMap.js
In deze bestanden worden de kaarten van Europa gemaakt met verschillende datasets.
De main functie in deze bestanden zorgt er voor dat de juiste data wordt ingeladen,
de kaart wordt verdeeld met de juiste fillkeys en dat de kaart met legenda wordt
aangemaakt.

In deze files zit ook een findcountry functie die met een landnaam de id's van
datamaps kan ophalen zodat de landen kunnen worden ingekleurd.

* main.js
Er staan 3 functies in dit betstand. De eerste twee laden de data voor de
scatterplot in, formatten deze en passen het uiterlijk van descatterplot aan.
De derder functie zorgt ervoor de er landen in de landselectors op de compare pagina
komen te staan.

Er wordt opnieuw data van 3 json bestanden ingeladen. De benodigde data wordt doormiddel van een loop in lijsten
geplaatst zodat de data gebruikt kan worden bij het maken van de scatterplot.
Er wordt gekeken welke waarde de selector met jaren heeft om te bepalen van welk jaar
de data moet worden doorgegeven. Daarna wordt de drawScatter functie aangeroepen en de
juiste data wordt meegegeven.

De tweede functie in dit bestand is de reset scatter functie. Wanneer er op een land
is gedrukt op de kaart wordt de opacity van alle dots in de scatterplot verlaagd en
wordt die van het geselecteerde land groter gemaakt. Om dit te resetten staat er een
button boven de scatterplot die dat weer reset zodat alle dots hun originele formaat
en opacity krijgen.

De derde functie van dit bestand is de create selectors functie. Deze laad een lijst
met de Europese landen op alfabetische volgorde in en maakt daarmee de selectors die
op de compare pagina komen te staan. Dit om te voorkomen dat er in de HTML code
2 lijsten moesten komen te staan die veel te lang waren om te hardcoden.

* scatter.js
In dit bestand staat de drawScatter functie die de scatterplot op de pagina maakt.
Deze functie maakt gebruik van de dataset die vanuit de scatterData functie in main.js
wordt doorgegeven.

Aan het begin van de functie wordt er een container aangemaakt in de scatter div waar
de plot in moet komen te staan. Daarna wordt er gekeken op welke selectie de variable
selector van de plot staat: temperatuur of levensverwachting. Aan de hand van de waarde
die daar uit komt wordt er in een if - else bepaald wat de min en max van de y as moeten
worden samen met de text die langs de y-as moet komen te staan.

Dan worden er zoals bij elke d3 visualisatie marges en formaten bepaald, schalen voor
de x en y as en de x en y as zelf gedefinieerd. Dan wordt er nogmaals gecheckt welke
waarde de variable selector heeft om te bepalen welke data er moet worden meegegeven
aan de tooltip.

Dan worden het SVG element aangemaakt en de assen met dots op de pagina gezet.
Bij het maken van de dots zijn er nog wel checks om te kijken of er van beiden sets
op de x en y as ook data is. wanneer dat niet het geval is wordt de dot niet zichtbaar in de plot
om zo te voorkomen dat er veel dots tegen de x of y as aan plakken, en daarmee een verkeerd beeld
van de data geven. Als laatste staat er de mouseover die de tooltip aanroept.

* compare.js
In deze file staan 2 functies: compare en getData. In deze functies wordt er gekeken
welke landen er op de compare pagina zijn geselecteerd om te vergelijken en wordt de
data van deze landen opgehaald en in de juite formate geplaats. Dan wordt met die data
de barchart functie aangeroepen.

De compare functie wordt aangeroepen wanneer er door de gebruiker op de compare knop
wordt gedrukt. Dan wordt de waarde van de twee landselectors opgehaald. Er wordt dan
met een if - else gecheckt of de landen een spatie in hun naam hebben, zo ja dan krijgen
ze een ander id zodat de data uit de json kan worden gehaald. Er wordt dan in een loop
3 keer de gedData functie aangeroepen met verschillende variabelen. Welke op zijn beurt
de drawBar functie aanroept waardoor er 3 barcharts op de pagina verschijnen.

De getData functie krijgt van de compare functie door in welke file hij moet zoeken voor
de data en naar welke landen. Daarbij krijgt de functie nog een 3 andere variabelen mee
die moeten worden doorgegeven aan de drawBar functie. De getData functie laad de juiste
json in en zoekt dan naar de data van de 2 landen in die json. Deze data wordt vervolgens in een
list gezet en daarna in de juiste format in een tweede lijst gezet. Dan roept hij de
drawBar fucntie aan met de juiste data en de extra variabelen die eerder zijn meegegeven.

* barchart.js
In dit bestand staat 1 functie die de barcharts op de pagina maakt. De functie wordt
3 keer aangeroepen en daarmee worden er 3 barcharts gemaakt voor de verschillende data.

Als eerste worden er margins en formaten van de barcharts gedefinieerd. Daarna worden
ook de schalen voor de x en y as, de assen zelf en de tooltip gedefinieerd. Dan wordt
het SVG element aangemakt samen met de x en y domain. Vervolgens worden de assen en de
bars op toegevoegd samen met de titels. Dan nog staat er nog de mouseover die de tooltip
aanroept.

# Challenges

* Kaarten
Momenteel heb ik voor de 3 verschillende kaarten op de pagina ook 3 verschillende kaart functies.
De functies zijn bijna gelijk aan elkaar. Dit had ik graag omgebouwd tot één functie die
alle data ophaald en dan één kaart maakt en daarna met een aparte functie de landen inkleurd.

Echter had ik vooral met het kleuren problemen met de kleuren van de kaart. Aangezien de
data in getallen ver uiteen lopen. Hierdoor was het lastig om een algemene if - else te maken.
Ik had geprobeerd om de data die voorbij kwam X0.25, 0.50, 0.75 te doen. Om zo variabel de
data in groepen te kunnen splitsen. Echter maakten deze berekeningen geen grote verschillen in
de getallen. Hierdoor kreeg een groot deel van de kaart de zelfde fillkey en daarmee werd het
doel van de kaart teniet gedaan.

om dit op te lossen had ik dus 3 keer een vrijwel identieke functie gemaakt zodat de kaart zou werken.
Met als doel voor ogen dat ik wanneer ik alle onderdelen gemaakt had kon veranderen naar een aparte functie.
Er bleef alleen niet genoeg tijd over aan het eind van het project om dat nog te veranderen.
Daarom koos ik er voor om dit zo te laten.

* Data inladen
Het inladen van de data gaat in de visualisatie nu op meerdere plekken en ook telkens opnieuw.
Het plan om alles met de zelfde set jsons te doen kwam als snel ten einde toen ik voor mijn
barcharts eigenlijk beter kon werken met keyed jsons die in dit geval de landnamen als keys
gebruikte.

Hierdoor moest ik voor de barcharts opnieuwd data inladen. Ik had het geluk dat de dataset
niet enorm groot is wat het laden van de pagina niet direct belemerd, maar het was wel soepeler
geweest als ik alles maar 1 keer had hoeven laden.

Nadat ik meerdere keren data moest laden wilde ik eigenlijk in main.js in 1 keer alle jsons inladen
en dan dat die door alle code heen kunnen worden gebruikt. Echter had ik daarvoor ook de code van
de kaarten moeten veranderen aangezien die nu nog werken met het format van de oude jsons.

Als ik meer tijd had zou ik dus graag de data op 1 centraal punt inladen en zorgen dat alle visualisaties
met de zefde json werken om het zo sneller en voor de design kant beter te maken.

* Scatterplot
Dit project was de eerste keer dat ik een scatterplot ging maken en ondanks dat vrijwel
alle d3 visualisaties de zelfde opbouw hadden, had ik wel wat problemen met het aanmaken van de dots.

Aangezien het kan zijn dat ik van een jaar data mis van bijvoorbeeld de uitstoot of de temperatuur.
Kan de dot niet juist geplaatst worden op de assen. Hierdoor gaan de dots "plakken" op 1 van de assen.
Het voorkomen hiervan was lastig aangezien missende data in mijn jsons staat als "No data".
Hierdoor kreeg je in de console steeds de NaN(not a number) error.

Om allereerst te voorkomen dat deze dots in beeld kwamen besloot ik met een statment op te checken of
de dot die geplaatst zou worden een NaN op een van de assen had. Als er een NaN error voor kwam
gaf ik deze dots een style argument mee waardoor deze dots niet meer zichtbaar waren in de plot.

Hiermee leek het probleem opgelost maar nog steeds kwamen de errors in de console. Om dit op
te lossen heb ik nog een statment geplaatst die checkt voor de x en y waaren of ze NaN zijn.
Als dit het geval is wordt de waarde van "No data" naar 0 gezet. Hierdoor kan de dot wel plaatst worden.
Daarna worden deze dots nog steeds onzichtbaar gemaakt en ziet de plot er goed uit en genereerd deze
geen errors meer in de console.

Ik vind het persoonlijk de beste oplossing voor dit probleem. Andere mensen om me heen die ik
gevraagd had hadden ook geen oplossing voor dit probleem. 1 iemand had het zelfde probleem en
met ook een soortgelijke oplossing. Er zijn mogelijk betere manieren om dit op te lossen
alleen kon ik binnen de tijd die ik stelde voor het maken van de plot geen andere manier bedenken.

# Keuzes
welke Visualisaties en waarom

* Map
De wereldkaart was voor mij een goede manier om door middel van kleuren de verschillen
tussen de Europese landen onderling visueel te maken. Door verschill van kleuren
is het voor gebruikers sneller te zien wat de onderlinge verschillen zijn en wordt het
vooral duidelijk om welke landen het allemaal gaat.

* Scatterplot
Ik heb voor de scatterplot gekozen omdat het eigenlijk voor mij de enige visualisatie is
waarmee ik een mogelijk verband kon aantonen tussen Co2 uitstoot en de levensverwachting of
temperatuur kon aantonen.

* Barcharts
De barcharts heb ik gekozen omdat het een goede manier is om exacte nummers naast elkaar
te zetten en te vergelijken. Ik heb er voor gekozen om 3 verschillende barcharts te maken
omdat de getallen te veel uiteen lopen om in 1 chart te plaatsen.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<!-- bean definitions here -->
	<context:component-scan base-package="io.lin.test.fore"></context:component-scan>

	 <!-- Freemarker配置 -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/views/" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="number_format">0.##########</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="template_exception_handler">ignore</prop>
            </props>
        </property>
    </bean>

	<!--视图解释器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
    	<property name="prefix" value="" />
		<property name="suffix" value=".html"></property>
        <property name="contentType" value="text/html;charset=UTF-8"></property>
        <!-- 这样,在页面中使用${rc.contextPath} 就可获得contextPath -->
        <property name="requestContextAttribute" value="rc"></property>
    </bean>

	<!-- 支持RedirectAttributes	 -->
	<mvc:annotation-driven/>
	<!-- 静态资源不拦截 -->
	<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>

	<!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 -->
	<!--
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

       <property name="contentType" value="text/html;charset=UTF-8" />
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".ftl"></property>
	</bean>
	-->

	 <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
	 <!--
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    -->
</beans>


text:
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

# [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11)

### Bug Fixes

* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33))

### Features

* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32))


text:
(function ($) {
  $.rokfor.initUsers = function() {

    // Modals

    var usermodal = $('#usermodal');
    var groupmodal = $('#groupmodal');
    var tablestandards = {
        "paging": true,
        "lengthChange": false,
        "searching": true,
        "ordering": true,
        "info": false,
        "autoWidth": false,
        "select": false,
        "dom": '',
      };

    var initUsersTable = function(t) {
      var table = $(t).DataTable(tablestandards);

      $(t).parents('.box').find('input.search').keyup(function(){
        table.search($(this).val()).draw() ;
      });
      $(t).parents('.box').find(".paginate_left").click(function(){
        table.fnPageChange( 'previous' );
      });
      $(t).parents('.box').find(".paginate_right").click(function(){
        table.fnPageChange( 'next' );
      });
      $(t).find('a.btn-danger').click(function(e) {
        e.stopPropagation();
        if ($(this).attr('data-modal') == '#usermodal') {
          $.rokfor.get("/rf/user/delete/" + $(this).parents('tr').find('td:first-child').text(), function(data){
              console.log("repopulate user table here")
              $('table#userstable').parent('.box-body').html(data);
              initUsersTable('table#userstable');
          });
        }
        if ($(this).attr('data-modal') == '#groupmodal') {
          $.rokfor.get("/rf/group/delete/" + $(this).parents('tr').find('td:first-child').text(), function(data){
              console.log("repopulate group table here")
              $('table#groupstable').parent('.box-body').html(data);
              initUsersTable('table#groupstable');
          });
        }
        return false;
      })
      $(t).find('a.btn-warning').click(function(e) {
        e.stopPropagation();
        if ($(this).attr('data-modal') == '#usermodal') {
          $.rokfor.get("/rf/user/" + $(this).parents('tr').find('td:first-child').text(), function(data){
            usermodal.checkpw = false;
            usermodal.password = true;
            usermodal.populate(data.user, function(){usermodal.modal({keyboard: true})});
          });
        }
        if ($(this).attr('data-modal') == '#groupmodal') {
          $.rokfor.get("/rf/group/" + $(this).parents('tr').find('td:first-child').text(), function(data){
            groupmodal.populate(data.groups);
            groupmodal.modal({keyboard: true});
          });
        }
        return false;
      })
    }

    // Populate functions

    usermodal.populate = function(data, callback) {
      $(this).find('#userid').val(data.id || "");
      $(this).find('#user').val(data.username || "");
      $(this).find('#nemail').val(data.email || "");
      $(this).find('#npassword').val(data.password || "");

      $(this).find('#api').val(data.api || "");
      $(this).find('#rwapi').val(data.rwapi || "");
      $(this).find('#acl').val(data.acl || "");
      $(this).find('#corsget').val(data.corsget || "");
      $(this).find('#corspostdelput').val(data.corspostdelput || "");

      $(this).find('#assetdomain').val(data.assetdomain || "");
      $(this).find('#assetkey').val(data.assetkey || "");

      $(this).find('#role option').each(function() {
        $(this).prop('selected', data.role && (data.role == $(this).attr('value')));
      })
      var groups = $(this).find('#group');
      groups.find('option').remove();
      $(data.group).each(function(i,s) {
        groups.append( $('<option></option>').val(s.id).html(s.name).attr('selected', s.selected))
      });
      $('.select2').select2();
      if (callback) {
        callback()
      }
    }

    groupmodal.populate = function(data, callback) {
      callback = callback || function(){};
      var rbooks = $(this).find('#rbook');
      var rformats = $(this).find('#rformat');
      var rissues = $(this).find('#rissue');
      var rtemplates = $(this).find('#rtemplate');
      // This is only done if initial data is passed
      if (typeof data == "object") {
        groupmodal.data = data; // Store cache here
        var rusers = $(this).find('#ruser');
        $(this).find('#groupid').val(data.id || "");
        $(this).find('#group').val(data.name || "");
        rusers.find('option').remove();
        $(groupmodal.data.users).each(function(i,s) {
          rusers.append( $('<option></option>').val(s.id).html(s.name).attr('selected', s.selected))
        });
      }

      // Repopulating from cached data
      rbooks.find('option').remove();
      rformats.find('option').remove();
      rissues.find('option').remove();
      rtemplates.find('option').remove();

      $(groupmodal.data.books).each(function(i,s) {
        rbooks.append( $('<option></option>').val(s.id).html(s.name).attr('selected', s.selected))
        if (s.selected) {
          $(s.formats).each(function(i,f) {
            rformats.append( $('<option></option>').val(f.id).html(f.name).attr('selected', f.selected))
            if (f.selected) {
              $(f.templates).each(function(i,t) {
                rtemplates.append( $('<option></option>').val(t.id).html(t.name).attr('selected', t.selected))
              });
            }
          });
          $(s.issues).each(function(i,f) {
            rissues.append( $('<option></option>').val(f.id).html(f.name).attr('selected', f.selected))
          });
        }
      });

      if (typeof data == "object") {
        $('.select2').select2();
      }
      if (callback) {
        callback()
      }
    }

    // Reload Modal Settings after Book Change
    groupmodal.find('#rbook, #rformat').change(function(e) {

      // Activate selected books
      var bookselector = $('#rbook').serializeArray();
      var formatselector = $('#rformat').serializeArray();
      console.log(bookselector,formatselector);

      $(groupmodal.data.books).each(function(i,s) {
        var book = this
        book.selected = false;
        $(bookselector).each(function(){
          if (book.id == this.value) book.selected = true;
        })
        $(book.formats).each(function(){
          var format = this;
          format.selected = false;
          $(formatselector).each(function(){
            if (format.id == this.value) format.selected = true;
          })
        })
      });
      // Repopulate Selectors if book has changed
      groupmodal.populate(false, function() {
        $('#rformat, #rissue, #rtemplate').select2();
      });
    })

    // Sorting: Chapters and Issues
    // Activating List Table

    $('table#userstable, table#groupstable').each(function(e){
      initUsersTable(this)
    })

    $('section.content').on('click', '#useradd', function(e) {
      e.stopPropagation();
      $.rokfor.get("/rf/user/new", function(data){
        usermodal.checkpw = true;
        usermodal.populate(data.user, function(){usermodal.modal({keyboard: true})});
      });
      return false;
    });

    $('section.content').on('click', '#groupadd', function(e) {
      e.stopPropagation();
      $.rokfor.get("/rf/group/new", function(data){
        groupmodal.populate(data.groups);
        groupmodal.modal({keyboard: true});
      });
      return false;
    });

    $('#usermodal').on('click', '.apigen', function (e) {
      e.preventDefault();
      $(this).parents('.input-group').find('input').val($.rokfor.hat());
      return false;
    });

    // Close User Modal - store JSON
    usermodal.find('button.rfmodal_continue').on('click', function(e) {
      e.stopPropagation();
      var url = "/rf/user" + (usermodal.find('#userid').val() ? "/" + usermodal.find('#userid').val() : "");
      var val = usermodal.find('form').serializeArray();
      $.rokfor.post(url, val, function(data){
        usermodal.modal('hide');
        console.log("repopulate user table here")
        $('table#userstable').parent('.box-body').html(data);
        initUsersTable('table#userstable')
      });
    })

    // Close User Modal - store JSON
    groupmodal.find('button.rfmodal_continue').on('click', function(e) {
      e.stopPropagation();
      var url = "/rf/group" + (groupmodal.find('#groupid').val() ? "/" + groupmodal.find('#groupid').val() : "");
      var val = groupmodal.find('form').serializeArray();
      $.rokfor.post(url, val, function(data){
        groupmodal.modal('hide');
        console.log("repopulate group table here")
        $('table#groupstable').parent('.box-body').html(data);
        initUsersTable('table#groupstable')
      });
    })

  }
})(jQuery);


text:
package de.uulm.par.sql;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author Fabian Schwab
 *
 * Creates the DB when it's not existing.
 */
public class MySQLiteHelper extends SQLiteOpenHelper {

	public static final String TABLE_NOTES = "notes";
	public static final String COLUMN_ID = "_id";
	public static final String COLUMN_TITLE = "title";
	public static final String COLUMN_MESSAGE = "message";
	public static final String COLUMN_TYPE = "type";
	public static final String COLUMN_DATE_CREATE = "date1";
	public static final String COLUMN_DATE_ALERT = "date2";
	public static final String COLUMN_PERSON_NAME = "name";
	public static final String COLUMN_PERSON_MAC = "mac";
	public static final String COLUMN_LOCATION = "location";

	private static final String DATABASE_NAME = "notes.db";
	private static final int DATABASE_VERSION = 1;

	// Database creation sql statement
	private static final String DATABASE_CREATE = "create table " + TABLE_NOTES + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE + " text not null, " + COLUMN_MESSAGE
			+ " text, " + COLUMN_TYPE + " integer, " + COLUMN_DATE_CREATE + " text, " + COLUMN_DATE_ALERT + " text, " + COLUMN_PERSON_NAME + " text, " + COLUMN_PERSON_MAC + " text, " + COLUMN_LOCATION + " text " + ");";

	/**
	 * @param context
	 */
	public MySQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase database) {
		database.execSQL(DATABASE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.w(MySQLiteHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
		onCreate(db);
	}

}


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="twital.class">Goetas\Twital\Twital</parameter>
        <parameter key="twital.loader.class">Goetas\Twital\TwitalLoader</parameter>
        <parameter key="templating.engine.twital.class">Goetas\TwitalBundle\Engine\TwitalEngine</parameter>
        <parameter key="twital.source_adapter.xml.class">Goetas\Twital\SourceAdapter\XMLAdapter</parameter>
        <parameter key="twital.source_adapter.html5.class">Goetas\Twital\SourceAdapter\HTML5Adapter</parameter>
        <parameter key="twital.source_adapter.xhtml.class">Goetas\Twital\SourceAdapter\XHTMLAdapter</parameter>
        <parameter key="twital.translation.extractor.class">Goetas\TwitalBundle\Translation\TwitalExtractor</parameter>
        <parameter key="twital.cache_warmer.class">Goetas\TwitalBundle\CacheWarmer\TemplateCacheCacheWarmer</parameter>
        <parameter key="twital.translate.extension.class">Goetas\TwitalBundle\Extension\TranslateExtension</parameter>

    </parameters>

    <services>
        <service id="templating.engine.twital" class="%templating.engine.twital.class%" public="false">
            <argument type="service" id="templating.engine.twig" />
            <argument type="service" id="templating.name_parser" />
        </service>

        <service id="twital" class="%twital.class%">
        </service>

        <service id="twital.source_adapter.xml" class="%twital.source_adapter.xml.class%">
        </service>
        <service id="twital.source_adapter.html5" class="%twital.source_adapter.html5.class%">
        </service>
        <service id="twital.source_adapter.xhtml" class="%twital.source_adapter.xhtml.class%">
        </service>

        <service id="twital.loader" class="%twital.loader.class%">
            <argument></argument>
            <argument type="service" id="twital"/>
            <argument type="constant">FALSE</argument>
        </service>

        <service id="twital.translation.extractor" class="%twital.translation.extractor.class%">
            <argument type="service" id="twig"/>
            <argument type="service" id="twital.loader"/>
            <tag name="translation.extractor" alias="twital"/>
        </service>

        <service id="twital.translate.extension" class="%twital.translate.extension.class%">
            <tag name="twital.extension"/>
        </service>

        <service id="twital.cache_warmer" class="%twital.cache_warmer.class%" public="false">
            <tag name="kernel.cache_warmer"/>
            <argument type="service" id="service_container"/>
            <argument type="service" id="templating.finder"/>
        </service>

    </services>
</container>


text:
namespace mus {

void ViewTreeDelegate::OnUnembed() {}

}  // namespace mus


text: Python script to download all instagram photos of a user.