text:
namespace agent {
namespace asan {

// A global recursive lock. This gates all access to block protection
// functions. This is exposed for crash processing, which wants to block
// other threads from tinkering with page protections.
extern ::common::RecursiveLock block_protect_lock;

// Given a pointer to the body of a block extracts its layout. If the block
// header is not under any block protections then the layout will be read from
// the header. If the header is corrupt, or the memory is otherwise unreadable,
// this will be inferred from the shadow memory (less efficient, but not subject
// to corruption). This is effectively a wrapper to BlockInfoFromMemory and
// Shadow::GetBlockInfo.
// @param body A pointer to the body of a block.
// @param block_info The description of the block to be populated.
// @returns true if a valid block was encountered at the provided location,
//     false otherwise.
bool GetBlockInfo(const BlockBody* body, CompactBlockInfo* block_info);
bool GetBlockInfo(const BlockBody* body, BlockInfo* block_info);

// Unprotects all pages fully covered by the given block. All pages
// intersecting but not fully covered by the block will be left in their
// current state.
// @param block_info The block whose protections are to be modified.
// @note Under block_protect_lock.
void BlockProtectNone(const BlockInfo& block_info);

// Protects all entire pages that are spanned by the redzones of the
// block. All pages intersecting the body of the block will be explicitly
// unprotected. All pages not intersecting the body but only partially
// covered by the redzone will be left in their current state.
// @param block_info The block whose protections are to be modified.
// @note Under block_protect_lock.
void BlockProtectRedzones(const BlockInfo& block_info);

// Protects all pages completely spanned by the block. All pages
// intersecting but not fully covered by the block will be left in their
// current state.
// @param block_info The block whose protections are to be modified.
// @note Under block_protect_lock.
void BlockProtectAll(const BlockInfo& block_info);

// Sets the block protections according to the block state. If in the allocated
// state uses BlockProtectRedzones. If in quarantined or freed uses
// BlockProtectAll.
// @param block_info The block whose protections are to be modified.
// @note Under block_protect_lock.
void BlockProtectAuto(const BlockInfo& block_info);

}  // namespace asan
}  // namespace agent

#endif  // SYZYGY_AGENT_ASAN_PAGE_PROTECTION_HELPERS_H_


text:
<?php

namespace RectorPrefix20210615\Symfony\Component\HttpKernel\ControllerMetadata;

/**
 * Builds method argument data.
 *
 * @author Iltar van der Berg <kjarli@gmail.com>
 */
interface ArgumentMetadataFactoryInterface
{
    /**
     * @param mixed $controller The controller to resolve the arguments for
     *
     * @return ArgumentMetadata[]
     */
    public function createArgumentMetadata($controller);
}

redpajama_set_name: RedPajamaGithub


text:
using System.Windows.Forms;
using TGC.Examples.Example;
using TGC.Examples.UserControls;

namespace TGC.Examples.Engine2D.Spaceship
{
    /// <summary>
    ///     Ejemplo Game2D:
    ///     Unidades Involucradas:
    ///     # Unidad 2 - Conceptos Avanzados de 2D - Animacion, Sprites, Primitivas
    ///     MiniJuego de nave con asteroides.
    ///     Muestra como utilizar las herramientas de dibujado 2D de DirectX.
    ///     Muestra como utilizar eventos del mouse y deteccion de colisiones 2D.
    ///     Autor: Leandro Barbagallo, Matias Leone
    /// </summary>
    public class Game2D : TGCExampleViewer
    {
        private GameManager gameManager;

        public Game2D(string mediaDir, string shadersDir, TgcUserVars userVars, Panel modifiersPanel)
            : base(mediaDir, shadersDir, userVars, modifiersPanel)
        {
            Category = "2D";
            Name = "Game 2D";
            Description = "Ejemplo 2D utilizando Sprites. Hacer clic con el mouse para mover la nave.";
        }

        public override void Init()
        {
            gameManager = GameManager.Instance;

            gameManager.Init(MediaDir + "Engine2D\\", UserVars, Input);
        }

        public override void Update()
        {
            gameManager.Update(ElapsedTime);
        }

        public override void Render()
        {
            PreRender();

            gameManager.Render(ElapsedTime);

            PostRender();
        }

        public override void Dispose()
        {
            gameManager.Dispose();
        }
    }
}


text:
/**
 * @file
 * The GPUComputeDriver implements an HSADriver for an HSA AMD GPU
 * agent. Other GPU devices, or other HSA agents, should not derive
 * from this class. Instead device-specific implementations of an
 * HSADriver should be provided for each unique device.
 */

#ifndef __GPU_COMPUTE_GPU_COMPUTE_DRIVER_HH__
#define __GPU_COMPUTE_GPU_COMPUTE_DRIVER_HH__

#include <cassert>
#include <cstdint>
#include <set>
#include <unordered_map>

#include "base/addr_range_map.hh"
#include "base/types.hh"
#include "enums/GfxVersion.hh"
#include "mem/request.hh"
#include "sim/emul_driver.hh"

namespace gem5
{

struct GPUComputeDriverParams;
class GPUCommandProcessor;
class PortProxy;
class ThreadContext;

class GPUComputeDriver final : public EmulatedDriver
{
  public:
    typedef GPUComputeDriverParams Params;
    GPUComputeDriver(const Params &p);
    int ioctl(ThreadContext *tc, unsigned req, Addr ioc_buf) override;

    int open(ThreadContext *tc, int mode, int flags) override;
    Addr mmap(ThreadContext *tc, Addr start, uint64_t length,
              int prot, int tgt_flags, int tgt_fd, off_t offset) override;
    virtual void signalWakeupEvent(uint32_t event_id);
    void sleepCPU(ThreadContext *tc, uint32_t milliSecTimeout);
    /**
     * Called by the compute units right before a request is issued to ruby.
     * This uses our VMAs to correctly set the MTYPE on a per-request basis.
     * In real hardware, this is actually done through PTE bits in GPUVM.
     * Since we are running a single VM (x86 PT) system, the MTYPE bits aren't
     * available.  Adding GPUVM specific bits to x86 page tables probably
     * isn't the best way to proceed.  For now we just have the driver set
     * these until we implement a proper dual PT system.
     */
    void setMtype(RequestPtr req);

    int
    doorbellSize()
    {
        switch (gfxVersion) {
          case GfxVersion::gfx801:
          case GfxVersion::gfx803:
          case GfxVersion::gfx902:
            return 4;
          case GfxVersion::gfx900:
            // gfx900 supports large BAR, so it has a larger doorbell
            return 8;
          default:
            fatal("Invalid GPU type\n");
        }
        return 4;
    }

    class DriverWakeupEvent : public Event
    {
      public:
        DriverWakeupEvent(GPUComputeDriver *gpu_driver,
                          ThreadContext *thrd_cntxt)
          : driver(gpu_driver), tc(thrd_cntxt) {}
        void process() override;
        const char *description() const override;
        void scheduleWakeup(Tick wakeup_delay);
      private:
        GPUComputeDriver *driver;
        ThreadContext *tc;
    };

    class EventTableEntry
    {
      public:
        EventTableEntry() :
            mailBoxPtr(0), tc(nullptr), threadWaiting(false), setEvent(false)
        {}
        // Mail box pointer for this address. Current implementation does not
        // use this mailBoxPtr to notify events but directly calls
        // signalWakeupEvent from dispatcher (GPU) to notifiy events. So,
        // currently this mailBoxPtr is not used. But a future implementation
        // may communicate to the driver using mailBoxPtr.
        Addr mailBoxPtr;
        // Thread context waiting on this even. We do not support multiple
        // threads waiting on an event currently.
        ThreadContext *tc;
        // threadWaiting = true, if some thread context is waiting on this
        // event. A thread context waiting on this event is put to sleep.
        bool threadWaiting;
        // setEvent = true, if this event is triggered but when this event
        // triggered, no thread context was waiting on it. In the future, some
        // thread context will try to wait on this event but since event has
        // already happened, we will not allow that thread context to go to
        // sleep. The above mentioned scneario can happen when the waiting
        // thread and wakeup thread race on this event and the wakeup thread
        // beat the waiting thread at the driver.
        bool setEvent;
    };
    typedef class EventTableEntry ETEntry;

  private:
    /**
     * GPU that is controlled by this driver.
     */
    GPUCommandProcessor *device;
    uint32_t queueId;
    bool isdGPU;
    GfxVersion gfxVersion;
    int dGPUPoolID;
    Addr eventPage;
    uint32_t eventSlotIndex;
    //Event table that keeps track of events. It is indexed with event ID.
    std::unordered_map<uint32_t, ETEntry> ETable;

    /**
     * VMA structures for GPUVM memory.
     */
    AddrRangeMap<Request::CacheCoherenceFlags, 1> gpuVmas;

    /**
     * Mtype bits {Cached, Read Write, Shared} for caches
     */
    enum MtypeFlags
    {
        SHARED                  = 0,
        READ_WRITE              = 1,
        CACHED                  = 2,
        NUM_MTYPE_BITS
    };

    Request::CacheCoherenceFlags defaultMtype;

    // TCEvents map keeps trak of the events that can wakeup this thread. When
    // multiple events can wake up this thread, this data structure helps to
    // reset all events when one of those events wake up this thread. the
    // signal events that can wake up this thread are stored in signalEvents
    // whereas the timer wakeup event is stored in timerEvent.
    class EventList
    {
      public:
        EventList() : driver(nullptr), timerEvent(nullptr, nullptr) {}
        EventList(GPUComputeDriver *gpu_driver, ThreadContext *thrd_cntxt)
            : driver(gpu_driver), timerEvent(gpu_driver, thrd_cntxt)
        { }
        void clearEvents() {
            assert(driver);
            for (auto event : signalEvents) {
                assert(event < driver->eventSlotIndex);
                driver->ETable[event].tc = nullptr;
                driver->ETable[event].threadWaiting = false;
            }
            signalEvents.clear();
            if (timerEvent.scheduled()) {
                driver->deschedule(timerEvent);
            }
        }
        GPUComputeDriver *driver;
        DriverWakeupEvent timerEvent;
        // The set of events that can wake up the same thread.
        std::set<uint32_t> signalEvents;
    };
    std::unordered_map<ThreadContext *, EventList> TCEvents;

    /**
     * Register a region of host memory as uncacheable from the perspective
     * of the dGPU.
     */
    void registerUncacheableMemory(Addr start, Addr length);

    /**
     * The aperture (APE) base/limit pairs are set
     * statically at startup by the real KFD. AMD
     * x86_64 CPUs only use the areas in the 64b
     * address space where VA[63:47] == 0x1ffff or
     * VA[63:47] = 0. These methods generate the APE
     * base/limit pairs in exactly the same way as
     * the real KFD does, which ensures these APEs do
     * not fall into the CPU's address space
     *
     * see the macros in the KFD driver in the ROCm
     * Linux kernel source:
     *
     * drivers/gpu/drm/amd/amdkfd/kfd_flat_memory.c
     */
    Addr gpuVmApeBase(int gpuNum) const;
    Addr gpuVmApeLimit(Addr apeBase) const;
    Addr scratchApeBase(int gpuNum) const;
    Addr scratchApeBaseV9() const;
    Addr scratchApeLimit(Addr apeBase) const;
    Addr ldsApeBase(int gpuNum) const;
    Addr ldsApeBaseV9() const;
    Addr ldsApeLimit(Addr apeBase) const;

    /**
     * Allocate/deallocate GPUVM VMAs for tracking virtual address allocations
     * and properties on DGPUs.  For now, we use these to track MTYPE and to
     * be able to select which pages to unmap when the user provides us with
     * a handle during the free ioctl.
     */
    void allocateGpuVma(Request::CacheCoherenceFlags mtype, Addr start,
                        Addr length);
    Addr deallocateGpuVma(Addr start);

    void allocateQueue(PortProxy &mem_proxy, Addr ioc_buf_addr);

};

} // namespace gem5

#endif // __GPU_COMPUTE_GPU_COMPUTE_DRIVER_HH__


text:
package org.apache.sling.engine.jmx;

import aQute.bnd.annotation.ProviderType;

/**
 * This is the management interface for the SlingRequestProcessor.
 */
@ProviderType
public interface RequestProcessorMBean {

    /**
     * Returns the number of requests collected since last resetting the
     * statistics.
     *
     * @see #resetStatistics()
     */
    long getRequestsCount();

