text:
"use strict";

/**
 * Return a new vec2 object with the specified x/y coordinates. If the first argument is an array,
 * the vec2 will be initialised using the first 2 elements of the array. If the first argument is
 * an object with x and y properties, these will be used instead (this is useful for copying vec2
 * instances). If no arguments are provided, or the arguments are invalid, a zero-vector will be
 * returned instead.
 * @param {Number|Array|Object} x The x-coordinate, or an array with at least 2 elements, or an
 * object with x and y properties.
 * @param {Number} [y] The y-coordinate, if an x-coordinate has also been provided.
 * @returns {Object} A vec2 instance.
 * @example
 * var v1 = vec2(2, 1); // v1 == { x: 2, y: 1 }
 * var v2 = vec2([2, 1]); // v2 == { x: 2, y: 1 }
 * var v3 = vec2(v1); // v3 == { x: 2, y: 1 }
 */
var vec2 = function(x, y) {
	if (arguments.length == 1) {
		if (x instanceof Array && x.length > 1) { // vec2 from array
			return { x: x[0], y: x[1] };
		} else if (x.x !== undefined && x.y !== undefined) {
			return { x: x.x, y: x.y }; // vec2 from vec2 (copy)
		}
		return { x: 0, y: 0 }; // Arguments incorrect, return [0, 0]
	}
	return { x: x || 0, y: y || 0 };
};

/**
 * @callback mapCallback
 * @param {Number} x The x or y component of the vector.
 * @param {...*} arguments Any additional arguments passed to vec2.map.
 * @returns {Boolean} True if the current element is the one being searched for.
 */
/**
 * Return a new vector from v by mapping it's components to f.
 * @param {vec2} v The vector to transform.
 * @param {mapCallback} f A callback that will be called for both the x and y components.
 * @param {...*} arguments - Additional arguments will be passed to f for each component.
 * @returns {vec2} The transformed vector.
 * @example
 * var v = vec2(1.5, 2.5);
 * v = vec2.map(v, Math.floor); // v == { x: 1, y: 2 }
 */
vec2.map = function(v, f) {
	var args = arguments.length == 1 ? [arguments[0]] : Array.apply(null, arguments);
	args = Array.prototype.slice.call(args, 2);
	return vec2(f.apply(this, [v.x].concat(args)), f.apply(this, [v.y].concat(args)));
};

/**
 * Get the length of a vector.
 * @param {vec2} v The vector.
 * @returns {Number} The vector's length.
 */
vec2.len = function(v) {
	return Math.sqrt(v.x * v.x + v.y * v.y);
};

/**
 * Get the angle of a vector in radians.
 * @param {vec2} v The vector.
 * @returns {Number} The angle of the vector in radians.
 */
vec2.rad = function(v) {
	return Math.atan2(v.y, v.x);
};

/**
 * Get the dot product of two vectors.
 * @param {vec2} v1 The first vector.
 * @param {vec2} v2 The second vector.
 * @returns {Number} The dot product of v1 and v2.
 */
vec2.dot = function(v1, v2) {
	return v1.x * v2.x + v1.y * v2.y;
};

/**
 * Normalise a vector
 * @param {vec2} v The vector.
 * @returns {vec2} The normalised vector.
 */
vec2.norm = function(v) {
	var length = vec2.len(v);
	if (length) {
		return vec2.div(v, length);
	}
	return vec2();
};

/**
 * Reflect a vector across a plane with normal n
 * @param {vec2} v The vector.
 * @param {vec2} n The plane normal vector.
 * @returns {vec2} The reflected vector.
 */
vec2.reflect = function(v, n) {
	return vec2.add(v, vec2.mul(vec2.mul(n, vec2.dot(v, n)), -2));
};

/**
 * Get the cross product of two vectors. The z-coord is assumed to be 0, since these are 2d vectors.
 * @param {vec2} v1 The first vector.
 * @param {vec2} v2 The second vector.
 * @returns {Number} The cross product of v1 and v2.
 */
vec2.cross = function(v1, v2) {
	return v1.x * v2.y - v1.y * v2.x;
};

/**
 * Rotate a vector.
 * @param {vec2} v The vector.
 * @param {Number} r The amount to rotate the vector by, in radians.
 * @returns {vec2} The rotated vector.
 */
vec2.rot = function(v, r) {
	var sinAngle = Math.sin(r),
		cosAngle = Math.cos(r),
		x = cosAngle * v.x - sinAngle * v.y,
		y = sinAngle * v.x + cosAngle * v.y;
	return vec2(x, y);
};

/**
 * Add two vectors or add a scalar to each component.
 * @param {vec2} v1 The first vector.
 * @param {vec2|Number} v2 The second vector, or a scalar value to add to each component of v1.
 * @returns {vec2} The sum of v1 and v2.
 */
vec2.add = function(v1, v2) {
	if (v2.x !== undefined && v2.y !== undefined) {
		return vec2(v1.x + v2.x, v1.y + v2.y);
	} else {
		return vec2(v1.x + v2, v1.y + v2);
	}
};

/**
 * Subtract two vectors.
 * @param {vec2} v1 The first vector.
 * @param {vec2|Number} v2 The second vector, or a scalar value to subtract from each component of
 * v1.
 * @returns {vec2} The difference of v1 and v2.
 */
vec2.sub = function(v1, v2) {
	if (v2.x !== undefined && v2.y !== undefined) {
		return vec2(v1.x - v2.x, v1.y - v2.y);
	} else {
		return vec2(v1.x - v2, v1.y - v2);
	}
};

/**
 * Multiply two vectors.
 * @param {vec2} v1 The first vector.
 * @param {vec2|Number} v2 The second vector, or a scalar value to multiply each component of v1 by.
 * @returns {vec2} The product of v1 and v2.
 */
vec2.mul = function(v1, v2) {
	if (v2.x !== undefined && v2.y !== undefined) {
		return vec2(v1.x * v2.x, v1.y * v2.y);
	} else {
		return vec2(v1.x * v2, v1.y * v2);
	}
};

/**
 * Divide two vectors.
 * @param {vec2} v1 The first vector.
 * @param {vec2|Number} v2 The second vector, or a scalar value to divide each component of v1 by.
 * @returns {vec2} The quotient of v1 and v2.
 */
vec2.div = function(v1, v2) {
	if (v2.x !== undefined && v2.y !== undefined) {
		return vec2(v1.x / v2.x, v1.y / v2.y);
	} else {
		return vec2(v1.x / v2, v1.y / v2);
	}
};

/**
 * Check if two vectors are equal.
 * @param {vec2} v1 The first vector.
 * @param {vec2} v2 The second vector.
 * @returns {Boolean} True if the vectors are equal.
 */
vec2.eq = function(v1, v2) {
	return (v1.x == v2.x && v1.y == v2.y);
};

/**
 * Convert a string representation of a vector (like '0,0' or '0, 0') into a vec2.
 * @param {String} s The string representation of the vector.
 * @returns {vec2} The resulting vec2, or a zero-vector if the string couldn't be parsed.
 */
vec2.fromString = function(s) {
	var values = s.split(",", 2);
	if (values.length == 2) {
		var x = parseFloat(values[0]),
			y = parseFloat(values[1]);
		return vec2(x, y);
	}
	return vec2(0, 0);
};

/**
 * Convert a vec2 into a string.
 * @param {vec2} v The vector to convert.
 * @param {String} [s=','] An optional separator string.
 * @returns {String} The string representation of v.
 */
vec2.toString = function(v, s) {
	return v.x + (s !== undefined ? s : ",") + v.y;
};


