text:
typedef uint_least16_t char16_t;
typedef uint_least32_t char32_t;
# endif
typedef float swift_float2  __attribute__((__ext_vector_type__(2)));
typedef float swift_float3  __attribute__((__ext_vector_type__(3)));
typedef float swift_float4  __attribute__((__ext_vector_type__(4)));
typedef double swift_double2  __attribute__((__ext_vector_type__(2)));
typedef double swift_double3  __attribute__((__ext_vector_type__(3)));
typedef double swift_double4  __attribute__((__ext_vector_type__(4)));
typedef int swift_int2  __attribute__((__ext_vector_type__(2)));
typedef int swift_int3  __attribute__((__ext_vector_type__(3)));
typedef int swift_int4  __attribute__((__ext_vector_type__(4)));
#endif

#if !defined(SWIFT_PASTE)
# define SWIFT_PASTE_HELPER(x, y) x##y
# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y)
#endif
#if !defined(SWIFT_METATYPE)
# define SWIFT_METATYPE(X) Class
#endif

#if defined(__has_attribute) && __has_attribute(objc_runtime_name)
# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X)))
#else
# define SWIFT_RUNTIME_NAME(X)
#endif
#if defined(__has_attribute) && __has_attribute(swift_name)
# define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X)))
#else
# define SWIFT_COMPILE_NAME(X)
#endif
#if !defined(SWIFT_CLASS_EXTRA)
# define SWIFT_CLASS_EXTRA
#endif
#if !defined(SWIFT_PROTOCOL_EXTRA)
# define SWIFT_PROTOCOL_EXTRA
#endif
#if !defined(SWIFT_ENUM_EXTRA)
# define SWIFT_ENUM_EXTRA
#endif
#if !defined(SWIFT_CLASS)
# if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted)
#  define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA
#  define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# else
#  define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
#  define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# endif
#endif

#if !defined(SWIFT_PROTOCOL)
# define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
# define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
#endif

#if !defined(SWIFT_EXTENSION)
# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__)
#endif

#if !defined(OBJC_DESIGNATED_INITIALIZER)
# if defined(__has_attribute) && __has_attribute(objc_designated_initializer)
#  define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
# else
#  define OBJC_DESIGNATED_INITIALIZER
# endif
#endif
#if !defined(SWIFT_ENUM)
# define SWIFT_ENUM(_type, _name) enum _name : _type _name; enum SWIFT_ENUM_EXTRA _name : _type
# if defined(__has_feature) && __has_feature(generalized_swift_name)
#  define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_EXTRA _name : _type
# else
#  define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) SWIFT_ENUM(_type, _name)
# endif
#endif
#if defined(__has_feature) && __has_feature(modules)
@import ObjectiveC;
@import Foundation;
@import XCTest;
#endif

#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch"
#pragma clang diagnostic ignored "-Wduplicate-method-arg"

/// An object encapsulating the file and line number at which a particular example is defined.
SWIFT_CLASS("_TtC5Quick8Callsite")
@interface Callsite : NSObject

/// The absolute path of the file in which an example is defined.
@property (nonatomic, readonly, copy) NSString * _Nonnull file;

/// The line number on which an example is defined.
@property (nonatomic, readonly) NSUInteger line;
@end

@class Example;
@class ExampleMetadata;

/// A configuration encapsulates various options you can use to configure Quick's behavior.
SWIFT_CLASS("_TtC5Quick13Configuration")
@interface Configuration : NSObject

/// Run all examples if none match the configured filters. True by default.
@property (nonatomic) BOOL runAllWhenEverythingFiltered;

/// Registers an inclusion filter.
///
/// All examples are filtered using all inclusion filters.
/// The remaining examples are run. If no examples remain, all examples are run.
///
/// \param filter A filter that, given an example, returns a value indicating
/// whether that example should be included in the examples
/// that are run.
- (void)include:(BOOL (^ _Nonnull)(Example * _Nonnull example))filter;

/// Registers an exclusion filter.
///
/// All examples that remain after being filtered by the inclusion filters are
/// then filtered via all exclusion filters.
///
/// \param filter A filter that, given an example, returns a value indicating
/// whether that example should be excluded from the examples
/// that are run.
- (void)exclude:(BOOL (^ _Nonnull)(Example * _Nonnull example))filter;
- (void)beforeEachWithMetadata:(void (^ _Nonnull)(ExampleMetadata * _Nonnull exampleMetadata))closure;

/// Like Quick.DSL.beforeEach, this configures Quick to execute the given closure before each example that is run. The closure passed to this method is executed before each example Quick runs, globally across the test suite. You may call this method multiple times across mulitple +[QuickConfigure configure:] methods in order to define several closures to run before each example.
///
/// Note that, since Quick makes no guarantee as to the order in which
/// +[QuickConfiguration configure:] methods are evaluated, there is no
/// guarantee as to the order in which beforeEach closures are evaluated
/// either. Mulitple beforeEach defined on a single configuration, however,
/// will be executed in the order they're defined.
///
/// \param closure The closure to be executed before each example
/// in the test suite.
- (void)beforeEach:(void (^ _Nonnull)(void))closure;
- (void)afterEachWithMetadata:(void (^ _Nonnull)(ExampleMetadata * _Nonnull exampleMetadata))closure;

/// Like Quick.DSL.afterEach, this configures Quick to execute the given closure after each example that is run. The closure passed to this method is executed after each example Quick runs, globally across the test suite. You may call this method multiple times across mulitple +[QuickConfigure configure:] methods in order to define several closures to run after each example.
///
/// Note that, since Quick makes no guarantee as to the order in which
/// +[QuickConfiguration configure:] methods are evaluated, there is no
/// guarantee as to the order in which afterEach closures are evaluated
/// either. Mulitple afterEach defined on a single configuration, however,
/// will be executed in the order they're defined.
///
/// \param closure The closure to be executed before each example
/// in the test suite.
- (void)afterEach:(void (^ _Nonnull)(void))closure;

/// Like Quick.DSL.beforeSuite, this configures Quick to execute the given closure prior to any and all examples that are run. The two methods are functionally equivalent.
- (void)beforeSuite:(void (^ _Nonnull)(void))closure;

/// Like Quick.DSL.afterSuite, this configures Quick to execute the given closure after all examples have been run. The two methods are functionally equivalent.
- (void)afterSuite:(void (^ _Nonnull)(void))closure;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end

/// Examples, defined with the it function, use assertions to demonstrate how code should behave. These are like "tests" in XCTest.
SWIFT_CLASS("_TtC5Quick7Example")
@interface Example : NSObject

/// A boolean indicating whether the example is a shared example; i.e.: whether it is an example defined with itBehavesLike.
@property (nonatomic) BOOL isSharedExample;

/// The site at which the example is defined. This must be set correctly in order for Xcode to highlight the correct line in red when reporting a failure.
@property (nonatomic, strong) Callsite * _Nonnull callsite;
@property (nonatomic, readonly, copy) NSString * _Nonnull description;

/// The example name. A name is a concatenation of the name of the example group the example belongs to, followed by the description of the example itself.
///
/// The example name is used to generate a test method selector
/// to be displayed in Xcode's test navigator.
@property (nonatomic, readonly, copy) NSString * _Nonnull name;

/// Executes the example closure, as well as all before and after closures defined in the its surrounding example groups.
- (void)run;
@end

/// Example groups are logical groupings of examples, defined with the describe and context functions. Example groups can share setup and teardown code.
SWIFT_CLASS("_TtC5Quick12ExampleGroup")
@interface ExampleGroup : NSObject
@property (nonatomic, readonly, copy) NSString * _Nonnull description;

/// Returns a list of examples that belong to this example group, or to any of its descendant example groups.
@property (nonatomic, readonly, copy) NSArray<Example *> * _Nonnull examples;
@end

/// A class that encapsulates information about an example, including the index at which the example was executed, as well as the example itself.
SWIFT_CLASS("_TtC5Quick15ExampleMetadata")
@interface ExampleMetadata : NSObject

/// The example for which this metadata was collected.
@property (nonatomic, readonly, strong) Example * _Nonnull example;

/// The index at which this example was executed in the test suite.
@property (nonatomic, readonly) NSInteger exampleIndex;
@end

/// A namespace for filter flag keys, defined primarily to make the keys available in Objective-C.
SWIFT_CLASS("_TtC5Quick6Filter")
@interface Filter : NSObject

/// Example and example groups with [Focused: true] are included in test runs, excluding all other examples without this flag. Use this to only run one or two tests that you're currently focusing on.
+ (NSString * _Nonnull)focused;

/// Example and example groups with [Pending: true] are excluded from test runs. Use this to temporarily suspend examples that you know do not pass yet.
+ (NSString * _Nonnull)pending;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end

@interface NSBundle (SWIFT_EXTENSION(Quick))
@end

/// A base class for a class cluster of Quick test suites, that should correctly build dynamic test suites for XCTest to execute.
SWIFT_CLASS("_TtC5Quick14QuickTestSuite")
@interface QuickTestSuite : XCTestSuite

/// Construct a test suite for a specific, selected subset of test cases (rather than the default, which as all test cases).
///
/// If this method is called multiple times for the same test case class, e.g..
///
/// FooSpec/testFoo
/// FooSpec/testBar
///
/// It is expected that the first call should return a valid test suite, and
/// all subsequent calls should return <code>nil
/// </code>.
+ (QuickTestSuite * _Nullable)selectedTestSuiteForTestCaseWithName:(NSString * _Nonnull)name;
- (nonnull instancetype)initWithName:(NSString * _Nonnull)name OBJC_DESIGNATED_INITIALIZER;
@end

#pragma clang diagnostic pop


text:
"""
Implements a base class for all Synchrony test suites to quickly create peer nodes.
"""
import time
import pprint
import random
import hashlib
import unittest
import binascii
import urlparse
from copy import deepcopy
from synchrony import app
from synchrony.models import Revision
from synchrony.controllers import dht
from synchrony.controllers import utils

class BaseSuite(unittest.TestCase):

    dfp            = 0.0          # 0% of peers are malicious by default
    alpha          = 0.0
    beta           = 0.85         # Normalisation factor
    ksize          = 20
    iterations     = 100          # calculate_trust iterates 100 times by default
    peer_amount    = 25
    storage_method = "rpc_append"

    def setUp(self):
        print "\nCreating %i peers configured to use %s." % \
            (self.peer_amount, self.storage_method)

        self.peers = create_peers(self.peer_amount, self.ksize, self.storage_method)

        count = int(len(self.peers) * self.dfp)
#        dht.log("%i peers will be malicious for this test." % count)
#        for i in range(count):
#            self.peers[i] ...

        # All remaining peers considered honest are automatically
        # added to one anothers' bucket of pre-trusted peers.
        #
        # Your test suite(s) will want to adjust this manually after the fact.
        self.honest_peers = {}
        honest_count = len(self.peers) - count

        dht.log("Creating %i pre-trusted peers." % honest_count)
        for j in range(honest_count):
            self.honest_peers[self.peers[count+j].node.long_id] = self.peers[count+j]

        for router in self.honest_peers.values():
            for r in self.honest_peers.values():
                if router.node.threeple == r.node.threeple: continue
                node = router.get_existing_node(r.node.threeple)
                if not node: continue
                node.trust += router.protocol.epsilon
                router.tbucket[node.long_id] = node
                # dht.log("Introduced %s to %s as a pre-trusted peer." % (node, router))

        # We add these RoutingTable objects as an attributes of mocked methods
        # so they can find other nodes and work on their protocol instances.
        #
        # Even though we're emulating dht.SynchronyProtocol to avoid network
        # and database calls, we still stick our mock functions on those instances
        # for the time being.
        mock_transmit.peers       = self.peers
        dht.transmit              = mock_transmit
        mock_get.peers            = self.peers
        dht.get                   = mock_get
        #mock_fetch_revision.peers = self.peers
        #for key in self.peers:
        #    self.peers[key].protocol.fetch_revision = mock_fetch_revision

