text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Writing on Imad Ali</title>
    <link>http://imadali.net/tags/writing/</link>
    <description>Recent content in Writing on Imad Ali</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Fri, 15 Jan 2021 16:14:19 -0700</lastBuildDate><atom:link href="http://imadali.net/tags/writing/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>A Year of... Blogging?</title>
      <link>http://imadali.net/posts/a-year-of-blogging/</link>
      <pubDate>Fri, 15 Jan 2021 16:14:19 -0700</pubDate>

      <guid>http://imadali.net/posts/a-year-of-blogging/</guid>
      <description>Maybe it wasn&rsquo;t really &ldquo;blogging&rdquo;&hellip; depends on your definition. I did a pretty bad job of regularly posting what I was writing. Ok, to be brutally honest I didn&rsquo;t actually post any of what I wrote until the new year. But I did regularly write and collect my thoughts throughout 2020 (thanks to Notion for making it so easy). That&rsquo;s the important part, right?
The whole process was incredibly invaluable. Writing did two things for me:</description>
    </item>

    <item>
      <title>An Imagineer Retires</title>
      <link>http://imadali.net/posts/an-imagineer-retires/</link>
      <pubDate>Mon, 11 Jan 2021 16:14:19 -0700</pubDate>

      <guid>http://imadali.net/posts/an-imagineer-retires/</guid>
      <description>Imagineer Joe Rohde retires and, in an interview, said the following that strongly resonated with me&hellip;
 Before you start to make decisions, you have got to do a tremendous amount of work on the fundamental reason why you are doing this at all. You will lose yourself in micro-decisions if you do not first sit down and figure out what this whole thing is about. What are we trying to say.</description>
    </item>

    <item>
      <title>Levels of AI as Levels of Automation</title>
      <link>http://imadali.net/posts/levels-of-ai-as-levels-of-automation/</link>
      <pubDate>Thu, 10 Dec 2020 00:22:23 -0700</pubDate>

      <guid>http://imadali.net/posts/levels-of-ai-as-levels-of-automation/</guid>
      <description>Date: 2020-12-10
I was thinking about the levels of automation for self-driving cars and that made me think about a neat way to interpret the &ldquo;levels&rdquo; of AI. The interpretation is not directly related to how AI concepts are being used in self-driving cars. Rather the interpretation is about the relationship between the driver and the car, and how it parallels the relationship between a researcher and software. So instead of having a driver and a car you have a researcher/engineer/whatever and some software that maintains an autonomous system.</description>
    </item>

    <item>
      <title>Aliasing Different Python Versions</title>
      <link>http://imadali.net/posts/aliasing-different-python-versions/</link>
      <pubDate>Fri, 06 Nov 2020 16:14:19 -0700</pubDate>

      <guid>http://imadali.net/posts/aliasing-different-python-versions/</guid>
      <description>I hit an issue with Python versions when trying to install pyarrow (which, at the time of writing, is not supported by Python 3.9). I use brew to manage my Python versions (see details here) and I wanted to keep the python3 executable to the default version of Python (which is the latest version installed by brew), but still want to have the opportunity to easily use an older version of Python 3.</description>
    </item>

    <item>
      <title>One Sentence Per Line</title>
      <link>http://imadali.net/posts/one-sentence-per-line/</link>
      <pubDate>Wed, 30 Sep 2020 16:14:19 -0700</pubDate>

      <guid>http://imadali.net/posts/one-sentence-per-line/</guid>
      <description>I like this concept and should practice it more often. From what I understand it&rsquo;ll make the Git diffs look a lot cleaner. Ironically I didn&rsquo;t do it for this blog post.</description>
    </item>

    <item>
      <title>Value from Less</title>
      <link>http://imadali.net/posts/value-from-less/</link>
      <pubDate>Mon, 28 Sep 2020 16:14:19 -0700</pubDate>

      <guid>http://imadali.net/posts/value-from-less/</guid>
      <description>I&rsquo;ve been thinking about minimalism a lot lately. Sometimes you get caught up in thinking buying/bringing things into your life will give you value. But it&rsquo;s all really just superficial value. When you have less around you it causes you to reflect about what gives you value. Maybe it&rsquo;s introducing a new object that provides functional value in your daily life. Or maybe it&rsquo;s learning something new, or picking up a project that you&rsquo;ve forgotten&hellip;</description>
    </item>

  </channel>
</rss>


text: Core of the Xpress Framework

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace CosmoW\ODM\Riak\Repository;

use CosmoW\ODM\Riak\DocumentManager;

/**
 * Interface for document repository factory.
 */
interface RepositoryFactory
{
    /**
     * Gets the repository for a document class.
     *
     * @param DocumentManager $documentManager The DocumentManager instance.
     * @param string          $documentName    The name of the document.
     *
     * @return \Doctrine\Common\Persistence\ObjectRepository
     */
    public function getRepository(DocumentManager $documentManager, $documentName);
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
	<title>Invoices</title>

	<link rel="icon" href="../../favicon.ico" type="image/x-icon">

	<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,cyrillic-ext" rel="stylesheet" type="text/css">
	<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">

	<link href="../../plugins/bootstrap/css/bootstrap.css" rel="stylesheet">

	<link href="../../plugins/node-waves/waves.css" rel="stylesheet" />

	<link href="../../plugins/animate-css/animate.css" rel="stylesheet" />

	<link href="../../plugins/bootstrap-colorpicker/css/bootstrap-colorpicker.css" rel="stylesheet" />

	<link href="../../plugins/dropzone/dropzone.css" rel="stylesheet">

	<link href="../../plugins/bootstrap-material-datetimepicker/css/bootstrap-material-datetimepicker.css" rel="stylesheet" />

	<link href="../../plugins/waitme/waitMe.css" rel="stylesheet" />

	<link href="../../plugins/multi-select/css/multi-select.css" rel="stylesheet">

	<link href="../../plugins/jquery-spinner/css/bootstrap-spinner.css" rel="stylesheet">

	<link href="../../plugins/bootstrap-tagsinput/bootstrap-tagsinput.css" rel="stylesheet">

	<link href="../../plugins/bootstrap-select/css/bootstrap-select.css" rel="stylesheet" />

	<link href="../../plugins/sweetalert/sweetalert.css" rel="stylesheet" />

	<link href="../../plugins/nouislider/nouislider.min.css" rel="stylesheet" />

	<link href="../../plugins/jquery-datatable/skin/bootstrap/css/dataTables.bootstrap.css" rel="stylesheet">

	<link href="../../css/style.css" rel="stylesheet">

	<link href="../../css/themes/theme-pink.css" rel="stylesheet" />

	<link href="../../plugins/nprogress/nprogress.css" rel="stylesheet" />

Please Wait

				Flieral Inc. Publisher Dashboard

							 Notifications
							notifications
							0

NOTIFICATIONS

												person_add

12 new members joined

													access_time 14 mins ago

								View All Notifications

							 Tasks
							flag
							0

TASKS

												Footer display issue
												32%

								View All Tasks

 Support CRMsupervisor_account

John Doe

john.doe@example.com

						keyboard_arrow_down

personProfile

languageLanguage

inputSign Out

							home
							Dashboard

							notifications_active
							Applications

							notifications_active
							Placements

							insert_chart
							Activity Monitor

							monetization_on
							Credits & Funds

								Checkout

								Invoices

								Transactions

					© 2016 Flieral Incorporation.

					Electronic Software Distribution Service

							Receipt Information

									Status

								<select id="receiptInformationStatus" class="form-control show-tick" multiple>
									<option>Checked</option>
									<option>Unchecked</option>
								</select>

									Beginning Time Filter

										<input id="receiptInformationBeginningTime" type="text" class="datepicker form-control" placeholder="Enter Beginning Date">

									Ending Time Filter

										<input id="receiptInformationEndingTime" type="text" class="datepicker form-control" placeholder="Enter Ending Date">

									Limit

										<input id="receiptInformationLimit" type="text" class="form-control text-center" value="10" data-rule="quantity">

								<button type="button" id="receiptInformationSearchButton" class="btn bg-cyan btn-block btn-lg waves-effect">Search</button>

											Receipt ID
											Date
											Receipt Info
											Price
											Status


text:
<script>
function boom()
{
  document.location.hash = "#1";
  document.open();
  window.parent.postMessage({}, '*');
}
</script>

<body onload="boom();"></body>


text:
layout: page
title: Sub Global Conference
date: 2016-05-24
author: Christina Bridges
tags: weekly links, java
status: published
summary: Morbi iaculis laoreet orci ut maximus. Pellentesque accumsan, sem.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 08/11/2016
  endDate: 08/12/2016
  ctyhocn: BOIHSHX
  groupCode: SGC
published: true
---
Aenean dignissim enim dolor, at ornare odio iaculis id. Nullam at dignissim augue, nec ornare arcu. Aenean sed lorem sed elit lacinia auctor. Vivamus maximus mi sit amet vestibulum condimentum. Fusce rutrum, lorem ut pretium dignissim, leo lorem blandit orci, iaculis consectetur leo diam quis erat. Nunc eu vulputate turpis. Nunc orci nisi, vehicula id porttitor mattis, tincidunt sit amet nulla. Pellentesque sit amet velit vel enim porttitor tempor. Aliquam erat volutpat. Sed rutrum tempus maximus.
Vivamus interdum lacus a varius lobortis. Nunc nec eros ipsum. Aenean euismod felis non ex blandit, nec gravida lectus efficitur. Fusce mattis id lectus vitae posuere. Nam maximus neque sodales ligula tincidunt luctus. Phasellus in lacinia dui, vitae dictum ante. Nunc quis auctor orci. Nunc nisl augue, ultrices eu luctus imperdiet, finibus auctor purus. Vestibulum dictum, justo eu fringilla gravida, dolor elit sagittis odio, non hendrerit erat massa in neque. Aliquam hendrerit purus non ligula porttitor, eget commodo leo lobortis.

* Phasellus interdum leo in mi lobortis, et faucibus diam facilisis
* Ut pharetra ligula eu felis viverra viverra
* Pellentesque condimentum dolor eu ex rhoncus, et elementum arcu molestie
* Nullam at velit dapibus, consectetur tortor egestas, finibus orci
* Duis lacinia quam a leo lobortis pulvinar
* Donec posuere sem non nulla eleifend efficitur.

Sed condimentum ex quis hendrerit fringilla. Ut consectetur dui a quam ornare, tempus mollis felis fringilla. Nulla nec turpis et magna ullamcorper dignissim vitae non purus. Nulla mollis purus vel nunc viverra convallis. Aliquam bibendum sem auctor lorem pellentesque facilisis. Aenean at ultricies orci. Donec efficitur lobortis mollis. In ultricies blandit libero ut ultrices.


text:
FROM jwilder/dockerize

COPY build/tests_entrypoint /

ENTRYPOINT ["dockerize", "-wait", "tcp://stan:4222"]


text:
namespace Group
{