    /**
     * Returns the time in milliseconds used by the longest request since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    long getMaxRequestDurationMsec();

    /**
     * Returns the time in milliseconds used by the shortest request since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    long getMinRequestDurationMsec();

    /**
     * Returns the mean request processing time in milliseconds since resetting
     * the statistics.
     *
     * @see #resetStatistics()
     */
    double getMeanRequestDurationMsec();

    /**
     * Returns the standard deviation of requests since resetting the
     * statistics. If zero or one requests have been collected only, this method
     * returns zero.
     *
     * @see #resetStatistics()
     */
    double getStandardDeviationDurationMsec();

    /**
     * Returns the maximum peak recursive execution depth since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    int getMaxPeakRecursionDepth();

    /**
     * Returns the minimal peak recursive execution depth since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    int getMinPeakRecursionDepth();

    /**
     * Returns the mean peak recursive execution depth since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    double getMeanPeakRecursionDepth();

    /**
     * Returns the standard deviation of peak recursive execution depth since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    double getStandardDeviationPeakRecursionDepth();

    /**
     * Returns the maximum servlet call count since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    int getMaxServletCallCount();

    /**
     * Returns the minimum servlet call count since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    int getMinServletCallCount();

    /**
     * Returns the mean servlet call count since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    double getMeanServletCallCount();

    /**
     * Returns the standard deviation servlet call counts since last
     * resetting the statistics.
     *
     * @see #resetStatistics()
     */
    double getStandardDeviationServletCallCount();

    /**
     * Resets all statistics values and restarts from zero.
     */
    void resetStatistics();

}


text:
import React from "react"

import {Layout} from "@internal/ui"
import {Heading} from "@internal/elements"

export default function PrivacyPolicy () {
  return <Layout subtitle="Privacy Policy" kind="article" data-component="PrivacyPolicy">

      <Heading kind="section">
        Empty
      </Heading>

        To be filled

  </Layout>
}


text:
var _ = require('lodash');
var async = require('async');
var crypto = require('crypto');
// var passport = require('passport');
var Post = require('../models/Post');
var validator = require('validator');
var randomstring = require("randomstring");
var ObjectId = require('mongodb').ObjectID;
var obj = {};
/**
 * POST /post
 * Post Ad.
 */
exports.saveAd = function(req, res) {
  console.log('saveAd');
  req.assert('productname', 'Product Name is not valid').matches(/^[a-z0-9 ]+$/i);
  req.assert('category', 'Category is not valid').isAlphanumeric();
  req.assert('condition', 'Condition is not valid').isAlphanumeric();
  req.assert('description', 'Description is not valid').matches(/^[a-z0-9 ]+$/i);
  req.assert('photos', 'Photos is not valid').isLength('5');
  req.assert('price', 'Price is not valid').isNumeric();
  req.assert('createdby', 'CreatedBy is not valid').isAlphanumeric();

  var errors = req.validationErrors();
  if (errors) {
    obj = {
      result: "failed",
      resultMessage: errors
    }
    res.send(obj);
  }else{
    console.log('Success all inputs sanitized');
    var post = new Post({
      productName : req.body.productname,
      category    : req.body.category,
      condition   : req.body.condition,
      description : req.body.description,
      photos      : req.body.photos,
      price       : req.body.price,
      createdBy   : req.body.createdby,
      is_deleted : false,
      is_archived : false
    });
    post.save (function (err, result) {
      if (err) {
        obj = {
          result: "failed",
          resultMessage: "Creating new Ad failed."
        }
      }else{
        obj = {
          result: "success",
          resultMessage: "Congratulations, You have successfully created a new Ad."
        }
      }
      return res.send(obj);
    });
  }
};

exports.getAds = function (req,res) {
  console.log(req.query.limit);
  var limits = req.query.limit;

  if(limits){
    Post.find({})
        .limit(parseInt(limits))
        // .sort({ created_at: -1 })
        .exec(function(err,post){
          console.log(post);
          res.send(post);
        });
  }else{
    Post.find({})
        .limit(parseInt(20))
        // .sort({ created_at: -1 })
        .exec(function(err,post){
          console.log(post);
          res.send(post);
        });
  }

}

exports.viewAd = function(req, res) {
  Post.findOne({ "_id": ObjectId(req.params.post_id) }, function (err, post) {
    if (err) return res.send(err);
    res.send(post);
  });
}

exports.soldAd = function(req,res) {
  Post.findOne({ "_id": ObjectId(req.params.post_id) }, function (err, post) {
    if (err) return res.send(err);

    post.is_archived = true;
    post.save (function (err, result) {
      if (err) {
        obj = {
          result: "failed",
          resultMessage: "Archiving your Ad failed."
        }
      }else{
        obj = {
          result: "success",
          resultMessage: "Congratulations, Your Ad was successfully archived"
        }
      }
      console.log(obj);
      res.send(obj);
    });
  });
}

exports.userAd = function(req,res) {
  Post.find({ "createdBy" : req.params.user_id }, function (err, posts) {
    if (err) return res.send(err);
    res.send(posts);
  });
}

exports.updateAd = function(req,res) {

  Post.findOne({ "_id": ObjectId(req.params.post_id)}, function (err, post) {
    if (err) return res.send(err);

    console.log('req.body: ', req.body);
    if (req.body.productname) {
      post.productName = req.body.productname;
    }

    if (req.body.category) {
      post.category = req.body.category;
    }

    if (req.body.condition) {
      post.condition = req.body.condition;
    }

    if (req.body.description) {
      post.description = req.body.description;
    }

    if (req.body.photos) {
      post.photos = req.body.photos;
    }

    if (req.body.price) {
      post.price = req.body.price;
    }
    console.log('before update: ', post);
    post.save (function (err, result) {
      if (err) {
        obj = {
          result: "failed",
          resultMessage: "Updating your Ad failed."
        }
      }else{
        obj = {
          result: "success",
          resultMessage: "Congratulations, Your Ad was successfully updated"
        }
      }
      // console.log(obj);
      res.send(obj);
    });
  });
}

exports.deleteAd = function(req,res){
  Post.findOne({ "_id": ObjectId(req.params.post_id) }, function (err, post) {
    if (err) return res.send(err);

    if(req.body.isdeleted){
      post.isdeleted = req.body.isdeleted;
    }

    post.save (function (err, result) {
      if (err) {
        obj = {
          result: "failed",
          resultMessage: "Updating your Ad failed."
        }
      }else{
        obj = {
          result: "success",
          resultMessage: "Congratulations, Your Ad was successfully updated"
        }
      }
      console.log(obj);
      res.send(obj);
    });
  });
}


text:
class Token < ApplicationRecord
  has_secure_token(:value)

  belongs_to(:created_by, class_name: 'User')

  validates(:created_by_id, presence: true)
  validates(:name, presence: true, uniqueness: { scope: :created_by_id })

  scope(:recent, -> { order(created_at: :desc) })
end


text:
<!DOCTYPE html>

        <title>Wingman - Alter Order</title>

        <link type="text/css" rel="stylesheet" media="only screen and (min-device-width: 768px) and (max-device-width: 1920px)" href="styling/style_tablet.css" />

Wingman

            <input type="button" value="Home" id="home_button" class="header_button" onClick="window.location.href='main_menu.php'">

            <input type="button" value="Back" id="back_button" class="header_button" onClick="window.location.href='alter_order_blade.php'">

            <input type="button" value="Log Out" id="logout_button" class="header_button" onClick="window.location.href='index.php'">

            <input type="button" value="Alter Order" id="button_1" class="highlighted_mainmenu_button">

                <form name="createorder_form" method="post" action="">

                            <select name="blade_location" size="1" class="input_field_middle_2" required="required">
                                <option selected="selected" value="">From: Blade Location</option>
                                <option value=""></option>
                            </select>

                            <select name="user_location" size="1" class="input_field_middle_3" required="required">
                                <option selected="selected" value="">To: User Location</option>
                                <option value=""></option>
                            </select>

                            <input type="time" name="time" id="time" class="input_field_middle_4" required="required">

                            <input type="button" value="Update and Save" id="accept_button" class="input_button" onClick="window.location.href='alter_order.php'">

                </form>

HELP:

    Select a new
    "From: Blade Location".

    Select a new
    "To: User Location".

    Select a new
    delivery Time.


text:
package im.actor.core.network;

public class RpcInternalException extends RpcException {
    public RpcInternalException() {
        super("INTERNAL_ERROR", 500, "Internal server error", true, null);
    }
}


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/fb.h>
#include <linux/leds.h>
#include <linux/err.h>
#include <linux/pwm.h>
#include <linux/leds_pwm.h>
#include <linux/slab.h>

struct led_pwm_data {
	struct led_classdev	cdev;
	struct pwm_device	*pwm;
	unsigned int 		active_low;
	unsigned int		period;
};

static void led_pwm_set(struct led_classdev *led_cdev,
	enum led_brightness brightness)
{
	struct led_pwm_data *led_dat =
		container_of(led_cdev, struct led_pwm_data, cdev);
	unsigned int max = led_dat->cdev.max_brightness;
	unsigned int period =  led_dat->period;

	if (brightness == 0) {
		pwm_config(led_dat->pwm, 0, period);
		pwm_disable(led_dat->pwm);
	} else {
		pwm_config(led_dat->pwm, brightness * period / max, period);
		pwm_enable(led_dat->pwm);
	}
}

static int led_pwm_probe(struct platform_device *pdev)
{
	struct led_pwm_platform_data *pdata = pdev->dev.platform_data;
	struct led_pwm *cur_led;
	struct led_pwm_data *leds_data, *led_dat;
	int i, ret = 0;

	if (!pdata)
		return -EBUSY;

	leds_data = kzalloc(sizeof(struct led_pwm_data) * pdata->num_leds,
				GFP_KERNEL);
	if (!leds_data)
		return -ENOMEM;

	for (i = 0; i < pdata->num_leds; i++) {
		cur_led = &pdata->leds[i];
		led_dat = &leds_data[i];

		led_dat->pwm = pwm_request(cur_led->pwm_id,
				cur_led->name);
		if (IS_ERR(led_dat->pwm)) {
			ret = PTR_ERR(led_dat->pwm);
			dev_err(&pdev->dev, "unable to request PWM %d\n",
					cur_led->pwm_id);
			goto err;
		}

		led_dat->cdev.name = cur_led->name;
		led_dat->cdev.default_trigger = cur_led->default_trigger;
		led_dat->active_low = cur_led->active_low;
		led_dat->period = cur_led->pwm_period_ns;
		led_dat->cdev.brightness_set = led_pwm_set;
		led_dat->cdev.brightness = LED_OFF;
		led_dat->cdev.max_brightness = cur_led->max_brightness;
		led_dat->cdev.flags |= LED_CORE_SUSPENDRESUME;

		ret = led_classdev_register(&pdev->dev, &led_dat->cdev);
		if (ret < 0) {
			pwm_free(led_dat->pwm);
			goto err;
		}
	}

	platform_set_drvdata(pdev, leds_data);

	return 0;

err:
	if (i > 0) {
		for (i = i - 1; i >= 0; i--) {
			led_classdev_unregister(&leds_data[i].cdev);
			pwm_free(leds_data[i].pwm);
		}
	}

	kfree(leds_data);

	return ret;
}

static int __devexit led_pwm_remove(struct platform_device *pdev)
{
	int i;
	struct led_pwm_platform_data *pdata = pdev->dev.platform_data;
	struct led_pwm_data *leds_data;

	leds_data = platform_get_drvdata(pdev);

	for (i = 0; i < pdata->num_leds; i++) {
		led_classdev_unregister(&leds_data[i].cdev);
		pwm_free(leds_data[i].pwm);
	}

	kfree(leds_data);

	return 0;
}

static struct platform_driver led_pwm_driver = {
	.probe		= led_pwm_probe,
	.remove		= __devexit_p(led_pwm_remove),
	.driver		= {
		.name	= "leds_pwm",
		.owner	= THIS_MODULE,
	},
};

static int __init led_pwm_init(void)
{
	return platform_driver_register(&led_pwm_driver);
}

static void __exit led_pwm_exit(void)
{
	platform_driver_unregister(&led_pwm_driver);
}

module_init(led_pwm_init);
module_exit(led_pwm_exit);

MODULE_AUTHOR("Luotao Fu <l.fu@pengutronix.de>");
MODULE_DESCRIPTION("PWM LED driver for PXA");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:leds-pwm");


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
        <item
        android:drawable="@drawable/upomp_lthj_button_gray_noselect"
        android:top="0dip"
        android:right="0dip"
        android:bottom="0dip"
        android:left="0dip" />
        <item
        android:drawable="@drawable/upomp_lthj_button_select"
        android:top="0dip"
        android:right="0dip"
        android:bottom="0dip"
        android:left="0dip" />