def create_peers(peer_amount, ksize, storage_method):
    peers = {}
    for i in range(peer_amount):
        peers[i] = dht.RoutingTable(
                "127.0.0.1",
                random.randint(0, 999999),
                app.key.publickey().exportKey(),
                None,
        )
        peers[i].buckets = [dht.KBucket(0, 2**160, 20)]

        rpcmethod = getattr(peers[i].protocol, storage_method, None)
        if not rpcmethod:
            raise Exception("Unknown storage method: %s" % storage_method)
        peers[i].storage_method = rpcmethod

        # Our TestProtocol is a subclass that calls methods on peer routing
        # tables directly instead of making network calls and database commits.
        peers[i].protocol = TestProtocol(
                                peers[i],
                                dht.Storage(),
                                peers[i].ksize,
                                peers
                            )

        # Attempted pings in add_contact would cause some previously
        # added peers to be promptly removed. We manually swap the method
        # for a mockup and reintroduce the original once we have our set of peers.
        peers[i].protocol.original_ping = peers[i].protocol.rpc_ping
        peers[i].protocol.rpc_ping = mock_ping

    log = dht.log
    # We check for unique port numbers because addr is /usually/ an (ip, port)
    # tuple when calling dht.transmit.
    ports = [p.node.port for p in peers.values()]
    unique_ports = len(set(ports)) == len(peers.keys())
    dht.log("Unique port numbers: %s" % str("Yes." if unique_ports else "No. Recreating."))
    if not unique_ports:
        return create_peers(peer_amount, storage_method)

    dht.log("Introducing peers to one another.")
    dht.log = lambda x, y=None: x
    for peer in peers.values():
        [peer.add_contact(router.node) for router in peers.values()]
    dht.log = log
    print pprint.pformat(peers)

    # Please god, forgive this fourth loop?
    for p in peers.values():
        peer.protocol.rpc_ping = peer.protocol.original_ping
    return peers

def mock_ping(addr):
    return

def mock_transmit(routes, addr, data):
    """
    Put dht.RoutingTable instances through to one another without calling out
    to the network.
    """
    # Test case setup method should set a peers attr on this function beforehand
    if not hasattr(mock_transmit, "peers"):
        dht.log("Can't find test peers.")
        dht.log("synchrony.test.utils.mock_transmit is missing a peers dictionary.")
        return

    if isinstance(addr, dht.Node):
        addr = (addr.ip, addr.port)

    # Filter for everyone who isn't the intended recipient
    peer_routes = filter(
        lambda r: r if r.node.port == addr[1] else None,
        [r for r in mock_transmit.peers.values()]
    )

    if not peer_routes:
        dht.log("Unknown peer %s:%i" % addr)
        return

    peer_routes = peer_routes[0]
    data = dht.envelope(routes, data)

    for field in data.keys():
        if field.startswith('rpc_'):
            rpc_name = 'handle_%s' % field.replace('rpc_', '')
            rpc_method = getattr(peer_routes.protocol, rpc_name, None)
            if not rpc_method:
                dht.log("%s tried to call unknown procedure %s." % \
                    (routes.node, rpc_name), "warning")
                return
            return rpc_method(data)

def mock_get(addr, path, field="data", all=True):
    if isinstance(addr, dht.Node):
        f    = lambda f: f.node.threeple == addr.threeple
        addr = filter(f, mock_get.peers.values())
        if addr:
            if '/' in path:
                node_id = long(path.split('/')[1])
                for peer in addr[0]:
                    if peer.long_id == node_id:
                        return peer.jsonify()
                return {}

            return [p.jsonify() for p in addr[0]]

    return []

def mock_fetch_revision(url, content_hash, nodes):
    first_node = mock_fetch_revision.peers.values()[0].node
    f = lambda x: x.node.threeple == first_node.threeple
    c = filter(f, nodes)
    if not c: return
    c = c[0]

    return  Revision.query.filter(Revision.hash == content_hash).first()

class TestProtocol(dht.SynchronyProtocol):
    def __init__(self, router, storage, ksize, peers):
        self.peers         = peers
        self.ksize         = ksize
        self.router        = router
        self.epsilon       = 0.0001
        self.storage       = storage
        self.source_node   = router.node
        self.downloads     = dht.ForgetfulStorage()         # content_hash -> (n.ip, n.port)
        self.received_keys = dht.ForgetfulStorage(bound=2)  # node -> [republish_messages,..]

        super(dht.SynchronyProtocol, self).__init__()

    def get_refresh_ids(self):
        """
        Get ids to search for to keep old buckets up to date.
        """
        ids = []
        for bucket in self.router.get_lonely_buckets():
            ids.append(random.randint(*bucket.range))
        return ids

    def rpc_ping(self, addr):
        # "addr" may be an (addr, port) tuple
        data = dht.transmit(self.router, addr, {"rpc_ping":True})
        # Remove peer
        if not data:
            if isinstance(addr, Node):
                self.router.remove_node(addr)
            return
        node = dht.Node(*data['node'], pubkey=data['pubkey'], router=self.router)
        self.router.add_contact(node)
        # FIXME: Ping nodes in the 'peers' part of the response.
        #        Don't let malicious nodes fill the routing table with
        #        information for peers who won't respond.
        if 'peers' in data:
            for peer in data['peers']:
                if peer['node'][0] == self.source_node.long_id:
                    continue
                peer = dht.Node(*peer['node'],
                            pubkey=peer['pubkey'],
                            router=self.router)
                self.router.add_contact(peer)
#                self.rpc_ping(node)
        return node

    def rpc_report_trust(self, node_to_rate, node_to_tell):
        """
        The equivalent is a GET request to /v1/peers/node_id

        """
        pass

    def rpc_add_friend(self, local_uid, addr):
        """
        addr is of the form "network_name/node_id/remote_user_id"
        Implements ADD_FRIEND where we find the node in addr and
        tell them a local user wants to add the remote UID as a friend.
        """
        if addr.count("/") != 2:
            return False, None
        network, node_id, remote_uid = addr.split("/")

        if network != self.router.network:
            return False, None

        node = dht.Node(long(node_id))
        nearest = self.router.find_neighbours(node)
        if len(nearest) == 0:
            dht.log("There are no neighbours to help us add users on %s as friends." % node_id)
            return False, None
        spider  = NodeSpider(self, node, nearest, self.ksize, self.router.alpha)
        nodes   = spider.find()

        if len(nodes) != 1:
            return False, None

        node    = nodes[0]

        # Sometimes spidering doesn't get us all the way there.
        # Check who we already know:
        if node.long_id != long(node_id):
            nodes = [n for n in self.router if n.long_id == long(node_id)]
            if len(nodes) != 1:
                return False, None
            node = nodes[0]

        dht.log(node_id, "debug")
        dht.log(node.long_id, "debug")

        dht.log("Found remote instance %s." % node)
        message = {"rpc_add_friend": {"from": local_uid, "to": remote_uid}}

        response = dht.transmit(self.router, node, message)
        if not isinstance(response, dict) or not "response" in response:
            return False, None

        return response['response'], node

    def rpc_chat(self, nodeple, data):
        """
        Implements CHAT where we encrypt a message destined for the user with
        UID on the receiving node.

        Message data should be of the form
        {
           'to': 'uid',
           'from': ['uid', 'username'],
           'type': Can be any of "message", "init", "close"
           'body': {'m':'content'}
        }
        """
        # Worth retaining this ping call for the routing information we get.
        node     = self.rpc_ping(nodeple)

        if node == None:
            return

        data     = base64.b64encode(json.dumps(data))
        key      = RSA.importKey(node.pubkey)
        data     = key.encrypt(data, 32)
        data     = base64.b64encode(data[0])
        response = dht.transmit(self.router, node, {'rpc_chat': data})
        dht.log(response, "debug")
        return response

    def rpc_edit(self, node, data):
        """
        Implements inter-instance EDIT.

        Message data should be of the form
        {
           'stream': 'stream_id',
           'from': ['uid', 'username'],
           'edit': 'Some DOM nodes to match and replace'
        }
        """
        data = base64.b64encode(json.dumps(data))
        key  = RSA.importKey(node.pubkey)
        data = key.encrypt(data, 32)
        dht.transmit(self.router, addr, {'rpc_edit': data})

    def rpc_leaving(self, node):
        addr = self.get_address(node)
        return dht.transmit(self.router, addr, {"rpc_leaving":True})

    def rpc_append(self, node, url_hash, content_hash):
        """
        Allows senders to tell peers they have the data for the hash of a path.
        Hash here is the hash made from the content the peer has stored.
        They're letting you know they have data that corresponds to the hash.
        {
         peers:       [],
         pubkey:      "",
         signature:   "",
         time:        1440064069.0,
         rpc_append:  {url_hash: content_hash},
        }
        """
        # Append this peer to the list of nodes storing data for this path
        # urls[data['url']].append(sender)
        addr = self.get_address(node)
        data = {"rpc_append": {url_hash: content_hash}}