  // compute high-quality discrete 1D gaussian kernel
  // for histogram smoothing
  static void gaussian1D (const float sigma,      // sigma of gaussian
                          const float support,    // units of sigma
                          const float res,        // bin width
                          Util::Array1D<float>& kernel)    // result
  {
      const int zoom = 100;       // must be even
      const int r = (int) ceil (sigma * support / res);
      const int d = 2 * r + 1;
      kernel.resize (d);
      kernel.init (0);
      float sum = 0;
      for (int i = 0; i < r * zoom + zoom / 2; i++)
      {
        const float x = ((float) i + 0.5) / zoom * res;
        const int index = (int) rint ((float) x / res);
        const float val = exp (-x * x / (2 * sigma * sigma));
        assert (index >= 0 && index <= r);
        kernel (r + index) += val;
        kernel (r - index) += val;
        sum += 2 * val;
      }

      // Unit L1 norm.
      for (int i = 0; i < d; i++)
      {
        kernel (i) /= sum;
      }
  }

  void computeCG(const Util::Image& channel, const int nbins, const float scale, const int norient,
                 const float sigma, const float support, const float zoom, Util::ImageStack& cg)
  {
      // check arguments
      assert (nbins > 0);
      assert (scale > 0);
      assert (norient > 0);
      assert (sigma > 0);
      assert (support > 0);
      assert (zoom > 0);

      const int width = channel.size(0);
      const int height = channel.size(1);

      // all color values must be in [0,1]
      for (int x = 0; x < width; x++)
      {
        for (int y = 0; y < height; y++)
        {
          const float a = channel(x,y);
          assert (a >= 0 && a <= 1);
        }
      }

      // allocate cg
      cg.resize(norient,width,height);

      // construct our gaussian blob that we will add to the
      // histogram for each sample
      Util::Array1D<float> kernel;
      gaussian1D (sigma, support, sigma / zoom, kernel);
      assert ((kernel.size () % 2) == 1);
      const int kd = kernel.size ();
      const int kr = kd / 2;
      assert (kd == 2 * kr + 1);

      // precompute spatial offsets for the  kernel
      Util::Array1D<float> offsets(kd);
      for (int i = -kr; i <= kr; i++)
      {
        offsets(kr+i) = (float) i / kr / zoom * sigma * support;
      }

      // compute pie slice membership for each window location
      // count the number of pixels inside the disc
      const int windowRadius = (int) ceil (scale);
      const int windowDiameter = 2 * windowRadius;
      Util::Array2D<int> pie (windowDiameter, windowDiameter);
      for (int u = -windowRadius; u < windowRadius; u++)
      {
        for (int v = -windowRadius; v < windowRadius; v++)
        {
          const int i = u + windowRadius;
          const int j = v + windowRadius;
          float theta = atan2(v+0.5,u+0.5);
          if (theta < 0)
          {
            theta += 2 * M_PI;
          }
          assert (theta >= 0 && theta < 2 * M_PI);
          const int slice = (int) floor (theta / (M_PI / norient));
          assert (slice >= 0 && slice < 2 * norient);
          pie(i,j) = slice;
        }
      }

      // left and right disc histograms
      Util::Array1D<float> histL(nbins);
      Util::Array1D<float> histR(nbins);
      Util::Array2D<float> histPie(2*norient,nbins);

      Util::Message::startBlock(width,"CG computation");
      for (int x = 0; x < width; x++)
      {
        Util::Message::stepBlock();
        for (int y = 0; y < height; y++)
        {
          // comute the pie slice histograms
          histPie.init(0);
          for (int u = -windowRadius; u < windowRadius; u++)
          {
            for (int v = -windowRadius; v < windowRadius; v++)
            {
              if ((u+0.5)*(u+0.5) + (v+0.5)*(v+0.5) > scale*scale) { continue; }
              const int xi = x + u;
              const int yi = y + v;
              if (xi < 0 || xi >= width) { continue; }
              if (yi < 0 || yi >= height) { continue; }

              // figure out which pie slice we're in
              const int slice = pie(windowRadius+u,windowRadius+v);

              // get this point's color
              const float a = channel(xi,yi);
              for (int i = 0; i < kd; i++)
              {
                const float ai = a + offsets(i);
                int bin1 = (int) floor (ai * nbins);
                bin1 = Util::minmax(0, bin1, nbins-1);
                histPie(slice, bin1) += kernel(i);
              }
            }
          }

  #define ACC(h,OP,slice) { \
    const int __slice = slice; \
    for (int i = 0; i < nbins; i++) \
      h(i) OP histPie(__slice,i); \
    }
          // set up L histogram (minus last slice)
          histL.init (0);
          for (int orient = 0; orient < norient - 1; orient++)
          {
            ACC(histL,+=,orient);
          }

          // set up R histogram (minus last slice)
          histR.init (0);
          for (int orient = norient; orient < 2 * norient - 2; orient++)
          {
            ACC(histR,+=,orient);
          }

          // spin the disc
          for (int orient = 0; orient < norient; orient++)
          {
            // add next slice into L and R histograms
            ACC(histL,+=,orient+norient-1);
            ACC(histR,+=,Util::wrap(orient-1,2*norient));
            // normalize L,R histograms
            float sumL = 0;
            float sumR = 0;
            for (int i = 0; i < nbins; i++)
            {
              sumL += histL(i);
              sumR += histR(i);
            }
            if (sumL <= 0)
            {
              sumL = 1;
            }
            if (sumR <= 0)
            {
              sumR = 1;
            }
            assert(sumL > 0);
            assert(sumR > 0);

            // compute chi-squared distance
            float chi2 = 0;
            for (int i = 0; i < nbins; i++)
            {
              float LL = (histL(i) / sumL);
              float RR = (histR(i) / sumR);
              float sum = LL + RR;
              if (sum > 0)
              {
                float dif = LL - RR;
                chi2 += dif*dif / sum;
              }
            }
            chi2 *= 0.5f;
            chi2 = Util::minmax (0.0f,chi2,1.0f);
            assert (chi2 >= 0 && chi2 <= 1);
            cg(orient,x,y) = chi2;

            //subtract last slice
            if (orient < norient - 1)
            {
              ACC(histL,-=,orient);
              ACC(histR,-=,orient+norient);
            }
          }
        }
  #undef ACC
      }
      Util::Message::endBlock();
  }

  // precompute histogram for a given scale
  void computeColorHistograms (const Util::Image& channel, const int nbins,
                               const float scale, const float sigma,
                               const float support, const float zoom,
                               Histogram& histogram)
  {
      // check arguments
      assert (nbins > 0);
      assert (scale> 0);
      assert (sigma > 0);
      assert (support > 0);
      assert (zoom > 0);

      const int width = channel.size(0);
      const int height = channel.size(1);

      // all color values must be in [0,1]
      for (int x = 0; x < width; x++)
      {
        for (int y = 0; y < height; y++)
        {
          const float a = channel(x,y);
          assert (a >= 0 && a <= 1);
        }
      }

      // construct our gaussian blob that we will add to the
      // histogram for each sample
      Util::Array1D<float> kernel;
      gaussian1D (sigma, support, sigma / zoom, kernel);
      assert ((kernel.size () % 2) == 1);
      const int kd = kernel.size ();
      const int kr = kd / 2;
      assert (kd == 2 * kr + 1);

      // precompute spatial offsets for the  kernel
      Util::Array1D<float> offsets(kd);
      for (int i = -kr; i <= kr; i++)
      {
        offsets(kr+i) = (float) i / kr / zoom * sigma * support;
      }

      // allocate histogram
      histogram.resize(width,height,nbins);
      histogram.init(0);

      // minimum square window radius to include disc
      const int windowRadius = (int)ceil(scale);

      Util::Message::startBlock(width,"color histogram patch computation");
      for (int x = 0; x < width; x++)
      {
        Util::Message::stepBlock();
        for (int y = 0; y < height; y++)
        {
          for (int u = -windowRadius; u <= windowRadius; u++)
          {
            for (int v = -windowRadius; v <= windowRadius; v++)
            {
              if (u*u + v*v > scale*scale) { continue; }
              const int xi = x + u;
              const int yi = y + v;
              if (xi < 0 || xi >= width) { continue; }
              if (yi < 0 || yi >= height) { continue; }

              // get this point's color
              const float a = channel(xi,yi);
              for (int i = 0; i < kd; i++)
              {
                const float ai = a + offsets(i);
                int bin = (int) floor (ai * nbins);
                bin = Util::minmax(0, bin, nbins-1);
                histogram(x,y,bin) += kernel(i);
              }
            }
          }
        }
      }
      Util::Message::endBlock();
      Util::Message::startBlock("histogram normalization");
      normalizeHistogram(histogram);
      Util::Message::endBlock();
  }

  // precompute histogram for a given scale
  void computeColorHistograms (const Util::Image& channel, const int nbins, const float sigma,
                               const float support, const float zoom, const SupportMap& supportMap,
                               Histogram& histogram)
  {
      // check arguments
      assert (nbins > 0);
      assert (sigma > 0);
      assert (support > 0);
      assert (zoom > 0);

      const int width = channel.size(0);
      const int height = channel.size(1);

      // all color values must be in [0,1]
      for (int x = 0; x < width; x++)
      {
        for (int y = 0; y < height; y++)
        {
          assert (channel(x,y) >= 0 && channel(x,y) <= 1);
        }
      }

      // construct our gaussian blob that we will add to the
      // histogram for each sample
      Util::Array1D<float> kernel;
      gaussian1D (sigma, support, sigma / zoom, kernel);
      assert ((kernel.size () % 2) == 1);
      const int kd = kernel.size ();
      const int kr = kd / 2;
      assert (kd == 2 * kr + 1);

      // precompute spatial offsets for the  kernel
      Util::Array1D<float> offsets(kd);
      for (int i = -kr; i <= kr; i++)
      {
        offsets(kr+i) = (float) i / kr / zoom * sigma * support;
      }

      // allocate histogram
      histogram.resize(width,height,nbins);
      histogram.init(0);

      Util::Message::startBlock(width,"weighted color histogram patch computation");
      for (int x = 0; x < width; x++)
      {
        Util::Message::stepBlock();
        for (int y = 0; y < height; y++)
        {

          for (int i = 0; i < supportMap(x,y).size(); i++)
          {
            // compute coordinates of point in the window
            const int ix = supportMap(x,y)(i).x;
            const int iy = supportMap(x,y)(i).y;
            assert(ix >= 0);
            assert(ix < width);
            assert(iy >= 0);
            assert(iy < height);

            // get this point's color and weighting
            const float a = channel(ix,iy);
            const float weight = supportMap(x,y)(i).sim;

            for (int i = 0; i < kd; i++)
            {
              const float ai = a + offsets(i);
              int bin = (int) floor (ai * nbins);
              bin = Util::minmax(0, bin, nbins-1);
              histogram(x,y,bin) += weight*kernel(i);
            }
          }
        }
      }
      Util::Message::endBlock();

      Util::Message::startBlock("histogram normalization");
      normalizeHistogram(histogram);
      Util::Message::endBlock();
  }

