text:
<?php

namespace PHPExiftool\Driver\Tag\Minolta;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class ColorCompensationFilter extends AbstractTag
{

    protected $Id = 'mixed';

    protected $Name = 'ColorCompensationFilter';

    protected $FullName = 'mixed';

    protected $GroupName = 'Minolta';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'Minolta';

    protected $g2 = 'Camera';

    protected $Type = 'mixed';

    protected $Writable = true;

    protected $Description = 'Color Compensation Filter';

    protected $flag_Permanent = true;

}


text:
from django.db import models

class CaseInsensitiveCharField(models.CharField):
    def db_type(self, connection):
        return "varchar(%d) collate nocase" % self.max_length

redpajama_set_name: RedPajamaGithub


text:
.. _config_network_filters_sni_dynamic_forward_proxy:

SNI dynamic forward proxy
=========================

.. attention::

  SNI dynamic forward proxy support should be considered alpha and not production ready.

Through the combination of :ref:`TLS inspector <config_listener_filters_tls_inspector>` listener filter,
this network filter and the
:ref:`dynamic forward proxy cluster <envoy_api_msg_config.cluster.dynamic_forward_proxy.v2alpha.ClusterConfig>`,
Envoy supports SNI based dynamic forward proxy. The implementation works just like the
:ref:`HTTP dynamic forward proxy <arch_overview_http_dynamic_forward_proxy>`, but using the value in
SNI as target host instead.

The following is a complete configuration that configures both this filter
as well as the :ref:`dynamic forward proxy cluster
<envoy_api_msg_config.cluster.dynamic_forward_proxy.v2alpha.ClusterConfig>`. Both filter and cluster
must be configured together and point to the same DNS cache parameters for Envoy to operate as an
SNI dynamic forward proxy.

.. note::

  The following config doesn't terminate TLS in listener, so there is no need to configure TLS context
  in cluster. The TLS handshake is passed through by Envoy.

.. code-block:: yaml

  admin:
    access_log_path: /tmp/admin_access.log
    address:
      socket_address:
        protocol: TCP
        address: 127.0.0.1
        port_value: 9901
  static_resources:
    listeners:
    - name: listener_0
      address:
        socket_address:
          protocol: TCP
          address: 0.0.0.0
          port_value: 10000
      listener_filters:
        - name: envoy.filters.listener.tls_inspector
      filter_chains:
        - filters:
            - name: envoy.filters.network.sni_dynamic_forward_proxy
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.filters.network.sni_dynamic_forward_proxy.v3alpha.FilterConfig
                port_value: 443
                dns_cache_config:
                  name: dynamic_forward_proxy_cache_config
                  dns_lookup_family: V4_ONLY
            - name: envoy.tcp_proxy
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy
                stat_prefix: tcp
                cluster: dynamic_forward_proxy_cluster
    clusters:
    - name: dynamic_forward_proxy_cluster
      connect_timeout: 1s
      lb_policy: CLUSTER_PROVIDED
      cluster_type:
        name: envoy.clusters.dynamic_forward_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig
          dns_cache_config:
            name: dynamic_forward_proxy_cache_config
            dns_lookup_family: V4_ONLY


text:
const fs = require('fs');
const path = require('path');
const MFS = require('memory-fs');
const { EventEmitter } = require('async-events-listener');
const webpackDevMiddleWare = require('webpack-dev-middleware');
const webpack = require('webpack');
const ctk = require('koa-connect');
const hotMiddleWare = require('webpack-hot-middleware');
const LRU = require('lru-cache');
const { createBundleRenderer } = require('vue-server-renderer');
const staticCache = require('./cahce');

class MioxKoaVue2xServerSideRenderer extends EventEmitter {
    constructor(app) {
        super();
        this.app = app;
        this.configs = {};
        this.options = {};
        this.data = {};
        this.isProd = process.env.NODE_ENV === 'production';
        this.microCache = LRU({ max: 100, maxAge: 1000 });
    }

    connect(client, server, options = {}) {
        this.configs.client = client;
        this.configs.server = server;
        this.options = Object.assign({
            hot: true,
            dir: null,
            cache: false,
            title: 'new Document',
            runInNewContext: true,
            maxAge: 31536000,
            gzip: true,
            dynamic: true
        }, options);

        this.data.publicPath = this.configs.client.output.publicPath || '/';
        this.data.hmr = path.resolve(this.data.publicPath, '__webpack_hmr__');
        this.data.template = this.resolveTemplate();

        if (this.isProd) {
            this.onProduction();
        } else {
            this.onDevelopment();
        }

        this.createServer();
    }

    onDevelopment() {
        this.data.dir = this.options.dir || path.dirname(this.configs.client.entry.app);
        // this.data.dir = this.configs.client.entry.app;
        this.readyPromise = this.createDevServer((bundle, options) => {
            this.renderer = this.createRenderer(bundle, options);
        });
    }

    onProduction() {
        const SSR_Bundle = path.resolve(this.configs.server.output.path, 'vue-ssr-server-bundle.json');
        const SSR_Manifest = path.resolve(this.configs.client.output.path, 'vue-ssr-client-manifest.json');
        const bundle = require(SSR_Bundle);
        const clientManifest = require(SSR_Manifest);
        this.renderer = this.createRenderer(bundle, { clientManifest });
        this.createProServer();
    }

    resolveTemplate() {
        const template = fs.readFileSync(this.options.html, 'utf8');
        return template.replace(
            '',
            `

`
        )
    }

    createRenderer(bundle, options) {
        const { cache, runInNewContext } = this.options;
        const configs = {
            template: this.data.template,
            basedir: this.data.dir,
            runInNewContext: runInNewContext || true
        };

        if (cache) {
            configs.cache = LRU({
                max: 1000,
                maxAge: 1000 * 60 * 15
            });
        }

        return createBundleRenderer(bundle, Object.assign(options, configs));
    }

    clientDevServer(object, callback) {
        if (this.options.hot) {
            this.configs.client.entry.app = [`webpack-hot-middleware/client?reload=true`, this.configs.client.entry.app];
            this.configs.client.plugins.push(new webpack.HotModuleReplacementPlugin());
        }

        this.configs.client.plugins.push(new webpack.NoEmitOnErrorsPlugin());
        const clientCompiler = webpack(this.configs.client);
        const devMiddleware = webpackDevMiddleWare(clientCompiler, {
            publicPath: this.data.publicPath,
            noInfo: true
        });

        if (this.options.hot) {
            this.app.use(ctk(hotMiddleWare(clientCompiler, {
                heartbeat: 2000
            })));
        }

        this.app.use(async (ctx, next) => {
            ctx.status = 200;
            await next();
        });

        this.app.use(ctk(devMiddleware));

        clientCompiler.plugin('done', () => {
            const fs = devMiddleware.fileSystem;
            const readFile = file => fs.readFileSync(path.join(this.configs.client.output.path, file), 'utf-8');
            try{
                object.clientManifest = JSON.parse(readFile('vue-ssr-client-manifest.json'));
            } catch(e) {}
            object.bundle && callback(object.bundle, { clientManifest: object.clientManifest });
        });
    }

    serverDevServer(object, callback) {
        const serverCompiler = webpack(this.configs.server);
        const mfs = new MFS();
        serverCompiler.outputFileSystem = mfs;
        serverCompiler.watch({}, (err, stats) => {
            if (err) throw err;
            stats = stats.toJson();
            stats.errors.forEach(err => console.error(err));
            stats.warnings.forEach(err => console.warn(err));
            const readFile = file => mfs.readFileSync(path.join(this.configs.client.output.path, file), 'utf-8');
            try{
                object.bundle = JSON.parse(readFile('vue-ssr-server-bundle.json'));
            } catch(e) {}
            object.clientManifest && callback(object.bundle, { clientManifest: object.clientManifest });
        });
    }

    createDevServer(cb) {
        const object = {
            bundle: null,
            resolve: null,
            clientManifest: null
        };

        const readyPromise = new Promise(r => { object.resolve = r });
        const ready = (...args) => { object.resolve(); cb(...args); };

        this.clientDevServer(object, ready);
        this.serverDevServer(object, ready);

        return readyPromise;
    }

    createProServer() {
        const { maxAge, gzip, dynamic } = this.options;
        this.app.use(staticCache(this.configs.client.output.path, {
            prefix: this.configs.client.output.publicPath,
            maxAge, gzip, dynamic
        }));
    }

    render(ctx, resolve, reject) {
        const { cache, title } = this.options;
        const url = ctx.request.url;

        if (cache) {
            const hit = this.microCache.get(url);
            if (hit) {
                if (!this.isProd) console.log(':', '[!]', url);
                ctx.body = hit;
                return;
            }
        }

        const context = {
            ctx, url,
            title: title,
            app: this.app
        };

        this.renderer.renderToString(context, (err, html) => {
            if (isError(err)) err.originUri = url;
            if (err) return reject(err);
            cache && this.microCache.set(url, html);
            resolve(html);
        });
    }

    createServer() {
        this.app.use(async (ctx, next) => {
            if (!this.render) return await next();

            const { cache } = this.options;
            const body = await new Promise((resolve, reject) => {
                if (this.isProd) { this.render(ctx, resolve, reject); }
                else { this.readyPromise.then(() => this.render(ctx, resolve, reject)); }
            }).catch(e => Promise.resolve(e));

            if (!cache) {
                ctx.set('Expires', 0);
                ctx.set('Cache-Control', 'no-cache');
                ctx.set('Pragma', 'no-cache');
            }

            if (isError(body)) {
                switch (body.code) {
                    case 404:
                        ctx.status = 404;
                        return await next();
                    case 302:
                        if (body.url) {
                            ctx.redirect(body.url);
                        } else {
                            throw new Error('302 redirect: miss url');
                        }
                        break;
                    default:
                        if (EventEmitter.listenerCount(this, 'error') === 0) {
                            ctx.status = body.code || 500;
                            ctx.body = `

Internet Server Error ${ctx.status}

Origin url: ${body.originUri}

${body.stack}

                            `;
                        } else {
                            this.emit('error', ctx, body);
                        }
                }
            } else {
                ctx.body = body;
            }
        });
    }
}

module.exports = MioxKoaVue2xServerSideRenderer;

function isError(err) {
    return err instanceof Error || Object.prototype.toString.call(err) === '[object Error]';
}