</layer-list>


text:
import gym
import universe

env = gym.make('flashgames.DuskDrive-v0')
observation_n = env.reset()

while True:
    action_n = [[('KeyEvent', 'ArrowUp', True)] for ob in observation_n] # your agent here
    observation_n, reward_n, done_n, info = env.step(action_n)
    env.render()


text:
<ion-view view-title="Top Projects ({{selectedLanguage}})">
	<top-projects time-scale="monthly" language="selectedLanguage"></top-projects>
</ion-view>


text:
layout: default
---

    {% for post in site.posts %}

                    <meta itemprop="datePublished" content="{{post.date}}">
                    <time datetime="{{ post.date | date_to_xmlschema }}">

                            {{ post.date | date: "%d" }}

                            {{ post.date | date: "%B %Y" }}

                    </time>

{{ post.title }}

                        {{ post.content | strip_html | truncatewords:40 }}
                        Read more about {{post.title}}

                        {% for tag in post.tags %}
                            {{ tag }}
                        {% endfor %}

    {% endfor %}


text:
import {inject} from 'aurelia-dependency-injection';
import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli';

@inject(Project, CLIOptions, UI)
export default class TaskGenerator {
  constructor(project, options, ui) {
    this.project = project;
    this.options = options;
    this.ui = ui;
  }

  async execute() {
    const name = await this.ui.ensureAnswer(
      this.options.args[0],
      'What would you like to call the task?'
    );

    let fileName = this.project.makeFileName(name);
    let functionName = this.project.makeFunctionName(name);

    this.project.tasks.add(
      ProjectItem.text(`${fileName}.js`, this.generateSource(functionName))
    );

    await this.project.commitChanges();
    await this.ui.log(`Created ${fileName}.`);
  }

  generateSource(functionName) {
    return `import gulp from 'gulp';
import project from '../aurelia.json';

export default function ${functionName}() {
  return gulp.src(project.paths.???)
    .pipe(gulp.dest(project.paths.output));
}
`;

  }
}


text:
//[-------------------------------------------------------]
//[ Includes                                              ]
//[-------------------------------------------------------]
#include "Renderer/Public/Resource/CompositorNode/Pass/ShadowMap/CompositorInstancePassShadowMap.h"
#include "Renderer/Public/Resource/CompositorNode/Pass/Compute/CompositorInstancePassCompute.h"
#include "Renderer/Public/Resource/CompositorNode/Pass/Compute/CompositorResourcePassCompute.h"
#include "Renderer/Public/Resource/CompositorNode/CompositorNodeInstance.h"
#include "Renderer/Public/Resource/CompositorWorkspace/CompositorContextData.h"
#include "Renderer/Public/Resource/Texture/TextureResourceManager.h"
#include "Renderer/Public/Resource/Scene/Item/Camera/CameraSceneItem.h"
#include "Renderer/Public/Resource/Scene/Item/Light/LightSceneItem.h"
#include "Renderer/Public/Resource/Scene/SceneNode.h"
#include "Renderer/Public/RenderQueue/RenderableManager.h"
#include "Renderer/Public/Core/Math/Math.h"
#include "Renderer/Public/Core/IProfiler.h"
#include "Renderer/Public/IRenderer.h"

// Disable warnings in external headers, we can't fix them
PRAGMA_WARNING_PUSH
	PRAGMA_WARNING_DISABLE_MSVC(4464)	// warning C4464: relative include path contains '..'
	#include <glm/gtc/matrix_transform.hpp>
PRAGMA_WARNING_POP

#include <algorithm>

//[-------------------------------------------------------]
//[ Anonymous detail namespace                            ]
//[-------------------------------------------------------]
namespace
{
	namespace detail
	{

		//[-------------------------------------------------------]
		//[ Global definitions                                    ]
		//[-------------------------------------------------------]
		static constexpr float	  SHADOW_MAP_FILTER_SIZE							  = 7.0f;
		static constexpr uint8_t  INTERMEDIATE_CASCADE_INDEX						  = 3;
		static constexpr uint32_t DEPTH_SHADOW_MAP_TEXTURE_ASSET_ID					  = ASSET_ID("Unrimp/Texture/DynamicByCode/DepthShadowMap");
		static constexpr uint32_t INTERMEDIATE_DEPTH_BLUR_SHADOW_MAP_TEXTURE_ASSET_ID = ASSET_ID("Unrimp/Texture/DynamicByCode/IntermediateDepthBlurShadowMap");

		//[-------------------------------------------------------]
		//[ Global functions                                      ]
		//[-------------------------------------------------------]
		[[nodiscard]] glm::vec4 transformVectorByMatrix(const glm::mat4& matrix, const glm::vec4& vector)
		{
			const glm::vec4 temporaryVector = matrix * vector;
			return temporaryVector / temporaryVector.w;
		}

//[-------------------------------------------------------]
//[ Anonymous detail namespace                            ]
//[-------------------------------------------------------]
	} // detail
}

//[-------------------------------------------------------]
//[ Namespace                                             ]
//[-------------------------------------------------------]
namespace Renderer
{

	//[-------------------------------------------------------]
	//[ Public methods                                        ]
	//[-------------------------------------------------------]
	void CompositorInstancePassShadowMap::setNumberOfShadowCascades(uint8_t numberOfShadowCascades)
	{
		if (mNumberOfShadowCascades != numberOfShadowCascades)
		{
			RHI_ASSERT(getCompositorNodeInstance().getCompositorWorkspaceInstance().getRenderer().getContext(), numberOfShadowCascades <= CompositorResourcePassShadowMap::MAXIMUM_NUMBER_OF_SHADOW_CASCADES, "Invalid number of shadow cascades")
			mNumberOfShadowCascades = numberOfShadowCascades;
			++mSettingsGenerationCounter;
		}
	}

	void CompositorInstancePassShadowMap::setNumberOfShadowMultisamples(uint8_t numberOfShadowMultisamples)
	{
		if (mNumberOfShadowMultisamples != numberOfShadowMultisamples)
		{
			RHI_ASSERT(getCompositorNodeInstance().getCompositorWorkspaceInstance().getRenderer().getContext(), numberOfShadowMultisamples >= 1, "Invalid number of shadow multisamples")
			RHI_ASSERT(getCompositorNodeInstance().getCompositorWorkspaceInstance().getRenderer().getContext(), numberOfShadowMultisamples <= getCompositorNodeInstance().getCompositorWorkspaceInstance().getRenderer().getRhi().getCapabilities().maximumNumberOfMultisamples, "Invalid number of shadow multisamples")
			mNumberOfShadowMultisamples = numberOfShadowMultisamples;
			++mSettingsGenerationCounter;
		}
	}