  //
  // given two points and the color histograms, compute
  // chisquared distance between them
  //
  void colorSimilarity(const Histogram& histogram,
                         const int x1, const int y1,
                         const int x2, const int y2, float& similarity)
  {
    chiSquared(histogram,x1,y1,x2,y2,similarity);
  }

} //namespace Group


text:
#include "DT3Core/Types/Animation/SkeletonJoint.hpp"
#include "DT3Core/Types/FileBuffer/Archive.hpp"
#include "DT3Core/Types/FileBuffer/ArchiveData.hpp"

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

namespace DT3 {

//==============================================================================
/// Standard class constructors/destructors
//==============================================================================

SkeletonJoint::SkeletonJoint (void)
	:	_index						(0)
{

}

SkeletonJoint::SkeletonJoint (const SkeletonJoint &rhs)
	:	_name						(rhs._name),
		_name_hash					(rhs._name_hash),
		_index						(rhs._index),
		_local_transform			(rhs._local_transform),
		_local_transform_inverse	(rhs._local_transform_inverse),
		_world_transform			(rhs._world_transform),
		_world_transform_inverse	(rhs._world_transform_inverse),
		_children					(rhs._children)
{

}

SkeletonJoint::SkeletonJoint (SkeletonJoint &&rhs)
	:	_name						(std::move(rhs._name)),
		_name_hash					(rhs._name_hash),
		_index						(rhs._index),
		_local_transform			(rhs._local_transform),
		_local_transform_inverse	(rhs._local_transform_inverse),
		_world_transform			(rhs._world_transform),
		_world_transform_inverse	(rhs._world_transform_inverse),
		_children					(std::move(rhs._children))
{

}

SkeletonJoint& SkeletonJoint::operator = (const SkeletonJoint &rhs)
{
	_name = rhs._name;
	_name_hash = rhs._name_hash;
	_index = rhs._index;
	_local_transform = rhs._local_transform;
	_local_transform_inverse = rhs._local_transform_inverse;
	_world_transform = rhs._world_transform;
	_world_transform_inverse = rhs._world_transform_inverse;
	_children = rhs._children;
    return (*this);
}

SkeletonJoint& SkeletonJoint::operator = (SkeletonJoint &&rhs)
{
	_name = std::move(rhs._name);
	_name_hash = rhs._name_hash;
	_index = rhs._index;
	_local_transform = rhs._local_transform;
	_local_transform_inverse = rhs._local_transform_inverse;
	_world_transform = rhs._world_transform;
	_world_transform_inverse = rhs._world_transform_inverse;
	_children = std::move(rhs._children);
    return (*this);
}

SkeletonJoint::~SkeletonJoint (void)
{

}

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

void SkeletonJoint::archive (const std::shared_ptr<Archive> &archive)
{
    *archive << ARCHIVE_DATA_RAW(_name, DATA_PERSISTENT);
    *archive << ARCHIVE_DATA_RAW(_name_hash, DATA_PERSISTENT);
    *archive << ARCHIVE_DATA_RAW(_index, DATA_PERSISTENT);
    *archive << ARCHIVE_DATA_RAW(_local_transform, DATA_PERSISTENT);
    *archive << ARCHIVE_DATA_RAW(_local_transform_inverse, DATA_PERSISTENT);
    *archive << ARCHIVE_DATA_RAW(_world_transform, DATA_PERSISTENT);
    *archive << ARCHIVE_DATA_RAW(_world_transform_inverse, DATA_PERSISTENT);

    DTsize children_size = _children.size();
    *archive << ARCHIVE_DATA_RAW(children_size, DATA_PERSISTENT);
    _children.resize(children_size);

    for (auto &child : _children) {
        child.archive(archive);
    }
}

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

} // DT3


text:
package net.kucoe.elvn.lang.result;

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

import net.kucoe.elvn.*;
import net.kucoe.elvn.lang.ELCommand;
import net.kucoe.elvn.util.Config;
import net.kucoe.elvn.util.Display;

/**
 * Task changes over searched tasks.
 *
 * @author Vitaliy Basyuk
 */
public class SearchTask extends TaskResult {

    /**
     * Search query.
     */
    public final String query;

    /**
     * Constructs SearchTask.
     */
    public SearchTask() {
        this(null, null, null);
    }

    /**
     * Constructs SearchTask.
     *
     * @param list
     * @param text
     * @param query
     */
    public SearchTask(final String list, final String text, final String query) {
        super(list, patternText(text, query));
        this.query = query;
    }

    protected static String patternText(final String text, final String query) {
        String res = text;
        if (res != null && res.startsWith("%")) {
            res = query + res;
        }
        return res;
    }

    @Override
    public String execute(final Display display, final Config config) throws Exception {
        String currentList = display.getCurrentList();
        if (ELCommand.Ideas.el().equals(currentList)) {
            List<Idea> ideas = config.findIdeas(query);
            if (text != null) {
                for (Idea idea : ideas) {
                    config.saveIdea(new Idea(idea.getId(), processText(idea.getText(), text)));
                }
            }
            ideas = config.findIdeas(query);
            display.showIdeas(ideas);
            return currentList;
        }
        List<Task> tasks = config.findTasks(query);
        if (text != null || list != null) {
            for (Task task : tasks) {
                updateTask(task, config, currentList);
            }
        }
        List<Task> result = new ArrayList<Task>();
        for (Task t : tasks) {
            result.add((Task) config.getById(t.getId()));
        }
        display.showTasks(result);
        return ListColor.All.toString();
    }

}


text:
import cv2
import numpy as np
import sys
import os
from .bbox import BoundBox, bbox_iou
from scipy.special import expit
import hashlib, math

def md5check(md5sum,weights_file):
    if md5sum != "":
        read_file_hex = hashlib.md5(open(weights_file,'rb').read()).hexdigest()
        if read_file_hex != md5sum:
            print("ERROR: md5 checksum of the provided weights file doesn't match!")
            sys.exit(1)
        else:
            print("MD5 check on your weights: correct.")
    else:
        print(":: Kind notice :: No md5 sum provided. Consider adding it once you have some trained weights to avoid great confusion in the future")

def _sigmoid(x):
    return expit(x)

def makedirs(path):
    try:
        os.makedirs(path)
    except OSError:
        if not os.path.isdir(path):
            raise

def evaluate(model,
             generator,
             iou_threshold=0.5,
             obj_thresh=0.5,
             nms_thresh=0.45,
             net_h=416,
             net_w=416,
             save_path=None):
    """ Evaluate a given dataset using a given model.
    code originally from https://github.com/fizyr/keras-retinanet

    # Arguments
        model           : The model to evaluate.
        generator       : The generator that represents the dataset to evaluate.
        iou_threshold   : The threshold used to consider when a detection is positive or negative.
        obj_thresh      : The threshold used to distinguish between object and non-object
        nms_thresh      : The threshold used to determine whether two detections are duplicates
        net_h           : The height of the input image to the model, higher value results in better accuracy
        net_w           : The width of the input image to the model
        save_path       : The path to save images with visualized detections to.
    # Returns
        A dict mapping class names to mAP scores.
    """
    # gather all detections and annotations
    all_detections     = [[None for i in range(generator.num_classes())] for j in range(generator.size())]
    all_annotations    = [[None for i in range(generator.num_classes())] for j in range(generator.size())]

    for i in range(generator.size()):
        raw_image = [generator.load_image(i)]

        # make the boxes and the labels
        pred_boxes = get_yolo_boxes(model, raw_image, net_h, net_w, generator.get_anchors(), obj_thresh, nms_thresh)[0]

        score = np.array([box.get_score() for box in pred_boxes])
        pred_labels = np.array([box.label for box in pred_boxes])

        if len(pred_boxes) > 0:
            pred_boxes = np.array([[box.xmin, box.ymin, box.xmax, box.ymax, box.get_score()] for box in pred_boxes])
        else:
            pred_boxes = np.array([[]])

        # sort the boxes and the labels according to scores
        score_sort = np.argsort(-score)
        pred_labels = pred_labels[score_sort]
        pred_boxes  = pred_boxes[score_sort]

        # copy detections to all_detections
        for label in range(generator.num_classes()):
            all_detections[i][label] = pred_boxes[pred_labels == label, :]

        annotations = generator.load_annotation(i)

        # copy detections to all_annotations
        for label in range(generator.num_classes()):
            all_annotations[i][label] = annotations[annotations[:, 4] == label, :4].copy()

    # compute mAP by comparing all detections and all annotations
    average_precisions = {}

    for label in range(generator.num_classes()):
        false_positives = np.zeros((0,))
        true_positives  = np.zeros((0,))
        scores          = np.zeros((0,))
        num_annotations = 0.0

        for i in range(generator.size()):
            detections           = all_detections[i][label]
            annotations          = all_annotations[i][label]
            num_annotations     += annotations.shape[0]
            detected_annotations = []

            for d in detections:
                scores = np.append(scores, d[4])

                if annotations.shape[0] == 0:
                    false_positives = np.append(false_positives, 1)
                    true_positives  = np.append(true_positives, 0)
                    continue

                overlaps            = compute_overlap(np.expand_dims(d, axis=0), annotations)
                assigned_annotation = np.argmax(overlaps, axis=1)
                max_overlap         = overlaps[0, assigned_annotation]

                if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations:
                    false_positives = np.append(false_positives, 0)
                    true_positives  = np.append(true_positives, 1)
                    detected_annotations.append(assigned_annotation)
                else:
                    false_positives = np.append(false_positives, 1)
                    true_positives  = np.append(true_positives, 0)

        # no annotations -> AP for this class is 0 (is this correct?)
        if num_annotations == 0:
            average_precisions[label] = 0
            continue

        # sort by score
        indices         = np.argsort(-scores)
        false_positives = false_positives[indices]
        true_positives  = true_positives[indices]

        # compute false positives and true positives
        false_positives = np.cumsum(false_positives)
        true_positives  = np.cumsum(true_positives)

        # compute recall and precision
        recall    = true_positives / num_annotations
        precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps)

        # compute average precision
        average_precision  = compute_ap(recall, precision)
        average_precisions[label] = average_precision

    return average_precisions

def correct_yolo_boxes(boxes, image_h, image_w, net_h, net_w):
    if (float(net_w)/image_w) < (float(net_h)/image_h):
        new_w = net_w
        new_h = (image_h*net_w)/image_w
    else:
        new_h = net_w
        new_w = (image_w*net_h)/image_h

    for i in range(len(boxes)):
        x_offset, x_scale = (net_w - new_w)/2./net_w, float(new_w)/net_w
        y_offset, y_scale = (net_h - new_h)/2./net_h, float(new_h)/net_h

        boxes[i].xmin = int((boxes[i].xmin - x_offset) / x_scale * image_w)
        boxes[i].xmax = int((boxes[i].xmax - x_offset) / x_scale * image_w)
        boxes[i].ymin = int((boxes[i].ymin - y_offset) / y_scale * image_h)
        boxes[i].ymax = int((boxes[i].ymax - y_offset) / y_scale * image_h)

