text:
facts("Order object methods") do
  context("Constructor checks") do
    @fact_throws TradingLogic.Order("error", 10, 150.0,
                                    :obscuresym,
                                    :market, :complete, "string")
    @fact_throws TradingLogic.Order("error", 10, 150.0,
                                    :buy, :obscuresym,
                                    :complete, "string")
    @fact_throws TradingLogic.Order("error", 10, 150.0,
                                    :buy, :market,
                                    :obscuresym, "string")
  end
  context("Get info and modify methods") do
    emptord = TradingLogic.emptyorder()
    @fact TradingLogic.getorderposchg(emptord) --> 0
    @fact TradingLogic.ispending(emptord) --> false
    emptord.status = :pending
    @fact TradingLogic.ispending(emptord) --> true
    TradingLogic.setcancelled!(emptord)
    @fact TradingLogic.ispending(emptord) --> false

    # targeted position change with proper sign
    emptord.side = :qq
    @fact_throws TradingLogic.getorderposchg(emptord)
    posord = TradingLogic.Order("pos", 10, 150.0,
                                :buy, :limit, :pending, "aux")
    negord = TradingLogic.Order("neg", 10, 150.0,
                                :sell, :limit, :pending, "aux")
    @fact TradingLogic.getorderposchg(posord) > 0 --> true
    @fact TradingLogic.getorderposchg(negord) < 0 --> true
  end
end