text:
[![Switch](../docs/Pictures/Menu/Switch.png)](Home.md)[![Switch](../docs/Pictures/Menu/Gallery.png)](Gallery.md)[![Switch](../docs/Pictures/Menu/Examples.png)](Examples.md)[![Switch](../docs/Pictures/Menu/Downloads.png)](Downloads.md)[![Switch](../docs/Pictures/Menu/Documentation.png)](Documentation.md)[![Switch](../docs/Pictures/Menu/Project.png)](https://sourceforge.net/projects/switchpro)[![Switch](../docs/Pictures/Menu/Sources.png)](https://github.com/gammasoft71/switch)[![Switch](../docs/Pictures/Menu/Contact.png)](Contact.md)[![Switch](../docs/Pictures/Menu/Gammasoft.png)](https://gammasoft71.wixsite.com/gammasoft)

The general-purpose value type is most often referred to as a struct, its C++ keyword. This section provides guidelines for general struct design.

**X DO NOT** provide a default constructor for a struct.

Following this guideline allows arrays of structs to be created without having to run the constructor on each item of the array.

**X DO NOT** define mutable value types.

Mutable value types have several problems. For example, when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value. Also, some languages (dynamic languages, in particular) have problems using mutable value types because even local variables, when dereferenced, cause a copy to be made.

**√ DO** ensure that a state where all instance data is set to zero, false, or null (as appropriate) is valid.

This prevents accidental creation of invalid instances when an array of the structs is created.

The System::Object::Equals method on value types causes boxing, and its default implementation is not very efficient, because it uses reflection. Equals can have much better performance and can be implemented so that it will not cause boxing.

**X DO** explicitly extend System::ValueType.

In general, structs can be very useful but should only be used for small, single, immutable values that will not be boxed frequently.

# See also

Other Resources

* [Framework Design Guidelines](FrameworkDesignGuidelines.md)
* [Type Design Guidelines](TypeDesignGuidelines.md)

______________________________________________________________________________________________

© 2018 Gammasoft.


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

namespace Modules.FastReflection
{
    /// <summary>
    /// Constructor(构造函数)快速反射接口
    /// </summary>
    public interface IConstructorInvoker
    {
        /// <summary>
        /// 调用构造函数
        /// </summary>
        /// <param name="parameters">构造函数参数</param>
        /// <returns>实例</returns>
        object Invoke(params object[] parameters);

        /// <summary>
        /// 构造函数信息
        /// </summary>
        ConstructorInfo Constructor { get; }
    }

    /// <summary>
    /// Constructor(构造函数)快速反射类
    /// </summary>
    public class ConstructorInvoker : IConstructorInvoker
    {
        private Func<object[], object> invoker;

        /// <summary>
        /// 构造函数信息
        /// </summary>
        public ConstructorInfo Constructor { get; private set; }

        /// <summary>
        /// 调用构造函数
        /// </summary>
        /// <param name="parameters">构造函数参数</param>
        /// <returns>实例</returns>
        public object Invoke(params object[] parameters)
        {
            return invoker(parameters);
        }

        /// <summary>
        /// ConstructorInvoker构造函数
        /// </summary>
        /// <param name="constructor">构造函数信息</param>
        public ConstructorInvoker(ConstructorInfo constructor)
        {
            Constructor = constructor;
            InitializeInvoker();
        }

        private void InitializeInvoker()
        {
            ParameterExpression parametersParameter = Expression.Parameter(typeof(object[]), "parameters");
            List<Expression> parameterConverts = new List<Expression>();
            ParameterInfo[] parameters = Constructor.GetParameters();
            for (int i = 0; i < parameters.Length; i++)
            {
                BinaryExpression parameterIndex = Expression.ArrayIndex(parametersParameter, Expression.Constant(i));
                parameterConverts.Add(Expression.Convert(parameterIndex, parameters[i].ParameterType));
            }
            NewExpression instanceNew = Expression.New(Constructor, parameterConverts);
            UnaryExpression instanceConvert = Expression.Convert(instanceNew, typeof(object));
            invoker = Expression.Lambda<Func<object[], object>>(instanceConvert, parametersParameter).Compile();
        }
    }

    /// <summary>
    /// Constructor(构造函数)快速反射类工厂类
    /// </summary>
    public class ConstructorInvokerFactory : FastReflectionFactory<ConstructorInfo, IConstructorInvoker>
    {
        /// <summary>
        /// 创建Constructor(构造函数)快速反射类
        /// </summary>
        /// <param name="key">构造函数信息</param>
        /// <returns>Constructor(构造函数)快速反射接口</returns>
        public override IConstructorInvoker Create(ConstructorInfo key)
        {
            return new ConstructorInvoker(key);
        }
    }
}


text:
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <asm/io.h>
#include <asm/uaccess.h>

#define WATCHDOG_NAME "Wafer 5823 WDT"
#define PFX WATCHDOG_NAME ": "
#define WD_TIMO 60			/* 60 sec default timeout */

static unsigned long wafwdt_is_open;
static char expect_close;
static spinlock_t wafwdt_lock;

/*
 *	You must set these - there is no sane way to probe for this board.
 *
 *      To enable, write the timeout value in seconds (1 to 255) to I/O
 *      port WDT_START, then read the port to start the watchdog. To pat
 *      the dog, read port WDT_STOP to stop the timer, then read WDT_START
 *      to restart it again.
 */

static int wdt_stop = 0x843;
static int wdt_start = 0x443;

static int timeout = WD_TIMO;  /* in seconds */
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds. 1<= timeout <=255, default=" __MODULE_STRING(WD_TIMO) ".");

static int nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, int, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=CONFIG_WATCHDOG_NOWAYOUT)");

static void wafwdt_ping(void)
{
	/* pat watchdog */
	spin_lock(&wafwdt_lock);
	inb_p(wdt_stop);
	inb_p(wdt_start);
	spin_unlock(&wafwdt_lock);
}

static void wafwdt_start(void)
{
	/* start up watchdog */
	outb_p(timeout, wdt_start);
	inb_p(wdt_start);
}

static void
wafwdt_stop(void)
{
	/* stop watchdog */
	inb_p(wdt_stop);
}

static ssize_t wafwdt_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
	/* See if we got the magic character 'V' and reload the timer */
	if (count) {
		if (!nowayout) {
			size_t i;

			/* In case it was set long ago */
			expect_close = 0;

			/* scan to see whether or not we got the magic character */
			for (i = 0; i != count; i++) {
				char c;
				if (get_user(c, buf + i))
					return -EFAULT;
				if (c == 'V')
					expect_close = 42;
			}
		}
		/* Well, anyhow someone wrote to us, we should return that favour */
		wafwdt_ping();
	}
	return count;
}

static int wafwdt_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
	     unsigned long arg)
{
	int new_timeout;
	void __user *argp = (void __user *)arg;
	int __user *p = argp;
	static struct watchdog_info ident = {
		.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT | WDIOF_MAGICCLOSE,
		.firmware_version = 1,
		.identity = "Wafer 5823 WDT",
	};

	switch (cmd) {
	case WDIOC_GETSUPPORT:
		if (copy_to_user(argp, &ident, sizeof (ident)))
			return -EFAULT;
		break;

	case WDIOC_GETSTATUS:
	case WDIOC_GETBOOTSTATUS:
		return put_user(0, p);

	case WDIOC_KEEPALIVE:
		wafwdt_ping();
		break;

	case WDIOC_SETTIMEOUT:
		if (get_user(new_timeout, p))
			return -EFAULT;
		if ((new_timeout < 1) || (new_timeout > 255))
			return -EINVAL;
		timeout = new_timeout;
		wafwdt_stop();
		wafwdt_start();
		/* Fall */
	case WDIOC_GETTIMEOUT:
		return put_user(timeout, p);

	case WDIOC_SETOPTIONS:
	{
		int options, retval = -EINVAL;

		if (get_user(options, p))
			return -EFAULT;

		if (options & WDIOS_DISABLECARD) {
			wafwdt_start();
			retval = 0;
		}

		if (options & WDIOS_ENABLECARD) {
			wafwdt_stop();
			retval = 0;
		}

		return retval;
	}

	default:
		return -ENOIOCTLCMD;
	}
	return 0;
}

static int wafwdt_open(struct inode *inode, struct file *file)
{
	if (test_and_set_bit(0, &wafwdt_is_open))
		return -EBUSY;

	/*
	 *      Activate
	 */
	wafwdt_start();
	return nonseekable_open(inode, file);
}

static int
wafwdt_close(struct inode *inode, struct file *file)
{
	if (expect_close == 42) {
		wafwdt_stop();
	} else {
		printk(KERN_CRIT PFX "WDT device closed unexpectedly.  WDT will not stop!\n");
		wafwdt_ping();
	}
	clear_bit(0, &wafwdt_is_open);
	expect_close = 0;
	return 0;
}

/*
 *	Notifier for system down
 */

static int wafwdt_notify_sys(struct notifier_block *this, unsigned long code, void *unused)
{
	if (code == SYS_DOWN || code == SYS_HALT) {
		/* Turn the WDT off */
		wafwdt_stop();
	}
	return NOTIFY_DONE;
}

/*
 *	Kernel Interfaces
 */

static struct file_operations wafwdt_fops = {
	.owner		= THIS_MODULE,
	.llseek		= no_llseek,
	.write		= wafwdt_write,
	.ioctl		= wafwdt_ioctl,
	.open		= wafwdt_open,
	.release	= wafwdt_close,
};

static struct miscdevice wafwdt_miscdev = {
	.minor	= WATCHDOG_MINOR,
	.name	= "watchdog",
	.fops	= &wafwdt_fops,
};

/*
 *	The WDT needs to learn about soft shutdowns in order to
 *	turn the timebomb registers off.
 */

static struct notifier_block wafwdt_notifier = {
	.notifier_call = wafwdt_notify_sys,
};

static int __init wafwdt_init(void)
{
	int ret;

	printk(KERN_INFO "WDT driver for Wafer 5823 single board computer initialising.\n");

	spin_lock_init(&wafwdt_lock);

	if (timeout < 1 || timeout > 255) {
		timeout = WD_TIMO;
		printk (KERN_INFO PFX "timeout value must be 1<=x<=255, using %d\n",
			timeout);
	}

	if (wdt_stop != wdt_start) {
		if(!request_region(wdt_stop, 1, "Wafer 5823 WDT")) {
			printk (KERN_ERR PFX "I/O address 0x%04x already in use\n",
			wdt_stop);
			ret = -EIO;
			goto error;
		}
	}

	if(!request_region(wdt_start, 1, "Wafer 5823 WDT")) {
		printk (KERN_ERR PFX "I/O address 0x%04x already in use\n",
			wdt_start);
		ret = -EIO;
		goto error2;
	}

	ret = register_reboot_notifier(&wafwdt_notifier);
	if (ret != 0) {
		printk (KERN_ERR PFX "cannot register reboot notifier (err=%d)\n",
			ret);
		goto error3;
	}

	ret = misc_register(&wafwdt_miscdev);
	if (ret != 0) {
		printk (KERN_ERR PFX "cannot register miscdev on minor=%d (err=%d)\n",
			WATCHDOG_MINOR, ret);
		goto error4;
	}

	printk (KERN_INFO PFX "initialized. timeout=%d sec (nowayout=%d)\n",
		timeout, nowayout);

	return ret;
error4:
	unregister_reboot_notifier(&wafwdt_notifier);
error3:
	release_region(wdt_start, 1);
error2:
	if (wdt_stop != wdt_start)
		release_region(wdt_stop, 1);
error:
	return ret;
}

static void __exit wafwdt_exit(void)
{
	misc_deregister(&wafwdt_miscdev);
	unregister_reboot_notifier(&wafwdt_notifier);
	if(wdt_stop != wdt_start)
		release_region(wdt_stop, 1);
	release_region(wdt_start, 1);
}

module_init(wafwdt_init);
module_exit(wafwdt_exit);