def do_nms(boxes, nms_thresh):
    if len(boxes) > 0:
        nb_class = len(boxes[0].classes)
    else:
        return

    for c in range(nb_class):
        sorted_indices = np.argsort([-box.classes[c] for box in boxes])

        for i in range(len(sorted_indices)):
            index_i = sorted_indices[i]

            if boxes[index_i].classes[c] == 0: continue

            for j in range(i+1, len(sorted_indices)):
                index_j = sorted_indices[j]

                if bbox_iou(boxes[index_i], boxes[index_j]) >= nms_thresh:
                    boxes[index_j].classes[c] = 0

def decode_netout(netout, anchors, obj_thresh, net_h, net_w):
    grid_h, grid_w = netout.shape[:2]
    nb_box = 3
    netout = netout.reshape((grid_h, grid_w, nb_box, -1))
    nb_class = netout.shape[-1] - 5

    boxes = []

    netout[..., :2]  = _sigmoid(netout[..., :2])
    netout[..., 4:]  = _sigmoid(netout[..., 4:])
    netout[..., 5:]  = netout[..., 4][..., np.newaxis] * netout[..., 5:]
    netout[..., 5:] *= netout[..., 5:] > obj_thresh

    for i in range(grid_h*grid_w):
        row = i // grid_w
        col = i % grid_w

        for b in range(nb_box):
            # 4th element is objectness score
            objectness = netout[row, col, b, 4]

            if(objectness <= obj_thresh): continue

            # first 4 elements are x, y, w, and h
            x, y, w, h = netout[row,col,b,:4]

            x = (col + x) / grid_w # center position, unit: image width
            y = (row + y) / grid_h # center position, unit: image height
            w = anchors[2 * b + 0] * np.exp(w) / net_w # unit: image width
            h = anchors[2 * b + 1] * np.exp(h) / net_h # unit: image height

            # last elements are class probabilities
            classes = netout[row,col,b,5:]

            box = BoundBox(x-w/2, y-h/2, x+w/2, y+h/2, objectness, classes)

            boxes.append(box)

    return boxes

def preprocess_input(image, net_h, net_w):
    new_h, new_w, _ = image.shape

    # determine the new size of the image
    if (float(net_w)/new_w) < (float(net_h)/new_h):
        new_h = (new_h * net_w)//new_w
        new_w = net_w
    else:
        new_w = (new_w * net_h)//new_h
        new_h = net_h

    # resize the image to the new size
    resized = cv2.resize(image[:,:,::-1]/255., (new_w, new_h))

    # embed the image into the standard letter box
    new_image = np.ones((net_h, net_w, 3)) * 0.5
    new_image[(net_h-new_h)//2:(net_h+new_h)//2, (net_w-new_w)//2:(net_w+new_w)//2, :] = resized
    new_image = np.expand_dims(new_image, 0)

    return new_image

def normalize(image):
    return image/255.

def get_yolo_boxes(model, images, net_h, net_w, anchors, obj_thresh, nms_thresh):
    image_h, image_w, _ = images[0].shape
    nb_images           = len(images)
    batch_input         = np.zeros((nb_images, net_h, net_w, 3))

    # preprocess the input
    for i in range(nb_images):
        batch_input[i] = preprocess_input(images[i], net_h, net_w)

    # run the prediction
    batch_output = model.predict_on_batch(batch_input)
    batch_boxes  = [None]*nb_images

    for i in range(nb_images):
        yolos = [batch_output[0][i], batch_output[1][i], batch_output[2][i]]
        boxes = []

        # decode the output of the network
        for j in range(len(yolos)):
            yolo_anchors = anchors[(2-j)*6:(3-j)*6] # config['model']['anchors']
            boxes += decode_netout(yolos[j], yolo_anchors, obj_thresh, net_h, net_w)

        # correct the sizes of the bounding boxes
        correct_yolo_boxes(boxes, image_h, image_w, net_h, net_w)

        # suppress non-maximal boxes
        do_nms(boxes, nms_thresh)

        batch_boxes[i] = boxes

    return batch_boxes

def compute_overlap(a, b):
    """
    Code originally from https://github.com/rbgirshick/py-faster-rcnn.
    Parameters
    ----------
    a: (N, 4) ndarray of float
    b: (K, 4) ndarray of float
    Returns
    -------
    overlaps: (N, K) ndarray of overlap between boxes and query_boxes
    """
    area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])

    iw = np.minimum(np.expand_dims(a[:, 2], axis=1), b[:, 2]) - np.maximum(np.expand_dims(a[:, 0], 1), b[:, 0])
    ih = np.minimum(np.expand_dims(a[:, 3], axis=1), b[:, 3]) - np.maximum(np.expand_dims(a[:, 1], 1), b[:, 1])

    iw = np.maximum(iw, 0)
    ih = np.maximum(ih, 0)

    ua = np.expand_dims((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]), axis=1) + area - iw * ih

    ua = np.maximum(ua, np.finfo(float).eps)

    intersection = iw * ih

    return intersection / ua

def compute_ap(recall, precision):
    """ Compute the average precision, given the recall and precision curves.
    Code originally from https://github.com/rbgirshick/py-faster-rcnn.

    # Arguments
        recall:    The recall curve (list).
        precision: The precision curve (list).
    # Returns
        The average precision as computed in py-faster-rcnn.
    """
    # correct AP calculation
    # first append sentinel values at the end
    mrec = np.concatenate(([0.], recall, [1.]))
    mpre = np.concatenate(([0.], precision, [0.]))

    # compute the precision envelope
    for i in range(mpre.size - 1, 0, -1):
        mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])

    # to calculate area under PR curve, look for points
    # where X axis (recall) changes value
    i = np.where(mrec[1:] != mrec[:-1])[0]

    # and sum (\Delta recall) * prec
    ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
    return ap

"""
Cut the image to a multiply of 32
"""
def makeYoloCompatible(image):
    im_height, im_width = image.shape[:2]
    new_width = 32 * math.floor(im_width / 32)
    new_height = 32 * math.floor(im_height / 32)
    im_yolo = image[0:new_height,0:new_width,:]
    return im_yolo

def pleaseCheckMyDirectories(config, data_dir):
    print('Checking if all output directories exist alright')

    preped_images_dir = data_dir + config['preped_images_dir']
    groundtruths_dir = data_dir + config['groundtruths_dir']
    predictions_dir = data_dir + config['predictions_dir']
    annotations_dir = data_dir + config['annotations_dir']
    bbox_images_dir = data_dir + config['bbox_images_dir']
    tracks_dir = data_dir + config['tracks_dir']

    dirs = [
        preped_images_dir, groundtruths_dir, predictions_dir, annotations_dir, bbox_images_dir, tracks_dir
    ]

    for dir in dirs:
        if not os.path.isdir(dir):
            print('Creating ' + dir)
            os.mkdir(dir)


text:
package main

import (
	"github.com/codegangsta/martini"

	. "github.com/rastasheep/todo/controllers"
)

func main() {
	m := martini.Classic()
   m.Use(martini.Static("views"))

	m.Get("/tasks", GetTasks)
	m.Post("/task", CreateTask)
	m.Get("/task/:id", FindTask, GetTask)
	m.Put("/task/:id", FindTask, UpdateTask)

	m.Run()
}


text:
package org.apache.cassandra.distributed.test;

import org.junit.Test;

import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICoordinator;

import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
import static org.apache.cassandra.distributed.shared.AssertUtils.row;

public class CountersTest extends TestBaseImpl
{
    @Test
    public void testUpdateCounter() throws Throwable
    {
        testUpdateCounter(false);
    }

    @Test
    public void testUpdateCounterWithDroppedCompactStorage() throws Throwable
    {
        testUpdateCounter(true);
    }