facts("Order handling based on target input") do
  context("Limit and marker order from target input") do
    nostoplim = Array(Float64, 0)
    ord = TradingLogic.emptyorder()
    # should not be calling targ2order! with zero position change
    @fact TradingLogic.targ2order!(ord, (0, nostoplim),
                                   "", 0, true) --> false
    # stoplimit is not handled by targ2order!
    @fact TradingLogic.targ2order!(ord, (10, [1.0, 2.0]),
                                   "", 0, true) --> false

    # when no limit price is given: submit market
    ord.ordertype = :limit
    qty = -10
    @fact TradingLogic.targ2order!(ord, (qty, nostoplim),
                                   "", 0, true) --> true
    @fact ord.ordertype --> :market
    @fact isnan(ord.price) --> true
    @fact TradingLogic.getorderposchg(ord) --> qty
    @fact ord.side --> :sell
    @fact TradingLogic.ispending(ord) --> true

    # limit order for submission
    ord = TradingLogic.emptyorder()
    @fact ord.ordertype --> :market
    @fact ord.side --> :buy
    @fact TradingLogic.ispending(ord) --> false
    qty, prc = -50, 100.0
    @fact TradingLogic.targ2order!(ord, (qty, [prc]),
                                   "", 150, true) --> true
    @fact ord.ordertype --> :limit
    @fact isnan(ord.price) --> false
    @fact ord.price --> roughly(prc)
    @fact TradingLogic.getorderposchg(ord) --> qty
    @fact ord.side --> :sell
    @fact TradingLogic.ispending(ord) --> true
  end

  # orderhandling! input
  tnow() = unix2datetime(time())
  tinit = tnow()
  posactual = [0]
  blotter = TradingLogic.emptyblotter()
  backtest = true

  penter, pexit = 150.0, 110.0
  qty = 10
  shortgain = -(pexit - penter) * qty

  context("Order handling: pending order now complete") do
    # any target (irrelevant at this step -> evaluated next step)
    targ = (0, Array(Float64, 0))

    # market order was pending
    ord = TradingLogic.Order("neg", qty, NaN, :sell,
                             :market, :pending, "aux")
    @fact TradingLogic.ispending(ord) --> true
    @fact TradingLogic.orderhandling!(
      targ, penter, tinit, posactual, ord,
      blotter, backtest) --> (true, 0.0)
    # position updated, no new order generated yet
    # (need to re-evaluate target after position update)
    @fact blotter[tinit] --> (-qty, penter)
    @fact TradingLogic.ispending(ord) --> false
    @fact posactual[1] --> -qty

    # same with limit-order that was pending
    #  and is satisfied at current price
    ord = TradingLogic.Order("pos", qty, 120.0, :buy,
                             :limit, :pending, "aux")
    @fact TradingLogic.ispending(ord) --> true
    @fact TradingLogic.orderhandling!(
      targ, pexit, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # position updated, no new order generated yet
    # (need to re-evaluate target after position update)
    @fact TradingLogic.ispending(ord) --> false
    @fact posactual[1] --> 0
    @fact length(keys(blotter)) --> 2
  end

  context("Order handling: no position change targeted") do
    targ = (0, Array(Float64, 0))

    # nothing was pending
    ord = TradingLogic.emptyorder()
    @fact TradingLogic.ispending(ord) --> false
    @fact TradingLogic.orderhandling!(
      targ, 100.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # now still nothing pending, actual position is the same
    @fact TradingLogic.ispending(ord) --> false
    @fact posactual[1] --> 0

    # order was pending that is still pending (limit)
    ord = TradingLogic.Order("pos", 10, 50.0, :buy,
                             :limit, :pending, "aux")
    @fact TradingLogic.ispending(ord) --> true
    @fact TradingLogic.orderhandling!(
      targ, 100.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # now pending order gets cancelled
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0
  end

  context("Order handling: market buy/sell") do
    targ = (10, Array(Float64, 0))

    # nothing was pending
    ord = TradingLogic.emptyorder()
    @fact TradingLogic.ispending(ord) --> false
    @fact TradingLogic.orderhandling!(
      targ, 100.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # now pending, actual position still the same
    @fact TradingLogic.ispending(ord) --> true
    @fact ord.ordertype --> :market
    @fact posactual[1] --> 0

    # order was pending that is still pending (limit)
    ord = TradingLogic.Order("pos", 10, 50.0, :buy,
                             :limit, :pending, "aux")
    @fact TradingLogic.ispending(ord) --> true
    @fact TradingLogic.orderhandling!(
      targ, 100.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # now market target so cancel pending order
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0
  end

  context("Order handling: limit buy/sell") do
    targ = (30, [75.0])

    # nothing was pending
    ord = TradingLogic.emptyorder()
    @fact TradingLogic.ispending(ord) --> false
    @fact TradingLogic.orderhandling!(
      targ, 100.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # now limit pending, actual position still the same
    @fact TradingLogic.ispending(ord) --> true
    @fact ord.ordertype --> :limit
    @fact ord.side --> :buy
    @fact posactual[1] --> 0

    # limit order was pending that is still pending
    # in line with the target
    ord = TradingLogic.Order("pos", 30, 75.0, :buy,
                             :limit, :pending, "aux")
    @fact TradingLogic.orderhandling!(
      targ, 100.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # leave it pending
    @fact TradingLogic.ispending(ord) --> true
    @fact ord.ordertype --> :limit
    @fact ord.side --> :buy
    @fact posactual[1] --> 0

    # limit order was pending that is still pending
    # position change not in line with the target (value)
    ord = TradingLogic.Order("pos", 25, 75.0, :buy,
                             :limit, :pending, "aux")
    @fact TradingLogic.orderhandling!(
      targ, 100.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # cancel different order
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0

    # limit order was pending that is still pending
    # position change not in line with the target (side)
    ord = TradingLogic.Order("pos", 30, 75.0, :sell,
                             :limit, :pending, "aux")
    @fact TradingLogic.orderhandling!(
      targ, 70.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # cancel different order
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0

    # limit order was pending that is still pending
    # limit price not in line with the target
    ord = TradingLogic.Order("pos", 30, 85.0, :buy,
                             :limit, :pending, "aux")
    @fact TradingLogic.orderhandling!(
      targ, 100.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # cancel different order
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0
  end

  context("Order handling: stoplimit to track, buy-side") do
    targ = (50, [80.0, 75.0]) #[limitprice, stopprice]

    # nothing was pending
    # stop price not reached
    ord = TradingLogic.emptyorder()
    @fact TradingLogic.ispending(ord) --> false
    @fact TradingLogic.orderhandling!(
      targ, 70.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # no change, keep tracking the price
    @fact TradingLogic.ispending(ord) --> false
    @fact posactual[1] --> 0

    # nothing was pending
    # stop price reached
    ord = TradingLogic.emptyorder()
    @fact TradingLogic.ispending(ord) --> false
    @fact TradingLogic.orderhandling!(
      targ, 75.1, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # now limit pending, actual position still the same
    @fact TradingLogic.ispending(ord) --> true
    @fact ord.ordertype --> :limit
    @fact ord.side --> :buy
    @fact ord.price --> roughly(80.0)
    @fact posactual[1] --> 0

    # limit order was pending that is still pending
    # stop price not reached
    ord = TradingLogic.Order("pos", 30, 65.0, :buy,
                             :limit, :pending, "aux")
    @fact TradingLogic.orderhandling!(
      targ, 70.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # cancel previous order, keep tracking the price
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0

    # limit order was pending that is still pending
    # stop price reached
    # limit-target and prev. limit-pending can not match
    # (stop < limit for buy, sell symmetrically)
    # here we have (buy) limit_prev < stop < price_curr
    ord = TradingLogic.Order("pos", 50, 70.0, :buy,
                             :limit, :pending, "aux")
    @fact TradingLogic.orderhandling!(
      targ, 75.1, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # cancel previous order with different limit-price
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0
  end

  context("Order handling: stoplimit to track, sell-side") do
    targ = (-50, [60.0, 75.0]) #[limitprice, stopprice]

    # nothing was pending
    # stop price not reached
    ord = TradingLogic.emptyorder()
    @fact TradingLogic.ispending(ord) --> false
    @fact TradingLogic.orderhandling!(
      targ, 80.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # no change, keep tracking the price
    @fact TradingLogic.ispending(ord) --> false
    @fact posactual[1] --> 0

    # nothing was pending
    # stop price reached
    ord = TradingLogic.emptyorder()
    @fact TradingLogic.ispending(ord) --> false
    @fact TradingLogic.orderhandling!(
      targ, 74.9, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # now limit pending, actual position still the same
    @fact TradingLogic.ispending(ord) --> true
    @fact ord.ordertype --> :limit
    @fact ord.side --> :sell
    @fact ord.price --> roughly(60.0)
    @fact posactual[1] --> 0

    # limit order was pending that is still pending
    # stop price not reached
    ord = TradingLogic.Order("neg", 30, 85.0, :sell,
                             :limit, :pending, "aux")
    @fact TradingLogic.orderhandling!(
      targ, 80.0, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # cancel previous order, keep tracking the price
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0

    # limit order was pending that is still pending
    # stop price reached
    # limit-target and prev. limit-pending can not match
    # (stop < limit for buy, sell symmetrically)
    # here we have (sell) limit_prev > stop > price_curr
    ord = TradingLogic.Order("neg", 50, 80.0, :sell,
                             :limit, :pending, "aux")
    @fact TradingLogic.orderhandling!(
      targ, 74.9, tnow(), posactual, ord,
      blotter, backtest) --> (true, shortgain)
    # cancel previous order with different limit-price
    @fact TradingLogic.ispending(ord) --> false
    @fact ord.status --> :cancelled
    # no position updates
    @fact posactual[1] --> 0
  end
  #println(blotter)
end


text:
(function(root, factory) {
    if(typeof exports === 'object') {
        module.exports = factory();
    }
    else if(typeof define === 'function' && define.amd) {
        define([], factory);
    }
    else {
        root['BackboneComputed'] = factory();
    }
}(this, function() {

    var BackboneComputed = { VERSION: '0.1.0' };

    BackboneComputed.mixin = {

        get: function(attr, options) {
            var parent, computedAttr;

            parent = this.parent ? this.parent : Backbone.Model.prototype.get;
            options = options || {};

            // Ignore if specifically told so
            if (options.ignoreComputed) { return parent.apply(this, arguments); }

            if (this.computed && attr in this.computed) {
                computedAttr = this.computed[attr];

                if (_.isFunction(computedAttr)) {
                    return computedAttr.apply(this);
                } else if (_.isObject(computedAttr) && computedAttr.get) {
                    return computedAttr.get.apply(this);
                } else {
                    return undefined;
                }
            }
            return parent.apply(this, arguments);
        },

        /**
         * Overwrite Backbone 'set' method to check if a computed setter has
         * been defined, before falling back to Backbine's own 'set' method
         *
         * @param {String|Object} attr - the key of the value your are interested in
         *   setting. Can also be hash of attribute => value.
         * @param {Boolean} options.ignoreComputed - ignore any computed setters
         */
        set: function(attr, value, options) {
            var parent, computedAttr, attrs, opts, settings, unset, changes, changing, prev, current;

            settings = BackboneComputed.settings;
            parent = this.parent ? this.parent : Backbone.Model.prototype.set;

            // Handle both "key", value and {key: value} -style arguments.
            if (typeof attr === 'object') {
                attrs = attr;
                options = value;
            } else {
                (attrs = {})[attr] = value;
            }

            options = options || {};

            // Ignore if no computed hash or specifically told so
            if (options.ignoreComputed || !this.computed) {
                return parent.apply(this, arguments);
            }

            // Extract options
            unset = options.unset;
            silent = options.silent;
            changes = [];
            changing = this._changing;
            this._changing = true;

            if(!changing) {
                this._previousAttributes = _.clone(this.attritbutes || {});
                this.changed = {};
            }
            current = this.attributes, prev = this._previousAttributes;

            // Set each attribute with getter on computed attribute or
            // fallback to Backbone set method
            _.each(attrs, function(value, attr) {
                var computedAttr, currentValue;

                // Intercept any collections being set
                if (value instanceof Backbone.Collection) {
                    this.stopListening(this.get('attr'));
                    this.listenTo(value, 'add remove reset sort', this.propagateCollectionEvent);
                }

                if (attr in this.computed) {
                    computedAttr = this.computed[attr];

                    if (_.isObject(computedAttr) && computedAttr.set) {
                        computedAttr.set.call(this, value, options);
                        currentValue = this.get(attr);

                        if (!_.isEqual(currentValue, value)) {
                            changes.push(attr);
                            this.changed[attr] = value;
                            current[attr] = value;
                            this.attributes[attr] = value;
                        }
                    }
                }
            }, this);

            /*
             * Apply parent set method
             * This allows all attributes not handled by
             * computed attributes to be properly set
             */
            parent.apply(this, arguments);

            if (!silent) {
                if (changes.length) this._pending = options;
                for (var i = 0, l = changes.length; i < l; i++) {
                    this.trigger('change:' + changes[i], this, current[changes[i]], options);
                }
            }

            if (changing) return this;
            if (!silent) {
                while (this._pending) {
                    options = this._pending;
                    this._pending = false;
                    this.trigger('change', this, options);
                    this.triggerComputed(options);
                }
            }
            this._pending = false;
            this._changing = false;
            return this;
        },

        propagateCollectionEvent: function() {
            var collection, attr, collectionChanged;
            // Support arguments for all four collection events:
            // 'add remove reset sort'
            if (arguments[0] instanceof Backbone.Model) {
                collection = arguments[1];
            } else {
                collection = arguments[0];
            }

            // Find attr (key) for collection
            _.each(this.attributes, function(value, key) {
                if (value === collection) {
                    attr = key;
                }
            });

            // Trigger computed informing it that a collection
            // has updated, or remove event listening on collection
            // if it's no longer present in attributes
            if (attr) {
                collectionChanged = {};
                collectionChanged[attr] = collection;
                this.triggerComputed({
                    changed: collectionChanged,
                    externalEvent: true
                });
            } else {
                this.stopListening(collection);
            }
        },

        /*
         * Trigger events for computed attributes
         * if dependencies have changed
         *
         * @param {Boolean} options.externalEvent -
         *   If false: Assume this is called right after 'set' and examine
         *   freshly made 'changed' hash.
         *   If true: This method has been triggered by something else,
         *   and changes in 'changed' are to be considered old.
         * @param {Dict} options.changed - Examine these changed attributes instead,
         *   if options.externalEvent is true.
         */
        triggerComputed: function(options) {
            var changed,
                computedChanged = {},
                depsChanged = {},
                opts = options || {};

            if (opts.externalEvent) {
                changed = opts.changed;
            } else {
                changed = this.changedAttributes();
            }
            if (!changed) { return; }
            this._buildDependencyHash();

            // Calculate list of dependencies that have changed
            // that means the subset of current 'model.changed' that are defined
            // as dependecies in 'computed' hash
            depsChanged = _.pick(this._dependencyHash, _.keys(changed));
            _.each(depsChanged, function(value, key) {
                var computedList = value;

                // For each computed attribute that have an affected
                // dependency, store the computed value with it's value
                // in computedChanged. Note: the same computed attr can be
                // stored many times - overriding the previous one.
                _.each(computedList, function(computedAttr) {
                    computedChanged[computedAttr] = this.get(computedAttr);
                }, this);
            }, this);

            // Merge in 'computed changed' into model.changed so 'change' event
            // handlers AFTER this one, will 'see' them.
            // This works as event callbacks are added to the object itself, in an
            // array - which will always have the same order.
            _.extend(this.changed, computedChanged);

            // Manully trigger events for computed attrs
            // we not passing options array, as it is uncertain have
            // this should be done
            _.each(computedChanged, function(value, key) {
                this.trigger('change:' + key, this, value, {});
            }, this);
        },

        _buildDependencyHash: function() {
            // Construct dependencyHash if not already there
            // Depency hash looks like this:
            //   dependency1: [computed1, computed2],
            //   dependency2: [computed1]
            //
            // - also add eventhandlers to collection defined as depencies, as
            // these are not changed through 'set' method when collection is updated
            if (!this._dependencyHash) {
                this._dependencyHash = {};
                _.each(this.computed, function(cattr, key) {
                    if (_.isObject(cattr) && _.has(cattr, 'deps')) {
                        _.each(cattr.deps, function(dep) {
                            if (!_.has(this._dependencyHash, dep)) {
                                this._dependencyHash[dep] = [];
                            }
                            this._dependencyHash[dep].push(key);
                        }, this);
                    }
                }, this);
            }
        }
    }

    return BackboneComputed;

}));

redpajama_set_name: RedPajamaGithub


text:
class GlobalSuper extends GlobalClass {}
const globalSuper = new GlobalSuper();

class SideEffectSuper extends (() => {
	console.log( 'effect' );
	return class {};
})() {
}

class SuperConstructorEffect {
	constructor () {
		console.log( 'effect' );
	}
}
class SideEffectsSuperConstructor1 extends SuperConstructorEffect {}
const sideEffectsSuperConstructor1 = new SideEffectsSuperConstructor1();

class SideEffectsSuperConstructor2 extends SuperConstructorEffect {
	constructor () {
		super();
	}
}
const sideEffectsSuperConstructor2 = new SideEffectsSuperConstructor2();

class SuperMethodEffect {
	effect () {
		console.log( 'effect' );
	}
}
class SideEffectsSuperMethod extends SuperMethodEffect {
	constructor () {
		super();
		super.effect();
	}
}
const sideEffectsSuperMethod = new SideEffectsSuperMethod();


text: Number = (int, float)


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Whathecode.Interop;
using Whathecode.System.Runtime.InteropServices;

namespace Whathecode.System.Security.Principal
{
	/// <summary>
	///   A helper class to do common <see cref="WindowsIdentity" /> operations.
	/// </summary>
	public static class WindowsIdentityHelper
	{
		/// <summary>
		///   Checks whether the primary access token of the process belongs to a user account that is a member of the local Administrator group, even if it currently is not elevated.
		/// </summary>
		/// <returns>
		///   True if the primary access token of the process belongs to a user account that is a member of the Administrators group; false otherwise.
		/// </returns>
		public static bool IsUserInAdminGroup()
		{
			// Default token's received aren't impersonation tokens, we are looking for an impersonation token.
			bool isImpersonationToken = false;

			// Open the access token of the current process.
			SafeTokenHandle processToken;
			if ( !AdvApi32.OpenProcessToken( Process.GetCurrentProcess().Handle, (uint)(TokenAccessLevels.Query | TokenAccessLevels.Duplicate), out processToken ) )
			{
				MarshalHelper.ThrowLastWin32ErrorException();
			}

			// Starting from Vista linked tokens are supported which need to be checked.
			if ( EnvironmentHelper.VistaOrHigher )
			{
				// Determine token type: limited, elevated, or default.
				int marshalSize = sizeof( AdvApi32.TokenElevationType );
				var elevationTypeHandle = SafeUnmanagedMemoryHandle.FromNewlyAllocatedMemory( marshalSize );
				if ( !AdvApi32.GetTokenInformation( processToken, AdvApi32.TokenInformationClass.TokenElevationType, elevationTypeHandle.DangerousGetHandle(), marshalSize, out marshalSize ) )
				{
					MarshalHelper.ThrowLastWin32ErrorException();
				}
				var tokenType = (AdvApi32.TokenElevationType)Marshal.ReadInt32( elevationTypeHandle.DangerousGetHandle() );

				// If limited, get the linked elevated token for further check.
				if ( tokenType == AdvApi32.TokenElevationType.TokenElevationTypeLimited )
				{
					// Get the linked token.
					marshalSize = IntPtr.Size;
					var linkedTokenHandle = SafeUnmanagedMemoryHandle.FromNewlyAllocatedMemory( marshalSize );
					if ( !AdvApi32.GetTokenInformation( processToken, AdvApi32.TokenInformationClass.TokenLinkedToken, linkedTokenHandle.DangerousGetHandle(), marshalSize, out marshalSize ) )
					{
						MarshalHelper.ThrowLastWin32ErrorException();
					}
					processToken = new SafeTokenHandle( Marshal.ReadIntPtr( linkedTokenHandle.DangerousGetHandle() ) );
					isImpersonationToken = true; // Linked tokens are already impersonation tokens.
				}
			}

			// We need an impersonation token in order to check whether it contains admin SID.
			if ( !isImpersonationToken )
			{
				SafeTokenHandle impersonatedToken;
				if ( !AdvApi32.DuplicateToken( processToken, AdvApi32.SecurityImpersonationLevel.SecurityIdentification, out impersonatedToken ) )
				{
					MarshalHelper.ThrowLastWin32ErrorException();
				}
				processToken = impersonatedToken;
			}

			// Check if the token to be checked contains admin SID.
			var identity= new WindowsIdentity( processToken.DangerousGetHandle() );
			var principal = new WindowsPrincipal( identity );
			return principal.IsInRole( WindowsBuiltInRole.Administrator );
		}
	}
}


text:
knoOddsApp
==========

know the odds app


text:
from __future__ import unicode_literals

from flask import request

from indico.modules.users.api import RHUserFavoritesAPI, fetch_authenticated_user
from indico.modules.users.controllers import (RHAcceptRegistrationRequest, RHAdmins, RHExportDashboardICS,
                                              RHPersonalData, RHRegistrationRequestList, RHRejectRegistrationRequest,
                                              RHUserDashboard, RHUserEmails, RHUserEmailsDelete, RHUserEmailsSetPrimary,
                                              RHUserEmailsVerify, RHUserFavorites, RHUserFavoritesCategoryAPI,
                                              RHUserFavoritesUserRemove, RHUserFavoritesUsersAdd, RHUserPreferences,
                                              RHUsersAdmin, RHUsersAdminCreate, RHUsersAdminMerge,
                                              RHUsersAdminMergeCheck, RHUsersAdminSettings, RHUserSearch,
                                              RHUserSearchInfo, RHUserSuggestionsRemove)
from indico.web.flask.wrappers import IndicoBlueprint

_bp = IndicoBlueprint('users', __name__, template_folder='templates', virtual_template_folder='users',
                      url_prefix='/user')

# Admins
_bp.add_url_rule('!/admin/admins', 'admins', RHAdmins, methods=('GET', 'POST'))

# User management
_bp.add_url_rule('!/admin/users/', 'users_admin', RHUsersAdmin, methods=('GET', 'POST'))
_bp.add_url_rule('!/admin/users/settings', 'users_admin_settings', RHUsersAdminSettings, methods=('GET', 'POST'))
_bp.add_url_rule('!/admin/users/create/', 'users_create', RHUsersAdminCreate, methods=('GET', 'POST'))
_bp.add_url_rule('!/admin/users/merge/', 'users_merge', RHUsersAdminMerge, methods=('GET', 'POST'))
_bp.add_url_rule('!/admin/users/merge/check/', 'users_merge_check', RHUsersAdminMergeCheck)
_bp.add_url_rule('!/admin/users/registration-requests/', 'registration_request_list', RHRegistrationRequestList)
_bp.add_url_rule('!/admin/users/registration-requests/<int:request_id>/accept', 'accept_registration_request',
                 RHAcceptRegistrationRequest, methods=('POST',))
_bp.add_url_rule('!/admin/users/registration-requests/<int:request_id>/reject', 'reject_registration_request',
                 RHRejectRegistrationRequest, methods=('POST',))

# User profile
with _bp.add_prefixed_rules('/<int:user_id>'):
    _bp.add_url_rule('/dashboard/', 'user_dashboard', RHUserDashboard)
    _bp.add_url_rule('/suggestions/categories/<int:category_id>', 'user_suggestions_remove', RHUserSuggestionsRemove,
                     methods=('DELETE',))
    _bp.add_url_rule('/profile/', 'user_profile', RHPersonalData, methods=('GET', 'POST'))
    _bp.add_url_rule('/preferences/', 'user_preferences', RHUserPreferences, methods=('GET', 'POST'))
    _bp.add_url_rule('/favorites/', 'user_favorites', RHUserFavorites)
    _bp.add_url_rule('/favorites/users/', 'user_favorites_users_add', RHUserFavoritesUsersAdd, methods=('POST',))
    _bp.add_url_rule('/favorites/users/<int:fav_user_id>', 'user_favorites_user_remove', RHUserFavoritesUserRemove,
                     methods=('DELETE',))
    _bp.add_url_rule('/favorites/categories/<int:category_id>', 'user_favorites_category_api',
                     RHUserFavoritesCategoryAPI, methods=('PUT', 'DELETE'))
    _bp.add_url_rule('/emails/', 'user_emails', RHUserEmails, methods=('GET', 'POST'))
    _bp.add_url_rule('/emails/verify/<token>', 'user_emails_verify', RHUserEmailsVerify)
    _bp.add_url_rule('/emails/<email>', 'user_emails_delete', RHUserEmailsDelete, methods=('DELETE',))
    _bp.add_url_rule('/emails/make-primary', 'user_emails_set_primary', RHUserEmailsSetPrimary, methods=('POST',))

_bp.add_url_rule('/<int:user_id>/dashboard.ics', 'export_dashboard_ics', RHExportDashboardICS)

# User search
_bp.add_url_rule('/search/info', 'user_search_info', RHUserSearchInfo)
_bp.add_url_rule('/search/', 'user_search', RHUserSearch)

# Users API
_bp.add_url_rule('!/api/user/', 'authenticated_user', fetch_authenticated_user)

_bp.add_url_rule('/api/favorites/', 'favorites_api', RHUserFavoritesAPI)
_bp.add_url_rule('/api/favorites/<int:user_id>', 'favorites_api', RHUserFavoritesAPI, methods=('PUT', 'DELETE'))

@_bp.url_defaults
def _add_user_id(endpoint, values):
    """Add user id to user-specific urls if one was set for the current page.

    This ensures that the URLs we have both with an without user id always
    preserve the user id if there is one, but regular users don't end up
    with the user id in the URL all the time.

    Note that this needs to be replicated in other blueprints when they add
    stuff to the user pages using the `user_sidemenu` signal.
    """
    if endpoint.startswith('users.user_') and 'user_id' not in values:
        values['user_id'] = request.view_args.get('user_id')


text:
require 'test_helper'
require 'rubygems'
require 'kansas'
require 'dbi'

def all_students_in_courses
  result = []
  @ksdbh.select('Courses').each do |course|
    course.students_taking.each do |c|
      result << [course.name, c.student.first_name, c.student.student_number ]
    end
  end

  result
end

describe "transactions" do
  before do
    @params = Hash.new
    begin
      IO.foreach('tests.conf') do |line|
        if m = /^\s*(\w+)\s*=\s*(.*)$/.match(line)
          @params[m[1].downcase] = m[2]
        end
      end
    rescue Exception
      raise "There was an error opening tests.conf.  Please verify that it exists and is readable, and then run the tests again."
    end

    unless @params['vendor']
      raise "Database vendor not found; please specify the database vendor in tests.conf."
    end

    unless @params['host']
      raise "Database host not found; please specify the database host in tests.conf."
    end

    unless @params['name']
      raise "Database name not found; please specify the database name in tests.conf."
    end

    @dbh = DBI.connect("dbi:#{@params['vendor']}:#{@params['name']}:#{@params['host']}",@params['user'],@params['password'])
    IO.foreach(File.join(File.dirname(__FILE__),'create_tables.sql'),';') do |line|
      begin
        @dbh.do line
      rescue Exception => e
        puts "DBI Error: #{e}"
        puts "For SQL: #{line}"
        puts "Continuing with tests...."
      end
    end

    @ksdbh = KSDatabase.new(@dbh)
    @ksdbh.commit
    @ksdbh.set_autocommit(false)

    @ksdbh.table(:Students,'Students')
    @ksdbh.table('Courses',:Courses)
    @ksdbh.table('CoursesTaken','Courses_Taken')

    KSDatabase::CoursesTaken.to_one('course', 'name', 'Courses')
    KSDatabase::CoursesTaken.to_one(:student, :student_number, KSDatabase::Students)
    KSDatabase::Students.to_many(:courses_taken, KSDatabase::CoursesTaken, "student_number")
    KSDatabase::Courses.to_many(:students_taking, :CoursesTaken, :name)
  end

  it "basic commit" do
    sandy = @ksdbh.select('Students') {|s| (s.first_name == 'Sandy')}.first.dup
    sandy.first_name.must_equal "Sandy"

    sandy.first_name = 'Jessica'
    sandy.first_name.must_equal 'Jessica'

    @ksdbh.select('Students') {|s| (s.student_number == 101)}.each do |should_still_be_sandy|
      should_still_be_sandy.first_name.must_equal "Sandy"
    end

    @ksdbh.commit

    @ksdbh.select('Students') {|s| (s.student_number == 101)}.each do |now_it_should_be_jessica|
      now_it_should_be_jessica.first_name.must_equal "Jessica"
    end
  end

  it "basic rollback" do

    sandy = @ksdbh.select('Students') {|s| (s.first_name == 'Sandy')}.first.dup
    sandy.first_name.must_equal "Sandy"

    sandy.first_name = 'Jessica'
    sandy.first_name.must_equal 'Jessica'

    @ksdbh.select('Students') {|s| (s.student_number == 101)}.each do |should_still_be_sandy|
      should_still_be_sandy.first_name.must_equal "Sandy"
    end

    @ksdbh.rollback

    @ksdbh.select('Students') {|s| (s.student_number == 101)}.each do |should_still_be_sandy|
      should_still_be_sandy.first_name.must_equal "Sandy"
    end
  end

  it "extended commit" do

    starting_attendees = all_students_in_courses

    @ksdbh.select('Courses') {|c| (c.name == 'XZY987')}.first.name = 'ASL101'
    @ksdbh.select('CoursesTaken') {|c| (c.name == 'XZY987')}.each do |course_taken|
      course_taken.name = 'ASL101'
    end

    @ksdbh.select('Students') {|s| (s.first_name == 'Sandy')}.first.first_name = 'Jessica'

    pete = @ksdbh.select('Students') {|s| (s.first_name == 'Pete')}.first.dup
    @ksdbh.select('CoursesTaken') {|ct| (ct.name == 'LAW101') & (ct.student_number == pete.student_number)}.each do |oldclass|
      oldclass.name = 'ASL101'
    end

    @ksdbh.commit

    changed_courses_and_students = all_students_in_courses

  end

  it "extended updates in a transaction block" do
    starting_attendees = all_students_in_courses

    @ksdbh.transaction do |ksdbh|
      ksdbh.select('Courses') {|c| (c.name == 'XZY987')}.first.name = 'ASL101'
      ksdbh.select('CoursesTaken') {|c| (c.name == 'XZY987')}.each do |course_taken|
        course_taken.name = 'ASL101'
      end

      ksdbh.select('Students') {|s| (s.first_name == 'Sandy')}.first.first_name = 'Jessica'

      pete = ksdbh.select('Students') {|s| (s.first_name == 'Pete')}.first.dup
      ksdbh.select('CoursesTaken') {|ct| (ct.name == 'LAW101') & (ct.student_number == pete.student_number)}.each do |oldclass|
        oldclass.name = 'ASL101'
      end
    end

  end

  it "extended updates in a transaction block, with an exception triggering rollback" do
    starting_attendees = all_students_in_courses

    begin
      @ksdbh.transaction do |ksdbh|
        ksdbh.select('Courses') {|c| (c.name == 'XZY987')}.first.name = 'ASL101'
        ksdbh.select('CoursesTaken') {|c| (c.name == 'XZY987')}.each do |course_taken|
          course_taken.name = 'ASL101'
        end

        ksdbh.select('Students') {|s| (s.first_name == 'Sandy')}.first.first_name = 'Jessica'

        pete = ksdbh.select('Students') {|s| (s.first_name == 'Pete')}.first.dup
        ksdbh.select('CoursesTaken') {|ct| (ct.name == 'LAW101') & (ct.student_number == pete.student_number)}.each do |oldclass|
          oldclass.name = 'ASL101'
        end

        raise Exception.new("This should roll it back")
      end

    rescue Exception => e
      e.to_s.must_equal "This should roll it back"
    end

  end
end


text:
namespace AutoMapper.Configuration
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using Execution;

    public class MappingExpression : MappingExpression<object, object>, IMappingExpression
    {
        public MappingExpression(TypePair types, MemberList memberList) : base(memberList, types.SourceType, types.DestinationType)
        {
        }

        public new IMappingExpression ReverseMap() => (IMappingExpression) base.ReverseMap();

        public new IMappingExpression Substitute(Func<object, object> substituteFunc)
            => (IMappingExpression) base.Substitute(substituteFunc);

        public new IMappingExpression ConstructUsingServiceLocator()
            => (IMappingExpression)base.ConstructUsingServiceLocator();

        public void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions)
            => base.ForAllMembers(opts => memberOptions((IMemberConfigurationExpression)opts));

        void IMappingExpression.ConvertUsing<TTypeConverter>()
        {
            ConvertUsing(typeof(TTypeConverter));
        }

        public void ConvertUsing(Type typeConverterType)
        {
            var interfaceType = typeof(ITypeConverter<,>).MakeGenericType(Types.SourceType, Types.DestinationType);
            var convertMethodType = interfaceType.IsAssignableFrom(typeConverterType) ? interfaceType : typeConverterType;
            var converter = new DeferredInstantiatedConverter(convertMethodType, typeConverterType.BuildCtor<object>(
                context => typeof(ITypeConverter<,>).MakeGenericType(context.SourceType, context.DestinationType)));

            TypeMapActions.Add(tm => tm.UseCustomMapper(converter.Convert));
        }

        public void As(Type typeOverride) => TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeOverride);

        public void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions)
        {
            base.ForAllOtherMembers(o => memberOptions((IMemberConfigurationExpression)o));
        }

        public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions)
            => (IMappingExpression)base.ForMember(name, c => memberOptions((IMemberConfigurationExpression)c));

        public new IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions)
            => (IMappingExpression)base.ForSourceMember(sourceMemberName, memberOptions);

        public new IMappingExpression Include(Type otherSourceType, Type otherDestinationType)
            => (IMappingExpression)base.Include(otherSourceType, otherDestinationType);

        public new IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter()
            => (IMappingExpression)base.IgnoreAllPropertiesWithAnInaccessibleSetter();

        public new IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
            => (IMappingExpression)base.IgnoreAllSourcePropertiesWithAnInaccessibleSetter();

        public new IMappingExpression IncludeBase(Type sourceBase, Type destinationBase)
            => (IMappingExpression)base.IncludeBase(sourceBase, destinationBase);

        public new IMappingExpression BeforeMap(Action<object, object> beforeFunction)
            => (IMappingExpression)base.BeforeMap(beforeFunction);

        public new IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>
            => (IMappingExpression)base.BeforeMap<TMappingAction>();

        public new IMappingExpression AfterMap(Action<object, object> afterFunction)
            => (IMappingExpression)base.AfterMap(afterFunction);

        public new IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>
            => (IMappingExpression)base.AfterMap<TMappingAction>();

        public new IMappingExpression ConstructUsing(Func<object, object> ctor)
            => (IMappingExpression)base.ConstructUsing(ctor);

        public new IMappingExpression ConstructUsing(Func<ResolutionContext, object> ctor)
            => (IMappingExpression)base.ConstructUsing(ctor);

        public IMappingExpression ConstructProjectionUsing(LambdaExpression ctor)
        {
            var func = ctor.Compile();

            TypeMapActions.Add(tm => tm.ConstructExpression = ctor);

            return ConstructUsing(ctxt => func.DynamicInvoke(ctxt.SourceValue));
        }

        public new IMappingExpression MaxDepth(int depth)
            => (IMappingExpression)base.MaxDepth(depth);

        public new IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions)
            => (IMappingExpression)base.ForCtorParam(ctorParamName, paramOptions);

        public new IMappingExpression PreserveReferences() => (IMappingExpression)base.PreserveReferences();

        protected override IMemberConfiguration CreateMemberConfigurationExpression<TMember>(IMemberAccessor member,
            Type sourceType)
        {
            return new MemberConfigurationExpression(member, sourceType);
        }

        protected override MappingExpression<object, object> CreateReverseMapExpression()
        {
            return new MappingExpression(new TypePair(DestinationType, SourceType), MemberList.Source);
        }

        private class MemberConfigurationExpression : MemberConfigurationExpression<object, object>, IMemberConfigurationExpression
        {
            public MemberConfigurationExpression(IMemberAccessor destinationMember, Type sourceType)
                : base(destinationMember, sourceType)
            {
            }
        }

    }

    public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, ITypeMapConfiguration
    {
        private readonly List<IMemberConfiguration> _memberConfigurations = new List<IMemberConfiguration>();
        private readonly List<SourceMappingExpression> _sourceMemberConfigurations = new List<SourceMappingExpression>();
        private readonly List<CtorParamConfigurationExpression<TSource>> _ctorParamConfigurations = new List<CtorParamConfigurationExpression<TSource>>();
        private MappingExpression<TDestination, TSource> _reverseMap;
        private Action<IMemberConfigurationExpression<TSource, object>> _allMemberOptions;
        private Func<IMemberAccessor, bool> _memberFilter;

        public MappingExpression(MemberList memberList)
        {
            MemberList = memberList;
            Types = new TypePair(typeof(TSource), typeof(TDestination));
        }

        public MappingExpression(MemberList memberList, Type sourceType, Type destinationType)
        {
            MemberList = memberList;
            Types = new TypePair(sourceType, destinationType);
        }

        public MemberList MemberList { get; }
        public TypePair Types { get; }
        public Type SourceType => Types.SourceType;
        public Type DestinationType => Types.DestinationType;
        public ITypeMapConfiguration ReverseTypeMap => _reverseMap;
        protected List<Action<TypeMap>> TypeMapActions { get; } = new List<Action<TypeMap>>();

        public IMappingExpression<TSource, TDestination> PreserveReferences()
        {
            TypeMapActions.Add(tm => tm.EnablePreserveReferences());
            return this;
        }

        protected virtual IMemberConfiguration CreateMemberConfigurationExpression<TMember>(IMemberAccessor member, Type sourceType)
        {
            return new MemberConfigurationExpression<TSource, TMember>(member, sourceType);
        }

        protected virtual MappingExpression<TDestination, TSource> CreateReverseMapExpression()
        {
            return new MappingExpression<TDestination, TSource>(MemberList.Source, DestinationType, SourceType);
        }

        public IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
                                                                   Action<IMemberConfigurationExpression<TSource, TMember>> memberOptions)
        {
            var memberInfo = ReflectionHelper.FindProperty(destinationMember);
            IMemberAccessor destProperty = memberInfo.ToMemberAccessor();

            ForDestinationMember(destProperty, memberOptions);

            return this;
        }

        public IMappingExpression<TSource, TDestination> ForMember(string name,
                                                                   Action<IMemberConfigurationExpression<TSource, object>> memberOptions)
        {
            var member = DestinationType.GetFieldOrProperty(name);
            ForDestinationMember(member.ToMemberAccessor(), memberOptions);
            return this;
        }

        public void ForAllOtherMembers(Action<IMemberConfigurationExpression<TSource, object>> memberOptions)
        {
            _allMemberOptions = memberOptions;
            _memberFilter = m => _memberConfigurations.All(c=>c.DestinationMember.MemberInfo != m.MemberInfo);
        }

        public void ForAllMembers(Action<IMemberConfigurationExpression<TSource, object>> memberOptions)
        {
            _allMemberOptions = memberOptions;
            _memberFilter = _ => true;
        }

        public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter()
        {
            var properties = DestinationType.GetDeclaredProperties().Where(pm => pm.HasAnInaccessibleSetter());
            foreach (var property in properties)
                ForMember(property.Name, opt => opt.Ignore());
            return this;
        }

        public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
        {
            var properties = SourceType.GetDeclaredProperties().Where(pm => pm.HasAnInaccessibleSetter());
            foreach (var property in properties)
                ForSourceMember(property.Name, opt => opt.Ignore());
            return this;
        }

        public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
            where TOtherSource : TSource
            where TOtherDestination : TDestination
        {
            return Include(typeof(TOtherSource), typeof(TOtherDestination));
        }

        public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType)
        {
            TypeMapActions.Add(tm => tm.IncludeDerivedTypes(otherSourceType, otherDestinationType));

            return this;
        }

        public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>()
        {
            return IncludeBase(typeof(TSourceBase), typeof(TDestinationBase));
        }

        public IMappingExpression<TSource, TDestination> IncludeBase(Type sourceBase, Type destinationBase)
        {
            TypeMapActions.Add(tm => tm.IncludeBaseTypes(sourceBase, destinationBase));

            return this;
        }

        public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression)
        {
            TypeMapActions.Add(tm => tm.UseCustomProjection(projectionExpression));

            ConvertUsing(projectionExpression.Compile());
        }

        public IMappingExpression<TSource, TDestination> MaxDepth(int depth)
        {
            TypeMapActions.Add(tm => tm.MaxDepth = depth);
            return PreserveReferences();
        }

        public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator()
        {
            TypeMapActions.Add(tm => tm.ConstructDestinationUsingServiceLocator = true);

            return this;
        }

        public IMappingExpression<TDestination, TSource> ReverseMap()
        {
            var mappingExpression = CreateReverseMapExpression();

            _reverseMap = mappingExpression;

            return mappingExpression;
        }

        public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression> memberOptions)
        {
            var memberInfo = ReflectionHelper.FindProperty(sourceMember);

            var srcConfig = new SourceMappingExpression(memberInfo);

            memberOptions(srcConfig);

            _sourceMemberConfigurations.Add(srcConfig);

            return this;
        }

        public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions)
        {
            var memberInfo = SourceType.GetMember(sourceMemberName).First();

            var srcConfig = new SourceMappingExpression(memberInfo);

            memberOptions(srcConfig);

            _sourceMemberConfigurations.Add(srcConfig);

            return this;
        }

        public IMappingExpression<TSource, TDestination> Substitute(Func<TSource, object> substituteFunc)
        {
            TypeMapActions.Add(tm => tm.Substitution = src => substituteFunc((TSource) src));

            return this;
        }

        public void ConvertUsing(Func<TSource, TDestination> mappingFunction)
        {
            TypeMapActions.Add(tm => tm.UseCustomMapper((source, ctxt) => mappingFunction((TSource) source)));
        }

        public void ConvertUsing(Func<TSource, ResolutionContext, TDestination> mappingFunction)
        {
            TypeMapActions.Add(tm => tm.UseCustomMapper((source, ctxt) => mappingFunction((TSource) source, ctxt)));
        }

        public void ConvertUsing(ITypeConverter<TSource, TDestination> converter)
        {
            ConvertUsing(converter.Convert);
        }

        public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>
        {
            var converter = new DeferredInstantiatedConverter<TSource, TDestination>(typeof(TTypeConverter).BuildCtor<ITypeConverter<TSource, TDestination>>(
                context => typeof(ITypeConverter<,>).MakeGenericType(context.SourceType, context.DestinationType)));

            ConvertUsing(converter.Convert);
        }

        public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction)
        {
            TypeMapActions.Add(tm => tm.AddBeforeMapAction((src, dest, ctxt) => beforeFunction((TSource)src, (TDestination)dest)));

            return this;
        }

        public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction)
        {
            TypeMapActions.Add(tm => tm.AddBeforeMapAction((src, dest, ctxt) => beforeFunction((TSource)src, (TDestination)dest, ctxt)));

            return this;
        }

        public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>
        {
            Action<TSource, TDestination, ResolutionContext> beforeFunction = (src, dest, ctxt) =>
                ((TMappingAction)ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest);

            return BeforeMap(beforeFunction);
        }

        public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction)
        {
            TypeMapActions.Add(tm => tm.AddAfterMapAction((src, dest, ctxt) => afterFunction((TSource)src, (TDestination)dest)));

            return this;
        }

        public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction)
        {
            TypeMapActions.Add(tm => tm.AddAfterMapAction((src, dest, ctxt) => afterFunction((TSource)src, (TDestination)dest, ctxt)));

            return this;
        }

        public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>
        {
            Action<TSource, TDestination, ResolutionContext> afterFunction = (src, dest, ctxt)
                => ((TMappingAction)ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest);

            return AfterMap(afterFunction);
        }

        public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor)
        {
            return ConstructUsing(ctxt =>
            {
                var destination = ctor((TSource) ctxt.SourceValue);

                if (destination == null)
                    throw new InvalidOperationException($"Cannot create destination object of type {typeof(TDestination)}");

                return destination;
            });
        }

        public IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor)
        {
            TypeMapActions.Add(tm => tm.DestinationCtor = ctxt => ctor(ctxt));

            return this;
        }

        public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor)
        {
            var func = ctor.Compile();

            TypeMapActions.Add(tm => tm.ConstructExpression = ctor);

            return ConstructUsing(ctxt => func((TSource)ctxt.SourceValue));
        }

        private void ForDestinationMember<TMember>(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression<TSource, TMember>> memberOptions)
        {
            var expression = (MemberConfigurationExpression<TSource, TMember>) CreateMemberConfigurationExpression<TMember>(destinationProperty, SourceType);

            _memberConfigurations.Add(expression);

            memberOptions(expression);
        }

        public void As<T>()
        {
            TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeof(T));
        }

        public IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions)
        {
            var ctorParamExpression = new CtorParamConfigurationExpression<TSource>(ctorParamName);

            paramOptions(ctorParamExpression);

            _ctorParamConfigurations.Add(ctorParamExpression);

            return this;
        }

        public void Configure(IProfileConfiguration profile, TypeMap typeMap)
        {
            foreach (var destProperty in typeMap.DestinationTypeDetails.PublicWriteAccessors)
            {
                var attrs = destProperty.GetCustomAttributes(true);
                if (attrs.Any(x => x is IgnoreMapAttribute))
                {
                    ForMember(destProperty.Name, y => y.Ignore());
                    _reverseMap?.ForMember(destProperty.Name, opt => opt.Ignore());
                }
                if (profile.GlobalIgnores.Contains(destProperty.Name))
                {
                    ForMember(destProperty.Name, y => y.Ignore());
                }
            }

            if (_allMemberOptions != null)
            {
                foreach (var accessor in typeMap.DestinationTypeDetails.PublicReadAccessors.Select(m=>m.ToMemberAccessor()).Where(_memberFilter))
                {
                    ForDestinationMember(accessor, _allMemberOptions);
                }
            }

            foreach (var action in TypeMapActions)
            {
                action(typeMap);
            }
            foreach (var memberConfig in _memberConfigurations)
            {
                memberConfig.Configure(typeMap);
            }
            foreach (var memberConfig in _sourceMemberConfigurations)
            {
                memberConfig.Configure(typeMap);
            }
            foreach (var paramConfig in _ctorParamConfigurations)
            {
                paramConfig.Configure(typeMap);
            }

            if (_reverseMap != null)
            {
                foreach (var destProperty in typeMap.GetPropertyMaps().Where(pm => pm.IsIgnored()))
                {
                    _reverseMap.ForSourceMember(destProperty.DestinationProperty.Name, opt => opt.Ignore());
                }
                foreach (var includedDerivedType in typeMap.IncludedDerivedTypes)
                {
                    _reverseMap.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType);
                }
            }
        }

    }
}


