text:
'use strict';

var util = require('util');
var log = require('./log.js').logger();
var myutils = require('./utils.js');
var amqp = require('rhea').create_container();

var Artemis = function (connection) {
    this.connection = connection;
    this.sender = connection.open_sender('activemq.management');
    this.sender.on('sender_open', this.sender_open.bind(this));
    this.sender.on('sendable', this._send_pending_requests.bind(this));
    connection.on('receiver_open', this.receiver_ready.bind(this));
    connection.on('message', this.incoming.bind(this));
    connection.on('receiver_error', this.on_receiver_error.bind(this));
    connection.on('sender_error', this.on_sender_error.bind(this));
    var self = this;
    connection.on('connection_open', function (context) {
        let previous = self.id;
        self.id = context.connection.container_id;
        if (previous !== undefined && previous !== self.id) {
            log.info('[%s] connection opened (was %s)', self.id, previous);
        } else {
            log.info('[%s] connection opened', self.id);
        }
    });
    connection.on('connection_error', this.on_connection_error.bind(this));
    connection.on('connection_close', this.on_connection_close.bind(this));
    connection.on('disconnected', this.disconnected.bind(this));
    connection.on('error', this.on_error.bind(this));
    this.handlers = [];
    this.requests = [];
    this.pushed = 0;
    this.popped = 0;
};

Artemis.prototype.log_info = function (context) {
    if (this.id) {
        log.info('[%s] artemis requests pending: %d, made:%d, completed: %d, ready: %d', this.id, this.handlers.length, this.pushed, this.popped, this.address !== undefined);
    }
};

Artemis.prototype.sender_open = function () {
    var tmp_reply_address = 'activemq.management.tmpreply.' + amqp.generate_uuid();
    log.debug('[%s] sender ready, creating reply to address: %s', this.connection.container_id, tmp_reply_address);
    this._create_temp_response_queue(tmp_reply_address);
    this.connection.open_receiver({source:{address: tmp_reply_address}});
}

Artemis.prototype.receiver_ready = function (context) {
    this.address = context.receiver.remote.attach.source.address;
    log.info('[%s] ready to send requests, reply to address: %s', this.connection.container_id, this.address);
    this._send_pending_requests();
};

function as_handler(resolve, reject) {
    return function (context) {
        var message = context.message || context;
        if (message.application_properties && message.application_properties._AMQ_OperationSucceeded) {
            try {
                if (message.body) {
                    resolve(JSON.parse(message.body)[0]);
                } else {
                    resolve(true);
                }
            } catch (e) {
                log.info('[%s] Error parsing message body: %s : %s', this.connection.container_id, message, e);
                reject(message.body)
            }
        } else {
            reject(message.body);
        }
    };
}

Artemis.prototype.incoming = function (context) {
    var message = context.message;
    log.debug('[%s] recv: %j', this.id || context.connection.container_id, message);
    var handler = this.handlers.shift();
    if (handler) {
        this.popped++;
        handler(context);
    }
};

Artemis.prototype.disconnected = function (context) {
    log.info('[%s] disconnected', this.id || context.connection.container_id);
    this.address = undefined;
    this.abort_requests('disconnected');
};

Artemis.prototype.abort_requests = function (error) {
    while (this.handlers.length > 0) {
        var handler = this.handlers.shift();
        if (handler) {
            this.popped++;
            handler(error);
        }
    }
}

Artemis.prototype.on_sender_error = function (context) {
    var error = this.connection.container_id + ' sender error ' + JSON.stringify(context.sender.error);
    log.info('[' + this.connection.container_id + '] ' + error);
    this.abort_requests(error);
};

Artemis.prototype.on_receiver_error = function (context) {
    var error = this.connection.container_id + ' receiver error ' + JSON.stringify(context.receiver.error);
    log.info('[' + this.connection.container_id + '] ' + error);
    this.abort_requests(error);
};

Artemis.prototype.on_connection_error = function (context) {
    var error = this.connection.container_id + ' connection error ' + JSON.stringify(context.connection.error);
    log.info('[' + this.connection.container_id + '] connection error: ' + JSON.stringify(context.connection.error));
    this.abort_requests(error);
};

Artemis.prototype.on_connection_close = function (context) {
    var error = this.connection.container_id + ' connection closed';
    log.info('[' + this.connection.container_id + '] connection closed');
    this.abort_requests(error);
};

Artemis.prototype.on_error = function (error) {
    log.error('[%s] socket error: %s', this.connection.container_id, JSON.stringify(error));
};

Artemis.prototype._send_pending_requests = function () {
    if (this.address === undefined) return false;

    var i = 0;
    while (i < this.requests.length && this.sender.sendable()) {
        this._send_request(this.requests[i++]);
    }
    this.requests.splice(0, i);
    return this.requests.length === 0 && this.sender.sendable();
}

Artemis.prototype._send_request = function (request) {
    request.application_properties.JMSReplyTo = this.address;
    request.reply_to = this.address;
    if (process.env.AGENT_CORRELATE_MGMT === 'true') {
        // Aids debug, has no functional effect
        request.correlation_id = amqp.generate_uuid();
    }
    this.sender.send(request);
    log.debug('[%s] sent: %j', this.id, request);
}

Artemis.prototype._create_request_message = function(resource, operation, parameters) {
    var request = {application_properties: {'_AMQ_ResourceName': resource, '_AMQ_OperationName': operation}};
    request.body = JSON.stringify(parameters);
    return request;
}

Artemis.prototype._request = function (resource, operation, parameters) {
    var request = this._create_request_message(resource, operation, parameters);
    if (this._send_pending_requests()) {
        this._send_request(request);
    } else {
        this.requests.push(request);
    }
    var stack = this.handlers;
    var self = this;
    return new Promise(function (resolve, reject) {
        self.pushed++;
        stack.push(as_handler(resolve, reject));
    });
}

// No response requested
Artemis.prototype._create_temp_response_queue = function (name) {
    var request = this._create_request_message('broker', 'createQueue', [name/*address*/, 'ANYCAST', name/*queue name*/, null/*filter*/, false/*durable*/,
         1/*max consumers*/, true/*purgeOnNoConsumers*/, true/*autoCreateAddress*/]);
    this._send_request(request);
}

Artemis.prototype.createSubscription = function (name, address, maxConsumers) {
    return this._request('broker', 'createQueue', [address, 'MULTICAST', name/*queue name*/, null/*filter*/, true/*durable*/,
                                                   maxConsumers/*max consumers*/, false/*purgeOnNoConsumers*/, false/*autoCreateAddress*/]);
}

Artemis.prototype.createQueue = function (name) {
    return this._request('broker', 'createQueue', [name/*address*/, 'ANYCAST', name/*queue name*/, null/*filter*/, true/*durable*/,
                                                   -1/*max consumers*/, false/*purgeOnNoConsumers*/, true/*autoCreateAddress*/]);
}

Artemis.prototype.destroyQueue = function (name) {
    return this._request('broker', 'destroyQueue', [name, true, true]);
}

Artemis.prototype.purgeQueue = function (name) {
    return this._request('queue.'+name, 'removeMessages', [null]);
}

Artemis.prototype.getQueueNames = function () {
    return this._request('broker', 'getQueueNames', []);
}

var queue_attributes = {
    temporary: 'isTemporary',
    durable: 'isDurable',
    messages: 'getMessageCount',
    consumers: 'getConsumerCount',
    enqueued: 'getMessagesAdded',
    delivering: 'getDeliveringCount',
    acknowledged: 'getMessagesAcknowledged',
    expired: 'getMessagesExpired',
    killed: 'getMessagesKilled'
};

function add_queue_method(name) {
    Artemis.prototype[name] = function (queue) {
        return this._request('queue.'+queue, name, []);
    };
}

for (var key in queue_attributes) {
    add_queue_method(queue_attributes[key]);
}

var extra_queue_attributes = {
    address: 'getAddress',
    routing_type: 'getRoutingType'
}

for (var key in extra_queue_attributes) {
    add_queue_method(extra_queue_attributes[key]);
}

var queue_attribute_aliases = {
    'isTemporary': 'temporary',
    'isDurable': 'durable',
    'messageCount': 'messages',
    'consumerCount': 'consumers',
    'messagesAdded': 'enqueued',
    'deliveringCount': 'delivering',
    'messagesAcked': 'acknowledged',
    'messagesExpired': 'expired',
    'messagesKilled': 'killed'
};

function correct_type(o) {
    var i = Number(o);
    if (!Number.isNaN(i)) return i;
    else if (o === 'true') return true;
    else if (o === 'false') return false;
    else if (o === null) return undefined;
    else return o;
}

function set_queue_aliases(q) {
    for (var f in queue_attribute_aliases) {
        var a = queue_attribute_aliases[f];
        if (q[f] !== undefined) {
            q[a] = q[f];
            delete q[f];
        }
    }
}

function fix_types(o) {
    for (var k in o) {
        o[k] = correct_type(o[k]);
    }
}

function process_queue_stats(q) {
    fix_types(q);
    set_queue_aliases(q);
}

Artemis.prototype.listQueues = function () {
    return this._request('broker', 'listQueues', ['{"field":"","operation":"","value":"","sortOrder":"","sortBy":"","sortColumn":""}', 1, 2147483647/*MAX_INT*/]).then(function (result) {
        var queues = JSON.parse(result).data;
        queues.forEach(process_queue_stats);
        return queues;
    });
};

function routing_type_to_type(t) {
    if (t === 'MULTICAST') return 'topic';
    if (t === 'ANYCAST') return 'queue';
    return t;
}

function routing_types_to_type(t) {
    if (t.indexOf('MULTICAST') >= 0) {
        return 'topic';
    } else if (t.indexOf('ANYCAST') >= 0) {
        return 'queue';
    } else {
        return undefined;
    }
}

function address_to_queue_or_topic(a) {
    return {
        name: a.name,
        type: routing_types_to_type(a.routingTypes)
    };
}

Artemis.prototype.getAddresses = function () {
    return this._request('broker', 'listAddresses', ['{"field":"","operation":"","value":"","sortOrder":"","sortBy":"","sortColumn":""}', 1, 2147483647/*MAX_INT*/]).then(function (result) {
        return JSON.parse(result).data.map(address_to_queue_or_topic);
    });
};

Artemis.prototype.getQueueDetails = function (name, attribute_list) {
    var attributes = attribute_list || Object.keys(queue_attributes);
    var agent = this;
    return Promise.all(
        attributes.map(function (attribute) {
            var method_name = queue_attributes[attribute];
            if (method_name) {
                return agent[method_name](name);
            }
        })
    ).then(function (results) {
        var q = {'name':name};
        for (var i = 0; i < results.length; i++) {
            q[attributes[i]] = results[i];
        }
        return q;
    });
}

function initialise_topic_stats(a) {
    a.enqueued = 0;
    a.messages = 0;
    a.subscriptions = [];
    a.subscription_count = 0;
    a.durable_subscription_count = 0;
    a.inactive_durable_subscription_count = 0;
}

function update_topic_stats(a, q) {
    a.enqueued += q.enqueued;
    a.messages += q.messages;
    a.subscriptions.push(q);
    a.subscription_count++;
    if (q.durable) {
        a.durable_subscription_count++;
        if (q.consumers === 0) {
            a.inactive_durable_subscription_count++;
        }
    }
}