    private static void testUpdateCounter(boolean droppedCompactStorage) throws Throwable
    {
        try (Cluster cluster = Cluster.build(2).withConfig(c -> c.with(GOSSIP, NATIVE_PROTOCOL).set("enable_drop_compact_storage", true)).start())
        {
            cluster.schemaChange("CREATE KEYSPACE k WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");

            String createTable = "CREATE TABLE k.t ( k int, c int, total counter, PRIMARY KEY (k, c))";
            if (droppedCompactStorage)
            {
                cluster.schemaChange(createTable + " WITH COMPACT STORAGE");
                cluster.schemaChange("ALTER TABLE k.t DROP COMPACT STORAGE");
            }
            else
            {
                cluster.schemaChange(createTable);
            }

            ConsistencyLevel cl = ConsistencyLevel.ONE;
            String select = "SELECT total FROM k.t WHERE k = 1 AND c = ?";

            for (int i = 1; i <= cluster.size(); i++)
            {
                ICoordinator coordinator = cluster.coordinator(i);

                coordinator.execute("UPDATE k.t SET total = total + 1 WHERE k = 1 AND c = ?", cl, i);
                assertRows(coordinator.execute(select, cl, i), row(1L));

                coordinator.execute("UPDATE k.t SET total = total - 4 WHERE k = 1 AND c = ?", cl, i);
                assertRows(coordinator.execute(select, cl, i), row(-3L));
            }
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__int_rand_divide_62b.cpp
Label Definition File: CWE369_Divide_by_Zero__int.label.xml
Template File: sources-sinks-62b.tmpl.cpp
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: rand Set data to result of rand(), which may be zero
 * GoodSource: Non-zero
 * Sinks: divide
 *    GoodSink: Check for zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
 *
 * */

#include "std_testcase.h"

namespace CWE369_Divide_by_Zero__int_rand_divide_62
{

#ifndef OMITBAD

void badSource(int &data)
{
    /* POTENTIAL FLAW: Set data to a random value */
    data = RAND32();
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(int &data)
{
    /* FIX: Use a value not equal to zero */
    data = 7;
}

/* goodB2G() uses the BadSource with the GoodSink */
void goodB2GSource(int &data)
{
    /* POTENTIAL FLAW: Set data to a random value */
    data = RAND32();
}

#endif /* OMITGOOD */

} /* close namespace */


text:
using base::ASCIIToUTF16;
using base::UTF16ToUTF8;

namespace views {
namespace examples {

TextfieldExample::TextfieldExample()
   : ExampleBase("Textfield"),
     name_(NULL),
     password_(NULL),
     read_only_(NULL),
     show_password_(NULL),
     clear_all_(NULL),
     append_(NULL),
     set_(NULL),
     set_style_(NULL) {
}

TextfieldExample::~TextfieldExample() {
}

void TextfieldExample::CreateExampleView(View* container) {
  name_ = new Textfield();
  password_ = new Textfield();
  password_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
  password_->set_placeholder_text(ASCIIToUTF16("password"));
  read_only_ = new Textfield();
  read_only_->SetReadOnly(true);
  read_only_->SetText(ASCIIToUTF16("read only"));
  show_password_ = new LabelButton(this, ASCIIToUTF16("Show password"));
  clear_all_ = new LabelButton(this, ASCIIToUTF16("Clear All"));
  append_ = new LabelButton(this, ASCIIToUTF16("Append"));
  set_ = new LabelButton(this, ASCIIToUTF16("Set"));
  set_style_ = new LabelButton(this, ASCIIToUTF16("Set Styles"));
  name_->set_controller(this);
  password_->set_controller(this);

  GridLayout* layout = new GridLayout(container);
  container->SetLayoutManager(layout);

  ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL,
                        0.2f, GridLayout::USE_PREF, 0, 0);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL,
                        0.8f, GridLayout::USE_PREF, 0, 0);
  layout->StartRow(0, 0);
  layout->AddView(new Label(ASCIIToUTF16("Name:")));
  layout->AddView(name_);
  layout->StartRow(0, 0);
  layout->AddView(new Label(ASCIIToUTF16("Password:")));
  layout->AddView(password_);
  layout->StartRow(0, 0);
  layout->AddView(new Label(ASCIIToUTF16("Read Only:")));
  layout->AddView(read_only_);
  layout->StartRow(0, 0);
  layout->AddView(show_password_);
  layout->StartRow(0, 0);
  layout->AddView(clear_all_);
  layout->StartRow(0, 0);
  layout->AddView(append_);
  layout->StartRow(0, 0);
  layout->AddView(set_);
  layout->StartRow(0, 0);
  layout->AddView(set_style_);
}

void TextfieldExample::ContentsChanged(Textfield* sender,
                                       const base::string16& new_contents) {
  if (sender == name_) {
    PrintStatus("Name [%s]", UTF16ToUTF8(new_contents).c_str());
  } else if (sender == password_) {
    PrintStatus("Password [%s]", UTF16ToUTF8(new_contents).c_str());
  } else if (sender == read_only_) {
    PrintStatus("Read Only [%s]", UTF16ToUTF8(new_contents).c_str());
  }
}

bool TextfieldExample::HandleKeyEvent(Textfield* sender,
                                      const ui::KeyEvent& key_event) {
  return false;
}

bool TextfieldExample::HandleMouseEvent(Textfield* sender,
                                        const ui::MouseEvent& mouse_event) {
  PrintStatus("HandleMouseEvent click count=%d", mouse_event.GetClickCount());
  return false;
}

void TextfieldExample::ButtonPressed(Button* sender, const ui::Event& event) {
  if (sender == show_password_) {
    PrintStatus("Password [%s]", UTF16ToUTF8(password_->text()).c_str());
  } else if (sender == clear_all_) {
    base::string16 empty;
    name_->SetText(empty);
    password_->SetText(empty);
    read_only_->SetText(empty);
  } else if (sender == append_) {
    name_->AppendText(ASCIIToUTF16("[append]"));
    password_->AppendText(ASCIIToUTF16("[append]"));
    read_only_->AppendText(ASCIIToUTF16("[append]"));
  } else if (sender == set_) {
    name_->SetText(ASCIIToUTF16("[set]"));
    password_->SetText(ASCIIToUTF16("[set]"));
    read_only_->SetText(ASCIIToUTF16("[set]"));
  } else if (sender == set_style_) {
    if (!name_->text().empty()) {
      name_->SetColor(SK_ColorGREEN);
      name_->SetStyle(gfx::BOLD, true);

      if (name_->text().length() >= 5) {
        size_t fifth = name_->text().length() / 5;
        const gfx::Range big_range(1 * fifth, 4 * fifth);
        name_->ApplyStyle(gfx::BOLD, false, big_range);
        name_->ApplyStyle(gfx::UNDERLINE, true, big_range);
        name_->ApplyColor(SK_ColorBLUE, big_range);

        const gfx::Range small_range(2 * fifth, 3 * fifth);
        name_->ApplyStyle(gfx::ITALIC, true, small_range);
        name_->ApplyStyle(gfx::UNDERLINE, false, small_range);
        name_->ApplyStyle(gfx::DIAGONAL_STRIKE, true, small_range);
        name_->ApplyColor(SK_ColorRED, small_range);
      }
    }
  }
}

}  // namespace examples
}  // namespace views


text:
<?php

declare(strict_types=1);

namespace Tests\Money\Exchange;

use Exchanger\Contract\ExchangeRate;
use Exchanger\Exception\Exception as ExchangerException;
use Money\Currency;
use Money\CurrencyPair;
use Money\Exception\UnresolvableCurrencyPairException;
use Money\Exchange\SwapExchange;
use PHPUnit\Framework\TestCase;
use Swap\Swap;

/** @covers \Money\Exchange\SwapExchange */
final class SwapExchangeTest extends TestCase
{
    /** @test */
    public function it_exchanges_currencies(): void
    {
        $base         = new Currency('EUR');
        $counter      = new Currency('USD');
        $swapExchange = $this->createMock(Swap::class);
        $exchangeRate = $this->createMock(ExchangeRate::class);

        $exchangeRate->method('getValue')
            ->willReturn(1.25);

        $swapExchange->expects(self::once())
            ->method('latest')
            ->with('EUR/USD')
            ->willReturn($exchangeRate);

        self::assertEquals(
            new CurrencyPair($base, $counter, '1.25'),
            (new SwapExchange($swapExchange))
                ->quote($base, $counter)
        );
    }

    /** @test */
    public function it_throws_an_exception_when_cannot_exchange_currencies(): void
    {
        $base         = new Currency('EUR');
        $counter      = new Currency('USD');
        $swapExchange = $this->createMock(Swap::class);
        $exchangeRate = $this->createMock(ExchangeRate::class);

        $exchangeRate->method('getValue')
            ->willReturn(1.25);

        $swapExchange->expects(self::once())
            ->method('latest')
            ->with('EUR/USD')
            ->willThrowException(new ExchangerException());

        $exchanger = new SwapExchange($swapExchange);

        $this->expectException(UnresolvableCurrencyPairException::class);

        $exchanger->quote($base, $counter);
    }
}


text:
package org.apache.wink.common.internal.providers.header;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.core.Cookie;
import javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate;

import org.apache.wink.common.internal.i18n.Messages;

public class CookieHeaderDelegate implements HeaderDelegate<Cookie> {

    private static Pattern      whitespace = Pattern.compile("\\s"); //$NON-NLS-1$
    private static final String VERSION    = "$Version"; //$NON-NLS-1$
    private static final String DOMAIN     = "$Domain"; //$NON-NLS-1$
    private static final String PATH       = "$Path"; //$NON-NLS-1$

    public Cookie fromString(String cookie) throws IllegalArgumentException {

        if (cookie == null) {
            throw new IllegalArgumentException(Messages.getMessage("headerIsNull", "Cookie")); //$NON-NLS-1$ //$NON-NLS-2$
        }

        String tokens[] = cookie.split("[;,]"); //$NON-NLS-1$

        if (tokens.length <= 0) {
            throw new IllegalArgumentException(Messages.getMessage("invalidCookie", cookie)); //$NON-NLS-1$
        }

        ModifiableCookie firstCookie = null;
        int cookieNum = 0;
        boolean versionSet = false;
        for (String token : tokens) {
            String[] subTokens = token.trim().split("=", 2); //$NON-NLS-1$
            String name = subTokens.length > 0 ? subTokens[0] : null;
            String value = subTokens.length > 1 ? subTokens[1] : null;
            if (value != null && value.startsWith("\"") //$NON-NLS-1$
                && value.endsWith("\"") //$NON-NLS-1$
                && value.length() > 1) {
                value = value.substring(1, value.length() - 1);
            }

            if (!name.startsWith("$")) { //$NON-NLS-1$
                cookieNum++;
                if (cookieNum > 1) {
                    // Return only first Cookie
                    break;
                }
                if (firstCookie == null) {
                    firstCookie = new ModifiableCookie();
                }
                firstCookie.name = name;
                firstCookie.value = value;
            } else if (name.startsWith(VERSION)) {
                if (firstCookie == null) {
                    firstCookie = new ModifiableCookie();
                } else {
                    if (versionSet) {
                        throw new IllegalArgumentException(
                                                           Messages.getMessage("cookieCannotContainAddlVers", cookie)); //$NON-NLS-1$
                    }
                }
                versionSet = true;
                firstCookie.version = Integer.parseInt(value);
            } else if (name.startsWith(PATH) && cookie != null) {
                if (firstCookie == null) {
                    throw new IllegalArgumentException(Messages.getMessage("cookieMustStartWithVersion", cookie)); //$NON-NLS-1$
                }
                firstCookie.path = value;
            } else if (name.startsWith(DOMAIN) && cookie != null) {
                if (firstCookie == null) {
                    throw new IllegalArgumentException(Messages.getMessage("cookieMustStartWithVersion", cookie)); //$NON-NLS-1$
                }
                firstCookie.domain = value;
            }
        }
        if (cookieNum == 0) {
            throw new IllegalArgumentException(Messages.getMessage("cookieDoesNotContainNAMEVALUE", cookie)); //$NON-NLS-1$
        }

        if (firstCookie != null) {
            return validateAndBuildCookie(firstCookie, cookie);
        } else {
            throw new IllegalArgumentException(Messages.getMessage("failedToParseCookie", cookie)); //$NON-NLS-1$
        }
    }

    private Cookie validateAndBuildCookie(ModifiableCookie firstCookie, String cookie) {
        if (firstCookie.name == null || firstCookie.value == null) {
            throw new IllegalArgumentException(Messages.getMessage("failedToParseCookie", cookie)); //$NON-NLS-1$
        }
        return new Cookie(firstCookie.name, firstCookie.value, firstCookie.path,
                          firstCookie.domain, firstCookie.version);

    }

    public String toString(Cookie cookie) {
        if (cookie == null) {
            throw new IllegalArgumentException(Messages.getMessage("headerIsNull", "Cookie")); //$NON-NLS-1$ //$NON-NLS-2$
        }

        StringBuilder cookieHeader = new StringBuilder();

        cookieHeader.append(VERSION + "=").append(cookie.getVersion()).append(';'); //$NON-NLS-1$
        cookieHeader.append(cookie.getName()).append('=');
        appendValue(cookieHeader, cookie.getValue());

        if (cookie.getDomain() != null) {
            cookieHeader.append(";" + DOMAIN + "="); //$NON-NLS-1$ //$NON-NLS-2$
            appendValue(cookieHeader, cookie.getDomain());
        }
        if (cookie.getPath() != null) {
            cookieHeader.append(";" + PATH + "="); //$NON-NLS-1$ //$NON-NLS-2$
            appendValue(cookieHeader, cookie.getPath());
        }
        return cookieHeader.toString();
    }

    private void appendValue(StringBuilder cookieHeader, String value) {

        Matcher matcher = whitespace.matcher(value);
        boolean isQuote = matcher.find();
        if (isQuote) {
            cookieHeader.append('"');
        }
        escapeQuotes(cookieHeader, value);
        if (isQuote) {
            cookieHeader.append('"');
        }
    }

    private void escapeQuotes(StringBuilder b, String value) {
        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            if (c == '"')
                b.append('\\');
            b.append(c);
        }
    }

    private static class ModifiableCookie {

        public String name;
        public String value;
        public int    version = 0;
        public String path;
        public String domain;
    }
}


text:
<?php

/*
 * This file is part of the kompakt/mediameister package.
 *
 * (c) Christian Hoegl <chrigu@sirprize.me>
 *
 */

namespace Kompakt\Mediameister\Task\SelectionAdder\Exception;

use Kompakt\Mediameister\Exception as BaseException;

class PackshotNotFoundException extends \InvalidArgumentException implements BaseException
{
    protected $packshotName = null;