text:
--------------------------------
--
-- @function [parent=#WavesTiles3D] setAmplitude
-- @param self
-- @param #float amplitude

--------------------------------
--
-- @function [parent=#WavesTiles3D] setAmplitudeRate
-- @param self
-- @param #float amplitudeRate

--------------------------------
--  waves amplitude
-- @function [parent=#WavesTiles3D] getAmplitude
-- @param self
-- @return float#float ret (return value: float)

--------------------------------
--  creates the action with a number of waves, the waves amplitude, the grid size and the duration
-- @function [parent=#WavesTiles3D] create
-- @param self
-- @param #float duration
-- @param #size_table gridSize
-- @param #unsigned int waves
-- @param #float amplitude
-- @return WavesTiles3D#WavesTiles3D ret (return value: cc.WavesTiles3D)

--------------------------------
--
-- @function [parent=#WavesTiles3D] clone
-- @param self
-- @return WavesTiles3D#WavesTiles3D ret (return value: cc.WavesTiles3D)

--------------------------------
--
-- @function [parent=#WavesTiles3D] update
-- @param self
-- @param #float time

return nil

redpajama_set_name: RedPajamaGithub


text:
class ScrubDatabase
  def self.run!
    User.find_each do |user|
      user.name = "#{user.role.name.downcase.gsub(/[- ]/, '_')}#{user.id}"
      user.fullname = "#{user.id}, #{user.role.name.downcase.gsub(/[- ]/, '_')}"
      user.email = 'expertiza@mailinator.com'
      user.handle = 'handle'
      user.password = 'password'
      # user.password_confirmation = "password"
      user.save(validate: false)
    end
    Participant.find_each do |participant|
      participant.handle = 'handle'
      participant.save(validate: false)
    end
  end
end


text:
package org.ethereum.crypto;

import org.spongycastle.crypto.digests.SHA3Digest;
import org.spongycastle.util.encoders.Hex;

import java.math.BigInteger;

public class SHA3Helper {

    public static final int DEFAULT_SIZE = 256;
    public static final int DEFAULT_SIZE_BYTES = DEFAULT_SIZE / 8;

    public static String sha3String(String message) {
        return sha3String(message, new SHA3Digest(DEFAULT_SIZE), true);
    }

    public static String sha3String(byte[] message) {
        return sha3String(message, new SHA3Digest(DEFAULT_SIZE), true);
    }

    public static byte[] sha3(String message) {
        return sha3(Hex.decode(message), new SHA3Digest(DEFAULT_SIZE), true);
    }

    public static byte[] sha3(byte[] message) {
        return sha3(message, new SHA3Digest(DEFAULT_SIZE), true);
    }

    public static byte[] sha3(byte[] message, Size sz) {
        return sha3(message, new SHA3Digest(sz.bits), true);
    }

    public static byte[] sha3(byte[] m1, byte[] m2) {
        return sha3(m1, m2, new SHA3Digest(DEFAULT_SIZE), true);
    }

    public static byte[] sha3(byte[] message, int start, int length) {
        return sha3(message, start, length, new SHA3Digest(DEFAULT_SIZE), true);
    }

    protected static String sha3String(String message, Size bitSize) {
        SHA3Digest digest = new SHA3Digest(bitSize.bits);
        return sha3String(message, digest, true);
    }

    protected static String sha3String(byte[] message, Size bitSize) {
        SHA3Digest digest = new SHA3Digest(bitSize.bits);
        return sha3String(message, digest, true);
    }

    protected static String sha3String(String message, Size bitSize, boolean bouncyencoder) {
        SHA3Digest digest = new SHA3Digest(bitSize.bits);
        return sha3String(message, digest, bouncyencoder);
    }

    protected static String sha3string(byte[] message, Size bitSize, boolean bouncyencoder) {
        SHA3Digest digest = new SHA3Digest(bitSize.bits);
        return sha3String(message, digest, bouncyencoder);
    }

    private static String sha3String(String message, SHA3Digest digest, boolean bouncyencoder) {
        if (message != null) {
            return sha3String(Hex.decode(message), digest, bouncyencoder);
        }
        throw new NullPointerException("Can't hash a NULL value");
    }

    private static String sha3String(byte[] message, SHA3Digest digest, boolean bouncyencoder) {
        byte[] hash = doSha3(message, digest, bouncyencoder);
        if (bouncyencoder) {
            return Hex.toHexString(hash);
        } else {
            BigInteger bigInt = new BigInteger(1, hash);
            return bigInt.toString(16);
        }
    }

    private static byte[] sha3(byte[] message, SHA3Digest digest, boolean bouncyencoder) {
        return doSha3(message, digest, bouncyencoder);
    }

    private static byte[] sha3(byte[] m1, byte[] m2, SHA3Digest digest, boolean bouncyencoder) {
        return doSha3(m1, m2, digest, bouncyencoder);
    }

    private static byte[] sha3(byte[] message, int start, int length, SHA3Digest digest, boolean bouncyencoder) {
        byte[] hash = new byte[digest.getDigestSize()];

        if (message.length != 0) {
            digest.update(message, start, length);
        }
        digest.doFinal(hash, 0);
        return hash;
    }

    private static byte[] doSha3(byte[] message, SHA3Digest digest, boolean bouncyencoder) {
        byte[] hash = new byte[digest.getDigestSize()];

        if (message.length != 0) {
            digest.update(message, 0, message.length);
        }
        digest.doFinal(hash, 0);
        return hash;
    }

    private static byte[] doSha3(byte[] m1, byte[] m2, SHA3Digest digest, boolean bouncyencoder) {
        byte[] hash = new byte[digest.getDigestSize()];
        digest.update(m1, 0, m1.length);
        digest.update(m2, 0, m2.length);

        digest.doFinal(hash, 0);
        return hash;
    }

    public enum Size {

        S224(224),
        S256(256),
        S384(384),
        S512(512);

        int bits = 0;

        Size(int bits) {
            this.bits = bits;
        }

        public int getValue() {
            return this.bits;
        }
    }

}


text:
'use strict'

// make tests work on Node <1
process.nextTick = require('process.nexttick')

var http     = require('http'),
    EE       = require('events').EventEmitter,
    AE       = require('assert').AssertionError,
    inherits = require('util').inherits,
    test     = require('tap'),
    sse      = require('../')

test.plan(33)

test.type(sse, 'function', 'main export should be a function')
test.type(sse.Broadcaster, 'function', 'constructor should be exposed')
test.equal(sse, sse.Broadcaster, 'constructor should be the main export')
test.type(sse.proto, 'function', 'prototype extender method should be exposed')
test.equal(sse.proto.length, 1, 'prototype extender method should accept one argument')
test.equal(
    sse.version, require(__dirname + '/../package.json').version,
    'package version should be exposed'
)

var server
test.doesNotThrow(
    function () {
         server = sse.Broadcaster()
    },
    '`new` keyword should not be necessary'
)

test.ok(server instanceof sse, '`new` keyword should not be necessary')
test.ok(server instanceof EE, 'server should be an EventEmitter instance')
test.same(server._channels, {}, 'channel lookup object should be empty')
test.same(server.channels, [], 'channel name list should be returned')
test.type(server.subscribe, 'function', 'instance should have a `subscribe()` method')
test.equal(server.subscribe.length, 3, '`subscribe()` method should accept two arguments')
test.type(server.unsubscribe, 'function', 'instance should have a `unsubscribe()` method')
test.equal(server.unsubscribe.length, 2, '`unsubscribe()` method should accept two arguments')
test.type(server.publish, 'function', 'instance should have a `publish()` method')
test.equal(server.publish.length, 4, '`publish()` method should accept four arguments')
test.type(server.send, 'function', 'instance should have a `send()` method')
test.equal(server.send.length, 5, '`send()` method should accept five arguments')
test.type(server.sendEvent, 'function', 'instance should have a `sendEvent()` method')
test.equal(server.sendEvent.length, 5, '`sendEvent()` method should accept five arguments')
test.type(server.subscribers, 'function', 'instance should have a `subscribers()` method')
test.equal(server.subscribers.length, 1, '`subscribers()` method should accept four arguments')
test.type(server.subscriberCount, 'function', 'instance should have a `subscriberCount()` method')
test.equal(server.subscriberCount.length, 1, '`subscriberCount()` method should accept four arguments')
test.type(server.middleware, 'function', 'middleware factory method should be exposed')
test.equal(server.middleware.length, 1, 'middleware factory method should accept one argument')

function noop() {}
function FakeResponse() {
    this.socket = {
        setNoDelay: noop
    }
    this.writeHead = noop
    this.setHeader = noop
    this.write = function (data, encoding, callback) {
        callback()
    }
}
inherits(FakeResponse, http.ServerResponse)

var res  = new FakeResponse,
    res2 = new FakeResponse

test.test('subscriptions', function (test) {
    server.subscribe('test', res)
    test.same(server._channels, { test: [ res ] }, 'subscription should be stored')
    server.subscribe('test', res)
    test.same(server._channels, { test: [ res ] }, 're-subscription should be ignored')
    server.subscribe('test2', res)
    test.same(
        server._channels, { test: [ res ], test2: [ res ] },
        'subscription in a different room should be stored'
    )
    server.subscribe('test', res2)
    test.same(
        server._channels, { test: [ res, res2 ], test2: [ res ] },
        'subscription with a different response should be stored'
    )
    server.unsubscribe('test', {})
    test.same(
        server._channels, { test: [ res, res2 ], test2: [ res ] },
        'unsubscribe with an absent response should not have effect'
    )
    server.unsubscribe('test3', res)
    test.same(
        server._channels, { test: [ res, res2 ], test2: [ res ] },
        'unsubscribe from an absent room should not have effect'
    )
    server.unsubscribe('test', res)
    test.same(
        server._channels, { test: [ res2 ], test2: [ res ] },
        'unsubscribe should remove stored response'
    )
    server.unsubscribe('test2', res)
    test.same(
        server._channels, { test: [ res2 ] },
        'empty room should be removed'
    )
    test.type(server.subscribers('test'), Array, '`subscribers()` must return an array')
    test.same(server.subscribers('test'), [ res2 ], 'a subscriber array should be returned')
    test.same(server.subscribers('absent'), [], 'an empty array should be returned')
    test.equal(server.subscriberCount('test'), 1, 'subscriber count should be returned')
    test.equal(server.subscriberCount('absent'), 0, 'zero should be returned')

    test.end()
})

test.test('warning', function (test) {
    test.plan(3)

    server.on('warning', function (description, response) {
        test.pass('warning event should be emitted if headers are already sent')
        test.equal(description, 'headers are already sent')
        test.equal(response, res2)
    })
    Object.defineProperty(res2, 'headersSent', { value: true, writable: true })
    server.publish('test', 'test')
    res2.headersSent = false
})

test.test('convenience methods', function (test) {
    var proto = http.ServerResponse.prototype

    test.throws(
        function () {
            sse.proto()
        },
        AE, '`proto()` should require an argument'
    )
    test.throws(
        function () {
            sse.proto({})
        },
        AE, '`proto()` should require a broadcaster instance'
    )
    test.doesNotThrow(
        function () {
            sse.proto(server)
        },
        '`proto()` should accept a broadcaster instance'
    )

    test.type(proto.sendEvent, 'function', 'prototype should be extended with `sendEvent()`')
    test.type(proto.sendEvent.length, 4, '`sendEvent()` should accept four arguments')
    test.type(proto.publish, 'function', 'prototype should be extended with `subscribe()`')
    test.type(proto.publish.length, 4, '`publish()` should accept four arguments')
    test.type(proto.subscribe, 'function', 'prototype should be extended with `subscribe()`')
    test.type(proto.subscribe.length, 2, '`subscribe()` should accept two arguments')
    test.type(proto.unsubscribe, 'function', 'prototype should be extended with `unsubscribe()`')
    test.type(proto.unsubscribe.length, 1, '`unsubscribe()` should accept one argument')

    res.unsubscribe('test')
    res2.unsubscribe('test')
    test.same(server._channels, {}, 'unsubscribe via proto methods should work')
    res2.subscribe('test')
    test.same(
        server._channels, { test: [ res2 ] },
        'subscribe via proto methods should work'
    )
    test.throws(
        function () {
            res.publish()
        },
        AE, 'argument count should be asserted'
    )
    test.doesNotThrow(
        function () {
            res.publish('test', 'test')
        },
        'argument count should be asserted'
    )
    test.throws(
        function () {
            res.sendEvent()
        },
        AE, 'argument count should be asserted'
    )
    test.doesNotThrow(
        function () {
            res.sendEvent('test', 'test')
        },
        'argument count should be asserted'
    )

    test.end()
})

test.test('`publish()` signatures', function (test) {
    test.throws(
        function () {
            server.publish()
        },
        AE, '`publish()` should require at least two arguments'
    )
    test.throws(
        function () {
            server.publish('test')
        },
        AE, '`publish()` should require at least two arguments'
    )
    test.throws(
        function () {
            server.publish(true, 'test')
        },
        AE, '`publish()` should require a valid room name'
    )
    test.throws(
        function () {
            server.publish('test', true)
        },
        TypeError, '`publish()` should require a valid event name or options object'
    )
    test.doesNotThrow(
        function () {
            server.publish('test', 'test')
        },
        '`publish()` should accept valid arguments'
    )
    test.doesNotThrow(
        function () {
            server.publish('test', {})
        },
        '`publish()` should accept valid arguments'
    )
    test.doesNotThrow(
        function () {
            server.publish('test', {}, noop)
        },
        '`publish()` should accept valid arguments'
    )
    test.throws(
        function () {
            server.publish('test', {}, {}, noop)
        },
        AE, '`publish()` should not accept both an options and a data argument'
    )
    test.doesNotThrow(
        function () {
            server.publish('test', 'test', {})
        },
        '`publish()` should accept valid arguments'
    )
    test.doesNotThrow(
        function () {
            server.publish('test', 'test', {}, noop)
        },
        '`publish()` should accept valid arguments'
    )
    test.doesNotThrow(
        function () {
            server.publish('test', 'test', 'test', noop)
        },
        '`publish()` should accept valid arguments'
    )
    test.doesNotThrow(
        function () {
            server.publish('test', 'test', new Buffer('test'), noop)
        },
        '`publish()` should accept valid arguments'
    )

    function onerror(err) {
        test.pass('error handler should be called')
        test.type(err, Error)
    }
    var circular = {}
    circular.test = circular
    server.once('error', onerror)
    test.doesNotThrow(
        function () {
            server.publish('test', 'test', circular)
        },
        'an error event should be emitted'
    )
    server.once('error', onerror)
    test.doesNotThrow(
        function () {
            server.publish('test', { data: circular })
        },
        'an error event should be emitted'
    )
    test.doesNotThrow(
        function () {
            // note: must add an error handler to prevent EventEmitter to throw,
            // because we used `once()` in the previous test
            server.once('error', noop)
            server.publish('test', 'test', circular, onerror)
        },
        'callback should be fired with an error'
    )

    // note: `publish()` always fires the callback asynchronously
    process.nextTick(test.end.bind(test))
})

test.test('middleware factory', function (test) {
    test.throws(
        function () {
            server.middleware()
        },
        AE,
        'middleware factory argument should be asserted'
    )
    test.throws(
        function () {
            server.middleware(true)
        },
        TypeError,
        'middleware factory argument should be asserted'
    )
    test.throws(
        function () {
            server.middleware({})
        },
        AE,
        'middleware factory argument should be asserted'
    )
    test.throws(
        function () {
            server.middleware({ test: 42 })
        },
        TypeError,
        'middleware factory argument should be asserted'
    )
    test.throws(
        function () {
            server.middleware({ query: 'a', body: 'b' })
        },
        AE,
        'middleware factory argument should be asserted'
    )
    test.doesNotThrow(
        function () {
            server.middleware({ param: 'a' })
        },
        'middleware factory should accept valid arguments'
    )
    test.type(server.middleware({ param: 'a' }), 'function', 'middleware factory should return a function')

    test.end()
})

test.test('chaining', function (test) {
    test.equal(res.publish('test', 'test'), res, '`res.publish()` should be chainable')
    test.equal(res.subscribe('test'), res, '`res.subscribe()` should be chainable')
    test.equal(res.unsubscribe('test'), res, '`res.unsubscribe()` should be chainable')

    test.equal(sse.proto(server), server, '`proto()` should be chainable')
    test.equal(server.publish('test', 'test'), server, '`publish()` should be chainable')
    test.equal(server.subscribe('test', res), server, '`subscribe()` should be chainable')
    test.equal(server.unsubscribe('test', res), server, '`unsubscribe()` should be chainable')

    test.end()
})


text:
Troubleshooting
===============

.. toctree::
    :maxdepth: 1

    self_verification
    common_troubleshooting
    submit_debug_info
    ask_for_support


text:
A powerful, flexible, easy to use and Fully Featured ASP .NET CMS

To view the complete developer guide click here: https://github.com/MacdonaldRobinson/FlexDotnetCMS/raw/master/WebApplication/Admin/media/docs/FlexDotnetCMSGuide.docx

## Demo Site ##
- **URL**: http://flexdotnetcms.somee.com/
- **Base Headless Api Url**: http://flexdotnetcms.somee.com/?format=json

- **CMS Login URL**: http://flexdotnetcms.somee.com/admin/
	- **Username:** test_dev
	- **Password:** test_password

## Automatic Single Page App / Universal App with SSR ( Server Side Rendering )
- Automatic Single Page App functionality with SSR via the Single Page App library that I built ( https://github.com/MacdonaldRobinson/jquery-spa )
- Since the pages are rendred Server Side, you do not lose any of the functionality offered by the CMS like frontend editing / dynamic nav generation based on the site tree in the CMS.
- Since the pages are rendered Server Side on the first request, you dont run into any SEO issues as you would in a classic SPA ( This is similar to how NuxtJS works )
- You can even use other frontend libraries like VueJS as a javascript include to enhance form submissions etc and it works well with the built in SPA library.

## Automatic Image Optimization
- The Framework automaticly optimizes ALL image requestes using the Image Processor Library ( https://imageprocessor.org/imageprocessor-web/imageprocessingmodule/quality/ )

## Automatic Google Site Map Generator
- I built a Google Site Map Generator that is dynamicly updated based on the changes in the CMS, the site map generator is automaticly called from the robots.txt file, so you dont even need to submit your site map.

## Automatic RSS and JSON Generator
- I built a RSS generator and a JSON generator which are dynamicly generated based on changes in the CMS
  - You can call the RSS generator by simply adding "?format=rss" at the end of any URL
  - You can call the JSON generator by simply adding "?format=json" at the end of any URL ( This doubles as the Headless CMS API )

## Decoupled CMS
- The CMS is only used to house content
- You can easily pull CMS content into your cshtml files, please scroll down to the section labeled ( Example showing how you can pull content from the CMS from a cshtml file )

## Headless CMS
- Comes with a API that allows you to load content via AJAX which means you can use the CMS as a Headless CMS ( Simply add "?format=json" at the end of the URL of any page an that will return a JSON representation of all the fields, incluiding the custom fields that you have created in the CMS )

## Static File Generator
- The CMS is also a Static File Generator which builds static pages and stores them in the Cache folder, and then on every other request it loads the page via cache making the performance extremely fast ( Please view the Cache section below to see how caching works )
  - Please note that these static files are dynamicly generated on the first request of the page, and are then re-generated based on changes made in the CMS, so there is no need of a build  and deployment process

## Works side by side with other SPA Javascript Frameworks like React / Vue / Angular
- If you prefer to not use the built in SPA library, you could use any other javascript framework and place it in the "Frontend" folder, the only thing you need to do is to make sure that you are loading the index page for all virtual page requests.
  - You can do this from the CMS by changing the code in the Layouts section for every template to load the index file {IncludeFile:'/Frontend/PATH_TO_INDEX_FILE'}
- You can then use the CMS has a Headless CMS and load content via the API
- This gives you the benefit of having only one host hosting both your frontend and backend systems.

## Editing
- FrontEnd Editing: Every field can be edited from the frontend of the website
- Visual Layout Editor ( Experimental ): Once logged into the cms and browsing the frontend of the website, you can toggle the visual layout editor, which allows you to create, delete, reorder the rows, columns and fields
- Every time you save a page in the CMS it will automatically create a history version which you can then reload and publish LIVE again.
- The HTML structure of the page and the Content of the page are clearly seperated and both the Content and the HTML structure for the page can be edited directly in the CMS, there is no need to use a 3rd party editor or to use FTP, this speeds up the time it takes to make changes on the website.
  - Since the HTML structure and the content are clearly seperated you do not need to worry about having the client change any of the HTML structure.
- Ability to create custom fields with their own unique layouts. You can create new Fields in the CMS directly, no need to hardcode anything in the code behind. The CMS comes with several field types already prebuilt, so you do not even need to know programming inorder to add new fields, however if you do know programming ( Razor Engine Code ) you can program it to do anything you like, you have complete freedom over the HTML that is generated.
- Ability to modify the layout of all pages with a specific page type or unlink from a page type and create a unique layout for every page. Every page in the CMS has a type, so you can either have it so that it would use the style of the page type, or have it so that it has its own unique layout.
- When you edit content and save it you can see how it looks right away in the browser panel instead of having to open a new window and browse to the page
- You can resize the browser panel and see how the site looks in different sizes i.e test responsive layout directly through the cms
- You can create draft versions for pages which you can reload and edit at anytime
  - You will also get a visual indicator in the site tree besides pages that have a draft version.
  - The following indicators exist: "Will Publish", "Will Expire", "UnPublished", "HasDraft" along with a clock besides them if they are set to auto publish / auto expire

## Programming
- Programming in the CMS is done using C# and using the Razor Syntax
- Code is compiled and run on the fly using Razor Engine ( http://antaris.github.io/RazorEngine/ )
- You have access to the entire framework code, so you can pretty much do anything
- There are several Database Mappers and Helpers that are included with the framework.
- You can write Razor Code in any of the layout views in the CMS
- You can use short codes in any of the layout tabs and fields
- You can automatically execute some razor code when a page is published in the CMS by putting the code in the "On Publish Execute Code" Accordian tab under the Layouts tab for an individual page, or if you want to have the same code execute for all pages of the same type you can put this in the media type layouts section.

**Instead of programming directly in the CMS you can use an include ShortCode "{IncludeFile:'[Path-To-File]'}" which allows you to load a cshtml file, which will be executed at runtime, without any build process, kinda makes your workflow similar to PHP, simply make your change and refresh the page.**

*You will get full intellisence and code completion support when using Visual Studio*

## Multi Language
- You can create as many languages in the CMS as you like.
- Ability to add new languages to each page with ease: You can simply browse to a page and then switch the language and save and publish and your done, you have now created a new language version of the page.

## Publishing
- Ability to automatically publish a page live at a specified date time
- Ability to automatically take down a page at a specified date time
- Ability to save as draft, you can come back and make changes to the draft page later, you can even send links to the draft version of the page inorder to get approval, and then push the page LIVE once you are done.
  - You can also set the draft version to automaticly get pushed live at a specified date time.

## SEO
- All pages automaticly get a search engine friendly URL, you have the ability to change the uri segment for the page from the CMS
- Ability to change the SEO for every page: Page title, Meta Description, Meta Keywords, Meta Robots, Link title ( Url Segment for the page )
- Ability to create 301 or 302 redirects. You can create your own url redirect rules, you can have it so that /oldpage is redirected to /about/contact/

## Caching
- You have 3 levels of caching: Memory Caching, File System Caching and Redis Caching
- You have control over caching of pages. If you have set all pages to cache, the first time a visitor visits the page, it will generate a cache for that page and the next time the request will load from cache, drasticly speeding up performance.
- If the page is cached then it bypasses the database connection all together making the load time extreamly fast.
- If you have the page cached and there is an error connecting to the database, the system will attempt to load that page from cache if it exists.
- You have the ability to clear the cache of an individual page.
- Ability to clear all cache

## Roles and Permissions
- Ability to Manage Users and Roles
- Ability to limit access to a page or a page type ( role based ). Only people that belong to the role can access these pages in the CMS
- Ability to automatically propigate role limitations to all child pages.
- You can enforce the role limitations in the frontend as well, so you need to be logged in with appropriate credentials inorder to view these pages in the frontend.

## Admin Tools
- Database Compare Tool: Allows you to compare 2 environments to see what has changed i.e New Pages, New Fields, Different Content  etc.
  - NOTE: This will only work if the 2 environments have the same database schema.
- Database Backup and Restore Tool: Allows you to backup the current database to a folder and displays a list of all backed up files, you can then restore from a backup file.
  - NOTE: This only works if both the web application and the database are on the same server.
- You can view the email logs from the CMS ( provided the emails were sent using the system its self )
- You can view the error logs from the CMS

## Additional Functionality  / Features
- Built in Blog functionality, including moderated blog posts
- Built in File Manager with the following functionality:
  - Ability to create, rename and delete folders
  - Ability to create, rename, preview and open files in a new window
  - Ability to move files and folders around by dragging and dropping files and folders onto other folders
- Ability to Add / Edit / Delete Glossary terms.
- Ability to Create, Edit, Delete/Recover, Permanently Delete, Hide/Show, Duplicate and Publish/unpublish pages
- Ability to search for a page based on any field value in the backend for quick access
- Several prebuilt field types are included which should sute most use cases.
- Code completion examples are provided to get started with programming in the Layouts tab using C# and the Razor Code syntax.

## Example showing how you can pull content from the CMS from a cshtml file
You will get full intellisence and code completion support when using Visual Studio

```html
@using FrameworkLibrary
@{
	var currentPage = Model.MediaDetail as MediaDetail;
	var referencesField = currentPage.LoadField("References");

	if (referencesField != null && !string.IsNullOrEmpty(referencesField.FieldValue))
	{
		var content = currentPage.RenderField("References");
		<p>@content</p>
	}

	var resourcesField = (MediaDetailField)currentPage.LoadField("Resources");

	if (resourcesField != null && resourcesField.FieldAssociations.Any())
	{
		<div>
			<h2>Resources</h2>
			<div class="resources__cards">
			@foreach (var fieldsAssociation in resourcesField.FieldAssociations)
			{
				var sectionTitle = fieldsAssociation.MediaDetail.SectionTitle;
				var briefDescription = fieldsAssociation.MediaDetail.RenderField("BriefDescription", false);
				var websiteAddress = fieldsAssociation.MediaDetail.RenderField("WebsiteAddress", false);

					<a href="@websiteAddress">
						<div></div>
						<div>
							<div>
								<h4>@sectionTitle</h4>
							</div>
							@Raw(briefDescription)
						</div>
						<div>
							<span>View Resource</span>
						</div>
					</a>
			}
			</div>
		</div>
	}
}

```


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/add_source"
        android:icon="@drawable/add"
        android:showAsAction="ifRoom"
        android:title="@string/addFileSource">
    </item>

</menu>


text:
/* jshint ignore:start */
import Ember from 'ember';

export default Ember.Component.extend({
  drawVendorMap: Ember.on('init', async function() {
    try {
      let geo = await this.geoGoogleService.getGeoposition();
      this.geoGoogleService.drawMap(geo, 'mapfeed');
      this.get('vendors').forEach(vendor => this.geoGoogleService.createMarker(vendor.get('location')));
    } catch (err) {
      Ember.get(this, 'flashMessages').error(err);
    }
  })
});
/* jshint ignore:end */


text:
if Rails.env == 'production'
  secret_key_base = ENV['SECRET_KEY_BASE']
else
  secret_key_base = '123456789012345678901234567890'
end
SmalrubyEditor::Application.config.secret_key_base = secret_key_base


text:
package com.arpnetworking.tsdcore.model;

import com.arpnetworking.tsdcore.statistics.Statistic;
import com.arpnetworking.utility.OvalBuilder;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import net.sf.oval.constraint.NotNull;
import org.joda.time.DateTime;
import org.joda.time.Period;

import java.util.Map;

/**
 * Fully qualified statistic name. This uniquely describes any statistic
 * or computed value in the system. In the hypercube that is any metric
 * the statistic is the specification of a point in each dimension and thus
 * identification of a single value. The FQSN is composed of the cluster name,
 * service name, metric name, period, period start, host and statistical
 * operator.
 *
 * In the future the FQSN will also include any user specified dimensions.
 * service name, metric name, statistic, period, period start and any
 * dimensions.
 *
 * @author Ville Koskela (vkoskela at groupon dot com)
 */
public final class FQSN {

    /**
     * Return the fully qualified data space name portion of the fully
     * qualified statistic name.
     *
     * @return Fully qualified data space name portion.
     */
    public FQDSN toFQDSN() {
        return _fqdsn;
    }

    public String getMetric() {
        return _fqdsn.getMetric();
    }

    public String getService() {
        return _fqdsn.getService();
    }

    public String getCluster() {
        return _fqdsn.getCluster();
    }

    public Statistic getStatistic() {
        return _fqdsn.getStatistic();
    }

    public Period getPeriod() {
        return _period;
    }

    public DateTime getStart() {
        return _start;
    }

    /*
    // TODO(vkoskela): Enable dimensions. [MAI-449]
    public Map<String, String> getDimensions() {
        return Collections.unmodifiableMap(_dimensions);
    }
    */

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(final Object object) {
        if (this == object) {
            return true;
        }
        if (object == null || getClass() != object.getClass()) {
            return false;
        }

        final FQSN other = (FQSN) object;

        return Objects.equal(_fqdsn, other._fqdsn)
                && Objects.equal(_period, other._period)
                && Objects.equal(_start, other._start);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        return Objects.hashCode(
                _fqdsn,
                _period,
                _start);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("id", Integer.toHexString(System.identityHashCode(this)))
                .add("FQDSN", _fqdsn)
                .add("Period", _period)
                .add("Start", _start)
                .add("Dimensions", _dimensions)
                .toString();
    }

    private FQSN(final Builder builder) {
        _fqdsn = builder._fqdsn.build();
        _period = builder._period;
        _start = builder._start;
        _dimensions = builder._dimensions;
    }

    private final FQDSN _fqdsn;
    private final Period _period;
    private final DateTime _start;
    private final Map<String, String> _dimensions;

    /**
     * Implementation of builder pattern for FQSN.
     *
     * @author Ville Koskela (vkoskela at groupon dot com)
     */
    public static final class Builder extends OvalBuilder<FQSN> {

        /**
         * Public constructor.
         */
        public Builder() {
            super(FQSN.class);
        }

        /**
         * The full qualified data space name. This sets the cluster, service,
         * metric and statistic. Cannot be null.
         *
         * @param value The fully qualified metric name.
         * @return This instance of Builder.
         */
        public Builder fromFQDSN(final FQDSN value) {
            setCluster(value.getCluster());
            setService(value.getService());
            setMetric(value.getMetric());
            setStatistic(value.getStatistic());
            return this;
        }

        /**
         * The cluster. Cannot be null or empty.
         *
         * @param value The cluster.
         * @return This instance of Builder.
         */
        public Builder setCluster(final String value) {
            _fqdsn.setCluster(value);
            return this;
        }

        /**
         * The service. Cannot be null or empty.
         *
         * @param value The service.
         * @return This instance of Builder.
         */
        public Builder setService(final String value) {
            _fqdsn.setService(value);
            return this;
        }

        /**
         * The metric. Cannot be null or empty.
         *
         * @param value The metric.
         * @return This instance of Builder.
         */
        public Builder setMetric(final String value) {
            _fqdsn.setMetric(value);
            return this;
        }

        /**
         * The Statistic instance. Cannot be null.
         *
         * @param value The Statistic instance.
         * @return This instance of Builder.
         */
        public Builder setStatistic(final Statistic value) {
            _fqdsn.setStatistic(value);
            return this;
        }

        /**
         * The period. Cannot be null.
         *
         * @param value The period.
         * @return This instance of Builder.
         */
        public Builder setPeriod(final Period value) {
            _period = value;
            return this;
        }

        /**
         * The period start. Cannot be null.
         *
         * @param value The period start.
         * @return This instance of Builder.
         */
        public Builder setStart(final DateTime value) {
            _start = value;
            return this;
        }

        /**
         * The dimensions. Optional. Cannot be null. Default is an empty
         * Map.
         *
         * @param value The dimensions.
         * @return This instance of Builder.
         */
        /*
        // TODO(vkoskela): Enable dimensions. [MAI-449]
        public Builder setDimensions(final Map<String, String> value) {
            _dimensions = Maps.newHashMap(value);
            return this;
        }
        */

        /**
         * Add dimension. Optional. Cannot be null. Default is an empty
         * Map.
         *
         * @param dimension The dimension.
         * @param value The value .
         * @return This instance of Builder.
         */
        /*
        // TODO(vkoskela): Enable dimensions. [MAI-449]
        public Builder addDimension(final String dimension, final String value) {
            if (_dimensions == null) {
                _dimensions = Maps.newHashMap();
            }
            _dimensions.put(dimension, value);
            return this;
        }
        */

        @NotNull
        private FQDSN.Builder _fqdsn = new FQDSN.Builder();
        @NotNull
        private Period _period;
        @NotNull
        private DateTime _start;
        @NotNull
        private Map<String, String> _dimensions = Maps.newHashMap();
    }
}


text:
void test01()
{
  using namespace __gnu_test;
  time_counter time;
  resource_counter resource;

  start_counters(time, resource);
  for (unsigned i = 0; i < 200000; ++i)
    {
      std::string a;
      for (unsigned j = 0; j < 400; ++j)
	a.append(1, 'x');
    }
  stop_counters(time, resource);

  report_performance(__FILE__, "", time, resource);
  clear_counters(time, resource);
}

int main()
{
  test01();
  return 0;
}


text:
.lang-fi {
  display: none;
}

.lang-fi-hidden, .lang-en-hidden {
  display: none;
}

A.langmenu-fi-selected, A.langmenu-en-selected {
  font-weight: bold;
  text-decoration: none;
  color: black;
}

.langmenu-fi, .langmenu-en {

}


text:
<?php

namespace Symfony\Component\Intl\Data\Bundle\Reader;

use Symfony\Component\Intl\Data\Util\RingBuffer;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @internal
 */
class BufferedBundleReader implements BundleReaderInterface
{
    private $reader;
    /** @var RingBuffer<string, mixed> */
    private $buffer;

    /**
     * Buffers a given reader.
     *
     * @param int $bufferSize The number of entries to store in the buffer
     */
    public function __construct(BundleReaderInterface $reader, int $bufferSize)
    {
        $this->reader = $reader;
        $this->buffer = new RingBuffer($bufferSize);
    }

    /**
     * {@inheritdoc}
     */
    public function read(string $path, string $locale)
    {
        $hash = $path.'//'.$locale;

        if (!isset($this->buffer[$hash])) {
            $this->buffer[$hash] = $this->reader->read($path, $locale);
        }

        return $this->buffer[$hash];
    }
}


text:
typedef NS_ENUM(NSInteger, UIImageViewURLDownloadState) {
    UIImageViewURLDownloadStateUnknown = 0,
    UIImageViewURLDownloadStateLoaded,
    UIImageViewURLDownloadStateWaitingForLoad,
    UIImageViewURLDownloadStateNowLoading,
    UIImageViewURLDownloadStateFailed,
};

@interface UIView (XHRemoteImage)

// url
@property (nonatomic, strong) NSURL *url;

// download state
@property (nonatomic, readonly) UIImageViewURLDownloadState loadingState;

//
@property (nonatomic, assign) XHMessageAvatarType messageAvatarType;

// UI
@property (nonatomic, strong) UIView *loadingView;
// Set UIActivityIndicatorView as loadingView
- (void)setDefaultLoadingView;

// instancetype
+ (id)imageViewWithURL:(NSURL *)url autoLoading:(BOOL)autoLoading;

// Get instance that has UIActivityIndicatorView as loadingView by default
+ (id)indicatorImageView;
+ (id)indicatorImageViewWithURL:(NSURL *)url autoLoading:(BOOL)autoLoading;

// Download
- (void)setImageWithURL:(NSURL *)url;
- (void)setImageWithURL:(NSURL *)url placeholer:(UIImage *)placeholerImage;
- (void)setImageWithURL:(NSURL *)url placeholer:(UIImage *)placeholerImage showActivityIndicatorView:(BOOL)show;
- (void)setImageWithURL:(NSURL *)url placeholer:(UIImage *)placeholerImage showActivityIndicatorView:(BOOL)show completionBlock:(void(^)(UIImage *image, NSURL *url, NSError *error))handler;

- (void)setImageUrl:(NSURL *)url autoLoading:(BOOL)autoLoading;
- (void)load;

@end


text:
@interface THTransitionViewController ()
@property (strong, nonatomic) THVideoTransition *transition;
@property (strong, nonatomic) NSArray *transitionTypes;
@end

@implementation THTransitionViewController

+ (id)controllerWithTransition:(THVideoTransition *)transition {
	return [[self alloc] initWithTransition:transition];
}

- (id)initWithTransition:(THVideoTransition *)transition {
	self = [super initWithStyle:UITableViewStylePlain];
	if (self) {
		_transition = transition;
		self.transitionTypes = @[@"Dissolve", @"Push", @"Wipe"];
		self.tableView.showsVerticalScrollIndicator = NO;
        self.tableView.separatorInset = UIEdgeInsetsZero;
        self.tableView.scrollEnabled = NO;
	}
	return self;
}

- (CGSize)preferredContentSize {
	return CGSizeMake(200, 140);
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.transitionTypes.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *cellID = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
	if (!cell) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
	}

    NSString *type = self.transitionTypes[indexPath.row];
	cell.textLabel.text = type;
    if (self.transition.type == [self transitionTypeFromString:type]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

	return cell;
}

#pragma mark - Table view delegate

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSIndexPath *currentIndexPath = [tableView indexPathForSelectedRow];
	if (![currentIndexPath isEqual:indexPath]) {
		[self.tableView deselectRowAtIndexPath:currentIndexPath animated:YES];
	}
	return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSString *type = self.transitionTypes[indexPath.row];
    self.transition.type = [self transitionTypeFromString:type];
    [self.tableView reloadData];
	[self.delegate transitionSelected];
}

- (THVideoTransitionType)transitionTypeFromString:(NSString *)type {
	if ([type isEqualToString:@"Dissolve"]) {
        return THVideoTransitionTypeDissolve;
	} else if ([type isEqualToString:@"Push"]) {
		return  THVideoTransitionTypePush;
	} else {
        return THVideoTransitionTypeWipe;
    }
}

@end


text:
0.6.0 / 2015-10-05
==================

  * use faster API methods: users.list to get presence
  * fix polling interval increase
  * allow hosting slackin under a path (eg: /slack)
  * fix for deployment instructions
  * add already registered link
  * use SLACK_CHANNELS instead of SLACK_CHANNEL on Heroku
  * standardize use of example host
  * allow hosting at a subfolder

0.5.1 / 2015-06-23
==================

  * added safety check for channels.
  * fix counting deleted users

0.5.0 / 2015-05-07
==================

  * allow for multiple guest channels [afeld]
  * add important notes to README
  * better error handling and tests [afeld]
  * add Slack favicon and better title [frabrunelle]
  * error when the token account is not an admin [martypenner]
  * added Dockerfile [darron]

0.4.0 / 2015-04-10
==================

 * use SVG Heroku button
 * fixed svg dimensions issues
 * exclude bots (and slackbot) from users count
 * improve mobile zoom
 * use `<input type="email">`
 * fix for single-channel guests invitation parameter name

0.3.1 / 2015-03-16
==================

 * fix meta tags for mobile support

0.3.0 / 2015-03-06
==================

 * update `babel`, fix all scenarios

0.2.9 / 2015-03-03
==================

 * package: bump `socket.io`

0.2.8 / 2015-02-03
==================

 * bump socket.io

0.2.7 / 2015-02-02
==================

 * support for custom css

0.2.6 / 2015-02-01
==================

 * fix issue with 6to5 and `-g install`

0.2.5 / 2015-02-01
==================

 * fix single channel invites to be ultra restricted

0.2.4 / 2015-02-01
==================

 * bump 6to5

0.2.3 / 2015-02-01
==================

 * fixed heroku button

0.2.2 / 2015-01-30
==================

 * fixed ability to `require('slackin')`

0.2.1 / 2015-01-30
==================

 * improved startup speed by leveraging pre-compilation

0.2.0 / 2015-01-30
==================

 * improved CLI interface [buildkite]
 * support for ENV vars [buildkite]
 * deploy to heroku button [buildkite]

0.1.2 / 2015-01-28
==================

 * fix bin name [brianloweswords]

0.1.1 / 2015-01-26
==================

 * fix typo

0.1.0 / 2015-01-26
==================

 * initial release


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Michelia 1(no. 2): 148 (1878)

#### Original name
Phyllosticta ailanthi Sacc.

### Remarks
null


text:
openstack-ansible
=================

Ansible roles for OpenStack ( support only RHEL6 now )


text:
{-# LANGUAGE FlexibleInstances #-}

module FindUnit where

import Unit
import Monad.Analysis
import Control.Monad
import Control.Monad.Extra
import Language.C.Pretty
import Language.C.Data.Ident
import Language.C.Data.Position
import Language.C.Syntax.Constants
import Language.C.Syntax.AST

class FindUnit a where
    findUnit :: a -> Analysis (Maybe Unit)

instance FindUnit Unit where
    findUnit u = return (Just u)

instance FindUnit CDeclr where
    findUnit declr =
        case declr of
          CDeclr _ _ _ attrs _ -> findUnit attrs

instance FindUnit CAttr where
    findUnit attr =
        case attr of
          CAttr (Ident "unit" _ _) [e] _ -> parseCExprAsUnit e
          _ -> return Nothing

parseCExprAsQ :: CExpr -> Analysis (Maybe Q)
parseCExprAsQ expr =
    case expr of
      CConst (CIntConst (CInteger i _ _) _) -> return (Just (toRational i))
      CUnary CNegOp e _ ->
          do u <- parseCExprAsQ e
             return (liftM negate u)
      CBinary CAddOp e1 e2 _ ->
          do u1 <- parseCExprAsQ e1
             u2 <- parseCExprAsQ e2
             return (liftM2 (+) u1 u2)
      CBinary CSubOp e1 e2 _ ->
          do u1 <- parseCExprAsQ e1
             u2 <- parseCExprAsQ e2
             return (liftM2 (-) u1 u2)
      CBinary CMulOp e1 e2 _ ->
          do u1 <- parseCExprAsQ e1
             u2 <- parseCExprAsQ e2
             return (liftM2 (*) u1 u2)
      CBinary CDivOp e1 e2 _ ->
          do u1 <- parseCExprAsQ e1
             u2 <- parseCExprAsQ e2
             return (liftM2 (/) u1 u2)
      _ -> do err expr ("Can't parse expression as power: " ++ show (pretty expr))
              return Nothing

parseCExprAsUnit :: CExpr -> Analysis (Maybe Unit)
parseCExprAsUnit expr =
    case expr of
      CBinary CMulOp e1 e2 _ ->
          do u1 <- parseCExprAsUnit e1
             u2 <- parseCExprAsUnit e2
             return (liftM2 Unit.mul u1 u2)
      CBinary CDivOp e1 e2 _ ->
          do u1 <- parseCExprAsUnit e1
             u2 <- parseCExprAsUnit e2
             return (liftM2 Unit.div u1 u2)
      CVar (Ident name _ _) _ -> return (Just (Unit.fundamental name))
      CConst (CIntConst (CInteger 1 _ _) _) -> return (Just Unit.one)
      CCall (CVar (Ident name _ _) _) [e] _ | elem name ["sqrt", "sqrtf", "sqrtl"] ->
          do u <- parseCExprAsUnit e
             return (fmap Unit.sqrt u)
      _ -> do err expr ("Can't parse expression as unit: " ++ show (pretty expr))
              return Nothing

instance FindUnit CDeclSpec where
    findUnit declSpec =
        case declSpec of
          CStorageSpec _ -> return Nothing
          CTypeSpec typeSpec -> findUnit typeSpec
          CTypeQual typeQual -> findUnit typeQual
          CFunSpec funSpec -> return Nothing
          CAlignSpec alignSpec -> return Nothing

instance FindUnit CTypeSpec where
    findUnit typeSpec =
        case typeSpec of
          CVoidType _ -> return Nothing
          CCharType _ -> return Nothing
          CShortType _ -> return Nothing
          CIntType _ -> return Nothing
          CLongType _ -> return Nothing
          CFloatType _ -> return Nothing
          CDoubleType _ -> return Nothing
          CSignedType _ -> return Nothing
          CUnsigType _ -> return Nothing
          CBoolType _ -> return Nothing
          CComplexType _ -> return Nothing
          CSUType _ _ -> return Nothing
          CEnumType _ _ -> return Nothing
          CTypeDef _ident _ ->
              do err typeSpec "typedef type specifiers not yet handled"
                 return Nothing
          CTypeOfExpr _e _ ->
              do err typeSpec "typeof(expr) type specifiers not yet handled"
                 return Nothing
          CTypeOfType _t _ ->
              do err typeSpec "typeof(type) type specifiers not yet handled"
                 return Nothing
          CInt128Type _ -> return Nothing
          CFloatNType _ _ _ -> return Nothing
          CAtomicType _ _ -> do err typeSpec "_atomic(type) type specifiers not yet handled"
                                return Nothing

instance FindUnit CTypeQual where
    findUnit typeQual =
        case typeQual of
          CConstQual _ -> return Nothing
          CVolatQual _ -> return Nothing
          CRestrQual _ -> return Nothing
          CAttrQual attr -> findUnit attr
          CAtomicQual _ -> return Nothing
          CNullableQual _ -> return Nothing
          CNonnullQual _ -> return Nothing
          CClRdOnlyQual _ -> return Nothing
          CClWrOnlyQual _ -> return Nothing

instance FindUnit a => FindUnit (Maybe a) where
    findUnit m =
        case m of
          Just a -> findUnit a
          Nothing -> return Nothing

instance FindUnit a => FindUnit [a] where
    findUnit list =
        do units <- mapMaybeM findUnit list
           case units of
             [] -> return Nothing
             [u] -> return (Just u)
             us -> do err nopos ("Conflicting units: " ++ show us)
                      return Nothing


text:
'use strict';

function parseDate( date ) {
   var dy = new Date(date).getFullYear();
   var dm = new Date(date).getMonth() + 1;
   var dd = new Date(date).getDate();

   return dy + '-' + ( ( dm >= 1 && dm <= 9 ) ? '0' + dm : dm ) + '-' + ( ( dd >= 1 && dd <= 9 ) ? '0' + dd : dd );
}

function parseContractData( data, i ) {
   var obj = {};

   obj.title = data[i].title;
   obj.funded = data[i].funded;
   obj.PI = data[i].PI;

   obj.startDate = parseDate(data[i].startDate);
   obj.endDate = parseDate(data[i].endDate);

   obj.fundingAgency = data[i].fundingAgency;
   obj.fundingPortion = data[i].fundingPortion;
   obj.value = data[i].value;

   obj.id = data[i]._id;

   return obj;
}

angular.module('reports').controller('Section15Controller', ['$scope', '$http', '$stateParams', '$location', 'Authentication',
	function($scope, $http, $stateParams, $location, Authentication ) {
		$scope.authentication = Authentication;

		//variable for section 15 to initialize the table
		$scope.incomplete = false;
      $scope.hideTable = false;

      $scope.total = 0;

      $http.get('/reports/' + $stateParams.reportId + '/contracts').
         success(function(data, status, headers, config) {
            var obj = [];

            for (var i=0; i<data.length; i++) {
               obj[i] = parseContractData(data, i);
               $scope.total += data[i].fundingPortion;
            }

            $scope.obj = obj;
         }).
         error(function(data, status, headers, config) {
            console.log('There was an error in getting report');
         });

      $scope.create = function() {
         $http.post('/reports/' + $stateParams.reportId + '/contracts', {
            contracts: {
               title: $scope.title,
               funded: $scope.funded,
               PI: $scope.PI,
               startDate: $scope.startDate,
               endDate: $scope.endDate,
               fundingAgency: $scope.fundingAgency,
               fundingPortion: $scope.fundingPortion,
               value: $scope.value
            }
         }).
         success(function(data, status, headers, config) {
            $scope.total = $scope.total + $scope.fundingPortion;

            $scope.obj.push(parseContractData([data], 0));
            $scope.title = '';
            $scope.funded = '';
            $scope.PI = '';
            $scope.startDate = '';
            $scope.endDate = '';
            $scope.fundingAgency = '';
            $scope.fundingPortion = '';
            $scope.value = '';

            alert('Created!');
         }).
         error(function(data, status, headers, config) {
            console.log('There was an error in creating the report: ');
            console.log(data);
         });
      };

      $scope.update = function( id, i ) {
         $http.put('/contracts/' + id, {
            contracts: {
               title: $scope.obj[i].title,
               funded: $scope.obj[i].funded,
               PI: $scope.obj[i].PI,
               startDate: $scope.obj[i].startDate,
               endDate: $scope.obj[i].endDate,
               fundingAgency: $scope.obj[i].fundingAgency,
               fundingPortion: $scope.obj[i].fundingPortion,
               value: $scope.obj[i].value
            }
         }).
         success(function(data, status, headers, config) {
            alert('updated');
         }).
         error(function(data, status, headers, config) {
            console.log('There was an error in updating the report');
         });
      };

      $scope.delete = function( id, i ) {
         $http.delete('/contracts/' + id).
         success(function(data, status, headers, config) {
            $scope.obj.splice(i, 1); //remove from the DOM
            alert('deleted');
         }).
         error(function(data, status, headers, config) {
            console.log('There was an error in deleting the report');
         });
      };
    /*
      //Function to look for changes that are happening in the Grants object.
      $scope.$watch('grants.titleOfGrant',function(){$scope.test();});
      $scope.$watch('grants.fundingAgency',function() {$scope.test();});
      $scope.$watch('grants.PI',function() {$scope.test();});
      $scope.$watch('grants.value',function() {$scope.test();});
      $scope.$watch('grants.startEnd',function() {$scope.test();});

       //to watch whether these strings are empty, in order to check for completion of forms to enable button
      $scope.test = function() {
         $scope.incomplete = true;
         $scope.incomplete = false;
         if($scope.grants.value <= 0 || !$scope.grants.titleOfGrant.length||!$scope.grants.fundingAgency.length||!$scope.grants.PI.length||!$scope.grants.startEnd.length){
            $scope.incomplete = true;
         }
      }; */
   }
]);


text:
To reproduce our Wall Street Journal (WSJ) experiments, please follow the
instructions below. All the steps should be done at the kaldi WSJ recipe
[directory](https://github.com/kaldi-asr/kaldi/tree/master/egs/wsj/s5)
(or you can add symlinks to all the files (`local`, `steps`, `utils`, etc)
as some people do). In order to perform steps 1, 2, 5 you should source
`path.sh` file from the recipe before you sourced `$LVSR/env.sh`.

### Note
Check that `$LVSR` environment variable points to this repository and
`$LD_LIBRARY_PATH` includes a path to openfst library.

## Steps
1. Compile a Fuel-compatible dataset file in HDF5 format. This step requires
   kaldi and kaldi-python.

   First, run prepare data part from the WSJ recipe. You'll get all
   `*.scp` files which link waves and text.

   Then, run
   ```
   $LVSR/exp/wsj/write_hdf_dataset.sh
   ```
   The resulting file `wsj.h5` should be put to $FUEL_DATA_PATH folder.

2. Compile language model FST's from ARPA-format language models provided with WSJ.
   This step requires kaldi.

   `$LVSR/exp/wsj/make_all_wsj_graphs.sh <lmfile> <lmsdir>`

   where `<lmfile>` is the arpa languge model which goes with WSJ dataset.
   (we placed it to `$FUEL_DATA_PATH/WSJ/lm_bg.arpa.gz`) and `<lmsdir>` is a
   directry to place FST language models (we use `data/lms`).

3. Train the model. You don't need kaldi for training and it doesn't use any
   scripts from the recipe.

   For the End-to-End Attention-based Large Vocabulary Speech Recognition use
   the `model=wsj_paper7` and for the Task Loss Estimation for Sequence
   Prediction use `model=wsj_reward6` in the following script:
   ```
   $LVSR/bin/run.py train <model> $LVSR/exp/wsj/configs/<model>.yaml
   ```

   This will start training and save the model to the folder `<model>`.

4. Decode the model on the validation and training datasets.

   ```
   $LVSR/exp/wsj/decode.sh wsj_paper7 <part> <beam-size>
   ```
   or
   ```
   $LVSR/exp/wsj/decode_tle.sh wsj_reward6 <part> <beam-size>
   ```
   for the task loss estimation model.

   We typically use beam size 200 to get the best performance. However, with beam size
   the scores are typically only 10\% worse and decoding is **much** faster.
   You can see reports at `wsj_paper6/reports` directory. For every language
   model option, beam size and subset there are alignment images and
   `report.txt` which contains transcripts, approximate CER and WER and other
   auxiliary information.

5. Score the recognized transcripts:

    ```
    $LVSR/exp/wsj/score.sh <part> <model>/reports/valid_trigram_200/
    ```

    This script produces `<part>-text.wer` and `<part>-text.errs` files in the
    corresponding directory. The first one contains WER and the second one
    the report of `compute-wer` kadli script.


text:
""" This module is used for integration testing. """

# pylint: disable=locally-disabled,unused-import
import venv_exclusive


text:
layout: update
published: false
title: Some UI and feature enhancements to the Colour Picker tool
date: 2015-05-19
article:
  written_on: 2015-05-19
  updated_on: 2015-05-19
authors:
- umarhansa
collection: updates
type: tip
category: tools
product: chrome-devtools
featured-image: /web/updates/images/2015-05-19-some-ui-and-feature-enhancements-to-the-colour-picker-tool/colour-picker-upgrade.gif
source_name: DevTips
source_url: https://umaar.com/dev-tips/22-colour-picker-upgrade
permalink: /updates/2015/05/19/some-ui-and-feature-enhancements-to-the-colour-picker-tool.html
---

The colour picker tool in DevTools is getting an upgrade.

There's an eye dropper feature.

Simple interface to pick your colour including alpha.

Colour format switcher (hex, rgba, hsla).

Currently in Chrome Canary


text:
module Invoicer
  class FreshbooksInvoice
    def self.from_freshbooks(freshbooks_invoice)
      total = freshbooks_invoice["total_amount"].to_f
      date = Date.strptime(freshbooks_invoice["date"], "%Y-%m-%d 00:00:00")
      Invoice.new(
        :id => freshbooks_invoice["invoice_id"],
        :number => freshbooks_invoice["number"],
        :total_amount => total,
        :due_amount => total - freshbooks_invoice["paid"].to_f,
        :issued_on => Date.strptime(freshbooks_invoice["date"], "%Y-%m-%d 00:00:00"),
        :currency => freshbooks_invoice["currency_code"],
        :service => :freshbooks
      )
    end
  end
end


text:
require 'spec_helper_puppet'

describe 'Puppet::Type::JBoss_jmsqueue::ProviderJbosscli' do
  let(:mock_values) do
    {
      :product    => 'jboss-eap',
      :version    => '6.4.0.GA',
      :controller => '127.0.0.1:9999',
      :home       => '/usr/local/jboss-eap-6.4.0.GA'
    }
  end

  before :each do
    PuppetX::Coi::Jboss::Configuration.reset_config(mock_values)
    expect(Puppet).not_to receive(:err)
  end
  after :each do
    PuppetX::Coi::Jboss::Configuration.reset_config
    executor.verify_commands_executed
  end
  let(:described_class) do
    Puppet::Type.type(:jboss_jmsqueue).provider(:jbosscli)
  end
  let(:sample_repl) do
    {
      :name    => 'app-mails',
      :durable => true,
      :ensure  => 'present',
      :profile => 'full-ha',
      :entries => [
        'queue/app-mails',
        'java:jboss/exported/jms/queue/app-mails'
      ]
    }
  end

  let(:extended_repl) do
    {}
  end

  let(:resource) do
    raw = sample_repl.merge(extended_repl)
    raw[:provider] = described_class.name

    Puppet::Type.type(:jboss_jmsqueue).new(raw)
  end

  let(:executor) { Testing::Mock::ExecutionStateWrapper.new }

  let(:provider) do
    provider = resource.provider
    provider.executor(executor)
    provider
  end

  describe '#create wth runasdomain? => true' do
    let(:extended_repl) do
      { :runasdomain => true }
    end
    before :each do
      compiled_cmd_subsystem = '/profile=full-ha/subsystem=messaging'
      executor.register_failing_command(
        '/extension=org.jboss.as.messaging:read-resource()'
      )
      executor.register_command(
        '/extension=org.jboss.as.messaging:add()'
      )
      executor.register_failing_command(
        "#{compiled_cmd_subsystem}:read-resource()"
      )
      executor.register_command(
        "#{compiled_cmd_subsystem}:add()"
      )
      hornet_cmd = 'hornetq-server=default'
      compiled_hornet_cmd = "#{compiled_cmd_subsystem}/#{hornet_cmd}"
      exec_hornet_cmd = "#{compiled_hornet_cmd}:read-resource()"
      hornet_bring_up_cmd = "#{compiled_hornet_cmd}:add()"
      executor.register_failing_command(exec_hornet_cmd)
      executor.register_command(hornet_bring_up_cmd)

      final_cmd = 'jms-queue --profile=full-ha add --queue-address=app-mails ' \
        '--entries=["queue/app-mails", "java:jboss/exported/jms/queue/app-mails"] --durable=true'
      executor.register_command(final_cmd)
    end

    subject { provider.create }
    it { expect(subject.success?).to eq(true) }
  end

  describe '#destroy' do
    let(:extended_repl) do
      { :runasdomain => true }
    end
    before :each do
      cmd = "jms-queue --profile=#{resource[:profile]} remove --queue-address=#{resource[:name]}"
      executor.register_command(cmd)
    end

    subject { provider.destroy }
    it { expect(subject.success?).to eq(true) }
  end

  describe '#exists?' do
    describe 'with result => true' do
      before :each do
        cmd = "/subsystem=messaging/hornetq-server=default/jms-queue=#{resource[:name]}:read-resource()"
        compiled_cmd = "/profile=full-ha#{cmd}"
        executor.register_command(
          compiled_cmd,
          {
            'outcome' => 'success',
            'result'  => 'asd'
          }
        )
      end

      subject { provider.exists? }
      it { expect(subject).to eq(true) }
    end

    describe 'with result => false' do
      before :each do
        cmd = "/subsystem=messaging/hornetq-server=default/jms-queue=#{resource[:name]}:read-resource()"
        compiled_cmd = "/profile=full-ha#{cmd}"
        expected_output = {
          'outcome' => 'failure',
          'result'  => 'asd'
        }
        executor.register_command(
          compiled_cmd, expected_output
        )
      end

      subject { provider.exists? }
      it { expect(subject).to eq(false) }
    end
  end

  describe 'managed properties' do
    before :each do
      executor.register_command(
        '/profile=full-ha/subsystem=messaging/hornetq-server=default/jms-queue=app-mails:read-resource()',
        {
          'outcome' => 'success',
          'result'  => data
        }
      )
      provider.exists?
    end

    describe '#durable' do
      let(:data) do
        { 'durable' => durable }
      end
      describe 'getting value' do
        let(:durable) { true }
        subject { provider.durable }
        it { expect(subject).to eq('true') }
      end

      describe 'setting with true' do
        let(:durable) { false }
        before :each do
          executor.register_command(
            '/profile=full-ha/subsystem=messaging/hornetq-server=default/jms-queue=app-mails' \
            ':write-attribute(name="durable", value=true)'
          )
        end
        subject { provider.durable = true }
        it { expect(subject).to eq(true) }
      end
    end

    describe '#entries' do
      let(:data) do
        { 'entries' => 'Lorem ipsum' }
      end
      describe 'getting value' do
        subject { provider.entries }
        it { expect(subject).to eq('Lorem ipsum') }
      end

      describe 'setting with "true", "false"' do
        before :each do
          entries = '["true", "false"]'
          executor.register_command(
            '/profile=full-ha/subsystem=messaging/hornetq-server=default/jms-queue=app-mails' \
            ":write-attribute(name=\"entries\", value=#{entries})"
          )
        end

        subject { provider.entries = %w[true false] }
        it { expect(subject).to eq(%w[true false]) }
      end
    end
  end
end


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000"
    android:gravity="center"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    tools:context="home.ned.lul.NativePlaybackActivity">

    <!-- The primary full-screen view. This can be replaced with whatever view
         is needed to present your content, e.g. VideoView, SurfaceView,
         TextureView, etc. -->
    <!--<TextView-->
        <!--android:id="@+id/fullscreen_content"-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent"-->
        <!--android:gravity="center"-->
        <!--android:keepScreenOn="true"-->
        <!--android:text="@string/dummy_content"-->
        <!--android:textColor="#33b5e5"-->
        <!--android:textSize="50sp"-->
        <!--android:textStyle="bold" />-->

    <VideoView
        android:id="@+id/fullscreen_content"
        android:gravity="center"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </VideoView>

    <!-- This FrameLayout insets its children based on system windows using
         android:fitsSystemWindows. -->
    <!--<FrameLayout-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent"-->
        <!--android:fitsSystemWindows="true">-->

        <!--<LinearLayout-->
            <!--android:id="@+id/fullscreen_content_controls"-->
            <!--style="?metaButtonBarStyle"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:layout_gravity="bottom|center_horizontal"-->
            <!--android:background="@color/black_overlay"-->
            <!--android:orientation="horizontal"-->
            <!--tools:ignore="UselessParent">-->

            <!--<Button-->
                <!--android:id="@+id/dummy_button"-->
                <!--style="?metaButtonBarButtonStyle"-->
                <!--android:layout_width="0dp"-->
                <!--android:layout_height="wrap_content"-->
                <!--android:layout_weight="1"-->
                <!--android:text="@string/dummy_button" />-->

        <!--</LinearLayout>-->
    <!--</FrameLayout>-->

</LinearLayout>


text:
@interface GQNetworkTrafficManager()
{
    BOOL        _isUsingGPRSNetwork;
    BOOL        _isAlert;
    BOOL        _shouldLog;
    double      _wifiInBytes;
    double      _wifiOutBytes;
    double      _gprsInBytes;
    double      _gprsOutBytes;
    int         _resetDayInMonth;
    int         _maxgprsMegaBytes;     // this is MB not byte

    NSDate      *_lastAlertTime;
    NSDate      *_lastResetDate;

    GQReachability *_reachability;
}

- (void)restore;
- (void)inGQrafficData;

- (double)getMegabytesFromBytes:(int)bytes;

@end

@implementation GQNetworkTrafficManager
@synthesize networkStatus = _networkStatus;

GQOBJECT_SINGLETON_BOILERPLATE(GQNetworkTrafficManager, sharedManager)

- (id)init
{
    self = [super init];
    if (self) {
        [self restore];
    }
    return self;
}

#pragma mark - private methods
- (void)inGQrafficData
{
    _maxgprsMegaBytes = [[GQ_USER_DEFAULT objectForKey:GQ_NETWORK_TRAFFIC_MAX_GPRS] intValue];
    if (!_maxgprsMegaBytes) {
        _wifiInBytes = 0;
        _wifiOutBytes = 0;
        _gprsInBytes = 0;
        _gprsOutBytes = 0;
        _resetDayInMonth = 1;
        _maxgprsMegaBytes = 999;
    }
    else {
        _wifiInBytes = [[GQ_USER_DEFAULT objectForKey:GQ_NETWORK_TRAFFIC_WIFI_IN] doubleValue];
        _wifiOutBytes = [[GQ_USER_DEFAULT objectForKey:GQ_NETWORK_TRAFFIC_WIFI_OUT] doubleValue];
        _gprsInBytes = [[GQ_USER_DEFAULT objectForKey:GQ_NETWORK_TRAFFIC_GPRS_IN] doubleValue];
        _gprsOutBytes = [[GQ_USER_DEFAULT objectForKey:GQ_NETWORK_TRAFFIC_GPRS_OUT] doubleValue];
        _resetDayInMonth = [[GQ_USER_DEFAULT objectForKey:GQ_NETWORK_TRAFFIC_RESET_DAY_IN_MONTH] intValue];
        _maxgprsMegaBytes = [[GQ_USER_DEFAULT objectForKey:GQ_NETWORK_TRAFFIC_MAX_GPRS] intValue];
    }
    _lastResetDate =(NSDate*)[GQ_USER_DEFAULT objectForKey:GQ_NETWORK_TRAFFIC_LAST_RESET_DATE];
    _isAlert = [GQ_USER_DEFAULT boolForKey:GQ_NETWORK_TRAFFIC_IS_ALERT];
    _shouldLog = [GQ_USER_DEFAULT boolForKey:GQ_SHOULD_LOG_TRAFFIC_DATA];
    [self checkIsResetDay];
}

- (void) networkStateDidChanged:(NSNotification*)n
{
    [GQDebugLog infoMessage:@"networkStateDidChanged"];
    GQReachability* curReach = [n object];
    NSParameterAssert([curReach isKindOfClass: [GQReachability class]]);
    [self updateNetwordStatus:curReach.currentReachabilityStatus];
}

- (void) updateNetwordStatus:(GQNetworkStatus)status
{
    _networkStatus = status;
    _isUsingGPRSNetwork = FALSE;
    switch (status)
    {
        case GQReachableViaWiFi:
            break;
        case GQReachableViaWWAN:
            _isUsingGPRSNetwork = TRUE;
            break;
        case GQNotReachable:
            break;
        default:
            break;
    }
    [self debugNetworkStatus];
}

- (void)debugNetworkStatus {
    NSString *networkType = @"unknown";
    switch (_networkStatus)
    {
        case GQReachableViaWiFi:
            networkType = @"wifi";
            break;
        case GQReachableViaWWAN:
            networkType = @"gprs";
            _isUsingGPRSNetwork = TRUE;
            break;
        case GQNotReachable:
            networkType = @"unavailable";
            break;
        default:
            break;
    }
    [GQDebugLog infoMessage:[NSString stringWithFormat:@"network status %@", networkType]];
}

- (void)restore
{
    _networkStatus = GQReachableViaWiFi;
    _lastAlertTime = nil;
    [self inGQrafficData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateDidChanged:) name:kGQReachabilityChangedNotification object:nil];
    _reachability = [GQReachability reachabilityForInternetConnection];
    [self updateNetwordStatus:_reachability.currentReachabilityStatus];
    [_reachability startNotifier];
}

-(void)checkIsResetDay
{
    //得到当前的日期

    NSDate *date = [NSDate date];
    NSDate *nextResetDate =(NSDate*)[[NSUserDefaults standardUserDefaults] objectForKey:GQ_NETWORK_TRAFFIC_NEXT_RESET_DATE];
    if (!nextResetDate||[nextResetDate timeIntervalSinceNow] < 0) {
        [self resetData];
    }

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [calendar components:NSCalendarUnitDay fromDate:date];
    NSInteger day = [comps day];

    NSInteger nextResetMoth = comps.month;
    NSInteger nextResetYear = comps.year;
    NSInteger nextResetDay = _resetDayInMonth;

    if (day>_resetDayInMonth) {
        nextResetMoth +=1;
        if (nextResetMoth>12) {
            nextResetMoth-=12;
            nextResetYear+=1;
        }
    }
    [comps setDay:nextResetDay];
    [comps setMonth:nextResetMoth];
    [comps setYear:nextResetYear];

    nextResetDate = [calendar dateFromComponents:comps];
    [GQ_USER_DEFAULT setObject:nextResetDate forKey:GQ_NETWORK_TRAFFIC_NEXT_RESET_DATE];
    [GQ_USER_DEFAULT synchronize];
}

- (double)getMegabytesFromBytes:(int)bytes
{
    return (bytes * 1.0/1000)/1000;
}

#pragma mark - public methods
- (void)doSave
{
    [GQ_USER_DEFAULT setObject:@(_wifiInBytes) forKey:GQ_NETWORK_TRAFFIC_WIFI_IN];
    [GQ_USER_DEFAULT setObject:@(_wifiOutBytes) forKey:GQ_NETWORK_TRAFFIC_WIFI_OUT];
    [GQ_USER_DEFAULT setObject:@(_gprsInBytes) forKey:GQ_NETWORK_TRAFFIC_GPRS_IN];
    [GQ_USER_DEFAULT setObject:@(_gprsOutBytes) forKey:GQ_NETWORK_TRAFFIC_GPRS_OUT];
    [GQ_USER_DEFAULT setObject:@(_resetDayInMonth) forKey:GQ_NETWORK_TRAFFIC_RESET_DAY_IN_MONTH];
    [GQ_USER_DEFAULT setObject:@(_maxgprsMegaBytes) forKey:GQ_NETWORK_TRAFFIC_MAX_GPRS];
    [GQ_USER_DEFAULT synchronize];
}

// log traffic
- (void)logTrafficIn:(unsigned long long)bytes
{
    NSUserDefaults *userinfo = [NSUserDefaults standardUserDefaults];
    switch (_networkStatus) {
        case GQReachableViaWWAN:
            _gprsInBytes = _gprsInBytes + bytes;
            [userinfo setObject:@(_gprsInBytes) forKey:GQ_NETWORK_TRAFFIC_GPRS_IN];
            [userinfo synchronize];
            if (_shouldLog) {
                [GQDebugLog infoMessage:[NSString stringWithFormat:@"gprs trafic in :%lf bytes", _gprsInBytes]];
            }
            break;
        case GQReachableViaWiFi:
            _wifiInBytes = _wifiInBytes + bytes;
            [userinfo setObject:@(_wifiInBytes) forKey:GQ_NETWORK_TRAFFIC_WIFI_IN];
            [userinfo synchronize];
            if (_shouldLog) {
                [GQDebugLog infoMessage:[NSString stringWithFormat:@"wifi trafic in :%lf bytes", _wifiInBytes]];
            }
            break;
        default:
            break;
    }
    if ([self hasExceedMaxGPRSTraffic]&&_isAlert) {
        NSDate *now = [NSDate date];
        BOOL shouldShowAlert = NO;
        if (!_lastAlertTime || [now timeIntervalSinceDate:_lastAlertTime]/100 > GQ_NETWORK_TRAFFIC_MAX_GPRS_ALERT_INTERVAL) {
            shouldShowAlert = YES;
        }
        if (shouldShowAlert) {
            NSString *alertMsg = [NSString stringWithFormat:@"您目前的GPRS流量(%4.2fM)已超过您所设定的上限(%dM)",[self getGPRSTraffic],[self getMaxGPRSTraffic]];

//            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"流量提示" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
//            [alertController addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
//
//            }]];

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"流量提示"
                                                            message:alertMsg
                                                           delegate:nil
                                                  cancelButtonTitle:@"知道了"
                                                  otherButtonTitles:nil];
            [alert show];
            _lastAlertTime = now;
        }
    }
}

- (void)logTrafficOut:(unsigned long long)bytes
{
    switch (_networkStatus) {
        case GQReachableViaWWAN:
            _gprsOutBytes = _gprsOutBytes + bytes;
            [GQ_USER_DEFAULT setObject:@(_gprsOutBytes) forKey:GQ_NETWORK_TRAFFIC_GPRS_OUT];
            [GQ_USER_DEFAULT synchronize];
            if (_shouldLog) {
                [GQDebugLog infoMessage:[NSString stringWithFormat:@"gprs trafic in :%lf bytes", _gprsInBytes]];
            }
            break;
        case GQReachableViaWiFi:
            _wifiOutBytes = _wifiOutBytes + bytes;
            [GQ_USER_DEFAULT setObject:@(_wifiOutBytes) forKey:GQ_NETWORK_TRAFFIC_WIFI_OUT];
            [GQ_USER_DEFAULT synchronize];
            if (_shouldLog) {
                [GQDebugLog infoMessage:[NSString stringWithFormat:@"wifi trafic in :%lf bytes", _wifiInBytes]];
            }
            break;
        default:
            break;
    }
}

// set /get reset data date
- (void)setTrafficResetDay:(int)dayInMonth
{
    _resetDayInMonth = dayInMonth;
    [GQ_USER_DEFAULT setObject:@(_resetDayInMonth) forKey:GQ_NETWORK_TRAFFIC_RESET_DAY_IN_MONTH];
    [GQ_USER_DEFAULT synchronize];
}

- (int)getTrafficResetDay
{
    return _resetDayInMonth;
}

// alert user
- (void)setMaxGPRSTraffic:(int)megabyte
{
    _maxgprsMegaBytes = megabyte;
    [GQ_USER_DEFAULT setObject:@(_maxgprsMegaBytes) forKey:GQ_NETWORK_TRAFFIC_MAX_GPRS];
    [GQ_USER_DEFAULT synchronize];
}

- (int)getMaxGPRSTraffic
{
    return _maxgprsMegaBytes;
}

- (BOOL)hasExceedMaxGPRSTraffic
{
    if (_maxgprsMegaBytes <= 0 || !_isAlert) {
        return NO;
    }
    else{
        return ([self getGPRSTraffic] > _maxgprsMegaBytes) ;
    }
}

-(void)setAlertStatus:(BOOL)isAlert
{
    [GQ_USER_DEFAULT setBool:isAlert forKey:GQ_NETWORK_TRAFFIC_IS_ALERT];
    [GQ_USER_DEFAULT synchronize];
    _isAlert = isAlert;
}

-(BOOL)getAlertStatus
{
    return _isAlert;
}

- (void)setLogTrafficDataStatus:(BOOL)log
{
    [GQ_USER_DEFAULT setBool:log forKey:GQ_SHOULD_LOG_TRAFFIC_DATA];
    [GQ_USER_DEFAULT synchronize];
    _shouldLog = log;
}

- (BOOL)getLogTrafficDataStatus
{
    return _shouldLog;
}

// reset
- (void)resetData
{
    _wifiInBytes = 0;
    _wifiOutBytes = 0;
    _gprsOutBytes = 0;
    _gprsInBytes = 0;
    [GQ_USER_DEFAULT setObject:[NSDate date] forKey:GQ_NETWORK_TRAFFIC_LAST_RESET_DATE];
    [self doSave];
}

// get traffic data, return megabytes
- (double)getGPRSTrafficIn
{
    return [self getMegabytesFromBytes:_gprsInBytes];
}

- (double)getGPRSTrafficOut
{
    return [self getMegabytesFromBytes:_gprsOutBytes];
}

- (double)getGPRSTraffic
{
    return [self getMegabytesFromBytes:(_gprsInBytes + _gprsOutBytes)];
}

- (double)getWifiTrafficIn
{
    return [self getMegabytesFromBytes:_wifiInBytes];
}

- (double)getWifiTrafficOut
{
    return [self getMegabytesFromBytes:_wifiOutBytes];
}

- (double)getWifiTraffic
{
    return [self getMegabytesFromBytes:(_wifiInBytes + _wifiOutBytes)];
}

// for debug
- (void)consoleDeviceNetworkTrafficInfo
{
    [GQDebugLog infoMessage:@"==============current network traffic=============\n"];
    [GQDebugLog infoMessage:[NSString stringWithFormat:@"gprs in:%fmb", [self getGPRSTrafficIn]]];
    [GQDebugLog infoMessage:[NSString stringWithFormat:@"gprs out:%fmb", [self getGPRSTrafficOut]]];
    [GQDebugLog infoMessage:[NSString stringWithFormat:@"gprs total:%fmb", [self getGPRSTraffic]]];
    [GQDebugLog infoMessage:[NSString stringWithFormat:@"wifi in:%fmb", [self getWifiTrafficIn]]];
    [GQDebugLog infoMessage:[NSString stringWithFormat:@"wifi out:%fmb", [self getWifiTrafficOut]]];
    [GQDebugLog infoMessage:[NSString stringWithFormat:@"wifi total:%fmb", [self getWifiTraffic]]];
    [GQDebugLog infoMessage:@"==================================================\n"];
}

- (GQNetworkStatus)networkStatus {
    return _networkStatus;
}

- (BOOL)isReachability
{
    return _networkStatus != GQNotReachable;
}

- (BOOL)isUseGPRSNetwork
{
    return _networkStatus == GQReachableViaWWAN;
}

- (BOOL)isUseWIFINetwork
{
    return _networkStatus == GQReachableViaWiFi;
}

@end


text:
package org.spongepowered.common.util.gen;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import com.flowpowered.math.vector.Vector3i;
import net.minecraft.world.biome.Biome;
import org.spongepowered.api.util.DiscreteTransform3;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.biome.BiomeTypes;
import org.spongepowered.api.world.extent.ImmutableBiomeVolume;
import org.spongepowered.api.world.extent.MutableBiomeVolume;
import org.spongepowered.api.world.extent.StorageType;
import org.spongepowered.api.world.extent.UnmodifiableBiomeVolume;
import org.spongepowered.api.world.extent.worker.MutableBiomeVolumeWorker;
import org.spongepowered.api.world.schematic.Palette;
import org.spongepowered.common.world.extent.MutableBiomeViewDownsize;
import org.spongepowered.common.world.extent.MutableBiomeViewTransform;
import org.spongepowered.common.world.extent.UnmodifiableBiomeVolumeWrapper;
import org.spongepowered.common.world.extent.worker.SpongeMutableBiomeVolumeWorker;

import java.util.Arrays;
import java.util.Objects;

/**
 * Mutable biome volume backed by a byte array. Reusable.
 *
 *
Using {@link #detach()} the underlying byte array can be accessed.
 * The byte array can then be reused by calling {@link #reuse(Vector3i)}.

 */
public final class ByteArrayMutableBiomeBuffer extends AbstractBiomeBuffer implements MutableBiomeVolume {

    private boolean detached;
    private final byte[] biomes;
    private final Palette<BiomeType> palette;

    private void checkOpen() {
        checkState(!this.detached, "trying to use buffer after it's closed");
    }

    public ByteArrayMutableBiomeBuffer(Palette<BiomeType> palette, Vector3i start, Vector3i size) {
        this(palette, new byte[size.getX() * size.getZ()], start, size);
    }

    public ByteArrayMutableBiomeBuffer(Palette<BiomeType> palette, byte[] biomes, Vector3i start, Vector3i size) {
        super(start, size);
        this.biomes = biomes;
        this.palette = palette;
    }

    @Override
    public void setBiome(int x, int y, int z, BiomeType biome) {
        checkOpen();
        checkRange(x, y, z);

        this.biomes[getIndex(x, z)] = (byte) this.palette.getOrAssign(biome);
    }

    @Override
    public BiomeType getBiome(int x, int y, int z) {
        checkOpen();
        checkRange(x, y, z);

        byte biomeId = this.biomes[getIndex(x, z)];
        return this.palette.get(biomeId & 255).orElse(BiomeTypes.OCEAN);
    }

    /**
     * Gets the internal byte array, and prevents further of it through this
     * object uses until {@link #reuse(Vector3i)} is called.
     *
     * @return The internal byte array.
     */
    public byte[] detach() {
        checkOpen();

        this.detached = true;
        return this.biomes;
    }

    /**
     * Gets whether this biome volume is currently detached. When detached, this
     * object is available for reuse using {@link #reuse(Vector3i)}.
     *
     * @return Whether this biome volume is detached
     */
    public boolean isDetached() {
        return this.detached;
    }

    /**
     * Changes the bounds of this biome volume, so that it can be reused for
     * another chunk.
     *
     * @param start New start position.
     */
    public void reuse(Vector3i start) {
        checkState(this.detached, "Cannot reuse while still in use");

        this.start = checkNotNull(start, "start");
        this.end = this.start.add(this.size).sub(Vector3i.ONE);
        Arrays.fill(this.biomes, (byte) 0);

        this.detached = false;
    }

    @Override
    public MutableBiomeVolume getBiomeView(Vector3i newMin, Vector3i newMax) {
        checkRange(newMin.getX(), newMin.getY(), newMin.getZ());
        checkRange(newMax.getX(), newMax.getY(), newMax.getZ());
        return new MutableBiomeViewDownsize(this, newMin, newMax);
    }

    @Override
    public MutableBiomeVolume getBiomeView(DiscreteTransform3 transform) {
        return new MutableBiomeViewTransform(this, transform);
    }

    @Override
    public MutableBiomeVolumeWorker<? extends MutableBiomeVolume> getBiomeWorker() {
        return new SpongeMutableBiomeVolumeWorker<>(this);
    }

    @Override
    public UnmodifiableBiomeVolume getUnmodifiableBiomeView() {
        return new UnmodifiableBiomeVolumeWrapper(this);
    }

    @Override
    public MutableBiomeVolume getBiomeCopy(StorageType type) {
        checkOpen();
        switch (type) {
            case STANDARD:
                return new ByteArrayMutableBiomeBuffer(this.palette, this.biomes.clone(), this.start, this.size);
            case THREAD_SAFE:
            default:
                throw new UnsupportedOperationException(type.name());
        }
    }

    @Override
    public ImmutableBiomeVolume getImmutableBiomeCopy() {
        checkOpen();
        return new ByteArrayImmutableBiomeBuffer(this.palette, this.biomes, this.start, this.size);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }
        ByteArrayMutableBiomeBuffer that = (ByteArrayMutableBiomeBuffer) o;
        return this.detached == that.detached &&
               Arrays.equals(this.biomes, that.biomes) &&
               this.palette.equals(that.palette);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(super.hashCode(), this.detached, this.palette);
        result = 31 * result + Arrays.hashCode(this.biomes);
        return result;
    }
}