#        if addr.threeple == self.source_node.threeple:
#            self.storage[url_hash] = (content_hash, addr)
        return dht.transmit(self.router, addr, data)

    def rpc_find_node(self, node_to_ask, node_to_find):
        address = (node_to_ask.ip, node_to_ask.port)
        message = {'key': node_to_find.id}
        message = dht.envelope(self.router, message)
        return self.handle_find_node(message)

    def rpc_find_value(self, node_to_ask, node_to_find):
        address = (node_to_ask.ip, node_to_ask.port)
        message = {'rpc_find_value': binascii.hexlify(node_to_find.id)}
        return dht.transmit(self.router, address, message)

    def rpc_transfer_routing_table(self, sender, nodeid):
        pass

    def rpc_republish(self, node, data):
        """
        Please refer to SynchronyProtocol.republish_keys to see what's really going
        on here.

        The data argument here is a list that looks like this:
        [{'node': [[nodeple], 'pubkey'],'keys': {signature: key_data}}, ...]
        Where "key_data" is a b64encoded JSON dump of the return value for
        self.storage.get_entries_for(self.source_node).

        Peers save this message, as we remember when they send rpc_republish
        messages to us. We forward previous rpc_republish messages for peers
        we still have as a contact.
        """
        addr = self.get_address(node)
        data = {'rpc_republish': data}
        return dht.transmit(self.router, addr, data)

    def rpc_transfer_storage_table(self, node):
        """
        Given a new node, send it all the keys/values it should be storing.
        node here is a new node that's just joined or that we've just found
        out about.

        For each key in storage, get k closest nodes. If newnode is closer
        than the furthest in that list, and the node for this server
        is closer than the closest in that list, then store the key/value
        on the new node (per section 2.5 of the paper)
        """
        ds = []
        for key, value in self.storage.iteritems():
            keynode = dht.Node(sha1(key).digest())
            neighbours = self.router.find_neighbours(keynode)
            if len(neighbours) > 0:
                new_node_close = node.distance_to(keynode) < neighbours[-1].distance_to(keynode)
                this_node_closest = self.source_node.distance_to(keynode) < neighbours[0].distance_to(keynode)
            if len(neighbours) == 0 or (new_node_close and this_node_closest):
                ds.append(self.call_store(node, key, value))
        return ds

    # handle_* methods (generally) indicate a request initiated by a peer node.

    def handle_ping(self, data):
        node = self.read_envelope(data)
        dht.log("Received rpc_ping from %s." % node)
        return dht.envelope(self.router, {'ping':"pong"})

    def handle_add_friend(self, data):
        """
        Match to UID and return a new Friend instance representing our side.
        """
        assert "rpc_add_friend" in data

        dht.log(data, "debug")
        request   = data['rpc_add_friend']

        if not "from" in request or not "to" in request:
            return False

        node         = self.read_envelope(data)
        user         = User.query.filter(User.uid == request['to']).first()
        if not user: return None
        from_addr    = "/".join([self.router.network, str(node.long_id), request['from']])
        friend       =  Friend.query.filter(
                            and_(Friend.address == from_addr, Friend.user == user)
                        ).first()
        if friend:
            # This permits the remote side to see if they're added or blocked.
            return dht.envelope(self.router, {"response": friend.jsonify()})

        node = dht.Node(*data['node'])

        network = Network.query.filter(Network.name == self.router.network).first()

        if network != None:
            network = Network(name = self.router.network)

        peer = Peer.query.filter(
                    and_(Peer.network == network,
                         Peer.ip      == node.ip,
                         Peer.port    == node.port)
                ).first()

        if peer == None:
            peer = Peer()
            peer.load_node(node)
            peer.network = network

        friend          = Friend(address=from_addr)
        friend.state    = 1
        friend.received = True
        # TODO: Make this correspond to the existing rpc_friend method.

        user.friends.append(friend)
        peer.friends.append(friend)

        db.session.add(user)
        db.session.add(peer)
        db.session.add(friend)
        db.session.add(network)
        db.session.commit()

        return dht.envelope(self.router, {"response": friend.jsonify()})

    def handle_chat(self, data):
        """
        Move a message from a remote node up to the UI if the recipient
        UID has an active connection to the chat stream.
        """
        node            = self.read_envelope(data)
        # With the ciphertext being a binary string we also b64encode it
        message_content = base64.b64decode(data['rpc_chat'])
        message_content = app.key.decrypt((message_content,))
        data            = json.loads(base64.b64decode(message_content))
        dht.log(message_content, "debug")
        dht.log(data, "debug")

        user = User.query.filter(User.uid == data['to']).first()
        if user == None:
            return {"error": "No such user."}

        friend = Friend.query.filter(and_(Friend.user    == user,
                                          Friend.network == self.router.network,
                                          Friend.node_id == str(node.long_id),
                                          Friend.uid     == data['from'][0])
                                    ).first()
        if friend:

            available = utils.check_availability(self.router.httpd, "chat", user)
            if not available:
                return {"error": "The intended recipient isn't connected to chat."}

            if data['type'] == "init":
                # Enable the recipient to reply by forcing them into the channel
                dht.log("Changing chat channel of %s to %s." % \
                    (user.username, friend.address), "debug")
                utils.change_channel(self.router.httpd,
                                     "chat",
                                     user,
                                     friend.address)
                utils.broadcast(self.router.httpd,
                                "chat",
                                "rpc_chat_init",
                                data['from'],
                                user=user)

            if data['type'] == "message":
                utils.broadcast(self.router.httpd,
                                "chat",
                                "rpc_chat",
                                data,
                                user=user)
        return {"state": "delivered"}

    def handle_edit(self, data):
        self.read_envelope(data)
        data = app.key.decrypt(data['rpc_edit'])
        pass

    def handle_leaving(self, data):
        conscientous_objector = self.read_envelope(data)
        self.router.remove_node(conscientous_objector)

    def handle_find_node(self, data):
        """
        Used for finding existing nodes near to a target ID.
        """
        source = self.read_envelope(data)
        if not 'key' in data:
            return "No target key specified.", 400
        node = dht.Node(data['key'])
        dht.log("Finding neighbours of %s." % node.long_id)
        nodes = {'nodes': [p.jsonify() for p in \
                self.router.find_neighbours(node, exclude=source)]}
        return dht.envelope(self.router, nodes)

    def handle_find_value(self, data):
        source = self.read_envelope(data)
        if not source: return
        if not 'rpc_find_value' in data: return
        # usually comes in as unicode
        if not isinstance(data['rpc_find_value'], (unicode, str)):
            return
        key = data['rpc_find_value']
        dht.log("Finding value for %s" % key)
        value = self.storage.get(key, None)
        if key is None:
            dht.log("No value found for %s" % key)
            return self.rpc_find_node(sender, nodeid, key)
        dht.log("Found %s" % value)
        return dht.envelope(self.router,{'value':value})

    def handle_append(self, data):
        """
        Handle messages of the form {'rpc_append': {'url_hash': 'content_hash'}}
        We do this by inserting the data into a structure that looks like
        { 'url_hash': {'content_hash': [(ts,nodeple)]}}
        """
        node = self.read_envelope(data)
        if max(node.trust, 0) == 0:
            dht.log("%s with negative trust rating tried to append." % node, "warning")
            return False
        url_hash, content_hash = data['rpc_append'].items()[0]
        dht.log("Received rpc_append request from %s." % node)
        dht.log("Adjusting known peers for %s." % url_hash)
        self.storage[url_hash] = (content_hash, node)
#        if self.router.options and self.router.options.autoreplicate:
#            if not Revision.query.filter(Revision.hash == content_hash).first():
#                revision = self.fetch_revision(content_hash, [source])
#                if revision:
#                    db.session.add(revision)
#                    db.session.commit()
        return True

    def handle_republish(self, data):
        """
        Retain signed messages here so they can be relayed.
        """
        node = self.read_envelope(data)

        if max(node.trust, 0) == 0:
            dht.log("%s with negative trust rating tried to republish." % node, "warning")
            return False

        dht.log("Received rpc_republish from %s." % node)
        republished_keys = data['rpc_republish']
        for message in republished_keys:

            if max(node.trust, 0) == 0:
                return False

            signature = (long(message['keys'].keys()[0]),)
            data      = message['keys'].values()[0]
            hash      = SHA256.new(data).digest()
            key       = RSA.importKey(message['node'][1])
            if not key.verify(hash, signature):
                dht.log("Invalid signatures for keys provided by %s." % node, "warning")
                node.trust -= self.epsilon
                continue

            try:
                keys = json.loads(base64.b64decode(data))
            except Exception, e:
                dht.log("Error unserialising republished keys: %s" % e.message, "error")
                continue

            referee = dht.Node(*message['node'][0], pubkey=message['node'][1])
            if self.router.is_new_node(referee):
                self.rpc_ping(referee)

            # Get the trust rating of this referee
            referee = self.router.get_existing_node(referee)
            if not referee or referee.trust < 0:
                dht.log("%s is currently republishing for %s." % (node, referee), "warning")
                continue

            self.storage.merge(keys)
            self.received_keys[referee.id] = message

        return True

    def fetch_revision(self, url, content_hash, nodeples):
        """
        Accesses the most trustworthy peers' routing table and see if they have
        any references to themselves for the desired url/content_hash pair.

        Updates local download references and then returns the revision.
        """
        urls       = []
        nodes      = []
        routers    = []
        hashed_url = hashlib.sha1(url).digest()
        revision   = Revision.query.filter(Revision.hash == content_hash).first()

        if revision == None:
            dht.log("No match for %s could be found in the current database.", "error")

        for n in nodeples:
            if n[1] == self.source_node.ip and n[2] == self.source_node.port:
                continue

            # Get local references to peer nodes
            node = self.router.get_existing_node(n)
            if node:
                nodes.append(node)
                continue
            node = self.rpc_ping(n)
            if node == None:
                continue

        # Get remote peer by its own routing table
        # TestProtocol.peers is test suite shorthand for all peers
        for node in dht.sort_nodes_by_trust(nodes):
            for router in self.peers.values():
                if node.threeple == router.node.threeple:
                    routers.append(router)

        if not any(routers):
            return None

        for router in routers:
            node = self.router.get_existing_node(router.node.threeple)

            node.trust += self.epsilon

            references = router.protocol.storage\
                .get(binascii.hexlify(hashed_url), None)
            if not references: continue

            # downloads is a list of (timestamp, node_triple) pairs.
            downloads = references.get(content_hash)
            if not any(downloads): continue

            for download in downloads:
                if download[1] == router.node.threeple:
                    self.downloads[url] = {revision.hash: (node.ip, node.port)}
                    return revision

        return None

    def republish_keys(self):
        """
        This means retransmitting url and content hashes we're serving for and
        signing the message.

        Signing permits peers to relay the message and permits us to republish
        for our peers.
        """
        data       = self.storage.get_entries_for(self.source_node)
        messages   = []
        threads    = []

        # Organise our keys for republishing
        if data:
            data = base64.b64encode(json.dumps(data))
            hash = SHA256.new(data).digest()
            signature = app.key.sign(hash, '')[0]
            messages.append(
                    {'node': [self.source_node.threeple, self.source_node.pubkey],
                    'keys': {signature: data}}
            )
        # Grab keys we've seen our peers republish
        for key in self.received_keys:
            messages.append(self.received_keys[key][-1])

        # Tell everyone
        if messages:
            dht.log("Republishing keys.")
            for node in self.router:
                threads.append(gevent.spawn(self.rpc_republish, node, messages))
            gevent.joinall(threads)

    def read_envelope(self, data):
        """
        Take an incoming message and either update the last_seen time for the
        sender or add the sender as a new contact.

        peers.py should also call this method once it's determined the network
        a message is for. That way we can inspect the 'peers' attribute and
        use read_envelope to also learn of new peers.
        """
        # Validate the senders' node ID
        seed = "%s:%i:%s" % (data['node'][1],data['node'][2],data['pubkey'])
        if data['node'][0] != long(utils.generate_node_id(seed).encode('hex'), 16):
            dht.log("\"%s\" is using an incorrect node ID." % data['node'][1], "warning")
            return

        # Learn of peers
        #  TODO: Spawn green threads to ping these nodes.
        #  NOTE: Don't permit a spammer to abuse the routing topology.
        #        This can include decrementing the senders trust rating for
        #        referring us to dead nodes.
        if 'peers' in data:
            for peer in data['peers']:
                node = dht.Node(*peer['node'], pubkey=peer['pubkey'], router=self.router)
                if node != self.source_node and self.router.is_new_node(node):
                    self.router.add_contact(node)

        # Update last_seen times for contacts or add if new
        node          = dht.Node(*data['node'], pubkey=data['pubkey'], router=self.router)
        existing_node = self.router.get_existing_node(node)
        if existing_node:
            existing_node.last_seen = time.time()
            return existing_node
        elif node != self.source_node:
            self.router.add_contact(node)
            return node

    def decrement_trust(self, addr, severity=1):
        """
        Implements the feedback mechanism for our trust metric.

        "addr" is an (ip, port) tuple to match to a known peer.
        "severity" is a floating point severity level indicating how bad the
        content in question was perceived to be.

        Notes on how this all works in sum as a distributed system are here:
        http://nlp.stanford.edu/pubs/eigentrust.pdf
        http://www.cc.gatech.edu/~lingliu/papers/2012/XinxinFan-EigenTrust++.pdf
        http://dimacs.rutgers.edu/Workshops/InformationSecurity/slides/gamesandreputation.pdf

        The second PDF is recommended.
        """
        for node in self.router:
            if node.ip == addr[0] and node.port == addr[1]:
                amount = severity / 100.0
                dht.log("Decrementing trust rating for %s by %f." % (node, amount), "warning")
                node.trust -= 2 * self.epsilon