MODULE_AUTHOR("Justin Cormack");
MODULE_DESCRIPTION("ICP Wafer 5823 Single Board Computer WDT driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);

/* end of wafer5823wdt.c */


text:
using System;
using System.Diagnostics;

namespace garbage_calendar.Utils
{
    public class CalendarUtils
    {
        public static int CalcRowSize(int year, int month)
        {
            var diff = CalcPrevMonthDays(year, month);
            var endOfDay = GetCountOfDays(year, month);
            var cellCountWithPrefix = diff + endOfDay;
            if (cellCountWithPrefix % 7 == 0)
            {
                return cellCountWithPrefix / 7;
            }

            return cellCountWithPrefix / 7 + 1;
        }

        public static int CalcPrevMonthDays(int year, int month)
        {
            var date = new DateTime(year, month, 1);
            var startWeek = date.DayOfWeek;
            return startWeek - DayOfWeek.Sunday;
        }

        public static int CalcNextMonthDays(int year, int month)
        {
            var date = new DateTime(year, month, 1);
            var endOfDay = DateTime.DaysInMonth(year, month);
            date = new DateTime(year, month, endOfDay);

            var startWeek = date.DayOfWeek;

            return DayOfWeek.Saturday - startWeek;
        }

        public static int GetCountOfDays(int year, int month)
        {
            return DateTime.DaysInMonth(year, month);
        }

        public static DateTime CalcDate(int year, int month, int prevMonthDays, int idx)
        {
            // 前の月
            if (prevMonthDays >= idx)
            {
                var dateTime = new DateTime(year, month, 1);
                dateTime = dateTime.AddMonths(-1);
                var lastDay = GetCountOfDays(dateTime.Year, dateTime.Month);

                return new DateTime(dateTime.Year, dateTime.Month, lastDay - prevMonthDays + idx);
            }
            else
            {
                var lastDay = GetCountOfDays(year, month);
                // 当月
                if (lastDay + prevMonthDays >= idx)
                {
                    return new DateTime(year, month, idx - prevMonthDays);
                }
                // 次の月
                var dateTime = new DateTime(year, month, 1);
                dateTime = dateTime.AddMonths(1);

                return new DateTime(dateTime.Year, dateTime.Month, idx - lastDay - prevMonthDays);
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>{{ page.name }}'s Portfolio </title>
    <link rel="alternate" type="application/atom+xml" href="{{ page.root_path }}/?/feed/">
    <link rel="stylesheet" href="{{ page.root_path }}/public/docs/css/screen.css" type="text/css" media="screen">

        {{ page.name }}
        {{ page.profession }}

      {{ page.email }}

      {% include 'partials/navigation/navigation.html' %}

        {% include 'partials/navigation/category-lists.html' %}

© Copyright {{ page.name }} {{ page.current_year }} RSS

        Content managed by stacey


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Cube lambert and lighting</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow: hidden
        }
    </style>
</head>
<body>
<script src="js/three.js/three.js"></script>

<script>
    "use strict";
    //        var nextRotation = 0, rotationSpeed = 0.01, fps = 60;
    //
    //        setInterval(function()
    //        {
    //            cube.rotation.z = nextRotation;
    //            renderer.render(scene, camera);
    //            nextRotation += rotationSpeed;
    //        }, 1000 / fps);

    var angularSpeed = 0.2,
        lastTime = 0;

    function animate() {
        var time = (new Date()).getTime();
        var timeDiff = time - lastTime;
        var angularChange = angularSpeed * timeDiff * 2 * Math.PI / 1000;
        cube.rotation.y -= angularChange;
        lastTime = time;

        renderer.render(scene, camera);

        requestAnimationFrame(function() {
            animate();
        });
    }

    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);

    // near & far
    camera.position.y = -400; // pull the camera back to see the object in the middle of the scene

    // up & down
    camera.position.z = 400; // raise the camera up 200 units

    // left & right
    camera.rotation.x = 45 * (Math.PI / 180);

    // everything starts at the center of the scene
    var scene = new THREE.Scene();

    // without new THREE.MeshNormalMaterial() we'll get a wireframe cube
    var cube = new THREE.Mesh(new THREE.CubeGeometry(200, 100, 200), new THREE.MeshLambertMaterial({
        color: 'lightblue'
    }));

    var light = new THREE.DirectionalLight('white', 1.1);
    light.position.set(0, -400, 400).normalize();
    scene.add(light);

    scene.add(cube);

    animate();

    // In three.js doc: Math.degToRad(degrees) and Math.radToDeg(radians)
    // .75 = aproximately 45 degrees which is = 3.14159/180 * 45
</script>
</body>
</html>


text:
'use babel';

import { Disposable, CompositeDisposable } from 'atom';

import Injector from './injector.js';
import DockManager from './dock-manager.js';
import FileIcons from './file-icons.js';
import { CONFIG_PREFIX, COMMAND_PREFIX } from './constants.js';

class TreeViewPanes {
  constructor() {
    this.injector    = null;
    this.dockManager = new DockManager();

    this.subscriptions = new CompositeDisposable();
  }

  activate(state) {
    this.injector = new Injector((state && state.injector) || {});
    this.dockManager.initSubscriptions();

    this.subscriptions.add(atom.commands.add('atom-workspace', {
      [`${COMMAND_PREFIX}toggle-injected-view`]: () => {
        atom.config.set(
          `${CONFIG_PREFIX}injectView`,
          !atom.config.get(`${CONFIG_PREFIX}injectView`)
        );
      }
    }));
  }

  deactivate() {
    this.subscriptions.dispose();

    this.injector.destroy();
    this.dockManager.destroy();
  }

  serialize() {
    return {
      injector: this.injector.serialize()
    };
  }

  updateItemIcons() {
    this.injector.updateItemIcons();
    this.dockManager.updateItemIcons();
  }

  consumeFileIcons(service) {
    FileIcons.setService(service);
    this.updateItemIcons();
    return new Disposable(() => {
      FileIcons.resetService();
      this.updateItemIcons();
    });
  }

  getOrCreateDockItem(state) {
    return this.dockManager.getOrCreateDockItem(state);
  }
}

export default new TreeViewPanes();


text:
namespace ToDoCore
{

class ToDo
{
public:
    ToDo();
    ~ToDo();

    size_t size() const;

    void addTask(const std::string& task);
    std::string getTask(size_t index) const;

private:
    std::vector< std::string > this_tasks;
};

} // namespace ToDoCore

#endif // TODO_H


text:
package main

import (
	"path/filepath"
	"testing"
)

func TestIsLegalFile(t *testing.T) {
	testcase := func(filename string, want bool) {
		t.Run(filename, func(t *testing.T) {
			have := isLegalFile(filename)
			if have != want {
				t.Fail()
			}
		})
	}

	testcase("license.md", true)
	testcase("license.txt", true)
	testcase("LICENSE", true)
	testcase("LICENCE", true)
	testcase("LICENSE.md", true)
	testcase(filepath.Join("pkg", "LICENSE.md"), true)
	testcase("LEGAL", true)
	testcase("README", true)
	testcase("COPYING", true)
	testcase("COPYRIGHT", true)
	testcase("UNLICENSE", true)
	testcase("PATENTS", true)

	testcase(filepath.Join("pat", "ents"), false)
	testcase("picture.jpeg", false)
}

func TestKeep(t *testing.T) {
	testcase := func(filename string, want bool) {
		t.Run(filename, func(t *testing.T) {
			have := keepFile(filename)
			if have != want {
				t.Fail()
			}
		})
	}

	testcase("program.go", true)
	testcase("program_test.go", false)
	testcase(filepath.Join("pkg", "program.go"), true)
	testcase(filepath.Join("pkg", "program_test.go"), false)

	testcase("assembly.s", true)
	testcase("notassembly.as", false)
	testcase("sqlite.c", true)
	testcase("spec", false)
	testcase("sqlite.h", true)
	testcase("picture.gif", false)
	testcase("LICENSE.md", true)
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sborník severoceského Musea, Historia Naturalis 1: 65 (1958)

#### Original name
Hygrocybe calyptriformis (Berk.) Fayod, 1889

### Remarks
null


text:
/**
 * This file provides styles for modal dialogues.
 */

.dokuwiki .ui-widget {
    font-size: 100%;
}

/* link wizard (opens from the link button in the edit toolbar)
********************************************************************/

#link__wiz {
}

#link__wiz_result {
    background-color: __background__;
    width:  293px;
    height: 193px;
    overflow: auto;
    border: 1px solid __border__;
    margin: 3px auto;
    text-align: left;
    line-height: 1;
}

#link__wiz_result div {
    padding: 3px 3px 3px 0;
}

#link__wiz_result div a {
    display: block;
    padding-left: 22px;
    min-height: 16px;
    background: transparent 3px center no-repeat;
}

#link__wiz_result div.type_u a {
    background-image: url(../../images/up.png);
}
#link__wiz_result div.type_f a {
    background-image: url(../../images/page.png);
}
#link__wiz_result div.type_d a {
    background-image: url(../../images/ns.png);
}

#link__wiz_result div.even {
    background-color: __background_neu__;
}

#link__wiz_result div.selected {
    background-color: __background_alt__;
}

#link__wiz_result span {
    display: block;
    color: __text_neu__;
    margin-left: 22px;
}

/* media option wizard (opens when inserting media in the media popup)
********************************************************************/

#media__popup {
    /* for backwards compatibility (not needed since Rincewind) */
    display: none;
}

#media__popup_content p {
    margin: 0 0 .5em;
}

#media__popup_content label {
    margin-right: .5em;
    cursor: default;
}

#media__popup_content .button {
    margin-right: 1px;
    cursor: pointer;
}


text:
#include <aws/pinpoint/model/WriteTreatmentResource.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Pinpoint
{
namespace Model
{

WriteTreatmentResource::WriteTreatmentResource() :
    m_messageConfigurationHasBeenSet(false),
    m_scheduleHasBeenSet(false),
    m_sizePercent(0),
    m_sizePercentHasBeenSet(false),
    m_treatmentDescriptionHasBeenSet(false),
    m_treatmentNameHasBeenSet(false)
{
}

WriteTreatmentResource::WriteTreatmentResource(JsonView jsonValue) :
    m_messageConfigurationHasBeenSet(false),
    m_scheduleHasBeenSet(false),
    m_sizePercent(0),
    m_sizePercentHasBeenSet(false),
    m_treatmentDescriptionHasBeenSet(false),
    m_treatmentNameHasBeenSet(false)
{
  *this = jsonValue;
}

WriteTreatmentResource& WriteTreatmentResource::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("MessageConfiguration"))
  {
    m_messageConfiguration = jsonValue.GetObject("MessageConfiguration");

    m_messageConfigurationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Schedule"))
  {
    m_schedule = jsonValue.GetObject("Schedule");

    m_scheduleHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SizePercent"))
  {
    m_sizePercent = jsonValue.GetInteger("SizePercent");

    m_sizePercentHasBeenSet = true;
  }

  if(jsonValue.ValueExists("TreatmentDescription"))
  {
    m_treatmentDescription = jsonValue.GetString("TreatmentDescription");

    m_treatmentDescriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("TreatmentName"))
  {
    m_treatmentName = jsonValue.GetString("TreatmentName");

    m_treatmentNameHasBeenSet = true;
  }

  return *this;
}

JsonValue WriteTreatmentResource::Jsonize() const
{
  JsonValue payload;

  if(m_messageConfigurationHasBeenSet)
  {
   payload.WithObject("MessageConfiguration", m_messageConfiguration.Jsonize());

  }

  if(m_scheduleHasBeenSet)
  {
   payload.WithObject("Schedule", m_schedule.Jsonize());

  }

  if(m_sizePercentHasBeenSet)
  {
   payload.WithInteger("SizePercent", m_sizePercent);

  }

  if(m_treatmentDescriptionHasBeenSet)
  {
   payload.WithString("TreatmentDescription", m_treatmentDescription);

  }

  if(m_treatmentNameHasBeenSet)
  {
   payload.WithString("TreatmentName", m_treatmentName);

  }

  return payload;
}

} // namespace Model
} // namespace Pinpoint
} // namespace Aws


