text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = """
---
module: sros_config
version_added: "2.2"
author: "Peter Sprygada (@privateip)"
short_description: Manage Nokia SR OS device configuration
description:
  - Nokia SR OS configurations use a simple block indent file syntax
    for segmenting configuration into sections.  This module provides
    an implementation for working with SR OS configuration sections in
    a deterministic way.
extends_documentation_fragment: sros
options:
  lines:
    description:
      - The ordered set of commands that should be configured in the
        section.  The commands must be the exact same commands as found
        in the device running-config.  Be sure to note the configuration
        command syntax as some commands are automatically modified by the
        device config parser.  The I(lines) argument only supports current
        context lines.  See EXAMPLES
    required: false
    default: null
    aliases: ['commands']
  parents:
    description:
      - The ordered set of parents that uniquely identify the section
        the commands should be checked against.  If the parents argument
        is omitted, the commands are checked against the set of top
        level or global commands.
    required: false
    default: null
  src:
    description:
      - Specifies the source path to the file that contains the configuration
        or configuration template to load.  The path to the source file can
        either be the full path on the Ansible control host or a relative
        path from the playbook or role root directory.  This argument is mutually
        exclusive with I(lines).
    required: false
    default: null
    version_added: "2.2"
  before:
    description:
      - The ordered set of commands to push on to the command stack if
        a change needs to be made.  This allows the playbook designer
        the opportunity to perform configuration commands prior to pushing
        any changes without affecting how the set of commands are matched
        against the system.
    required: false
    default: null
  after:
    description:
      - The ordered set of commands to append to the end of the command
        stack if a change needs to be made.  Just like with I(before) this
        allows the playbook designer to append a set of commands to be
        executed after the command set.
    required: false
    default: null
  match:
    description:
      - Instructs the module on the way to perform the matching of
        the set of commands against the current device config.  If
        match is set to I(line), commands are matched line by line.  If
        match is set to I(strict), command lines are matched with respect
        to position.  If match is set to I(exact), command lines
        must be an equal match.  Finally, if match is set to I(none), the
        module will not attempt to compare the source configuration with
        the running configuration on the remote device.
    required: false
    default: line
    choices: ['line', 'strict', 'exact', 'none']
  replace:
    description:
      - Instructs the module on the way to perform the configuration
        on the device.  If the replace argument is set to I(line) then
        the modified lines are pushed to the device in configuration
        mode.  If the replace argument is set to I(block) then the entire
        command block is pushed to the device in configuration mode if any
        line is not correct.
    required: false
    default: line
    choices: ['line', 'block']
  force:
    description:
      - The force argument instructs the module to not consider the
        current devices running-config.  When set to true, this will
        cause the module to push the contents of I(src) into the device
        without first checking if already configured.
      - Note this argument should be considered deprecated.  To achieve
        the equivalent, set the C(match=none) which is idempotent.  This argument
        will be removed in a future release.
    required: false
    default: false
    choices: [ "true", "false" ]
    version_added: "2.2"
  backup:
    description:
      - This argument will cause the module to create a full backup of
        the current C(running-config) from the remote device before any
        changes are made.  The backup file is written to the C(backup)
        folder in the playbook root directory.  If the directory does not
        exist, it is created.
    required: false
    default: no
    choices: ['yes', 'no']
    version_added: "2.2"
  config:
    description:
      - The C(config) argument allows the playbook designer to supply
        the base configuration to be used to validate configuration
        changes necessary.  If this argument is provided, the module
        will not download the running-config from the remote node.
    required: false
    default: null
    version_added: "2.2"
  defaults:
    description:
      - This argument specifies whether or not to collect all defaults
        when getting the remote device running config.  When enabled,
        the module will get the current config by issuing the command
        C(show running-config all).
    required: false
    default: no
    choices: ['yes', 'no']
    aliases: ['detail']
    version_added: "2.2"
  save:
    description:
      - The C(save) argument instructs the module to save the running-
        config to the startup-config at the conclusion of the module
        running.  If check mode is specified, this argument is ignored.
    required: false
    default: no
    choices: ['yes', 'no']
    version_added: "2.2"
"""

EXAMPLES = """
# Note: examples below use the following provider dict to handle
#       transport and authentication to the node.
---
vars:
  cli:
    host: "{{ inventory_hostname }}"
    username: admin
    password: admin
    transport: cli

---
- name: enable rollback location
  sros_config:
    lines: configure system rollback rollback-location "cf3:/ansible"
    provider: "{{ cli }}"

- name: set system name to {{ inventory_hostname }} using one line
  sros_config:
    lines:
        - configure system name "{{ inventory_hostname }}"
    provider: "{{ cli }}"

- name: set system name to {{ inventory_hostname }} using parents
  sros_config:
    lines:
        - 'name "{{ inventory_hostname }}"'
    parents:
        - configure
        - system
    provider: "{{ cli }}"
    backup: yes

- name: load config from file
  sros_config:
      src: "{{ inventory_hostname }}.cfg"
      provider: "{{ cli }}"
      save: yes

- name: invalid use of lines
  sros_config:
    lines:
      - service
      -     vpls 1000 customer foo 1 create
      -         description "invalid lines example"
    provider: "{{ cli }}"

- name: valid use of lines
  sros_config:
    lines:
      - description "invalid lines example"
    parents:
      - service
      - vpls 1000 customer foo 1 create
    provider: "{{ cli }}"
"""