#               peer = Peer.query.filter(
#                       and_(Peer.network == self.network,
#                            Peer.ip      == addr[0],
#                            Peer.port    == addr[1])
#                   ).first()
#               if peer:
#                   peer.trust -= amount
#                   db.session.add(peer)
#                   db.session.commit()
                return True

        return False

    def get_address(self, node):
        if node.ip == self.source_node.ip:
            address = ('127.0.0.1', node.port)
        else:
            address = (node.ip, node.port)
        return address

redpajama_set_name: RedPajamaGithub


text:
namespace content {

// Callback interface to receive results of RunFileChooser() and
// EnumerateDirectory() of WebContentsDelegate.
class FileSelectListener {
 public:
  virtual ~FileSelectListener() {}

  // This function should be called if file selection succeeds.
  // |files| - A list of selected files.
  // |base_dir| - This has non-empty directory path if |mode| argument is
  //              kUploadFolder and kUploadFolder is supported by the
  //              WebContentsDelegate instance. It represents enumeration root
  //              directory.
  //              This is an empty FilePath otherwise.
  // |mode| - kUploadFolder for WebContentsDelegate::EnumerateDirectory(), and
  //          |params.mode| for WebContentsDelegate::RunFileChooser().
  virtual void FileSelected(
      std::vector<blink::mojom::FileChooserFileInfoPtr> files,
      const base::FilePath& base_dir,
      blink::mojom::FileChooserParams::Mode mode) = 0;

  // This function should be called if a user cancels a file selection
  // dialog, or we open no file selection dialog for some reason.
  virtual void FileSelectionCanceled() = 0;
};

}  // namespace content
#endif  // CONTENT_PUBLIC_BROWSER_FILE_SELECT_LISTENER_H_


text:
package org.apache.sis.internal.storage.gpx;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.apache.sis.storage.DataStore;
import org.apache.sis.storage.DataStoreException;
import org.apache.sis.storage.StorageConnector;
import org.apache.sis.internal.storage.Capability;
import org.apache.sis.internal.storage.Capabilities;
import org.apache.sis.internal.storage.xml.stream.StaxDataStoreProvider;
import org.apache.sis.measure.Range;
import org.apache.sis.util.Version;

/**
 * The provider of {@link Store} instances. Given a {@link StorageConnector} input,
 * this class tries to instantiate a GPX {@code Store}.
 *
 * @author  Johann Sorel (Geomatys)
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.8
 * @since   0.8
 * @module
 */
@Capabilities({Capability.READ, Capability.WRITE})
public final class StoreProvider extends StaxDataStoreProvider {
    /**
     * The "1.0" version.
     */
    static final Version V1_0 = Version.valueOf(1,0);

    /**
     * The "1.1" version.
     */
    static final Version V1_1 = Version.valueOf(1,1);

    /**
     * The range of versions returned by {@link #getSupportedVersions()}.
     */
    private static final Range<Version> VERSIONS = new Range<>(Version.class, V1_0, true, V1_1, true);

    /**
     * Creates a new GPX store provider.
     */
    public StoreProvider() {
        super("GPX", 4);
        types.put(Tags.NAMESPACE_V10, "application/gpx+xml");
        types.put(Tags.NAMESPACE_V11, "application/gpx+xml");
    }

    /**
     * Returns the range of versions supported by the GPX data store.
     *
     * @return the range of supported versions.
     */
    @Override
    public Range<Version> getSupportedVersions() {
        return VERSIONS;
    }

    /**
     * Returns a GPX {@link Store} implementation associated with this provider.
     *
     * @param  connector  information about the storage (URL, stream, <i>etc</i>).
     * @return a data store implementation associated with this provider for the given storage.
     * @throws DataStoreException if an error occurred while creating the data store instance.
     */
    @Override
    public DataStore open(StorageConnector connector) throws DataStoreException {
        return new Store(this, connector);
    }

    /**
     * Returns the JAXB context for the data store. This method is invoked at most once.
     *
     * @return the JAXB context.
     * @throws JAXBException if an error occurred while creating the JAXB context.
     */
    @Override
    protected JAXBContext getJAXBContext() throws JAXBException {
        return JAXBContext.newInstance(Metadata.class);
    }
}


text:
var OnboardingViewModel = require('builder/components/onboardings/onboarding-view-model');

describe('components/onboardings/onboarding-view-model', function () {
  beforeEach(function () {
    this.createContentViewResult = {};
    this.createContentView = jasmine.createSpy('createContentView').and.returnValue(this.createContentViewResult);
    this.model = new OnboardingViewModel({
      createContentView: this.createContentView
    });
  });

  it('should allow show/hide onboarding', function () {
    expect(this.model.get('show')).toBe(true);
    expect(this.model.isHidden()).toBe(false);

    this.model.hide();
    expect(this.model.get('show')).toBe(false);
    expect(this.model.isHidden()).toBe(true);

    this.model.show();
    expect(this.model.get('show')).toBe(true);
    expect(this.model.isHidden()).toBe(false);
  });

  describe('.createContentView', function () {
    beforeEach(function () {
      this.view = this.model.createContentView();
    });

    it('should create content view given viewModel', function () {
      expect(this.createContentView).toHaveBeenCalled();
      expect(this.createContentView).toHaveBeenCalledWith(this.model);
    });

    it('should return created view', function () {
      expect(this.view).toBe(this.createContentViewResult);
    });
  });

  describe('.destroy', function () {
    beforeEach(function () {
      this.destroySpy = jasmine.createSpy('onDestroy');
      this.model.on('destroy', this.destroySpy);
      this.model.destroy('arg1', 'arg2', 'arg3');
    });

    it('should destroy the model', function () {
      expect(this.destroySpy).toHaveBeenCalled();
    });

    it('should pass through any arguments to listener', function () {
      var args = this.destroySpy.calls.argsFor(0);
      expect(args[0]).toEqual('arg1');
      expect(args[1]).toEqual('arg2');
      expect(args[2]).toEqual('arg3');
    });
  });
});


text:
$(document).on("ready", function(){
    $("#zonasqr_menu").attr("class","active zonasqr_menu");

    loaddatazona();
    listamensajeszona();

    $("#general").click(changesectiongeneral);
    $("#msjs_programados").click(changesectionmensaje);

});

function loadtiposzonas(){

    url= $(".now").val() + "index.php/api/zonasrest/loadtiposzonas/format/json";

    $.get(url).done(function(data){
        reporte="";
        for (a = 0; a < data.length; a++) {

            name_img =data[a].img_name;
            url_img = $(".now").val()+"application/img/tipo_zonas/"+name_img;

            reporte+="
";
            reporte+="
<input type='radio' name='tipozona' id='"+data[a].idTipo_zona+"' value='"+ data[a].idTipo_zona+"'  class='tipozona' onclick='etipozona(this);'> "+data[a].nombre +"
" ;
            reporte+="
";

        }
              llenaelementoHTML("#edit_tipozona", reporte);

    }).fail(function(){

        alert("Error");
    });

}

function etipozona(e){
    nueva_tzona  = e.value;
    idzona =  $("#zonaqredit").val();

    url = $("#now").val()+"index.php/api/zonasrest/settipocampbyid/format/json/";

    $.post(url , {"tzona" : nueva_tzona , "idzona":idzona }).done(function(data){

    }).fail(function(){
        alert("error");
    });

}

function loaddatazona(){

	idzona =  $("#zonaqredit").val();
	loadtiposzonas();
    tipo_zona = "";
    url = $(".now").val()+ "index.php/api/zonasrest/getzonabyid/format/json";
    add_img = $(".now").val()+ "application/img/general/add13.png";
    newimg= "";

    $.get(url, { "idzona": idzona}).done(function(data){

    	if (data.length >0) {

    		for (var a = 0; a < data.length; a++) {

    			//valorHTML("#zona_name" , data[a].zonanombre);
                if ($.trim(data[a].zonanombre) == "") {

                    llenaelementoHTML("#zona_name" , newimg);
                }else{
                    llenaelementoHTML("#zona_name" , data[a].zonanombre);
                }

                if ( $.trim(data[a].descripcion) == "") {

                    llenaelementoHTML("#zona_referencia" , newimg);
                }else{
                    llenaelementoHTML("#zona_referencia" , data[a].descripcion );
                }

    			llenaelementoHTML("#zona_fecha" , data[a].fecharegistro );

                if ($.trim(data[a].mensajedefault) ==""){
                    llenaelementoHTML( "#zona_defmsj", newimg);
                }else{
                    llenaelementoHTML( "#zona_defmsj", data[a].mensajedefault);
                }

                tipo_zona = data[a].idTipo_zona;

                valorHTML("#zona_name_input_value" , data[a].zonanombre);
                valorHTML("#zona_name_area_value" , data[a].descripcion );

                idtipozonacheck =  "#"+data[a].idTipo_zona;

                $(idtipozonacheck).prop( "checked", true );

                valorHTML("#zona_defmsj_input_value", data[a].mensajedefault);

    		}

            img_qr = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data="+$(".now").val()+"index.php/appqrsocial/zonaatt?idzona="+idzona+"&format=json/";
            llenaelementoHTML("#qr_zona_img", "" );
    	}else{

    		urlnext = $(".now").val()+"index.php/zonasqr/principal";
    		redirect(urlnext);
    	}

        select_tipozona(tipo_zona);

    }).fail(function(){

    	alert("Fail on load data zona");

    });

$("#zona_name").click(editacampo);
$("#zona_referencia").click(editarea);
$("#zona_defmsj").click(editacampomensadedef);
/*Termina load zona*/
}

function editacampomensadedef(){

    text_valor= $("#"+this.id).text();
    $("#"+this.id).hide();

    valorHTML("#zona_defmsj_input_value" , text_valor);
    $("#zona_defmsj_input_value").show();

    $("#zona_defmsj_input_value").blur(function(e){

                 label_val = $("#zona_defmsj_input_value").val();
                 llenaelementoHTML("#zona_defmsj", label_val );
                 $("#zona_defmsj").show();
                 $("#zona_defmsj_input_value").hide();
                 update_zona();
                 return false;
                 //$("#"+this.id).remove();

        });
        return false;

}

function editacampo(){

    text_valor= $("#"+this.id).text();
    valorHTML("#zona_name_input_value" , text_valor);
    $("#"+this.id).hide();
    $("#zona_name_input_value").show();

    $("#zona_name_input_value").blur(function(e){

             label_val= $("#zona_name_input_value").val();
             llenaelementoHTML("#zona_name", label_val );
             $("#zona_name").show();
              $("#zona_name_input_value").hide();
             update_zona();

    });
    return false;

}

function editarea(){

    text_valor= $("#"+this.id).text();
    $("#"+this.id).hide();
    $("#zona_name_area_value").show();
    valorHTML("#zona_name_area_value", text_valor);

        $("#zona_name_area_value").blur(function(e){

                     label_val= $("#zona_name_area_value").val();
                     llenaelementoHTML("#zona_referencia", label_val );
                     $("#zona_referencia").show();
                     $("#zona_name_area_value").hide();
                     update_zona();

            });

    return false;

}