text:
"""
Set of tools for utilizing Przelewy24 API.

Version: 0.4
Author: Piotr Wasilewski <piotrek@piotrek.io>

The MIT License (MIT)

Copyright (c) 2016 Piotr Wasilewski

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import collections
import hashlib

import requests

VERSION = (0, 4)

API_VERSION = '3.2'

BASE_URL = 'https://secure.przelewy24.pl/'
BASE_SANDBOX_URL = 'https://sandbox.przelewy24.pl/'

CURRENCY_PLN = 'PLN'
CURRENCY_EUR = 'EUR'
CURRENCY_GBP = 'GBP'
CURRENCY_CZK = 'CZK'

COUNTRY_AD = 'AD'
COUNTRY_AT = 'AT'
COUNTRY_BE = 'BE'
COUNTRY_CY = 'CY'
COUNTRY_CZ = 'CZ'
COUNTRY_DK = 'DK'
COUNTRY_EE = 'EE'
COUNTRY_FI = 'FI'
COUNTRY_FR = 'FR'
COUNTRY_EL = 'EL'
COUNTRY_ES = 'ES'
COUNTRY_NL = 'NL'
COUNTRY_IE = 'IE'
COUNTRY_IS = 'IS'
COUNTRY_LT = 'LT'
COUNTRY_LV = 'LV'
COUNTRY_LU = 'LU'
COUNTRY_MT = 'MT'
COUNTRY_NO = 'NO'
COUNTRY_PL = 'PL'
COUNTRY_PT = 'PT'
COUNTRY_SM = 'SM'
COUNTRY_SK = 'SK'
COUNTRY_SI = 'SI'
COUNTRY_CH = 'CH'
COUNTRY_SE = 'SE'
COUNTRY_HU = 'HU'
COUNTRY_GB = 'GB'
COUNTRY_IT = 'IT'
COUNTRY_US = 'US'
COUNTRY_CA = 'CA'
COUNTRY_JP = 'JP'
COUNTRY_UA = 'UA'
COUNTRY_BY = 'BY'
COUNTRY_RU = 'RU'

LANGUAGE_PL = 'pl'
LANGUAGE_EN = 'en'
LANGUAGE_DE = 'de'
LANGUAGE_ES = 'es'
LANGUAGE_IT = 'it'

WAIT_FOR_RESULT_NO = 0
WAIT_FOR_RESULT_YES = 1

CHANNEL_CARD = 1
CHANNEL_TRANSFER = 2
CHANNEL_TRADITIONAL_TRANSFER = 4
CHANNEL_NA = 8
CHANNEL_ALL_247 = 16
CHANNEL_PREPAID = 32

ENCODING_ISO = 'ISO-8859-2'
ENCODING_UTF = 'UTF-8'
ENCODING_WIN = 'Windows-1250'

Config = collections.namedtuple(
    'Config',
    ['merchant_id', 'pos_id', 'crc', 'sandbox'])

Transaction = collections.namedtuple(
    'Transaction',
    ['session_id', 'amount', 'currency', 'description', 'email', 'client',
     'address', 'zip', 'city', 'country', 'phone', 'language', 'method',
     'url_return', 'url_status', 'time_limit', 'wait_for_result', 'channel',
     'shipping', 'transfer_label', 'encoding']
)

def get_sign(*args):
    return hashlib.md5(('|'.join(str(arg) for arg in args)).encode()).hexdigest()

def get_amount(amount):
    return int(amount * 100)

def get_url(config, path):
    if config.sandbox:
        return BASE_SANDBOX_URL + path
    else:
        return BASE_URL + path

class P24Response:
    def __init__(self, http_response):
        self._http_response = http_response

        try:
            content = http_response.content.decode()
        except UnicodeDecodeError:
            content = http_response.content.decode('windows-1250')
        data = {}
        for kv in content.split('&'):
            key, value = kv.split('=')
            data[key] = value

        self.error = data.get('error', None)
        self.error_message = data.get('errorMessage', None)
        self.token = data.get('token', None)

def test_connection(config):
    url = get_url(config, 'testConnection')
    data = {
        'p24_merchant_id': config.merchant_id,
        'p24_pos_id': config.pos_id,
        'p24_sign': get_sign(config.pos_id, config.crc)
    }
    http_response = requests.post(url, data)
    p24_response = P24Response(http_response)
    return p24_response

def transaction_register(config, transaction):
    url = get_url(config, 'trnRegister')
    data = {
        'p24_merchant_id': config.merchant_id,
        'p24_pos_id': config.pos_id,
        'p24_session_id': transaction.session_id,
        'p24_amount': get_amount(transaction.amount),
        'p24_currency': transaction.currency,
        'p24_description': transaction.description,
        'p24_email': transaction.email,
        'p24_country': transaction.country,
        'p24_url_return': transaction.url_return,
        'p24_api_version': API_VERSION,
        'p24_sign': get_sign(
            transaction.session_id,
            config.merchant_id,
            get_amount(transaction.amount),
            transaction.currency,
            config.crc),
        'p24_encoding': transaction.encoding,
    }
    if transaction.client is not None:
        data['p24_client'] = transaction.client
    if transaction.address is not None:
        data['p24_address'] = transaction.address
    if transaction.zip is not None:
        data['p24_zip'] = transaction.zip
    if transaction.city is not None:
        data['p24_city'] = transaction.city
    if transaction.phone is not None:
        data['p24_phone'] = transaction.phone
    if transaction.language is not None:
        data['p24_language'] = transaction.language
    if transaction.method is not None:
        data['p24_method'] = transaction.method
    if transaction.url_status is not None:
        data['p24_url_status'] = transaction.url_status
    if transaction.time_limit is not None:
        data['p24_time_limit'] = transaction.time_limit
    if transaction.wait_for_result is not None:
        data['p24_wait_for_result'] = transaction.wait_for_result
    if transaction.channel is not None:
        data['p24_channel'] = transaction.channel
    if transaction.shipping is not None:
        data['p24_shipping'] = transaction.shipping
    if transaction.transfer_label is not None:
        data['p24_transfer_label'] = transaction.transfer_label
    if transaction.encoding is not None:
        data['p24_encoding'] = transaction.encoding
    http_response = requests.post(url, data)
    p24_response = P24Response(http_response)
    return p24_response

def transaction_verify(config, transaction, order_id):
    url = get_url(config, 'trnVerify')
    data = {
        'p24_merchant_id': config.merchant_id,
        'p24_pos_id': config.pos_id,
        'p24_session_id': transaction.session_id,
        'p24_amount': get_amount(transaction.amount),
        'p24_currency': transaction.currency,
        'p24_order_id': order_id,
        'p24_sign': get_sign(
            transaction.session_id,
            config.merchant_id,
            get_amount(transaction.amount),
            transaction.currency,
            config.crc),
    }
    http_response = requests.post(url, data)
    p24_response = P24Response(http_response)
    return p24_response


text:
describe('TODO <ArticleBaseStats />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(true)
  })
})


text:
@interface DiscoveryNewsListCell : TJSBaseCollectionViewCell

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *aspectForIamge;

@end


text:
import io
from unittest import mock

import ddt

from rally.cli import cliutils
from rally.cli.commands import plugin as plugin_cmd
from rally.common.plugin import plugin
from rally.common import utils
from tests.unit import test

@ddt.ddt
class PluginCommandsTestCase(test.TestCase):

    def setUp(self):
        super(PluginCommandsTestCase, self).setUp()
        self.plugin_cmd = plugin_cmd.PluginCommands()

        @plugin.configure("p1", "p1_ns")
        class Plugin1(plugin.Plugin):
            """T1.

            Description of T1

            :param x: x arg
            :param y: y arg
            """
            pass

        self.Plugin1 = Plugin1

        @plugin.configure("p2", "p2_ns")
        class Plugin2(plugin.Plugin):
            """T2."""
            pass

        self.Plugin2 = Plugin2

        @plugin.configure("p3", "p2_ns")
        class Plugin3(plugin.Plugin):
            """T3."""
            pass

        self.Plugin3 = Plugin3

    def tearDown(self):
        super(PluginCommandsTestCase, self).tearDown()
        self.Plugin1.unregister()
        self.Plugin2.unregister()
        self.Plugin3.unregister()

    def test__print_plugins_list(self):
        out = io.StringIO()
        original_print_list = cliutils.print_list

        def print_list(*args, **kwargs):
            kwargs["out"] = out
            original_print_list(*args, **kwargs)

        with mock.patch.object(plugin_cmd.cliutils, "print_list",
                               new=print_list):
            plugin_cmd.PluginCommands._print_plugins_list(
                [self.Plugin1, self.Plugin2])

        self.assertEqual(
            "+-------------+------+----------+-------+\n"
            "| Plugin base | Name | Platform | Title |\n"
            "+-------------+------+----------+-------+\n"
            "| Plugin      | p1   | p1_ns    | T1.   |\n"
            "| Plugin      | p2   | p2_ns    | T2.   |\n"
            "+-------------+------+----------+-------+\n", out.getvalue())

    def test_show(self):
        with utils.StdOutCapture() as out:
            plugin_cmd.PluginCommands().show(None, "p1", "p1_ns")
            output = out.getvalue()

            self.assertIn("NAME\n\tp1", output)
            self.assertIn("PLATFORM\n\tp1_ns", output)
            self.assertIn("cli.commands.test_plugin", output)
            self.assertIn("DESCRIPTION\n\tDescription of T1", output)
            self.assertIn("PARAMETERS", output)

    @ddt.data(
        {
            "name": "nonex",
            "platform": None,
            "text": "Plugin nonex not found at any platform\n"
        },
        {
            "name": "nonexplugin",
            "platform": "nonex",
            "text": "Plugin nonexplugin@nonex not found\n"
        }
    )
    @ddt.unpack
    def test_show_not_found(self, name, platform, text):
        with utils.StdOutCapture() as out:
            plugin_cmd.PluginCommands().show(None, name, platform)
            self.assertEqual(out.getvalue(), text)

    @mock.patch("rally.cli.commands.plugin.PluginCommands._print_plugins_list")
    def test_show_many(self, mock_plugin_commands__print_plugins_list):
        with utils.StdOutCapture() as out:
            with mock.patch("rally.cli.commands.plugin.plugin.Plugin."
                            "get_all") as mock_plugin_get_all:
                mock_plugin_get_all.return_value = [self.Plugin2, self.Plugin3]
                plugin_cmd.PluginCommands().show(None, "p", "p2_ns")
                self.assertEqual("Multiple plugins found:\n", out.getvalue())
                mock_plugin_get_all.assert_called_once_with(platform="p2_ns")

        mock_plugin_commands__print_plugins_list.assert_called_once_with([
            self.Plugin2, self.Plugin3])

    @ddt.data(
        {
            "name": None,
            "platform": "nonex",
            "text": "Platform nonex not found\n"
        },
        {
            "name": "p2",
            "platform": "p1_ns",
            "text": "Plugin p2 not found\n"
        }
    )
    @ddt.unpack
    def test_list_not_found(self, name, platform, text):

        with utils.StdOutCapture() as out:
            plugin_cmd.PluginCommands().list(None, name, platform)
            self.assertEqual(text, out.getvalue())

    @mock.patch("rally.cli.commands.plugin.PluginCommands._print_plugins_list")
    def test_list(self, mock_plugin_commands__print_plugins_list):

        plugin_cmd.PluginCommands().list(None, None, "p1_ns")
        plugin_cmd.PluginCommands().list(None, "p1", "p1_ns")
        plugin_cmd.PluginCommands().list(None, "p2", None)

        mock_plugin_commands__print_plugins_list.assert_has_calls([
            mock.call([self.Plugin1]),
            mock.call([self.Plugin1]),
            mock.call([self.Plugin2])
        ])


text:
package de.fraunhofer.fokus.oefit.adhoc.forms;

/**
 * A form representing an entry for a data-list
 */
public class CategoryForm {

	private String	m_strName;
	private String	m_strDescr;
	private String	m_strParent;
	private String	m_strCat;
	private String	m_strType;

	/**
	 * Instantiates a new category form.
	 */
	public CategoryForm() {

	}

	/**
	 * Clear.
	 */
	public void clear() {
		this.m_strCat = "";
		this.m_strDescr = "";
		this.m_strName = "";
		this.m_strParent = "";
	}

	/**
	 * Gets the cat.
	 *
	 * @return the cat
	 */
	public String getCat() {
		return this.m_strCat;
	}

	/**
	 * Gets the descr.
	 *
	 * @return the descr
	 */
	public String getDescr() {
		return this.m_strDescr;
	}

	/**
	 * Gets the name.
	 *
	 * @return the name
	 */
	public String getName() {
		return this.m_strName;
	}

	/**
	 * Gets the parent.
	 *
	 * @return the parent
	 */
	public String getParent() {
		return this.m_strParent;
	}

	/**
	 * Gets the type.
	 *
	 * @return the type
	 */
	public String getType() {
		return this.m_strType;
	}

	/**
	 * Sets the cat.
	 *
	 * @param val the new cat
	 */
	public void setCat(final String val) {
		this.m_strCat = val;
	}

	/**
	 * Sets the descr.
	 *
	 * @param val the new descr
	 */
	public void setDescr(final String val) {
		this.m_strDescr = val;
	}

	/**
	 * Sets the name.
	 *
	 * @param val the new name
	 */
	public void setName(final String val) {
		this.m_strName = val;
	}

	/**
	 * Sets the parent.
	 *
	 * @param val the new parent
	 */
	public void setParent(final String val) {
		this.m_strParent = val;
	}

	/**
	 * Sets the type.
	 *
	 * @param val the new type
	 */
	public void setType(final String val) {
		this.m_strType = val;
	}
}


text:
package org.easycluster.easyconfig.client;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

public interface ConfigClient {

	/**
	 * Retrieves the name of the group running on this configuration cluster
	 *
	 * @return the name of the group running on this cluster
	 */
	String getGroup();

	/**
	 * Retrieves the name of the data id running on this configuration cluster
	 *
	 * @return the name of the data id running on this cluster
	 */
	String getDataId();

	/**
	 * Looks up the configuration info.
	 *
	 * @return the configuration information if found, otherwise null
	 */
	String getConfigurationInfo();

	String getConfigurationInfo(long timeout);

	String getConfiguratonInfoFromSnapshot(long timeout);

	Properties getPropertiesConfigurationInfo(long timeout);

	Properties getPropertiesConfigurationInfoFromSnapshot(long timeout);

	/**
	 * Registers a ConfigListener with the
	 * ConfigClient to receive cluster events.
	 *
	 * @param listener
	 *            the listener instance to register
	 *
	 * @return a ConfigListenerKey that can be used to unregister the listener
	 */
	Long addListener(ConfigListener listener);

	/**
	 * Unregisters a ConfigListener with the
	 * ConfigClient.
	 *
	 * @param key
	 *            the key what was returned by addListener when the
	 *            ConfigListener was registered
	 */
	void removeListener(Long key);

	/**
	 * Queries whether or not a connection to the cluster is established.
	 *
	 * @return true if connected, false otherwise
	 */
	boolean isConnected();

	/**
	 * Queries whether or not this ConfigClient has been shut
	 * down.
	 *
	 * @return true if shut down, false otherwise
	 */
	boolean isShutdown();

	/**
	 * Waits for the connection to the cluster to be established. This method
	 * will wait indefinitely for the connection.
	 *
	 * @throws InterruptedException
	 *             thrown if the current thread is interrupted while waiting
	 */
	void awaitConnection() throws InterruptedException;

	/**
	 * Waits for the connection to the cluster to be established for the
	 * specified duration of time.
	 *
	 * @param timeout
	 *            how long to wait before giving up, in terms of
	 *            unit
	 * @param unit
	 *            the TimeUnit that timeout should be
	 *            interpreted in
	 *
	 * @return true if the connection was established before the timeout, false
	 *         if the timeout occurred
	 * @throws InterruptedException
	 *             thrown if the current thread is interrupted while waiting
	 */
	boolean awaitConnection(long timeout, TimeUnit unit) throws InterruptedException;

	/**
	 * Waits for the connection to the cluster to be established. This method
	 * will wait indefinitely for the connection and will swallow any
	 * InterruptedExceptions thrown while waiting.
	 */
	void awaitConnectionUninterruptibly();

	/**
	 * start up the cluster configuration client.
	 */
	void start();

	/**
	 * Shut down the cluster configuration client.
	 */
	void shutdown();
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="robots" content="none">
    <title>QA Story</title>
    <link rel="canonical" href="navigation.html">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet" nonce="1Cj0hIrd7TASSx52tMxlmQ">

    <amp-story
        standalone
        title="QA Story"
        publisher="AMP Story team"
        publisher-logo-src="assets/logo.png"
        poster-portrait-src="assets/poster.jpg">

      <amp-story-page id="page1" auto-advance-after="page1" background-audio="./video/p1.mp4">
        <amp-story-grid-layer template="vertical" class="text">
          auto-advance after background-audio
        </amp-story-grid-layer>
      </amp-story-page>

      <amp-story-page id="page2" background-audio="./video/p1.mp4">
        <amp-story-grid-layer template="vertical" class="text">
          background-audio
        </amp-story-grid-layer>
      </amp-story-page>
    </amp-story>


text:
package xushuai.viewpager_indicator_demo;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.viewpagerindicator.IconPagerAdapter;

class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {

    protected String[] CONTENT = new String[] { "Reading", "Travel", "Sport" };

    protected static final int[] ICONS = new int[] {
            R.drawable.actionbar_bg_user,
            R.drawable.actionbar_bg_music,
            R.drawable.actionbar_bg_cast,
    };

    private int mCount = CONTENT.length;

    public TestFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    public void  setContent(String[] content){
        CONTENT = content;
    }

    @Override
    public Fragment getItem(int position) {
        return ListFragment.newInstance(CONTENT[position % CONTENT.length]);
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      return CONTENT[position % CONTENT.length];
    }

    @Override
    public int getIconResId(int index) {
      return ICONS[index % ICONS.length];
    }

    public void setCount(int count) {
        if (count > 0 && count <= 10) {
            mCount = count;
            notifyDataSetChanged();
        }
    }
}


text:
package br.ufsc.lehmann.msm.artigo.classifiers.validation;

/**
 * An abstract interface to measure the regression performance.
 *
 * @author Haifeng Li
 */
public interface RegressionMeasure {

    /**
     * Returns an index to measure the quality of regression.
     * @param truth the true response values.
     * @param prediction the predicted response values.
     */
    public double measure(double[] truth, double[] prediction);
}


text:
from model.overall_runner import init_corpora, corpora_to_day_features, match_features_to_labels, multid_combine_day_ranges, split_data
from model.keras_lstm_regression_model import LSTMRegressionModel
from util.config import Config
import math

if __name__ == "__main__":
    print("Initializing corpus...")
    approval_ratings, article_corpora = init_corpora()
    print("Got " + str(len(article_corpora.items())) + " days of articles.")
    print("Got " + str(len(approval_ratings.items())) + " days of approval ratings.")
    print("Done.")
    print("Building feature vectors...")
    features_by_day = corpora_to_day_features(article_corpora)
    print("Found " + str(len(features_by_day)) + " number of days with articles")
    range_features = multid_combine_day_ranges(features_by_day)
    X, Y = match_features_to_labels(range_features, approval_ratings)
    print("There are " + str(len(X)) + " ranges of features")
    print("There are " + str(len(Y)) + " labels")
    #partition data into train/test
    X_data, Y_data = split_data(X, Y)
    X_train, X_test, X_val = X_data
    Y_train, Y_test, Y_val = Y_data
    print("Done.")
    print("Training set of size: " + str(len(X_train)))
    print("Test set of size: " + str(len(X_test)))
    print("Creating model...")
    model = LSTMRegressionModel(train_data=[X_train, Y_train], test_data=[X_test, Y_test])
    print("Done.")
    print("Training model...")
    model.train()
    print("Done.")
    print("Printing architecture...")
    model.plot_model("lstm.png")
    print("Done.")
    """print("Evaluating...")
    predict_train = model.predict(X_train)
    print(predict_train)
    print(predict_train.shape)
    total_error = 0.0
    for i in range(len(predict_train)):
        predict_approval = predict_train[i][0][0] * 100
        diff_approval = predict_approval - Y_train[i][0]
        total_error += math.pow(math.fabs(diff_approval), 2)
    print("MSE (train): " + str(total_error / len(Y_train)))
    print("RMSE (train): " + str(math.sqrt(total_error / len(Y_train))))

    predict_test = model.predict(X_test)
    print(predict_test)
    print(predict_test.shape)
    total_error = 0.0
    for i in range(len(predict_test)):
        predict_approval = predict_test[i][0][0] * 100
        diff_approval = predict_approval - Y_test[i][0]
        total_error += math.pow(math.fabs(diff_approval), 2)
    print("MSE (test): " + str(total_error / len(Y_test)))
    print("RMSE (test): " + str(math.sqrt(total_error / len(Y_test))))"""
    #print(predict_test)
    print("Done.")


text:
module.exports = {
  stylePrefix: 'comp-',

  wrapperId: 'wrapper',

  // Default wrapper configuration
  wrapper: {
    //classes: ['body'],
    removable: false,
    copyable: false,
    stylable: ['background','background-color','background-image', 'background-repeat','background-attachment','background-position'],
    draggable: false,
    badgable: false,
    components: [],
  },

  // Could be used for default components
  components: [],

  rte: {},

  // Class for new image component
  imageCompClass  : 'fa fa-picture-o',

  // Open assets manager on create of image component
  oAssetsOnCreate  : true,

  // List of void elements
  voidElements: ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'],
};


text:
using System;
using System.Threading.Tasks;
using System.Windows.Input;

namespace DoubleTapTest
{
    public interface IAsyncCommand : ICommand
    {
        Task ExecuteAsync(object parameter);
    }
}


text:
@interface ChimeClass ()

@property (nonatomic, weak) ChimeClass *chimeSuperclass;

@property (nonatomic) NSPointerArray *subclassesInternal;

@end

@implementation ChimeClass

#pragma mark Public Methods

- (NSString *)userVisibleTypeString {
    return NSLocalizedStringFromTableInBundle(@"Class", @"Chime", [NSBundle bundleForClass:[self class]], @"User-visible type string for a class.");
}

- (NSArray *)subclasses {
    return [self.subclassesInternal allObjects];
}

#pragma mark Framework Only Methods

- (instancetype)initWithName:(NSString *)name USR:(NSString *)universalSymbolResolution superclass:(ChimeClass *)superclass index:(ChimeIndex *)index {
    self = [super initWithName:name USR:universalSymbolResolution index:index];
    if (self != nil) {
        _chimeSuperclass = superclass;

        _subclassesInternal = [NSPointerArray weakObjectsPointerArray];

        [superclass addSubclass:self];
    }

    return self;
}

- (void)addSubclass:(ChimeClass *)subclass {
    [self.subclassesInternal addPointer:(__bridge void *)subclass];
}

@end


text:
package datastore

import (
	"bytes"
	"errors"
	"io/ioutil"
	"net/http"

	"github.com/mpl/scancabimport/third_party/code.google.com/p/goprotobuf/proto"
)

type client struct {
	transport http.RoundTripper
}

func (c *client) call(url string, req proto.Message, resp proto.Message) (err error) {
	client := http.Client{Transport: c.transport}
	payload, err := proto.Marshal(req)
	if err != nil {
		return
	}
	r, err := client.Post(url, "application/x-protobuf", bytes.NewBuffer(payload))
	if err != nil {
		return
	}
	defer r.Body.Close()
	body, err := ioutil.ReadAll(r.Body)
	if r.StatusCode != http.StatusOK {
		if err != nil {
			return err
		}
		return errors.New("datastore: error during call: " + string(body))
	}
	if err != nil {
		return err
	}
	if err = proto.Unmarshal(body, resp); err != nil {
		return
	}
//	if err := ioutil.WriteFile("/home/mpl/datastore.xml", []byte(resp.String()), 0700); err != nil {
//		return err
//	}
	return
}


text:
<?php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="forecast_budget_item")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ForecastBudgetItemRepository")
 */
class ForecastBudgetItem
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var ForecastBudgetPeriod
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\ForecastBudgetPeriod")
     * @ORM\JoinColumn(nullable=false)
     */
    private $period;

    /**
     * @var string
     *
     * @ORM\Column(name="category", type="string", length=255)
     */
    private $category;

    /**
     * @var string
     *
     * @ORM\Column(name="amount", type="decimal", precision=20, scale=5)
     */
    private $amount;

    /**
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @param string $category
     * @return ForecastBudgetItem
     */
    public function setCategory($category)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * @return string
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * @param string $amount
     * @return ForecastBudgetItem
     */
    public function setAmount($amount)
    {
        $this->amount = $amount;

        return $this;
    }

    /**
     * @return ForecastBudgetPeriod
     */
    public function getPeriod()
    {
        return $this->period;
    }

    /**
     * @param ForecastBudgetPeriod $period
     * @return ForecastBudgetItem
     */
    public function setPeriod(ForecastBudgetPeriod $period)
    {
        $this->period = $period;

        return $this;
    }
}


text:
package main

import (
	"go/ast"
	"go/token"
	"reflect"
	"strings"
)

func init() {
	register(cftypeFix)
}

var cftypeFix = fix{
	name:     "cftype",
	date:     "2017-09-27",
	f:        cftypefix,
	desc:     `Fixes initializers and casts of C.*Ref and JNI types`,
	disabled: false,
}

// Old state:
//
//	type CFTypeRef unsafe.Pointer
//
// New state:
//
//	type CFTypeRef uintptr
//
// and similar for other *Ref types.
// This fix finds nils initializing these types and replaces the nils with 0s.
func cftypefix(f *ast.File) bool {
	return typefix(f, func(s string) bool {
		return strings.HasPrefix(s, "C.") && strings.HasSuffix(s, "Ref") && s != "C.CFAllocatorRef"
	})
}

// typefix replaces nil with 0 for all nils whose type, when passed to badType, returns true.
func typefix(f *ast.File, badType func(string) bool) bool {
	if !imports(f, "C") {
		return false
	}
	typeof, _ := typecheck(&TypeConfig{}, f)
	changed := false

	// step 1: Find all the nils with the offending types.
	// Compute their replacement.
	badNils := map[any]ast.Expr{}
	walk(f, func(n any) {
		if i, ok := n.(*ast.Ident); ok && i.Name == "nil" && badType(typeof[n]) {
			badNils[n] = &ast.BasicLit{ValuePos: i.NamePos, Kind: token.INT, Value: "0"}
		}
	})

	// step 2: find all uses of the bad nils, replace them with 0.
	// There's no easy way to map from an ast.Expr to all the places that use them, so
	// we use reflect to find all such references.
	if len(badNils) > 0 {
		exprType := reflect.TypeOf((*ast.Expr)(nil)).Elem()
		exprSliceType := reflect.TypeOf(([]ast.Expr)(nil))
		walk(f, func(n any) {
			if n == nil {
				return
			}
			v := reflect.ValueOf(n)
			if v.Type().Kind() != reflect.Pointer {
				return
			}
			if v.IsNil() {
				return
			}
			v = v.Elem()
			if v.Type().Kind() != reflect.Struct {
				return
			}
			for i := 0; i < v.NumField(); i++ {
				f := v.Field(i)
				if f.Type() == exprType {
					if r := badNils[f.Interface()]; r != nil {
						f.Set(reflect.ValueOf(r))
						changed = true
					}
				}
				if f.Type() == exprSliceType {
					for j := 0; j < f.Len(); j++ {
						e := f.Index(j)
						if r := badNils[e.Interface()]; r != nil {
							e.Set(reflect.ValueOf(r))
							changed = true
						}
					}
				}
			}
		})
	}

	// step 3: fix up invalid casts.
	// It used to be ok to cast between *unsafe.Pointer and *C.CFTypeRef in a single step.
	// Now we need unsafe.Pointer as an intermediate cast.
	// (*unsafe.Pointer)(x) where x is type *bad -> (*unsafe.Pointer)(unsafe.Pointer(x))
	// (*bad.type)(x) where x is type *unsafe.Pointer -> (*bad.type)(unsafe.Pointer(x))
	walk(f, func(n any) {
		if n == nil {
			return
		}
		// Find pattern like (*a.b)(x)
		c, ok := n.(*ast.CallExpr)
		if !ok {
			return
		}
		if len(c.Args) != 1 {
			return
		}
		p, ok := c.Fun.(*ast.ParenExpr)
		if !ok {
			return
		}
		s, ok := p.X.(*ast.StarExpr)
		if !ok {
			return
		}
		t, ok := s.X.(*ast.SelectorExpr)
		if !ok {
			return
		}
		pkg, ok := t.X.(*ast.Ident)
		if !ok {
			return
		}
		dst := pkg.Name + "." + t.Sel.Name
		src := typeof[c.Args[0]]
		if badType(dst) && src == "*unsafe.Pointer" ||
			dst == "unsafe.Pointer" && strings.HasPrefix(src, "*") && badType(src[1:]) {
			c.Args[0] = &ast.CallExpr{
				Fun:  &ast.SelectorExpr{X: &ast.Ident{Name: "unsafe"}, Sel: &ast.Ident{Name: "Pointer"}},
				Args: []ast.Expr{c.Args[0]},
			}
			changed = true
		}
	})

	return changed
}


text:
This is a repo for tracking the progress of using synthetic images for computer vision research. If you found any important work is missing or information is not up-to-date, please edit this file directly and make a pull request. Each publication is tagged with a keyword to make it easier to search.

If you find anything missing from this page, please edit this `README.md` file to add it. When adding a new item, you can simply follow the format of existing items. How this document is structured is documented in [`contribute.md`](contribute.md).

**How to use**: Click publication to jump to the paper title, detailed information such as code and project page will be provided together with pdf file.**

## Synthetic image dataset

- [SunCG (Princeton)](https://sscnet.cs.princeton.edu/)
- [Minos](https://minosworld.github.io/)
- [House3d (Facebook)](https://github.com/facebookresearch/House3D)
- [Procedural Human Action Videos (PHAV)](#de2016procedural)
- [SURREAL](#varol2017learning)
- [Virtual KITTI](#gaidon2016virtual)
- [Synthia](#ros2016synthia)
- [Sintel](#butler2012naturalistic), A synthetic dataset for optical flow
- [SceneFlow](#mayer2015large)
- [4D Light Fields](#honauer2016dataset)
- [ICL-NUIM dataset](#handa2014benchmark)
- [Driving in the Matrix](#drivingthematrix)
- [Playing for Benchmarks](http://playing-for-benchmarks.org/overview/)

## 3D Model Repository

Realistic 3D models are critical for creating realistic and diverse virtual worlds. Here are research efforts for creating 3D model repositories.

- [ShapeNet](#chang2015shapenet)
- [3dscan](#choi2016large)
- [seeing3Dchairs](#aubry2014seeing)

## Tools

- [AirSim (Microsoft)](https://github.com/Microsoft/AirSim)
- [CARLA (Intel)](https://github.com/carla-simulator/carla)
- [Unity ML agents](https://blogs.unity3d.com/2017/09/19/introducing-unity-machine-learning-agents/)
- Render SMPL human bodies on Blender, see [CVPR2017](#varol2017learning)
- Render for CNN, based on Blender, see [ICCV2015](#su2015render)
- [UETorch](https://github.com/facebook/UETorch), based on UE4, see [ICML2016](#lerer2016learning)
- [UnrealCV](https://github.com/unrealcv/unrealcv), based on UE4, see [ArXiv](#qiu2016unrealcv)
- VizDoom, based on Doom, see [ArXiv](#kempka2016vizdoom)
- OpenAI Universe, see [project page](https://universe.openai.com/)
- Blender addon for 4D light field rendering, see [project page](https://github.com/lightfield-analysis/blender-addon)
- Event-Camera Dataset and Simulator see [project page](https://github.com/uzh-rpg/rpg_davis_simulator)

## Resources

[ECCV 2016 Workshop Virtual/Augmented Reality for Visual Artificial Intelligence (VARVAI) workshop](http://adas.cvc.uab.es/varvai2016/)

[ICCV 2017 Workshop Role of Simulation in Computer Vision](https://www.microsoft.com/en-us/research/event/iccv-2017-role-of-simulation-in-computer-vision/)

[Virtual Reality Meets Physical Reality:
Modelling and Simulating Virtual Humans and Environments
Siggraph Asia 2016 workshop](http://sigvr.org/)

[CVPR 2017 Workshop THOR Challenge](http://vuchallenge.org/thor.html)

See also: http://riemenschneider.hayko.at/vision/dataset/index.php?filter=+synthetic

## Misc.
- RealismCNN [github](https://github.com/junyanz/RealismCNN)
- Abnormality Detection in Images(http://paul.rutgers.edu/~babaks/abnormality_detection.html)

## Reference

### 2017

(Total=11)

- Adversarially Tuned Scene Generation
	([pdf](https://arxiv.org/pdf/1701.00405.pdf))

- UE4Sim: A Photo-Realistic Simulator for Computer Vision Applications
	([pdf](https://arxiv.org/abs/1708.05869))
	([project](https://ue4sim.org/))

- Playing for Benchmarks
	([pdf](http://vladlen.info/papers/playing-for-benchmarks.pdf))

- A Self-supervised Learning System for Object Detection using Physics Simulation and Multi-view Pose Estimation

	([:octocat:code](https://github.com/cmitash/PHYSIM_6DPose))
	([pdf](https://arxiv.org/pdf/1703.03347.pdf))
	([project](http://paul.rutgers.edu/~cm1074/PHYSIM.html))

 - Procedural Generation of Videos to Train Deep Action Recognition Networks
	([pdf](http://openaccess.thecvf.com/content_cvpr_2017/papers/de_Souza_Procedural_Generation_of_CVPR_2017_paper.pdf))
	([project](http://adas.cvc.uab.es/phav/))
	([citation:8](https://scholar.google.com/scholar?cites=12002008688864745159&as_sdt=2005&sciodt=0,5&hl=en))

- Learning from Synthetic Humans

	([:octocat:code](https://github.com/gulvarol/surreal))
	([pdf](https://arxiv.org/abs/1701.01370))
	([project](http://www.di.ens.fr/willow/research/surreal/))
	tag: synthetic human

- [Nvidia Issac](http://www.marketwired.com/press-release/nvidia-ushers-new-era-robotics-with-breakthroughs-making-it-easier-build-train-intelligent-2215481.htm)

- Configurable, Photorealistic Image Rendering and Ground Truth Synthesis by Sampling Stochastic Grammars Representing Indoor Scenes

- Aerial Informatics and Robotics Platform

	([:octocat:code](https://github.com/Microsoft/AirSim))
	([pdf](https://www.microsoft.com/en-us/research/wp-content/uploads/2017/02/aerial-informatics-robotics-TR.pdf))
	([project](https://www.microsoft.com/en-us/research/project/aerial-informatics-robotics-platform/))
	tag: tool

- Tobin, Josh, et al. "Domain Randomization for Transferring Deep Neural Networks from Simulation to the Real World." arXiv preprint arXiv:1703.06907 (2017). tag: domain
	([pdf](https://arxiv.org/pdf/1703.06907.pdf))

- M. Johnson-Roberson, C. Barto, R. Mehta, S. N. Sridhar, Karl Rosaen,and R. Vasudevan, "Driving in the matrix: Can virtual worlds replace human-generated annotations for real world tasks?," in IEEE International Conference on Robotics and Automation, pp. 1–8, 2017.

	([:octocat:code](https://github.com/umautobots/driving-in-the-matrix))
	([pdf](https://arxiv.org/pdf/1610.01983))
	([project](https://fcav.engin.umich.edu/sim-dataset/))
	([citation:3](https://scholar.google.com/scholar?um=1&ie=UTF-8&lr&cites=2191650018344815319))

### 2016
(Total=17)

- Sadeghi, Fereshteh, and Sergey Levine. "rl: Real single-image flight without a single real image. arXiv preprint." arXiv preprint arXiv:1611.04201 12 (2016). tag: rl

- Johnson, Justin, et al. "CLEVR: A Diagnostic Dataset for Compositional Language and Elementary Visual Reasoning." arXiv preprint arXiv:1612.06890 (2016).
	([pdf](https://arxiv.org/abs/1612.06890))

- McCormac, John, et al. "SceneNet RGB-D: 5M Photorealistic Images of Synthetic Indoor Trajectories with Ground Truth." arXiv preprint arXiv:1612.05079 (2016).

- de Souza, César Roberto, et al. "Procedural Generation of Videos to Train Deep Action Recognition Networks." arXiv preprint arXiv:1612.00881 (2016).
	([pdf](https://arxiv.org/abs/1612.00881))
	([project](http://adas.cvc.uab.es/phav/))
	tag: synthetic human

- Synnaeve, Gabriel, et al. "TorchCraft: a Library for Machine Learning Research on Real-Time Strategy Games." arXiv preprint arXiv:1611.00625 (2016).
	([pdf](https://arxiv.org/abs/1611.00625))
	([code](https://github.com/TorchCraft/TorchCraft))

- Lin, Jenny, et al. "A virtual reality platform for dynamic human-scene interaction." SIGGRAPH ASIA 2016 Virtual Reality meets Physical Reality: Modelling and Simulating Virtual Humans and Environments. ACM, 2016.
	([pdf](https://xiaozhuchacha.github.io/projects/siggraphasia16_vrplatform/vrplatform2016siggraphasia.pdf))
	([project](https://xiaozhuchacha.github.io/projects/siggraphasia16_vrplatform/index.html))

- Mahendran, A., et al. "ResearchDoom and CocoDoom: Learning Computer Vision with Games." arXiv preprint arXiv:1610.02431 (2016).
	([pdf](https://arxiv.org/pdf/1610.02431.pdf))
	([project](www.robots.ox.ac.uk/~vgg/research/researchdoom/))

- The SYNTHIA dataset: A large collection of synthetic images for semantic segmentation of urban scenes.  2016
	 ([pdf](http://www.cv-foundation.org/openaccess/content_cvpr_2016/html/Ros_The_SYNTHIA_Dataset_CVPR_2016_paper.html))
	 ([project](http://synthia-dataset.net/))
	 ([citation:4](http://scholar.google.com/scholar?cites=9178628328030932213&as_sdt=2005&sciodt=0,5&hl=en))

-   Virtual Worlds as Proxy for Multi-Object Tracking Analysis.  2016
	 ([pdf](http://arxiv.org/abs/1605.06457))
	 ([project](http://www.xrce.xerox.com/Research-Development/Computer-Vision/Proxy-Virtual-Worlds))
	 ([citation:5](http://scholar.google.com/scholar?cites=11727455440906017188&as_sdt=2005&sciodt=0,5&hl=en))

-   Playing for data: Ground truth from computer games.  2016
	 ([pdf](http://link.springer.com/chapter/10.1007/978-3-319-46475-6_7))
	 ([citation:1](http://scholar.google.com/scholar?cites=12822958035144353200&as_sdt=2005&sciodt=0,5&hl=en))

-   Play and Learn: Using Video Games to Train Computer Vision Models.  2016
	 ([pdf](http://arxiv.org/abs/1608.01745))
	 ([citation:1](http://scholar.google.com/scholar?cites=16081073673799361643&as_sdt=2005&sciodt=0,5&hl=en))

-   ViZDoom: A Doom-based AI Research Platform for Visual Reinforcement Learning.  2016
	([:octocat:code](https://github.com/Marqt/ViZDoom))
	([pdf](http://arxiv.org/abs/1605.02097))
	([project](http://vizdoom.cs.put.edu.pl/))
	([citation:4](http://scholar.google.com/scholar?cites=4101579648300742816&as_sdt=2005&sciodt=0,5&hl=en))

-   A large dataset of object scans.  2016
	 ([pdf](http://arxiv.org/abs/1602.02481))
	 ([project](http://redwood-data.org/3dscan/))
	 ([citation:6](http://scholar.google.com/scholar?cites=5989950372336055491&as_sdt=2005&sciodt=0,5&hl=en))

-   UnrealCV: Connecting Computer Vision to Unreal Engine  2016

	([:octocat:code](https://github.com/unrealcv/unrealcv))
	([project](http://unrealcv.github.io))
	([pdf](http://arxiv.org/abs/1609.01326))

-   Learning Physical Intuition of Block Towers by Example  2016
	([:octocat:code](https://github.com/facebook/UETorch))
	([pdf](http://arxiv.org/abs/1603.01312))
	([citation:12](http://scholar.google.com/scholar?cites=12846348306706460250&as_sdt=2005&sciodt=0,5&hl=en))

-   Target-driven Visual Navigation in Indoor Scenes using Deep Reinforcement Learning  2016
	 ([pdf](http://arxiv.org/abs/1609.05143))

-   A Dataset and Evaluation Methodology for Depth Estimation on 4D Light Fields. ACCV 2016
	 ([:octocat:code](https://github.com/lightfield-analysis))
	 ([pdf](http://lightfield-analysis.net/benchmark/paper/lightfield_benchmark_accv_2016.pdf))
	 ([project](http://lightfield-analysis.net/))
	 ([citation](https://scholar.google.de/scholar?cluster=3369030498099069181&hl=en&as_sdt=0,5))

### 2015
(Total=3)

-   A Large Dataset to Train Convolutional Networks for Disparity, Optical Flow, and Scene Flow Estimation.  2015
	 ([pdf](http://arxiv.org/abs/1512.02134))
	 ([citation:9](http://scholar.google.com/scholar?cites=16431759299155441580&as_sdt=2005&sciodt=0,5&hl=en))

-   Render for cnn: Viewpoint estimation in images using cnns trained with rendered 3d model views.  2015
	([:octocat:code](https://github.com/ShapeNet/RenderForCNN))
	([pdf](http://www.cv-foundation.org/openaccess/content_iccv_2015/html/Su_Render_for_CNN_ICCV_2015_paper.html))
	([citation:33](http://scholar.google.com/scholar?cites=1209553997502402606&as_sdt=2005&sciodt=0,5&hl=en))

-   Shapenet: An information-rich 3d model repository.  2015
	 ([pdf](http://arxiv.org/abs/1512.03012))
	 ([project](http://shapenet.cs.stanford.edu/))
	 ([citation:27](http://scholar.google.com/scholar?cites=1341601736562194564&as_sdt=2005&sciodt=0,5&hl=en))

### 2014
(Total=2)

-   Virtual and real world adaptation for pedestrian detection.  2014
	 ([pdf](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=6587038))
	 ([citation:46](http://scholar.google.com/scholar?cites=2637402509859183337&as_sdt=2005&sciodt=0,5&hl=en))

-   Seeing 3d chairs: exemplar part-based 2d-3d alignment using a large dataset of cad models.  2014
	([:octocat:code](https://github.com/dimatura/seeing3d))
	([pdf](http://www.cv-foundation.org/openaccess/content_cvpr_2014/html/Aubry_Seeing_3D_Chairs_2014_CVPR_paper.html))
	([project](http://www.di.ens.fr/willow/research/seeing3Dchairs/))
	([citation:110](http://scholar.google.com/scholar?cites=18030645502969108287&as_sdt=2005&sciodt=0,5&hl=en))

- Handa, Ankur, Thomas Whelan, John McDonald, and Andrew J. Davison. "A benchmark for RGB-D visual odometry, 3D reconstruction and SLAM." In Robotics and automation (ICRA), 2014 IEEE international conference on, pp. 1524-1531. IEEE, 2014.
	([project](https://www.doc.ic.ac.uk/~ahanda/VaFRIC/iclnuim.html))

### 2013
(Total=1)

-   Detailed 3d representations for object recognition and modeling.  2013
	 ([pdf](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=6516504))
	 ([citation:67](http://scholar.google.com/scholar?cites=6595507135181144034&as_sdt=2005&sciodt=0,5&hl=en))

### 2012
(Total=1)

-   A naturalistic open source movie for optical flow evaluation.  2012
	 ([pdf](http://link.springer.com/chapter/10.1007/978-3-642-33783-3_44))
	 ([project](http://sintel.is.tue.mpg.de/))
	 ([citation:227](http://scholar.google.com/scholar?cites=15124407213489971559&as_sdt=20000005&sciodt=0,21&hl=en))

### 2010
(Total=1)

-   Learning appearance in virtual scenarios for pedestrian detection.  2010
	 ([pdf](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=5540218))
	 ([citation:79](http://scholar.google.com/scholar?cites=17243485674852907889&as_sdt=2005&sciodt=0,5&hl=en))

### 2007
(Total=1)

-   Ovvv: Using virtual worlds to design and evaluate surveillance systems.  2007
	 ([pdf](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4270516))
	 ([citation:58](http://scholar.google.com/scholar?cites=3459961090644684583&as_sdt=2005&sciodt=0,5&hl=en))


text:
package org.wso2.carbon.integration.test.inputflow;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.databridge.commons.Event;
import org.wso2.carbon.databridge.commons.StreamDefinition;
import org.wso2.carbon.databridge.commons.utils.EventDefinitionConverterUtils;
import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationDto;
import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationInfoDto;
import org.wso2.carbon.integration.test.client.Wso2EventClient;
import org.wso2.carbon.integration.test.client.Wso2EventServer;
import org.wso2.cep.integration.common.utils.CEPIntegrationTest;
import org.wso2.cep.integration.common.utils.CEPIntegrationTestConstants;

import javax.xml.namespace.QName;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Sending different formatted events to the Wso2Event Receiver according to the receivers custom mapping type
 */
public class Wso2EventTestCase extends CEPIntegrationTest {

    private static final Log log = LogFactory.getLog(Wso2EventTestCase.class);

    @BeforeClass(alwaysRun = true)
    public void init()
            throws Exception {

        super.init(TestUserMode.SUPER_TENANT_ADMIN);
        String loggedInSessionCookie = getSessionCookie();

        eventReceiverAdminServiceClient = configurationUtil.getEventReceiverAdminServiceClient(backendURL,
                                                                                loggedInSessionCookie);
        eventStreamManagerAdminServiceClient = configurationUtil.getEventStreamManagerAdminServiceClient(backendURL,
                                                                                loggedInSessionCookie);
        eventPublisherAdminServiceClient = configurationUtil.getEventPublisherAdminServiceClient(backendURL,
                                                                                loggedInSessionCookie);
    }

    @Test(groups = {"wso2.cep"}, description = "Testing wso2event receiver with custom mapping formatting")
    public void wso2EventMapReceiverTestWithCustomMappingScenario() throws Exception {
        String samplePath = "inputflows" + File.separator + "sample0008";
        String eventReceiverName = "wso2eventReceiver";

        int startESCount = eventStreamManagerAdminServiceClient.getEventStreamCount();
        int startActiveERCount = eventReceiverAdminServiceClient.getActiveEventReceiverCount();
        int startAllERCount = eventReceiverAdminServiceClient.getEventReceiverCount();
        int startEPCount = eventPublisherAdminServiceClient.getActiveEventPublisherCount();

        EventReceiverConfigurationInfoDto[] startEventReceiverConfigurationInfoDtos = eventReceiverAdminServiceClient
                .getAllStreamSpecificActiveEventReceiverConfigurations("org.wso2.event.sensor.stream:1.0.0");
        int startStreamSpecificActiveERCount = startEventReceiverConfigurationInfoDtos == null ? 0 : startEventReceiverConfigurationInfoDtos.length;

        //Add StreamDefinition
        String streamDefinitionAsString = getJSONArtifactConfiguration(samplePath,
                                                                       "org.wso2.event.sensor.stream_1.0.0.json");
        eventStreamManagerAdminServiceClient.addEventStreamAsString(streamDefinitionAsString);
        Assert.assertEquals(eventStreamManagerAdminServiceClient.getEventStreamCount(), startESCount + 1);

        String streamDefinitionMapAsString = getJSONArtifactConfiguration(samplePath,
                                                                          "org.wso2.mapped.sensor.data_1.0.0.json");
        eventStreamManagerAdminServiceClient.addEventStreamAsString(streamDefinitionMapAsString);
        Assert.assertEquals(eventStreamManagerAdminServiceClient.getEventStreamCount(), startESCount + 2);

        //Add File EventReceiver without mapping
        String eventReceiverConfig = getXMLArtifactConfiguration(samplePath, "wso2eventReceiver.xml");
        eventReceiverAdminServiceClient.addEventReceiverConfiguration(eventReceiverConfig);
        Thread.sleep(2000);
        Assert.assertEquals(eventReceiverAdminServiceClient.getActiveEventReceiverCount(), startActiveERCount + 1);
        Assert.assertEquals(eventReceiverAdminServiceClient.getEventReceiverCount(), startAllERCount + 1);
        EventReceiverConfigurationDto eventReceiverConfigurationDto = eventReceiverAdminServiceClient.
                getActiveEventReceiverConfiguration(eventReceiverName);
        Assert.assertTrue(eventReceiverConfigurationDto.getCustomMappingEnabled());
        String deployedEventReceiverConfig = eventReceiverAdminServiceClient.getEventReceiverConfigurationContent(eventReceiverName);
        Assert.assertNotNull(deployedEventReceiverConfig);
        OMElement omElement = AXIOMUtil.stringToOM(deployedEventReceiverConfig);
        String deployedERName = omElement.getAttributeValue(new QName("name"));
        Assert.assertEquals(deployedERName, eventReceiverName);

        eventReceiverAdminServiceClient.setTracingEnabled(eventReceiverName, false);
        eventReceiverAdminServiceClient.setStatisticsEnabled(eventReceiverName, true);
        EventReceiverConfigurationInfoDto[] eventReceiverConfigurationInfoDtos = eventReceiverAdminServiceClient
                .getAllStreamSpecificActiveEventReceiverConfigurations("org.wso2.mapped.sensor.data:1.0.0");
        Assert.assertEquals(eventReceiverConfigurationInfoDtos.length, startStreamSpecificActiveERCount + 1);
        EventReceiverConfigurationInfoDto deployedERInfoDto = null;
        for (EventReceiverConfigurationInfoDto eventReceiverConfigurationInfoDto : eventReceiverConfigurationInfoDtos) {
            if (eventReceiverConfigurationDto.getEventReceiverName().equals(eventReceiverName)) {
                deployedERInfoDto = eventReceiverConfigurationInfoDto;
                break;
            }
        }
        Assert.assertNotNull(deployedERInfoDto);
        Assert.assertFalse(deployedERInfoDto.getEnableTracing());
        Assert.assertTrue(deployedERInfoDto.getEnableStats());

        String[] supportedAdapterTypes = eventReceiverAdminServiceClient.getAllInputAdapterTypes();
        Assert.assertTrue(Arrays.asList(supportedAdapterTypes).contains(deployedERInfoDto.getInputAdapterType()));

        //Add Wso2event EventPublisher
        String eventPublisherConfig2 = getXMLArtifactConfiguration(samplePath, "wso2eventPublisher.xml");
        eventPublisherAdminServiceClient.addEventPublisherConfiguration(eventPublisherConfig2);
        Assert.assertEquals(eventPublisherAdminServiceClient.getActiveEventPublisherCount(), startEPCount + 1);

        // The data-bridge receiver
        Wso2EventServer agentServer = new Wso2EventServer(samplePath, CEPIntegrationTestConstants.TCP_PORT, true);
        Thread agentServerThread = new Thread(agentServer);
        agentServerThread.start();
        // Let the server start
        Thread.sleep(2000);

        StreamDefinition streamDefinition = EventDefinitionConverterUtils
                .convertFromJson(streamDefinitionAsString);

        Wso2EventClient.publish("thrift", "localhost", String.valueOf(CEPIntegrationTestConstants.TCP_PORT),
                                "admin", "admin", "org.wso2.event.sensor.stream:1.0.0", "wso2eventReceiver.csv",
                                samplePath, streamDefinition, 3, 1000);

        eventStreamManagerAdminServiceClient.removeEventStream("org.wso2.event.sensor.stream", "1.0.0");
        eventReceiverAdminServiceClient.removeInactiveEventReceiverConfiguration("wso2eventReceiver.xml");
        eventPublisherAdminServiceClient.removeInactiveEventPublisherConfiguration("wso2eventPublisher.xml");

        Thread.sleep(1000);

        List<Event> eventList = new ArrayList<>();
        Event event = new Event();
        event.setStreamId("org.wso2.event.sensor.stream:1.0.0");
        event.setMetaData(new Object[]{4354643, false, 501, "temperature"});
        event.setCorrelationData(new Object[]{90.34344, 20.44345});
        event.setPayloadData(new Object[]{2.3f, 20.44345});
        eventList.add(event);
        Event event2 = new Event();
        event2.setStreamId("org.wso2.event.sensor.stream:1.0.0");
        event2.setMetaData(new Object[]{4354653, false, 502, "temperature"});
        event2.setCorrelationData(new Object[]{90.34344, 20.44345});
        event2.setPayloadData(new Object[]{2.3f, 20.44345});
        eventList.add(event2);
        Event event3 = new Event();
        event3.setStreamId("org.wso2.event.sensor.stream:1.0.0");
        event3.setMetaData(new Object[]{4354343, false, 503, "temperature"});
        event3.setCorrelationData(new Object[]{90.34344, 20.44345});
        event3.setPayloadData(new Object[]{2.3f, 20.44345});
        eventList.add(event3);

        try {
            Assert.assertEquals(agentServer.getMsgCount(), eventList.size(), "Incorrect number of messages consumed!");

            int counter = 0;
            for (Event currentEvent : agentServer.getPreservedEventList()) {
                //Time stamp is dynamically added at the receiver client so it cannot be tested
                currentEvent.setTimeStamp(0);
                Assert.assertEquals(currentEvent.toString(), eventList.get(counter).toString(), "Mapping is incorrect!");
                counter++;
            }
        } catch (Throwable e) {
            log.error("Exception thrown: " + e.getMessage(), e);
            Assert.fail("Exception: " + e.getMessage());
        } finally {
            agentServer.stop();
        }
    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {
        super.cleanup();
    }
}


text:
namespace arangodb {
namespace velocypack {
class Builder;
}
namespace aql {

struct ExecutionStats {
  ExecutionStats();

  /// @brief instantiate the statistics from VelocyPack
  explicit ExecutionStats(arangodb::velocypack::Slice const& slice);

  /// @brief convert the statistics to VelocyPack
  void toVelocyPack(arangodb::velocypack::Builder&) const;

  /// @brief create empty statistics for VelocyPack
  static void toVelocyPackStatic(arangodb::velocypack::Builder&);

  /// @brief sets query execution time from the outside
  void setExecutionTime(double value) { executionTime = value; }

  /// @brief sumarize two sets of ExecutionStats
  void add(ExecutionStats const& summand) {
    writesExecuted += summand.writesExecuted;
    writesIgnored += summand.writesIgnored;
    scannedFull += summand.scannedFull;
    scannedIndex += summand.scannedIndex;
    filtered += summand.filtered;
    httpRequests += summand.httpRequests;
    if (summand.fullCount > 0) {
      // fullCount may be negative, don't add it then
      fullCount += summand.fullCount;
    }
    // intentionally no modification of executionTime
  }

  void clear() {
    writesExecuted = 0;
    writesIgnored = 0;
    scannedFull = 0;
    scannedIndex = 0;
    filtered = 0;
    httpRequests = 0;
    fullCount = -1;
    executionTime = 0.0;
  }

  /// @brief number of successfully executed write operations
  int64_t writesExecuted;

  /// @brief number of ignored write operations (ignored due to errors)
  int64_t writesIgnored;

  /// @brief number of documents scanned (full-collection scan)
  int64_t scannedFull;

  /// @brief number of documents scanned (using indexes scan)
  int64_t scannedIndex;

  /// @brief number of documents filtered away
  int64_t filtered;
  /// @brief total number of HTTP requests made

  int64_t httpRequests;

  /// @brief total number of results, before applying last limit
  int64_t fullCount;

  /// @brief query execution time (wall-clock time). value will be set from
  /// the outside
  double executionTime;
};
}
}

#endif


text: <nvd3 options="options" data="data"></nvd3>


text:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include "kk-win-lib-checker-memory-operation-mismatch-hook-crtcpp.h"

#include "../kk-win-lib-namedpipe.h"
#include "kk-win-lib-checker-memory-operation-mismatch.h"
#include "../kk-win-lib-hook-local.h"
#include "kk-win-lib-checker-memory-operation-mismatch-client.h"

#include <stdlib.h>

#include <assert.h>

namespace kk
{

namespace checker
{

namespace hookcrtcpp
{

static
DWORD64
sCRTStaticFunc[MemoryOperationMismatch::kIndexCRTStaticFuncMAX];

static
MemoryOperationMismatchClient*
sMemoryOperationMismatch = NULL;

static
size_t
sHookIndex[MemoryOperationMismatch::kIndexCRTStaticFuncMAX/2];

typedef void* (*PFN_new)(size_t size);
static
PFN_new             pfn_new = NULL;

typedef void* (*PFN_new_array)(size_t size);
static
PFN_new_array       pfn_new_array = NULL;

typedef void (*PFN_delete)(void* p);
static
PFN_delete          pfn_delete = NULL;

typedef void (*PFN_delete_array)(void* p);
static
PFN_delete_array    pfn_delete_array = NULL;

typedef void (*PFN_delete_size)(void* p,size_t size);
static
PFN_delete_size         pfn_delete_size = NULL;

typedef void (*PFN_delete_array_size)(void* p,size_t size);
static
PFN_delete_array_size   pfn_delete_array_size = NULL;

static
void*
my_new( size_t size )
{
    void* p = pfn_new(size);

    sMemoryOperationMismatch->sendOperation( MemoryOperationMismatch::kOperationCRTStaticNew, (DWORD64)p );

    return p;
}

static
void*
my_new_array( size_t size )
{
    void* p = pfn_new_array(size);

    sMemoryOperationMismatch->sendOperation( MemoryOperationMismatch::kOperationCRTStaticNewArray, (DWORD64)p );

    return p;
}

static
void
my_delete( void* p )
{
    sMemoryOperationMismatch->sendOperation( MemoryOperationMismatch::kOperationCRTStaticDelete, (DWORD64)p );

    pfn_delete(p);

    return;
}

static
void
my_delete_array( void* p )
{
    sMemoryOperationMismatch->sendOperation( MemoryOperationMismatch::kOperationCRTStaticDeleteArray, (DWORD64)p );

    pfn_delete_array(p);

    return;
}

static
void
my_delete_size( void* p, size_t size )
{
    sMemoryOperationMismatch->sendOperation( MemoryOperationMismatch::kOperationCRTStaticDeleteSize, (DWORD64)p );

    pfn_delete_size(p,size);

    return;
}

static
void
my_delete_array_size( void* p, size_t size )
{
    sMemoryOperationMismatch->sendOperation( MemoryOperationMismatch::kOperationCRTStaticDeleteArraySize, (DWORD64)p );

    pfn_delete_array_size(p,size);

    return;
}

static
bool
hookCRTCPP( const HMODULE hModule )
{
    if ( NULL == hModule )
    {
        return false;
    }

    bool result = true;

    for ( size_t indexOperation = 0; indexOperation < MemoryOperationMismatch::kIndexCRTStaticFuncMAX; indexOperation += 2 )
    {
        const size_t nOrigOffset = static_cast<const size_t>(sCRTStaticFunc[indexOperation+0]);
        const size_t nOrigSize   = static_cast<const size_t>(sCRTStaticFunc[indexOperation+1]);

        const void* hookFunc = NULL;
        void**      origFunc = NULL;

        {
            switch ( indexOperation )
            {
            case MemoryOperationMismatch::kIndexCRTStaticFuncNew:
                hookFunc = reinterpret_cast<const void*>(my_new);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncNewArray:
                hookFunc = reinterpret_cast<const void*>(my_new_array);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncDelete:
                hookFunc = reinterpret_cast<const void*>(my_delete);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncDeleteArray:
                hookFunc = reinterpret_cast<const void*>(my_delete_array);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncDeleteSize:
                hookFunc = reinterpret_cast<const void*>(my_delete_size);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncDeleteArraySize:
                hookFunc = reinterpret_cast<const void*>(my_delete_array_size);
                break;
            default:
                assert( false );
                break;
            }
        }

        {
            switch ( indexOperation )
            {
            case MemoryOperationMismatch::kIndexCRTStaticFuncNew:
                origFunc = reinterpret_cast<void**>(&pfn_new);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncNewArray:
                origFunc = reinterpret_cast<void**>(&pfn_new_array);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncDelete:
                origFunc = reinterpret_cast<void**>(&pfn_delete);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncDeleteArray:
                origFunc = reinterpret_cast<void**>(&pfn_delete_array);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncDeleteSize:
                origFunc = reinterpret_cast<void**>(&pfn_delete_size);
                break;
            case MemoryOperationMismatch::kIndexCRTStaticFuncDeleteArraySize:
                origFunc = reinterpret_cast<void**>(&pfn_delete_array_size);
                break;
            }
        }

        const bool bRet = sMemoryOperationMismatch->hook( sHookIndex[indexOperation/2], hModule, nOrigOffset, nOrigSize, hookFunc, origFunc );
        if ( false == bRet )
        {
            result = false;
        }

    }

    return result;
}

static
bool
unhookCRTCPP( void )
{
    if ( NULL == sMemoryOperationMismatch )
    {
        return false;
    }

    for ( size_t indexOperation = 0; indexOperation < MemoryOperationMismatch::kIndexCRTStaticFuncMAX; indexOperation += 2 )
    {
        const size_t indexHook = sHookIndex[indexOperation/2];

        const bool bRet = sMemoryOperationMismatch->unhook( indexHook );
    }

    pfn_new = NULL;
    pfn_delete = NULL;
    pfn_new_array = NULL;
    pfn_delete_array = NULL;
    pfn_delete_size = NULL;
    pfn_delete_array_size = NULL;

    return true;
}

} // namespace hookcrtcpp

bool
hookMemoryOperationMismatchCRTCPP( const HMODULE hModule, MemoryOperationMismatchClient* pMOM )
{
    bool result = true;
    {
        const bool bRet = pMOM->getCRTStaticFunc( hookcrtcpp::sCRTStaticFunc );
        if ( !bRet )
        {
            result = false;
        }
        else
        {
            hookcrtcpp::sMemoryOperationMismatch = pMOM;
        }
    }

    if ( result )
    {
        const bool bRet = hookcrtcpp::hookCRTCPP( hModule );
        if ( !bRet )
        {
            result = false;
        }
        else
        {
        }
    }

    return result;
}

bool
unhookMemoryOperationMismatchCRTCPP( void )
{
    bool result = true;
    {
        const bool bRet = hookcrtcpp::unhookCRTCPP();
        if ( !bRet )
        {
            result = false;
        }
    }

    hookcrtcpp::sMemoryOperationMismatch = NULL;

    return result;
}

} // namespace checker

} // namespace kk