RETURN = """
updates:
  description: The set of commands that will be pushed to the remote device
  returned: always
  type: list
  sample: ['config system name "sros01"']
commands:
  description: The set of commands that will be pushed to the remote device
  returned: always
  type: list
  sample: ['config system name "sros01"']
backup_path:
  description: The full path to the backup file
  returned: when backup is yes
  type: string
  sample: /playbooks/ansible/backup/sros_config.2016-07-16@22:28:34
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.netcfg import NetworkConfig, dumps
from ansible.module_utils.sros import sros_argument_spec, check_args
from ansible.module_utils.sros import load_config, run_commands, get_config

def get_active_config(module):
    contents = module.params['config']
    if not contents:
        flags = []
        if module.params['defaults']:
            flags = ['detail']
        return get_config(module, flags)
    return contents

def get_candidate(module):
    candidate = NetworkConfig(indent=4)
    if module.params['src']:
        candidate.load(module.params['src'])
    elif module.params['lines']:
        parents = module.params['parents'] or list()
        candidate.add(module.params['lines'], parents=parents)
    return candidate

def run(module, result):
    match = module.params['match']

    candidate = get_candidate(module)

    if match != 'none':
        config_text = get_active_config(module)
        config = NetworkConfig(indent=4, contents=config_text)
        configobjs = candidate.difference(config)
    else:
        configobjs = candidate.items

    if configobjs:
        commands = dumps(configobjs, 'commands')
        commands = commands.split('\n')

        result['commands'] = commands
        result['updates'] = commands

        # send the configuration commands to the device and merge
        # them with the current running config
        if not module.check_mode:
            load_config(module, commands)
        result['changed'] = True

def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),

        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),

        match=dict(default='line', choices=['line', 'none']),

        config=dict(),
        defaults=dict(type='bool', default=False, aliases=['detail']),

        backup=dict(type='bool', default=False),
        save=dict(type='bool', default=False),
    )

    argument_spec.update(sros_argument_spec)

    mutually_exclusive = [('lines', 'src')]

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    result = dict(changed=False, warnings=list())

    warnings = list()
    check_args(module, warnings)
    if warnings:
        result['warnings'] = warnings

    if module.params['backup']:
        result['__backup__'] = get_config(module)

    run(module, result)

    if module.params['save']:
        if not module.check_mode:
            run_commands(module, ['admin save'])
        result['changed'] = True

    module.exit_json(**result)

if __name__ == '__main__':
    main()


text:
using System.Web.Mvc;
using System.Web.UI;

namespace Ext.Net.MVC.Examples.Areas.MessageBus_Basic.Controllers
{
    public class SimpleController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult PublishEvent()
        {
            MessageBus.Default.Publish("Msg.Server", "It is an event from server side");

            return this.Direct();
        }

        public ActionResult ServerBusEvent(string message)
        {
            this.GetCmp<Panel>("Panel2").Body.CreateChild(new DomObject
            {
                Html = message,
                Tag = HtmlTextWriterTag.P,
                CustomConfig =
                {
                    new ConfigItem("style", "color:green;", ParameterMode.Value)
                }
            });

            return this.Direct();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="apple-touch-icon-precomposed" sizes="57x57" href="/img/apple-touch-icon-57x57.png" />
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/img/apple-touch-icon-114x114.png" />
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/img/apple-touch-icon-72x72.png" />
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/img/apple-touch-icon-144x144.png" />
    <link rel="apple-touch-icon-precomposed" sizes="60x60" href="/img/apple-touch-icon-60x60.png" />
    <link rel="apple-touch-icon-precomposed" sizes="120x120" href="/img/apple-touch-icon-120x120.png" />
    <link rel="apple-touch-icon-precomposed" sizes="76x76" href="/img/apple-touch-icon-76x76.png" />
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="/img/apple-touch-icon-152x152.png" />
    <link rel="icon" type="image/png" href="/img/favicon-196x196.png" sizes="196x196" />
    <link rel="icon" type="image/png" href="/img/favicon-96x96.png" sizes="96x96" />
    <link rel="icon" type="image/png" href="/img/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="/img/favicon-16x16.png" sizes="16x16" />
    <link rel="icon" type="image/png" href="/img/favicon-128.png" sizes="128x128" />
    <meta name="application-name" content=" " />
    <meta name="msapplication-TileColor" content="#FFFFFF" />
    <meta name="msapplication-TileImage" content="/img/mstile-144x144.png" />
    <meta name="msapplication-square70x70logo" content="/img/mstile-70x70.png" />
    <meta name="msapplication-square150x150logo" content="/img/mstile-150x150.png" />
    <meta name="msapplication-wide310x150logo" content="/img/mstile-310x150.png" />
    <meta name="msapplication-square310x310logo" content="/img/mstile-310x310.png" />

    <meta charset="utf-8">
    <title>SGDQ 2017 Stats</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/odometer.js/0.4.8/themes/odometer-theme-minimal.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Live Data Visualizations for GamesDoneQuick Livestreams ">
    <meta name="robots" content="index, follow">
    <meta name="author" content="Benjamin Congdon">
    <link rel="stylesheet" type="text/css" href="css/rechartsLabels.css">

 Summer Games Done Quick2017 Stats

         Made with  by Benjamin Congdon, 2016-


text:
package com.vmware.vim25;
import lombok.Getter;
import lombok.Setter;

public class VirtualResourcePoolSpec extends DynamicData {
    @Getter @Setter public String vrpId;
    @Getter @Setter public String vrpName;
    @Getter @Setter public String description;
    @Getter @Setter public VrpResourceAllocationInfo cpuAllocation;
    @Getter @Setter public VrpResourceAllocationInfo memoryAllocation;
    @Getter @Setter public ManagedObjectReference[] rpList;
    @Getter @Setter public ManagedObjectReference[] hubList;
    @Getter @Setter public Boolean rootVRP;
    @Getter @Setter public Boolean staticVRP;
    @Getter @Setter public Long changeVersion;
}


text:
#ifndef __AGENT_FLOW_TABLE_H__
#define __AGENT_FLOW_TABLE_H__

#include <map>
#if defined(__GNUC__)
#include "base/compiler.h"
#if __GNUC_PREREQ(4, 5)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
#endif
#endif
#include <boost/uuid/random_generator.hpp>
#if defined(__GNUC__)
#if __GNUC_PREREQ(4, 6)
#pragma GCC diagnostic pop
#endif
#endif

#include <boost/uuid/uuid_io.hpp>
#include <boost/intrusive_ptr.hpp>
#include <tbb/atomic.h>
#include <tbb/mutex.h>
#include <base/util.h>
#include <net/address.h>
#include <db/db_table_walker.h>
#include <cmn/agent_cmn.h>
#include <oper/mirror_table.h>
#include <filter/traffic_action.h>
#include <filter/acl_entry.h>
#include <filter/acl.h>
#include <pkt/pkt_types.h>
#include <pkt/pkt_handler.h>
#include <pkt/pkt_init.h>
#include <pkt/pkt_flow_info.h>
#include <pkt/flow_entry.h>
#include <sandesh/sandesh_trace.h>
#include <oper/vn.h>
#include <oper/vm.h>
#include <oper/interface_common.h>
#include <oper/nexthop.h>
#include <oper/route_common.h>
#include <oper/sg.h>
#include <oper/vrf.h>
#include <filter/acl.h>
#include <sandesh/common/flow_types.h>

class FlowStatsCollector;
class PktSandeshFlow;
class FetchFlowRecord;
class FlowEntry;
class FlowTable;
class FlowTableKSyncEntry;
class FlowTableKSyncObject;
class FlowEvent;
class FlowEventKSync;

#define FLOW_LOCK(flow, rflow, flow_event) \
    bool is_flow_rflow_key_same = false; \
    if (flow == rflow) { \
        if (flow_event == FlowEvent::DELETE_FLOW) { \
            assert(0); \
        } \
        is_flow_rflow_key_same = true; \
        rflow = NULL; \
    } \
    tbb::mutex tmp_mutex1, tmp_mutex2, *mutex_ptr_1, *mutex_ptr_2; \
    FlowTable::GetMutexSeq(flow ? flow->mutex() : tmp_mutex1, \
                           rflow ? rflow->mutex() : tmp_mutex2, \
                           &mutex_ptr_1, &mutex_ptr_2); \
    tbb::mutex::scoped_lock lock1(*mutex_ptr_1); \
    tbb::mutex::scoped_lock lock2(*mutex_ptr_2); \
    if (is_flow_rflow_key_same) { \
        flow->MakeShortFlow(FlowEntry::SHORT_SAME_FLOW_RFLOW_KEY); \
    }

/////////////////////////////////////////////////////////////////////////////
// Class to manage free-list of flow-entries
// Flow allocation can happen from multiple threads. In scaled scenarios
// allocation of flow-entries in multi-thread environment adds overheads.
// The FlowEntryFreeList helps to maintain a per task free-list. Alloc/Free
// can happen withou lock.
//
// Alloc and Free happens in a chunk. Alloc/Free are done based on thresholds
// in task context of the corresponding flow-table
/////////////////////////////////////////////////////////////////////////////
class FlowEntryFreeList {
public:
    static const uint32_t kInitCount = (25 * 1000);
    static const uint32_t kTestInitCount = (5 * 1000);
    static const uint32_t kGrowSize = (1 * 1000);
    static const uint32_t kMinThreshold = (4 * 1000);

    typedef boost::intrusive::member_hook<FlowEntry,
            boost::intrusive::list_member_hook<>,
            &FlowEntry::free_list_node_> Node;
    typedef boost::intrusive::list<FlowEntry, Node> FreeList;

    FlowEntryFreeList(FlowTable *table);
    virtual ~FlowEntryFreeList();

    FlowEntry *Allocate(const FlowKey &key);
    void Free(FlowEntry *flow);
    void Grow();
    uint32_t max_count() const { return max_count_; }
    uint32_t free_count() const { return free_list_.size(); }
    uint32_t alloc_count() const { return (max_count_ - free_list_.size()); }
    uint32_t total_alloc() const { return total_alloc_; }
    uint32_t total_free() const { return total_free_; }
private:
    FlowTable *table_;
    uint32_t max_count_;
    bool grow_pending_;
    uint64_t total_alloc_;
    uint64_t total_free_;
    FreeList free_list_;
    uint64_t grow_count_;
    DISALLOW_COPY_AND_ASSIGN(FlowEntryFreeList);
};

/////////////////////////////////////////////////////////////////////////////
// Flow addition is a two step process.
// - FlowHandler :
//   Flow is created in this context (file pkt_flow_info.cc).
//   There can potentially be multiple FlowHandler task running in parallel
// - FlowTable :
//   This module will maintain a tree of all flows created. It is also
//   responsible to generate KSync events. It is run in a single task context
//
//   Functionality of FlowTable:
//   1. Manage flow_entry_map_ which contains all flows
//   2. Enforce the per-VM flow limits
//   3. Generate events to KSync and FlowMgmt modueles
/////////////////////////////////////////////////////////////////////////////
struct FlowTaskMsg : public InterTaskMsg {
    FlowTaskMsg(FlowEntry * fe) : InterTaskMsg(0), fe_ptr(fe) { }
    virtual ~FlowTaskMsg() { }

    FlowEntryPtr fe_ptr;
};

struct Inet4FlowKeyCmp {
    bool operator()(const FlowKey &lhs, const FlowKey &rhs) const {
        const FlowKey &lhs_base = static_cast<const FlowKey &>(lhs);
        return lhs_base.IsLess(rhs);
    }
};

class FlowTable {
public:
    static const uint32_t kPortNatFlowTableInstance = 0;
    static const uint32_t kInvalidFlowTableInstance = 0xFF;

    typedef std::map<FlowKey, FlowEntry *, Inet4FlowKeyCmp> FlowEntryMap;
    typedef std::pair<FlowKey, FlowEntry *> FlowEntryMapPair;
    typedef boost::function<bool(FlowEntry *flow)> FlowEntryCb;
    typedef std::vector<FlowEntryPtr> FlowIndexTree;

    struct LinkLocalFlowInfo {
        uint32_t flow_index;
        FlowKey flow_key;
        uint64_t timestamp;

        LinkLocalFlowInfo(uint32_t index, const FlowKey &key, uint64_t t) :
            flow_index(index), flow_key(key), timestamp(t) {}
    };
    typedef std::map<int, LinkLocalFlowInfo> LinkLocalFlowInfoMap;
    typedef std::pair<int, LinkLocalFlowInfo> LinkLocalFlowInfoPair;

    FlowTable(Agent *agent, uint16_t table_index);
    virtual ~FlowTable();

    void Init();
    void InitDone();
    void Shutdown();

    // Accessor routines
    void set_ksync_object(FlowTableKSyncObject *obj) { ksync_object_ = obj; }
    FlowTableKSyncObject *ksync_object() const { return ksync_object_; }

    // Table managment routines
    FlowEntry *Locate(FlowEntry *flow, uint64_t t);
    FlowEntry *Find(const FlowKey &key);
    void Add(FlowEntry *flow, FlowEntry *rflow);
    void Update(FlowEntry *flow, FlowEntry *rflow);
    //bool Delete(const FlowKey &flow_key);
    bool Delete(const FlowKey &key, bool del_reverse_flow);
    void DeleteAll();
    // Test code only used method
    void DeleteFlow(const AclDBEntry *acl, const FlowKey &key,
                    AclEntryIDList &id_list);

    // Accessor routines
    Agent *agent() const { return agent_; }
    uint16_t table_index() const { return table_index_; }
    size_t Size() { return flow_entry_map_.size(); }
    FlowTable::FlowEntryMap::iterator begin() {
        return flow_entry_map_.begin();
    }
    FlowTable::FlowEntryMap::iterator end() {
        return flow_entry_map_.end();
    }

    const LinkLocalFlowInfoMap &linklocal_flow_info_map() {
        return linklocal_flow_info_map_;
    }
    void AddLinkLocalFlowInfo(int fd, uint32_t index, const FlowKey &key,
                              const uint64_t timestamp);
    void DelLinkLocalFlowInfo(int fd);

    static const char *TaskName() { return kTaskFlowEvent; }
    // Sandesh routines
    void Copy(FlowEntry *lhs, FlowEntry *rhs, bool update);
    void SetAclFlowSandeshData(const AclDBEntry *acl, AclFlowResp &data,
                               const int last_count);
    void SetAceSandeshData(const AclDBEntry *acl, AclFlowCountResp &data,
                           int ace_id);

    void RecomputeFlow(FlowEntry *flow);
    void DeleteMessage(FlowEntry *flow);

    void DeleteVrf(VrfEntry *vrf);

    void HandleRevaluateDBEntry(const DBEntry *entry, FlowEntry *flow,
                                bool active_flow, bool deleted_flow);
    void HandleKSyncError(FlowEntry *flow, FlowTableKSyncEntry *ksync_entry,
                          int ksync_error, uint32_t flow_handle,
                          uint32_t gen_id);
    boost::uuids::uuid rand_gen();

    void UpdateKSync(FlowEntry *flow, bool update);
    void DeleteKSync(FlowEntry *flow);

    // Free list
    void GrowFreeList();
    FlowEntryFreeList *free_list() { return &free_list_; }

    void ProcessKSyncFlowEvent(const FlowEventKSync *req, FlowEntry *flow);
    bool ProcessFlowEvent(const FlowEvent *req, FlowEntry *flow,
                          FlowEntry *rflow);
    void PopulateFlowEntriesUsingKey(const FlowKey &key, bool reverse_flow,
                                     FlowEntry** flow, FlowEntry** rflow);

    // Concurrency check to ensure all flow-table and free-list manipulations
    // are done from FlowEvent task context only
    bool ConcurrencyCheck(int task_id);
    int flow_task_id() const { return flow_task_id_; }
    int flow_update_task_id() const { return flow_update_task_id_; }
    int flow_delete_task_id() const { return flow_delete_task_id_; }
    int flow_ksync_task_id() const { return flow_ksync_task_id_; }
    static void GetMutexSeq(tbb::mutex &mutex1, tbb::mutex &mutex2,
                            tbb::mutex **mutex_ptr_1, tbb::mutex **mutex_ptr_2);
    static void GetFlowSandeshActionParams(const FlowAction &action_info,
                                           std::string &action_str);

    friend class FlowStatsCollector;
    friend class PktSandeshFlow;
    friend class PktSandeshFlowStats;
    friend class FetchFlowRecord;
    friend class PktFlowInfo;
    friend void intrusive_ptr_release(FlowEntry *fe);
private:
    void DisableKSyncSend(FlowEntry *flow, uint32_t evict_gen_id);
    bool IsEvictedFlow(const FlowKey &key);

    void DeleteInternal(FlowEntry *fe, uint64_t t, const RevFlowDepParams &p);
    void DeleteFlowInfo(FlowEntry *fe, const RevFlowDepParams &params);

    void AddFlowInfo(FlowEntry *fe);
    void UpdateReverseFlow(FlowEntry *flow, FlowEntry *rflow);

    void UpdateUnLocked(FlowEntry *flow, FlowEntry *rflow);
    void AddInternal(FlowEntry *flow, FlowEntry *new_flow, FlowEntry *rflow,
                     FlowEntry *new_rflow, bool fwd_flow_update,
                     bool rev_flow_update);
    void Add(FlowEntry *flow, FlowEntry *new_flow, FlowEntry *rflow,
             FlowEntry *new_rflow, bool fwd_flow_update, bool rev_flow_update);
    void EvictFlow(FlowEntry *flow, FlowEntry *rflow, uint32_t evict_gen_id);
    bool DeleteFlows(FlowEntry *flow, FlowEntry *rflow);
    bool DeleteUnLocked(const FlowKey &key, bool del_reverse_flow);
    bool DeleteUnLocked(bool del_reverse_flow, FlowEntry *flow,
                        FlowEntry *rflow);
    void ReleasePort(FlowEntry *flow, bool evict);

    Agent *agent_;
    boost::uuids::random_generator rand_gen_;
    uint16_t table_index_;
    FlowTableKSyncObject *ksync_object_;
    FlowEntryMap flow_entry_map_;

    FlowIndexTree flow_index_tree_;
    // maintain the linklocal flow info against allocated fd, debug purpose only
    LinkLocalFlowInfoMap linklocal_flow_info_map_;
    FlowEntryFreeList free_list_;
    tbb::mutex mutex_;
    int flow_task_id_;
    int flow_update_task_id_;
    int flow_delete_task_id_;
    int flow_ksync_task_id_;
    DISALLOW_COPY_AND_ASSIGN(FlowTable);
};

struct FlowEntryCmp {
    bool operator()(const FlowEntryPtr &l, const FlowEntryPtr &r) {
        FlowEntry *lhs = l.get();
        FlowEntry *rhs = r.get();

        return (lhs < rhs);
    }
};

typedef std::set<FlowEntryPtr, FlowEntryCmp> FlowEntryTree;
extern SandeshTraceBufferPtr FlowTraceBuf;
extern void SetActionStr(const FlowAction &, std::vector<ActionStr> &);

#define FLOW_TRACE(obj, ...)\
do {\
    Flow##obj::TraceMsg(FlowTraceBuf, __FILE__, __LINE__, ##__VA_ARGS__);\
} while(false);\

#endif


text:
package se.emilsjolander.sprinkles.exceptions;

public class AutoIncrementMustBeIntegerException extends RuntimeException {

	public AutoIncrementMustBeIntegerException(String column) {
		super(String.format("The column %s was marked as a @AutoIncrement field but is not a int or a long", column));
	}

}


text:
import Agenda = require("agenda");
// Import injectable and reflect metadata for dependency injection
import { inject, injectable } from "inversify";
import "reflect-metadata";
// Import interfaces for class implementation and dependency injection
import { IPeriodicJob } from "../interfaces/IPeriodicJob";
import { IPIWebAPIService } from "../interfaces/IPIWebAPIService";
import { IYouLess } from "../interfaces/IYouLess";

// Import class definitions
import { EventFrame } from "../apiclients/piwebapi";
// Import node modules
import rp = require("request-promise");

@injectable()
export class HelloYouLess implements IPeriodicJob {

    // Job config
    public config = {
        // Every 2 seconds cron notation
        interval: "*/2 * * * * *",
    };

    // Get instance of PIWebAPIService with dependency injection
    @inject("IPIWebAPIService")
    private service: IPIWebAPIService;

    // Job run function
    public async run(job: Agenda.Job, done: any) {
        try {
            // Get YouLess data (Dutch Energy Monitor)
            const youLessResponse = await rp("http://172.16.70.13/a&f=j");
            // Parse string to data and define data format with interface
            const youLessData: IYouLess = JSON.parse(youLessResponse);
            // Check for watt peak
            const maxWatt: number = 8000;
            const isWattPeak = parseInt(youLessData.pwr, 10) >= maxWatt;

            if (isWattPeak) {
                // Create event frame and persist locally in job
                // (storing in AF will create to much latency for the if check)
                if (!job.attrs.data) {
                    const data = new EventFrame();
                    data.Name = "YouLess Power Peak " + new Date().toDateString();
                    data.StartTime = new Date().toISOString();
                    data.Description = `Youless power is starting to peak above ${maxWatt} with ${youLessData.pwr} Watt`;
                    job.attrs.data = data;
                }
            } else {
                // Close event frame persisted in job and store in AF database;
                if (job.attrs.data) {
                    const data = job.attrs.data as EventFrame;
                    data.EndTime = new Date().toISOString();
                    await this.service.createEventFrameForDatabase("\\\\PIAF01\\YouLess", data);
                    job.attrs.data = null;
                }
            }
            done();
        } catch (error) {
            console.error(error);
            done();
        }
    }
}


text:
'use strict';

const sinon = require('sinon');
const assert = require('assert');

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GCLOUD_PROJECT environment variable. See
// https://googlecloudplatform.github.io/gcloud-node/#/docs/google-cloud/latest/guides/authentication
const {Datastore} = require('@google-cloud/datastore');

function makeStub() {
  return sinon.stub().returns(Promise.resolve([]));
}

// This mock is used in the documentation snippets.
let datastore = {
  delete: makeStub(),
  get: makeStub(),
  insert: makeStub(),
  key: makeStub(),
  update: makeStub(),
  upsert: makeStub(),
  runQuery: sinon.stub().returns(Promise.resolve([[]])),
  save: makeStub(),
};

const namespace = `${Date.now()}`;
class TestHelper {
  constructor(projectId) {
    const options = {
      projectId: projectId,
      namespace,
    };
    this.datastore = new Datastore(options);
  }
}

class Entity extends TestHelper {
  constructor(projectId) {
    super(projectId);
    // To create the keys, we have to use this instance of Datastore.
    datastore.key = this.datastore.key;
    datastore.namespace = this.datastore.namespace;

    this.incompleteKey = this.getIncompleteKey();
    this.namedKey = this.getNamedKey();
    this.keyWithParent = this.getKeyWithParent();
    this.keyWithMultiLevelParent = this.getKeyWithMultiLevelParent();
  }

  getIncompleteKey() {
    // [START datastore_incomplete_key]
    const taskKey = datastore.key('Task');
    // [END datastore_incomplete_key]

    return taskKey;
  }

  getNamedKey() {
    // [START datastore_named_key]
    const taskKey = datastore.key(['Task', 'sampleTask']);
    // [END datastore_named_key]

    return taskKey;
  }

  getKeyWithParent() {
    // [START datastore_key_with_parent]
    const taskKey = datastore.key([
      'TaskList',
      'default',
      'Task',
      'sampleTask',
    ]);
    // [END datastore_key_with_parent]

    return taskKey;
  }

  getKeyWithMultiLevelParent() {
    // [START datastore_key_with_multilevel_parent]
    const taskKey = datastore.key([
      'User',
      'alice',
      'TaskList',
      'default',
      'Task',
      'sampleTask',
    ]);
    // [END datastore_key_with_multilevel_parent]

    return taskKey;
  }

  getTask() {
    // [START datastore_basic_entity]
    const task = {
      category: 'Personal',
      done: false,
      priority: 4,
      description: 'Learn Cloud Datastore',
    };
    // [END datastore_basic_entity]

    return task;
  }

  testIncompleteKey() {
    return this.datastore.save({
      key: this.incompleteKey,
      data: {},
    });
  }

  testNamedKey() {
    return this.datastore.save({
      key: this.namedKey,
      data: {},
    });
  }

  testKeyWithParent() {
    return this.datastore.save({
      key: this.keyWithParent,
      data: {},
    });
  }

  testKeyWithMultiLevelParent() {
    return this.datastore.save({
      key: this.keyWithMultiLevelParent,
      data: {},
    });
  }

  testEntityWithParent() {
    // [START datastore_entity_with_parent]
    const taskKey = datastore.key([
      'TaskList',
      'default',
      'Task',
      'sampleTask',
    ]);

    const task = {
      key: taskKey,
      data: {
        category: 'Personal',
        done: false,
        priority: 4,
        description: 'Learn Cloud Datastore',
      },
    };
    // [END datastore_entity_with_parent]

    return this.datastore.save(task);
  }

  testProperties() {
    // [START datastore_properties]
    const task = [
      {
        name: 'category',
        value: 'Personal',
      },
      {
        name: 'created',
        value: new Date(),
      },
      {
        name: 'done',
        value: false,
      },
      {
        name: 'priority',
        value: 4,
      },
      {
        name: 'percent_complete',
        value: 10.0,
      },
      {
        name: 'description',
        value: 'Learn Cloud Datastore',
        excludeFromIndexes: true,
      },
    ];
    // [END datastore_properties]

    return this.datastore.save({
      key: this.incompleteKey,
      data: task,
    });
  }

  testArrayValue() {
    // [START datastore_array_value]
    const task = {
      tags: ['fun', 'programming'],
      collaborators: ['alice', 'bob'],
    };
    // [END datastore_array_value]

    return this.datastore.save({
      key: this.incompleteKey,
      data: task,
    });
  }

  testBasicEntity() {
    return this.datastore.save({
      key: this.getIncompleteKey(),
      data: this.getTask(),
    });
  }

  async testUpsert() {
    // [START datastore_upsert]
    const taskKey = datastore.key('Task');
    const task = {
      category: 'Personal',
      done: false,
      priority: 4,
      description: 'Learn Cloud Datastore',
    };

    const entity = {
      key: taskKey,
      data: task,
    };

    await datastore.upsert(entity);
    // Task inserted successfully.
    // [END datastore_upsert]

    return this.datastore.upsert({
      key: this.datastore.key(['Task', 1]),
      data: task,
    });
  }

  testInsert() {
    // [START datastore_insert]
    const taskKey = datastore.key('Task');
    const task = {
      category: 'Personal',
      done: false,
      priority: 4,
      description: 'Learn Cloud Datastore',
    };

    const entity = {
      key: taskKey,
      data: task,
    };

    datastore.insert(entity).then(() => {
      // Task inserted successfully.
    });
    // [END datastore_insert]

    return this.datastore.save({
      method: 'insert',
      key: taskKey,
      data: task,
    });
  }

  async testLookup() {
    // [START datastore_lookup]
    const taskKey = datastore.key('Task');
    const [entity] = await datastore.get(taskKey);
    // entity = {
    //   category: 'Personal',
    //   done: false,
    //   priority: 4,
    //   description: 'Learn Cloud Datastore',
    //   [Symbol(KEY)]:
    //    Key {
    //      namespace: undefined,
    //      id: '...',
    //      kind: 'Task',
    //      path: [Getter]
    //    }
    //   }
    // };
    console.log(entity);
    // [END datastore_lookup]
    await this.datastore.save({
      method: 'insert',
      key: taskKey,
      data: {},
    });

    return this.datastore.get(taskKey);
  }

  async testUpdate() {
    // [START datastore_update]
    const taskKey = datastore.key('Task');
    const task = {
      category: 'Personal',
      done: false,
      priority: 4,
      description: 'Learn Cloud Datastore',
    };

    const entity = {
      key: taskKey,
      data: task,
    };

    await datastore.update(entity);
    // Task updated successfully.
    // [END datastore_update]

    await this.datastore.save({
      method: 'insert',
      key: taskKey,
      data: {},
    });
    return this.datastore.update({key: taskKey, data: task});
  }

  async testDelete() {
    // [START datastore_delete]
    const taskKey = datastore.key('Task');
    await datastore.delete(taskKey);
    // Task deleted successfully.
    // [END datastore_delete]
    await this.datastore.save({
      method: 'insert',
      key: taskKey,
      data: {},
    });
    return this.datastore.delete(taskKey);
  }

  async testBatchUpsert() {
    // [START datastore_batch_upsert]
    const taskKey1 = this.datastore.key(['Task', 1]);
    const taskKey2 = this.datastore.key(['Task', 2]);

    const task1 = {
      category: 'Personal',
      done: false,
      priority: 4,
      description: 'Learn Cloud Datastore',
    };

    const task2 = {
      category: 'Work',
      done: false,
      priority: 8,
      description: 'Integrate Cloud Datastore',
    };

    const entities = [
      {
        key: taskKey1,
        data: task1,
      },
      {
        key: taskKey2,
        data: task2,
      },
    ];

    await datastore.upsert(entities);
    // Tasks inserted successfully.
    // [END datastore_batch_upsert]

    return this.datastore.upsert([
      {
        key: taskKey1,
        data: task1,
      },
      {
        key: taskKey2,
        data: task2,
      },
    ]);
  }

  async testBatchLookup() {
    // [START datastore_batch_lookup]
    const taskKey1 = this.datastore.key(['Task', 1]);
    const taskKey2 = this.datastore.key(['Task', 2]);

    const keys = [taskKey1, taskKey2];

    const [tasks] = await datastore.get(keys);
    // Tasks retrieved successfully.
    console.log(tasks);
    // [END datastore_batch_lookup]

    return this.datastore.get([taskKey1, taskKey2]);
  }

  async testBatchDelete() {
    // [START datastore_batch_delete]
    const taskKey1 = this.datastore.key(['Task', 1]);
    const taskKey2 = this.datastore.key(['Task', 2]);

    const keys = [taskKey1, taskKey2];

    await datastore.delete(keys);
    // Tasks deleted successfully.
    // [END datastore_batch_delete]

    return this.datastore.delete([taskKey1, taskKey2]);
  }
}

class Index extends TestHelper {
  testUnindexedPropertyQuery() {
    const datastore = this.datastore;

    // [START datastore_unindexed_property_query]
    const query = datastore
      .createQuery('Task')
      .filter('description', '=', 'A task description.');
    // [END datastore_unindexed_property_query]

    return this.datastore.runQuery(query);
  }

  async testExplodingProperties() {
    const original = datastore.key;
    datastore.key = this.datastore.key;

    // [START datastore_exploding_properties]
    const task = {
      method: 'insert',
      key: datastore.key('Task'),
      data: {
        tags: ['fun', 'programming', 'learn'],
        collaborators: ['alice', 'bob', 'charlie'],
        created: new Date(),
      },
    };
    // [END datastore_exploding_properties]

    datastore.key = original;

    await this.datastore.save(task);
    assert.ok(task.key);
    assert.ok(task.key.id);
  }
}

class Metadata extends TestHelper {
  async testNamespaceRunQuery() {
    const datastore = this.datastore;

    const startNamespace = 'Animals';
    const endNamespace = 'Zoos';

    await datastore.save({
      key: datastore.key({
        namespace: 'Animals',
        path: ['Ant', 1],
      }),
      data: {},
    });

    // [START datastore_namespace_run_query]
    async function runNamespaceQuery(startNamespace, endNamespace) {
      const startKey = datastore.key(['__namespace__', startNamespace]);
      const endKey = datastore.key(['__namespace__', endNamespace]);

      const query = datastore
        .createQuery('__namespace__')
        .select('__key__')
        .filter('__key__', '>=', startKey)
        .filter('__key__', '<', endKey);

      const [entities] = await datastore.runQuery(query);
      const namespaces = entities.map(entity => entity[datastore.KEY].name);

      console.log('Namespaces:');
      namespaces.forEach(namespace => console.log(namespace));

      return namespaces;
    }
    // [END datastore_namespace_run_query]

    const namespaces = await runNamespaceQuery(startNamespace, endNamespace);
    assert.strictEqual(namespaces.includes('Animals'), true);
  }

  async testKindRunQuery() {
    const datastore = this.datastore;

    // [START datastore_kind_run_query]
    async function runKindQuery() {
      const query = datastore.createQuery('__kind__').select('__key__');

      const [entities] = await datastore.runQuery(query);
      const kinds = entities.map(entity => entity[datastore.KEY].name);

      console.log('Kinds:');
      kinds.forEach(kind => console.log(kind));

      return kinds;
    }
    // [END datastore_kind_run_query]
    const kinds = await runKindQuery();
    assert.strictEqual(kinds.includes('Account'), true);
  }

  async testPropertyRunQuery() {
    const datastore = this.datastore;

    // [START datastore_property_run_query]
    async function runPropertyQuery() {
      const query = datastore.createQuery('__property__').select('__key__');
      const [entities] = await datastore.runQuery(query);
      // @TODO convert below object to map
      const propertiesByKind = {};

      entities.forEach(entity => {
        const key = entity[datastore.KEY];
        const kind = key.path[1];
        const property = key.path[3];

        propertiesByKind[kind] = propertiesByKind[kind] || [];
        propertiesByKind[kind].push(property);
      });

      console.log('Properties by Kind:');
      for (const key in propertiesByKind) {
        console.log(key, propertiesByKind[key]);
      }

      return propertiesByKind;
    }
    // [END datastore_property_run_query]
    const propertiesByKind = await runPropertyQuery();
    assert.deepStrictEqual(propertiesByKind.Account, ['balance']);
  }

  async testPropertyByKindRunQuery() {
    const datastore = this.datastore;

    // [START datastore_property_by_kind_run_query]
    async function runPropertyByKindQuery() {
      const ancestorKey = datastore.key(['__kind__', 'Account']);

      const query = datastore
        .createQuery('__property__')
        .hasAncestor(ancestorKey);
      const [entities] = await datastore.runQuery(query);

      const representationsByProperty = {};

      entities.forEach(entity => {
        const key = entity[datastore.KEY];
        const propertyName = key.name;
        const propertyType = entity.property_representation;

        representationsByProperty[propertyName] = propertyType;
      });

      console.log('Task property representations:');
      for (const key in representationsByProperty) {
        console.log(key, representationsByProperty[key]);
      }

      return representationsByProperty;
    }
    // [END datastore_property_by_kind_run_query]

    const propertiesByKind = await runPropertyByKindQuery();
    assert.deepStrictEqual(propertiesByKind, {
      balance: ['INT64'],
    });
  }
}

class Query extends TestHelper {
  constructor(projectId) {
    super(projectId);

    this.basicQuery = this.getBasicQuery();
    this.projectionQuery = this.getProjectionQuery();
    this.ancestorQuery = this.getAncestorQuery();
  }

  getBasicQuery() {
    const datastore = this.datastore;

    // [START datastore_basic_query]
    const query = datastore
      .createQuery('Task')
      .filter('done', '=', false)
      .filter('priority', '>=', 4)
      .order('priority', {
        descending: true,
      });
    // [END datastore_basic_query]

    return query;
  }

  getProjectionQuery() {
    const datastore = this.datastore;

    // [START datastore_projection_query]
    const query = datastore
      .createQuery('Task')
      .select(['priority', 'percent_complete']);
    // [END datastore_projection_query]

    return query;
  }

  getAncestorQuery() {
    const datastore = this.datastore;

    // [START datastore_ancestor_query]
    const ancestorKey = datastore.key(['TaskList', 'default']);

    const query = datastore.createQuery('Task').hasAncestor(ancestorKey);
    // [END datastore_ancestor_query]

    return query;
  }

  async testRunQuery() {
    const query = this.basicQuery;

    // [START datastore_run_query]
    const [tasks] = await datastore.runQuery(query);
    console.log('Tasks:');
    tasks.forEach(task => console.log(task));
    // [END datastore_run_query]

    return this.datastore.runQuery(query);
  }

  testPropertyFilter() {
    const datastore = this.datastore;

    // [START datastore_property_filter]
    const query = datastore.createQuery('Task').filter('done', '=', false);
    // [END datastore_property_filter]

    return this.datastore.runQuery(query);
  }

  testCompositeFilter() {
    const datastore = this.datastore;

    // [START datastore_composite_filter]
    const query = datastore
      .createQuery('Task')
      .filter('done', '=', false)
      .filter('priority', '=', 4);
    // [END datastore_composite_filter]

    return this.datastore.runQuery(query);
  }

  testKeyFilter() {
    const datastore = this.datastore;

    // [START datastore_key_filter]
    const query = datastore
      .createQuery('Task')
      .filter('__key__', '>', datastore.key(['Task', 'someTask']));
    // [END datastore_key_filter]

    return this.datastore.runQuery(query);
  }

  testAscendingSort() {
    const datastore = this.datastore;

    // [START datastore_ascending_sort]
    const query = datastore.createQuery('Task').order('created');
    // [END datastore_ascending_sort]

    return this.datastore.runQuery(query);
  }

  testDescendingSort() {
    const datastore = this.datastore;

    // [START datastore_descending_sort]
    const query = datastore.createQuery('Task').order('created', {
      descending: true,
    });
    // [END datastore_descending_sort]

    return this.datastore.runQuery(query);
  }

  testMultiSort() {
    const datastore = this.datastore;

    // [START datastore_multi_sort]
    const query = datastore
      .createQuery('Task')
      .order('priority', {
        descending: true,
      })
      .order('created');
    // [END datastore_multi_sort]

    return this.datastore.runQuery(query);
  }

  testKindlessQuery() {
    const datastore = this.datastore;
    const lastSeenKey = this.datastore.key(['Task', Date.now()]);

    // [START datastore_kindless_query]
    const query = datastore
      .createQuery()
      .filter('__key__', '>', lastSeenKey)
      .limit(1);
    // [END datastore_kindless_query]

    return this.datastore.runQuery(query);
  }

  async testRunQueryProjection() {
    const datastore = this.datastore;
    const query = this.projectionQuery;

    // [START datastore_run_query_projection]
    async function runProjectionQuery() {
      const priorities = [];
      const percentCompletes = [];
      const [tasks] = await datastore.runQuery(query);
      tasks.forEach(task => {
        priorities.push(task.priority);
        percentCompletes.push(task.percent_complete);
      });

      return {
        priorities: priorities,
        percentCompletes: percentCompletes,
      };
    }
    // [END datastore_run_query_projection]

    return await runProjectionQuery();
  }

  testKeysOnlyQuery() {
    const datastore = this.datastore;

    // [START datastore_keys_only_query]
    const query = datastore.createQuery().select('__key__').limit(1);
    // [END datastore_keys_only_query]

    return this.datastore.runQuery(query);
  }

  testDistinctOnQuery() {
    const datastore = this.datastore;

    // [START datastore_distinct_on_query]
    const query = datastore
      .createQuery('Task')
      .groupBy('category')
      .order('category')
      .order('priority');
    // [END datastore_distinct_on_query]

    return this.datastore.runQuery(query);
  }

  testArrayValueInequalityRange() {
    const datastore = this.datastore;

    // [START datastore_array_value_inequality_range]
    const query = datastore
      .createQuery('Task')
      .filter('tag', '>', 'learn')
      .filter('tag', '<', 'math');
    // [END datastore_array_value_inequality_range]

    return this.datastore.runQuery(query);
  }

  testArrayValueEquality() {
    const datastore = this.datastore;

    // [START datastore_array_value_equality]
    const query = datastore
      .createQuery('Task')
      .filter('tag', '=', 'fun')
      .filter('tag', '=', 'programming');
    // [END datastore_array_value_equality]

    return this.datastore.runQuery(query);
  }

  testInequalityRange() {
    const datastore = this.datastore;

    // [START datastore_inequality_range]
    const query = datastore
      .createQuery('Task')
      .filter('created', '>', new Date('1990-01-01T00:00:00z'))
      .filter('created', '<', new Date('2000-12-31T23:59:59z'));
    // [END datastore_inequality_range]

    return this.datastore.runQuery(query);
  }

  testInequalityInvalid() {
    const datastore = this.datastore;

    // [START datastore_inequality_invalid]
    const query = datastore
      .createQuery('Task')
      .filter('priority', '>', 3)
      .filter('created', '>', new Date('1990-01-01T00:00:00z'));
    // [END datastore_inequality_invalid]

    return this.datastore.runQuery(query);
  }

  testEqualAndInequalityRange() {
    const datastore = this.datastore;

    // [START datastore_equal_and_inequality_range]
    const query = datastore
      .createQuery('Task')
      .filter('priority', '=', 4)
      .filter('done', '=', false)
      .filter('created', '>', new Date('1990-01-01T00:00:00z'))
      .filter('created', '<', new Date('2000-12-31T23:59:59z'));
    // [END datastore_equal_and_inequality_range]

    return this.datastore.runQuery(query);
  }

  testInequalitySort() {
    const datastore = this.datastore;

    // [START datastore_inequality_sort]
    const query = datastore
      .createQuery('Task')
      .filter('priority', '>', 3)
      .order('priority')
      .order('created');
    // [END datastore_inequality_sort]

    return this.datastore.runQuery(query);
  }

  testInequalitySortInvalidNotSame() {
    const datastore = this.datastore;

    // [START datastore_inequality_sort_invalid_not_same]
    const query = datastore
      .createQuery('Task')
      .filter('priority', '>', 3)
      .order('created');
    // [END datastore_inequality_sort_invalid_not_same]

    return this.datastore.runQuery(query);
  }

  testInequalitySortInvalidNotFirst() {
    const datastore = this.datastore;

    // [START datastore_inequality_sort_invalid_not_first]
    const query = datastore
      .createQuery('Task')
      .filter('priority', '>', 3)
      .order('created')
      .order('priority');
    // [END datastore_inequality_sort_invalid_not_first]

    return this.datastore.runQuery(query);
  }

  testLimit() {
    const datastore = this.datastore;

    // [START datastore_limit]
    const query = datastore.createQuery('Task').limit(5);
    // [END datastore_limit]

    return this.datastore.runQuery(query);
  }

  async testCursorPaging() {
    const datastore = this.datastore;
    const pageSize = 1;

    // [START datastore_cursor_paging]
    // By default, google-cloud-node will automatically paginate through all of
    // the results that match a query. However, this sample implements manual
    // pagination using limits and cursor tokens.
    async function runPageQuery(pageCursor) {
      let query = datastore.createQuery('Task').limit(pageSize);

      if (pageCursor) {
        query = query.start(pageCursor);
      }
      const results = await datastore.runQuery(query);
      const entities = results[0];
      const info = results[1];

      if (info.moreResults !== Datastore.NO_MORE_RESULTS) {
        // If there are more results to retrieve, the end cursor is
        // automatically set on `info`. To get this value directly, access
        // the `endCursor` property.
        const results = await runPageQuery(info.endCursor);

        // Concatenate entities
        results[0] = entities.concat(results[0]);
        return results;
      }

      return [entities, info];
    }
    // [END datastore_cursor_paging]
    const [entities, info] = await runPageQuery();
    assert.strictEqual(Array.isArray(entities), true);
    if (!info || !info.endCursor) {
      throw new Error('An `info` with an `endCursor` is not present.');
    }
  }

  async testEventualConsistentQuery() {
    const datastoreMock = datastore;
    datastore = this.datastore;
    // [START datastore_eventual_consistent_query]
    const ancestorKey = datastore.key(['TaskList', 'default']);
    const query = datastore.createQuery('Task').hasAncestor(ancestorKey);

    query.run({consistency: 'eventual'});
    // [END datastore_eventual_consistent_query]
    const [entities] = await query.run({consistency: 'eventual'});
    datastore = datastoreMock;
    return entities;
  }
}

// [START datastore_transactional_update]
async function transferFunds(fromKey, toKey, amount) {
  const transaction = datastore.transaction();
  await transaction.run();
  const results = await Promise.all([
    transaction.get(fromKey),
    transaction.get(toKey),
  ]);
  const accounts = results.map(result => result[0]);

  accounts[0].balance -= amount;
  accounts[1].balance += amount;

  transaction.save([
    {
      key: fromKey,
      data: accounts[0],
    },
    {
      key: toKey,
      data: accounts[1],
    },
  ]);

  return await transaction.commit();
}
// [END datastore_transactional_update]

class Transaction extends TestHelper {
  constructor(projectId) {
    super(projectId);
    this.fromKey = this.datastore.key(['Bank', 1, 'Account', 1]);
    this.toKey = this.datastore.key(['Bank', 1, 'Account', 2]);

    this.originalBalance = 100;
    this.amountToTransfer = 10;
  }

  restoreBankAccountBalances(config) {
    const entities = config.keys.map(key => {
      return {
        key: key,
        data: {
          balance: config.balance,
        },
      };
    });

    return this.datastore.save(entities);
  }

  async testTransactionalUpdate() {
    const fromKey = this.fromKey;
    const toKey = this.toKey;
    const originalBalance = this.originalBalance;
    const amountToTransfer = this.amountToTransfer;
    const datastoreMock = datastore;

    // Overwrite so the real Datastore instance is used in `transferFunds`.
    datastore = this.datastore;
    try {
      await this.restoreBankAccountBalances({
        keys: [fromKey, toKey],
        balance: originalBalance,
      });
      await transferFunds(fromKey, toKey, amountToTransfer);
      const results = await Promise.all([
        this.datastore.get(fromKey),
        this.datastore.get(toKey),
      ]);
      const accounts = results.map(result => result[0]);
      // Restore `datastore` to the mock API.
      datastore = datastoreMock;
      assert.strictEqual(
        accounts[0].balance,
        originalBalance - amountToTransfer
      );
      assert.strictEqual(
        accounts[1].balance,
        originalBalance + amountToTransfer
      );
    } catch (err) {
      datastore = datastoreMock;
      throw err;
    }
  }

  async testTransactionalRetry() {
    // Overwrite so the real Datastore instance is used in `transferFunds`.
    const datastoreMock = datastore;
    datastore = this.datastore;

    const fromKey = this.fromKey;
    const toKey = this.toKey;
    await this.restoreBankAccountBalances({
      keys: [fromKey, toKey],
      balance: this.originalBalance,
    });

    // [START datastore_transactional_retry]
    async function transferFundsWithRetry() {
      const maxTries = 5;

      async function tryRequest(currentAttempt, delay) {
        try {
          await transferFunds(fromKey, toKey, 10);
        } catch (err) {
          if (currentAttempt <= maxTries) {
            // Use exponential backoff
            setTimeout(async () => {
              await tryRequest(currentAttempt + 1, delay * 2);
            }, delay);
          }
          throw err;
        }
      }

      await tryRequest(1, 100);
    }
    // [END datastore_transactional_retry]
    await transferFundsWithRetry();
    // Restore `datastore` to the mock API.
    datastore = datastoreMock;
  }

  async testTransactionalGetOrCreate() {
    const taskKey = this.datastore.key(['Task', Date.now()]);

    // Overwrite so the real Datastore instance is used in `transferFunds`.
    const datastoreMock = datastore;
    datastore = this.datastore;

    // [START datastore_transactional_get_or_create]
    async function getOrCreate(taskKey, taskData) {
      const taskEntity = {
        key: taskKey,
        data: taskData,
      };
      const transaction = datastore.transaction();

      try {
        await transaction.run();
        const [task] = await transaction.get(taskKey);
        if (task) {
          // The task entity already exists.
          await transaction.rollback();
        } else {
          // Create the task entity.
          transaction.save(taskEntity);
          await transaction.commit();
        }
        return taskEntity;
      } catch (err) {
        await transaction.rollback();
      }
    }
    // [END datastore_transactional_get_or_create]
    try {
      let task = await getOrCreate(taskKey, {});
      assert.ok(task, 'Should have a task.');
      task = await getOrCreate(taskKey, {});
      assert.ok(task, 'Should have a task.');
      // Restore `datastore` to the mock API.
      datastore = datastoreMock;
    } catch (err) {
      // Restore `datastore` to the mock API.
      datastore = datastoreMock;
      throw err;
    }
  }

  async testSingleEntityGroupReadOnly() {
    // Overwrite so the real Datastore instance is used in `transferFunds`.
    const datastoreMock = datastore;
    datastore = this.datastore;

    // [START datastore_transactional_single_entity_group_read_only]
    async function getTaskListEntities() {
      const transaction = datastore.transaction({readOnly: true});
      try {
        const taskListKey = datastore.key(['TaskList', 'default']);

        await transaction.run();
        const [taskList] = await transaction.get(taskListKey);
        const query = datastore.createQuery('Task').hasAncestor(taskListKey);
        const [taskListEntities] = await transaction.runQuery(query);
        await transaction.commit();
        return [taskList, taskListEntities];
      } catch (err) {
        await transaction.rollback();
      }
    }
    // [END datastore_transactional_single_entity_group_read_only]

    return getTaskListEntities().then(
      results => {
        // Restore `datastore` to the mock API.
        datastore = datastoreMock;
        assert.strictEqual(results.length, 2);
        assert.strictEqual(Array.isArray(results[1]), true);
      },
      err => {
        // Restore `datastore` to the mock API.
        datastore = datastoreMock;
        return Promise.reject(err);
      }
    );
  }
}

module.exports = {
  Entity: Entity,
  Index: Index,
  Metadata: Metadata,
  Query: Query,
  Transaction: Transaction,
};


text:
package backtype.storm.serialization;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.nio.ByteBuffer;

/**
 * @author Cody (weiyue.wy@alibaba-inc.com)
 * @since 2.1.1
 */
public class KryoByteBufferSerializer extends Serializer<ByteBuffer> {

    @Override
    public void write(Kryo kryo, Output output, ByteBuffer object) {
        output.writeInt(object.array().length);
        output.write(object.array());
    }

    @Override
    public ByteBuffer read(Kryo kryo, Input input, Class<ByteBuffer> type) {
        int len = input.readInt();
        return ByteBuffer.wrap(input.readBytes(len));
    }
}


text:
title:  "Devember Day 18"
author: Gary McAdam
date:   2015-12-19T02:18:00+00:00
template: devember2015.jade
seriesNumber: 18
category: devember2015
---

Quiet evening, *again!*

My issues with the player component come from the destructive nature of VideoJS and the component life-cycle in ReactJS.

I feel I'm close to a solution but I've only been able to commit about an hour tonight after a busy schedule.

## In Other News

![](https://travis-ci.org/gpmcadam/Blog.svg?branch=master)

The blog, however, I spent a few hours on since I wanted to test out a continuous integration system. I went with [Travis](http://travis-ci.org) in the end, and the blog is now publishing to Amazon S3 automatically upon commit! It's something else I've failed to get up to speed on, and I'm glad I was able to during Devember. I intend to put up a more detailed post on Travis towards the end of the month.

I'll also be looking at solutions that integrate with BitBucket, too.

*Tomorrow I'll fix the player. Tomorrow I'll fix the player. Tomorrow I'll fix the player. Tomorrow I'll fix the player. Tomorrow I'll fix the player. Tomorrow I'll fix the player. Tomorrow I'll fix the player. Tomorrow I'll fix the player...*

    ![](future.gif)

## Today's Observations

 - Stats for today: 0 commits, time spent: 1h 04m 10s


text:
<?php

namespace Behat\Behat\Definition\Context\Attribute;

use Behat\Behat\Context\Annotation\DocBlockHelper;
use Behat\Behat\Context\Attribute\AttributeReader;
use Behat\Step\Definition;
use Behat\Step\Given;
use Behat\Step\Then;
use Behat\Step\When;
use ReflectionMethod;

/**
 * Reads definition Attributes from the context class.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
final class DefinitionAttributeReader implements AttributeReader
{
    /**
     * @var string[]
     */
    private static $classes = array(
        Given::class => 'Behat\Behat\Definition\Call\Given',
        When::class  => 'Behat\Behat\Definition\Call\When',
        Then::class  => 'Behat\Behat\Definition\Call\Then',
    );

    /**
     * @var DocBlockHelper
     */
    private $docBlockHelper;

    /**
     * Initializes reader.
     *
     * @param DocBlockHelper $docBlockHelper
     */
    public function __construct(DocBlockHelper $docBlockHelper)
    {
        $this->docBlockHelper = $docBlockHelper;
    }

    /**
     * @{inheritdoc}
     */
    public function readCallees(string $contextClass, ReflectionMethod $method)
    {
        if (\PHP_MAJOR_VERSION < 8) {
            return [];
        }

        /**
         * @psalm-suppress UndefinedClass (ReflectionAttribute is PHP 8.0 only)
         */
        $attributes = $method->getAttributes(Definition::class, \ReflectionAttribute::IS_INSTANCEOF);

        $callees = [];
        foreach ($attributes as $attribute) {
            $class = self::$classes[$attribute->getName()];
            $callable = array($contextClass, $method->getName());
            $description = null;
            if ($docBlock = $method->getDocComment()) {
                $description = $this->docBlockHelper->extractDescription($docBlock);
            }

            $callees[] = new $class($attribute->newInstance()->pattern, $callable, $description);
        }

        return $callees;
    }
}


text:
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

package com.microsoft.windowsazure.management.sql;

import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.sql.models.RecoverableDatabaseGetResponse;
import com.microsoft.windowsazure.management.sql.models.RecoverableDatabaseListResponse;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.concurrent.Future;

/**
* Contains operations for getting Azure SQL Databases that can be recovered.
*/
public interface RecoverableDatabaseOperations {
    /**
    * Returns information about a recoverable Azure SQL Database.
    *
    * @param serverName Required. The name of the Azure SQL Database Server on
    * which the database was hosted.
    * @param databaseName Required. The name of the recoverable Azure SQL
    * Database to be obtained.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @return Contains the response to the Get Recoverable Database request.
    */
    RecoverableDatabaseGetResponse get(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException;

    /**
    * Returns information about a recoverable Azure SQL Database.
    *
    * @param serverName Required. The name of the Azure SQL Database Server on
    * which the database was hosted.
    * @param databaseName Required. The name of the recoverable Azure SQL
    * Database to be obtained.
    * @return Contains the response to the Get Recoverable Database request.
    */
    Future<RecoverableDatabaseGetResponse> getAsync(String serverName, String databaseName);

    /**
    * Returns a collection of databases that can be recovered from a specified
    * server.
    *
    * @param serverName Required. The name of the Azure SQL Database Server on
    * which the databases were hosted.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @return Contains the response to the List Recoverable Databases request.
    */
    RecoverableDatabaseListResponse list(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException;

    /**
    * Returns a collection of databases that can be recovered from a specified
    * server.
    *
    * @param serverName Required. The name of the Azure SQL Database Server on
    * which the databases were hosted.
    * @return Contains the response to the List Recoverable Databases request.
    */
    Future<RecoverableDatabaseListResponse> listAsync(String serverName);
}


text:
package me.littlecheesecake.qrcodescanner.core;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.view.WindowManager;

import java.util.List;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";

    private Camera mCamera;
    private Handler mAutoFocusHandler;
    private boolean mPreviewing = true;
    private boolean mAutoFocus = true;
    private boolean mSurfaceCreated = false;
    private Camera.PreviewCallback mPreviewCallback;

    public CameraPreview(Context context) {
        super(context);
    }

    public CameraPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setCamera(Camera camera, Camera.PreviewCallback previewCallback) {
        mCamera = camera;
        mPreviewCallback = previewCallback;
        mAutoFocusHandler = new Handler();
    }

    public void initCameraPreview() {
        if(mCamera != null) {
            getHolder().addCallback(this);
            getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            if(mPreviewing) {
                requestLayout();
            } else {
                showCameraPreview();
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        mSurfaceCreated = true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
        if(surfaceHolder.getSurface() == null) {
            return;
        }
        stopCameraPreview();
        showCameraPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mSurfaceCreated = false;
        stopCameraPreview();
    }

    public void showCameraPreview() {
        if(mCamera != null) {
            try {
                mPreviewing = true;
                setupCameraParameters();
                mCamera.setPreviewDisplay(getHolder());
                mCamera.setDisplayOrientation(getDisplayOrientation());
                mCamera.setOneShotPreviewCallback(mPreviewCallback);
                mCamera.startPreview();
                if(mAutoFocus) {
                    if (mSurfaceCreated) { // check if surface created before using autofocus
                        safeAutoFocus();
                    } else {
                        scheduleAutoFocus(); // wait 1 sec and then do check again
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.toString(), e);
            }
        }
    }

    public void safeAutoFocus() {
        try {
            mCamera.autoFocus(autoFocusCB);
        } catch (RuntimeException re) {
            // Horrible hack to deal with autofocus errors on Sony devices
            // See https://github.com/dm77/barcodescanner/issues/7 for example
            scheduleAutoFocus(); // wait 1 sec and then do check again
        }
    }

    public void stopCameraPreview() {
        if(mCamera != null) {
            try {
                mPreviewing = false;
                mCamera.cancelAutoFocus();
                mCamera.setOneShotPreviewCallback(null);
                mCamera.stopPreview();
            } catch(Exception e) {
                Log.e(TAG, e.toString(), e);
            }
        }
    }

    public void setupCameraParameters() {
        Camera.Size optimalSize = getOptimalPreviewSize();
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewSize(optimalSize.width, optimalSize.height);
        mCamera.setParameters(parameters);
        adjustViewSize(optimalSize);
    }

    private void adjustViewSize(Camera.Size cameraSize) {
        Point previewSize = convertSizeToLandscapeOrientation(new Point(getWidth(), getHeight()));
        float cameraRatio = ((float) cameraSize.width) / cameraSize.height;
        float screenRatio = ((float) previewSize.x) / previewSize.y;

        if (screenRatio > cameraRatio) {
            setViewSize((int) (previewSize.y * cameraRatio), previewSize.y);
        } else {
            setViewSize(previewSize.x, (int) (previewSize.x / cameraRatio));
        }
    }

    private Point convertSizeToLandscapeOrientation(Point size) {
        if (getDisplayOrientation() % 180 == 0) {
            return size;
        } else {
            return new Point(size.y, size.x);
        }
    }

    private void setViewSize(int width, int height) {
        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        if (getDisplayOrientation() % 180 == 0) {
            layoutParams.width = width;
            layoutParams.height = height;
        } else {
            layoutParams.width = height;
            layoutParams.height = width;
        }
        setLayoutParams(layoutParams);
    }

    public int getDisplayOrientation() {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, info);
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        int rotation = display.getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        return result;
    }

    private Camera.Size getOptimalPreviewSize() {
        if(mCamera == null) {
            return null;
        }

        List<Camera.Size> sizes = mCamera.getParameters().getSupportedPreviewSizes();
        int w = getWidth();
        int h = getHeight();
        if (DisplayUtils.getScreenOrientation(getContext()) == Configuration.ORIENTATION_PORTRAIT) {
            int portraitWidth = h;
            h = w;
            w = portraitWidth;
        }

        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    public void setAutoFocus(boolean state) {
        if(mCamera != null && mPreviewing) {
            if(state == mAutoFocus) {
                return;
            }
            mAutoFocus = state;
            if(mAutoFocus) {
                if (mSurfaceCreated) { // check if surface created before using autofocus
                    Log.v(TAG, "Starting autofocus");
                    safeAutoFocus();
                } else {
                    scheduleAutoFocus(); // wait 1 sec and then do check again
                }
            } else {
                Log.v(TAG, "Cancelling autofocus");
                mCamera.cancelAutoFocus();
            }
        }
    }

    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if(mCamera != null && mPreviewing && mAutoFocus && mSurfaceCreated) {
                safeAutoFocus();
            }
        }
    };

    // Mimic continuous auto-focusing
    Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            scheduleAutoFocus();
        }
    };

    private void scheduleAutoFocus() {
        mAutoFocusHandler.postDelayed(doAutoFocus, 1000);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/xsolla_form_bg">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/xsolla_base_16"
        android:textSize="@dimen/xsolla_textLarge"
        android:textColor="@color/xsolla_text_main"
        android:text="Medium Text"
        android:id="@+id/text1" />

</LinearLayout>


text:
  Si cette option est activée, vous devrez vous connecter avec un nom d'utilisateur
  et un mot de passe qui ont le rôle "admin" pour pouvoir changer la configuration ou
  lancer un nouveau build (utiliser le lien "login" en haut à droite de cette page).
  La configuration des comptes utilisateurs est spécifique au conteneur web que vous
  utilisez. Par exemple, par défaut, Tomcat utilise
  <tt>$TOMCAT_HOME/conf/tomcat-users.xml</tt>).

  Si vous utilisez Hudson sur un intranet (ou d'autres environnements "de confiance"),
  il est souvent préférable de laisser cette case décochée, ce qui permet à chaque
  développeur de configurer son propre projet sans vous déranger.

  Si vous exposez Hudson sur internet, vous devez activer cette option. Hudson lance des
  processes, donc une installation non-sécurisée de Hudson est un bon moyen d'attirer
  les hackers.

  Pour plus d'informations sur la sécurité dans Hudson, voir
  ce document.


text:
package COLASIMPLE;

public interface ICola<T> {
	public void enQueue(T nodo);
	public void deQueue();
	public void clear();
	public boolean isEmpty();
	public boolean isFull();

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Página de inicio</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/thumbnail-gallery.css" rel="stylesheet">


text:
import pysimpledmx

class Spot:
    """
    Control some generic brand 5 channel LED moving head spotlight

    Channels:
    1: Pan (540 degrees)
    2: Tilt (270 degrees)
    3: Dimmer/Strobe
    4: Color Macro
    5: Gobo
    """

    def __init__(self, serial_port, channel):
        self.dmx = pysimpledmx.DMXConnection(serial_port)
        self.channel = channel

    def blackout(self):
        for i in range(5):
            self.dmx.clear(self.channel + i)
        self.dmx.render()

    def pan(self, value, send_now=False):
        self.dmx.setChannel(self.channel, value)
        if send_now:
            self.dmx.render()

    def tilt(self, value, send_now=False):
        self.dmx.setChannel(self.channel + 1, value)
        if send_now:
            self.dmx.render()

    def dimmer(self, value, send_now=False):
        self.dmx.setChannel(self.channel + 2, value)
        if send_now:
            self.dmx.render()

    def color_macro(self, value, send_now=False):
        self.dmx.setChannel(self.channel + 3, value)
        if send_now:
            self.dmx.render()

    def gobo(self, value, send_now=False):
        self.dmx.setChannel(self.channel + 4, value)
        if send_now:
            self.dmx.render()

    def send(self):
        self.dmx.render()

if __name__ == "__main__":
    import time
    import random
    spot = Spot("/dev/ttyUSB0", 1)
    spot.pan(random.randint(0, 255))
    spot.tilt(random.randint(0, 255))
    spot.dimmer(random.randint(0, 255))
    spot.color_macro(random.randint(0, 255))
    spot.gobo(random.randint(0, 255))
    spot.send()
    time.sleep(5)
    spot.blackout()


text:
package com.github.shredder121.gh_event_api.handler.commit_comment;

import com.github.shredder121.gh_event_api.testutil.HmacTest;

@HmacTest
public class HmacCommitCommentHandlerTest extends CommitCommentHandlerTest {
}


text:
require 'spec_helper'

describe DSFU do
  it "is valid" do
    DSFU::Testerino.new.hi
  end
end


text:
all:

install:
	_support/install

compass:
	compass watch

serve:
	jekyll serve --baseurl '' --watch

topic:
	_support/topic

lesson:
	_support/lesson

.PHONY: install compass serve lesson


text:
var mobileRegex = new RegExp(/^\D*0(\D*\d){9}\D*$/);
var emailRegex = new RegExp(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i);
var passwordRegex = new RegExp(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=.\-_*])([a-zA-Z0-9@#$%^&+=*.\-_]){3,}$/);

function validateSubmitForm() {

  var fname = document.submitForm.firstName,
    lname = document.submitForm.lastName,
    email = document.submitForm.email,
    mobile = document.submitForm.mobile,
    password = document.submitForm.password,
    confirmPassword = document.submitForm.confirmPassword;

  if (isEmptyOrUndefined(fname.value)) {
    alert("Please provide your first name!");
    fname.focus();
    return false;
  }

  // if (isEmptyOrUndefined(lname.value)) {
  // 	alert("Please provide your first name!");
  // 	fname.focus();
  // 	return false;
  // }

  if (isEmptyOrUndefined(mobile.value)) {
    alert("Please provide your mobile");
    mobile.focus();
    return false;
  }

  if (isEmptyOrUndefined(password.value)) {
    alert("Please choose a password");
    password.focus();
    return false;
  }

  if (isEmptyOrUndefined(email.value)) {
    alert("Please provide your email");
    email.focus();
    return false;
  }

  if (checkInvalid(mobileRegex, mobile.value)) {
    alert("Please provide a valid mobile number");
    mobile.focus();
    return false;
  }

  if (checkInvalid(passwordRegex, password.value)) {
    alert("Please enter a password with with a number, a lowercase, a uppercase, and a special character");
    password.focus();
    return false;
  }

  // if(password.value!=confirmPassword.value){
  // 	alert("Passwords do not match please try again");
  // 	password.value = "", confirmPassword.value = "";
  // 	password.focus();
  // }
  return true;

}

function isEmptyOrUndefined(value) {
  if (value == "" || value == undefined) {
    return true;
  }
  return false;
}

function checkInvalid(regex, toCheck) {
  alert("here " + toCheck)
  if (!regex.test(toCheck)) {
    return true;
  }
  return false;
}


text:
copy_file(){
    echo "Copying $1 to $2"
    cp $1 $2 -R
}
auto_gen_dir=./src/auto_generated/
# rm -r ${auto_gen_dir}
mkdir -p ${auto_gen_dir}

copy_file ../README.md ${auto_gen_dir}

echo "Done. Please run \`build_data.sh\` as well"
python3 ./copy_default_templates.py > ${auto_gen_dir}/templateData.js
python3 ./copy_readme_template_section.py > ${auto_gen_dir}/README_TEMPLATE_SECTION.md
python3 ./copy_ts_model_definition.py > ${auto_gen_dir}/qualityResultDefinition.js

quality_result_path=./src/auto_generated/qualityResultList.js
json_path=./data_builder/out/all_data.json
echo "creating ${quality_result_path}"
echo "Please run \`build_data.sh\` if you get an error or you would like to update the data."
echo -n "export default " > ${quality_result_path}
cat ${json_path} >> ${quality_result_path}
echo ";" >> ${quality_result_path}
mkdir ./public/api/ -p
cp ${json_path} ./public/api/all.json


text:
<?php

namespace frontend\models\produccion;

use common\models\catalogos\Procesos;
use Yii;
use yii\data\ArrayDataProvider;
use common\models\catalogos\Materiales;
use common\models\catalogos\SubProcesos;

/**
 * This is the model class for table "MaterialesVaciado".
 *
 * @property integer $IdMaterialVaciado
 * @property integer $IdProduccion
 * @property integer $IdMaterial
 * @property double $Cantidad
 *
 * @property Materiales $idMaterial
 * @property Producciones $idProduccion
 */
class MaterialesVaciado extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'MaterialesVaciado';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['IdProduccion', 'IdMaterial', 'Cantidad'], 'required'],
            [['IdProduccion', 'IdMaterial'], 'integer'],
            [['Cantidad'], 'number']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'IdMaterialVaciado' => 'Id Material Vaciado',
            'IdProduccion' => 'Id Produccion',
            'IdMaterial' => 'Id Material',
            'Cantidad' => 'Cantidad',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdMaterial()
    {
        return $this->hasOne(Materiales::className(), ['IdMaterial' => 'IdMaterial'])
            ->with('idSubProceso')
            ->with('idMaterialTipo');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdProduccion()
    {
        return $this->hasOne(Producciones::className(), ['IdProduccion' => 'IdProduccion']);
    }

    public function getDetalle($produccion){
        $result = $this->find()->with('idMaterial')->where("IdProduccion = $produccion")->asArray()->all();

        if(count($result)!=0){
            foreach ($result as &$res) {
                $res['Material'] = $res['idMaterial']['Descripcion'];
            }

            return new ArrayDataProvider([
                'allModels' => $result,
                'id'=>'IdMaterialVaciado',
                'sort'=>array(
                    'attributes'=> $result[0],
                ),
                'pagination'=>false,
            ]);
        }
        return [];
    }
}


text:
SPEC_BEGIN(QueryDataSourceSpec)

        it(@"should should allow the user to select the query to use from Interface Builder", ^{

            QueryDataSource* dataSource = [[QueryDataSource alloc] init];
            [dataSource setValue:[NSNumber numberWithBool:YES] forKey:@"CustomersListMobile"];

            NSString* query = [dataSource query];
            [[query should] equal:@"CustomersListMobile"];
        });

        it(@"should throw an exception if more than one query is set.", ^{

            [[theBlock(^{
                QueryDataSource* dataSource = [[QueryDataSource alloc] init];
                [dataSource setValue:[NSNumber numberWithBool:YES] forKey:@"CustomersListMobile"];
                [dataSource setValue:[NSNumber numberWithBool:YES] forKey:@"AnotherQuery"];
                NSString* query = [dataSource query];
            }) should] raiseWithReason:(NSString*) @"Expected QueryDataSource to have one query, but instead got: (\n"
                    "    AnotherQuery,\n"
                    "    CustomersListMobile\n"
                    ")"];

        });

        SPEC_END


text:
define(['barView'], function(BarView) {
  'use strict';

  describe('barView', function() {
    var barView;
    beforeEach(function() {
      barView = new BarView();
    });
    describe('constructor', function() {
    });
    describe('render', function() {
      beforeEach(function() {
        barView.render();
      } )
      it('returns self', function() {
        expect(barView.render()).to.equal(barView);
      });
    });

  });

});


text:
<?php
/**
 * Created by PhpStorm.
 * User: sjoder
 * Date: 26.05.15
 * Time: 17:44
 */

namespace PM\ScanBundle\Command;

use PM\ScanBundle\Entity\File;
use PM\ScanBundle\Entity\Folder;
use PM\ScanBundle\Entity\Log;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class TranscodeCommand
 *
 * @package PM\ScanBundle\Command
 */
class TranscodeCommand extends ContainerAwareCommand
{
    /**
     * Configuration
     */
    protected function configure()
    {
        $this
            ->setName('pm:scan:transcode')
            ->setDescription('Transcode files')
            ->addOption(
                'continue',
                null,
                InputOption::VALUE_NONE,
                'If set, it will search for new file after transcoding'
            );

    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /**
         * Check disk space
         */
        $dirMedia = $this->getContainer()->getParameter("dir_media");
        $dirMediaFreeSpace = $this->getContainer()->getParameter("dir_media_minimum_free_space");
        if ($dirMediaFreeSpace > disk_free_space($dirMedia)) {
            $output->writeln("<error>Disk space below limit!</error>");

            return;
        }

        $files = $this->getDoctrine()->getRepository("PMScanBundle:File")->findBy(array('transcodeStatus' => File::TRANSCODE_NONE), array("modified" => "asc"), 1);
        if (1 === count($files)) {
            $file = $files[0];

            $output->writeln(sprintf("Checking file <option=bold>%s</option=bold>", $file->getPath()));

            if (false === $file->isKnownExtension()) {
                $output->writeln(" <error>Unknown extension</error>");

                $this->setTranscodeStatus($file, File::TRANSCODE_FAILED);
            } else {
                /**
                 * Check if streams have to be converted
                 */
                $this->setTranscodeStatus($file, File::TRANSCODE_WORKING);

                try {
                    if (true === in_array($file->getFolder()->getType(), Folder::getTypesVideo())) {
                        $this->transcodeVideo($file);
                    } elseif (true === in_array($file->getFolder()->getType(), Folder::getTypesAudio())) {
                        $this->transcodeAudio($file);
                    } else {
                        throw new \LogicException("Unknown Type");
                    }

                    $output->writeln(" <info>Done</info>");

                } catch (\Exception $e) {
                    $this->setTranscodeStatus($file, File::TRANSCODE_FAILED);

                    $output->writeln(sprintf(" <error>Failed</error>: %s", $e->getMessage()));
                }
            }

            /**
             * Check new files
             */
            if (true === $input->getOption('continue')) {
                $this->execute($input, $output);
            }
        } else {
            $output->writeln("<info>Nothing to do...</info>");
        }
    }

    /**
     * Get Codec Status
     *
     * @param File $file
     *
     * @return bool
     * @throws \Exception
     */
    private function transcodeVideo($file)
    {
        $ffmpeg = $this->getContainer()->get("pm_scan.services.transcode_service");
        $ffprobe = $this->getContainer()->get("pm_scan.services.stream_service");

        $streams = $ffprobe->get($file->getPath());

        $videoStreams = $ffprobe->getValid($streams, $ffmpeg->getVideoCodec());
        $audioStreams = $ffprobe->getValid($streams, $ffmpeg->getVideoAudioCodec(), $ffmpeg->getVideoAudioLanguage());

        if (true === $ffmpeg->isValidVideoContainer($file->getExtension()) && 0 < count($videoStreams) && 0 < count($audioStreams)) {
            $this->setTranscodeStatus($file, File::TRANSCODE_IGNORED);
        } else {
            $result = $ffmpeg->transcodeVideo($file->getPath());

            /**
             * Move to Backup
             */
            $fileBackup = File::getPathWithNewExtension($file->getPath(), "backup");
            rename($file->getPath(), $fileBackup);

            $backup = clone $file;
            $backup
                ->setPath($fileBackup)
                ->setName(basename($fileBackup))
                ->setExtension('backup')
                ->setTranscodeStatus(File::TRANSCODE_BACKUP)
                ->setFolder($file->getFolder())
                ->setModified(new \DateTime());

            $file
                ->setPath($result['filePath'])
                ->setName(basename($result['filePath']))
                ->setExtension($ffmpeg->getVideoContainer())
                ->setTranscodeStatus(File::TRANSCODE_DONE);

            /**
             * Log
             */
            $log = new Log();
            $log
                ->setCommand($result['command'])
                ->setFile($file)
                ->setResult($result['output'])
                ->setTime(new \DateTime());

            $this->getDoctrine()->getManager()->persist($backup);
            $this->getDoctrine()->getManager()->persist($file);
            $this->getDoctrine()->getManager()->persist($log);

            $this->getDoctrine()->getManager()->flush();
        }
    }

    /**
     * Get Codec Status
     *
     * @param File $file
     *
     * @return bool
     */
    private function transcodeAudio($file)
    {

    }

    /**
     * Get Doctrine
     *
     * @return \Doctrine\Bundle\DoctrineBundle\Registry
     */
    private function getDoctrine()
    {
        return $this->getContainer()->get("doctrine");
    }

    /**
     * Set Transcode Status
     *
     * @param File $file
     * @param int  $status
     */
    private function setTranscodeStatus($file, $status)
    {
        $file->setTranscodeStatus($status);

        $this->getDoctrine()->getManager()->persist($file);
        $this->getDoctrine()->getManager()->flush();
    }

}


text:
#include "ignite/impl/ignite_impl.h"

using namespace ignite::common::concurrent;
using namespace ignite::jni::java;

namespace ignite
{
    namespace impl
    {
        IgniteImpl::IgniteImpl(SharedPointer<IgniteEnvironment> env, jobject javaRef) :
            env(env),
            javaRef(javaRef)
        {
            IgniteError err;

            txImpl = InternalGetTransactions(err);

            IgniteError::ThrowIfNeeded(err);

            prjImpl = InternalGetProjection(err);

            IgniteError::ThrowIfNeeded(err);
        }

        IgniteImpl::~IgniteImpl()
        {
            JniContext::Release(javaRef);
        }

        const char* IgniteImpl::GetName() const
        {
            return env.Get()->InstanceName();
        }

        const IgniteConfiguration& IgniteImpl::GetConfiguration() const
        {
            return env.Get()->GetConfiguration();
        }

        JniContext* IgniteImpl::GetContext()
        {
            return env.Get()->Context();
        }

        SharedPointer<IgniteBindingImpl> IgniteImpl::GetBinding()
        {
            return env.Get()->GetBinding();
        }

        IgniteImpl::SP_TransactionsImpl IgniteImpl::InternalGetTransactions(IgniteError &err)
        {
            SP_TransactionsImpl res;

            JniErrorInfo jniErr;

            jobject txJavaRef = env.Get()->Context()->ProcessorTransactions(javaRef, &jniErr);

            if (txJavaRef)
                res = SP_TransactionsImpl(new transactions::TransactionsImpl(env, txJavaRef));
            else
                IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

            return res;
        }

        IgniteImpl::SP_ClusterGroupImpl IgniteImpl::InternalGetProjection(IgniteError& err)
        {
            SP_ClusterGroupImpl res;

            JniErrorInfo jniErr;

            jobject txJavaRef = env.Get()->Context()->ProcessorProjection(javaRef, &jniErr);

            if (txJavaRef)
                res = SP_ClusterGroupImpl(new cluster::ClusterGroupImpl(env, txJavaRef));
            else
                IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);

            return res;
        }
    }
}


text:
package com.jfrog.xray.client.impl.services.summary;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfrog.xray.client.impl.XrayImpl;
import com.jfrog.xray.client.impl.util.ObjectMapperHelper;
import com.jfrog.xray.client.services.summary.Components;
import com.jfrog.xray.client.services.summary.Summary;
import com.jfrog.xray.client.services.summary.SummaryResponse;
import org.apache.http.HttpResponse;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by romang on 2/27/17.
 */
public class SummaryImpl implements Summary {

    private final XrayImpl xray;

    public SummaryImpl(XrayImpl xray) {
        this.xray = xray;
    }

    @Override
    public SummaryResponse artifactSummary(List<String> checksums, List<String> paths) throws IOException {
        if (checksums == null && paths == null) {
            return new SummaryResponseImpl();
        }

        ObjectMapper mapper = ObjectMapperHelper.get();
        ArtifactSummaryBody summaryBody = new ArtifactSummaryBody(checksums, paths);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        mapper.writeValue(out, summaryBody);
        ByteArrayInputStream content = new ByteArrayInputStream(out.toByteArray());

        Map<String, String> headers = new HashMap<>();
        XrayImpl.addContentTypeJsonHeader(headers);

        HttpResponse response = xray.post("summary/artifact", headers, content);
        return mapper.readValue(response.getEntity().getContent(), SummaryResponseImpl.class);
    }

    @Override
    public SummaryResponse buildSummary(String buildName, String buildNumber) {
        return null;
    }

    @Override
    public SummaryResponse componentSummary(Components components) throws IOException {
        if (components == null) {
            return new SummaryResponseImpl();
        }

        ObjectMapper mapper = ObjectMapperHelper.get();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        mapper.writeValue(out, components);
        ByteArrayInputStream content = new ByteArrayInputStream(out.toByteArray());

        Map<String, String> headers = new HashMap<>();
        XrayImpl.addContentTypeJsonHeader(headers);

        HttpResponse response = xray.post("summary/component", headers, content);
        return mapper.readValue(response.getEntity().getContent(), SummaryResponseImpl.class);
    }

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private class ArtifactSummaryBody {

        private List<String> checksums = null;
        private List<String> paths = null;

        public ArtifactSummaryBody(List<String> checksums, List<String> paths) {
            this.checksums = checksums;
            this.paths = paths;
        }

        @JsonProperty("checksums")
        public List<String> getChecksums() {
            return checksums;
        }

        @JsonProperty("paths")
        public List<String> getPaths() {
            return paths;
        }
    }

}


text:
require 'rails_helper'

describe Blacksand do
  it '' do
    expect(Blacksand.site_id).to eq 'dark'
    expect(Blacksand.site_name).to eq 'test name'
    expect(Blacksand.carrierwave_storage).to eq :file
  end
end