text:
REP is environment for conducting data-driven research in a consistent and reproducible way.

Main REP features include:

  * unified classifiers wrapper for variety of implementations
    * TMVA
    * Sklearn
    * XGBoost
    * uBoost
    * Theanets
    * Pybrain
    * Neurolab
  * parallel training of classifiers on cluster
  * classification/regression reports with plots
  * support for interactive plots
  * grid-search algorithms with parallelized execution
  * versioning of research using git
  * pluggable quality metrics for classification
  * meta-algorithm design (aka 'rep-lego')

### Running using docker
We provide the docker container with `REP` and all it's dependencies

https://github.com/yandex/rep/wiki/Running-REP-using-Docker/

### Installation
However, if you want to install `REP` on your machine, follow this manual:

https://github.com/yandex/rep/wiki/Installing-manually

and https://github.com/yandex/rep/wiki/Running-manually

### First steps

To get started with the framework, look at the notebooks in /howto/

Notebooks in repository can be viewed (not executed) online at nbviewer: http://nbviewer.ipython.org/github/yandex/rep/tree/master/howto/

There are basic introductory notebooks (about python, IPython) and more advanced ones (about the REP itself)


text:
package com.ht1.cc.upload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.*;

import org.apache.commons.net.ftp.FTPClient;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class UploadHelper extends AsyncTask<String, Integer, Long> {

	Context context;

    public UploadHelper(Context context) {
        this.context = context;
    }
	protected Long doInBackground(String... data) {

		//SO, here is where you're going to want to decide
		//how and where you want to send the "data.csv"

		//I send to both azure site (FTP) and a google spreadsheet - between the
		//two I get pretty close to 100% up-time

		//FTP Example::

		FTPClient ftpClient = new FTPClient();

		try {
			ftpClient.connect(InetAddress.getByName("[YOUR SERVER]"));
			ftpClient.login("USERNAME", "PASSWORD");
			ftpClient.changeWorkingDirectory("DIRECTORY");

			if (ftpClient.getReplyString().contains("250")) {
				ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
				BufferedInputStream buffIn = null;
				buffIn = new BufferedInputStream(new FileInputStream(new File(context.getFilesDir(), "data.csv")));
				ftpClient.enterLocalPassiveMode();

				ftpClient.storeFile("data.csv", buffIn);
				buffIn.close();
				ftpClient.logout();
				ftpClient.disconnect();
			}
		}

		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return 1L;
	}

	protected void onPostExecute(Long result) {
		super.onPostExecute(result);
		Log.i("Uploader", result + " Status: FINISHED");

	}

}