function queues_to_addresses(addresses, queues, include_topic_stats, include_reverse_index) {
    var index = {};
    var reverse_index = include_reverse_index ? {} : undefined;
    for (var i = 0; i < addresses.length; i++) {
        var a = addresses[i];
        var b = index[a.name];
        if (b === undefined) {
            index[a.name] = a;
            if (include_topic_stats && a.type === 'topic') {
                initialise_topic_stats(a);
            }
        } else {
            log.warn('Duplicate address: %s (%s)', a.name, a.type);
        }
    }
    for (var i = 0; i < queues.length; i++) {
        var q = queues[i];
        if (reverse_index) {
            reverse_index[q.name] = q.address;
        }
        var a = index[q.address];
        if (q.routingType === 'MULTICAST') {
            if (a === undefined) {
                log.warn('Missing address %s for topic queue %s', q.address, q.name);
                a = {
                    name: q.address,
                    type: 'topic'
                };
                index[q.address] = a;
                if (include_topic_stats) {
                    initialise_topic_stats(a);
                }
            } else if (a.type !== 'topic') {
                log.warn('Unexpected address type: queue %s has type %s, address %s has type %s', q.name, q.routingType, q.address, a.type);
            }
            if (q.durable && !q.purgeOnNoConsumers) {
                //treat as subscription
                index[q.name] = myutils.merge(q, {
                    name: q.name,
                    type: 'subscription'
                });
            }
            if (include_topic_stats) {
                update_topic_stats(a, q);
            }
        } else if (q.routingType === 'ANYCAST') {
            if (a === undefined) {
                a = {
                    name: q.address,
                    type: 'queue'
                };
                index[q.address] = a;
                log.warn('Missing address %s for queue %s', q.address, q.name);
            } else if (q.name !== q.address) {
                log.warn('Mismatched address %s for queue %s', q.address, q.name);
            } else if (a.routingType !== undefined) {
                log.warn('Duplicate queue for address %s: %j %j', q.address, a, q);
            }
            myutils.merge(a, q);
        } else {
            log.error('Unknown routingType: %s', q.routingType);
        }
    }
    return {
        addresses: addresses,
        queues: queues,
        index: index,
        reverse_index: reverse_index
    };
}

Artemis.prototype._get_address_data = function (include_topic_stats, include_reverse_index) {
    return Promise.all([this.getAddresses(), this.listQueues()]).then(function (results) {
        return queues_to_addresses(results[0], results[1], include_topic_stats, include_reverse_index);
    });
};

Artemis.prototype.listAddresses = function () {
    return this._get_address_data().then(function (data) {
        return data.index;
    });
};

Artemis.prototype.getAllAddressData = function () {
    return this._get_address_data(true, true).then(function (data) {
        return data;
    });
};

Artemis.prototype.getAllQueuesAndTopics = function () {
    return this._get_address_data(true, false).then(function (data) {
        return data.index;
    });
};

Artemis.prototype.getAddressNames = function () {
    return this._request('broker', 'getAddressNames', []);
}

Artemis.prototype.createAddress = function (name, type) {
    var routing_types = [];
    if (type.anycast || type.queue) routing_types.push('ANYCAST');
    if (type.multicast || type.topic) routing_types.push('MULTICAST');
    return this._request('broker', 'createAddress', [name, routing_types.join(',')]);
};

Artemis.prototype.deleteAddress = function (name) {
    return this._request('broker', 'deleteAddress', [name]);
};

var address_settings_fields = {
    'DLA':'',
    'expiryAddress':'',
    'expiryDelay':-1,
    'lastValueQueue':false,
    'deliveryAttempts':-1,
    'maxSizeBytes':-1,
    'pageSizeBytes':-1,
    'pageMaxCacheSize':-1,
    'redeliveryDelay':-1,
    'redeliveryMultiplier':-1,
    'maxRedeliveryDelay':-1,
    'redistributionDelay':-1,
    'sendToDLAOnNoRoute':false,
    'addressFullMessagePolicy': 'FAIL',
    'slowConsumerThreshold':-1,
    'slowConsumerCheckPeriod':-1,
    'slowConsumerPolicy':'DROP',
    'autoCreateJmsQueues':false,
    'autoDeleteJmsQueues':false,
    'autoCreateJmsTopics':false,
    'autoDeleteJmsTopics':false,
    'autoCreateQueues':false,
    'autoDeleteQueues':false,
    'autoCreateAddresses':false,
    'autoDeleteAddresses':false
};

Artemis.prototype.addAddressSettings = function (match, settings) {
    var args = [match];
    for (var name in address_settings_fields) {
        var v = settings[name] || address_settings_fields[name];
        args.push(v);
    }
    return this._request('broker', 'addAddressSettings', args);
};

Artemis.prototype.removeAddressSettings = function (match) {
    return this._request('broker', 'removeAddressSettings', [match]);
};

Artemis.prototype.deleteAddressAndBindings = function (address) {
    var self = this;
    return this.deleteBindingsFor(address).then(function () {
        return self.deleteAddress(address);
    });
};

Artemis.prototype.deleteBindingsFor = function (address) {
    var self = this;
    return this.getBoundQueues(address).then(function (results) {
        return Promise.all(results.map(function (q) { return self.destroyQueue(q); }));
    });
};

Artemis.prototype.getBoundQueues = function (address) {
    return this._request('address.'+address, 'getQueueNames', []);
};

Artemis.prototype.createDivert = function (name, source, target) {
    return this._request('broker', 'createDivert', [name, name, source, target, false, null, null]);
}

Artemis.prototype.destroyDivert = function (name) {
    return this._request('broker', 'destroyDivert', [name]);
}

Artemis.prototype.getDivertNames = function () {
    return this._request('broker', 'getDivertNames', []);
}

/**
 * Create divert if one does not already exist.
 */
Artemis.prototype.ensureDivert = function (name, source, target) {
    var broker = this;
    return broker.findDivert(name).then(
        function (found) {
            if (!found) {
                return broker.createDivert(name, source, target);
            }
        }
    );
};

Artemis.prototype.findDivert = function (name) {
    return this.getDivertNames().then(
        function (results) {
            return results.indexOf(name) >= 0;
        }
    );
};

Artemis.prototype.createConnectorService = function (connector) {
    var parameters = {
        "host": process.env.MESSAGING_SERVICE_HOST,
        "port": process.env.MESSAGING_SERVICE_PORT_AMQPS_BROKER,
        "clusterId": connector.clusterId
    };

    if (connector.containerId !== undefined) {
	parameters.containerId = connector.containerId;
    }
    if (connector.linkName !== undefined) {
	parameters.linkName = connector.linkName;
    }
    if (connector.targetAddress !== undefined) {
	parameters.targetAddress = connector.targetAddress;
    }
    if (connector.sourceAddress !== undefined) {
	parameters.sourceAddress = connector.sourceAddress;
    }
    if (connector.direction !== undefined) {
	parameters.direction = connector.direction;
    }
    return this._request('broker', 'createConnectorService', [connector.name, "org.apache.activemq.artemis.integration.amqp.AMQPConnectorServiceFactory", parameters]);
}

Artemis.prototype.destroyConnectorService = function (name) {
    return this._request('broker', 'destroyConnectorService', [name]);
}

Artemis.prototype.getConnectorServices = function () {
    return this._request('broker', 'getConnectorServices', []);
}

Artemis.prototype.listConnections = function () {
    return this._request('broker', 'listConnectionsAsJSON', []).then(function (result) {
        return JSON.parse(result);
    });
}

Artemis.prototype.listSessionsForConnection = function (connection_id) {
    return this._request('broker', 'listSessionsAsJSON', [connection_id]).then(function (result) {
        return JSON.parse(result);
    });
}

Artemis.prototype.listConnectionsWithSessions = function () {
    var self = this;
    return this.listConnections().then(function (conns) {
        return Promise.all(conns.map(function (c) { return self.listSessionsForConnection(c.connectionID)})).then(function (sessions) {
            for (var i in conns) {
                conns[i].sessions = sessions[i];
            }
            return conns;
        });
    });
}

Artemis.prototype.listConsumers = function () {
    return this._request('broker', 'listAllConsumersAsJSON', []).then(function (result) {
        return JSON.parse(result);
    });
}

Artemis.prototype.listProducers = function () {
    return this._request('broker', 'listProducersInfoAsJSON', []).then(function (result) {
        return JSON.parse(result);
    });
}

Artemis.prototype.getGlobalMaxSize = function ()
{
    return this._request('broker', 'getGlobalMaxSize', []);
}

/**
 * Create connector service if one does not already exist.
 */
Artemis.prototype.ensureConnectorService = function (connector) {
    var broker = this;
    return broker.findConnectorService(connector.name).then(
        function (found) {
            if (!found) {
                return broker.createConnectorService(connector);
            }
        }
    );
};

Artemis.prototype.findConnectorService = function (name) {
    return this.getConnectorServices().then(
        function (results) {
            return results.indexOf(name) >= 0;
        }
    );
};

Artemis.prototype.close = function () {
    if (this.connection) {
        var connection = this.connection;
        return new Promise(function (resolve) {
            connection.on('connection_close', resolve);
            connection.on('connection_error', resolve);
            connection.close();
        });
    } else {
        return Promise.resolve();
    }
}

module.exports.Artemis = Artemis;
module.exports.connect = function (options) {
    return new Artemis(amqp.connect(options));
}


text:
import itertools
import argparse
import sys

# Dear argparse, Thank you for existing and making life tolerable. Your pal, Gary
parser = argparse.ArgumentParser(description='Generate an (n)fecta sheet for betting on the order of multiple outcomes.')
parser.add_argument('-o', '--file', dest='file', default='trifecta.html')
# add support for a list of racer names instead of numbers
parser.add_argument('-r', '--racers', dest='racers', help='How many elements to choose from')
parser.add_argument('-x', '--fecta-factor', dest='fecta', help='How many choices to make in each permutation.', default='3')
parser.add_argument('-c', '--cols', dest='chart_cols', default='8')
parser.add_argument('-R', '--rows', dest='chart_rows', default='10')
parser.add_argument('-b', '--breaks', dest='breaks', default=True)
parser.add_argument('-p', '--paper', dest='paper', choices=['U', 'A'], default='U',
                    help='Choose between US Letter and 8A page formatting.')
parser.add_argument('-t', '--first-ticket', dest='ticket', help='First ticket serial number.', default=1)
parser.add_argument('-T', '--title', dest='title')
args = parser.parse_args(sys.argv[1:])

outfile = open(args.file, 'w')
title = str(args.title)
racers = range(1, int(args.racers)+1, 1)
fecta = int(args.fecta)
chart_cols = int(args.chart_cols)
chart_rows = int(args.chart_rows)
fecta_iterator = itertools.permutations(tuple(racers), fecta)
fecta_list = list(fecta_iterator)
fecta_cellcount = len(fecta_list) + 1
fecta_rows = []
for rowstart in range(0, len(fecta_list), chart_cols):
    fecta_rows.append(fecta_list[rowstart:rowstart + chart_cols])