	//[-------------------------------------------------------]
	//[ Protected virtual Renderer::ICompositorInstancePass methods ]
	//[-------------------------------------------------------]
	void CompositorInstancePassShadowMap::onFillCommandBuffer([[maybe_unused]] const Rhi::IRenderTarget* renderTarget, const CompositorContextData& compositorContextData, Rhi::CommandBuffer& commandBuffer)
	{
		const CompositorWorkspaceInstance& compositorWorkspaceInstance = getCompositorNodeInstance().getCompositorWorkspaceInstance();
		const IRenderer& renderer = compositorWorkspaceInstance.getRenderer();

		// Sanity check
		RHI_ASSERT(renderer.getContext(), nullptr == renderTarget, "The shadow map compositor instance pass needs an invalid render target")

		// Settings update handling
		if (mUsedSettingsGenerationCounter != mSettingsGenerationCounter)
		{
			mUsedSettingsGenerationCounter = mSettingsGenerationCounter;
			destroyShadowMapRenderTarget();
			createShadowMapRenderTarget();
		}

		// Early escape if shadow is disabled
		if (!mEnabled)
		{
			return;
		}

		// Fill command buffer
		const CameraSceneItem* cameraSceneItem = compositorContextData.getCameraSceneItem();
		const LightSceneItem* lightSceneItem = compositorContextData.getLightSceneItem();
		if (nullptr != mDepthFramebufferPtr && nullptr != cameraSceneItem && cameraSceneItem->getParentSceneNode() && nullptr != lightSceneItem && lightSceneItem->getParentSceneNode())
		{
			const glm::vec3 worldSpaceSunlightDirection = lightSceneItem->getParentSceneNode()->getGlobalTransform().rotation * Math::VEC3_FORWARD;
			mPassData.shadowMapSize = static_cast<int>(mShadowMapSize);

			// TODO(co) Stabilize cascades Reversed-Z update
			const bool stabilizeCascades = false;
//			const bool stabilizeCascades = mStabilizeCascades;

			// TODO(co) The minimum and maximum distance need to be calculated dynamically via depth buffer reduction as seen inside e.g. https://github.com/TheRealMJP/MSAAFilter/tree/master/MSAAFilter
			const float minimumDistance = 0.0f;
			const float maximumDistance = 0.5f;

			// Compute the split distances based on the partitioning mode
			float cascadeSplits[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
			{
				const float nearClip = cameraSceneItem->getNearZ();
				const float farClip = cameraSceneItem->getFarZ();
				const float clipRange = farClip - nearClip;
				const float minimumZ = nearClip + minimumDistance * clipRange;
				const float maximumZ = nearClip + maximumDistance * clipRange;
				const float range = maximumZ - minimumZ;
				const float ratio = maximumZ / minimumZ;

				for (uint8_t cascadeIndex = 0; cascadeIndex < mNumberOfShadowCascades; ++cascadeIndex)
				{
					const float p = static_cast<float>(cascadeIndex + 1) / static_cast<float>(mNumberOfShadowCascades);
					const float log = minimumZ * std::pow(ratio, p);
					const float uniform = minimumZ + range * p;
					const float d = mCascadeSplitsLambda * (log - uniform) + uniform;
					cascadeSplits[cascadeIndex] = (d - nearClip) / clipRange;
				}
			}

			// Coordinate system related adjustments
			// -> Vulkan and Direct3D: Left-handed coordinate system with clip space depth value range 0..1
			// -> OpenGL without "GL_ARB_clip_control"-extension: Right-handed coordinate system with clip space depth value range -1..1
			const float nearZ = renderer.getRhi().getCapabilities().zeroToOneClipZ ? 0.0f : -1.0f;

			// Get the 8 points of the view frustum in world space
			glm::vec4 worldSpaceFrustumCorners[8] =
			{
				// Near
				{-1.0f,  1.0f, nearZ, 1.0f},	// 0: Near top left
				{ 1.0f,  1.0f, nearZ, 1.0f},	// 1: Near top right
				{-1.0f, -1.0f, nearZ, 1.0f},	// 2: Near bottom left
				{ 1.0f, -1.0f, nearZ, 1.0f},	// 3: Near bottom right
				// Far
				{-1.0f,  1.0f, 1.0f, 1.0f},		// 4: Far top left
				{ 1.0f,  1.0f, 1.0f, 1.0f},		// 5: Far top right
				{-1.0f, -1.0f, 1.0f, 1.0f},		// 6: Far bottom left
				{ 1.0f, -1.0f, 1.0f, 1.0f}		// 7: Far bottom right
			};
			{
				uint32_t renderTargetWidth = 0;
				uint32_t renderTargetHeight = 0;
				RHI_ASSERT(renderer.getContext(), nullptr != compositorWorkspaceInstance.getExecutionRenderTarget(), "Invalid compositor workspace instance execution render target")
				compositorWorkspaceInstance.getExecutionRenderTarget()->getWidthAndHeight(renderTargetWidth, renderTargetHeight);
				if (compositorContextData.getSinglePassStereoInstancing())
				{
					renderTargetWidth /= 2;
				}
				const glm::mat4 worldSpaceToClipSpaceMatrix = cameraSceneItem->getViewSpaceToClipSpaceMatrix(static_cast<float>(renderTargetWidth) / static_cast<float>(renderTargetHeight)) * cameraSceneItem->getCameraRelativeWorldSpaceToViewSpaceMatrix();
				const glm::mat4 clipSpaceToWorldSpaceMatrix = glm::inverse(worldSpaceToClipSpaceMatrix);
				for (int i = 0; i < 8; ++i)
				{
					worldSpaceFrustumCorners[i] = ::detail::transformVectorByMatrix(clipSpaceToWorldSpaceMatrix, worldSpaceFrustumCorners[i]);
				}
			}

			// Combined scoped profiler CPU and GPU sample as well as renderer debug event command
			RENDERER_SCOPED_PROFILER_EVENT_DYNAMIC(renderer.getContext(), commandBuffer, static_cast<const CompositorResourcePassShadowMap&>(getCompositorResourcePass()).getDebugName())

			// Render the meshes to each cascade
			// -> Shadows should never be rendered via single pass stereo instancing
			const CompositorContextData shadowCompositorContextData(compositorContextData.getCompositorWorkspaceInstance(), compositorContextData.getCameraSceneItem(), false, compositorContextData.getLightSceneItem(), compositorContextData.getCompositorInstancePassShadowMap());
			for (uint8_t cascadeIndex = 0; cascadeIndex < mNumberOfShadowCascades; ++cascadeIndex)
			{
				// Scoped debug event
				RENDERER_SCOPED_PROFILER_EVENT_DYNAMIC(renderer.getContext(), commandBuffer, ("Shadow cascade " + std::to_string(cascadeIndex)).c_str())

				// Compute the MVP matrix from the light's point of view
				glm::mat4 depthProjectionMatrix;
				glm::mat4 depthViewMatrix;
				glm::vec3 minimumExtents;
				glm::vec3 maximumExtents;
				glm::vec3 cascadeExtents;
				const float splitDistance = cascadeSplits[cascadeIndex];
				{
					const float previousSplitDistance = (0 == cascadeIndex) ? minimumDistance : cascadeSplits[cascadeIndex - 1];

					// Get the corners of the current cascade slice of the view frustum
					glm::vec4 cascadeSliceWorldSpaceFrustumCorners[8];
					for (int i = 0; i < 4; ++i)
					{
						const glm::vec4 cornerRay = worldSpaceFrustumCorners[i + 4] - worldSpaceFrustumCorners[i];
						const glm::vec4 nearCornerRay = cornerRay * previousSplitDistance;
						const glm::vec4 farCornerRay = cornerRay * splitDistance;
						cascadeSliceWorldSpaceFrustumCorners[i + 4] = worldSpaceFrustumCorners[i] + farCornerRay;
						cascadeSliceWorldSpaceFrustumCorners[i] = worldSpaceFrustumCorners[i] + nearCornerRay;
					}

					// Calculate the centroid of the view frustum slice
					glm::vec4 temporaryFrustumCenter = Math::VEC4_ZERO;
					for (int i = 0; i < 8; ++i)
					{
						temporaryFrustumCenter += cascadeSliceWorldSpaceFrustumCorners[i];
					}
					const glm::vec3 frustumCenter = temporaryFrustumCenter / 8.0f;

					// Pick the right vector to use for the light camera, this needs to be constant for it to be stable
					const glm::vec3 rightDirection = stabilizeCascades ? Math::VEC3_RIGHT : (cameraSceneItem->getParentSceneNodeSafe().getTransform().rotation * Math::VEC3_RIGHT);

					// Calculate the minimum and maximum extents
					if (stabilizeCascades)
					{
						// Calculate the radius of a bounding sphere surrounding the frustum corners
						float sphereRadius = 0.0f;
						for (int i = 0; i < 8; ++i)
						{
							const float distance = glm::distance(glm::vec3(cascadeSliceWorldSpaceFrustumCorners[i]), frustumCenter);
							sphereRadius = std::max(sphereRadius, distance);
						}
						sphereRadius = std::ceil(sphereRadius * 16.0f) / 16.0f;
						maximumExtents = glm::vec3(sphereRadius, sphereRadius, sphereRadius);
						minimumExtents = -maximumExtents;
					}
					else
					{
						// Create a temporary view matrix for the light
						const glm::vec3& lightCameraPosition = frustumCenter;
						const glm::vec3 lightCameraTarget = frustumCenter - worldSpaceSunlightDirection;
						const glm::mat4 lightView = glm::lookAt(lightCameraPosition, lightCameraTarget, rightDirection);

						// Calculate an AABB around the frustum corners
						glm::vec4 mins(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
						glm::vec4 maxes(std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min());
						for (int i = 0; i < 8; ++i)
						{
							const glm::vec4 corner = ::detail::transformVectorByMatrix(lightView, cascadeSliceWorldSpaceFrustumCorners[i]);
							mins = glm::min(mins, corner);
							maxes = glm::max(maxes, corner);
						}
						minimumExtents = mins;
						maximumExtents = maxes;

						// Adjust the minimum/maximum to accommodate the filtering size
						const float scale = (static_cast<float>(mShadowMapSize) + ::detail::SHADOW_MAP_FILTER_SIZE) / static_cast<float>(mShadowMapSize);
						minimumExtents.x *= scale;
						minimumExtents.y *= scale;
						maximumExtents.x *= scale;
						maximumExtents.x *= scale;
					}
					cascadeExtents = maximumExtents - minimumExtents;

					// Get position of the shadow camera
					const glm::vec3 shadowCameraPosition = frustumCenter + worldSpaceSunlightDirection * -minimumExtents.z;

					// Come up with a new orthographic camera for the shadow caster
					depthProjectionMatrix = glm::ortho(minimumExtents.x, maximumExtents.x, minimumExtents.y, maximumExtents.y, 0.0f, cascadeExtents.z);
					depthViewMatrix = glm::lookAt(shadowCameraPosition, frustumCenter, rightDirection);
				}

				// Create the rounding matrix, by projecting the world-space origin and determining the fractional offset in texel space
				glm::mat4 viewSpaceToClipSpace = depthProjectionMatrix * depthViewMatrix;
				if (stabilizeCascades)
				{
					glm::vec4 shadowOrigin(0.0f, 0.0f, 0.0f, 1.0f);
					shadowOrigin = ::detail::transformVectorByMatrix(viewSpaceToClipSpace, shadowOrigin);
					shadowOrigin *= static_cast<float>(mShadowMapSize) * 0.5f;

					const glm::vec4 roundedOrigin = glm::round(shadowOrigin);
					glm::vec4 roundOffset = roundedOrigin - shadowOrigin;
					roundOffset *= 2.0f / static_cast<float>(mShadowMapSize);
					roundOffset.z = 0.0f;
					roundOffset.w = 0.0f;

					depthProjectionMatrix[3] += roundOffset;
					viewSpaceToClipSpace = depthProjectionMatrix * depthViewMatrix;
				}

				// Set custom camera matrices
				const_cast<CameraSceneItem*>(cameraSceneItem)->setCustomWorldSpaceToViewSpaceMatrix(depthViewMatrix);
				const_cast<CameraSceneItem*>(cameraSceneItem)->setCustomViewSpaceToClipSpaceMatrix(depthProjectionMatrix, glm::ortho(minimumExtents.x, maximumExtents.x, minimumExtents.y, maximumExtents.y, cascadeExtents.z, 0.0f));

				{ // Render shadow casters
					// Scoped debug event
					RENDERER_SCOPED_PROFILER_EVENT(renderer.getContext(), commandBuffer, "Render shadow casters")

					// Set graphics render target
					Rhi::Command::SetGraphicsRenderTarget::create(commandBuffer, mDepthFramebufferPtr);

					// Set the graphics viewport and scissor rectangle
					Rhi::Command::SetGraphicsViewportAndScissorRectangle::create(commandBuffer, 0, 0, mShadowMapSize, mShadowMapSize);

					{ // Clear the graphics depth buffer of the current render target
						const float color[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
						Rhi::Command::ClearGraphics::create(commandBuffer, Rhi::ClearFlag::DEPTH, color);
					}

					// Render shadow casters
					// TODO(co) Optimization: Do only render stuff which calls into the current shadow cascade
					RHI_ASSERT(renderer.getContext(), nullptr != mRenderQueueIndexRange, "Invalid render queue index range")
					const MaterialTechniqueId materialTechniqueId = static_cast<const CompositorResourcePassScene&>(getCompositorResourcePass()).getMaterialTechniqueId();
					for (const RenderableManager* renderableManager : mRenderQueueIndexRange->renderableManagers)
					{
						// The render queue index range covered by this compositor instance pass scene might be smaller than the range of the
						// cached render queue index range. So, we could add a range check in here to reject renderable managers, but it's not
						// really worth to do so since the render queue only considers renderables inside the render queue range anyway.
						if (renderableManager->getCastShadows())
						{
							mRenderQueue.addRenderablesFromRenderableManager(*renderableManager, materialTechniqueId, shadowCompositorContextData, true);
						}
					}
					if (mRenderQueue.getNumberOfDrawCalls() > 0)
					{
						mRenderQueue.fillGraphicsCommandBuffer(*mDepthFramebufferPtr, shadowCompositorContextData, commandBuffer);
						mRenderQueue.clear();
					}
				}

				// Unset custom camera matrices
				const_cast<CameraSceneItem*>(cameraSceneItem)->unsetCustomWorldSpaceToViewSpaceMatrix();
				const_cast<CameraSceneItem*>(cameraSceneItem)->unsetCustomViewSpaceToClipSpaceMatrix();

				// Apply the scale/offset matrix, which transforms from [-1,1] post-projection space to [0,1] UV space
				const glm::mat4 shadowMatrix = Math::getTextureScaleBiasMatrix(renderer.getRhi()) * viewSpaceToClipSpace;

				// Store the split distance in terms of view space depth
				const float clipDistance = cameraSceneItem->getFarZ() - cameraSceneItem->getNearZ();
				mPassData.shadowCascadeSplits[cascadeIndex] = cameraSceneItem->getNearZ() + splitDistance * clipDistance;
				if (0 == cascadeIndex)
				{
					mPassData.shadowMatrix = shadowMatrix;
					mPassData.shadowCascadeOffsets[0] = Math::VEC4_ZERO;
					mPassData.shadowCascadeScales[0] = Math::VEC4_ONE;
				}
				else
				{
					// Calculate the position of the lower corner of the cascade partition, in the UV space of the first cascade partition
					const glm::mat4 inverseShadowMatrix = glm::inverse(shadowMatrix);
					glm::vec4 cascadeCorner = ::detail::transformVectorByMatrix(inverseShadowMatrix, glm::vec4(0.0f, 0.0f, 0.0f, 1.0f));
					cascadeCorner = ::detail::transformVectorByMatrix(mPassData.shadowMatrix, cascadeCorner);

					// Do the same for the upper corner
					glm::vec4 otherCorner = ::detail::transformVectorByMatrix(inverseShadowMatrix, Math::VEC4_ONE);
					otherCorner = ::detail::transformVectorByMatrix(mPassData.shadowMatrix, otherCorner);

					// Calculate the scale and offset
					const glm::vec4 cascadeScale = Math::VEC4_ONE / (otherCorner - cascadeCorner);
					mPassData.shadowCascadeOffsets[cascadeIndex] = glm::vec4(-glm::vec3(cascadeCorner), 0.0f);
					mPassData.shadowCascadeScales[cascadeIndex] = glm::vec4(glm::vec3(cascadeScale), 1.0f);
				}
				mPassData.currentShadowCascadeIndex = cascadeIndex;

				// Calculate exponential variance shadow map (EVSM) and blur if necessary
				const glm::vec4& cascadeScale = mPassData.shadowCascadeScales[cascadeIndex];
				const float filterSizeX = std::max(mShadowFilterSize * cascadeScale.x, 1.0f);
				const float filterSizeY = std::max(mShadowFilterSize * cascadeScale.y, 1.0f);
				if (filterSizeX > 1.0f || filterSizeY > 1.0f)
				{
					// Execute compositor instance pass compute, use cascade index three as intermediate render target
					RHI_ASSERT(renderer.getContext(), nullptr != mVarianceFramebufferPtr[::detail::INTERMEDIATE_CASCADE_INDEX], "Invalid variance framebuffer")
					Rhi::Command::SetGraphicsRenderTarget::create(commandBuffer, mVarianceFramebufferPtr[::detail::INTERMEDIATE_CASCADE_INDEX]);
					mDepthToExponentialVarianceCompositorInstancePassCompute->onFillCommandBuffer(mVarianceFramebufferPtr[::detail::INTERMEDIATE_CASCADE_INDEX], shadowCompositorContextData, commandBuffer);
					mDepthToExponentialVarianceCompositorInstancePassCompute->onPostCommandBufferDispatch();

					// Horizontal blur
					mPassData.shadowFilterSize = filterSizeX;
					Rhi::Command::SetGraphicsRenderTarget::create(commandBuffer, mIntermediateFramebufferPtr);
					mHorizontalBlurCompositorInstancePassCompute->onFillCommandBuffer(mIntermediateFramebufferPtr, shadowCompositorContextData, commandBuffer);
					mHorizontalBlurCompositorInstancePassCompute->onPostCommandBufferDispatch();

					// Vertical blur
					mPassData.shadowFilterSize = filterSizeY;
					RHI_ASSERT(renderer.getContext(), nullptr != mVarianceFramebufferPtr[cascadeIndex], "Invalid variance framebuffer")
					Rhi::Command::SetGraphicsRenderTarget::create(commandBuffer, mVarianceFramebufferPtr[cascadeIndex]);
					mVerticalBlurCompositorInstancePassCompute->onFillCommandBuffer(mVarianceFramebufferPtr[cascadeIndex], shadowCompositorContextData, commandBuffer);
					mVerticalBlurCompositorInstancePassCompute->onPostCommandBufferDispatch();
				}
				else
				{
					// Execute compositor instance pass compute
					RHI_ASSERT(renderer.getContext(), nullptr != mVarianceFramebufferPtr[cascadeIndex], "Invalid variance framebuffer")
					Rhi::Command::SetGraphicsRenderTarget::create(commandBuffer, mVarianceFramebufferPtr[cascadeIndex]);
					mDepthToExponentialVarianceCompositorInstancePassCompute->onFillCommandBuffer(mVarianceFramebufferPtr[cascadeIndex], shadowCompositorContextData, commandBuffer);
					mDepthToExponentialVarianceCompositorInstancePassCompute->onPostCommandBufferDispatch();
				}
			}
		}
		else
		{
			// Error!
			RHI_ASSERT(renderer.getContext(), false, "We should never end up in here")
		}
	}

	//[-------------------------------------------------------]
	//[ Private methods                                       ]
	//[-------------------------------------------------------]
	CompositorInstancePassShadowMap::CompositorInstancePassShadowMap(const CompositorResourcePassShadowMap& compositorResourcePassShadowMap, const CompositorNodeInstance& compositorNodeInstance) :
		CompositorInstancePassScene(compositorResourcePassShadowMap, compositorNodeInstance, true),
		// Settings
		mEnabled(true),
		mShadowMapSize(1024),
		mNumberOfShadowCascades(4),
		mNumberOfShadowMultisamples(2),
		mCascadeSplitsLambda(0.99f),
		mShadowFilterSize(8.0f),
		mStabilizeCascades(true),
		// Internal
		mSettingsGenerationCounter(0),
		mUsedSettingsGenerationCounter(0),
		mDepthTextureResourceId(getInvalid<TextureResourceId>()),
		mVarianceTextureResourceId(getInvalid<TextureResourceId>()),
		mIntermediateDepthBlurTextureResourceId(getInvalid<TextureResourceId>()),
		mDepthToExponentialVarianceCompositorResourcePassCompute(nullptr),
		mDepthToExponentialVarianceCompositorInstancePassCompute(nullptr),
		mHorizontalBlurCompositorResourcePassCompute(nullptr),
		mHorizontalBlurCompositorInstancePassCompute(nullptr),
		mVerticalBlurCompositorResourcePassCompute(nullptr),
		mVerticalBlurCompositorInstancePassCompute(nullptr)
	{
		mPassData.shadowMatrix = Math::MAT4_IDENTITY;
		for (int i = 0; i < CompositorResourcePassShadowMap::MAXIMUM_NUMBER_OF_SHADOW_CASCADES; ++i)
		{
			mPassData.shadowCascadeScales[i] = Math::VEC4_ONE;
		}
		createShadowMapRenderTarget();
	}

	void CompositorInstancePassShadowMap::createShadowMapRenderTarget()
	{
		const CompositorResourcePassShadowMap& compositorResourcePassShadowMap = static_cast<const CompositorResourcePassShadowMap&>(getCompositorResourcePass());
		const IRenderer& renderer = getCompositorNodeInstance().getCompositorWorkspaceInstance().getRenderer();
		const AssetId assetId = compositorResourcePassShadowMap.getTextureAssetId();

		// Tell the texture resource manager about our render target texture so it can be referenced inside e.g. compositor nodes
		TextureResourceManager& textureResourceManager = renderer.getTextureResourceManager();
		TextureResource* textureResource = textureResourceManager.getTextureResourceByAssetId(assetId);
		if (nullptr == textureResource)
		{
			Rhi::IRhi& rhi = renderer.getRhi();
			if (mEnabled)
			{
				// Check shadow map settings
				RHI_ASSERT(renderer.getContext(), mNumberOfShadowCascades <= CompositorResourcePassShadowMap::MAXIMUM_NUMBER_OF_SHADOW_CASCADES, "Invalid number of shadow cascades")
				RHI_ASSERT(renderer.getContext(), mNumberOfShadowMultisamples >= 1, "Invalid number of shadow multisamples")
				uint8_t numberOfShadowMultisamples = mNumberOfShadowMultisamples;
				{ // Multisamples sanity check
					const uint8_t maximumNumberOfMultisamples = rhi.getCapabilities().maximumNumberOfMultisamples;
					if (numberOfShadowMultisamples > maximumNumberOfMultisamples)
					{
						RHI_ASSERT(renderer.getContext(), false, "Number of shadow multisamples not supported by the RHI implementation")
						numberOfShadowMultisamples = maximumNumberOfMultisamples;
					}
				}

				{ // Depth shadow map
					const Rhi::TextureFormat::Enum textureFormat = Rhi::TextureFormat::D32_FLOAT;
					Rhi::ITexture* texture = renderer.getTextureManager().createTexture2D(mShadowMapSize, mShadowMapSize, textureFormat, nullptr, Rhi::TextureFlag::SHADER_RESOURCE | Rhi::TextureFlag::RENDER_TARGET, Rhi::TextureUsage::DEFAULT, numberOfShadowMultisamples, nullptr RHI_RESOURCE_DEBUG_NAME("Compositor instance pass depth shadow map"));

					{ // Create the framebuffer object (FBO) instance
						const Rhi::FramebufferAttachment depthStencilFramebufferAttachment(texture);
						mDepthFramebufferPtr = rhi.createFramebuffer(*rhi.createRenderPass(0, nullptr, textureFormat, 1 RHI_RESOURCE_DEBUG_NAME("Compositor instance pass depth shadow map")), nullptr, &depthStencilFramebufferAttachment RHI_RESOURCE_DEBUG_NAME("Compositor instance pass depth shadow map"));
					}

					// Create texture resource
					mDepthTextureResourceId = textureResourceManager.createTextureResourceByAssetId(::detail::DEPTH_SHADOW_MAP_TEXTURE_ASSET_ID, *texture);
				}

				{ // Depth to exponential variance
					MaterialProperties materialProperties;
					materialProperties.setPropertyById(STRING_ID("DepthMap"), MaterialPropertyValue::fromTextureAssetId(::detail::DEPTH_SHADOW_MAP_TEXTURE_ASSET_ID), MaterialProperty::Usage::UNKNOWN, true);
					materialProperties.setPropertyById(STRING_ID("NumberOfMultisamples"), MaterialPropertyValue::fromInteger((numberOfShadowMultisamples == 1) ? 0 : numberOfShadowMultisamples), MaterialProperty::Usage::UNKNOWN, true);
					mDepthToExponentialVarianceCompositorResourcePassCompute = new CompositorResourcePassCompute(compositorResourcePassShadowMap.getCompositorTarget(), compositorResourcePassShadowMap.getDepthToExponentialVarianceMaterialBlueprintAssetId(), materialProperties);
					#if defined(RHI_DEBUG) || defined(RENDERER_PROFILER)
						mDepthToExponentialVarianceCompositorResourcePassCompute->setDebugName("Depth to exponential variance");
					#endif
					mDepthToExponentialVarianceCompositorInstancePassCompute = new CompositorInstancePassCompute(*mDepthToExponentialVarianceCompositorResourcePassCompute, getCompositorNodeInstance());
				}

				{ // Variance shadow map
					const Rhi::TextureFormat::Enum textureFormat = Rhi::TextureFormat::R32G32B32A32F;
					Rhi::ITexture* texture = renderer.getTextureManager().createTexture2DArray(mShadowMapSize, mShadowMapSize, CompositorResourcePassShadowMap::MAXIMUM_NUMBER_OF_SHADOW_CASCADES, textureFormat, nullptr, Rhi::TextureFlag::SHADER_RESOURCE | Rhi::TextureFlag::RENDER_TARGET, Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME("Compositor instance pass variance shadow map"));

					// Create the framebuffer object (FBO) instances
					Rhi::IRenderPass* renderPass = rhi.createRenderPass(1, &textureFormat, Rhi::TextureFormat::UNKNOWN, 1 RHI_RESOURCE_DEBUG_NAME("Compositor instance pass variance shadow map"));
					for (uint8_t cascadeIndex = 0; cascadeIndex < CompositorResourcePassShadowMap::MAXIMUM_NUMBER_OF_SHADOW_CASCADES; ++cascadeIndex)
					{
						const Rhi::FramebufferAttachment colorFramebufferAttachment(texture, 0, cascadeIndex);
						mVarianceFramebufferPtr[cascadeIndex] = rhi.createFramebuffer(*renderPass, &colorFramebufferAttachment, nullptr RHI_RESOURCE_DEBUG_NAME(("Compositor instance pass variance shadow map " + std::to_string(cascadeIndex)).c_str()));
					}
					for (uint8_t cascadeIndex = CompositorResourcePassShadowMap::MAXIMUM_NUMBER_OF_SHADOW_CASCADES; cascadeIndex < CompositorResourcePassShadowMap::MAXIMUM_NUMBER_OF_SHADOW_CASCADES; ++cascadeIndex)
					{
						mVarianceFramebufferPtr[cascadeIndex] = nullptr;
					}

					// Create texture resource
					mVarianceTextureResourceId = textureResourceManager.createTextureResourceByAssetId(assetId, *texture);
				}

				{ // Intermediate depth blur shadow map
					const Rhi::TextureFormat::Enum textureFormat = Rhi::TextureFormat::R32G32B32A32F;
					Rhi::ITexture* texture = renderer.getTextureManager().createTexture2D(mShadowMapSize, mShadowMapSize, textureFormat, nullptr, Rhi::TextureFlag::SHADER_RESOURCE | Rhi::TextureFlag::RENDER_TARGET, Rhi::TextureUsage::DEFAULT, 1, nullptr RHI_RESOURCE_DEBUG_NAME("Compositor instance pass intermediate depth blur shadow map"));

					{ // Create the framebuffer object (FBO) instance
						const Rhi::FramebufferAttachment colorFramebufferAttachment(texture);
						mIntermediateFramebufferPtr = rhi.createFramebuffer(*rhi.createRenderPass(1, &textureFormat, Rhi::TextureFormat::UNKNOWN, 1 RHI_RESOURCE_DEBUG_NAME("Compositor instance pass intermediate depth blur shadow map")), &colorFramebufferAttachment, nullptr RHI_RESOURCE_DEBUG_NAME("Compositor instance pass intermediate depth blur shadow map"));
					}

					// Create texture resource
					mIntermediateDepthBlurTextureResourceId = textureResourceManager.createTextureResourceByAssetId(::detail::INTERMEDIATE_DEPTH_BLUR_SHADOW_MAP_TEXTURE_ASSET_ID, *texture);
				}

				{ // Horizontal blur
					MaterialProperties materialProperties;
					materialProperties.setPropertyById(STRING_ID("VerticalBlur"), MaterialPropertyValue::fromBoolean(false), MaterialProperty::Usage::UNKNOWN, true);
					materialProperties.setPropertyById(STRING_ID("ColorMap"), MaterialPropertyValue::fromTextureAssetId(assetId), MaterialProperty::Usage::UNKNOWN, true);
					mHorizontalBlurCompositorResourcePassCompute = new CompositorResourcePassCompute(compositorResourcePassShadowMap.getCompositorTarget(), compositorResourcePassShadowMap.getBlurMaterialBlueprintAssetId(), materialProperties);
					#if defined(RHI_DEBUG) || defined(RENDERER_PROFILER)
						mHorizontalBlurCompositorResourcePassCompute->setDebugName("Horizontal blur");
					#endif
					mHorizontalBlurCompositorInstancePassCompute = new CompositorInstancePassCompute(*mHorizontalBlurCompositorResourcePassCompute, getCompositorNodeInstance());
				}

				{ // Vertical blur
					MaterialProperties materialProperties;
					materialProperties.setPropertyById(STRING_ID("VerticalBlur"), MaterialPropertyValue::fromBoolean(true), MaterialProperty::Usage::UNKNOWN, true);
					materialProperties.setPropertyById(STRING_ID("ColorMap"), MaterialPropertyValue::fromTextureAssetId(::detail::INTERMEDIATE_DEPTH_BLUR_SHADOW_MAP_TEXTURE_ASSET_ID), MaterialProperty::Usage::UNKNOWN, true);
					mVerticalBlurCompositorResourcePassCompute = new CompositorResourcePassCompute(compositorResourcePassShadowMap.getCompositorTarget(), compositorResourcePassShadowMap.getBlurMaterialBlueprintAssetId(), materialProperties);
					#if defined(RHI_DEBUG) || defined(RENDERER_PROFILER)
						mVerticalBlurCompositorResourcePassCompute->setDebugName("Vertical blur");
					#endif
					mVerticalBlurCompositorInstancePassCompute = new CompositorInstancePassCompute(*mVerticalBlurCompositorResourcePassCompute, getCompositorNodeInstance());
				}
			}
			else
			{
				// If shadow is disabled, we still need to create at least a dummy for the resulting main variance shadow map resource
				const float data[] = { 0.0f, 0.0f, 0.0f, 0.0f };
				mVarianceTextureResourceId = textureResourceManager.createTextureResourceByAssetId(
					assetId,
					*renderer.getTextureManager().createTexture2DArray(1, 1, 1, Rhi::TextureFormat::R32G32B32A32F, data, Rhi::TextureFlag::SHADER_RESOURCE, Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME("Compositor instance pass variance shadow map")));
			}
		}
		else
		{
			// This is not allowed to happen
			RHI_ASSERT(renderer.getContext(), false, "We should never end up in here")
		}
	}

	void CompositorInstancePassShadowMap::destroyShadowMapRenderTarget()
	{
		RHI_ASSERT(getCompositorNodeInstance().getCompositorWorkspaceInstance().getRenderer().getContext(), isValid(mVarianceTextureResourceId), "Invalid compositor instance pass resource")

		// Depth to exponential variance
		delete mDepthToExponentialVarianceCompositorInstancePassCompute;
		mDepthToExponentialVarianceCompositorInstancePassCompute = nullptr;
		delete mDepthToExponentialVarianceCompositorResourcePassCompute;
		mDepthToExponentialVarianceCompositorResourcePassCompute = nullptr;

		// Horizontal blur
		delete mHorizontalBlurCompositorResourcePassCompute;
		mHorizontalBlurCompositorResourcePassCompute = nullptr;
		delete mHorizontalBlurCompositorInstancePassCompute;
		mHorizontalBlurCompositorInstancePassCompute = nullptr;

		// Vertical blur
		delete mVerticalBlurCompositorResourcePassCompute;
		mVerticalBlurCompositorResourcePassCompute = nullptr;
		delete mVerticalBlurCompositorInstancePassCompute;
		mVerticalBlurCompositorInstancePassCompute = nullptr;

		// Release the framebuffers and other RHI resources referenced by the framebuffers
		mDepthFramebufferPtr = nullptr;
		for (uint8_t cascadeIndex = 0; cascadeIndex < CompositorResourcePassShadowMap::MAXIMUM_NUMBER_OF_SHADOW_CASCADES; ++cascadeIndex)
		{
			mVarianceFramebufferPtr[cascadeIndex] = nullptr;
		}
		mIntermediateFramebufferPtr = nullptr;

		// Inform the texture resource manager that our render target texture is gone now
		TextureResourceManager& textureResourceManager = getCompositorNodeInstance().getCompositorWorkspaceInstance().getRenderer().getTextureResourceManager();
		if (isValid(mDepthTextureResourceId))
		{
			textureResourceManager.destroyTextureResource(mDepthTextureResourceId);
			setInvalid(mDepthTextureResourceId);
		}
		textureResourceManager.destroyTextureResource(mVarianceTextureResourceId);
		setInvalid(mVarianceTextureResourceId);
		if (isValid(mIntermediateDepthBlurTextureResourceId))
		{
			textureResourceManager.destroyTextureResource(mIntermediateDepthBlurTextureResourceId);
			setInvalid(mIntermediateDepthBlurTextureResourceId);
		}
	}

//[-------------------------------------------------------]
//[ Namespace                                             ]
//[-------------------------------------------------------]
} // Renderer


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>NHArrowView Reference</title>

	<link rel="stylesheet" href="css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1333)">

				NHArrowView

				Centre for Global eHealth Innovation

Hierarchy

NHArrowView Reference

Class References

NHArrowView

Category References

UIBezierPath(Arrow)

Copyright © 2015 Centre for Global eHealth Innovation. All rights reserved. Updated: 2015-02-13

Generated by appledoc 2.2.1 (build 1333).


text:
<?php

/**
 *  @Service("esearch", {
 *      server:  {"required": true},
 *      name:  {"required": true},
 *  }, {shared: true})
 */
function esearch($config)
{
    $elastica = new \Elastica\Client($config['server']);
    return $elastica->getIndex($config['name']);
}


text:
REPO            ?= riak_explorer
PKG_VERSION	    ?= $(shell git describe --tags --abbrev=0 | tr - .)
OS_FAMILY          ?= ubuntu
OS_VERSION       ?= 14.04
PKGNAME         ?= $(REPO)-$(PKG_VERSION)-$(OS_FAMILY)-$(OS_VERSION).tar.gz
OAUTH_TOKEN     ?= $(shell cat oauth.txt)
GIT_TAG         ?= $(shell git describe --tags --abbrev=0)
RELEASE_ID      ?= $(shell curl -sS https://api.github.com/repos/basho-labs/$(REPO)/releases/tags/$(GIT_TAG)?access_token=$(OAUTH_TOKEN) | python -c 'import sys, json; print(json.load(sys.stdin)["id"])')
DEPLOY_BASE     ?= "https://uploads.github.com/repos/basho-labs/$(REPO)/releases/$(RELEASE_ID)/assets?access_token=$(OAUTH_TOKEN)&name=$(PKGNAME)"
DOWNLOAD_BASE   ?= https://github.com/basho-labs/$(REPO)/releases/download/$(GIT_TAG)/$(PKGNAME)

BASE_DIR         = $(shell pwd)
ERLANG_BIN       = $(shell dirname $(shell which erl))
REBAR           ?= $(BASE_DIR)/rebar
OVERLAY_VARS    ?=

ifneq (,$(shell whereis sha256sum | awk '{print $2}';))
SHASUM = sha256sum
else
SHASUM = shasum -a 256
endif

.PHONY: deps

all: compile

compile: deps
	$(REBAR) compile
recompile:
	$(REBAR) compile skip_deps=true
deps:
	$(REBAR) get-deps
clean: cleantest relclean clean-sandbox
	-rm -rf packages
clean-sandbox:
	-rm -rf rel/sandbox
cleantest:
	rm -rf .eunit/*
test: cleantest
	$(REBAR)  skip_deps=true eunit
itest: recompile cleantest
	INTEGRATION_TEST=true $(REBAR) skip_deps=true eunit
reitest: cleantest
	INTEGRATION_TEST=true $(REBAR) skip_deps=true eunit
relclean:
	-rm -rf rel/riak_explorer
	-rm -rf rel/root
rel: relclean deps compile
	$(REBAR) compile
	$(REBAR) skip_deps=true generate $(OVERLAY_VARS)
stage: rel
	$(foreach dep,$(wildcard deps/*), rm -rf rel/riak_explorer/lib/$(shell basename $(dep))-* && ln -sf $(abspath $(dep)) rel/riak_explorer/lib;)
	$(foreach app,$(wildcard apps/*), rm -rf rel/riak_explorer/lib/$(shell basename $(app))-* && ln -sf $(abspath $(app)) rel/riak_explorer/lib;)
	rm -rf rel/riak_explorer/priv/ember_riak_explorer/dist && ln -sf $(abspath priv/ember_riak_explorer/dist) rel/riak_explorer/priv/ember_riak_explorer

riak-addon:
	-rm -rf rel/riak-addon
	mkdir -p rel/riak-addon/ebin
	mkdir -p rel/riak-addon/priv
	$(REBAR) compile
	cp -R deps/riakc/ebin/* rel/riak-addon/ebin/
	cp -R deps/riak_pb/ebin/* rel/riak-addon/riak/lib/basho-patches/
	cp -R deps/protobuffs/ebin/* rel/riak-addon/riak/lib/basho-patches/
	cp -R ebin/* rel/riak-addon/ebin/
	cp -R priv/* rel/riak-addon/priv/

##
## Packaging targets
##
tarball-standalone: rel
	echo "Creating packages/"$(PKGNAME)
	mkdir -p packages
	tar -C rel -czf $(PKGNAME) $(REPO)/
	mv $(PKGNAME) packages/
	cd packages && $(SHASUM) $(PKGNAME) > $(PKGNAME).sha
	cd packages && echo "$(DOWNLOAD_BASE)" > remote.txt
	cd packages && echo "$(BASE_DIR)/packages/$(PKGNAME)" > local.txt
sync-standalone:
	echo "Uploading to "$(DOWNLOAD_BASE)
	@cd packages && \
		curl -XPOST -sS -H 'Content-Type: application/gzip' $(DEPLOY_BASE) --data-binary @$(PKGNAME) && \
		curl -XPOST -sS -H 'Content-Type: application/octet-stream' $(DEPLOY_BASE).sha --data-binary @$(PKGNAME).sha

ASSET_ID        ?= $(shell curl -sS https://api.github.com/repos/basho-labs/$(REPO)/releases/$(RELEASE_ID)/assets?access_token=$(OAUTH_TOKEN) | python -c 'import sys, json; print("".join([str(asset["id"]) if asset["name"] == "$(PKGNAME)" else "" for asset in json.load(sys.stdin)]))')
ASSET_SHA_ID    ?= $(shell curl -sS https://api.github.com/repos/basho-labs/$(REPO)/releases/$(RELEASE_ID)/assets?access_token=$(OAUTH_TOKEN) | python -c 'import sys, json; print("".join([str(asset["id"]) if asset["name"] == "$(PKGNAME).sha" else "" for asset in json.load(sys.stdin)]))')
DELETE_DEPLOY_BASE     ?= "https://api.github.com/repos/basho-labs/$(REPO)/releases/assets/$(ASSET_ID)?access_token=$(OAUTH_TOKEN)"
DELETE_SHA_DEPLOY_BASE ?= "https://api.github.com/repos/basho-labs/$(REPO)/releases/assets/$(ASSET_SHA_ID)?access_token=$(OAUTH_TOKEN)"

sync-delete-standalone:
	echo "Deleting "$(DOWNLOAD_BASE)
	- $(shell curl -XDELETE -sS $(DELETE_DEPLOY_BASE))
	- $(shell curl -XDELETE -sS $(DELETE_SHA_DEPLOY_BASE))

RIAK_BASE             ?= root
PATCH_PKG_VERSION     ?= $(PKG_VERSION).patch
PATCH_PKGNAME         ?= $(REPO)-$(PATCH_PKG_VERSION)-$(OS_FAMILY)-$(OS_VERSION).tar.gz
PATCH_DEPLOY_BASE     ?= "https://uploads.github.com/repos/basho-labs/$(REPO)/releases/$(RELEASE_ID)/assets?access_token=$(OAUTH_TOKEN)&name=$(PATCH_PKGNAME)"
PATCH_DOWNLOAD_BASE   ?= https://github.com/basho-labs/$(REPO)/releases/download/$(GIT_TAG)/$(PATCH_PKGNAME)

reltarball: RIAK_BASE = .
reltarball: PATCH_PKG_VERSION = $(PKG_VERSION).relpatch
reltarball: compile clean-sandbox
reltarball:
	$(call build-tarball)

relsync: RIAK_BASE = .
relsync: PATCH_PKG_VERSION = $(PKG_VERSION).relpatch
relsync:
	$(call do-sync)

tarball: compile clean-sandbox
tarball:
	$(call build-tarball)

sync:
	$(call do-sync)

define build-tarball
	echo "Creating packages/"$(PATCH_PKGNAME)
	-rm -rf rel/sandbox/$(RIAK_BASE)
	mkdir -p rel/sandbox/$(RIAK_BASE)/riak/lib/basho-patches
	mkdir -p rel/sandbox/$(RIAK_BASE)/riak/priv
	cp -R deps/riakc/ebin/* rel/sandbox/$(RIAK_BASE)/riak/lib/basho-patches/
	cp -R deps/riak_pb/ebin/* rel/sandbox/$(RIAK_BASE)/riak/lib/basho-patches/
	cp -R deps/protobuffs/ebin/* rel/sandbox/$(RIAK_BASE)/riak/lib/basho-patches/
	cp -R ebin/* rel/sandbox/$(RIAK_BASE)/riak/lib/basho-patches/
	cp -R priv/* rel/sandbox/$(RIAK_BASE)/riak/priv/
	mkdir -p packages
	tar -C rel/sandbox -czf $(PATCH_PKGNAME) $(RIAK_BASE)
	mv $(PATCH_PKGNAME) packages/
	cd packages && $(SHASUM) $(PATCH_PKGNAME) > $(PATCH_PKGNAME).sha
	cd packages && echo "$(PATCH_DOWNLOAD_BASE)" > remote.txt
	cd packages && echo "$(BASE_DIR)/packages/$(PATCH_PKGNAME)" > local.txt
endef

define do-sync
	echo "Uploading to "$(PATCH_DOWNLOAD_BASE)
	@cd packages && \
		curl -XPOST -sS -H 'Content-Type: application/gzip' $(PATCH_DEPLOY_BASE) --data-binary @$(PATCH_PKGNAME) && \
		curl -XPOST -sS -H 'Content-Type: application/octet-stream' $(PATCH_DEPLOY_BASE).sha --data-binary @$(PATCH_PKGNAME).sha
endef

PATCH_ASSET_ID        ?= $(shell curl -sS https://api.github.com/repos/basho-labs/$(REPO)/releases/$(RELEASE_ID)/assets?access_token=$(OAUTH_TOKEN) | python -c 'import sys, json; print "".join([str(asset["id"]) if asset["name"] == "$(PATCH_PKGNAME)" else "" for asset in json.load(sys.stdin)])')
PATCH_ASSET_SHA_ID    ?= $(shell curl -sS https://api.github.com/repos/basho-labs/$(REPO)/releases/$(RELEASE_ID)/assets?access_token=$(OAUTH_TOKEN) | python -c 'import sys, json; print "".join([str(asset["id"]) if asset["name"] == "$(PATCH_PKGNAME).sha" else "" for asset in json.load(sys.stdin)])')
PATCH_DELETE_DEPLOY_BASE     ?= "https://api.github.com/repos/basho-labs/$(REPO)/releases/assets/$(PATCH_ASSET_ID)?access_token=$(OAUTH_TOKEN)"
PATCH_DELETE_SHA_DEPLOY_BASE ?= "https://api.github.com/repos/basho-labs/$(REPO)/releases/assets/$(PATCH_ASSET_SHA_ID)?access_token=$(OAUTH_TOKEN)"

sync-delete:
	echo "Deleting "$(PATCH_DOWNLOAD_BASE)
	- $(shell curl -XDELETE -sS $(PATCH_DELETE_DEPLOY_BASE))
	- $(shell curl -XDELETE -sS $(PATCH_DELETE_SHA_DEPLOY_BASE))


text:
layout: post
title: The final recruitment list for 1st year (2013)
excerpt: The list of people selected after the rigourous interviews.
---

Congratulations to everyone who got in. We were overwhelmed by the amount of talent and aptitude these people brought on board. If we did not select you, it was because we had limited vacancies, not because we didn't like you. Each of the rest was as equally likely and capable be to be selected. And each time we took someone's name off the list, we were stricken with guilt.

## Programmers

* Abhinav Tushar (12115005)
* Abhishek Kandoi (12114003)
* Ankita Shukla (12114012)
* Deepali Jain (12115034)
* Divij Bindlish (12115037)
* Gautam Arakalgud (12115042)
* Mohite Kishor (12114041)
* Kshitij Bathla (12114036)
* Prakhar Singh (12213014)
* Satyam Vijay (12114061)
* Shubham Gupta (12114062)
* Shubham Roy (12119053)

## Designers

* Kushal Saharan (12116029)
* Rishabh Yadav (12115090)
* Viplov Kumar (12114073)

---
Team SDSLabs


text:
Get all environments for a given project.

```
GET /projects/:id/environments
```

| Attribute | Type    | Required | Description           |
| --------- | ------- | -------- | --------------------- |
| `id`      | integer/string | yes      | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `name`    | string  | no       | Return the environment with this name. Mutually exclusive with `search` |
| `search`  | string  | no       | Return list of environments matching the search criteria. Mutually exclusive with `name` |

```bash
curl --header "PRIVATE-TOKEN: <your_access_token>" https://gitlab.example.com/api/v4/projects/1/environments?name=review%2Ffix-foo
```

Example response:

```json
[
  {
    "id": 1,
    "name": "review/fix-foo",
    "slug": "review-fix-foo-dfjre3",
    "external_url": "https://review-fix-foo-dfjre3.example.gitlab.com",
    "state": "available"
  }
]
```

## Get a specific environment

```
GET /projects/:id/environments/:environment_id
```

| Attribute | Type    | Required | Description         |
|-----------|---------|----------|---------------------|
| `id`      | integer/string | yes      | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `environment_id` | integer | yes | The ID of the environment |

```bash
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/1/environments/1"
```

Example of response

```json
{
  "id": 1,
  "name": "review/fix-foo",
  "slug": "review-fix-foo-dfjre3",
  "external_url": "https://review-fix-foo-dfjre3.example.gitlab.com"
  "state": "available",
  "last_deployment": {
    "id": 100,
    "iid": 34,
    "ref": "fdroid",
    "sha": "416d8ea11849050d3d1f5104cf8cf51053e790ab",
    "created_at": "2019-03-25T18:55:13.252Z",
    "status": "success",
    "user": {
      "id": 1,
      "name": "Administrator",
      "state": "active",
      "username": "root",
      "avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
      "web_url": "http://localhost:3000/root"
    }
    "deployable": {
      "id": 710,
      "status": "success",
      "stage": "deploy",
      "name": "staging",
      "ref": "fdroid",
      "tag": false,
      "coverage": null,
      "created_at": "2019-03-25T18:55:13.215Z",
      "started_at": "2019-03-25T12:54:50.082Z",
      "finished_at": "2019-03-25T18:55:13.216Z",
      "duration": 21623.13423,
      "user": {
        "id": 1,
        "name": "Administrator",
        "username": "root",
        "state": "active",
        "avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
        "web_url": "http://gitlab.dev/root",
        "created_at": "2015-12-21T13:14:24.077Z",
        "bio": null,
        "location": null,
        "public_email": "",
        "skype": "",
        "linkedin": "",
        "twitter": "",
        "website_url": "",
        "organization": null
      }
      "commit": {
        "id": "416d8ea11849050d3d1f5104cf8cf51053e790ab",
        "short_id": "416d8ea1",
        "created_at": "2016-01-02T15:39:18.000Z",
        "parent_ids": [
          "e9a4449c95c64358840902508fc827f1a2eab7df"
        ],
        "title": "Removed fabric to fix #40",
        "message": "Removed fabric to fix #40\n",
        "author_name": "Administrator",
        "author_email": "admin@example.com",
        "authored_date": "2016-01-02T15:39:18.000Z",
        "committer_name": "Administrator",
        "committer_email": "admin@example.com",
        "committed_date": "2016-01-02T15:39:18.000Z"
      },
      "pipeline": {
        "id": 34,
        "sha": "416d8ea11849050d3d1f5104cf8cf51053e790ab",
        "ref": "fdroid",
        "status": "success",
        "web_url": "http://localhost:3000/Commit451/lab-coat/pipelines/34"
      },
      "web_url": "http://localhost:3000/Commit451/lab-coat/-/jobs/710",
      "artifacts": [
        {
          "file_type": "trace",
          "size": 1305,
          "filename": "job.log",
          "file_format": null
        }
      ],
      "runner": null,
      "artifacts_expire_at": null
    }
  }
}
```

## Create a new environment

Creates a new environment with the given name and external_url.

It returns `201` if the environment was successfully created, `400` for wrong parameters.

```
POST /projects/:id/environments
```

| Attribute     | Type    | Required | Description                  |
| ------------- | ------- | -------- | ---------------------------- |
| `id`          | integer/string | yes      | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user        |
| `name`        | string  | yes      | The name of the environment  |
| `external_url` | string  | no     | Place to link to for this environment |

```bash
curl --data "name=deploy&external_url=https://deploy.example.gitlab.com" --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/1/environments"
```

Example response:

```json
{
  "id": 1,
  "name": "deploy",
  "slug": "deploy",
  "external_url": "https://deploy.example.gitlab.com",
  "state": "available"
}
```

## Edit an existing environment

Updates an existing environment's name and/or external_url.

It returns `200` if the environment was successfully updated. In case of an error, a status code `400` is returned.

```
PUT /projects/:id/environments/:environments_id
```

| Attribute       | Type    | Required                          | Description                      |
| --------------- | ------- | --------------------------------- | -------------------------------  |
| `id`            | integer/string | yes                               | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user            |
| `environment_id` | integer | yes | The ID of the environment  |
| `name`          | string  | no                                | The new name of the environment  |
| `external_url`  | string  | no                                | The new external_url             |

```bash
curl --request PUT --data "name=staging&external_url=https://staging.example.gitlab.com" --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/1/environments/1"
```

Example response:

```json
{
  "id": 1,
  "name": "staging",
  "slug": "staging",
  "external_url": "https://staging.example.gitlab.com",
  "state": "available"
}
```

## Delete an environment

It returns `204` if the environment was successfully deleted, and `404` if the environment does not exist.

```
DELETE /projects/:id/environments/:environment_id
```

| Attribute | Type    | Required | Description           |
| --------- | ------- | -------- | --------------------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `environment_id` | integer | yes | The ID of the environment |

```bash
curl --request DELETE --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/1/environments/1"
```

## Stop an environment

It returns `200` if the environment was successfully stopped, and `404` if the environment does not exist.

```
POST /projects/:id/environments/:environment_id/stop
```

| Attribute | Type    | Required | Description           |
| --------- | ------- | -------- | --------------------- |
| `id` | integer/string | yes | The ID or [URL-encoded path of the project](README.md#namespaced-path-encoding) owned by the authenticated user |
| `environment_id` | integer | yes | The ID of the environment |

```bash
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/1/environments/1/stop"
```

Example response:

```json
{
  "id": 1,
  "name": "deploy",
  "slug": "deploy",
  "external_url": "https://deploy.example.gitlab.com",
  "state": "stopped"
}
```


text:
package com.kwanzoo.recurly.test;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import junit.framework.TestCase;

import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;

import com.kwanzoo.recurly.Account;
import com.kwanzoo.recurly.Base;
import com.kwanzoo.recurly.BillingInfo;
import com.kwanzoo.recurly.Charge;
import com.kwanzoo.recurly.CreditCard;
import com.kwanzoo.recurly.InvoiceDetailed;
import com.kwanzoo.recurly.Invoices;
import com.kwanzoo.recurly.Subscription;
import com.kwanzoo.recurly.TransparentResult;

public class RecurlyTest extends TestCase {

	private String[] plans = {};
	private String existingTransparentPostResult = "";
	private int currentYear = 0;

	private String getRandomAlphaNumString(final int n) {
		return RandomStringUtils.randomAlphanumeric(n);
	}

	private String getRandomNumString(final int n) {
		return RandomStringUtils.randomNumeric(n);
	}

	@Override
	public void setUp() {
		Properties props = new Properties();
		try {
			String propsFilePath = System.getProperty("user.home") + "/" + "recurly_auth";
			System.out.println("Reading properties from " + propsFilePath);
			props.load(new FileInputStream(propsFilePath));

			String username = props.getProperty("recurly_username");
			String password = props.getProperty("recurly_password");
			System.out.println("Using recurly credentials : " + username + "/" + password);

			String plansStr = props.getProperty("plans");
			plans = plansStr.split(",");
			for(int i=0;i<plans.length;i++){
				plans[i] = plans[i].trim();
			}
			System.out.println("Using plans : " + Arrays.toString(plans));

			currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));

			Base.setAuth(username, password);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void test0() throws Exception {
		if (!"".equals(existingTransparentPostResult)) {
			Subscription result = TransparentResult.get(existingTransparentPostResult);
			assertEquals("pending", result.state);
		} else {
			fail("create a transparent post demo and setup the transparent post result");
		}
	}

	// Manipulate Accounts
	@Test
	public void test1() throws Exception {

		// create fresh account
		final String accountCode = getRandomAlphaNumString(5);
		String username = getRandomAlphaNumString(5);
		String firstName = getRandomAlphaNumString(5);
		String lastName = getRandomAlphaNumString(5);
		String email = getRandomAlphaNumString(5) + "@site.com";
		String companyName = getRandomAlphaNumString(5);

		Account account = new Account();

		account.accountCode = accountCode;
		account.username = username;
		account.firstName = firstName;
		account.lastName = lastName;
		account.email = email;
		account.companyName = companyName;

		account.create();

		// check if find works
		account = Account.get(accountCode);

		assertEquals(accountCode, account.accountCode);
		assertEquals(username, account.username);
		assertEquals(firstName, account.firstName);
		assertEquals(lastName, account.lastName);
		assertEquals(email, account.email);
		assertEquals(companyName, account.companyName);

		// check if update works
		username = getRandomAlphaNumString(5);
		firstName = getRandomAlphaNumString(5);
		lastName = getRandomAlphaNumString(5);
		email = getRandomAlphaNumString(5) + "@site.com";
		companyName = getRandomAlphaNumString(5);

		account.username = username;
		account.firstName = firstName;
		account.lastName = lastName;
		account.email = email;
		account.companyName = companyName;

		account.update();

		account = Account.get(accountCode);

		assertEquals(accountCode, account.accountCode);
		assertEquals(username, account.username);
		assertEquals(firstName, account.firstName);
		assertEquals(lastName, account.lastName);
		assertEquals(email, account.email);
		assertEquals(companyName, account.companyName);

		Charge charge = new Charge(accountCode);
		charge.amount_in_cents = 500;
		charge.description = "first charge";
		charge.create();

		// cleanup
		account.delete();
	}

	// Manipulate billing info
	@Test
	public void test2() throws Exception {

		// create fresh account
		final String accountCode = getRandomAlphaNumString(5);
		final String username = getRandomAlphaNumString(5);
		String firstName = getRandomAlphaNumString(5);
		String lastName = getRandomAlphaNumString(5);
		final String email = getRandomAlphaNumString(5) + "@site.com";
		final String companyName = getRandomAlphaNumString(5);

		Account account = new Account();

		account.accountCode = accountCode;
		account.username = username;
		account.firstName = firstName;
		account.lastName = lastName;
		account.email = email;
		account.companyName = companyName;

		account.create();

		account = Account.get(accountCode);

		// check if adding billing info for a fresh account works
		final String number = "1"; // bogus credit card number accepted by test gateway
		String verificationValue = getRandomNumString(4);
		Integer expirationMonth = (new Random()).nextInt(12) + 1;
		Integer expirationYear = currentYear + (new Random()).nextInt(20);

		firstName = account.firstName;
		lastName = account.lastName;
		String address1 = getRandomAlphaNumString(10);
		String address2 = getRandomAlphaNumString(10);
		String city = "San Fransisco";
		String state = "CA";
		String zip = "20240";
		String country = "US";
		String ipAddress = "127.0.0.1";

		CreditCard creditCard = new CreditCard();

		creditCard.number = number;
		creditCard.verificationValue = verificationValue;
		creditCard.expirationMonth = expirationMonth;
		creditCard.expirationYear = expirationYear;

		BillingInfo billingInfo = new BillingInfo(accountCode);
		billingInfo.firstName = firstName;
		billingInfo.lastName = lastName;
		billingInfo.address1 = address1;
		billingInfo.address2 = address2;
		billingInfo.city = city;
		billingInfo.state = state;
		billingInfo.zip = zip;
		billingInfo.country = country;
		billingInfo.ipAddress = ipAddress;
		billingInfo.creditCard = creditCard;

		billingInfo.update();

		billingInfo = BillingInfo.get(accountCode);

		assertEquals(firstName, billingInfo.firstName);
		assertEquals(lastName, billingInfo.lastName);
		assertEquals(address1, billingInfo.address1);
		assertEquals(address2, billingInfo.address2);
		assertEquals(city, billingInfo.city);
		assertEquals(state, billingInfo.state);
		assertEquals(zip, billingInfo.zip);
		assertEquals(country, billingInfo.country);
		assertEquals(ipAddress, billingInfo.ipAddress);

		// Recurly returns empty for both the fields below
		// assertEquals(billingInfo.creditCard.number);
		// assertEquals(billingInfo.creditCard.verificationValue);

		assertEquals(expirationMonth, billingInfo.creditCard.expirationMonth);
		assertEquals(expirationYear, billingInfo.creditCard.expirationYear);

		// check if updating billing info of an account that already has billing info works
		verificationValue = getRandomNumString(4);
		expirationMonth = (new Random()).nextInt(12) + 1;

		expirationYear = currentYear + (new Random()).nextInt(20);

		firstName = account.firstName;
		lastName = account.lastName;
		address1 = getRandomAlphaNumString(10);
		address2 = getRandomAlphaNumString(10);
		city = "Some City";
		state = "NJ";
		zip = "94105";
		country = "IN";
		ipAddress = "127.0.0.1";

		creditCard = new CreditCard();
		creditCard.number = number;
		creditCard.verificationValue = verificationValue;
		creditCard.expirationMonth = expirationMonth;
		creditCard.expirationYear = expirationYear;

		billingInfo = new BillingInfo(accountCode);
		billingInfo.firstName = firstName;
		billingInfo.lastName = lastName;
		billingInfo.address1 = address1;
		billingInfo.address2 = address2;
		billingInfo.city = city;
		billingInfo.state = state;
		billingInfo.zip = zip;
		billingInfo.country = country;
		billingInfo.ipAddress = ipAddress;
		billingInfo.creditCard = creditCard;

		billingInfo.checkedUpdate();

		billingInfo = BillingInfo.get(accountCode);

		assertEquals(firstName, billingInfo.firstName);
		assertEquals(lastName, billingInfo.lastName);
		assertEquals(address1, billingInfo.address1);
		assertEquals(address2, billingInfo.address2);
		assertEquals(city, billingInfo.city);
		assertEquals(state, billingInfo.state);
		assertEquals(zip, billingInfo.zip);
		assertEquals(country, billingInfo.country);
		assertEquals(ipAddress, billingInfo.ipAddress);

		// cleanup
		account.delete();

	}

	// Manipulate subscriptions
	@Test
	public void test3() throws Exception {
		// create fresh account
		final String accountCode = getRandomAlphaNumString(5);
		final String username = getRandomAlphaNumString(5);
		String firstName = getRandomAlphaNumString(5);
		String lastName = getRandomAlphaNumString(5);
		final String email = getRandomAlphaNumString(5) + "@site.com";
		final String companyName = getRandomAlphaNumString(5);

		Account account = new Account();

		account.accountCode = accountCode;
		account.username = username;
		account.firstName = firstName;
		account.lastName = lastName;
		account.email = email;
		account.companyName = companyName;

		account.create();

		account = Account.get(accountCode);

		// subscribe to plan1
		final String number = "1";
		final String verificationValue = getRandomNumString(4);
		final Integer expirationMonth = (new Random()).nextInt(12);
		final Integer expirationYear = 2011 + (new Random()).nextInt(20);

		firstName = account.firstName;
		lastName = account.lastName;

		final String address1 = getRandomAlphaNumString(10);
		final String address2 = getRandomAlphaNumString(10);
		final String city = "San Fransisco";
		final String state = "NM";
		final String zip = "99546";
		final String country = "US";
		final String ipAddress = "127.0.0.1";

		final CreditCard creditCard = new CreditCard();
		creditCard.number = number;
		creditCard.verificationValue = verificationValue;
		creditCard.expirationMonth = expirationMonth;
		creditCard.expirationYear = expirationYear;

		BillingInfo billingInfo = new BillingInfo(accountCode);
		billingInfo.firstName = firstName;
		billingInfo.lastName = lastName;
		billingInfo.address1 = address1;
		billingInfo.address2 = address2;
		billingInfo.city = city;
		billingInfo.state = state;
		billingInfo.zip = zip;
		billingInfo.country = country;
		billingInfo.ipAddress = ipAddress;
		billingInfo.creditCard = creditCard;

		account.billingInfo = billingInfo;

		String planCode = plans[1]; // one of the plans defined in your recurly account
		Integer quantity = 1;

		Subscription subscription = new Subscription(accountCode);
		subscription.account = account;
		subscription.planCode = planCode;
		subscription.quantity = quantity;

		subscription.create();

		// TODO: get subscription and check with asserts
		subscription = Subscription.get(accountCode);

		assertEquals(accountCode, subscription.accountCode);
		assertEquals(planCode, subscription.plan.planCode);
		assertEquals("active", subscription.state);
		assertEquals(quantity, subscription.quantity);

		billingInfo = BillingInfo.get(accountCode);
		assertEquals(firstName, billingInfo.firstName);
		assertEquals(lastName, billingInfo.lastName);
		assertEquals(address1, billingInfo.address1);
		assertEquals(address2, billingInfo.address2);
		assertEquals(city, billingInfo.city);
		assertEquals(state, billingInfo.state);
		assertEquals(zip, billingInfo.zip);
		assertEquals(country, billingInfo.country);
		assertEquals(ipAddress, billingInfo.ipAddress);

		// Recurly returns a null for both the fields below.
		// assertEquals(billingInfo.creditCard.number);
		// assertEquals(billingInfo.creditCard.verificationValue);

		assertEquals(expirationMonth, billingInfo.creditCard.expirationMonth);
		assertEquals(expirationYear, billingInfo.creditCard.expirationYear);

		// invoice check
		Invoices invoices = Invoices.get(accountCode);
		assertEquals(1, invoices.invoice.size());

		// downgrade check

		planCode = plans[0]; // a plan with lesser features/rate than testplan1
		quantity = 2;

		subscription = new Subscription(accountCode);
		subscription.timeframe = "now";
		subscription.planCode = planCode;
		subscription.quantity = quantity;

		subscription.update();

		subscription = Subscription.get(accountCode);

		assertEquals(accountCode, subscription.accountCode);
		assertEquals(planCode, subscription.plan.planCode);
		assertEquals("active", subscription.state);
		assertEquals(quantity, subscription.quantity);

		// invoice check
		invoices = Invoices.get(accountCode);
		assertEquals(2, invoices.invoice.size());

		// upgrade check

		planCode = plans[2]; // a plan with better features/rate than testplan1
		quantity = 3;

		subscription = new Subscription(accountCode);
		subscription.timeframe = "now"; // immediate upgrade
		subscription.planCode = planCode;
		subscription.quantity = quantity;

		subscription.update();

		subscription = Subscription.get(accountCode);

		assertEquals(accountCode, subscription.accountCode);
		assertEquals(planCode, subscription.plan.planCode);
		assertEquals("active", subscription.state);
		assertEquals(quantity, subscription.quantity);

		// invoice check
		invoices = Invoices.get(accountCode);
		assertEquals(3, invoices.invoice.size());

		// detailed invoice check
		InvoiceDetailed invoiceDetailed = InvoiceDetailed.get(invoices.invoice.get(2).id);
		assertEquals(invoices.invoice.get(2).id, invoiceDetailed.id);
		assertEquals(1, invoiceDetailed.payment.size());
		assertEquals(1, invoiceDetailed.line_item.size());

		// cancel & check with asserts

		subscription = new Subscription(accountCode);
		subscription.delete();

		subscription = Subscription.get(accountCode);
		assertEquals("canceled", subscription.state);

		account.delete();
	}

}


text:
//
//  FoodModel.h
//  YsLinkTableView
//
//  Created by weiying on 16/2/14.
//  Copyright © 2016年 Yuns. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NSObject+Model.h"

@class FoodItemModel;

@interface FoodModel : NSObject <ModelDelegate>
/**分组标题*/
@property (nonatomic, copy) NSString *title;
/**分组中的 食品*/
@property (nonatomic, strong) NSArray<FoodItemModel *> *foodSubs;

@end

@interface FoodItemModel : NSObject
/**菜品id*/
@property (nonatomic, assign) NSInteger foodId;
/**菜品名称*/
@property (nonatomic, copy) NSString *foodName;
/**菜品图片*/
@property (nonatomic, copy) NSString *foodImage;
/**菜品单价*/
@property (nonatomic, assign) double foodPrice;
/**售卖状态 1代表售卖中 0 代表 售卖完*/
@property (nonatomic, assign) NSInteger saleStatus;

/**添加一个字段用来统计单个菜品的选择数量*/
//@property (nonatomic, assign) NSInteger foodCount;

@end


text:
package ve.com.abicelis.chefbuddy.database.exceptions;

/**
 * Created by abicelis on 7/7/2017.
 */

public class CouldNotInsertDataException extends Exception {

    private static final String DEFAULT_MESSAGE = "Could not insert data into the database.";

    public CouldNotInsertDataException() {
        super(DEFAULT_MESSAGE);
    }
    public CouldNotInsertDataException(String message) {
        super(message);
    }
    public CouldNotInsertDataException(String message, Throwable cause) {
        super(message, cause);
    }

}