text:
from django.conf.urls import patterns
from django.conf.urls import url

from openstack_dashboard.contrib.trove.content.database_backups import views

urlpatterns = patterns(
    '',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^create$', views.BackupView.as_view(), name='create'),
    url(r'^(?P<backup_id>[^/]+)/$', views.DetailView.as_view(),
        name='detail'),
)


text:
license: Licensed to the Apache Software Foundation (ASF) under one
         or more contributor license agreements.  See the NOTICE file
         distributed with this work for additional information
         regarding copyright ownership.  The ASF licenses this file
         to you under the Apache License, Version 2.0 (the
         "License"); you may not use this file except in compliance
         with the License.  You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

         Unless required by applicable law or agreed to in writing,
         software distributed under the License is distributed on an
         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
         KIND, either express or implied.  See the License for the
         specific language governing permissions and limitations
         under the License.
---

accelerometer.watchAcceleration
===============================

Obtiene la aceleración de los ejes x, y, z, cada un cierto intervalo de tiempo.

    var watchID = navigator.accelerometer.watchAcceleration(accelerometerSuccess,
                                                           accelerometerError,
                                                           [accelerometerOptions]);

Descripción
-----------

El acelerómetro es un sensor de movimiento que detecta cambios en el movimiento relativa a la posición actual (la diferencia). El acelerómetro puede detectar movimiento 3D sobre los ejes x, y, z
La función `accelerometer.watchAcceleration` crea un visor que se encarga de observar la aceleración cada ciertos intervalos de tiempo. Cada vez que el visor de aceleración obtiene la aceleración, la función `accelerometerSuccess` se disparara.  Puedes especificar el intervalo (milisegundos) en la opción `frequency` del objeto `acceleratorOptions`.