outfile.write('\n\n<title>' + title + '</title>\n')
outfile.write('\n\n')
outfile.write('\n
\n')
curcell = 1
currow = 1
for row in fecta_rows:
    outfile.write("
")
    for cell in row:
        cell = str(cell).translate(None, '(),')
        outfile.write("
" + str(curcell) + "
" + str(cell) + "	")
        curcell += 1
    outfile.write("
\n")
    if currow % 10 == 0:
        outfile.write("
\n

\n
\n")
    currow += 1
outfile.write("
\n")
outfile.write("\n")

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var Helper = require('./test_helper.js').Helper; // helper module
var stringArray = Helper.stringArray;

var showProblem = function(arg1, stub_res) {
    var msg = '';
    msg += 'The list is ' + stringArray(arg1) + '. \n';
    msg += 'The different number is ' + stub_res + ' .\n';
    return msg;
};

var notEqual = function(arg1, stub_res, result) {
    var msg = showProblem(arg1, stub_res);
    msg += 'Your answer ' + result + ' is wrong .\n';
    return msg;
};

exports.notEqual = notEqual;


text:
@interface PodsDummy_Pods_Decoration : NSObject
@end
@implementation PodsDummy_Pods_Decoration
@end


text:
define(['underscore', 'backbone', 'jquery'], function(){
  var NoteView = Backbone.View.extend({

    template: _.template('
<%= title %>

<%= body %>
'),

    initialize: function(options){
      this.model.bind('change', this.render, this)
      this.model.fetch()
    },

    render: function() {
      var json = this.model.toJSON()
      var html = this.template(json)
      $(this.el).html(html)
      return this
    }
  })
  return NoteView
})


text:
![AddAndSubtract](http://wx3.sinaimg.cn/mw690/4c8b519dly1fcaq7v2pnvg20ho0wgh0z.gif)

#### Example

```JavaScript
import Template from 'rnx-ui/Template';

function Example(props) {
  return (
    <AddAndSubtract
      num={this.state.num}
      onPressAdder={this.add}
      onPressSubtracter={this.subtract}
    />
  );
}
```


text:
This is an easy way to enter into the Microsoft Azure Nodevember Competition!

There is an easier way, from [Sarah Sexton](https://github.com/SarahSexton) here: [Microsoft Azure](https://github.com/SarahSexton/NodevemberMS/blob/master/README.md)

The difference here is that you'll need to set up your Azure account, add an app, and add a new Azure remote to which you can push your code. A good tutorial can be found [here](http://blogs.msdn.com/b/sarahsays/archive/2015/08/31/building-your-first-node-js-app-and-publishing-to-azure.aspx) and [here](https://azure.microsoft.com/en-us/documentation/articles/web-sites-nodejs-develop-deploy-mac/)

## Whatsit do?

If you hit the root URL, you'll be given the taxonomic data for the Class Cephalopoda Cuvier.

## How's it work?

It uses [hapi.js](http://hapijs.com) to create a server that returns a JSON representation of the Cephalopods.

## IMPORTANT NOTE

When creating a server, you need to assign it a port. Azure will assign your port to you, and the way to access that can be found here:

```javascript
const port = process.env.PORT || 8080;
```

What's happening here is that Azure is setting the port number in the environment variable 'PORT', and the application is reading that. If it's not set, the port defaults to '8080'.

Good luck!


text:
:- module('logen_filter', [typedef/2,
                           filter_atom_with_filter_types/4,
                           generalise_with_filter_types/3]).

:- use_module(annfile, [user_type/2]).
:- use_module(logen_messages).
:- use_module(library(lists)).
:- use_module(logen_attributes).
:- use_module(library(terms),[term_variables/2]).

typedef(list(T),(struct([],[]) ; struct('.',[T,type(list(T))]))).
typedef(static_or_dynamic,(static ; dynamic)).
/* typedef(model_elim_literal,(struct(pos,[nonvar]) ; struct(neg,[nonvar]))).
typedef(channel, (struct(io,[type(list(dynamic)),nonvar]))).
typedef(rename_unit, (struct('<-',[type(channel),type(channel)]))).
typedef(csp,(struct(stop,[]) ;
             struct(skip,[]) ;
             struct(omega,[]);
             struct(agent_call,[nonnonvar]) ;
             struct(rename,[type(csp),type(list(type(rename_unit)))]) ;
             struct(hide,[type(csp),type(list(type(channel)))]) ;
             struct(prefix,[type(list(nonvar)),static,type(csp)]) ;
             struct(prefix,[type(list(nonvar)),static,nonvar,type(csp)]) ;
             struct(interleave,[type(csp),type(csp)]) ;
             struct(par,[type(csp),type(list(type(channel))),type(csp)]) ;
             struct(choice,[type(csp),type(csp)]) ;
             struct(int_choice,[type(csp),type(csp)]) ;
             struct(let,[dynamic,dynamic,type(csp)]) ;
             struct(if,[nonvar,type(csp),type(csp)]) ;
             struct(if,[nonvar,type(csp)])
	     )).
*/
typedef(Type,Def) :- user_type(Type,Def).  /* from annfile  */

/* ---------------------------------------------------------- */
/* filter_atom(Atom,ResultingFilteredAtom) */
/* ---------------------------------------------------------- */

filter_atom_with_filter_types(Module,Atom,AllArgTypes,FilteredAtom) :-
        Atom =..[Predicate|Arguments],
	((member(ArgTypes,AllArgTypes),
	  l_type_filter(ArgTypes,Arguments,[],RDynamicArguments))
	 -> (reverse(RDynamicArguments,DynamicArguments),
	     make_new_predicate_name(Module, Predicate, NewPred, FilteredAtom),
	     FilteredAtom =.. [NewPred|DynamicArguments])
	 ;  (print_error('*** WARNING: unable to filter: '), print_error(Atom),
	     print_error(AllArgTypes),
	     FilteredAtom = error_in_filter(Atom),
	     detect_error(AllArgTypes,Arguments))
	).

detect_error([ArgTypes],Arguments) :- !,
  /* if a single filter declaration: find source of error */
   l_detect_error(ArgTypes,Arguments).
detect_error(_,_).

l_detect_error([],[]).
l_detect_error([Type1|TT],[A1|AT]) :-
    (type_filter(Type1,A1,[],_)
     ->  l_detect_error(TT,AT)
     ;   (print_error(filter_argument_not_of_type(A1,Type1)),
          (type_check(Type1,A1)->true;true))
    ).

make_new_predicate_name(Module, Predicate, NewPred, FilteredAtom) :-
	(nonvar(FilteredAtom) ->
            FilteredAtom =.. [NewPred|_]   % already named
	;
            (getattr(Module, gensym, N) -> true ; N=0),
            N1 is N+1,
            setattr(Module, gensym, N1),
            name(PE_Sep,"__"),
            string_concatenate(Predicate,PE_Sep,IntPred),
	        string_concatenate(IntPred,N,NewPred)
	).

string_concatenate(X,Y,XY) :-
   name(X,Xs),name(Y,Ys),append(Xs,Ys,XYs),name(XY,XYs).

% ____________________________________________________________

:- use_module(intersectiontypes).

%%added by steve
type_filter(clp,Argument,ArgList,[Argument|ArgList]). /* treat as dynamic */
type_filter(clp(_,_),Argument,ArgList,[Argument|ArgList]). /* treat as dynamic */

type_filter(static,_Argument,ArgList,ArgList) :- ground(_Argument).
type_filter(static_nf,Argument,ArgList,[Argument|ArgList]) :- ground(Argument).
    /* mal: added groundness check so that we can use static in disjunctive types */
type_filter(dynamic,Argument,ArgList,[Argument|ArgList]).
type_filter(semi,Argument,ArgList,Res) :-  % [Argument|ArgList]) :-
  term_variables(Argument,Vars),
  reverse(Vars,RVars),
  append(RVars,ArgList,Res). /* treat as dynamic */
type_filter(free,_Argument,ArgList,ArgList) :- var(_Argument).
         /* mal: added var check so that we can use free in disjunctive types */
type_filter(static_or_free,_Argument,ArgList,ArgList).
        /* this corresponds to the original static of the '96 paper, in case somebody needs it */
type_filter(nonvar(Type),Argument,InArgList,OutArgList) :-
    nonvar(Argument),
    Argument =.. [_F|FArgs],
    l_type_filter2(Type,FArgs,InArgList,OutArgList).
type_filter(nonvar,Argument,InArgList,OutArgList) :-
    nonvar(Argument),
    Argument =.. [_F|FArgs],
    rev_acc(FArgs,InArgList,OutArgList).
type_filter(nonvar_nf,Argument,ArgList,[Argument|ArgList]). /* nonvar_no filter */
type_filter(nonnonvar,Argument,InArgList,OutArgList) :-
    nonvar(Argument),
    Argument =.. [_F|FArgs],
    make_copies(FArgs,nonvar,TList),
    l_type_filter(TList,FArgs,InArgList,OutArgList).
type_filter((Type1 ; _Type2),Argument,InArgList,OutArgList) :-
    type_filter(Type1,Argument,InArgList,OutArgList).
type_filter((_Type1 ; Type2),Argument,InArgList,OutArgList) :-
    type_filter(Type2,Argument,InArgList,OutArgList).
type_filter(type(F),Argument,InArgList,OutArgList) :-
    typedef(F,TypeExpr),
    type_filter(TypeExpr,Argument,InArgList,OutArgList).
type_filter(list(F),Argument,InArgList,OutArgList) :-
    typedef(list(F),TypeExpr),
    type_filter(TypeExpr,Argument,InArgList,OutArgList).
type_filter(struct(F,TArgs),Argument,InArgList,OutArgList) :-
    nonvar(Argument),
    Argument =.. [F|FArgs],
    l_type_filter(TArgs,FArgs,InArgList,OutArgList).
type_filter([IT1|RT],Argument,InArgList,OutArgList) :-
     filter_intersection_type([IT1|RT],Argument,InArgList,OutArgList).

l_type_filter([],[],Args,Args).
l_type_filter([Type1|TT],[A1|AT],InArgList,OutArgList) :-
    type_filter(Type1,A1,InArgList,IntArgList),
    l_type_filter(TT,AT,IntArgList,OutArgList).

l_type_filter2(_,[],Args,Args).
l_type_filter2(Type1,[A1|AT],InArgList,OutArgList) :-
    type_filter(Type1,A1,InArgList,IntArgList),
    l_type_filter2(Type1,AT,IntArgList,OutArgList).

rev_acc([],Args,Args).
rev_acc([A1|AT],InArgList,OutArgList) :-
    rev_acc(AT,[A1|InArgList],OutArgList).

%type_check(T,A) :- print_error(type_check(T,A)),nl,fail.
%New type checker, for better diagnostic
type_check(clp,_). /* treat as dynamic */
type_check(clp(_,_),_). /* treat as dynamic */
type_check(static,A) :-
  (ground(A) -> true ; (print_error(not_static(A)),fail)).
type_check(static_nf,A) :-
  (ground(A) -> true ; (print_error(not_static(A)),fail)).
type_check(dynamic,_).
type_check(semi,_). /* treat as dynamic */
type_check(free,A) :-
  (var(A) -> true ; (print_error(not_free(A)),fail)).
type_check(static_or_free,_).
type_check(nonvar(Type),A) :-
    (nonvar(A) -> (A =.. [_F|FArgs], l_type_check2(Type,FArgs))
               ;  (print_error(not_nonvar(A)),fail)).
type_check(nonvar,A) :-
    (nonvar(A) -> true  ; (print_error(not_nonvar(A)),fail)).
type_check(nonvar_nf,A) :-
    (nonvar(A) -> true  ; (print_error(not_nonvar_nf(A)),fail)).
type_check(nonnonvar,A) :-
    (nonvar(A) -> (A =.. [_F|FArgs],
                   make_copies(FArgs,nonvar,TList),
                   l_type_check(TList,FArgs))
               ; (print_error(not_nonvar(A)))
    ).
type_check((Type1 ; Type2),A) :-
    (type_check(Type1,A)
      -> true
      ;  (type_check(Type2,A) -> true ; print_error(not_or(Type1,Type2,A)))
     ).
type_check(type(F),A) :-
    typedef(F,TypeExpr),
    print_message(informational,typedef(F,TypeExpr,A)),
    type_check(TypeExpr,A).
type_check(list(F),A) :-
    typedef(list(F),TypeExpr),
    type_check(TypeExpr,A).
type_check(struct(F,TArgs),A) :-
    ((nonvar(A),A =.. [F|FArgs])
      -> l_type_check(TArgs,FArgs)
      ;  (print_error(not_struct(F,A)),fail)).
type_check([IT1|RT],A) :-
     (filter_intersection_type([IT1|RT],A,[],_)
      -> true ; (print(not_intersection_type([IT1|RT],A)),fail)).

l_type_check([],[]).
l_type_check([Type1|TT],[A1|AT]) :-
    type_check(Type1,A1),l_type_check(TT,AT).

l_type_check2(_,[]).
l_type_check2(Type1,[A1|AT]) :-
    type_check(Type1,A1),l_type_check2(Type1,AT).

/* ---------------------------------------------------------- */
/* generalise_with_filter_types(Atom,FilterTypes,ResultingGenAtom) */
/* ---------------------------------------------------------- */

generalise_with_filter_types(Call,[],GCall) :-  !,
    print_error('*** no filter; unable to generalise: '),print_error(Call),GCall=Call.
generalise_with_filter_types(Call,AllArgTypes,GCall) :-
    ((member(ArgTypes,AllArgTypes),
      Call =.. [F|FArgs],
      l_generalise(ArgTypes,FArgs,GArgs),
      (GCall =..[F|GArgs]) )
    ->
       true
    ;
     (print_error('*** WARNING: unable to generalise: '), print_error(Call),
      GCall = Call,
      Call =.. [_|FArgs],
      detect_error(AllArgTypes,FArgs))
    ).

:- use_module(intersectiontypes).
generalise_using_type(static_nf,Argument,Argument) :- ground(Argument).
generalise_using_type(static,Argument,Argument) :- ground(Argument).
           /* mal: added groundness check so that we can use static in disjunctive types,
                  one can avoid the overhead of the check for non-disjunctive types by
                  using static_or_free introduced below */
generalise_using_type(dynamic,_Argument,_FreshVariable).
generalise_using_type(free,_Argument,_FreshVariable) :- var(_Argument).
         /* mal: added var check so that we can use free in disjunctive types */
generalise_using_type(static_or_free,Argument,Argument).
        /* this corresponds to the original static of the '96 paper, in case somebody needs it */
generalise_using_type(nonvar(Type),Argument,GenArgument) :-
    (nonvar(Argument) ->
     (Argument =.. [F|FArgs],
      make_fresh_variables(FArgs,FVArgs),
      l_generalise2(Type,FVArgs,GArgs),
      GenArgument =..[F|GArgs] )
     ; (fail)
     ).
generalise_using_type(nonvar_nf,Argument,GenArgument) :-  generalise_using_type(nonvar,Argument,GenArgument).
generalise_using_type(nonvar,Argument,GenArgument) :-
    (nonvar(Argument) ->
     (Argument =.. [F|FArgs],
      make_fresh_variables(FArgs,GArgs),
      GenArgument =..[F|GArgs] )
     ; (fail)
     ).
generalise_using_type(nonnonvar,Argument,GenArgument) :-
    (nonvar(Argument) ->
     (Argument =.. [F|FArgs],
      make_copies(FArgs,nonvar,TList),
      l_generalise(TList,FArgs,GArgs),
      GenArgument =..[F|GArgs] )
     ; (fail)
     ).
generalise_using_type((Type1 ; _Type2),Argument,GenArgument) :-
    generalise_using_type(Type1,Argument,GenArgument).
generalise_using_type((_Type1 ; Type2),Argument,GenArgument) :-
    generalise_using_type(Type2,Argument,GenArgument).
generalise_using_type(list(X),Argument,GenArgument) :-
    /* special case for list: so that users do not have to use type(list(.)) */
    typedef(list(X),TypeExpr),
    generalise_using_type(TypeExpr,Argument,GenArgument).
generalise_using_type(type(F),Argument,GenArgument) :-
    typedef(F,TypeExpr),
    generalise_using_type(TypeExpr,Argument,GenArgument).
generalise_using_type(struct(F,TArgs),Argument,GenArgument) :-
    (nonvar(Argument) ->
     (Argument =.. [F|FArgs],
      l_generalise(TArgs,FArgs,GArgs),
      GenArgument =..[F|GArgs] )
     ; (fail)
     ).
generalise_using_type(semi,Argument,Argument). /* treat as static for generalisation */
generalise_using_type([IT1|RT],Argument,GenArgument) :-
    generalise_using_intersection_type([IT1|RT],Argument,GenArgument).

%%added by Steve
generalise_using_type(clp,Argument,Argument). /* treat as static for generalisation */
generalise_using_type(clp(_,_),Argument,Argument). /* treat as static for generalisation */

l_generalise([],[],[]).
l_generalise([Type1|TT],[A1|AT],[G1|GT]) :-
    generalise_using_type(Type1,A1,G1),
    l_generalise(TT,AT,GT).

l_generalise2(_,[],[]).
l_generalise2(Type1,[A1|AT],[G1|GT]) :-
    generalise_using_type(Type1,A1,G1),
    l_generalise2(Type1,AT,GT).

/* needs access to filter */
/* Not used anymore ??!!
generalise(Call,GCall) :-
	findall(AArgTypes,filter(Call,AArgTypes),ListOfArgTypes),
    (( ((ListOfArgTypes\=[]) -> true ; (print_error('*** no filter '),fail)),
      member(ArgTypes,ListOfArgTypes),
      Call =.. [F|FArgs],
      l_generalise(ArgTypes,FArgs,GArgs),
      (GCall =..[F|GArgs]) )
    ->
       true
    ;
     (print_error('*** WARNING: unable to generalise: '), print_error(Call),
      print_error('*** Filters: '), print_error(ListOfArgTypes),
      GCall = Call)
    ).
  ---- */

make_fresh_variables([],[]).
make_fresh_variables([_|T],[_|FT]) :-
    make_fresh_variables(T,FT).


text:
#ifndef UV_TEXTURE_H
#define UV_TEXTURE_H

#include <memory>
#include "texture.h"
#include "texture_mapping.h"

/*
 * Procedural texture that displays the st texture coordinates
 * as RG color values
 */
class UVTexture : public Texture {
	std::unique_ptr<TextureMapping> mapping;

public:
	UVTexture(std::unique_ptr<TextureMapping> mapping);
	/*
	 * Sample the texture color for the piece of geometry being textured
	 */
	Colorf sample(const DifferentialGeometry &dg) const override;
	/*
	 * Sometimes we want to re-use a texture but through a different mapping
	 * This method samples the texture directly using the texture sample passed in
	 */
	Colorf sample(const TextureSample &sample) const override;
};

#endif


text:
{-# LANGUAGE DataKinds, PolyKinds, TypeOperators, TypeFamilies #-}

module DumpParsedAst where

data Peano = Zero | Succ Peano

type family Length (as :: [k]) :: Peano where
  Length (a : as) = Succ (Length as)
  Length '[]      = Zero

main = putStrLn "hello"


text:
Ces différents plugins permettent de récupérer et envoyer des données depuis GotoMeeeting, GotoWebinar, GotoTraining et GoToAssist.

## Fonctionnalités

1. Crée les inscrits dans GoToWebinar et GoToTraining en fonction des décisions de campagne, des données du contact et de l'negistrement depuis les formulaires Mautic.
2. Renvoie les inscrits et participants depuis Citrix dans les segments et les campagnes.
3. Affiche la participation aux webinaire et formations (training) comme information complémentaire dans le fil d'activité du contact.
4. Envoi des emails avec les boutons de démarrage des événements GoToMeeting, GoToTraining et GoToAssist.

## Instructions
1. Activez le plugin de votre choix

![image](https://cloud.githubusercontent.com/assets/2924026/19797584/54467954-9ca9-11e6-8e31-f80f7469fe84.png)

2. Activez l plugin avec les clés API Citrix Developer

![image](https://cloud.githubusercontent.com/assets/2924026/19797588/5c6ce640-9ca9-11e6-981c-a98a728e1712.png)

3. Renseignez la "Consumer Keys" depuis le site développeur de Citrix

![image](https://cloud.githubusercontent.com/assets/2924026/19797595/612744f0-9ca9-11e6-90b0-566fdff69ef4.png)

4. De nouveaux filtres de segments sont désormais disponibles

![image](https://cloud.githubusercontent.com/assets/2924026/19797599/655fb6ce-9ca9-11e6-9d27-9ec295068a1a.png)

5. Vous pourrez sélectionner les événements passés

![image](https://cloud.githubusercontent.com/assets/2924026/19797600/69dd3604-9ca9-11e6-8212-7a0a383bff34.png)

6. De nouveaux types de champs sont disponibles dans les formulaires

![image](https://cloud.githubusercontent.com/assets/2924026/19798154/9954bf30-9cac-11e6-8173-06acc0ca1fa1.png)

7. Le champ affiche les événements disponibles à venir (le formulaire vérifira que vous avez bien utilisé tous les champs obligatoires à l'inscription aux événements)

![image](https://cloud.githubusercontent.com/assets/2924026/19797605/72ec51e4-9ca9-11e6-8416-be31a013c8d1.png)

8. Une nouvelle action de formulaire est disponible

![image](https://cloud.githubusercontent.com/assets/2924026/19797611/7699f9c2-9ca9-11e6-96f5-d90dcafcbd3f.png)

9. Chaque action permet vous permet de choisir d'afficher un seul événement ou de laisser le visiteur choisir parmis la liste d'événements depuis le formulaire.

![image](https://cloud.githubusercontent.com/assets/2924026/19797613/7b25eb68-9ca9-11e6-99c7-d9f4053136ac.png)

10. Voici un exemple de formulaire qui laisse le choix au visiteur

![image](https://cloud.githubusercontent.com/assets/2924026/19797614/7eea2f02-9ca9-11e6-86dd-c895bb0d65c3.png)

11. L'action d'envoi du lien de participation à l'événement nécessite d'utiliser un Token pour insérer le lien dans le contenu de l'email (sur le bouton par exemple)

![image](https://cloud.githubusercontent.com/assets/2924026/19797615/82b326f2-9ca9-11e6-9d30-1324b7efd49a.png)

12. Il existe de nouvelles conditions dans les campagnes (*inscrit* et *à participé*)

![image](https://cloud.githubusercontent.com/assets/2924026/19797618/8693fb8e-9ca9-11e6-8ae2-44b67f05769e.png)

13. Vous pouvez déclencher des actions spécifiques depuis les campagnes

![image](https://cloud.githubusercontent.com/assets/2924026/19797619/8a501b68-9ca9-11e6-8232-d5c23b9cf445.png)

14. Voici un exemple de campagne qui envoie le lien pour un rendez-vous préliminaire après l'inscription du contact à un webinaire

![image](https://cloud.githubusercontent.com/assets/2924026/19797623/8d7b1252-9ca9-11e6-9370-b3f05cc08ee1.png)

15. Dans cet exemple, le formulaire a été soumis

![image](https://cloud.githubusercontent.com/assets/2924026/19797632/9122e614-9ca9-11e6-991c-70b2033ea6c9.png)

16. L'événement est inscrit dans le fil d'actualité du contact

![image](https://cloud.githubusercontent.com/assets/2924026/19797638/9484bb7a-9ca9-11e6-9a18-62eab010378e.png)

17. L'email avec le lien de participation à l'événement (injecté grace au token) et vue dans le navigateur

![image](https://cloud.githubusercontent.com/assets/2924026/19797642/986c9c30-9ca9-11e6-9233-5e826f2520b9.png)

18. Lorsque le contact clique sur le lien, il sera redirigé vers l'événement et il démarrera

![image](https://cloud.githubusercontent.com/assets/2924026/19797644/9c6e43ce-9ca9-11e6-8f45-ec36b19502fa.png)

19. Ceci est un exemple d'un webinaire où le contact a participé

![image](https://cloud.githubusercontent.com/assets/2924026/19797647/a012bfb4-9ca9-11e6-8d27-92edfb071bfb.png)

20. Quand le CRON qui synchronise les données est activé, il récupère les données de participations et d'événements

![image](https://cloud.githubusercontent.com/assets/2924026/19797652/a435ee36-9ca9-11e6-9936-17cd19384452.png)

#### Les exemples ci dessus utilisent GoToMeeting et GoToWebinar, les méthodologies sont identiques pour GoToTraining et GoToAssist

### Paramétrage du CRON
Le CRON à paramétrer pour la synchronisation des données est :

`php app/console citrix:sync`

##### Usage
citrix:sync [options]

#### Options
* -p, --product[=PRODUCT]  Product to sync (webinar, meeting, training, assist)
* -i, --id[=ID]            The id of an individual registration to sync


text:
'use strict';
const should = require('should');
const recurse = require('../packages/reftools/lib/recurse.js').recurse;

describe('recurse',function(){
    describe('simple',function(){
        it('should traverse a simple nested object',function(){

            const input = { container: { child: { value: true, string: '1234' }, child2: { value: false, '{id}': { test: 'abc' } } } };
            let output = [];
            recurse(input,{},function(obj,key,state){
                let entry = {};
                entry.obj = obj;
                entry.key = key;
                entry.state = state;
                output.push(entry);
            });

            output.should.be.an.Array();
            should(output.length).equal(8);
            output[0].key.should.equal('container');
            output[0].obj.should.equal(input);
            output[0].state.depth.should.equal(0);
            output[0].state.path.should.equal('#');
            output[0].state.parent.should.deepEqual({});

            output[1].key.should.equal('child');
            output[1].obj.should.equal(input.container);
            output[1].state.depth.should.equal(1);
            output[1].state.path.should.equal('#/container');
            output[1].state.parent.should.equal(input);

            output[2].key.should.equal('value');
            output[2].obj.should.equal(input.container.child);
            output[2].state.depth.should.equal(2);
            output[2].state.path.should.equal('#/container/child');
            output[2].state.parent.should.equal(input.container);

            output[3].key.should.equal('string');
            output[3].obj.should.equal(input.container.child);
            output[3].state.depth.should.equal(2);
            output[3].state.path.should.equal('#/container/child');
            output[3].state.parent.should.equal(input.container);

            output[4].key.should.equal('child2');
            output[4].obj.should.equal(input.container);
            output[4].state.depth.should.equal(1);
            output[4].state.path.should.equal('#/container');
            output[4].state.parent.should.equal(input);

            output[5].key.should.equal('value');
            output[5].obj.should.equal(input.container.child2);
            output[5].state.depth.should.equal(2);
            output[5].state.path.should.equal('#/container/child2');
            output[5].state.parent.should.equal(input.container);

            output[6].key.should.equal('{id}');
            output[6].obj.should.equal(input.container.child2);
            output[6].state.depth.should.equal(2);
            output[6].state.path.should.equal('#/container/child2');
            output[6].state.parent.should.equal(input.container);

            output[7].key.should.equal('test');
            output[7].obj.should.equal(input.container.child2["{id}"]);
            output[7].state.depth.should.equal(3);
            output[7].state.path.should.equal('#/container/child2/%7Bid%7D');
            output[7].state.parent.should.equal(input.container.child2);
        });
    });
    it('should not traverse a string',function(){
        let calls = 0;
        recurse('hello',{},function(obj,key,state){
            calls++;
        });
        calls.should.be.exactly(0);
    });
    it('should not traverse a boolean',function(){
        let calls = 0;
        recurse(true,{},function(obj,key,state){
            calls++;
        });
        calls.should.be.exactly(0);
    });
    it('should not traverse a number',function(){
        let calls = 0;
        recurse(1,{},function(obj,key,state){
            calls++;
        });
        calls.should.be.exactly(0);
    });
    it('should not traverse a null',function(){
        let calls = 0;
        recurse(null,{},function(obj,key,state){
            calls++;
        });
        calls.should.be.exactly(0);
    });
    it('should traverse an array',function(){
        let calls = 0;
        recurse([0,1,2],{},function(obj,key,state){
            calls++;
        });
        calls.should.be.exactly(3);
    });

    describe('identity',function(){
        it('should detect object identity',function(){
            const input = { solo: '123' };
            const a = { hello: 'sailor' };
            input.b = a;
            input.c = a;
            recurse(input,{identityDetection:true},function(obj,key,state){
                if (key === 'solo') {
                    obj[key].should.equal(input.solo);
                    state.identity.should.be.exactly(false);
                }
                else if (key === 'b') {
                    state.identity.should.be.exactly(false);
                }
                else if (key === 'hello') {
                    state.identity.should.be.exactly(false);
                }
                else if (key === 'c') {
                    should(state.identityPath).not.be.undefined();
                    state.identity.should.be.exactly(true);
                    state.identityPath.should.be.exactly('#/b');
                }
            });
        });
    });
    describe('null',function(){
        it('should be able to recurse through an object with nulls',function(){
            recurse({test:null},{},function(obj,key,state){
                key.should.be.equal('test');
                should(obj[key]).be.exactly(null);
            });
        });
    });
    describe('null',function(){
        it('should be able to recurse through an object with nulls, id',function(){
            recurse({test:null},{identityDetection:true},function(obj,key,state){
                key.should.be.equal('test');
                should(obj[key]).be.exactly(null);
            });
        });
    });
});


text:
namespace HEX {

typedef unsigned int uint;
enum class NodeColor { UNOCCUPIED, RED, BLUE };

class Board {
public:
    typedef std::unordered_map<uint, NodeColor> NodeStatusMap;

public:
    const static uint N = 11;

    Board();

    Board(const Board& rhs_board);

    ~Board() {}

    // return surround nodes' index for a specific node in HEX board
    std::vector<uint> get_surround_nodes(uint row, uint col);

    // return current unoccupied nodes in the board
    std::vector<uint> get_available_nodes();

    // check whether there is a full path between two opposite sides
    bool has_complete_path(NodeColor node_color);

    void draw_board();

    // recover board to the original status
    inline void reset_board() {
        uint node_size = N * N;
        for (uint i = 0; i < node_size; ++i)
            m_node_status_map[i] = NodeColor::UNOCCUPIED;
    }

    // returns board node's status, eg NodeColor::UNOCCUPIED
    inline NodeColor get_node_status(uint x) {
        assert (m_node_status_map.count(x) == 1);
        return m_node_status_map[x];
    }

    // set board node's color
    inline void set_node_color(uint x, NodeColor color) {
        assert (m_node_status_map.count(x) == 1);
        assert (color == NodeColor::RED || color == NodeColor::BLUE);
        m_node_status_map[x] = color;
    }

    inline std::pair<uint, uint> number2loc(uint x) {
        assert (x >= 0 && x < N * N);
        uint row, col;
        row = static_cast<uint>(x/N);
        col = x%N;
        return std::make_pair(row, col);
    }

    inline uint loc2number(uint row, uint col) {
        assert(row >= 0 && row < N);
        assert(col >= 0 && col < N);
        return row * N + col;
    }

private:
    std::list<std::list<uint> > make_union(NodeColor node_color, uint row, std::unordered_map<uint, int>& curr_union_map);

    std::unordered_set<int> prev_unions(std::list<uint>& u, std::unordered_map<uint, int>& prev_union_map);

    bool merge_union(std::list<uint>& u1, std::list<uint>& u2, std::unordered_map<uint, int>& prev_union_map);

private:
    NodeStatusMap m_node_status_map;
};

} // namespace HEX

#endif // BOARD_H


text:
module.exports = function(app, express){

    // CONFIG INCLUDES
    //var db            = require('./database');

    // ==============================================================================================================
    // ROOT ---------------------------------------------------------------------------------------------------------

    app.get('/', function(req, res) {
        res.json({});
    });

    // ==============================================================================================================
    // CONTROLS INTERFACE -------------------------------------------------------------------------------------------

    app.get('/stream', function(req, res) {
            var fileSystem = require('fs'),
                path       = require('path'),
                filePath   = path.join(__dirname, '../../../media/09 And War (feat. Molly Dean).mp3'),
                // filePath   = path.join(__dirname, '../../media/02 Naysayer.mp3'),
                stat       = fileSystem.statSync(filePath);

            res.writeHead(200, {
                'Content-Type': 'audio/mp4',
                'Content-Length': stat.size
            });

            var readStream = fileSystem.createReadStream(filePath);
            readStream.on('end', _handleEndStream);
            readStream.pipe(res);
    });

    // ==============================================================================================================
    // 404 ----------------------------------------------------------------------------------------------------------

    app.use(function(req, res, next) {

        // Unregistered mapping? Send 404 response
        // res.status(404).render('404');
        res.json({error:'error'});
    });

    function _handleEndStream(e) {
        console.log('_handleEndStream');
    }

};


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace MO.Core.Window.Core.Hook {

   public class FMouseHook  : FWindowHook {

      public FMouseHook() {
         _type = EHookType.MouseLL;
      }

      public override bool Process(int code, IntPtr wparam, IntPtr lparam) {
         /*// if ok and someone listens to our events
         if ((nCode >= 0) && (OnMouseActivity != null)) {
            //Marshall the data from callback.
            MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));

            //detect button clicked
            MouseButtons button = MouseButtons.None;
            short mouseDelta = 0;
            switch (wParam) {
               case WM_LBUTTONDOWN:
                  //case WM_LBUTTONUP:
                  //case WM_LBUTTONDBLCLK:
                  button = MouseButtons.Left;
                  break;
               case WM_RBUTTONDOWN:
                  //case WM_RBUTTONUP:
                  //case WM_RBUTTONDBLCLK:
                  button = MouseButtons.Right;
                  break;
               case WM_MOUSEWHEEL:
                  //If the message is WM_MOUSEWHEEL, the high-order word of mouseData member is the wheel delta.
                  //One wheel click is defined as WHEEL_DELTA, which is 120.
                  //(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value
                  mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff);
                  //TODO: X BUTTONS (I havent them so was unable to test)
                  //If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
                  //or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
                  //and the low-order word is reserved. This value can be one or more of the following values.
                  //Otherwise, mouseData is not used.
                  break;
            }

            //double clicks
            int clickCount = 0;
            if (button != MouseButtons.None)
               if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2;
               else clickCount = 1;

            //generate event
            MouseEventArgs e = new MouseEventArgs(
                                               button,
                                               clickCount,
                                               mouseHookStruct.pt.x,
                                               mouseHookStruct.pt.y,
                                               mouseDelta);
            //raise it
            OnMouseActivity(this, e);
         }*/
         return false;
      }

   }

}


text:
@implementation CHSMultipartMessageHeader
@synthesize fields,encoding;

- (id) initWithData:(NSData *)data formEncoding:(NSStringEncoding) formEncoding {
	if( nil == (self = [super init]) ) {
        return self;
    }

	fields = [[NSMutableDictionary alloc] initWithCapacity:1];

	// In case encoding is not mentioned,
	encoding = contentTransferEncoding_unknown;

	char* bytes = (char*)data.bytes;
	NSInteger length = data.length;
	NSInteger offset = 0;

	// split header into header fields, separated by \r\n
	uint16_t fields_separator = 0x0A0D; // \r\n
	while( offset < length - 2 ) {

		// the !isspace condition is to support header unfolding
		if( (*(uint16_t*) (bytes+offset)  == fields_separator) && ((offset == length - 2) || !(isspace(bytes[offset+2])) )) {
			NSData* fieldData = [NSData dataWithBytesNoCopy:bytes length:offset freeWhenDone:NO];
			CHSMultipartMessageHeaderField * field = [[CHSMultipartMessageHeaderField alloc] initWithData: fieldData  contentEncoding:formEncoding];
			if( field ) {
				[fields setObject:field forKey:field.name];
				HTTPLogVerbose(@"CHSMultipartFormDataParser: Processed Header field '%@'",field.name);
			}
			else {
				NSString* fieldStr = [[NSString  alloc] initWithData:fieldData encoding:NSASCIIStringEncoding];
				HTTPLogWarn(@"CHSMultipartFormDataParser: Failed to parse MIME header field. Input ASCII string:%@",fieldStr);
			}

			// move to the next header field
			bytes += offset + 2;
			length -= offset + 2;
			offset = 0;
			continue;
		}
		++ offset;
	}

	if( !fields.count ) {
		// it was an empty header.
		// we have to set default values.
		// default header.
		[fields setObject:@"text/plain" forKey:@"Content-Type"];
	}

	return self;
}

- (NSString *)description {
	return [NSString stringWithFormat:@"%@",fields];
}

@end


text:
<?php

namespace flat\core\ssh\exception;
abstract class sftp extends \flat\core\ssh\exception {}


text:
Promises helped us with the painful experience we had with Callbacks and now Async functions allows to simply `await` on a Promise. We will cover all the three patterns with live coding to see how easy it is to write a cleaner code using async/await.

## Branch: async-await
Implementing CRUD using ES2016 async/await functions


text:
"""Main test class for app_cli"""
from src import app

class TestApp(object):

    def setup_method(self, _):
        self.app = app

    def test_function(self):
        self.app.set_name("test")
        assert self.app.get_name() == "test"


text:
class CreateDevices < ActiveRecord::Migration
  def self.up
    create_table :devices do |t|
      t.string :name
      t.text :description
      t.boolean :active

      t.timestamps
    end
  end

  def self.down
    drop_table :devices
  end
end


text:
function SFX() {
  this.context = new webkitAudioContext();
  this.osc = new context.createOscillator();
  this.osc.type = osc.SQUARE;
  this.osc.frequency.value = 220;

  this.filter = context.createBiquadFilter();
  this.filter.type = filter.LOWPASS;
  this.filter.frequency.value = 220;

  this.osc.connect(filter);
  this.filter.connect(context.destination);
};

SFX.prototype.mapFilter = function(f) {
  // expecting f in [0, 1]
  this.filter.frequency.value = 220 + f * 700;
};


text: A responsive static html/css website.


text:
.. _configure_service_broker:

.. toctree::
   :maxdepth: 2

=======================================
Murano service broker for Cloud Foundry
=======================================

Service broker overview
-----------------------

Service broker is a new murano component which implements `Cloud Foundry
<https://www.cloudfoundry.org/>`_ Service Broker API.

This lets users build 'hybrid' infrastructures that are services like databases, message
queues, key/value stores, and so on. This services can be uploaded and deployed with
murano and made available to Cloud Foundry apps on demand. The result is lowered cost,
shorter timetables, and quicker access to required tools — developers can 'self serve'
by building any required service, then make it instantly available in Cloud Foundry.

Configure service broker
------------------------

Manual installation
~~~~~~~~~~~~~~~~~~~

If you use local murano installation, you can configure and run murano service
broker in a few simple steps:

#. Change into the murano directory:

   .. code-block:: console

       cd ~/murano/murano

#. Generate the murano service broker config file.
   Murano service broker has a common config file for service broker API services.
   Using tox, generate a sample configuration file:

   .. code-block:: console

       tox -e gencfconfig

#. Copy the configuration file for further modifications:

   .. code-block:: console

       cd ~/murano/murano/etc/murano
       ln -s murano-cfapi.conf.sample murano-cfapi.conf

#. Edit ``murano-cfapi.conf``. Below is an example of the basic
   settings you may need to configure.

   .. note::

       The example below uses the SQLite database. Edit the **[database]**
       section to use another database.

   .. code-block:: ini

       [DEFAULT]
       debug = true
       verbose = true

       ...

       [database]
       backend = sqlalchemy
       connection = sqlite:///murano_cfapi.sqlite

       ...

       [keystone_authtoken]
       auth_uri = 'http://%OPENSTACK_HOST_IP%:5000/v3'
       auth_host = '%OPENSTACK_HOST_IP%'
       auth_port = 5000
       auth_protocol = http
       admin_tenant_name = %OPENSTACK_ADMIN_TENANT%
       admin_user = %OPENSTACK_ADMIN_USER%
       admin_password = %OPENSTACK_ADMIN_PASSWORD%

       ...

       [cfapi]
       tenant = %TENANT_NAME%
       bind_host = %HOST_IP%
       bind_port = 8083
       auth_url = 'http://%OPENSTACK_HOST_IP%:5000/v3'

   .. note::

       The ``bind_host`` IP should be in the same network as the
       Cloud Foundry instance.

#. Create database tables for murano service broker:

   .. code-block:: console

       cd ~/murano/murano
       tox -e venv -- murano-cfapi-db-manage \
         --config-file ./etc/murano/murano-cfapi.conf upgrade

#. Launch the murano service broker API in a separate terminal:

   .. code-block:: console

       cd ~/murano/murano
       tox -e venv -- murano-cfapi --config-file ./etc/murano/murano-cfapi.conf

   .. note::

       Run the command in a new terminal as the process will be running in
       the terminal until you terminate it, therefore, blocking the current
       terminal.

Devstack installation
~~~~~~~~~~~~~~~~~~~~~

It is really easy to enable service broker in your devstack installation.
You need simply update your :file:`local.conf` with the following:

    .. code-block:: ini

       [[local|localrc]]
       enable_plugin murano git://git.openstack.org/openstack/murano
       enable_service murano-cfapi

How to use service broker
-------------------------

After service broker is configured and started you have nothing to do with service
broker from murano side - it is an adapter which is used by Cloud Foundry PaaS.

To access and use murano packages through Cloud Foundry, you need to perform following steps:

#. Log in to Cloud Foundry instance via ssh.

   .. code-block:: console

      ssh -i <key_name> <username>@<hostname>

#. Log in to Cloud Foundry itself.

   .. code-block:: console

      cf login -a https://api.<smthg>.xip.io -u <user_name> -p <password>

#. Add murano service broker.

   .. code-block:: console

      cf create-service-broker <broker_name> <OS_USERNAME> <OS_PASSWORD>  http://<service_broker_ip>:8083

#. Enable access to murano packages.

   .. code-block:: console

      cf enable-service-access <service_name>

   .. warning::

      By default, access to all services is prohibited.

   .. note::

      You can use `service-access` command to see human-readable list of packages.

#. Provision murano service through Cloud Foundry.

   .. code-block:: console

      cf create-service 'Apache HTTP Server' default MyApacheInstance  -c apache.json

   .. code-block:: json

      {
          "instance": {
              "flavor": "m1.medium",
              "?": {
                  "type": "io.murano.resources.LinuxMuranoInstance"
              },
              "keyname": "nstarodubtsev",
              "assignFloatingIp": "True",
              "name": <name_pattern>,
              "availabilityZone": "nova",
              "image": "1b9ff37e-dff3-4308-be08-9185705dad91"
          },
          "enablePHP": "True"
      }

Known issues
------------

* `Hard to deploy complex apps
  <https://bugs.launchpad.net/murano/+bug/1500777>`_

Useful links
------------

Here is the list of the links for Cloud Foundry documentation which you might need:

#.  `Cloud Foundry development version launcher
    <https://github.com/yudai/cf_nise_installer>`_

#.  `How to manage Cloud Foundry service brokers
    <https://docs.cloudfoundry.org/services/managing-service-brokers.html>`_

#. `Cloud Foundry CLI docs
   <http://docs.cloudfoundry.org/devguide/#cf>`_


text:
using Aspose.App.Diagram.Pages.Models;
using Aspose.App.Diagram.Pages.PageRenderers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Aspose.App.Diagram.Pages.PageModels
{
    public class AppModel
    {
        public ResourceAdapter Resources { get; } = new ResourceAdapter();
        public string PageTitle { get; set; }
        public string PageMetaDescription { get; set; }

        public string Title { get; set; }
        public string TitleSub { get; set; }
        public string AppURL { get; set; }
        public DiagramApps App { get; set; }
        public string AppName { get; set; }
        public bool UploadAndRedirect { get; set; }
        public bool ShowViewerButton { get; set; }
        public ExtensionModel ExtensionModel { get; set; }
        public OverviewModel OverviewModel { get; set; }
        public HowToModel HowToModel { get; set; }
        public CanonicalModel CanonicalModel { get; set; }
        public OtherFeaturesModel OtherFeaturesModel { get; set; }
        public List<AnotherApp> OtherApps { get; set; }
        public List<string> SaveAsOptions { get; set; }
        public JSOptionsModel JSOptions { get; set; }
        public List<string> StructuralDataJson { get; set; }
        public string EmailTo { get; set; }

        public string ResourcesFromApp(string key)
        {
            return Resources[App.ToString() + key];
        }
    }
}


text:
.asmillerGalleria{list-style:none;width:100%; padding: 0; margin:0;}
.asmillerGalleria li{display:block;width:80px;height:80px;overflow:hidden;float:left;margin:0 10px 10px 0}
.asmillerGalleria li a{display:none}
.asmillerGalleria li div{position:absolute;display:none;top:0;left:180px}
.asmillerGalleria li div img{cursor:pointer}
.asmillerGalleria li.asmillerGalleria_active div img,.asmillerGalleria li.asmillerGalleria_active div{display:block}
.asmillerGalleria li img.asmillerGalleria_thumb{cursor:pointer;top:auto;left:auto;display:block;width:auto;height:auto}
.asmillerGalleria li .asmillerGalleria_caption{display:block;padding-top:.5em}
* html .asmillerGalleria li div span{width:400px} /* MSIE bug */

	.asmillerGalleria_caption{color:#888;position:absolute;bottom:60px;left:45px;width:200px;}
	.asmillerGalleryBlock{position:relative;margin-top:2em;}
	.asmillerGallery{float:left;}
	.asmillerGallery li{width:55px;height:70px;border:3px solid darkgray;margin: 0 2px 2px 0;background:#eee;}
	.asmillerGallery li.hover{border-color:#bbb;}
	.asmillerGallery li.asmillerGalleria_active{border-style:solid;border-color:#222;}
	.asmillerGalleria_caption{margin-left: 9999px; font:italic 0.7em/1.4 georgia,serif;}
	.asmillerMainImage img{border: double #222 1px;padding:5px;}

	.nav{padding-top:15px;clear:both;}

	.info{text-align:left;margin:30px 0;border-top:1px dotted #221;padding-top:30px;clear:both;}
	.info p{margin-top:1.6em;}

	.nav{position:absolute;top:410px;left:0;}


text:
export default async function handler(req, res) {
  // should be secret, custom header coming in from Contentful
  let inboundRevalToken = req.headers['x-vercel-reval-key']

  // Check for secret to confirm this is a valid request
  if (!inboundRevalToken) {
    return res
      .status(401)
      .json({ message: 'x-vercel-reval-key header not defined' })
  } else if (inboundRevalToken !== process.env.CONTENTFUL_REVALIDATE_SECRET) {
    return res.status(401).json({ message: 'Invalid token' })
  }

  try {
    // Note: if this fails to parse you may have forget to set the
    // "content-type" header correctly as mentioned here https://github.com/vercel/next.js/blob/canary/examples/cms-contentful/README.md#step-9-try-using-on-demand-revalidation
    let postSlug = req.body.fields.slug['en-US']

    // revalidate the individual post and the home page
    await res.revalidate(`/posts/${postSlug}`)
    await res.revalidate('/')

    return res.json({ revalidated: true })
  } catch (err) {
    // If there was an error, Next.js will continue
    // to show the last successfully generated page
    return res.status(500).send('Error revalidating')
  }
}


text:
var keys = require("@nathanfaucett/keys"),
    indexOf = require("@nathanfaucett/index_of"),
    isPrimitive = require("@nathanfaucett/is_primitive"),
    isFunction = require("@nathanfaucett/is_function"),
    isArrayLike = require("@nathanfaucett/is_array_like");

module.exports = deepCopy;

function deepCopy(object) {
    return baseDeepCopy(object, [], []);
}

function copyArray(array, seen, copied) {
    var length = array.length,
        i = -1,
        il = length - 1,
        out = new Array(length);

    copied[copied.length] = out;

    while (i++ < il) {
        out[i] = baseDeepCopy(array[i], seen, copied);
    }

    return out;
}

function copyObject(object, out, seen, copied) {
    var objectKeys = keys(object),
        i = -1,
        il = objectKeys.length - 1,
        key;

    copied[copied.length] = out;

    while (i++ < il) {
        key = objectKeys[i];
        out[key] = baseDeepCopy(object[key], seen, copied);
    }

    return out;
}

function baseDeepCopy(object, seen, copied) {
    var index;

    if (isPrimitive(object) || isFunction(object)) {
        return object;
    } else {
        if ((index = indexOf(seen, object)) !== -1) {
            return copied[index];
        } else {
            seen[seen.length] = object;

            if (isArrayLike(object)) {
                return copyArray(object, seen, copied);
            } else {
                return copyObject(object, object.constructor ? createConstructor(object) : {}, seen, copied);
            }
        }
    }
}

function createConstructor(object) {
    try {
        return new object.constructor();
    } catch (e) {
        return {};
    }
}


text:
import { ClassTransformVisitor } from "./classes/visitor";
import { ModuleTransformVisitor } from "./modules/visitor";

import { wrap } from "./modules/helpers/wrapper";

/*
References:
Babel Plugin Handbook: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md
AST Spec: https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md
Babel Types (t.*) https://github.com/babel/babel/tree/master/packages/babel-types
AST Explorer: https://astexplorer.net/
*/

module.exports = () => {
  const UI5Visitor = {
    Program: {
      enter(path, { opts }) {
        if (this.ran) return;
        this.ran = true;

        if (opts.onlyConvertNamedClass == false) {
          throw new Error(
            "ERROR: onlyConvertNamedClass=false is no longer supported. Use autoConvertAllExtendClassesByDefault=true"
          );
        }
        // TODO: enable this in a later version
        // else if (opts.onlyConvertNamedClass == true) {
        //   console.warn('WARN: onlyConvertNamedClass=true is now the default behaviour') // eslint-disable-line no-console
        // }

        // Opts
        this.namespacePrefix = opts.namespacePrefix;
        this.noImportInteropPrefixes = opts.noImportInteropPrefixes || ["sap/"];
        this.noImportInteropPrefixesRegexp = new RegExp(
          this.noImportInteropPrefixes.map(p => `(^${p}.*)`).join("|")
        );

        // Properties for Module Transform
        this.programNode = path.node;
        this.defaultExport = null;
        this.defaultExportNode = null;
        this.exportGlobal = false;
        this.ignoredImports = [];
        this.imports = [];
        this.namedExports = [];
        this.injectDynamicImportHelper = false;

        // Properties for Class Transform
        this.importNames = [];

        // The classes must be converted right away before any other class transforms get a chance to run.
        path.traverse(ClassTransformVisitor, this);
      },
      exit(path, { opts }) {
        wrap(this, path.node, opts);
      },
    },
    // The module transform visitor uses normal traversal so we capture
    // imports and helper code that get added by other transforms.
    ...ModuleTransformVisitor,
  };

  return {
    visitor: UI5Visitor,
  };
};


text:
<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Description of tags
 *
 * @author Kebot<i@yaofur.com>
 * @link http://kebot.me/
 */
class Base_Tags
{
    public static $columns = array('id','type','value','popular');

    /**
     * @param string $value
     * @param string $type
     * @return Base_Tags
     */
    public static function get($value,$type=NULL)
    {
        $handle = DB::select()->from('tags')->where('value', '=', $value);

        $type AND $handle->where('type', '=', $type);

        $handle = $handle->execute('base');

        if($handle->count() == 0){
            $id = self::add($value,$type);
        } else {
            $id = $handle->get('id');
        }
        return new self($id);
    }
    /**
     *
     * @param string $value
     * @param string $type
     */
    public static function add($value,$type=NULL){
        $values = array(NULL,$type,$value,0);
        $id = DB::insert('tags')->columns(self::$columns)->values($values)->execute('base');
        return $id[0];
    }

    public static function popularTags($limit = 10)
    {
        $tags = array();
        $handle = DB::select()->from('tags')->order_by('popular', 'DESC')->limit($limit)->execute('base');
        if($handle->valid()){
            $tags = $handle->as_array();
        }
        return $tags;
    }

    /**
     * @var int
     */
    public $id = NULL;
    /**
     * @var string
     */
    public $type = NULL;
    /**
     * @var string
     */
    public $value = NULL;
    /**
     * @var int
     */
    public $popular = NULL;

    public function __construct($id) {
        $handle = DB::select()->from('tags')->where('id', '=', $id)->execute('base');
        if($handle->count()){
            foreach (self::$columns as $value) {
                $this->$value = $handle->get($value);
            }
        }
    }
    /**
     * create a relationship between douban subject and a tag
     * @param type $douban_id
     * @return int id of relationship
     */
    public function link($douban_id)
    {
        $table = 'relationship';
        $select = DB::select()->from($table)->where('d_id', '=', $douban_id)->and_where('t_id', '=', $this->id)->execute('base');
        if( $select->count()==0 ){
            $columns = array('d_id','t_id');
            $values = array($douban_id,  $this->id);
            $id = DB::insert($table, $columns)->values($values)->execute('base');
            //Popular +1
            DB::update('tags')->set(array('popular'=>DB::expr('popular+1')))->where('id', '=', $this->id)->execute('base');
            return $id;
        } else {
            return $select->get('id');
        }
    }
}

?>


text:
namespace igl
{
  namespace copyleft
  {
    namespace cgal
    {
      // Compute the "outer hull" of a piecewise constant winding number induce
      // triangle mesh (V,F).
      //
      // Inputs:
      //   V  #V by 3 list of vertex positions
      //   F  #F by 3 list of triangle indices into V
      // Outputs:
      //   HV  #HV by 3 list of output vertex positions
      //   HF  #HF by 3 list of output triangle indices into HV
      //   J  #HF list of indices into F
      //   flip  #HF list of whether facet was flipped when added to HF
      //
      template <
        typename DerivedV,
        typename DerivedF,
        typename DerivedHV,
        typename DerivedHF,
        typename DerivedJ,
        typename Derivedflip>
      IGL_INLINE void outer_hull(
        const Eigen::PlainObjectBase<DerivedV> & V,
        const Eigen::PlainObjectBase<DerivedF> & F,
        Eigen::PlainObjectBase<DerivedHV> & HV,
        Eigen::PlainObjectBase<DerivedHF> & HF,
        Eigen::PlainObjectBase<DerivedJ> & J,
        Eigen::PlainObjectBase<Derivedflip> & flip);
      // Compute the "outer hull" of a potentially non-manifold mesh (V,F) whose
      // intersections have been "resolved" (e.g. using `cork` or
      // `igl::copyleft::cgal::selfintersect`). The outer hull is defined to be all facets
      // (regardless of orientation) for which there exists some path from infinity
      // to the face without intersecting any other facets. For solids, this is the
      // surface of the solid. In general this includes any thin "wings" or
      // "flaps".  This implementation largely follows Section 3.6 of "Direct
      // repair of self-intersecting meshes" [Attene 2014].
      //
      // Note: This doesn't require the input mesh to be piecewise constant
      // winding number, but won't handle multiple non-nested connected
      // components.
      //
      // Inputs:
      //   V  #V by 3 list of vertex positions
      //   F  #F by 3 list of triangle indices into V
      // Outputs:
      //   G  #G by 3 list of output triangle indices into V
      //   J  #G list of indices into F
      //   flip  #F list of whether facet was added to G **and** flipped orientation
      //     (false for faces not added to G)
      template <
        typename DerivedV,
        typename DerivedF,
        typename DerivedG,
        typename DerivedJ,
        typename Derivedflip>
      IGL_INLINE void outer_hull_legacy(
        const Eigen::PlainObjectBase<DerivedV> & V,
        const Eigen::PlainObjectBase<DerivedF> & F,
        Eigen::PlainObjectBase<DerivedG> & G,
        Eigen::PlainObjectBase<DerivedJ> & J,
        Eigen::PlainObjectBase<Derivedflip> & flip);
    }
  }
}

#ifndef IGL_STATIC_LIBRARY
#  include "outer_hull.cpp"
#endif
#endif


text: SELECT CAST('123.5abc' AS numeric)


text:
package org.apache.phoenix.parse;

import java.util.List;

import org.apache.hadoop.hbase.util.Pair;

import com.google.common.collect.ImmutableList;
import org.apache.phoenix.schema.ColumnModifier;

public class IndexKeyConstraint {
    private final List<Pair<ColumnParseNode, ColumnModifier>> columnNameToModifier;

    IndexKeyConstraint(List<Pair<ColumnParseNode, ColumnModifier>> columnNameAndModifier) {
        this.columnNameToModifier = ImmutableList.copyOf(columnNameAndModifier);
    }

    public List<Pair<ColumnParseNode, ColumnModifier>> getColumns() {
        return columnNameToModifier;
    }
}


text:
module ISO where

import Control.Monad
import Data.Void
-- A type of `Void` have no value.
-- So it is impossible to construct `Void`,
-- unless using undefined, error, unsafeCoerce, infinite recursion, etc
-- And there is a function
-- absurd :: Void -> a
-- That get any value out of `Void`
-- We can do this becuase we can never have void in the zeroth place.

-- so, when are two type, `a` and `b`, considered equal?
-- a definition might be, it is possible to go from `a` to `b`,
-- and from `b` to `a`.
-- Going a roundway trip should leave you the same value.
-- Unfortunately it is virtually impossible to test this in Haskell.
-- This is called Isomorphism.

type ISO a b = (a -> b, b -> a)

-- given ISO a b, we can go from a to b
substL :: ISO a b -> (a -> b)
substL = fst

-- and vice versa
substR :: ISO a b -> (b -> a)
substR = snd

-- There can be more than one ISO a b
isoBool :: ISO Bool Bool
isoBool = (id, id)

isoBoolNot :: ISO Bool Bool
isoBoolNot = (not, not)

-- isomorphism is reflexive
refl :: ISO a a
refl = (id, id)

-- isomorphism is symmetric
symm :: ISO a b -> ISO b a
symm (x, y) = (y, x)

-- isomorphism is transitive
trans :: ISO a b -> ISO b c -> ISO a c
trans (x, x') (y, y') = (y . x, x' . y')

-- We can combine isomorphism:
isoTuple :: ISO a b -> ISO c d -> ISO (a, c) (b, d)
isoTuple (ab, ba) (cd, dc) =
  (\(a, c) -> (ab a, cd c), \(b, d) -> (ba b, dc d))

isoList :: ISO a b -> ISO [a] [b]
isoList (x, y) = (map x, map y)

isoMaybe :: ISO a b -> ISO (Maybe a) (Maybe b)
isoMaybe (ab, ba) = (liftM ab, liftM ba)

isoEither :: ISO a b -> ISO c d -> ISO (Either a c) (Either b d)
isoEither (ab, ba) (cd, dc) = (f, g)
  where
    f (Left a) = Left $ ab a
    f (Right c) = Right $ cd c
    g (Left b) = Left $ ba b
    g (Right d) = Right $ dc d

isoFunc :: ISO a b -> ISO c d -> ISO (a -> c) (b -> d)
isoFunc (ab, ba) (cd, dc) = (\f -> cd . f . ba, \f -> dc . f . ab)

-- Going another way is hard (and is generally impossible)
isoUnMaybe :: ISO (Maybe a) (Maybe b) -> ISO a b
-- Remember, for all valid ISO, converting and converting back
-- Is the same as the original value.
-- You need this to prove some case are impossible.
isoUnMaybe (ab, ba) = (f, g)
  where
    f x = case ab (Just x) of
            Just y -> y
            Nothing -> case ab Nothing of
                            Nothing -> error "impossible"
                            Just y -> y
    g x = case ba (Just x) of
            Just y -> y
            Nothing -> case ba Nothing of
                            Nothing -> error "impossible"
                            Just y -> y

-- We cannot have
-- isoUnEither :: ISO (Either a b) (Either c d) -> ISO a c -> ISO b d.
-- Note that we have
isoEU :: ISO (Either [()] ()) (Either [()] Void)
isoEU = (f, g)
  where
    f (Right ()) = Left []
    f (Left x) = Left $ () : x
    g (Left []) = Right ()
    g (Left (_:xs)) = Left xs

-- where (), the empty tuple, has 1 value, and Void has 0 value
-- If we have isoUnEither,
-- We have ISO () Void by calling isoUnEither isoEU
-- That is impossible, since we can get a Void by substL on ISO () Void
-- So it is impossible to have isoUnEither

-- And we have isomorphism on isomorphism!
isoSymm :: ISO (ISO a b) (ISO b a)
isoSymm = (f, g)
  where
    f (ab, ba) = (ba, ab)
    g (ab, ba) = (ba, ab)


text:
define(function(require, exports, module) {
	"use strict";

	var Backbone = require("backbone");
	var app = require("app");
	var util = require("util");

	var VideosCollection = Backbone.Collection.extend({
		byCandidate: function(id) {
			this.reset(
				this.filter(function(video) {
					return _.contains(video.get("id_calon"), id);
				})
			);
		},

		byTag: function(tag) {
			this.reset(
				this.filter(function(video) {
					return _.contains(video.get("tags"), tag);
				})
			);
		},

		url: function() {
			return util.urlAddParam(
				app.api.endpoints.videos,
				"apiKey",
				app.api.key
			);
		},

		parse: function(resp) {
			if (!_.isUndefined(resp.data.results.videos)) {
				var urlParser = document.createElement("a");

				_.each(resp.data.results.videos, function(video, idx){

					// Inject Youtube video ID.
					urlParser.href = video.url_video;
					if (_.contains(["www.youtube.com", "youtube.com", "youtu.be"], urlParser.hostname)) {
						var params = urlParser.search.substr(1).split("&");
						var vId = _.filter(params, function(param){
							return (param.substr(0, 2) == "v=");
						});

						if (vId.length > 0) {
							resp.data.results.videos[idx].youtube_id = vId[0].substr(2);
						}
					}

					// Judul excerpt.
					resp.data.results.videos[idx].judul_excerpt = video.judul.substr(0, 64) + " ...";
				});

				return resp.data.results.videos;
			}

			return this.models;
		},

		_getYTId: function(url) {

		}
	});

	module.exports = VideosCollection;
});


text:
<?php

namespace s9e\TextFormatter\Configurator\Items\AttributeFilters;

use s9e\TextFormatter\Configurator\Items\AttributeFilter;

class UintFilter extends AttributeFilter
{
	/**
	* Constructor
	*/
	public function __construct()
	{
		parent::__construct('s9e\\TextFormatter\\Parser\\AttributeFilters\\NumericFilter::filterUint');
		$this->setJS('NumericFilter.filterUint');
	}

	/**
	* {@inheritdoc}
	*/
	public function isSafeInCSS()
	{
		return true;
	}

	/**
	* {@inheritdoc}
	*/
	public function isSafeInJS()
	{
		return true;
	}

	/**
	* {@inheritdoc}
	*/
	public function isSafeAsURL()
	{
		return true;
	}
}


text:
package de.debugco.jairport;

import com.beatofthedrum.alacdecoder.AlacDecodeUtils;
import com.beatofthedrum.alacdecoder.AlacFile;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;

public class RaopServer extends Thread {
  private RaopSession session;
  private int port;
  private DatagramSocket receiveSocket;
  private Cipher aesCipher;
  private SecretKeySpec secretKey;
  private IvParameterSpec keySpec;
  private SocketAddress clientSocketAddress;
  private AlacFile alac;
  private SourceDataLine line;
  private int[] outbuffer;
  private byte[] outbufferBytes;

  public RaopServer(RaopSession session) {
    super("RaopServer " + session.getId());

    this.port = session.getControlPort() - 1;
    this.session = session;
    try {
      this.aesCipher = Cipher.getInstance("AES/CBC/NOPADDING");
      receiveSocket = new DatagramSocket(port);

      DataLine.Info info = new DataLine.Info(SourceDataLine.class, new AudioFormat(session.getFormat().getSampleRate(), session.getFormat().getSampleSize(), 2, true, true));
      line = (SourceDataLine) AudioSystem.getLine(info);
      line.open();
      line.start();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    secretKey = new SecretKeySpec(session.getAesKey(), "AES");
    secretKey = new SecretKeySpec(session.getAesKey(), "AES");
    keySpec = new IvParameterSpec(session.getAesIv());

    int frameSize = session.getFormat().getFrameSize();
    alac = AlacDecodeUtils.create_alac(session.getFormat().getSampleSize(), 2);
    alac.setSetinfo_max_samples_per_frame(frameSize);
    alac.setSetinfo_rice_historymult(session.getFormat().getRiceHistoryMult());
    alac.setSetinfo_rice_initialhistory(session.getFormat().getRiceInitialHistory());
    alac.setSetinfo_rice_kmodifier(session.getFormat().getRiceKModifier());
    alac.setSetinfo_sample_size(session.getFormat().getSampleSize());

    outbuffer = new int[frameSize * 4];
    outbufferBytes = new byte[outbuffer.length * 2];
  }

  public void requestRtpResend(int first, int last) throws IOException {
    if(first > last) {
      System.out.println(first + " > " + last);
      return;
    }

    int len = last - first + 1;
    byte[] b = new byte[] { (byte) 0x80, (byte) (0x55|0x80), 0x01, 0x00, (byte) ((first & 0xFF00) >> 8), (byte) (first & 0xFF), (byte) ((len & 0xFF00) >> 8), (byte) (len & 0xFF)};
    DatagramPacket packet = new DatagramPacket(b, 0, b.length, clientSocketAddress);
    receiveSocket.send(packet);
  }

  private int lastSeqNo = 0;

  private int convertSampleBufferToByteBuffer(int[] sampleBuffer, int len, byte[] outbuffer) {
    int j = 0;
    for (int i = 0; i < len; ++i) {
      int sample = sampleBuffer[i];
      outbuffer[j++] = (byte) (sample >> 8);
      outbuffer[j++] = (byte) sample;
    }
    return j;
  }

  private void putDataInBuffer(int seqNo, byte[] data, int offset, int len) {
    byte[] out = new byte[len];
    decryptAes(data, offset, len, out);
    int samplesInBytes = AlacDecodeUtils.decode_frame(alac, out, outbuffer, outbuffer.length);
    assert(samplesInBytes == session.getFormat().getFrameSize() * 4);

    int lenBytes = convertSampleBufferToByteBuffer(outbuffer, samplesInBytes >> 1, outbufferBytes);
    line.write(outbufferBytes, 0, lenBytes);

    if(seqNo + 1 < lastSeqNo) {
      System.out.println(seqNo  + " " + lastSeqNo);
    }
    lastSeqNo = seqNo;
  }

  @Override
  public void run() {
    byte[] b = new byte[2048];
    DatagramPacket packet = new DatagramPacket(b, b.length);
    while(!Thread.interrupted()) {
      try {
        receiveSocket.receive(packet);
      } catch (IOException e) {
        e.printStackTrace();
        this.interrupt();
        continue;
      }
      if(clientSocketAddress == null) {
        clientSocketAddress = packet.getSocketAddress();
      }

      int offset = packet.getOffset();
      int length = packet.getLength();
      byte[] data = packet.getData();
      byte type = (byte)(data[offset + 1] & ~0x80);
      if(type == 0x60 || type == 0x56) { // audio data / resend
        if(type == 0x56) {
          offset = offset + 4;
          length = length - 4;
        }
        int seqno = (data[offset + 2]  << 8) | data[offset + 3];
        putDataInBuffer(seqno, data, offset + 12, length - 12);
      }
    }
  }

  public int getPort() {
    return port;
  }

  private int decryptAes(byte[] inbuf, int offset, int len, byte[] outbuffer) {
    int decodeLen = len - (len % 16);
    try {
      aesCipher.init(Cipher.DECRYPT_MODE, secretKey, keySpec);
      int ret = aesCipher.doFinal(inbuf, offset, decodeLen, outbuffer);
      System.arraycopy(inbuf, offset + decodeLen, outbuffer, decodeLen, len % 16);
      return ret;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}


text:
<?php

namespace Woland;

use \Psr\Http\Message\RequestInterface;

/// Request and path info squished together.
class RequestedPath
{
    use \lpeltier\Struct;

    /// @var string favorite name.
    public $favoriteName;

    /// @var string favorite name.
    public $favoritePathname;

    /// @var string path relative to the favorite.
    public $relative;

    /// @var \SplFileInfo
    public $info;

    /**
     * @param string[] $favorites
     * @return self
     */
    public static function fromRequest(RequestInterface $request, array $favorites)
    {
        $uriPath = urldecode($request->getUri()->getPath());
        $parts = array_values(array_filter(explode('/', $uriPath), 'strlen'));
        $favoriteName = (count($parts) > 0) ? $parts[0] : null;
        $relative = implode('/', array_slice($parts, 1));

        /* This should never happen as the browser resolves relative URIs by
         * itself but it is still possible to write the GET request and send
         * it manually. A real user won't ever see this message. */
        if (in_array('..', $parts, true)) {
            throw new \RuntimeException("`$uriPath` is not a valid path.");
        }

        if ($favoriteName === null) {
            return new self();
        } elseif (!array_key_exists($favoriteName, $favorites)) {
            throw new \RuntimeException("Unknown favorite `$favoriteName`.");
        }

        $info = new \SplFileInfo($favorites[$favoriteName] . "/$relative");
        $favoritePathname = $favorites[$favoriteName];

        return new self(compact('favoriteName', 'favoritePathname', 'info', 'relative', 'prefix'));
    }

    /// @return bool true if the requested path is the app index.
    public function isNone()
    {
        return $this->favoriteName === null;
    }

    /// @return bool if the requested path is the root of a favorite.
    public function isFavoriteRoot()
    {
        return !$this->isNone() && strlen($this->relative) <= 0;
    }
}


text:
require_relative 'base'
require 'tempfile'

class TestMkmf
  class TestHaveLibrary < TestMkmf
    LIBRARY_NAME = 'mkmftest'
    HEADER_NAME = "#{LIBRARY_NAME}.h"
    FUNC_NAME = 'ruby_mkmftest_foo'
    ARPREFIX = config_string('LIBRUBY_A') {|lib| lib[/\A\w+/]}

    def create_library(libname = LIBRARY_NAME)
      lib = "#{ARPREFIX}#{libname}.#{$LIBEXT}"
      open(HEADER_NAME, "w") do |hdr|
        hdr.puts "void #{FUNC_NAME}(void);"
        hdr.puts "void #{FUNC_NAME}_fake(void);"
      end
      create_tmpsrc("#include \"#{HEADER_NAME}\"\n""void #{FUNC_NAME}(void) {}")
      assert(xsystem(cc_command), "compile failed: #{cc_command}")
      command = "#{CONFIG['AR']} #{config_string('ARFLAGS') || 'cru '}#{lib} #{CONFTEST}.#{$OBJEXT}"
      assert(xsystem(command), "making library failed: #{command}")
      File.unlink("#{CONFTEST}.#{$OBJEXT}")
      config_string('RANLIB') do |ranlib|
        command = "#{ranlib} #{lib}"
        assert(xsystem(command), "ranlib failed: #{command}")
      end
    end

    def assert_have_library(*args)
      assert_equal(true, have_library(LIBRARY_NAME, *args), MKMFLOG)
    end

    def assert_not_have_library(*args)
      assert_equal(false, have_library(LIBRARY_NAME, *args), MKMFLOG)
    end

    def test_have_library
      create_library
      assert_have_library
    end

    def test_have_library_with_name
      create_library
      assert_have_library(FUNC_NAME, HEADER_NAME)
    end

    def test_not_have_library
      assert_not_have_library
    end

    def test_not_have_library_with_name
      create_library
      assert_not_have_library("#{FUNC_NAME}_fake", HEADER_NAME)
    end
  end
end


text:
package org.gridkit.sketchbook;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class IOUtils {

    public static String toString(InputStream is) throws IOException {
        try {
            StringBuilder buf = new StringBuilder();
            Reader reader = new InputStreamReader(is);
            char[] swap = new char[1024];
            while(true) {
                int n = reader.read(swap);
                if (n < 0) {
                    break;
                }
                else {
                    buf.append(swap, 0, n);
                }
            }
            return buf.toString();
        }
        finally {
            try {
                is.close();
            }
            catch(Exception e) {
                // ignore
            }
        }
    }

    public static Collection<String> toLines(InputStream is) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            List<String> result = new ArrayList<String>();
            while(true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                result.add(line);
            }
            return result;
        }
        finally {
            try {
                is.close();
            }
            catch(Exception e) {
                // ignore
            }
        }
    }

    public static void copy(InputStream in, OutputStream out) throws IOException {
        try {
            byte[] buf = new byte[1 << 12];
            while(true) {
                int n = in.read(buf);
                if(n >= 0) {
                    out.write(buf, 0, n);
                }
                else {
                    break;
                }
            }
        } finally {
            try {
                in.close();
            }
            catch(Exception e) {
                // ignore
            }
        }
    }
}


text:
package uk.gov.nationalarchives.droid.planet.xml.dao;

import java.util.List;

/**
 * Encapsulates Planets XML Data.
 * @author Alok Kumar Dash
 *
 */

public class PlanetsXMLData {

    //System dependent top level items.
    private List<String> topLevelItems;

    private ProfileStat profileStat;

    private List<GroupByYearSizeAndCountRow> groupByYear;

    private List<GroupByPuidSizeAndCountRow> groupByPuid;

    /**
     * @return the topLevelItems
     */
    public List<String> getTopLevelItems() {
        return topLevelItems;
    }

    /**
     * @param topLevelItems the topLevelItems to set
     */
    public void setTopLevelItems(List<String> topLevelItems) {
        this.topLevelItems = topLevelItems;
    }

    /**
     * @return the profileStat
     */
    public ProfileStat getProfileStat() {
        return profileStat;
    }

    /**
     * @param profileStat the profileStat to set
     */
    public void setProfileStat(ProfileStat profileStat) {
        this.profileStat = profileStat;
    }

    /**
     * @return the groupByYear
     */
    public List<GroupByYearSizeAndCountRow> getGroupByYear() {
        return groupByYear;
    }

    /**
     * @param groupByYear the groupByYear to set
     */
    public void setGroupByYear(List<GroupByYearSizeAndCountRow> groupByYear) {
        this.groupByYear = groupByYear;
    }

    /**
     * @return the groupByPuid
     */
    public List<GroupByPuidSizeAndCountRow> getGroupByPuid() {
        return groupByPuid;
    }

    /**
     * @param groupByPuid the groupByPuid to set
     */
    public void setGroupByPuid(List<GroupByPuidSizeAndCountRow> groupByPuid) {
        this.groupByPuid = groupByPuid;
    }

}