    public function setPackshotName($packshotName)
    {
        $this->packshotName = $packshotName;
    }

    public function getPackshotName()
    {
        return $this->packshotName;
    }
}


text:
What is KayVeep?
----------------

In short, it is a drop-dead-simple no-SQL data store.  What *hsqldb* is to *Java*, *Kayveep* aimed to be initially for PHP.  Then,
someone asked if KayVeep could be made to work in other languages, notably Groovy and Java.  The name is a mashup of "K-V-P", that is,
"Key-Value-Pair", the essential datatype that the store is built upon.  Data is stored in JSON format as simple text files in the
filesystem.

Hsqldb, what?
-------------

In Java, there are plenty of SQL databases that run as separate processes (MySQL, Oracle, PostgreSQL) but for creating a small
applicaton there is only one *hsqldb* that runs in-process, inside your own application.  Similarly, there are plenty of noSQL data
storage projects that will run as separate processes but I could see none that run in-process in your own application.

The API.
--------

Everything builds from *DataStore* and its three methods ```store()```, ```load()``` and ```delete()``` that allow you to store a
key/value pair, load the value from storage by key and delete it by its key respectively.  Note, the use of "key" and "ID" are used
synonymously throughout this document.  Everything else in KayVeep boils down to using a DataStore.

The *DataStore* stores a single item and returns it and really doesnt care what that single item is.  The *ArrayDataStore* builds
on the simple *DataStore* to allow a key to return an array of values.  This data structure is valuable for modelling one-to-many
relationships, for example.

Higher level serialization is handled by the *ObjectDataStore* which serializes the object itself and transparently stores meta-data
about the object as well.  A mapping between object type and IDs of all objects of that type is maintained, creating an index of sorts
to avoid trawling every file in the store when performing queries; using the type to ID mapping, its possible to query just the
"Employee" data stored in the store for instance.

Serialization is taken further with the *DomainDataStore* which adds meta-data storage of created and updated timestamps for data
items, and the ability to mark certain fields in an object as "raw".  Raw fields are not stored in the basic JSON representation but
instead are dropped into a file of their own.  This keeps the JSON datastore lightweight (for queries) yet still allows large "BLOB"
style data to be stored in KeyVeep.  Flagged raw fields are automatically split out from the object on ```store()``` and reconstituted
on ```load()```.  The *DomainDataStore* introduces the ability to query the store.

The Versions
------------

Everything started with PHP, and then moved on to Groovy as another dynamic, loosely typed language.  Since Groovy is close to Java,
that was the next port with considerations added for making the API type-safe.

The data in the data-store is the vital criteria.  Each language version must be 100% fully compatible with the others to allow data
portability.  Meta data, type data and JSON files must live in the same places.

KayVeep will be moving in two directions from here.  Firstly, gaining other language implementations.  Secondly, the data store needs
to be used by applications.


text:
var fs = require('fs'),
    path = require('path'),
    markdown = require('./markdown-parser');

var DEFAULT_FILE_ENCODING = 'UTF-8';

module.exports = {
    getMetadataSync: getMetadataSync,
    getSummarySync: getSummarySync
};

function getMetadataSync(sourceDir) {
    var metadata = {
            title: path.basename(sourceDir),
            language: 'en'
        },
        metadataFilePath = path.join(sourceDir, 'featurebook.json');

    if (fs.existsSync(metadataFilePath)) {
        var data = JSON.parse(fs.readFileSync(metadataFilePath, DEFAULT_FILE_ENCODING));
        metadata.title = data.title;
        metadata.authors = data.authors;
        metadata.contributors = data.contributors;
        metadata.version = data.version;
        metadata.language = data.language || 'en';
    }
    return metadata;
}

function getSummarySync(dir) {
    var summaryFilePath = path.join(dir, 'SUMMARY.md');

    if (fs.existsSync(summaryFilePath)) {
        var data = fs.readFileSync(summaryFilePath, DEFAULT_FILE_ENCODING);
        return markdown.parse(data);
    }
    return null;
}


text:
class SessionsController < ApplicationController
  def new
  end

  def create
    user = authenticate_session(session_params)

    if sign_in(user)
      redirect_to posts_path
    else
      redirect_to root_path, notice: "Invalid email or password"
    end
  end

  def destroy
    sign_out
    redirect_to root_path
  end

  private

  def session_params
    params.require(:session).permit(:email, :password)
  end
end


text:
namespace CSharpKata.Rules
{
	public interface IMultipleWithoutRule : IRule { }

	public class MultipleWithoutModuleRule : Rule, IMultipleWithoutRule
	{
		public MultipleWithoutModuleRule(int value, string result)
			: base(value, result)
		{ }