Esta función retorna un identificador que referencia a este visor de aceleración, puedes usarlo en la función `clearWatch` para detenerlo.

Plataformas Soportadas
----------------------

- Android
- BlackBerry WebWorks (OS 5.0 y superior)
- iPhone

Ejemplo Rápido
--------------

    function onSuccess(acceleration) {
        alert('Aceleración X: ' + acceleration.x + '\n' +
              'Aceleración Y: '   + acceleration.y + '\n' +
              'Aceleración Z: '   + acceleration.z + '\n' +
              'Timestamp: '       + acceleration.timestamp + '\n');
    };

    function onError() {
        alert('onError!');
    };

    var options = { frequency: 3000 };  // Actualizar cada 3 segundos

    var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);

Ejemplo Completo
----------------

    <!DOCTYPE html>

        <title>Ejemplo de Acceleration</title>

Esperando al acelerómetro...

Peculiaridades iPhone
---------------------

- En cada intervalo de tiempo, PhoneGap llamara a la función onSuccess y le pasara los resultados del acelerómetro.
- Sin embargo, PhoneGap restringe el intervalo a un mínimo de 40ms y un máximo de 1000ms.
  - Por ejemplo, si solicitas un intervalo de 3 segundos (3000ms), PhoneGap automáticamente obtendrá la aceleración cada 1 segundo, pero llamara a la función onSuccess cada 3 segundos.