function update_zona(){

    url = $(".now").val()+"index.php/api/zonasrest/updatezona/format/json";
    $.post(url, $("#form_zona_edit").serialize()).done(function(data){

    }).fail(function(){
        alert("Falla al registrar cambios");
    });

    loaddatazona();
    urlimg = $(".now").val()+"application/img/general/glyphicons-207-ok-2.png";
        llenaelementoHTML("#repo_update" ,  "
 Los datos se han actualizado
");
    return false;
}

function changesectiongeneral(){
    $("#section_general").show();
    $("#section_mensajes").hide();
}
function changesectionmensaje(){
    $("#section_general").hide();
    $("#section_mensajes").show();
}

function listamensajeszona(){

    urlListist = $(".now").val()+ "application/img/general/list92.png";
    url= $(".now").val()+"index.php/api/zonasrest/listMensajesZona/format/json";
    $.get(url, $("#form_zona_edit").serialize()).done(function(data){

        list="

#	Mensaje	Red social
";
        for(var x in data){

            url_base_img="";

            if (data[x].social =="F") {
                url_base_img = $(".now").val()+"application/img/general/facebook29.png";
            }else{
                url_base_img = $(".now").val()+"application/img/general/social71.png";
            }

            img = "";
            list+="
"+data[x].idmensaje+"	 "+data[x].descripcion+"	 "+img+"
";
        }
        list+="
";
        llenaelementoHTML("#list_mensajes", list);

    }).fail(function(){
        alert("Fail ");
    });

}


text:
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/schema/types"
	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/spf13/cobra"
	"github.com/coreos/rkt/common"
	"github.com/coreos/rkt/pkg/label"
	"github.com/coreos/rkt/pkg/uid"
	"github.com/coreos/rkt/stage0"
	"github.com/coreos/rkt/store"
)

var (
	defaultStage1Image   string // either set by linker, or guessed in init()
	defaultStage1Name    string // set by linker
	defaultStage1Version string // set by linker

	cmdRun = &cobra.Command{
		Use:   "run [--volume=name,kind=host,...] IMAGE [-- image-args...[---]]...",
		Short: "Run image(s) in a pod in rkt",
		Long: `IMAGE should be a string referencing an image; either a hash, local file on disk, or URL.
They will be checked in that order and the first match will be used.

An "--" may be used to inhibit rkt run's parsing of subsequent arguments,
which will instead be appended to the preceding image app's exec arguments.
End the image arguments with a lone "---" to resume argument parsing.`,
		Run: runWrapper(runRun),
	}
	flagStage1Image  string
	flagVolumes      volumeList
	flagPorts        portList
	flagPrivateNet   common.PrivateNetList
	flagPrivateUsers bool
	flagInheritEnv   bool
	flagExplicitEnv  envMap
	flagInteractive  bool
	flagNoOverlay    bool
	flagLocal        bool
	flagPodManifest  string
	flagMDSRegister  bool
	flagUUIDFileSave string
)

func setDefaultStage1Image() {
	// if not set by linker, try discover the directory rkt is running
	// from, and assume the default stage1.aci is stored alongside it.
	if defaultStage1Image == "" {
		if exePath, err := os.Readlink("/proc/self/exe"); err == nil {
			defaultStage1Image = filepath.Join(filepath.Dir(exePath), "stage1.aci")
		}
	}
}

func init() {
	setDefaultStage1Image()

	cmdRkt.AddCommand(cmdRun)

	cmdRun.Flags().StringVar(&flagStage1Image, "stage1-image", defaultStage1Image, `image to use as stage1. Local paths and http/https URLs are supported. By default, rkt will look for a file called "stage1.aci" in the same directory as rkt itself`)
	cmdRun.Flags().Var(&flagVolumes, "volume", "volumes to mount into the pod")
	cmdRun.Flags().Var(&flagPorts, "port", "ports to expose on the host (requires --private-net)")
	cmdRun.Flags().Var(&flagPrivateNet, "private-net", "give pod a private network that defaults to the default network plus all user-configured networks. Can be limited to a comma-separated list of network names")
	cmdRun.Flags().Lookup("private-net").NoOptDefVal = "all"
	cmdRun.Flags().BoolVar(&flagInheritEnv, "inherit-env", false, "inherit all environment variables not set by apps")
	cmdRun.Flags().BoolVar(&flagNoOverlay, "no-overlay", false, "disable overlay filesystem")
	cmdRun.Flags().BoolVar(&flagPrivateUsers, "private-users", false, "Run within user namespaces (experimental).")
	cmdRun.Flags().Var(&flagExplicitEnv, "set-env", "an environment variable to set for apps in the form name=value")
	cmdRun.Flags().BoolVar(&flagInteractive, "interactive", false, "run pod interactively. If true, only one image may be supplied.")
	cmdRun.Flags().BoolVar(&flagLocal, "local", false, "use only local images (do not discover or download from remote URLs)")
	cmdRun.Flags().StringVar(&flagPodManifest, "pod-manifest", "", "the path to the pod manifest. If it's non-empty, then only '--private-net', '--no-overlay' and '--interactive' will have effects")
	cmdRun.Flags().BoolVar(&flagMDSRegister, "mds-register", true, "register pod with metadata service")
	cmdRun.Flags().StringVar(&flagUUIDFileSave, "uuid-file-save", "", "write out pod UUID to specified file")

	// per-app flags
	cmdRun.Flags().Var((*appAsc)(&rktApps), "signature", "local signature file to use in validating the preceding image")
	cmdRun.Flags().Var((*appExec)(&rktApps), "exec", "override the exec command for the preceding image")

	flagVolumes = volumeList{}
	flagPorts = portList{}

	// Disable interspersed flags to stop parsing after the first non flag
	// argument. All the subsequent parsing will be done by parseApps.
	// This is needed to correctly handle image args
	cmdRun.Flags().SetInterspersed(false)
}

func getStage1Hash(s *store.Store, stage1ImagePath string) (*types.Hash, error) {
	fn := &finder{
		imageActionData: imageActionData{
			s: s,
		},
		local:    true,
		withDeps: false,
	}
	isDefault := stage1ImagePath == defaultStage1Image

	var (
		s1img *types.Hash
		err   error
	)
	// with a default stage1, first try to get the image from the store
	if isDefault {
		// we make sure we've built rkt with a clean git tree, otherwise we
		// don't know if something changed
		if !strings.HasSuffix(defaultStage1Version, "-dirty") {
			stage1AppName := fmt.Sprintf("%s:%s", defaultStage1Name, url.QueryEscape(defaultStage1Version))
			s1img, err = fn.findImage(stage1AppName, "", true)
		}
	}

	// we couldn't find a proper stage1 image in the store, fall back to using
	// a stage1 ACI file (slow)
	if s1img == nil {
		s1img, err = fn.findImage(stage1ImagePath, "", false)
		if err != nil {
			return nil, fmt.Errorf("error finding stage1 image %q: %v", stage1ImagePath, err)
		}
	}

	return s1img, nil
}

func runRun(cmd *cobra.Command, args []string) (exit int) {
	privateUsers := uid.NewBlankUidRange()
	err := parseApps(&rktApps, args, cmd.Flags(), true)
	if err != nil {
		stderr("run: error parsing app image arguments: %v", err)
		return 1
	}

	if flagPrivateUsers {
		if !common.SupportsUserNS() {
			stderr("run: --private-users is not supported, kernel compiled without user namespace support")
			return 1
		}
		privateUsers.SetRandomUidRange(uid.DefaultRangeCount)
	}

	if len(flagPorts) > 0 && !flagPrivateNet.Any() {
		stderr("--port flag requires --private-net")
		return 1
	}

	if len(flagPodManifest) > 0 && (len(flagVolumes) > 0 || len(flagPorts) > 0 || flagInheritEnv || !flagExplicitEnv.IsEmpty() || rktApps.Count() > 0 || flagLocal) {
		stderr("conflicting flags set with --pod-manifest (see --help)")
		return 1
	}

	if globalFlags.Dir == "" {
		log.Printf("dir unset - using temporary directory")
		var err error
		globalFlags.Dir, err = ioutil.TempDir("", "rkt")
		if err != nil {
			stderr("error creating temporary directory: %v", err)
			return 1
		}
	}

	if flagInteractive && rktApps.Count() > 1 {
		stderr("run: interactive option only supports one image")
		return 1
	}

	if rktApps.Count() < 1 && len(flagPodManifest) == 0 {
		stderr("run: must provide at least one image or specify the pod manifest")
		return 1
	}

	s, err := store.NewStore(globalFlags.Dir)
	if err != nil {
		stderr("run: cannot open store: %v", err)
		return 1
	}

	config, err := getConfig()
	if err != nil {
		stderr("run: cannot get configuration: %v", err)
		return 1
	}
	fn := &finder{
		imageActionData: imageActionData{
			s:                  s,
			headers:            config.AuthPerHost,
			dockerAuth:         config.DockerCredentialsPerRegistry,
			insecureSkipVerify: globalFlags.InsecureSkipVerify,
			debug:              globalFlags.Debug,
		},
		local:    flagLocal,
		withDeps: false,
	}

	s1img, err := getStage1Hash(s, flagStage1Image)
	if err != nil {
		stderr("%v", err)
		return 1
	}

	fn.ks = getKeystore()
	fn.withDeps = true
	if err := fn.findImages(&rktApps); err != nil {
		stderr("%v", err)
		return 1
	}

	p, err := newPod()
	if err != nil {
		stderr("Error creating new pod: %v", err)
		return 1
	}

	// if requested, write out pod UUID early so "rkt rm" can
	// clean it up even if something goes wrong
	if flagUUIDFileSave != "" {
		if err := writeUUIDToFile(p.uuid, flagUUIDFileSave); err != nil {
			stderr("Error saving pod UUID to file: %v", err)
			return 1
		}
	}

	processLabel, mountLabel, err := label.InitLabels(nil)
	if err != nil {
		stderr("Error initialising SELinux: %v", err)
		return 1
	}

	cfg := stage0.CommonConfig{
		MountLabel:   mountLabel,
		ProcessLabel: processLabel,
		Store:        s,
		Stage1Image:  *s1img,
		UUID:         p.uuid,
		Debug:        globalFlags.Debug,
	}

	pcfg := stage0.PrepareConfig{
		CommonConfig: cfg,
		UseOverlay:   !flagNoOverlay && common.SupportsOverlay(),
		PrivateUsers: privateUsers,
	}

	if len(flagPodManifest) > 0 {
		pcfg.PodManifest = flagPodManifest
	} else {
		pcfg.Volumes = []types.Volume(flagVolumes)
		pcfg.Ports = []types.ExposedPort(flagPorts)
		pcfg.InheritEnv = flagInheritEnv
		pcfg.ExplicitEnv = flagExplicitEnv.Strings()
		pcfg.Apps = &rktApps
	}

	err = stage0.Prepare(pcfg, p.path(), p.uuid)
	if err != nil {
		stderr("run: error setting up stage0: %v", err)
		return 1
	}

	// get the lock fd for run
	lfd, err := p.Fd()
	if err != nil {
		stderr("Error getting pod lock fd: %v", err)
		return 1
	}

	// skip prepared by jumping directly to run, we own this pod
	if err := p.xToRun(); err != nil {
		stderr("run: unable to transition to run: %v", err)
		return 1
	}

	rcfg := stage0.RunConfig{
		CommonConfig: cfg,
		PrivateNet:   flagPrivateNet,
		LockFd:       lfd,
		Interactive:  flagInteractive,
		MDSRegister:  flagMDSRegister,
		LocalConfig:  globalFlags.LocalConfigDir,
	}

	apps, err := p.getApps()
	if err != nil {
		stderr("run: cannot get the appList in the pod manifest: %v", err)
		return 1
	}
	rcfg.Apps = apps
	stage0.Run(rcfg, p.path()) // execs, never returns

	return 1
}