		public override bool Validate(int number)
		{
			while (number > 0)
				number -= _value;
			return number == Rests.REST_ZERO;
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace Umbraco.Core.Persistence.Querying
{
    /// <summary>
    /// SD: This is a horrible hack but unless we break compatibility with anyone who's actually implemented IQuery{T} there's not much we can do.
    /// The IQuery{T} interface is useless without having a GetWhereClauses method and cannot be used for tests.
    /// We have to wait till v8 to make this change I suppose.
    /// </summary>
    internal static class QueryExtensions
    {
        /// <summary>
        /// Returns all translated where clauses and their sql parameters
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Tuple<string, object[]>> GetWhereClauses<T>(this IQuery<T> query)
        {
            var q = query as Query<T>;
            if (q == null)
            {
                throw new NotSupportedException(typeof(IQuery<T>) + " cannot be cast to " + typeof(Query<T>));
            }
            return q.GetWhereClauses();
        }
    }

    /// <summary>
    /// Represents a query for building Linq translatable SQL queries
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IQuery<T>
    {
        /// <summary>
        /// Adds a where clause to the query
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns>This instance so calls to this method are chainable</returns>
        IQuery<T> Where(Expression<Func<T, bool>> predicate);

    }
}


text:
package intro.JavaHW4.integer;

import intro.JavaHW4.exceptions.OverFlowException;
import intro.JavaHW4.expr.*;

public class IntegerSubtract extends Subtract<Integer> {
    IntegerSubtract(TripleOperation<Integer> a, TripleOperation<Integer> b) {
        super(a, b);
    }

    protected Integer calc(Integer x, Integer y) throws OverFlowException {
        long c = (long) x - y;
        checkOverflow(c);
        return x - y;
    }
}


text:
package org.apereo.cas.adaptors.u2f;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.io.Serializable;

/**
 * This is {@link U2FRegistration}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
@Getter
@RequiredArgsConstructor
public class U2FRegistration implements Serializable {
    private static final long serialVersionUID = 8478965906212939618L;

    private final String challenge;

    private final String appId;

    private final String requestId;

    private final String principalId;

    private final String jsonData;

    public String getVersion() {
        return "U2F_V2";
    }
}


text:
import functools
import operator
import warnings
from collections import OrderedDict, Mapping, MutableMapping
from datetime import datetime

import numpy as np
import pandas as pd

import xray
import variable

def alias_warning(old_name, new_name, stacklevel=2):
    warnings.warn('%s has been renamed to %s; this alias will be removed '
                  "before xray's initial release" % (old_name, new_name),
                  FutureWarning, stacklevel=stacklevel)

def function_alias(obj, old_name):
    @functools.wraps(obj)
    def wrapper(*args, **kwargs):
        alias_warning(old_name, obj.__name__, stacklevel=3)
        return obj(*args, **kwargs)
    return wrapper

def class_alias(obj, old_name):
    class Wrapper(obj):
        def __new__(cls, *args, **kwargs):
            alias_warning(old_name, obj.__name__, stacklevel=3)
            return super(Wrapper, cls).__new__(cls, *args, **kwargs)
    Wrapper.__name__ = obj.__name__
    return Wrapper

def as_safe_array(values, dtype=None):
    """Like np.asarray, but convert all datetime64 arrays to ns precision
    """
    values = np.asarray(values, dtype=dtype)
    if values.dtype.kind == 'M':
        # np.datetime64
        values = values.astype('datetime64[ns]')
    return values

def as_array_or_item(values, dtype=None):
    """Return the given values as a numpy array of the indicated dtype, or as
    an individual value if it's a 0-dimensional object array or datetime.
    """
    if isinstance(values, datetime):
        # shortcut because if you try to make a datetime or Timestamp object
        # into an array with the proper dtype, it is liable to be silently
        # converted into an integer instead :(
        return values
    values = as_safe_array(values, dtype=dtype)
    if values.ndim == 0 and values.dtype.kind == 'O':
        # unpack 0d object arrays to be consistent with numpy
        values = values.item()
        if isinstance(values, pd.Timestamp):
            # turn Timestamps back into datetime64 objects
            values = np.datetime64(values, 'ns')
    return values

def squeeze(xray_obj, dimensions, dimension=None):
    """Squeeze the dimensions of an xray object."""
    if dimension is None:
        dimension = [d for d, s in dimensions.iteritems() if s == 1]
    else:
        if isinstance(dimension, basestring):
            dimension = [dimension]
        if any(dimensions[k] > 1 for k in dimension):
            raise ValueError('cannot select a dimension to squeeze out '
                             'which has length greater than one')
    return xray_obj.indexed(**{dim: 0 for dim in dimension})

def allclose_or_equiv(arr1, arr2, rtol=1e-5, atol=1e-8):
    """Like np.allclose, but also allows values to be NaN in both arrays
    """
    if arr1.shape != arr2.shape:
        return False
    return np.isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=True).all()

def array_equiv(arr1, arr2):
    """Like np.array_equal, but also allows values to be NaN in both arrays
    """
    arr1, arr2 = np.asarray(arr1), np.asarray(arr2)
    if arr1.shape != arr2.shape:
        return False
    # we could make this faster by not-checking for null values if the dtype
    # does not support them, but the logic would get more convoluted.
    # using pd.isnull lets us defer the NaN handling to pandas (and unlike
    # np.isnan it works on every dtype).
    return ((arr1 == arr2) | (pd.isnull(arr1) & pd.isnull(arr2))).all()

def safe_cast_to_index(array):
    """Given an array, safely cast it to a pandas.Index.

    If it is already a pandas.Index, return it unchanged.

    Unlike pandas.Index, if the array has dtype=object or dtype=timedelta64,
    this function will not attempt to do automatic type conversion but will
    always return an index with dtype=object.
    """
    if isinstance(array, pd.Index):
        index = array
    elif isinstance(array, xray.Coordinate):
        index = array.as_index
    else:
        kwargs = {}
        if hasattr(array, 'dtype'):
            if array.dtype == object or array.dtype == np.timedelta64:
                kwargs['dtype'] = object
        index = pd.Index(np.asarray(array), **kwargs)
    return index

def multi_index_from_product(iterables, names=None):
    """Like pandas.MultiIndex.from_product, but not buggy

    Contains work-around for https://github.com/pydata/pandas/issues/6439
    """
    # note: pd.MultiIndex.from_product is new in pandas-0.13.1
    coords = [np.asarray(v) for v in iterables]
    return pd.MultiIndex.from_product(coords, names=names)

def update_safety_check(first_dict, second_dict, compat=operator.eq):
    """Check the safety of updating one dictionary with another.

    Raises ValueError if dictionaries have non-compatible values for any key,
    where compatibility is determined by identity (they are the same item) or
    the `compat` function.

    Parameters
    ----------
    first_dict, second_dict : dict-like
        All items in the second dictionary are checked against for conflicts
        against items in the first dictionary.
    compat : function, optional
        Binary operator to determine if two values are compatible. By default,
        checks for equality.
    """
    for k, v in second_dict.iteritems():
        if (k in first_dict and
                not (v is first_dict[k] or compat(v, first_dict[k]))):
            raise ValueError('unsafe to merge dictionaries without '
                             'overriding values; conflicting key %r' % k)

def remove_incompatible_items(first_dict, second_dict, compat=operator.eq):
    """Remove incompatible items from the first dictionary in-place.

    Items are retained if their keys are found in both dictionaries and the
    values are compatible.

    Parameters
    ----------
    first_dict, second_dict : dict-like
        Mappings to merge.
    compat : function, optional
        Binary operator to determine if two values are compatible. By default,
        checks for equality.
    """
    for k, v in second_dict.iteritems():
        if k in first_dict and not compat(v, first_dict[k]):
            del first_dict[k]

def dict_equal(first, second):
    """Test equality of two dict-like objects.  If any of the values
    are numpy arrays, compare them for equality correctly.

    Parameters
    ----------
    first, second : dict-like
        Dictionaries to compare for equality

    Returns
    -------
    equals : bool
        True if the dictionaries are equal
    """
    k1 = sorted(first.keys())
    k2 = sorted(second.keys())
    if k1 != k2:
        return False
    for k in k1:
        v1 = first[k]
        v2 = second[k]
        if isinstance(v1, np.ndarray) or isinstance(v2, np.ndarray):
            if not np.array_equal(v1, v2):
                return False
        elif v1 != v2:
            return False
    return True

def ordered_dict_intersection(first_dict, second_dict, compat=operator.eq):
    """Return the intersection of two dictionaries as a new OrderedDict.

    Items are retained if their keys are found in both dictionaries and the
    values are compatible.

    Parameters
    ----------
    first_dict, second_dict : dict-like
        Mappings to merge.
    compat : function, optional
        Binary operator to determine if two values are compatible. By default,
        checks for equality.

    Returns
    -------
    intersection : OrderedDict
        Intersection of the contents.
    """
    new_dict = OrderedDict(first_dict)
    remove_incompatible_items(new_dict, second_dict, compat)
    return new_dict

class Frozen(Mapping):
    """Wrapper around an object implementing the mapping interface to make it
    immutable. If you really want to modify the mapping, the mutable version is
    saved under the `mapping` attribute.
    """
    def __init__(self, mapping):
        self.mapping = mapping

    def __getitem__(self, key):
        return self.mapping[key]

    def __iter__(self):
        return iter(self.mapping)

    def __len__(self):
        return len(self.mapping)

    def __contains__(self, key):
        return key in self.mapping

    def __repr__(self):
        return '%s(%r)' % (type(self).__name__, self.mapping)

def FrozenOrderedDict(*args, **kwargs):
    return Frozen(OrderedDict(*args, **kwargs))

class SortedKeysDict(MutableMapping):
    """An wrapper for dictionary-like objects that always iterates over its
    items in sorted order by key but is otherwise equivalent to the underlying
    mapping.
    """
    def __init__(self, mapping=None):
        self.mapping = {} if mapping is None else mapping

    def __getitem__(self, key):
        return self.mapping[key]

    def __setitem__(self, key, value):
        self.mapping[key] = value

    def __delitem__(self, key):
        del self.mapping[key]

    def __iter__(self):
        return iter(sorted(self.mapping))

    def __len__(self):
        return len(self.mapping)

    def __contains__(self, key):
        return key in self.mapping

    def __repr__(self):
        return '%s(%r)' % (type(self).__name__, self.mapping)

class ChainMap(MutableMapping):
    """Partial backport of collections.ChainMap from Python>=3.3

    Don't return this from any public APIs, since some of the public methods
    for a MutableMapping are missing (they will raise a NotImplementedError)
    """
    def __init__(self, *maps):
        self.maps = maps

    def __getitem__(self, key):
        for mapping in self.maps:
            try:
                return mapping[key]
            except KeyError:
                pass
        raise KeyError(key)

    def __setitem__(self, key, value):
        self.maps[0][key] = value

    def __delitem__(self, value):
        raise NotImplementedError

    def __iter__(self):
        raise NotImplementedError

    def __len__(self):
        raise NotImplementedError

class NDArrayMixin(object):
    """Mixin class for making wrappers of N-dimensional arrays that conform to
    the ndarray interface required for the data argument to Variable objects.

    A subclass should set the `array` property and override one or more of
    `dtype`, `shape` and `__getitem__`.
    """
    @property
    def dtype(self):
        return self.array.dtype

    @property
    def shape(self):
        return self.array.shape

    @property
    def ndim(self):
        return len(self.shape)

    @property
    def size(self):
        # cast to int so that shape = () gives size = 1
        return int(np.prod(self.shape))

    def __len__(self):
        try:
            return self.shape[0]
        except IndexError:
            raise TypeError('len() of unsized object')

    def __array__(self, dtype=None):
        return np.asarray(self[...], dtype=dtype)

    def __getitem__(self, key):
        return self.array[key]

    def __repr__(self):
        return '%s(array=%r)' % (type(self).__name__, self.array)


text:
from cgi import parse_qs, escape
from zappa.async import task

def hello_world(environ, start_response):
    parameters = parse_qs(environ.get('QUERY_STRING', ''))
    if 'subject' in parameters:
        subject = escape(parameters['subject'][0])
    else:
        subject = 'World'
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ['''Hello {subject!s}
    Hello {subject!s}!

'''.format(**{'subject': subject})]

def schedule_me():
    return "Hello!"

@task
def async_me(arg1, **kwargs):
    return "run async when on lambda %s%s" % (arg1, kwargs.get('foo',''))

def callback(self):
    print("this is a callback")

def prebuild_me():
    print("this is a prebuild script")


text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Extensions.Testing.Abstractions;

namespace Microsoft.DotNet.Tools.Test
{
    public class TestSessionTerminateMessageHandler : IDotnetTestMessageHandler
    {
        private readonly ITestMessagesCollection _messages;

        public TestSessionTerminateMessageHandler(ITestMessagesCollection messages)
        {
            _messages = messages;
        }

        public DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message)
        {
            var nextState = DotnetTestState.NoOp;

            if (TestMessageTypes.TestSessionTerminate.Equals(message.MessageType))
            {
                nextState = DotnetTestState.Terminated;
                _messages.Drain();
            }

            return nextState;
        }
    }
}


text:
package kr.pe.courage.tech.uat.login.web;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kr.pe.courage.common.prop.PropertiesMap;
import kr.pe.courage.common.utils.Util;
import kr.pe.courage.common.web.listener.CourageHttpSessionBindingListener;
import kr.pe.courage.common.web.listener.SessionMap;
import kr.pe.courage.common.web.utils.WebUtils;
import kr.pe.courage.tech.uat.login.service.LoginService;
import kr.pe.courage.tech.uat.login.service.LoginVO;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springmodules.validation.commons.DefaultBeanValidator;

import egovframework.com.cmm.interceptor.CourageAuthenticationInterceptor;
import egovframework.com.sec.ram.service.AuthorManageVO;
import egovframework.com.sec.ram.service.EgovAuthorManageService;
import egovframework.com.sym.mnu.mpm.service.EgovMenuManageService;
import egovframework.com.sym.mnu.mpm.service.MenuManageVO;
import egovframework.com.utl.cas.service.EgovSessionCookieUtil;
import egovframework.com.utl.sim.service.EgovClntInfo;
import egovframework.rte.fdl.cryptography.CourageCryptoService;

/**
 *

 * kr.pe.courage.tech.uat.login.web
 * LoginController.java
 *

 *
 * @Author : ChangHo Seok
 * @Date : 2016. 1. 6.
 * @Version : 1.0
 * @see
 *
 *

 * << 개정이력 >>
 * 1. 수정일 : 2016. 1. 6., 수정자 : ChangHo Seok, 수정내용 : 최초등록
 *

 */
@Controller("loginController")
@RequestMapping("/uat/login/*")
@SessionAttributes("loginForm")
public class LoginController {
	private static final Logger logger = Logger.getLogger(LoginController.class);

	@Resource(name = "courageARIACryptoService")
	private CourageCryptoService cryptoService;;

	@Resource(name = "authorManageService")
	private EgovAuthorManageService authorManageService;

	@Resource(name = "MeunManageService")
	private EgovMenuManageService menuService;

	@Resource(name = "loginService")
	private LoginService loginService;

	@Resource(name = "beanValidator")
	protected DefaultBeanValidator beanValidator;

	@Value("#{uatView['formLoginView']}")
	private String formLoginView;

	@Value("#{uatView['subFormLoginView']}")
	private String subFormLoginView;

	@ModelAttribute("loginForm")
	private String loginForm() {
		return "";
	}

	/**
	 *

	 * 1. 개요 : 로그인 페이지
	 *

	 *
	 * @Author : ChangHo Seok
	 * @Date : 2016. 1. 14.
	 * @Method Name : formLogin
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = {"formLogin.*", "subFormLogin.*"})
	public ModelAndView formLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session, LoginVO loginVO, ModelMap model) throws Exception {
		boolean isLayerPopup = request.getServletPath().endsWith("subFormLogin." + WebUtils.getUrlExtension(request));

		// 로그인 여부 조회
		LoginVO userLoginVO = (LoginVO)request.getSession().getAttribute(PropertiesMap.getInstance().getValue("system.session.key"));

		if (userLoginVO == null) {
			// Cookie 조회
			String userID = EgovSessionCookieUtil.getCookie(request, "/", LoginVO.COOKIE_USER_ID);

			if (!Util.nvl(userID).equals("")) {
				try {
					// 데이터 복호화
					userID = new String(cryptoService.decrypt(Base64.decodeBase64(userID)));
				} catch (NullPointerException ex) {
					userID = "";
					EgovSessionCookieUtil.setCookie(response, "/", LoginVO.COOKIE_USER_ID);
				}
			}

			if (!Util.nvl(userID).equals("")) {
				loginVO.setRememberMe(true);
				loginVO.setEmplyrId(userID);
			}
			model.addAttribute("loginForm", isLayerPopup ? subFormLoginView : formLoginView);

			return new ModelAndView(isLayerPopup ? subFormLoginView : formLoginView);
		} else {
			if (isLayerPopup) {
				WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_SUCCESS);

				return new ModelAndView(subFormLoginView);
			} else {
				String returnUrl = PropertiesMap.getInstance().getValue("system.login.home");

				RedirectView redirectView = new RedirectView();
				redirectView.setContextRelative(true);
				redirectView.setUrl(returnUrl);

				return new ModelAndView(redirectView);
			}
		}
	}

	/**
	 *

	 * 1. 개요 : 사용자 로그인
	 *

	 *
	 * @Author	: ChangHo Seok
	 * @Date	: 2016. 1. 18.
	 * @Method Name : userLogin
	 * @param request
	 * @param session
	 * @param loginVO
	 * @param bindingResult
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="userLogin.*", method=RequestMethod.POST)
	public ModelAndView userLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			SessionStatus sessionStatus, @ModelAttribute("loginForm") String loginForm, LoginVO loginVO, BindingResult bindingResult,
			ModelMap model) throws Exception {
		beanValidator.validate(loginVO, bindingResult);

		if (bindingResult.hasErrors()) {
			model.addAttribute("validateCheck", "error");
			model.addAttribute("loginVO", loginVO);
			WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_VALIDATOR_ERROR);

			return new ModelAndView(loginForm, model);
		}

		LoginVO loginUserInfo = loginService.selectLoginUserInfo(loginVO);

		if (loginUserInfo != null && loginUserInfo.getLoginStat().equals(LoginVO.LOGIN_STATUS_SUCCESS)) {
			// 사용자 로그인여부 확인
			boolean duplecateLoginCheck = PropertiesMap.getInstance().getValue("system.login.duplecateCheck").equals("true") ? true : false;

			logger.debug("## 사용자 중복 로그인 여부");
			if (SessionMap.getInstance().isExists(loginUserInfo.getEsntlId())) {
				logger.debug("## 중복 로그인된 사용자 = " + loginUserInfo.getEsntlId());

				if (duplecateLoginCheck) {
					if (loginVO.isEnfrcLogin()) {
						logger.debug("## 기존 로그인된 사용자 로그아웃");
						SessionMap.getInstance().logout(loginUserInfo.getEsntlId());
					} else {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						HttpSession beforeSession = SessionMap.getInstance().get(loginUserInfo.getEsntlId());

						model.addAttribute(WebUtils.ACTION_MESSAGE, "이미 로그인된 사용자 입니다.\\n기존 접속을 종료하고 로그인 하려면 다시 로그인을 시도하세요.\\n로그인일시 : " + sdf.format(beforeSession.getCreationTime())
								+ "\\n접속IP : " + beforeSession.getAttribute(LoginVO.SESSION_USER_IP));

						loginVO.setEnfrcLogin(true); // 다시 로그인시도시 강제 로그인 설정
						model.addAttribute("loginVO", loginVO);
						WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_FAILED);

						return new ModelAndView(loginForm, model);
					}
				}
			} else {
				logger.debug("## 최초 로그인된 사용자 = " + loginUserInfo.getEsntlId());
			}

			// 사용자 권한 설정
			AuthorManageVO authorManageVO = new AuthorManageVO();
			authorManageVO.setEsntlId(loginUserInfo.getEsntlId());
			loginUserInfo.setAuthList(authorManageService.selectLoginUserAuthorList(authorManageVO));

			String[] auhtorCodes = new String[loginUserInfo.getAuthList().size()];
			for (int i = 0; i < loginUserInfo.getAuthList().size(); i++) {
				auhtorCodes[i] = loginUserInfo.getAuthList().get(i).getAuthorCode();
			}

			// 메뉴 설정
			MenuManageVO menuManageVO = new MenuManageVO();
			menuManageVO.setEsntlId(loginUserInfo.getEsntlId());
			menuManageVO.setAuthorCode(loginUserInfo.getAuthorCode());
			List<MenuManageVO> menuList = menuService.selectHierMenuManageList(menuManageVO);

			session.setAttribute(PropertiesMap.getInstance().getValue("system.session.key"), loginUserInfo);

			session.setAttribute(LoginVO.SESSION_USER_IP, EgovClntInfo.getClntIP(request));
			session.setAttribute(LoginVO.SESSION_USER_UNIQ_ID, loginUserInfo.getEsntlId());
			session.setAttribute(LoginVO.SESSION_USER_ID, loginUserInfo.getEmplyrId());
			session.setAttribute(LoginVO.SESSION_USER_NM, loginUserInfo.getName());
			session.setAttribute(LoginVO.SESSION_USER_MENULIST, menuList);
			session.setAttribute(LoginVO.SESSION_AUTHOR_LIST, loginUserInfo.getAuthList());
			session.setAttribute(LoginVO.SESSION_AUTHOR_CODE, loginUserInfo.getAuthorCode());
			session.setAttribute(LoginVO.SESSION_AUTHOR_NAME, loginUserInfo.getAuthorNm());
			session.setAttribute(LoginVO.SESSION_AUTHOR_CODE_ARRAY, auhtorCodes);

			// 익명사용자 권한 제거
			session.removeAttribute(CourageAuthenticationInterceptor.AUTHOR_CHECK_LIST);

			logger.info("isRememberMe : " + loginVO.isRememberMe());
			if (loginVO.isRememberMe()) {
				// 데이터 암호화
				String cryptoId = Base64.encodeBase64String(cryptoService.encrypt(loginUserInfo.getEmplyrId().getBytes()));

				EgovSessionCookieUtil.setCookie(response, "/", LoginVO.COOKIE_USER_ID, cryptoId, (60 * 24) * 7);
			} else {
				EgovSessionCookieUtil.setCookie(response, "/", LoginVO.COOKIE_USER_ID);
			}

			// Session Timeout 설정
			session.setMaxInactiveInterval(Integer.parseInt(PropertiesMap.getInstance().getValue("system.session.timeout")));

			CourageHttpSessionBindingListener sessionListener = new CourageHttpSessionBindingListener();
			session.setAttribute("Listener", sessionListener);
		} else if (loginUserInfo != null && loginUserInfo.getLoginStat().equals(LoginVO.LOGIN_STATUS_USER_NOTCONFM)) {
			model.addAttribute(WebUtils.ACTION_MESSAGE, "미승인 사용자입니다. 관리자에게 문의하세요.");
			model.addAttribute("loginVO", loginVO);
			WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_FAILED);

			return new ModelAndView(loginForm, model);
		} else {
			model.addAttribute(WebUtils.ACTION_MESSAGE, "등록되지 않은 사용자 이거나 정보 입력이 잘못되었습니다.");
			model.addAttribute("loginVO", loginVO);
			WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_FAILED);

			return new ModelAndView(loginForm, model);
		}

		sessionStatus.setComplete();

		if (!WebUtils.isAjaxRequest(request)) {
			String returnUrl = PropertiesMap.getInstance().getValue("system.login.home");

			RedirectView redirectView = new RedirectView();
			redirectView.setContextRelative(true);
			redirectView.setUrl(returnUrl);

			return new ModelAndView(redirectView);
		} else {
			WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_SUCCESS);
			return new ModelAndView(loginForm);
		}
	}

	/**
	 *

	 * 1. 개요 : 로그인 사용자 접근메뉴 정보 조회
	 *

	 *
	 * @Author	: ChangHo Seok
	 * @Date	: 2016. 3. 4.
	 * @Method Name : retrieveLoginUserMenuListJson
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "retrieveLoginUserMenuListJson.*")
	public @ResponseBody Map<String, Object> retrieveLoginUserMenuListJson(HttpSession session) throws Exception {

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("result", Boolean.TRUE);
		result.put("menuList", session.getAttribute(LoginVO.SESSION_USER_MENULIST));

		return result;
	}

	/**
	 *

	 * 1. 개요 : 사용자 로그아웃
	 *

	 *
	 * @Author	: ChangHo Seok
	 * @Date	: 2016. 4. 22.
	 * @Method Name : logout
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "logout.*")
	public ModelAndView logout(HttpSession session) throws Exception {
		session.removeAttribute(PropertiesMap.getInstance().getValue("system.session.key"));
		session.removeAttribute(LoginVO.SESSION_AUTHOR_NAME);
		session.removeAttribute(LoginVO.SESSION_AUTHOR_CODE);
		session.removeAttribute(LoginVO.SESSION_AUTHOR_LIST);
		session.removeAttribute(LoginVO.SESSION_USER_MENULIST);
		session.removeAttribute(LoginVO.SESSION_USER_NM);
		session.removeAttribute(LoginVO.SESSION_USER_ID);
		session.removeAttribute(LoginVO.SESSION_USER_IP);
		session.invalidate();

		RedirectView redirectView = new RedirectView();
		redirectView.setContextRelative(true);
		redirectView.setUrl("/");

		return new ModelAndView(redirectView);
	}

	/**
	 *

	 * 1. 개요 : 사용자 권한 변경 (다중권한 사용시)
	 *

	 *
	 * @Author	: ChangHo Seok
	 * @Date	: 2016. 4. 22.
	 * @Method Name : loginUserAuthorChange
	 * @param session
	 * @param authorId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "loginUserAuthorChange.*", method = RequestMethod.POST)
	public ModelAndView loginUserAuthorChange(HttpSession session, @RequestParam("authorId") String authorId) throws Exception {
		LoginVO loginVO = (LoginVO) session.getAttribute(PropertiesMap.getInstance().getValue("system.session.key"));

		if (loginVO != null) {
			List<AuthorManageVO> authList = loginVO.getAuthList();

			for (AuthorManageVO authInfo : authList) {
				if (authInfo.getAuthorCode().equals(authorId)) {
					loginVO.setAuthorCode(authInfo.getAuthorCode());
					loginVO.setAuthorNm(authInfo.getAuthorNm());

					// 메뉴설정
					MenuManageVO menuManageVO = new MenuManageVO();
					menuManageVO.setEsntlId(loginVO.getEsntlId());
					menuManageVO.setAuthorCode(loginVO.getAuthorCode());

					List<MenuManageVO> menuList = menuService.selectHierMenuManageList(menuManageVO);

					session.setAttribute(LoginVO.SESSION_AUTHOR_CODE, loginVO.getAuthorCode());
					session.setAttribute(LoginVO.SESSION_AUTHOR_NAME, loginVO.getAuthorNm());
					session.setAttribute(LoginVO.SESSION_USER_MENULIST, menuList);

					// 이전 권한체크 정보 제거
					session.removeAttribute(CourageAuthenticationInterceptor.AUTHOR_CHECK_LIST);

					// 권한 확인 캐시 제거
					authorManageService.removeAuthorCache();

					break;
				}
			}
		}

		String returnUrl = PropertiesMap.getInstance().getValue("system.login.home");

		RedirectView redirectView = new RedirectView();
		redirectView.setContextRelative(true);
		redirectView.setUrl(returnUrl);

		return new ModelAndView(redirectView);
	}
}