text:
// ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Description:
//  This class provides many String based utilities.
// ----------------------------------------------------------------------------
// Change History:
//  2010/07/04  Martin D. Flynn
//     -Initial release
// ----------------------------------------------------------------------------
package org.opengts.util;

/**
*** Provides various String parsing/format utilities
**/

public enum TriState
    implements EnumTools.IntValue
{

    // ------------------------------------------------------------------------
    // ------------------------------------------------------------------------

    /* Enum value definition */
    UNKNOWN     ( -1, "unknown"  ), // default
    FALSE       (  0, "false"    ),
    TRUE        (  1, "true"     );

    // ------------------------------------------------------------------------
    // ------------------------------------------------------------------------

    /**
    *** Returns the TriState value for the specified String representation
    **/
    public static TriState parseTriState(String val, TriState dft)
    {
        if (StringTools.isBlank(val)) {
            return dft;
        } else
        if (val.equalsIgnoreCase("unknown") ||
            val.equalsIgnoreCase("default")   ) {
            return TriState.UNKNOWN;
        } else
        if (val.equalsIgnoreCase("true"   ) ||
            val.equalsIgnoreCase("yes"    )   ) {
            return TriState.TRUE;
        } else
        if (val.equalsIgnoreCase("false"  ) ||
            val.equalsIgnoreCase("no"     )   ) {
            return TriState.FALSE;
        } else {
            return dft;
        }
    }

    // ------------------------------------------------------------------------
    // ------------------------------------------------------------------------

    /**
    *** Returns the String representation for the specified TriState value
    *** @param state   The TriState value
    *** @param unknown The String value to return for TriState.UNKNOWN
    **/
    public static String toStringValue(TriState state, String unknown)
    {
        if (state != null) {
            switch (state) {
                case TRUE : return "TRUE";
                case FALSE: return "FALSE";
                default   : return unknown;
            }
        } else {
            return unknown;
        }
    }

    /**
    *** Returns the String representation for the specified TriState value
    *** @param state   The TriState value
    **/
    public static String toStringValue(TriState state)
    {
        return TriState.toStringValue(state, "UNKNOWN");
    }

    // ------------------------------------------------------------------------
    // ------------------------------------------------------------------------

    private int         value = 0;
    private String      text  = null;

    // ------------------------------------------------------------------------

    /**
    *** Enum Constructor
    **/
    TriState(int v, String t)
    {
        this.value = v;
        this.text  = t;
    }

    // ------------------------------------------------------------------------

    /**
    *** Returns the integer value of this instance
    *** @return The integer value of this instance
    **/
    public int getIntValue()
    {
        return this.value;
    }

    // ------------------------------------------------------------------------

    /**
    *** Returns the String representation of this instance
    *** @return The String representation of this instance
    **/
    public String toString()
    {
        return text.toString();
    }

    // ------------------------------------------------------------------------

    /**
    *** Returns true if this is the default value (UNKNOWN) or this TriState
    *** @return True if this is the default value (UNKNOWN) or this TriState
    **/
    public boolean isDefault()
    {
        return this.equals(UNKNOWN);
    }

    /**
    *** Returns true if the value is "Unknown"
    *** @return True if the value is "Unknown"
    **/
    public boolean isUnknown()
    {
        return this.equals(UNKNOWN);
    }

    /**
    *** Returns true if the value is "True"
    *** @return True if the value is "True"
    **/
    public boolean isTrue()
    {
        return this.equals(TRUE);
    }

    /**
    *** Returns true if the value is "False"
    *** @return True if the value is "False"
    **/
    public boolean isFalse()
    {
        return this.equals(FALSE);
    }

}