// volumeList implements the flag.Value interface to contain a set of mappings
// from mount label --> mount path
type volumeList []types.Volume

func (vl *volumeList) Set(s string) error {
	vol, err := types.VolumeFromString(s)
	if err != nil {
		return err
	}

	*vl = append(*vl, *vol)
	return nil
}

func (vl *volumeList) String() string {
	var vs []string
	for _, v := range []types.Volume(*vl) {
		vs = append(vs, v.String())
	}
	return strings.Join(vs, " ")
}

func (vl *volumeList) Type() string {
	return "volumeList"
}

// portList implements the flag.Value interface to contain a set of mappings
// from port name --> host port
type portList []types.ExposedPort

func (pl *portList) Set(s string) error {
	parts := strings.SplitN(s, ":", 2)
	if len(parts) != 2 {
		return fmt.Errorf("%q is not in name:port format", s)
	}

	name, err := types.NewACName(parts[0])
	if err != nil {
		return fmt.Errorf("%q is not a valid port name: %v", parts[0], err)
	}

	port, err := strconv.ParseUint(parts[1], 10, 16)
	if err != nil {
		return fmt.Errorf("%q is not a valid port number", parts[1])
	}

	p := types.ExposedPort{
		Name:     *name,
		HostPort: uint(port),
	}

	*pl = append(*pl, p)
	return nil
}

func (pl *portList) String() string {
	var ps []string
	for _, p := range []types.ExposedPort(*pl) {
		ps = append(ps, fmt.Sprintf("%v:%v", p.Name, p.HostPort))
	}
	return strings.Join(ps, " ")
}

func (pl *portList) Type() string {
	return "portList"
}

// envMap implements the flag.Value interface to contain a set of name=value mappings
type envMap struct {
	mapping map[string]string
}

func (e *envMap) Set(s string) error {
	if e.mapping == nil {
		e.mapping = make(map[string]string)
	}
	pair := strings.SplitN(s, "=", 2)
	if len(pair) != 2 {
		return fmt.Errorf("environment variable must be specified as name=value")
	}
	if _, exists := e.mapping[pair[0]]; exists {
		return fmt.Errorf("environment variable %q already set", pair[0])
	}
	e.mapping[pair[0]] = pair[1]
	return nil
}

func (e *envMap) IsEmpty() bool {
	return len(e.mapping) == 0
}

func (e *envMap) String() string {
	return strings.Join(e.Strings(), "\n")
}

func (e *envMap) Strings() []string {
	var env []string
	for n, v := range e.mapping {
		env = append(env, n+"="+v)
	}
	return env
}

func (e *envMap) Type() string {
	return "envMap"
}


text:
//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "dll/base_traits.hpp"
#include "transform_layer.hpp"
#include "lcn.hpp"

namespace dll {

/*!
 * \brief Local Contrast Normalization layer
 */
template <typename Desc>
struct dyn_lcn_layer_impl : transform_layer<dyn_lcn_layer_impl<Desc>> {
    using desc        = Desc;                       ///< The descriptor of the layer
    using this_type   = dyn_lcn_layer_impl<Desc>;   ///< This layer's type
    using base_type   = transform_layer<this_type>; ///< The base type
    using layer_t     = this_type;                  ///< This layer's type
    using dyn_layer_t = typename desc::dyn_layer_t; ///< The dynamic version of this layer

    size_t K;
    size_t Mid;
    double sigma = 2.0;

    /*!
     * \brief Initialize the dynamic layer
     */
    void init_layer(size_t K){
        cpp_assert(K > 1, "The LCN kernel size must be greater than 1");
        cpp_assert(K % 2 == 1, "The LCN kernel size must be odd");

        this->K = K;
        this->Mid = K / 2;
    }

    /*!
     * \brief Returns a string representation of the layer
     */
    std::string to_short_string([[maybe_unused]] std::string pre = "") const {
        std::string desc("LCN(dyn): ");
        desc += std::to_string(K) + 'x' + std::to_string(K);
        return desc;
    }

    /*!
     * \brief Returns a string representation of the layer
     */
    std::string to_full_string([[maybe_unused]] std::string pre = "") const {
        std::string desc("LCN(dyn): ");
        desc += std::to_string(K) + 'x' + std::to_string(K);
        return desc;
    }

    template <typename W>
    etl::dyn_matrix<W, 2> filter(double sigma) const {
        etl::dyn_matrix<W, 2> w(K, K);

        lcn_filter(w, K, Mid, sigma);

        return w;
    }

    /*!
     * \brief Apply the layer to the batch of input
     * \param output The batch of output
     * \param input The batch of input to apply the layer to
     */
    template <typename Input, typename Output>
    void forward_batch(Output&& output, Input&& input) const {
        inherit_dim(output, input);

        using weight_t = etl::value_t<Input>;

        auto w = filter<weight_t>(sigma);

        for (size_t b = 0; b < etl::dim<0>(input); ++b) {
            lcn_compute(output(b), input(b), w, K, Mid);
        }
    }
};

// Declare the traits for the layer

template<typename Desc>
struct layer_base_traits<dyn_lcn_layer_impl<Desc>> {
    static constexpr bool is_neural     = false; ///< Indicates if the layer is a neural layer
    static constexpr bool is_dense      = false; ///< Indicates if the layer is dense
    static constexpr bool is_conv       = false; ///< Indicates if the layer is convolutional
    static constexpr bool is_deconv     = false; ///< Indicates if the layer is deconvolutional
    static constexpr bool is_standard   = false; ///< Indicates if the layer is standard
    static constexpr bool is_rbm        = false; ///< Indicates if the layer is RBM
    static constexpr bool is_pooling    = false; ///< Indicates if the layer is a pooling layer
    static constexpr bool is_unpooling  = false; ///< Indicates if the layer is an unpooling laye
    static constexpr bool is_transform  = true;  ///< Indicates if the layer is a transform layer
    static constexpr bool is_recurrent  = false; ///< Indicates if the layer is a recurrent layer
    static constexpr bool is_multi      = false; ///< Indicates if the layer is a multi-layer layer
    static constexpr bool is_dynamic    = true; ///< Indicates if the layer is dynamic
    static constexpr bool pretrain_last = false; ///< Indicates if the layer is dynamic
    static constexpr bool sgd_supported = true;  ///< Indicates if the layer is supported by SGD
};

/*!
 * \brief Specialization of sgd_context for dyn_lcn_layer_impl
 */
template <typename DBN, typename Desc, size_t L>
struct sgd_context<DBN, dyn_lcn_layer_impl<Desc>, L> {
    using layer_t          = dyn_lcn_layer_impl<Desc>;                            ///< The current layer type
    using previous_layer   = typename DBN::template layer_type<L - 1>;          ///< The previous layer type
    using previous_context = sgd_context<DBN, previous_layer, L - 1>;           ///< The previous layer's context
    using inputs_t         = decltype(std::declval<previous_context>().output); ///< The type of inputs

    inputs_t input;  ///< A batch of input
    inputs_t output; ///< A batch of output
    inputs_t errors; ///< A batch of errors

    sgd_context(const layer_t& /*layer*/){}
};

} //end of dll namespace


text:
px4_add_board(
	PLATFORM posix
	VENDOR px4
	MODEL sitl
	LABEL default
	TESTING

	DRIVERS
		#barometer # all available barometer drivers
		#batt_smbus
		camera_trigger
		#differential_pressure # all available differential pressure drivers
		#distance_sensor # all available distance sensor drivers
		gps
		#imu # all available imu drivers
		#magnetometer # all available magnetometer drivers
		pwm_out_sim
		#telemetry # all available telemetry drivers
		sim/tone_alarm
		tone_alarm
		#uavcan

	MODULES
		attitude_estimator_q
		camera_feedback
		commander
		dataman
		ekf2
		events
		fw_att_control
		fw_pos_control_l1
		gnd_att_control
		gnd_pos_control
		land_detector
		landing_target_estimator
		load_mon
		local_position_estimator
		logger
		mavlink
		mc_att_control
		mc_pos_control
		navigator
		replay
		sensors
		simulator
		vmount
		vtol_att_control
		wind_estimator

	SYSTEMCMDS
		#bl_update
		#config
		#dumpfile
		dyn
		esc_calib
		#hardfault_log
		led_control
		mixer
		motor_ramp
		#mtd
		#nshterm
		param
		perf
		pwm
		reboot
		sd_bench
		shutdown
		tests # tests and test runner
		top
		topic_listener
		tune_control
		ver

	EXAMPLES
		bottle_drop # OBC challenge
		dyn_hello # dynamically loading modules example
		fixedwing_control # Tutorial code from https://px4.io/dev/example_fixedwing_control
		hello
		#hwtest # Hardware test
		position_estimator_inav
		px4_mavlink_debug # Tutorial code from http://dev.px4.io/en/debug/debug_values.html
		px4_simple_app # Tutorial code from http://dev.px4.io/en/apps/hello_sky.html
		rover_steering_control # Rover example app
		segway
	)

set(config_sitl_viewer jmavsim CACHE STRING "viewer for sitl")
set_property(CACHE config_sitl_viewer PROPERTY STRINGS "jmavsim;none")

set(config_sitl_debugger disable CACHE STRING "debugger for sitl")
set_property(CACHE config_sitl_debugger PROPERTY STRINGS "disable;gdb;lldb")

# If the environment variable 'replay' is defined, we are building with replay
# support. In this case, we enable the orb publisher rules.
set(REPLAY_FILE "$ENV{replay}")
if(REPLAY_FILE)
	message("Building with uorb publisher rules support")
	add_definitions(-DORB_USE_PUBLISHER_RULES)

	message("Building without lockstep for replay")
	set(ENABLE_LOCKSTEP_SCHEDULER no)
else()
	set(ENABLE_LOCKSTEP_SCHEDULER yes)
endif()


text:
package aggregator_test

import (
	. "autoscaler/eventgenerator/aggregator"
	"autoscaler/fakes"
	"autoscaler/models"

	"sync"
	"time"

	"code.cloudfoundry.org/clock/fakeclock"
	"code.cloudfoundry.org/lager"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Aggregator", func() {
	const (
		fakeStatWindowSecs = 600
	)
	var (
		getPolicies          GetPoliciesFunc
		saveAppMetricToCache SaveAppMetricToCacheFunc
		aggregator           *Aggregator
		clock                *fakeclock.FakeClock
		logger               lager.Logger
		appMonitorsChan      chan *models.AppMonitor
		testAppId            string        = "testAppId"
		testMetricType       string        = "test-metric-name"
		testMetricUnit       string        = "a-metric-unit"
		fakeWaitDuration     time.Duration = 0 * time.Millisecond
		policyMap                          = map[string]*models.AppPolicy{
			testAppId: {
				AppId: testAppId,
				ScalingPolicy: &models.ScalingPolicy{
					InstanceMax: 5,
					InstanceMin: 1,
					ScalingRules: []*models.ScalingRule{
						{
							MetricType:            testMetricType,
							BreachDurationSeconds: 300,
							CoolDownSeconds:       300,
							Threshold:             30,
							Operator:              "<",
							Adjustment:            "-1",
						},
					},
				},
			},
		}
		appMetricDatabase    *fakes.FakeAppMetricDB
		appMetricChan        chan *models.AppMetric
		cacheLock            sync.RWMutex
		saveToCacheCallCount int
	)

	BeforeEach(func() {
		getPolicies = func() map[string]*models.AppPolicy {
			return policyMap
		}

		saveToCacheCallCount = 0
		saveAppMetricToCache = func(metric *models.AppMetric) bool {
			cacheLock.Lock()
			saveToCacheCallCount++
			cacheLock.Unlock()
			return true
		}

		clock = fakeclock.NewFakeClock(time.Now())
		logger = lager.NewLogger("Aggregator-test")

		appMonitorsChan = make(chan *models.AppMonitor, 10)
		if testAggregatorExecuteInterval > fakeWaitDuration {
			fakeWaitDuration = testAggregatorExecuteInterval
		}
		if testSaveInterval > fakeWaitDuration {
			fakeWaitDuration = testSaveInterval
		}
		appMetricDatabase = &fakes.FakeAppMetricDB{}
		appMetricChan = make(chan *models.AppMetric, 1)
	})

	Context("Start", func() {
		JustBeforeEach(func() {
			var err error
			aggregator, err = NewAggregator(logger, clock, testAggregatorExecuteInterval, testSaveInterval, appMonitorsChan,
				getPolicies, saveAppMetricToCache, fakeStatWindowSecs, appMetricChan, appMetricDatabase)
			Expect(err).NotTo(HaveOccurred())
			aggregator.Start()
			Expect(appMetricChan).Should(BeSent(&models.AppMetric{
				AppId:      testAppId,
				MetricType: testMetricType,
				Value:      "250",
				Unit:       testMetricUnit,
				Timestamp:  time.Now().UnixNano(),
			}))
			Eventually(clock.WatcherCount).Should(Equal(2))
		})

		AfterEach(func() {
			aggregator.Stop()
		})

		It("should send appMonitors and save appMetrics", func() {
			clock.Increment(1 * fakeWaitDuration)
			Eventually(appMonitorsChan).Should(Receive())
			Eventually(func() int {
				cacheLock.RLock()
				defer cacheLock.RUnlock()
				return saveToCacheCallCount
			}).Should(Equal(1))
			Eventually(appMetricDatabase.SaveAppMetricsInBulkCallCount).Should(Equal(1))
		})
	})

	Context("Stop", func() {
		JustBeforeEach(func() {
			var err error
			aggregator, err = NewAggregator(logger, clock, testAggregatorExecuteInterval, testSaveInterval, appMonitorsChan,
				getPolicies, saveAppMetricToCache, fakeStatWindowSecs, appMetricChan, appMetricDatabase)
			Expect(err).NotTo(HaveOccurred())
			aggregator.Start()
			Eventually(clock.WatcherCount).Should(Equal(2))
			aggregator.Stop()
			Expect(appMetricChan).Should(BeSent(&models.AppMetric{
				AppId:      testAppId,
				MetricType: testMetricType,
				Value:      "250",
				Unit:       testMetricUnit,
				Timestamp:  time.Now().UnixNano(),
			}))
		})

		It("should not send any appMetrics", func() {
			Eventually(clock.WatcherCount).Should(BeZero())

			clock.Increment(1 * fakeWaitDuration)
			Consistently(appMonitorsChan).ShouldNot(Receive())
			Consistently(appMetricDatabase.SaveAppMetricsInBulkCallCount).Should(Equal(0))
		})
	})
})


text:
OBJS = main.o run.o statsCollector.o agent.o
CC = g++
CFLAGS = -Wall -c
LFLAGS = -Wall

menger-abm : $(OBJS)
	$(CC) $(LFLAGS) $(OBJS) -o menger-abm

main.o : main.cpp run.h config.h statsCollector.h agent.h
	$(CC) $(CFLAGS) main.cpp

run.o : run.cpp run.h agent.h config.h statsCollector.h
	$(CC) $(CFLAGS) run.cpp

statsCollector.o : statsCollector.cpp statsCollector.h
	$(CC) $(CFLAGS) statsCollector.cpp

agent.o: agent.cpp config.h agent.h run.h util.h
	$(CC) $(CFLAGS) agent.cpp

clean:
	rm -rf $(OBJS)


text:
export const testSiteNotification = {
	id: 'test-notification-id',
	title: 'Test notification title',
	content: 'Test notification content',
	ctaURL: '',
	ctaLabel: '',
	ctaTarget: '',
	dismissible: true,
	dismissLabel: 'test dismiss site notification',
	learnMoreURL: '',
	learnMoreLabel: '',
};


text:
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Firestorm.Client.Tests")]


text:
---
id: 5a24c314108439a4d4036164
title: Crear un componente con composición
challengeType: 6
forumTopicId: 301383
dashedName: create-a-component-with-composition
---

# --description--

Ahora veremos cómo podemos componer múltiples componentes de React juntos. Imagina que estás construyendo una aplicación y has creado tres componentes: un `Navbar`, `Dashboard` y `Footer`.

Para componer estos componentes juntos, se podría crear un componente `App` *parent* que renderiza cada uno de estos tres componentes como *children*. Para renderizar un componente como hijo en un componente React, se incluye el nombre del componente escrito como una etiqueta HTML personalizada en el JSX. Por ejemplo, en el método `render` se puede escribir:

```jsx
return (
 <App>
  <Navbar />
  <Dashboard />
  <Footer />
 </App>
)
```

Cuando React encuentra una etiqueta HTML personalizada que hace referencia a otro componente (un nombre de componente envuelto en `< />` como en este ejemplo), renderiza el marcado de ese componente en la ubicación de la etiqueta. Esto debería ilustrar la relación padre/hijo entre el componente `App` y `Navbar`, `Dashboard`, y `Footer`.

# --instructions--

En el editor de código, hay un componente funcional simple llamado `ChildComponent` y un componente de clase llamado `ParentComponent`. Compón los dos juntos renderizando el `ChildComponent` dentro del `ParentComponent`. Asegúrate de cerrar la etiqueta `ChildComponent` con una barra diagonal.

**Nota:** `ChildComponent` se define con una función de flecha ES6 porque es una práctica muy común al usar React. Sin embargo, has de saber que se trata de una función simple. Si no estás familiarizado con la sintaxis de la función flecha, consulta la sección de JavaScript.

# --hints--

El componente React debe devolver un único elemento `div`.

```js
assert(
  (function () {
    var shallowRender = Enzyme.shallow(React.createElement(ParentComponent));
    return shallowRender.type() === 'div';
  })()
);
```

El componente debe devolver dos elementos anidados.

```js
assert(
  (function () {
    var shallowRender = Enzyme.shallow(React.createElement(ParentComponent));
    return shallowRender.children().length === 2;
  })()
);
```

El componente debe devolver el `ChildComponent` como un segundo hijo.

```js
assert(
  (function () {
    const mockedComponent = Enzyme.mount(React.createElement(ParentComponent));
    return (
      mockedComponent.find('ParentComponent').find('ChildComponent').length ===
      1
    );
  })()
);
```

# --seed--

## --after-user-code--

```jsx
ReactDOM.render(<ParentComponent />, document.getElementById('root'))
```

## --seed-contents--

```jsx
const ChildComponent = () => {
  return (
    <div>
      <p>I am the child</p>
    </div>
  );
};

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>I am the parent</h1>
        { /* Change code below this line */ }

        { /* Change code above this line */ }
      </div>
    );
  }
};
```

# --solutions--

```jsx
const ChildComponent = () => {
  return (
    <div>
      <p>I am the child</p>
    </div>
  );
};

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>I am the parent</h1>
        { /* Change code below this line */ }
        <ChildComponent />
        { /* Change code above this line */ }
      </div>
    );
  }
};
```


text:
function [data] = loadjson_wrapper(filename)
%Loads annotations from the given filename(full path).
%Assumes format as in:
%http://cs.unc.edu/~ammirato/active_vision_dataset_website/get_data.htm
%
%Uses json load function from matlab_file_exchange_helpers/json-lab...
%and adjusts the field names to match the image names
%
%
%INPUT
%       filename - the full path to the json file to load
%
%OUtPUT
%       data - a map from rgb image_name(with .jpg extension) to
%              a struct with the following fields:
%                 bounding_boxes: [Nx6]
%                 rotate_ccw: image_name
%                 rotate_ccw: image_name
%                 forward: image_name
%                 backward: image_name
%                 left: image_name
%                 right: image_name
%

  init;%set path variables and MATLAB search path

  %load the data using the file exchange library
  data_org = loadjson(filename);
  data = containers.Map();

  %get all the fieldnames. For some reason,
  %the jsonload function does something weird but
  %consistent with the image file names.
  fieldnames = fields(data_org);

  %for each fieldname, fix it
  for il=1:length(fieldnames)
    cur_name = fieldnames{il};

    split_name = strsplit(cur_name,'_');
    first_el= split_name{1};
    scene_type = first_el(end);

    image_name = strcat(scene_type,split_name{2},'.jpg');

    data(image_name) = data_org.(cur_name);

  end%for il, each fieldname

end%function


text:
package labassistant

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func fail_compare(co, ca []interface{}) bool {
	// This "comparison" will always fail.
	return true
}

func ignore_all(co, ca []interface{}) bool {
	// This "ignore" will always ignore.
	return true
}

func TestSetControlIsOK(t *testing.T) {
	a := assert.New(t)
	e := NewExperiment("")
	a.Zero(e.Control)
	a.NotPanics(func() {
		e.SetControl(good_func)
	})
	a.NotEmpty(e.Control)

	a.Panics(func() {
		e.SetControl("string")
	})
}

func TestAddCandidateIsOK(t *testing.T) {
	a := assert.New(t)
	e := NewExperiment("")
	a.Empty(e.Candidates)
	a.NotPanics(func() {
		e.AddCandidate(good_func)
	})

	a.Panics(func() {
		e.AddCandidate("string")
	})

	a.NotEmpty(e.Candidates)
	a.NotPanics(func() {
		e.AddCandidate(panic_func)
	})

	a.Equal(2, len(e.Candidates))
	a.NotEqual(e.Candidates[0], e.Candidates[1])
}

func TestRunIsOK(t *testing.T) {
	a := assert.New(t)
	e := NewExperiment("")
	a.Panics(func() {
		e.Run()
	})

	e.SetControl(good_func)
	e.AddCandidate(good_func)
	a.NotPanics(func() {
		e.Run(1)
	})
	a.Equal([]interface{}{1}, e.Inputs)
	a.Equal([]interface{}{1}, e.Control.Outputs)
	a.NotEmpty(e.RunOrder)

	a.Empty(e.Candidates[0].Panic)
	a.False(e.Candidates[0].Mismatch)
	a.Equal(e.Control.Outputs, e.Candidates[0].Outputs)
}

func TestRunWithPanicCandidates(t *testing.T) {
	a := assert.New(t)
	e := NewExperiment("")
	e.SetControl(good_func)
	e.AddCandidate(panic_func)
	a.NotPanics(func() {
		e.Run(1)
	})
	a.NotEmpty(e.Candidates[0].Panic)
	a.True(e.Candidates[0].Mismatch)

}

func TestRunWithBadCandidates(t *testing.T) {
	a := assert.New(t)
	e := NewExperiment("")
	e.SetControl(good_func)
	e.AddCandidate(bad_func)
	a.NotPanics(func() {
		e.Run(1)
	})
	a.Empty(e.Candidates[0].Panic)
	a.True(e.Candidates[0].Mismatch)
	a.NotEqual(e.Control.Outputs, e.Candidates[0].Outputs)

}

func TestRunWithCustomCompare(t *testing.T) {
	a := assert.New(t)
	e := NewExperiment("")
	e.SetControl(good_func)
	e.AddCandidate(good_func)
	e.SetCompare(fail_compare)
	e.Run(1)
	a.Equal([]interface{}{1}, e.Candidates[0].Outputs)
	a.True(e.Candidates[0].Mismatch)
}

func TestRunWithCustomIgnore(t *testing.T) {
	a := assert.New(t)
	e := NewExperiment("")
	e.SetControl(good_func)
	e.AddCandidate(bad_func)
	e.SetIgnore(ignore_all)
	e.Run(1)
	a.Equal([]interface{}{2}, e.Candidates[0].Outputs)
	a.Empty(e.Candidates[0].Panic)
	a.False(e.Candidates[0].Mismatch)
}


text:
using namespace concurrency;
using namespace Microsoft::WRL;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Devices::AllJoyn;
using namespace org::alljoyn::ControlPanel;

std::map<alljoyn_busobject, WeakReference*> PropertyProducer::SourceObjects;
std::map<alljoyn_interfacedescription, WeakReference*> PropertyProducer::SourceInterfaces;

PropertyProducer::PropertyProducer(AllJoynBusAttachment^ busAttachment)
    : m_busAttachment(busAttachment),
    m_sessionListener(nullptr),
    m_busObject(nullptr),
    m_sessionPort(0),
    m_sessionId(0)
{
    m_weak = new WeakReference(this);
    ServiceObjectPath = ref new String(L"/Service");
    m_signals = ref new PropertySignals();
    m_busAttachmentStateChangedToken.Value = 0;
}

PropertyProducer::~PropertyProducer()
{
    UnregisterFromBus();
    delete m_weak;
}

void PropertyProducer::UnregisterFromBus()
{
    if ((nullptr != m_busAttachment) && (0 != m_busAttachmentStateChangedToken.Value))
    {
        m_busAttachment->StateChanged -= m_busAttachmentStateChangedToken;
        m_busAttachmentStateChangedToken.Value = 0;
    }
    if (nullptr != SessionPortListener)
    {
        alljoyn_busattachment_unbindsessionport(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionPort);
        alljoyn_sessionportlistener_destroy(SessionPortListener);
        SessionPortListener = nullptr;
    }
    if (nullptr != BusObject)
    {
        alljoyn_busattachment_unregisterbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
        alljoyn_busobject_destroy(BusObject);
        BusObject = nullptr;
    }
    if (nullptr != SessionListener)
    {
        alljoyn_sessionlistener_destroy(SessionListener);
        SessionListener = nullptr;
    }
}

bool PropertyProducer::OnAcceptSessionJoiner(_In_ alljoyn_sessionport sessionPort, _In_ PCSTR joiner, _In_ const alljoyn_sessionopts opts)
{
    UNREFERENCED_PARAMETER(sessionPort); UNREFERENCED_PARAMETER(joiner); UNREFERENCED_PARAMETER(opts);

    return true;
}

void PropertyProducer::OnSessionJoined(_In_ alljoyn_sessionport sessionPort, _In_ alljoyn_sessionid id, _In_ PCSTR joiner)
{
    UNREFERENCED_PARAMETER(joiner);

    // We initialize the Signals object after the session has been joined, because it needs
    // the session id.
    m_signals->Initialize(BusObject, id);
    m_sessionPort = sessionPort;
    m_sessionId = id;

    alljoyn_sessionlistener_callbacks callbacks =
    {
        AllJoynHelpers::SessionLostHandler<PropertyProducer>,
        AllJoynHelpers::SessionMemberAddedHandler<PropertyProducer>,
        AllJoynHelpers::SessionMemberRemovedHandler<PropertyProducer>
    };

    SessionListener = alljoyn_sessionlistener_create(&callbacks, m_weak);
    alljoyn_busattachment_setsessionlistener(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), id, SessionListener);
}

void PropertyProducer::OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason)
{
    if (sessionId == m_sessionId)
    {
        AllJoynSessionLostEventArgs^ args = ref new AllJoynSessionLostEventArgs(static_cast<AllJoynSessionLostReason>(reason));
        SessionLost(this, args);
    }
}

void PropertyProducer::OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
    if (sessionId == m_sessionId)
    {
        auto args = ref new AllJoynSessionMemberAddedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
        SessionMemberAdded(this, args);
    }
}

void PropertyProducer::OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
    if (sessionId == m_sessionId)
    {
        auto args = ref new AllJoynSessionMemberRemovedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
        SessionMemberRemoved(this, args);
    }
}

void PropertyProducer::BusAttachmentStateChanged(_In_ AllJoynBusAttachment^ sender, _In_ AllJoynBusAttachmentStateChangedEventArgs^ args)
{
    if (args->State == AllJoynBusAttachmentState::Connected)
    {
        QStatus result = AllJoynHelpers::CreateProducerSession<PropertyProducer>(m_busAttachment, m_weak);
        if (ER_OK != result)
        {
            StopInternal(result);
            return;
        }
    }
    else if (args->State == AllJoynBusAttachmentState::Disconnected)
    {
        StopInternal(ER_BUS_STOPPING);
    }
}

void PropertyProducer::CallMetadataChangedSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message)
{
    auto source = SourceInterfaces.find(member->iface);
    if (source == SourceInterfaces.end())
    {
        return;
    }

    auto producer = source->second->Resolve<PropertyProducer>();
    if (producer->Signals != nullptr)
    {
        auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
        auto eventArgs = ref new PropertyMetadataChangedReceivedEventArgs();
        eventArgs->MessageInfo = callInfo;

        producer->Signals->CallMetadataChangedReceived(producer->Signals, eventArgs);
    }
}

void PropertyProducer::CallValueChangedSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message)
{
    auto source = SourceInterfaces.find(member->iface);
    if (source == SourceInterfaces.end())
    {
        return;
    }

    auto producer = source->second->Resolve<PropertyProducer>();
    if (producer->Signals != nullptr)
    {
        auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
        auto eventArgs = ref new PropertyValueChangedReceivedEventArgs();
        eventArgs->MessageInfo = callInfo;

        producer->Signals->CallValueChangedReceived(producer->Signals, eventArgs);
    }
}

QStatus PropertyProducer::AddMethodHandler(_In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_methodhandler_ptr handler)
{
    alljoyn_interfacedescription_member member;
    if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
    {
        return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
    }

    return alljoyn_busobject_addmethodhandler(
        m_busObject,
        member,
        handler,
        m_weak);
}

QStatus PropertyProducer::AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler)
{
    alljoyn_interfacedescription_member member;
    if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
    {
        return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
    }

    return alljoyn_busattachment_registersignalhandler(busAttachment, handler, member, NULL);
}

QStatus PropertyProducer::OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg value)
{
    UNREFERENCED_PARAMETER(interfaceName);

    if (0 == strcmp(propertyName, "Version"))
    {
        auto task = create_task(Service->GetVersionAsync(nullptr));
        auto result = task.get();

        if (AllJoynStatus::Ok != result->Status)
        {
            return static_cast<QStatus>(result->Status);
        }

        return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "q", result->Version));
    }
    if (0 == strcmp(propertyName, "States"))
    {
        auto task = create_task(Service->GetStatesAsync(nullptr));
        auto result = task.get();

        if (AllJoynStatus::Ok != result->Status)
        {
            return static_cast<QStatus>(result->Status);
        }

        return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "u", result->States));
    }
    if (0 == strcmp(propertyName, "OptParams"))
    {
        auto task = create_task(Service->GetOptParamsAsync(nullptr));
        auto result = task.get();

        if (AllJoynStatus::Ok != result->Status)
        {
            return static_cast<QStatus>(result->Status);
        }

        return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "a{qv}", result->OptParams));
    }
    if (0 == strcmp(propertyName, "Value"))
    {
        auto task = create_task(Service->GetValueAsync(nullptr));
        auto result = task.get();

        if (AllJoynStatus::Ok != result->Status)
        {
            return static_cast<QStatus>(result->Status);
        }

        return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "v", result->Value));
    }

    return ER_BUS_NO_SUCH_PROPERTY;
}

QStatus PropertyProducer::OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
{
    UNREFERENCED_PARAMETER(interfaceName);

    if (0 == strcmp(propertyName, "Value"))
    {
        Platform::Object^ argument;
        TypeConversionHelpers::GetAllJoynMessageArg(value, "v", &argument);

        auto task = create_task(Service->SetValueAsync(nullptr, argument));
        return static_cast<QStatus>(task.get());
    }
    return ER_BUS_NO_SUCH_PROPERTY;
}

void PropertyProducer::Start()
{
    if (nullptr == m_busAttachment)
    {
        StopInternal(ER_FAIL);
        return;
    }

    QStatus result = AllJoynHelpers::CreateInterfaces(m_busAttachment, c_PropertyIntrospectionXml);
    if (result != ER_OK)
    {
        StopInternal(result);
        return;
    }

    result = AllJoynHelpers::CreateBusObject<PropertyProducer>(m_weak);
    if (result != ER_OK)
    {
        StopInternal(result);
        return;
    }

    alljoyn_interfacedescription interfaceDescription = alljoyn_busattachment_getinterface(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), "org.alljoyn.ControlPanel.Property");
    if (interfaceDescription == nullptr)
    {
        StopInternal(ER_FAIL);
        return;
    }
    alljoyn_busobject_addinterface_announced(BusObject, interfaceDescription);

    result = AddSignalHandler(
        AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
        interfaceDescription,
        "MetadataChanged",
        [](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallMetadataChangedSignalHandler(member, message); });
    if (result != ER_OK)
    {
        StopInternal(result);
        return;
    }
    result = AddSignalHandler(
        AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
        interfaceDescription,
        "ValueChanged",
        [](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallValueChangedSignalHandler(member, message); });
    if (result != ER_OK)
    {
        StopInternal(result);
        return;
    }

    SourceObjects[m_busObject] = m_weak;
    SourceInterfaces[interfaceDescription] = m_weak;

    result = alljoyn_busattachment_registerbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
    if (result != ER_OK)
    {
        StopInternal(result);
        return;
    }

    m_busAttachmentStateChangedToken = m_busAttachment->StateChanged += ref new TypedEventHandler<AllJoynBusAttachment^,AllJoynBusAttachmentStateChangedEventArgs^>(this, &PropertyProducer::BusAttachmentStateChanged);
    m_busAttachment->Connect();
}

void PropertyProducer::Stop()
{
    StopInternal(AllJoynStatus::Ok);
}

void PropertyProducer::StopInternal(int32 status)
{
    UnregisterFromBus();
    Stopped(this, ref new AllJoynProducerStoppedEventArgs(status));
}

int32 PropertyProducer::RemoveMemberFromSession(_In_ String^ uniqueName)
{
    return alljoyn_busattachment_removesessionmember(
        AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
        m_sessionId,
        AllJoynHelpers::PlatformToMultibyteString(uniqueName).data());
}

PCSTR org::alljoyn::ControlPanel::c_PropertyIntrospectionXml = "<interface name=\"org.alljoyn.ControlPanel.Property\">"
"  <property name=\"Version\" type=\"q\" access=\"read\" />"
"  <property name=\"States\" type=\"u\" access=\"read\" />"
"  <property name=\"OptParams\" type=\"a{qv}\" access=\"read\" />"
"  <property name=\"Value\" type=\"v\" access=\"readwrite\" />"
"  <signal name=\"MetadataChanged\" />"
"  <signal name=\"ValueChanged\" type=\"v\" />"
"</interface>"
;