text:
//
//  XHTextField.h
//  XHTextField
//
//  Created by 曾 宪华 on 13-12-17.
//  Copyright (c) 2013年 曾宪华 开发团队(http://iyilunba.com ) 本人QQ:543413507. All rights reserved.
//

#import <UIKit/UIKit.h>

#define XH_BUNDLE_IMAGE(_file) [[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"XHTextField.bundle"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@.png", _file, ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2) ? @"@2x" : @""]]

@class XHTextField;

@protocol XHTextFieldDelegate <NSObject>

@required
@end

typedef NS_ENUM(NSInteger, XHFieldType) {
    kXHOtherField = 0,
    kXHAvatarField,
    kXHEmailField,
    kXHPasswordField,
    kXHUserNameField,
    kXHDateField,
    kXHGenderField,
    kXHConstellation
};

@interface XHTextField : UITextField

@property (nonatomic) BOOL required; // default is NO
@property (nonatomic, assign) XHFieldType fieldType;
@property (nonatomic, assign) id <XHTextFieldDelegate> textFieldDelegate;

@property (nonatomic, assign) NSInteger maxTextLength; // default is  140

@property (nonatomic, assign) CGPoint rectInsetPoint; // default is (10, 5)
/**
 *  set textFields for nil
 */
- (void)_resetAllTextFields;

/**
 *  check self requred condition
 *
 *  @return pass requred for YES
 */
- (BOOL)validate;

- (XHTextField *)textFieldAtIndex:(int)index;
- (int)numberOfTextFields;

/**
 *  get Constellation with date
 *
 *  @param date Tranform Constellation form date
 *
 *  @return Constellation string
 */
+ (NSString *)getConstellation:(NSDate *)date;

@end


text:
require 'json'
require 'active_record'
require 'sinatra'
require 'sinatra/activerecord'

set :database, "sqlite3:stuff.db"

# Serve static files
set :public_folder, File.dirname(__FILE__) + '/app'

class Topic < ActiveRecord::Base
	has_many :notes

	validates :name, {uniqueness: true, length: {minimum: 1}}
end

class Note < ActiveRecord::Base
	before_validation :init
	belongs_to :topic

	validates :question, length: {minimum: 1}
	validates :answer, length: {minimum: 1}
	validates :topic, presence: true

	def init
		self.needs_learning = true if self.needs_learning.nil?
	end

	def as_hash
		return {
			id: self.id,
			question: self.question,
			answer: self.answer,
			topic: self.topic_id,
			needs_learning: self.needs_learning
		}
	end
end

before do
	response['Access-Control-Allow-Origin'] = '*'
	response['Access-Control-Allow-Headers'] = 'Content-Type'
end

get '/' do
	redirect '/index.html'
end

# TOPICS
options '/topics' do
	%w(GET POST PUT DELETE)
end

get '/topics' do
	topics = Topic.all.includes(:notes)
	data = {topics: []}
	topics.each_with_index do |t, i|
		data[:topics][i] = t.attributes
		data[:topics][i][:notes] = t.notes.pluck(:id)
	end
	return data.to_json
end

post '/topics' do
	data = JSON.parse(request.body.read, symbolize_names: true)
	topic = Topic.new(data[:topic])
	if topic.save
		{topic: topic, notes: topic.notes}.to_json
	else
		error 400
	end
end

get '/topics/:id' do
	topic = Topic.find(params[:id])
	notes = topic.notes.all
	derp = {topic: topic.attributes, notes: []}
	derp[:topic][:notes] = topic.notes.map(&:id)
	notes.each do |n|
		derp[:notes] << n.as_hash
	end
	derp.to_json
end

put '/topics/:id' do
	topic = Topic.find(params[:id])
	data = JSON.parse(request.body.read, symbolize_names: true)
	topic.update(data[:topic])
	if topic.save
		{topic: topic}.to_json
	else
		error 400
	end
end

delete '/topics/:id' do
	Topic.find(params[:id]).destroy
end

# NOTES
options '/notes' do
	%w(GET POST PUT DELETE)
end

get '/notes/:id' do
	debug Note.find(params[:id])
	{notes: Note.find(params[:id])}.to_json
end

post '/notes' do
	note = Note.new
	data = JSON.parse(request.body.read, symbolize_names: true)
	topic = Topic.find(data[:note][:topic])

	note.question = data[:note][:question]
	note.answer = data[:note][:answer]

	topic.notes << note
	if note.save
		{note: note}.to_json
	else
		error 400
	end
end

put '/notes/:id' do
	note = Note.find(params[:id])
	data = JSON.parse(request.body.read, symbolize_names: true)
	data[:topic_id] = data[:note].delete(:topic)
	if note.update(data[:note])
		{note: note}.to_json
	else
		error 400
	end
end

delete '/notes/:id' do
	Note.find(params[:id]).destroy
end

def debug(obj)
	puts '#########'
	puts obj.inspect
	puts '#########'
end

redpajama_set_name: RedPajamaGithub


text: First porject that named wordCount with storm


text:
Change Log
==========

Change Log - v0.2.0 (Front End Alpha release)
-------------------

### ForgeCP Frontend:
##### Views (web/angular/views/):
- [ ] To be added by Marc

##### Angular App JS (web/angular/):
- [ ] To be added by Marc

### ForgeCP Backend API and Models:
##### Frontend to Backend link
- [ ] To be added by Marc

##### Core (web/core.php):
- [x] createSpacer - Working as intended
- [x] moveClients - Implemeted but **not active** (Requires testing)

##### Forge-TSM Install:
- [x] Requires IDE deployment to Heroku due to Config.php setup requirements

Change Log - v0.1.0 (Heroku Support Implemented)
-------------------

### ForgeCP Frontend Views, Widgets, Forms:
##### Core (web/core.php):
- [x] createChannel - Working as intended
- [x] setPerms - Working as intended

### ForgeCP Backend API and Models:
##### API (vendor/Forge-Media/forgetsm-php-framework/TeamSpeak3.php):
- [x] Addded Teamspeak 3 PHP Library to Packagist [forgetsm-php-framework](https://packagist.org/packages/forge-media/forgetsm-php-framework)

##### Forge-TSM Install:
- [x] heroku - Support added for Heroku Deploy using [heroku/heroku-buildpack-multi](https://github.com/heroku/heroku-buildpack-multi)


text:
TOPLEVEL_LANG ?= verilog
PWD=$(shell pwd)
TOPDIR=$(PWD)/..
COCOTB		:= $(shell $(python) nysa paths -c -s)
NYSA			:= $(shell $(python) nysa paths -s -v nysa-verilog)
SDIO_DEV	:= $(shell $(python) nysa paths -s -v sdio-device)
XILINX 		:= $(shell $(python) nysa paths -s -x)
WB_SD_SLV := $(PWD)/../../wb_sdio_device
PYTHONPATH := ./model:$(PYTHONPATH)
export PYTHONPATH
export PYTHONHOME=$(shell python -c "from distutils.sysconfig import get_config_var; print(get_config_var('prefix'))")

EXTRA_ARGS+=-I$(TOPDIR)/rtl/ -I$(NYSA)/verilog/ -DSIMULATION -DCOCOTB_WORKAROUND -I${SDIO_DEV}/rtl/ -I${SDIO_DEV}/rtl/cia -DCOCOTB_SIMULATION

#Dependencies
VERILOG_SOURCES = $(NYSA)/verilog/wishbone/master/wishbone_master.v
#VERILOG_SOURCES += $(NYSA)/verilog/sim/wishbone/interconnect/example_2port_interconnect/wishbone_interconnect.v
VERILOG_SOURCES += ${TOPDIR}/sim/wishbone_interconnect.v

#Simulation Devices

#RAM
VERILOG_SOURCES += ${NYSA}/verilog/generic/bram.v
VERILOG_SOURCES += ${NYSA}/verilog/wishbone/slave/wb_bram/rtl/wb_bram.v

VERILOG_SOURCES += ${TOPDIR}/sim/arbiter_2_masters.v
VERILOG_SOURCES += ${TOPDIR}/sim/wishbone_mem_interconnect.v
VERILOG_SOURCES += ${NYSA}/verilog/wishbone/common/wb_mem_2_ppfifo/rtl/wb_mem_2_ppfifo.v
VERILOG_SOURCES += ${NYSA}/verilog/wishbone/common/wb_ppfifo_2_mem/rtl/wb_ppfifo_2_mem.v
VERILOG_SOURCES += ${NYSA}/verilog/generic/cross_clock_enable.v
VERILOG_SOURCES += ${NYSA}/verilog/generic/cross_clock_strobe.v
VERILOG_SOURCES += ${NYSA}/verilog/generic/blk_mem.v
VERILOG_SOURCES += ${NYSA}/verilog/generic/dpb.v
VERILOG_SOURCES += ${NYSA}/verilog/generic/ppfifo.v
VERILOG_SOURCES += ${TOPDIR}/rtl/generic/sd_crc_16.v
VERILOG_SOURCES += ${TOPDIR}/rtl/generic/sd_crc_7.v

#SDIO Device
VERILOG_SOURCES += ${SDIO_DEV}/rtl/platform/sd_dev_platform_cocotb.v
VERILOG_SOURCES += ${SDIO_DEV}/rtl/sdio_data_control.v
VERILOG_SOURCES += $(SDIO_DEV)/sim/demo_function.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/generic/crc7.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/generic/crc16.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/generic/crc16_2bit.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/cia/sdio_fbr.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/cia/sdio_cccr.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/cia/sdio_cis.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/cia/sdio_cia.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/control/sdio_card_control.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/phy/sdio_phy.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/phy/sdio_data_phy.v
VERILOG_SOURCES += $(SDIO_DEV)/rtl/sdio_device_stack.v

#SDIO Slave
VERILOG_SOURCES += $(WB_SD_SLV)/rtl/sdio_memory_function.v
VERILOG_SOURCES += $(WB_SD_SLV)/rtl/wb_sdio_device.v

#SD Host
VERILOG_SOURCES += ${TOPDIR}/rtl/platform/sd_host_platform_cocotb.v
VERILOG_SOURCES += ${TOPDIR}/rtl/sd_host_defines.v
VERILOG_SOURCES += ${TOPDIR}/rtl/phy/sd_sd4_phy.v
VERILOG_SOURCES += ${TOPDIR}/rtl/phy/sd_phy_layer.v
VERILOG_SOURCES += ${TOPDIR}/rtl/cmd/sd_cmd_layer.v
VERILOG_SOURCES += ${TOPDIR}/rtl/sd_host_stack.v
VERILOG_SOURCES += ${TOPDIR}/rtl/wb_sd_host.v

#DUT
VERILOG_SOURCES += $(TOPDIR)/cocotb/tb_cocotb.v

TOPLEVEL = tb_cocotb

GPI_IMPL := vpi

export TOPLEVEL_LANG
MODULE=test_dut

include $(COCOTB)/makefiles/Makefile.inc
include $(COCOTB)/makefiles/Makefile.sim

.PHONY: wave test
wave:
	gtkwave waveforms.gtkw &


text:
import { combineReducers } from 'redux'

import counter from './counter';
import modal from './modal';

const rootReducer = combineReducers({
    modal,
    counter
})

export default rootReducer


text:
using System.Threading.Tasks;
using FluentValidation;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Autodash.Core
{
    public class UpdateEmailCommand
    {
        private readonly IMongoDatabase _db;
        private readonly ILoggerWrapper _logger;

        public UpdateEmailCommand(IMongoDatabase db, ILoggerProvider loggerProvider)
        {
            _db = db;
            _logger = loggerProvider.GetLogger(GetType().Name);
        }

        public async Task ExecuteAsync(EmailConfiguration config)
        {
            var validator = new UpdateEmailConfigValidator();
            validator.ValidateAndThrow(config);

            var filter = new BsonDocument();//get all
            await _db.GetCollection<EmailConfiguration>("EmailConfiguration")
                .ReplaceOneAsync(filter, config, new UpdateOptions { IsUpsert = true });

            _logger.Info("Email configuration updated. SMTP: {0}. Port: {1}. From: {2}", config.SmtpServer, config.Port, config.FromEmail);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<results title="frequencies">
 <result title="frequency" word="water" count="428"/>
 <result title="frequency" word="porous" count="313"/>
 <result title="frequency" word="filter" count="299"/>
 <result title="frequency" word="membrane" count="222"/>
 <result title="frequency" word="flow" count="207"/>
 <result title="frequency" word="passing" count="142"/>
 <result title="frequency" word="restrictor" count="121"/>
 <result title="frequency" word="irrigation" count="113"/>
 <result title="frequency" word="chamber" count="108"/>
 <result title="frequency" word="infiltration" count="83"/>
 <result title="frequency" word="present" count="81"/>
 <result title="frequency" word="pipe" count="61"/>
 <result title="frequency" word="disposed" count="57"/>
 <result title="frequency" word="figref[FIG." count="56"/>
 <result title="frequency" word="Embodiment" count="51"/>
 <result title="frequency" word="apparatus" count="50"/>
 <result title="frequency" word="restrictors" count="50"/>
 <result title="frequency" word="filtration" count="46"/>
 <result title="frequency" word="illustrated" count="46"/>
 <result title="frequency" word="tubular" count="46"/>
 <result title="frequency" word="restricting" count="43"/>
 <result title="frequency" word="membranes" count="41"/>
 <result title="frequency" word="stream" count="41"/>
 <result title="frequency" word="impurities" count="40"/>
 <result title="frequency" word="surface" count="38"/>
 <result title="frequency" word="section" count="37"/>
 <result title="frequency" word="diameter" count="34"/>
 <result title="frequency" word="invention" count="34"/>
 <result title="frequency" word="outflow" count="34"/>
 <result title="frequency" word="axial" count="33"/>
 <result title="frequency" word="pore" count="33"/>
 <result title="frequency" word="flows" count="32"/>
 <result title="frequency" word="formed" count="29"/>
 <result title="frequency" word="inlet" count="29"/>
 <result title="frequency" word="diagram" count="28"/>
 <result title="frequency" word="opening" count="28"/>
 <result title="frequency" word="seepage" count="28"/>
 <result title="frequency" word="wall" count="28"/>
 <result title="frequency" word="form" count="27"/>
 <result title="frequency" word="smaller" count="27"/>
 <result title="frequency" word="total" count="27"/>
 <result title="frequency" word="document-id::" count="26"/>
 <result title="frequency" word="inner" count="26"/>
 <result title="frequency" word="sidewall" count="26"/>
 <result title="frequency" word="citation:" count="25"/>
 <result title="frequency" word="cited" count="25"/>
 <result title="frequency" word="embodiment," count="25"/>
 <result title="frequency" word="figref[FIGS." count="25"/>
 <result title="frequency" word="corresponding" count="24"/>
 <result title="frequency" word="invention," count="24"/>
 <result title="frequency" word="plastic" count="24"/>
 <result title="frequency" word="outlet" count="23"/>
 <result title="frequency" word="pipe," count="23"/>
 <result title="frequency" word="sheet" count="22"/>
 <result title="frequency" word="[patcit]:" count="21"/>
 <result title="frequency" word="applicant" count="21"/>
 <result title="frequency" word="structural" count="21"/>
 <result title="frequency" word="according" count="20"/>
 <result title="frequency" word="bag" count="20"/>
 <result title="frequency" word="capability" count="20"/>
 <result title="frequency" word="filtered" count="20"/>
 <result title="frequency" word="orifice" count="20"/>
 <result title="frequency" word="direction" count="19"/>
 <result title="frequency" word="larger" count="19"/>
 <result title="frequency" word="plurality" count="19"/>
 <result title="frequency" word="support" count="19"/>
 <result title="frequency" word="claim" count="18"/>
 <result title="frequency" word="closely" count="18"/>
 <result title="frequency" word="having" count="18"/>
 <result title="frequency" word="maximum" count="18"/>
 <result title="frequency" word="method" count="18"/>
 <result title="frequency" word="chamber," count="17"/>
 <result title="frequency" word="edges" count="17"/>
 <result title="frequency" word="embodiment" count="17"/>
 <result title="frequency" word="pores" count="17"/>
 <result title="frequency" word="CLAIM-TEXT:." count="16"/>
 <result title="frequency" word="claim-ref[claim" count="16"/>
 <result title="frequency" word="wash" count="16"/>
 <result title="frequency" word="manufacturing" count="15"/>
 <result title="frequency" word="blockage" count="14"/>
 <result title="frequency" word="invention;" count="14"/>
 <result title="frequency" word="location" count="14"/>
 <result title="frequency" word="blocked" count="13"/>
 <result title="frequency" word="communicated" count="13"/>
 <result title="frequency" word="engaging" count="13"/>
 <result title="frequency" word="outside" count="13"/>
 <result title="frequency" word="membrane," count="12"/>
 <result title="frequency" word="mounted" count="12"/>
 <result title="frequency" word="particle" count="12"/>
 <result title="frequency" word="directly" count="11"/>
 <result title="frequency" word="end" count="11"/>
 <result title="frequency" word="longitudinal" count="11"/>
 <result title="frequency" word="membrane." count="11"/>
 <result title="frequency" word="micro" count="11"/>
 <result title="frequency" word="rate" count="11"/>
 <result title="frequency" word="apparatus," count="10"/>
 <result title="frequency" word="carried" count="10"/>
 <result title="frequency" word="covered" count="10"/>
 <result title="frequency" word="engaged" count="10"/>
 <result title="frequency" word="orifices," count="10"/>
 <result title="frequency" word="valve" count="10"/>
 <result title="frequency" word="chamber;" count="9"/>
 <result title="frequency" word="enclosed" count="9"/>
 <result title="frequency" word="is," count="9"/>
 <result title="frequency" word="molding" count="9"/>
 <result title="frequency" word="number" count="9"/>
 <result title="frequency" word="opening," count="9"/>
 <result title="frequency" word="optional" count="9"/>
 <result title="frequency" word="second" count="9"/>
 <result title="frequency" word="set" count="9"/>
 <result title="frequency" word="Thus," count="8"/>
 <result title="frequency" word="accommodating" count="8"/>
 <result title="frequency" word="apparatus." count="8"/>
 <result title="frequency" word="attached" count="8"/>
 <result title="frequency" word="correspondence" count="8"/>
 <result title="frequency" word="diameters" count="8"/>
 <result title="frequency" word="drawings" count="8"/>
 <result title="frequency" word="engage" count="8"/>
 <result title="frequency" word="following" count="8"/>
 <result title="frequency" word="force" count="8"/>
 <result title="frequency" word="particles" count="8"/>
 <result title="frequency" word="production" count="8"/>
 <result title="frequency" word="schematic" count="8"/>
 <result title="frequency" word="shape," count="8"/>
 <result title="frequency" word="structure" count="8"/>
 <result title="frequency" word=""impact" count="7"/>
 <result title="frequency" word="EMI-D" count="7"/>
 <result title="frequency" word="adhesive" count="7"/>
 <result title="frequency" word="area" count="7"/>
 <result title="frequency" word="covers" count="7"/>
 <result title="frequency" word="demand," count="7"/>
 <result title="frequency" word="different" count="7"/>
 <result title="frequency" word="embodiments" count="7"/>
 <result title="frequency" word="enters" count="7"/>
 <result title="frequency" word="i.e.," count="7"/>
 <result title="frequency" word="inside" count="7"/>
 <result title="frequency" word="invention." count="7"/>
 <result title="frequency" word="large" count="7"/>
 <result title="frequency" word="manner" count="7"/>
 <result title="frequency" word="penetrating" count="7"/>
 <result title="frequency" word="prior" count="7"/>
 <result title="frequency" word="restrictor," count="7"/>
 <result title="frequency" word="speed"" count="7"/>
 <result title="frequency" word="thereof" count="7"/>
 <result title="frequency" word="using" count="7"/>
 <result title="frequency" word="various" count="7"/>
 <result title="frequency" word="washed" count="7"/>
 <result title="frequency" word="bag-shaped" count="6"/>
 <result title="frequency" word="chamber." count="6"/>
 <result title="frequency" word="constituted" count="6"/>
 <result title="frequency" word="dispose" count="6"/>
 <result title="frequency" word="easily" count="6"/>
 <result title="frequency" word="engages" count="6"/>
 <result title="frequency" word="entire" count="6"/>
 <result title="frequency" word="equal" count="6"/>
 <result title="frequency" word="firstly" count="6"/>
 <result title="frequency" word="flat" count="6"/>
 <result title="frequency" word="greater" count="6"/>
 <result title="frequency" word="integrally" count="6"/>
 <result title="frequency" word="just" count="6"/>
 <result title="frequency" word="main" count="6"/>
 <result title="frequency" word="material" count="6"/>
 <result title="frequency" word="membranes;" count="6"/>
 <result title="frequency" word="mouth" count="6"/>
 <result title="frequency" word="one," count="6"/>
 <result title="frequency" word="passage" count="6"/>
 <result title="frequency" word="penetration" count="6"/>
 <result title="frequency" word="piston" count="6"/>
 <result title="frequency" word="pressure" count="6"/>
 <result title="frequency" word="provided" count="6"/>
 <result title="frequency" word="provides" count="6"/>
 <result title="frequency" word="pump" count="6"/>
 <result title="frequency" word="service" count="6"/>
 <result title="frequency" word="similar" count="6"/>
 <result title="frequency" word="support," count="6"/>
 <result title="frequency" word="thereby." count="6"/>
 <result title="frequency" word="thereof," count="6"/>
 <result title="frequency" word="thereof." count="6"/>
 <result title="frequency" word="times" count="6"/>
 <result title="frequency" word="water." count="6"/>
 <result title="frequency" word="No." count="5"/>
 <result title="frequency" word="addition," count="5"/>
 <result title="frequency" word="away" count="5"/>
 <result title="frequency" word="circumference" count="5"/>
 <result title="frequency" word="classification-national::" count="5"/>
 <result title="frequency" word="clear" count="5"/>
 <result title="frequency" word="correspondingly" count="5"/>
 <result title="frequency" word="descriptions" count="5"/>
 <result title="frequency" word="easy" count="5"/>
 <result title="frequency" word="effect" count="5"/>
 <result title="frequency" word="effectively" count="5"/>
 <result title="frequency" word="example," count="5"/>
 <result title="frequency" word="far" count="5"/>
 <result title="frequency" word="flowing" count="5"/>
 <result title="frequency" word="greatly" count="5"/>
 <result title="frequency" word="impurity" count="5"/>
 <result title="frequency" word="inserted" count="5"/>
 <result title="frequency" word="life" count="5"/>
 <result title="frequency" word="limited." count="5"/>
 <result title="frequency" word="locations." count="5"/>
 <result title="frequency" word="manners." count="5"/>
 <result title="frequency" word="membranes," count="5"/>
 <result title="frequency" word="membranes." count="5"/>
 <result title="frequency" word="mounting" count="5"/>
 <result title="frequency" word="omitted." count="5"/>
 <result title="frequency" word="pipe." count="5"/>
 <result title="frequency" word="preferably" count="5"/>
 <result title="frequency" word="process" count="5"/>
 <result title="frequency" word="pump," count="5"/>
 <result title="frequency" word="slightly" count="5"/>
 <result title="frequency" word="speed" count="5"/>
 <result title="frequency" word="substantially" count="5"/>
 <result title="frequency" word="(by" count="4"/>
 <result title="frequency" word="Application" count="4"/>
 <result title="frequency" word="Brownian" count="4"/>
 <result title="frequency" word="CLAIM-TEXT:one" count="4"/>
 <result title="frequency" word="Therefore," count="4"/>
 <result title="frequency" word="[nplcit]:" count="4"/>
 <result title="frequency" word="action-date:" count="4"/>
 <result title="frequency" word="addition" count="4"/>
 <result title="frequency" word="block" count="4"/>
 <result title="frequency" word="blocked." count="4"/>
 <result title="frequency" word="certain" count="4"/>
 <result title="frequency" word="complete" count="4"/>
 <result title="frequency" word="composed" count="4"/>
 <result title="frequency" word="connected" count="4"/>
 <result title="frequency" word="continuous" count="4"/>
 <result title="frequency" word="device" count="4"/>
 <result title="frequency" word="diagrams" count="4"/>
 <result title="frequency" word="difficult" count="4"/>
 <result title="frequency" word="discharged" count="4"/>
 <result title="frequency" word="disposing" count="4"/>
 <result title="frequency" word="examiner" count="4"/>
 <result title="frequency" word="exists" count="4"/>
 <result title="frequency" word="flush" count="4"/>
 <result title="frequency" word="generating-office::" count="4"/>
 <result title="frequency" word="gluing)" count="4"/>
 <result title="frequency" word="hot" count="4"/>
 <result title="frequency" word="illustrate" count="4"/>
 <result title="frequency" word="impact" count="4"/>
 <result title="frequency" word="implemented" count="4"/>
 <result title="frequency" word="improves" count="4"/>
 <result title="frequency" word="located" count="4"/>
 <result title="frequency" word="machine" count="4"/>
 <result title="frequency" word="make" count="4"/>
 <result title="frequency" word="making" count="4"/>
 <result title="frequency" word="manufactured" count="4"/>
 <result title="frequency" word="melting" count="4"/>
 <result title="frequency" word="method," count="4"/>
 <result title="frequency" word="narrow" count="4"/>
 <result title="frequency" word="needs" count="4"/>
 <result title="frequency" word="orifice." count="4"/>
 <result title="frequency" word="orifices" count="4"/>
 <result title="frequency" word="orifices." count="4"/>
 <result title="frequency" word="passes" count="4"/>
 <result title="frequency" word="plants" count="4"/>
 <result title="frequency" word="pores," count="4"/>
 <result title="frequency" word="problem" count="4"/>
 <result title="frequency" word="providing" count="4"/>
 <result title="frequency" word="pumped" count="4"/>
 <result title="frequency" word="reduces" count="4"/>
 <result title="frequency" word="shall" count="4"/>
 <result title="frequency" word="shape." count="4"/>
 <result title="frequency" word="sinks" count="4"/>
 <result title="frequency" word="sufficiently" count="4"/>
 <result title="frequency" word="surface," count="4"/>
 <result title="frequency" word="time," count="4"/>
</results>


text:
package org.onosproject.lisp.msg.types;

import com.google.common.testing.EqualsTester;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onosproject.lisp.msg.exceptions.LispParseError;
import org.onosproject.lisp.msg.exceptions.LispWriterException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.onosproject.lisp.msg.types.LispIpv6Address.Ipv6AddressReader;
import static org.onosproject.lisp.msg.types.LispIpv6Address.Ipv6AddressWriter;

/**
 * Unit tests for LispIpv6Address class.
 */
public class LispIpv6AddressTest {

    private LispIpv6Address address1;
    private LispIpv6Address sameAsAddress1;
    private LispIpv6Address address2;

    @Before
    public void setup() {

        address1 = new LispIpv6Address(IpAddress.valueOf("1111:2222:3333:4444:5555:6666:7777:8885"));
        sameAsAddress1 = new LispIpv6Address(IpAddress.valueOf("1111:2222:3333:4444:5555:6666:7777:8885"));
        address2 = new LispIpv6Address(IpAddress.valueOf("1111:2222:3333:4444:5555:6666:7777:8886"));
    }

    @Test
    public void testEquality() {
        new EqualsTester()
                .addEqualityGroup(address1, sameAsAddress1)
                .addEqualityGroup(address2).testEquals();
    }

    @Test
    public void testConstruction() {
        LispIpv6Address ipv6Address = address1;
        assertThat(ipv6Address.getAddress(), is(IpAddress.valueOf("1111:2222:3333:4444:5555:6666:7777:8885")));
    }

    @Test
    public void testSerialization() throws LispWriterException, LispParseError {
        ByteBuf byteBuf = Unpooled.buffer();

        Ipv6AddressWriter writer = new Ipv6AddressWriter();
        writer.writeTo(byteBuf, address1);

        Ipv6AddressReader reader = new Ipv6AddressReader();
        LispIpv6Address deserialized = reader.readFrom(byteBuf);

        new EqualsTester()
                .addEqualityGroup(address1, deserialized).testEquals();
    }
}


text:
/// <reference path="./lib/skillMap.d.ts" />

import React from 'react';
import { connect } from 'react-redux';

import store from "./store/store";
import * as authClient from "./lib/authClient";
import { getCompletedBadges, getFlattenedHeaderIds, hasUrlBeenStarted, isRewardNode } from "./lib/skillMapUtils";

import {
    dispatchAddSkillMap,
    dispatchChangeSelectedItem,
    dispatchClearSkillMaps,
    dispatchClearMetadata,
    dispatchSetPageTitle,
    dispatchSetPageDescription,
    dispatchSetPageInfoUrl,
    dispatchSetUser,
    dispatchSetPageSourceUrl,
    dispatchSetPageAlternateUrls,
    dispatchSetPageBackgroundImageUrl,
    dispatchSetPageBannerImageUrl,
    dispatchSetPageTheme,
    dispatchSetUserPreferences
} from './actions/dispatch';
import { PageSourceStatus, SkillMapState } from './store/reducer';
import { HeaderBar } from './components/HeaderBar';
import { AppModal } from './components/AppModal';
import { SkillGraphContainer } from './components/SkillGraphContainer';
import { InfoPanel } from './components/InfoPanel';

import { parseSkillMap } from './lib/skillMapParser';
import { parseHash, getMarkdownAsync, MarkdownSource, parseQuery,
    setPageTitle, setPageSourceUrl, ParsedHash, resolvePath } from './lib/browserUtils';

import { MakeCodeFrame } from './components/makecodeFrame';
import { getLocalUserStateAsync, getUserStateAsync, saveUserStateAsync } from './lib/workspaceProvider';
import { Unsubscribe } from 'redux';
import { UserProfile } from './components/UserProfile';
import { ReadyResources, ReadyPromise } from './lib/readyResources';

/* eslint-disable import/no-unassigned-import */
import './App.css';

// TODO: this file needs to read colors from the target
import './arcade.css';

/* eslint-enable import/no-unassigned-import */
interface AppProps {
    skillMaps: { [key: string]: SkillMap };
    activityOpen: boolean;
    backgroundImageUrl: string;
    theme: SkillGraphTheme;
    signedIn: boolean;
    activityId: string;
    highContrast?: boolean;
    dispatchAddSkillMap: (map: SkillMap) => void;
    dispatchChangeSelectedItem: (mapId?: string, activityId?: string) => void;
    dispatchClearSkillMaps: () => void;
    dispatchClearMetadata: () => void;
    dispatchSetPageTitle: (title: string) => void;
    dispatchSetPageDescription: (description: string) => void;
    dispatchSetPageInfoUrl: (infoUrl: string) => void;
    dispatchSetPageBackgroundImageUrl: (backgroundImageUrl: string) => void;
    dispatchSetPageBannerImageUrl: (bannerImageUrl: string) => void;
    dispatchSetUser: (user: UserState) => void;
    dispatchSetPageSourceUrl: (url: string, status: PageSourceStatus) => void;
    dispatchSetPageAlternateUrls: (urls: string[]) => void;
    dispatchSetPageTheme: (theme: SkillGraphTheme) => void;
    dispatchSetUserPreferences: (prefs: pxt.auth.UserPreferences) => void;
}

interface AppState {
    error?: string;
    cloudSyncCheckHasFinished: boolean;
    badgeSyncLock: boolean;
    showingSyncLoader?: boolean;
}

class AppImpl extends React.Component<AppProps, AppState> {
    protected queryFlags: {[index: string]: string} = {};
    protected unsubscribeChangeListener: Unsubscribe | undefined;
    protected loadedUser: UserState | undefined;
    protected readyPromise: ReadyPromise;

    constructor(props: any) {
        super(props);
        this.state = {
            cloudSyncCheckHasFinished: false,
            badgeSyncLock: false
        };
        this.readyPromise = new ReadyPromise();

        window.addEventListener("hashchange", this.handleHashChange);
        this.cloudSyncCheckAsync();
    }

    protected ready = (): Promise<ReadyResources> => this.readyPromise.promise();

    protected handleHashChange = async (e: HashChangeEvent) => {
        await this.parseHashAsync();
        e.stopPropagation();
        e.preventDefault();
    }

    protected async parseHashAsync() {
        let config = await pxt.targetConfigAsync();
        let hash: ParsedHash;

        const possibleAlias = window.location.hash.replace("#", "");

        if (possibleAlias && config.skillMap?.pathAliases?.[possibleAlias]) {
            hash = parseHash(config.skillMap.pathAliases[possibleAlias]);
        }
        else {
            hash = parseHash(window.location.hash || config.skillMap?.defaultPath);
        }

        await this.fetchAndParseSkillMaps(hash.cmd as MarkdownSource, hash.arg);
    }

    protected handleError = (msg?: string) => {
        const errorMsg = msg || lf("Oops! Couldn't load content, please check the URL and markdown file.");
        console.error(errorMsg);
        this.setState({ error: errorMsg });
    }

    protected async initLocalizationAsync() {
        const theme = pxt.appTarget.appTheme;

        const href = window.location.href;
        let force = false;
        let useLang: string | undefined = undefined;
        if (/[&?]translate=1/.test(href) && !pxt.BrowserUtils.isIE()) {
            useLang = ts.pxtc.Util.TRANSLATION_LOCALE;
        } else {
            const mlang = /(live)?(force)?lang=([a-z]{2,}(-[A-Z]+)?)/i.exec(window.location.href);
            if (mlang && window.location.hash.indexOf(mlang[0]) >= 0) {
                pxt.BrowserUtils.changeHash(window.location.hash.replace(mlang[0], ""));
            }
            useLang = mlang ? mlang[3] : (pxt.BrowserUtils.getCookieLang() || theme.defaultLocale || (navigator as any).userLanguage || navigator.language);
            force = !!mlang && !!mlang[2];
        }

        const defLocale = pxt.appTarget.appTheme.defaultLocale;
        if (!force && !pxt.Util.isLocaleEnabled(useLang!)) {
            useLang = defLocale;
        }

        // TODO: include the pxt webconfig so that we can get the commitcdnurl (and not always pass live=true)
        const baseUrl = "";
        const targetId = pxt.appTarget.id;
        const pxtBranch = pxt.appTarget.versions.pxtCrowdinBranch;
        const targetBranch = pxt.appTarget.versions.targetCrowdinBranch;

        const langLowerCase = useLang?.toLocaleLowerCase();
        const localDevServe = pxt.BrowserUtils.isLocalHostDev()
            && (!langLowerCase || (defLocale
                ? defLocale.toLocaleLowerCase() === langLowerCase
                : "en" === langLowerCase || "en-us" === langLowerCase));
        const serveLocal = pxt.BrowserUtils.isPxtElectron() || localDevServe;
        if (!serveLocal) {
            pxt.Util.enableLiveLocalizationUpdates();
        }

        await updateLocalizationAsync({
            targetId: targetId,
            baseUrl: baseUrl,
            code: useLang!,
            pxtBranch: pxtBranch!,
            targetBranch: targetBranch!,
            force: force,
        });

        if (pxt.Util.isLocaleEnabled(useLang!)) {
            pxt.BrowserUtils.setCookieLang(useLang!);
            pxt.Util.setUserLanguage(useLang!);
        }
    }

    protected async fetchAndParseSkillMaps(source: MarkdownSource, url: string) {
        const result = await getMarkdownAsync(source, url);

        const md = result?.text;
        const fetched = result?.identifier;
        const status = result?.status;

        let loadedMaps: SkillMap[] | undefined;

        if (md && fetched && status) {
            try {
                if (status === "banned") {
                    this.handleError(lf("This GitHub repository has been banned."));
                } else {
                    setPageSourceUrl(fetched);
                    this.props.dispatchSetPageSourceUrl(fetched, status);
                    this.props.dispatchClearMetadata();
                }

                const { maps, metadata } = parseSkillMap(md);
                if (maps?.length > 0) {
                    loadedMaps = maps;
                    this.props.dispatchClearSkillMaps();
                    maps.forEach(map => {
                        this.props.dispatchAddSkillMap(map);
                    })
                }

                if (metadata) {
                    const { title, description, infoUrl, backgroundImageUrl,
                        bannerImageUrl, theme, alternateSources } = metadata;
                    setPageTitle(title);
                    this.props.dispatchSetPageTitle(title);
                    if (description) this.props.dispatchSetPageDescription(description);
                    if (infoUrl) this.props.dispatchSetPageInfoUrl(infoUrl);
                    if (backgroundImageUrl) this.props.dispatchSetPageBackgroundImageUrl(backgroundImageUrl);
                    if (bannerImageUrl) this.props.dispatchSetPageBannerImageUrl(bannerImageUrl);
                    if (alternateSources) this.props.dispatchSetPageAlternateUrls(alternateSources);
                    if (theme) this.props.dispatchSetPageTheme(theme);
                }

                this.setState({ error: undefined });
            } catch (err) {
                this.handleError(err);
            }
        } else {
            this.setState({ error: lf("No content loaded.") })
        }

        let user = await getUserStateAsync();

        if (fetched && !user.completedTags[fetched]) {
            user.completedTags[fetched] = {};
        }

        this.applyQueryFlags(user, loadedMaps, fetched);
        this.loadedUser = user;
        this.props.dispatchSetUser(user);

        const prefs = await authClient.userPreferencesAsync();
        if (prefs) this.props.dispatchSetUserPreferences(prefs);
    }

    protected async cloudSyncCheckAsync() {
        const res = await this.ready();
        if (!await authClient.loggedInAsync()) {
            this.setState({cloudSyncCheckHasFinished: true});
        } else {
            const doCloudSyncCheckAsync = async () => {
                const state = store.getState();
                const localUser = await getLocalUserStateAsync();

                let currentUser = await getUserStateAsync();
                let headerIds = getFlattenedHeaderIds(localUser, state.pageSourceUrl, currentUser);
                // Tell the editor to transfer local skillmap projects to the cloud.
                const headerMap = (await res.sendMessageAsync!({
                    type: "pxteditor",
                    action: "savelocalprojectstocloud",
                    headerIds
                } as pxt.editor.EditorMessageSaveLocalProjectsToCloud)).resp.headerIdMap;
                if (headerMap) {
                    const newUser: UserState = {
                        ...currentUser,
                        mapProgress: {}
                    }

                    const localUrls = Object.keys(localUser.mapProgress);
                    for (const url of localUrls) {
                        // Copy over local user progress. If there is cloud progress, it will
                        // be overwritten
                        newUser.mapProgress[url] = {
                            ...localUser.mapProgress[url]
                        }

                        const maps = Object.keys(localUser.mapProgress[url]);
                        for (const map of maps) {
                            // Only copy over state if the user hasn't started this map yet
                            if (!hasUrlBeenStarted(currentUser, url)) {
                                newUser.mapProgress[url][map] = {
                                    ...localUser.mapProgress[url][map]
                                };
                                newUser.completedTags[url] = localUser.completedTags[url];
                                const activityState: {[index: string]: ActivityState} = {};
                                newUser.mapProgress[url][map].activityState = activityState;

                                const localProgress = localUser.mapProgress[url][map].activityState
                                for (const activity of Object.keys(localProgress)) {
                                    const localActivity = localProgress[activity];
                                    if (localActivity.headerId) {
                                        activityState[activity] = {
                                            ...localActivity,
                                            headerId: headerMap[localActivity.headerId] || localActivity.headerId
                                        };
                                    } else if (isRewardNode(state.maps[map].activities[activity])) {
                                        activityState[activity] = {
                                            ...localActivity
                                        };
                                    }
                                }
                            }
                        }
                    }

                    const visitedUrls = Object.keys(currentUser.mapProgress)
                    // Copy progress from cloud user for all visited URLs.
                    for (const url of visitedUrls) {
                        if (hasUrlBeenStarted(currentUser, url)) {
                            newUser.mapProgress[url] = {
                                ...currentUser.mapProgress[url]
                            }
                            newUser.completedTags[url] = currentUser.completedTags[url]
                        }
                    }

                    this.props.dispatchSetUser(newUser);
                    await saveUserStateAsync(newUser);
                    currentUser = newUser;

                    const prefs = await authClient.userPreferencesAsync();
                    if (prefs) this.props.dispatchSetUserPreferences(prefs);
                    await this.syncBadgesAsync();
                }

                // Tell the editor to send us the cloud status of our projects.
                await res.sendMessageAsync!({
                    type: "pxteditor",
                    action: "requestprojectcloudstatus",
                    headerIds: getFlattenedHeaderIds(currentUser, state.pageSourceUrl)
                } as pxt.editor.EditorMessageRequestProjectCloudStatus);
                this.setState({ cloudSyncCheckHasFinished: true, showingSyncLoader: false });
            }
            // Timeout if cloud sync check doesn't complete in a reasonable timeframe.
            const TIMEOUT_MS = 10 * 1000;
            await Promise.race([
                pxt.U.delay(TIMEOUT_MS).then(() => {
                    if (!this.state.cloudSyncCheckHasFinished)
                        this.setState({ cloudSyncCheckHasFinished: true, showingSyncLoader: false });
                }),
                doCloudSyncCheckAsync()]);
        }
    }

    protected onMakeCodeFrameLoaded = async (sendMessageAsync: (message: any) => Promise<any>) => {
        this.readyPromise.setSendMessageAsync(sendMessageAsync);
    }

    async componentDidMount() {
        this.unsubscribeChangeListener = store.subscribe(this.onStoreChange);
        this.queryFlags = parseQuery();
        if (this.queryFlags["authcallback"]) {
            await authClient.loginCallbackAsync(this.queryFlags);
        }

        await authClient.authCheckAsync();
        await this.initLocalizationAsync();
        await this.parseHashAsync();
        this.readyPromise.setAppMounted();

        if (await authClient.loggedInAsync() && !this.state.cloudSyncCheckHasFinished) {
            this.setState({ showingSyncLoader: true });
        }
    }

    componentDidUpdate() {
        const { highContrast } = this.props;

        const bodyIsHighContrast = document.body.classList.contains("high-contrast");

        if (highContrast) {
            if (!bodyIsHighContrast) document.body.classList.add("high-contrast");
        }
        else if (bodyIsHighContrast) {
            document.body.classList.remove("high-contrast");
        }
    }

    componentWillUnmount() {
        window.removeEventListener("hashchange", this.handleHashChange);
        if (this.unsubscribeChangeListener) {
            this.unsubscribeChangeListener();
        }
    }

    render() {
        const { skillMaps, activityOpen, backgroundImageUrl, theme } = this.props;
        const { error, showingSyncLoader } = this.state;
        const maps = Object.keys(skillMaps).map((id: string) => skillMaps[id]);
        return (<div className={`app-container ${pxt.appTarget.id}`}>
                <HeaderBar />
                {showingSyncLoader &&

{lf("Saving to cloud...")}

}
                <div className={`skill-map-container ${activityOpen ? "hidden" : ""}`} style={{ backgroundColor: theme.backgroundColor }}>
                    { error
                        ?
{error}

                        : <SkillGraphContainer maps={maps} backgroundImageUrl={backgroundImageUrl} />
                    }
                    { !error && <InfoPanel onFocusEscape={this.focusCurrentActivity} />}

                <MakeCodeFrame onWorkspaceReady={this.onMakeCodeFrameLoaded}/>
                <AppModal />
                <UserProfile />

);
    }

    protected applyQueryFlags(user: UserState, maps?: SkillMap[], sourceUrl?: string) {
        const pageSource = sourceUrl || "default";
        if (this.queryFlags["debugNewUser"] === "true") {
            user.isDebug = true;
            user.mapProgress = { [pageSource]: {} };
            user.completedTags = {};
        }

        if (this.queryFlags["debugCompleted"] === "true") {
            user.isDebug = true;
            user.mapProgress = { [pageSource]: {} };

            if (maps) {
                for (const map of maps) {
                    user.mapProgress[pageSource][map.mapId] = {
                        completionState: "completed",
                        mapId: map.mapId,
                        activityState: {}
                    };

                    for (const key of Object.keys(map.activities)) {
                        const activity = map.activities[key];
                        if (!user.mapProgress[pageSource][map.mapId].activityState[activity.activityId]) {
                            user.mapProgress[pageSource][map.mapId].activityState[activity.activityId] = {
                                activityId: activity.activityId,
                                isCompleted: true
                            };
                        }
                        else {
                            user.mapProgress[pageSource][map.mapId].activityState[activity.activityId].isCompleted = true;
                        }

                        if (activity.kind === "activity" && activity.tags?.length && sourceUrl) {
                            for (const tag of activity.tags) {
                                if (!user.completedTags[sourceUrl][tag]) user.completedTags[sourceUrl][tag] = 0;
                                user.completedTags[sourceUrl][tag]++;
                            }
                        }
                    }
                }
            }
        }
    }

    protected focusCurrentActivity = () => {
        const node = document.querySelector("[data-activity=" + this.props.activityId + "] button");
        (node as HTMLElement | SVGElement).focus();

        // Clear info panel
        this.props.dispatchChangeSelectedItem(undefined);
    }

    protected onStoreChange = async () => {
        const { user } = store.getState();

        if (user !== this.loadedUser && (!this.loadedUser || user.id === this.loadedUser.id)) {
            // To avoid a race condition where we save to local user's state to the cloud user
            // before we get a chance to run the cloud upgrade rules on projects, we need to wait
            // for cloudSyncCheck to finish if we're logged in.
            if (!this.props.signedIn ||
                (this.props.signedIn && this.state.cloudSyncCheckHasFinished)) {
                await saveUserStateAsync(user);
                this.loadedUser = user;
            }
        }

        await this.syncBadgesAsync();
    }

    protected async syncBadgesAsync() {
        const { user, maps, pageSourceUrl, pageSourceStatus } = store.getState();

        if (this.props.signedIn && this.state.cloudSyncCheckHasFinished && pageSourceStatus === "approved") {
            let allBadges: pxt.auth.Badge[] = [];
            for (const map of Object.keys(maps)) {
                allBadges.push(...getCompletedBadges(user, pageSourceUrl, maps[map]))
            }

            if (allBadges.length) {
                const badgeState = await authClient.getBadgeStateAsync() || { badges: [] };
                allBadges = allBadges.filter(badge => !pxt.auth.hasBadge(badgeState, badge))

                if (allBadges.length && !this.state.badgeSyncLock) {
                    this.setState({ badgeSyncLock: true })
                    try {
                        await authClient.grantBadgesAsync(allBadges, badgeState.badges)
                        const prefs = await authClient.userPreferencesAsync();
                        if (prefs) {
                            this.props.dispatchSetUserPreferences(prefs)
                        }
                    }
                    finally {
                        this.setState({ badgeSyncLock: false })
                    }
                }
            }
        }
    }
}

function mapStateToProps(state: SkillMapState, ownProps: any) {
    if (!state) return {};
    return {
        skillMaps: state.maps,
        activityOpen: !!state.editorView,
        backgroundImageUrl: state.backgroundImageUrl,
        theme: state.theme,
        signedIn: state.auth.signedIn,
        activityId: state.selectedItem?.activityId,
        highContrast: state.auth.preferences?.highContrast
    };
}
interface LocalizationUpdateOptions {
    targetId: string;
    baseUrl: string;
    code: string;
    pxtBranch: string;
    targetBranch: string;
    force?: boolean;
}

async function updateLocalizationAsync(opts: LocalizationUpdateOptions): Promise<void> {
    const {
        targetId,
        baseUrl,
        pxtBranch,
        targetBranch,
        force,
    } = opts;
    let { code } = opts;

    const translations = await pxt.Util.downloadTranslationsAsync(
        targetId,
        baseUrl,
        code,
        pxtBranch,
        targetBranch,
        pxt.Util.liveLocalizationEnabled(),
        ts.pxtc.Util.TranslationsKind.SkillMap
    );

    if (translations) {
        pxt.Util.setLocalizedStrings(translations);
    }
}

const mapDispatchToProps = {
    dispatchAddSkillMap,
    dispatchClearSkillMaps,
    dispatchClearMetadata,
    dispatchSetPageTitle,
    dispatchSetPageDescription,
    dispatchSetPageInfoUrl,
    dispatchSetUser,
    dispatchSetPageSourceUrl,
    dispatchSetPageAlternateUrls,
    dispatchSetPageBackgroundImageUrl,
    dispatchSetPageBannerImageUrl,
    dispatchSetPageTheme,
    dispatchSetUserPreferences,
    dispatchChangeSelectedItem
};

const App = connect(mapStateToProps, mapDispatchToProps)(AppImpl);

export default App;


text:
module.exports.auth = require('./auth');
module.exports.statics = require('./statics');
module.exports.user = require('./user');
module.exports.app = require('./app');

/* check if user is authenticated using passport */
module.exports.authenticatedUser = (req, res, next) => {
	// check user authentication status
	if(req.isAuthenticated()) return next();
	res.redirect('/');
};


text:
require 'test_helper'

class GroupTest < ActiveSupport::TestCase

  fixtures :users, :groups

  def test_validation
    group = Group.new
    assert !group.valid?

    group.name = ""
    assert !group.valid?
  end

  def test_fields
    group = Group.new({:name => "test"})
    assert_equal group.name, "test"
  end

  def test_leader
    cool_kids = groups(:cool_kids)
    assert_equal cool_kids.leader, users(:groupie)
  end

  def test_group_membership
    groupie = users(:groupie) #Member of one group
    patron = users(:patron) #Member of two groups
    regular = users(:regular) #Member of 0 groups

    cool_kids = groups(:cool_kids) #Has 2 members
    patroons = groups(:patroons) #Has 1 member

    #Test associations
    assert cool_kids.users.include?(groupie)
    assert !patroons.users.include?(groupie)
  end

end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.meruvian.workshop</groupId>
	<artifactId>meruvian-workshop-jaxrs-dagger</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<resteasy.version>3.0.11.Final</resteasy.version>
		<dagger.version>2.6</dagger.version>
		<swagger.version>1.5.0</swagger.version>
		<jetty.version>9.2.4.v20141103</jetty.version>
	</properties>

	<dependencies>
		<!-- Servlet API -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- RESTEasy JAX-RS -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-servlet-initializer</artifactId>
			<version>${resteasy.version}</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>${resteasy.version}</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>jaxrs-api</artifactId>
			<version>${resteasy.version}</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jackson2-provider</artifactId>
			<version>${resteasy.version}</version>
		</dependency>

		<!-- Dagger -->
		<dependency>
			<groupId>com.google.dagger</groupId>
			<artifactId>dagger</artifactId>
			<version>${dagger.version}</version>
		</dependency>

		<!-- Swagger REST API -->
		<dependency>
			<groupId>io.swagger</groupId>
			<artifactId>swagger-jaxrs</artifactId>
			<version>${swagger.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
				<dependencies>
					<dependency>
						<groupId>com.google.dagger</groupId>
						<artifactId>dagger-compiler</artifactId>
						<version>${dagger.version}</version>
					</dependency>
				</dependencies>
			</plugin>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>${jetty.version}</version>
			</plugin>
		</plugins>
	</build>
	<packaging>war</packaging>
</project>


text:
/* RCS compile-time configuration */

	/* $FreeBSD: soc2013/dpl/head/gnu/usr.bin/rcs/lib/conf.h 121579 2003-10-26 04:26:52Z peter $ */

/*
 * This file is generated automatically.
 * If you edit it by hand your changes may be lost.
 * Instead, please try to fix conf.sh,
 * and send your fixes to rcs-bugs@cs.purdue.edu.
 */

#define exitmain(n) return n /* how to exit from main() */
/* #define _POSIX_C_SOURCE 2147483647L */ /* if strict C + Posix 1003.1b-1993 or later */
/* #define _POSIX_SOURCE */ /* if strict C + Posix 1003.1-1990 */

#include <errno.h>
#include <stdio.h>
#include <time.h>

/* Comment out #include lines below that do not work.  */
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
/* #include <mach/mach.h> */
/* #include <net/errno.h> */
#include <pwd.h>
/* #include <siginfo.h> */
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
/* #include <ucontext.h> */
#include <unistd.h>
#include <utime.h>
/* #include <vfork.h> */

/* Define boolean symbols to be 0 (false, the default), or 1 (true).  */
#define has_sys_param_h 1 /* Does #include <sys/param.h> work?  */
/* extern int errno; */ /* Uncomment if <errno.h> doesn't declare errno.  */
#define has_readlink 1 /* Does readlink() work?  */
#define readlink_isreg_errno EINVAL /* errno after readlink on regular file */

#if has_readlink && !defined(MAXSYMLINKS)
#	if has_sys_param_h
#		include <sys/param.h>
#	endif
#	ifndef MAXSYMLINKS
#		define MAXSYMLINKS 20 /* BSD; not standard yet */
#	endif
#endif

/* Comment out the typedefs below if the types are already declared.  */
/* Fix any uncommented typedefs that are wrong.  */
/* typedef int mode_t; */
/* typedef long off_t; */
/* typedef int pid_t; */
/* typedef int sig_atomic_t; */
/* typedef unsigned size_t; */
/* typedef int ssize_t; */
/* typedef long time_t; */
/* typedef int uid_t; */

/* Comment out the keyword definitions below if the keywords work.  */
/* #define const */
/* #define volatile */

/* Define boolean symbols to be 0 (false, the default), or 1 (true).  */
#define has_prototypes 1 /* Do function prototypes work?  */
#define has_stdarg 1 /* Does <stdarg.h> work?  */
/* #define has_varargs ? */ /* Does <varargs.h> work?  */
#define va_start_args 2 /* How many args does va_start() take?  */

#if O_BINARY
	/* Text and binary i/o behave differently.  */
	/* This is incompatible with Posix and Unix.  */
#	define FOPEN_RB "rb"
#	define FOPEN_R_WORK (Expand==BINARY_EXPAND ? "r" : "rb")
#	define FOPEN_WB "wb"
#	define FOPEN_W_WORK (Expand==BINARY_EXPAND ? "w" : "wb")
#	define FOPEN_WPLUS_WORK (Expand==BINARY_EXPAND ? "w+" : "w+b")
#	define OPEN_O_BINARY O_BINARY
#else
	/*
	* Text and binary i/o behave the same.
	* Omit "b", since some nonstandard hosts reject it.
	*/
#	define FOPEN_RB "r"
#	define FOPEN_R_WORK "r"
#	define FOPEN_WB "w"
#	define FOPEN_W_WORK "w"
#	define FOPEN_WPLUS_WORK "w+"
#	define OPEN_O_BINARY 0
#endif

/* This may need changing on non-Unix systems (notably DOS).  */
#define OPEN_CREAT_READONLY (S_IRUSR|S_IRGRP|S_IROTH) /* lock file mode */
#define OPEN_O_LOCK 0 /* extra open flags for creating lock file */
#define OPEN_O_WRONLY O_WRONLY /* main open flag for creating a lock file */

/* Define or comment out the following symbols as needed.  */
#if has_prototypes
#	define P(params) params
#else
#	define P(params) ()
#endif
#if has_stdarg
#	include <stdarg.h>
#else
#	if has_varargs
#		include <varargs.h>
#	else
		typedef char *va_list;
#		define va_dcl int va_alist;
#		define va_start(ap) ((ap) = (va_list)&va_alist)
#		define va_arg(ap,t) (((t*) ((ap)+=sizeof(t)))  [-1])
#		define va_end(ap)
#	endif
#endif
#if va_start_args == 2
#	define vararg_start va_start
#else
#	define vararg_start(ap,p) va_start(ap)
#endif
#define bad_chmod_close 0 /* Can chmod() close file descriptors?  */
#define bad_creat0 0 /* Do writes fail after creat(f,0)?  */
#define bad_fopen_wplus 0 /* Does fopen(f,"w+") fail to truncate f?  */
#define getlogin_is_secure 0 /* Is getlogin() secure?  Usually it's not.  */
#define has_attribute_noreturn 1 /* Does __attribute__((noreturn)) work?  */
#if has_attribute_noreturn
#	define exiting __attribute__((noreturn))
#else
#	define exiting
#endif
#define has_dirent 1 /* Do opendir(), readdir(), closedir() work?  */
#define void_closedir 0 /* Does closedir() yield void?  */
#define has_fchmod 1 /* Does fchmod() work?  */
#define has_fflush_input 0 /* Does fflush() work on input files?  */
#define has_fputs 1 /* Does fputs() work?  */
#define has_ftruncate 1 /* Does ftruncate() work?  */
#define has_getuid 1 /* Does getuid() work?  */
#define has_getpwuid 1 /* Does getpwuid() work?  */
#define has_memcmp 1 /* Does memcmp() work?  */
#define has_memcpy 1 /* Does memcpy() work?  */
#define has_memmove 1 /* Does memmove() work?  */
#define has_map_fd 0 /* Does map_fd() work?  */
#define has_mmap 1 /* Does mmap() work on regular files?  */
#define has_madvise 0 /* Does madvise() work?  */
#define mmap_signal SIGBUS /* signal received if you reference nonexistent part of mmapped file */
#define has_rename 1 /* Does rename() work?  */
#define bad_a_rename 0 /* Does rename(A,B) fail if A is unwritable?  */
#define bad_b_rename 0 /* Does rename(A,B) fail if B is unwritable?  */
#define bad_NFS_rename 0 /* Can rename(A,B) falsely report success?  */
/* typedef int void; */ /* Some ancient compilers need this.  */
#define VOID (void) /* 'VOID e;' discards the value of an expression 'e'.  */
#define has_seteuid 1 /* Does seteuid() work?  See ../INSTALL.RCS.  */
#define has_setreuid 0 /* Does setreuid() work?  See ../INSTALL.RCS.  */
#define has_setuid 1 /* Does setuid() exist?  */
#define has_sigaction 1 /* Does struct sigaction work?  */
#define has_sa_sigaction 1 /* Does struct sigaction have sa_sigaction?  */
#define has_signal 1 /* Does signal() work?  */
#define signal_type void /* type returned by signal handlers */
#define sig_zaps_handler 0 /* Must a signal handler reinvoke signal()?  */
/* #define has_sigblock ? */ /* Does sigblock() work?  */
/* #define sigmask(s) (1 << ((s)-1)) */ /* Yield mask for signal number.  */
typedef size_t fread_type; /* type returned by fread() and fwrite() */
typedef size_t freadarg_type; /* type of their size arguments */
typedef void *malloc_type; /* type returned by malloc() */
#define has_getcwd 1 /* Does getcwd() work?  */
/* #define has_getwd ? */ /* Does getwd() work?  */
#define needs_getabsname 0 /* Must we define getabsname?  */
#define has_mktemp 1 /* Does mktemp() work?  */
#define has_mkstemp 1 /* Does mkstemp() work?  */
#define has_NFS 1 /* Might NFS be used?  */
#define has_psiginfo 0 /* Does psiginfo() work?  */
#define has_psignal 1 /* Does psignal() work?  */
/* #define has_si_errno ? */ /* Does siginfo_t have si_errno?  */
/* #define has_sys_siglist ? */ /* Does sys_siglist[] work?  */
/* #define strchr index */ /* Use old-fashioned name for strchr()?  */
/* #define strrchr rindex */ /* Use old-fashioned name for strrchr()?  */
#define bad_unlink 0 /* Does unlink() fail on unwritable files?  */
#define has_vfork 1 /* Does vfork() work?  */
#define has_fork 1 /* Does fork() work?  */
#define has_spawn 0 /* Does spawn*() work?  */
#define has_waitpid 1 /* Does waitpid() work?  */
#define bad_wait_if_SIGCHLD_ignored 0 /* Does ignoring SIGCHLD break wait()?  */
#define RCS_SHELL "/bin/sh" /* shell to run RCS subprograms */
#define has_printf_dot 1 /* Does "%.2d" print leading 0?  */
#define has_vfprintf 1 /* Does vfprintf() work?  */
#define has_attribute_format_printf 1 /* Does __attribute__((format(printf,N,N+1))) work?  */
#if has_attribute_format_printf
#	define printf_string(m, n) __attribute__((format(printf, m, n)))
#else
#	define printf_string(m, n)
#endif
#if has_attribute_format_printf && has_attribute_noreturn
	/* Work around a bug in GCC 2.5.x.  */
#	define printf_string_exiting(m, n) __attribute__((format(printf, m, n), noreturn))
#else
#	define printf_string_exiting(m, n) printf_string(m, n) exiting
#endif
/* #define has__doprintf ? */ /* Does _doprintf() work?  */
/* #define has__doprnt ? */ /* Does _doprnt() work?  */
/* #undef EXIT_FAILURE */ /* Uncomment this if EXIT_FAILURE is broken.  */
#define large_memory 1 /* Can main memory hold entire RCS files?  */
#ifndef LONG_MAX
#define LONG_MAX 2147483647L /* long maximum */
#endif
/* Do struct stat s and t describe the same file?  Answer d if unknown.  */
#define same_file(s,t,d) ((s).st_ino==(t).st_ino && (s).st_dev==(t).st_dev)
#define has_utimbuf 1 /* Does struct utimbuf work?  */
#define CO "/usr/bin/co" /* name of 'co' program */
#define COMPAT2 0 /* Are version 2 files supported?  */
#define DIFF "/usr/bin/diff" /* name of 'diff' program */
#define DIFF3 "/usr/bin/diff3" /* name of 'diff3' program */
#define DIFF3_BIN 1 /* Is diff3 user-visible (not the /usr/lib auxiliary)?  */
#define DIFFFLAGS "-an" /* Make diff output suitable for RCS.  */
#define DIFF_L 1 /* Does diff -L work?  */
#define DIFF_SUCCESS 0 /* DIFF status if no differences are found */
#define DIFF_FAILURE 1 /* DIFF status if differences are found */
#define DIFF_TROUBLE 2 /* DIFF status if trouble */
#define ED "/bin/ed" /* name of 'ed' program (used only if !DIFF3_BIN) */
#define MERGE "/usr/bin/merge" /* name of 'merge' program */
#define TMPDIR "/tmp" /* default directory for temporary files */
#define SLASH '/' /* principal filename separator */
#define SLASHes '/' /* `case SLASHes:' labels all filename separators */
#define isSLASH(c) ((c) == SLASH) /* Is arg a filename separator?  */
#define ROOTPATH(p) isSLASH((p)[0]) /* Is p an absolute pathname?  */
#define X_DEFAULT ",v/" /* default value for -x option */
#define SLASHSLASH_is_SLASH 1 /* Are // and / the same directory?  */
#define ALL_ABSOLUTE 1 /* Do all subprograms satisfy ROOTPATH?  */
#define DIFF_ABSOLUTE 1 /* Is ROOTPATH(DIFF) true?  */
#define SENDMAIL "/usr/sbin/sendmail" /* how to send mail */
#define TZ_must_be_set 0 /* Must TZ be set for gmtime() to work?  */

/* Adjust the following declarations as needed.  */

/* The rest is for the benefit of non-standard, traditional hosts.  */
/* Don't bother to declare functions that in traditional hosts do not appear, */
/* or are declared in .h files, or return int or void.  */

/* traditional BSD */

#if has_sys_siglist && !defined(sys_siglist)
	extern char const * const sys_siglist[];
#endif

/* Posix (ISO/IEC 9945-1: 1990 / IEEE Std 1003.1-1990) */

/* <fcntl.h> */
#ifdef O_CREAT
#	define open_can_creat 1
#else
#	define open_can_creat 0
#	define O_RDONLY 0
#	define O_WRONLY 1
#	define O_RDWR 2
#	define O_CREAT 01000
#	define O_TRUNC 02000
#endif
#ifndef O_EXCL
#define O_EXCL 0
#endif

/* <sys/stat.h> */
#ifndef S_IRUSR
#	ifdef S_IREAD
#		define S_IRUSR S_IREAD
#	else
#		define S_IRUSR 0400
#	endif
#	ifdef S_IWRITE
#		define S_IWUSR S_IWRITE
#	else
#		define S_IWUSR (S_IRUSR/2)
#	endif
#endif
#ifndef S_IRGRP
#	if has_getuid
#		define S_IRGRP (S_IRUSR / 0010)
#		define S_IWGRP (S_IWUSR / 0010)
#		define S_IROTH (S_IRUSR / 0100)
#		define S_IWOTH (S_IWUSR / 0100)
#	else
		/* single user OS -- not Posix or Unix */
#		define S_IRGRP 0
#		define S_IWGRP 0
#		define S_IROTH 0
#		define S_IWOTH 0
#	endif
#endif
#ifndef S_ISREG
#define S_ISREG(n) (((n) & S_IFMT) == S_IFREG)
#endif

/* <sys/wait.h> */
#ifndef WEXITSTATUS
#define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
#undef WIFEXITED /* Avoid 4.3BSD incompatibility with Posix.  */
#endif
#ifndef WIFEXITED
#define WIFEXITED(stat_val) (((stat_val)  &  0377) == 0)
#endif
#ifndef WTERMSIG
#define WTERMSIG(stat_val) ((stat_val) & 0177)
#undef WIFSIGNALED /* Avoid 4.3BSD incompatibility with Posix.  */
#endif
#ifndef WIFSIGNALED
#define WIFSIGNALED(stat_val) ((unsigned)(stat_val) - 1  <  0377)
#endif

/* <unistd.h> */
char *getlogin P((void));
#ifndef STDIN_FILENO
#	define STDIN_FILENO 0
#	define STDOUT_FILENO 1
#	define STDERR_FILENO 2
#endif
#if has_fork && !has_vfork
#	undef vfork
#	define vfork fork
#endif
#if has_getcwd || !has_getwd
	char *getcwd P((char*,size_t));
#else
	char *getwd P((char*));
#endif
#if has_setuid && !has_seteuid
#	undef seteuid
#	define seteuid setuid
#endif
#if has_spawn
#	if ALL_ABSOLUTE
#		define spawn_RCS spawnv
#	else
#		define spawn_RCS spawnvp
#	endif
#else
#	if ALL_ABSOLUTE
#		define exec_RCS execv
#	else
#		define exec_RCS execvp
#	endif
#endif

/* utime.h */
#if !has_utimbuf
	struct utimbuf { time_t actime, modtime; };
#endif

/* Standard C library */

/* <stdio.h> */
#ifndef L_tmpnam
#define L_tmpnam 32 /* power of 2 > sizeof("/usr/tmp/xxxxxxxxxxxxxxx") */
#endif
#ifndef SEEK_SET
#define SEEK_SET 0
#endif
#ifndef SEEK_CUR
#define SEEK_CUR 1
#endif
#if has_mktemp
	char *mktemp P((char*)); /* traditional */
#else
	char *tmpnam P((char*));
#endif

/* <stdlib.h> */
char *getenv P((char const*));
void _exit P((int)) exiting;
void exit P((int)) exiting;
malloc_type malloc P((size_t));
malloc_type realloc P((malloc_type,size_t));
#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif

/* <string.h> */
char *strcpy P((char*,char const*));
char *strchr P((char const*,int));
char *strrchr P((char const*,int));
void *memcpy P((void*,void const*,size_t));
#if has_memmove
	void *memmove P((void*,void const*,size_t));
#endif

/* <time.h> */
time_t time P((time_t*));


text:
'use strict';

const $ = require('jquery');
const _ = require('underscore');
const Marionette = require('backbone.marionette');
const Rickshaw = require('rickshaw');

const AgentLogsOverlay = require('./AgentLogsOverlay');

module.exports = Marionette.ItemView.extend({
    className: 'agent-tile',
    template: require('./agentData.hbs'),

    events: {
        'click button[name="view-logs"]': 'onClickViewLogs'
    },

    serializeData: function() {
        return _.extend({}, this.model.attributes, {
            processDataCollection: this.model.attributes.processDataCollection.toJSON(),
            diskDataCollection: this.model.attributes.diskDataCollection.toJSON()
        });
    },

    onRender: function() {
        this._drawCpuMetricsChart();
    },

    _drawCpuMetricsChart: function() {
        const series = [{
            name: 'system',
            data: [],
            color: 'red'
        }, {
            name: 'user',
            data: [],
            color: 'blue'
        }];

        this.model.get('cpuMetrics').reduce((memo, datum) => {
            if (datum.kernelUtilization && datum.userUtilization) {
                memo[0].data.push({
                    x: datum.sampleTime,
                    y: datum.kernelUtilization
                });
                memo[1].data.push({
                    x: datum.sampleTime,
                    y: datum.userUtilization
                });
            }

            return memo;
        }, series);

        if (series[0].data.length) {
            var graph = new Rickshaw.Graph({
                element: this.$('.cpu-info-chart').get(0),
                width: 600,
                height: 80,
                max: 125,
                series: series,
                renderer: 'line'
            });
            graph.render();
        }
    },

    onClickViewLogs: function() {
        const overlay = new AgentLogsOverlay({
            model: this.model
        });
        $('body').append(overlay.render().el);
    }
});


text:
/* (c) British Telecommunications plc, 2009, All Rights Reserved */
package com.bt.pi.app.networkmanager.iptables;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.bt.pi.app.common.entities.SecurityGroup;
import com.bt.pi.app.common.entities.SubnetAllocationIndex;
import com.bt.pi.app.common.entities.util.ResourceRange;
import com.bt.pi.app.common.id.PiIdBuilder;
import com.bt.pi.app.common.net.iptables.IpTablesHelper;
import com.bt.pi.app.common.net.utils.IpAddressUtils;
import com.bt.pi.core.application.resource.ConsumedDhtResourceRegistry;
import com.bt.pi.core.continuation.PiContinuation;
import com.bt.pi.core.dht.cache.DhtCache;
import com.bt.pi.core.node.NodeStartedEvent;
import com.bt.pi.core.util.common.CommandRunner;

@Component
public class IpTablesManager implements ApplicationListener<NodeStartedEvent> {
    protected static final String PI_CHAIN = "pi-chain";
    protected static final String PI_CHAIN_FORWARD = "-A FORWARD -j " + PI_CHAIN;
    protected static final String PI_CHAIN_DEFINITION = ":" + PI_CHAIN + " - [0:0]";
    protected static final String PI_CHAIN_CREATE = "-N " + PI_CHAIN;
    private static final String FILTER = "filter";
    private static final String NAT = "nat";
    private static final Log LOG = LogFactory.getLog(IpTablesManager.class);
    private static final String LINE_OF_EQUALS = "==================================================================";
    private IpTablesBuilder ipTablesBuilder;
    private IpTablesHelper ipTablesHelper;
    private String iptablesSaveCommand;
    private String iptablesRestoreCommand;
    private CommandRunner commandRunner;
    private ConsumedDhtResourceRegistry consumedDhtResourceRegistry;
    private PiIdBuilder piIdBuilder;
    private DhtCache dhtCache;
    private AtomicBoolean nodeStarted;

    public IpTablesManager() {
        this.ipTablesBuilder = null;
        this.ipTablesHelper = null;
        this.commandRunner = null;
        this.iptablesSaveCommand = "iptables-save";
        this.iptablesRestoreCommand = "iptables-restore";
        this.consumedDhtResourceRegistry = null;
        this.piIdBuilder = null;
        this.dhtCache = null;
        this.nodeStarted = new AtomicBoolean(false);
    }

    @Resource
    public synchronized void setPiIdBuilder(PiIdBuilder aPiIdBuilder) {
        this.piIdBuilder = aPiIdBuilder;
    }

    @Resource
    public synchronized void setConsumedDhtResourceRegistry(ConsumedDhtResourceRegistry aConsumedDhtResourceRegistry) {
        this.consumedDhtResourceRegistry = aConsumedDhtResourceRegistry;
    }

    @Resource
    public synchronized void setIpTablesBuilder(IpTablesBuilder aIpTablesBuilder) {
        this.ipTablesBuilder = aIpTablesBuilder;
    }

    @Resource
    public synchronized void setIpTablesHelper(IpTablesHelper aIpTablesHelper) {
        this.ipTablesHelper = aIpTablesHelper;
    }

    @Resource
    public synchronized void setCommandRunner(CommandRunner runner) {
        this.commandRunner = runner;
    }

    @Resource(name = "generalCache")
    public synchronized void setDhtCache(DhtCache aDhtCache) {
        this.dhtCache = aDhtCache;
    }

    public synchronized void refreshIpTables() {
        List<SecurityGroup> securityGroups = (List<SecurityGroup>) consumedDhtResourceRegistry.getByType(SecurityGroup.class);
        LOG.info(String.format("Refreshing iptables with %d group(s)", securityGroups.size()));

        final List<String> iptablesSaveNatLines = getLines(NAT);
        final List<String> iptablesSaveFilterLines = getLines(FILTER);

        final List<String> nonPiIptablesNatLines = ipTablesBuilder.removePiChainsAndRules(iptablesSaveNatLines);
        final List<String> nonPiIptablesFilterLines = ipTablesBuilder.removePiChainsAndRules(iptablesSaveFilterLines, Arrays.asList(new String[] { PI_CHAIN_DEFINITION, PI_CHAIN_FORWARD }));

        final List<String> natRules = ipTablesBuilder.generateNatTable(securityGroups, Arrays.asList(new String[0]));
        applyRules(NAT, natRules, nonPiIptablesNatLines);

        final List<String> filterRules = ipTablesBuilder.generateFilterTable(securityGroups, Arrays.asList(new String[0]));
        if (!nonPiIptablesFilterLines.contains(PI_CHAIN_FORWARD))
            filterRules.add(0, PI_CHAIN_FORWARD);
        if (!nonPiIptablesFilterLines.contains(PI_CHAIN_DEFINITION))
            filterRules.add(0, PI_CHAIN_CREATE);

        dhtCache.get(piIdBuilder.getPId(SubnetAllocationIndex.URL).forLocalRegion(), new PiContinuation<SubnetAllocationIndex>() {
            @Override
            public void handleResult(SubnetAllocationIndex subnetAllocationIndex) {
                if (null != subnetAllocationIndex) {
                    Set<ResourceRange> resourceRanges = subnetAllocationIndex.getResourceRanges();
                    for (ResourceRange rr : resourceRanges) {
                        long minBaseIpAddressAsLong = rr.getMin();
                        String ipAddress = IpAddressUtils.longToIp(minBaseIpAddressAsLong);
                        long maxBaseIpAddressAsLong = rr.getMax();
                        long numAddrs = maxBaseIpAddressAsLong - minBaseIpAddressAsLong + 1;
                        String rule = String.format("-A %s -d %s/%d -j DROP", PI_CHAIN, ipAddress, IpAddressUtils.slashnetFromAddrs(numAddrs));
                        filterRules.add(rule);
                    }
                } else {
                    LOG.warn(String.format("Cached subnet allocation index record was not found by ip tables manager"));
                }
                applyRules(FILTER, filterRules, nonPiIptablesFilterLines);
            }
        });
    }

    private synchronized void applyRules(String tableName, List<String> rules, List<String> existingLines) {
        LOG.debug(String.format("applyRules(%s, %s, %s)", tableName, rules, existingLines));
        logLines("before edit", tableName, existingLines);
        int i = 0;
        for (String line : existingLines) {
            if ("COMMIT".equals(line)) {
                break;
            }
            i++;
        }

        for (int j = rules.size() - 1; j >= 0; j--)
            existingLines.add(i, rules.get(j));

        logLines("after edit", tableName, existingLines);
        commandRunner.runInShell(String.format("echo '%s'", ipTablesHelper.linesToString(existingLines)) + " | " + String.format(iptablesRestoreCommand));
    }

    protected synchronized List<String> getLines(String section) {
        LOG.debug(String.format("getLines(%s)", section));
        return this.commandRunner.run(iptablesSaveCommand + " -t " + section).getOutputLines();
    }

    private void logLines(String where, String tableName, List<String> lines) {
        if (!LOG.isDebugEnabled())
            return;
        LOG.debug(String.format("==== Table %s: %s", tableName, LINE_OF_EQUALS));
        for (int i = 0; i < lines.size(); i++) {
            LOG.debug(String.format("%s (%d): %s", where, i, lines.get(i)));
        }
        LOG.debug(LINE_OF_EQUALS);
    }

    @Override
    public void onApplicationEvent(NodeStartedEvent event) {
        LOG.debug(String.format("onApplicationEvent(%s)", event));
        nodeStarted.set(true);
    }
}


text:
from os import path
import time
from xml.dom import minidom

def output(el, prefix="") :
    if el.nodeType != el.ELEMENT_NODE :
        return

    #print prefix, "<", el.tagName,

    atts = el.attributes
    for i in range(atts.length) :
        a = atts.item(i);
        #print a.nodeName, '="%s"' % a.nodeValue,
    #print '>'

    nl = el.childNodes
    for i in range(nl.length) :
        output(nl.item(i), prefix+"  ")

    #print prefix, "</", el.tagName, ">"

t = time.time()
count = 30
for i in range(count) :
    doc = minidom.parse(path.join(path.dirname(__file__), "sample", "big.xml"))

    el = doc.documentElement
    output(el)

t2 = time.time()
print count, "iterations in", t2-t, "seconds"


text:
layout: post
title : "Expression Blend 2 August CTP 2007"
date : 01.08.2007 00:25:52
tags: [wpf, expression]
---
{% include JB/setup %}

Um uns die Wartezeit auf die kommende Microsoft Expression Suite zu versüßen, hat Microsoft nun die [August CTP von Expression Blend 2](http://www.microsoft.com/expression/products/download.aspx?key=blend2preview) veröffentlicht.

Neben zahlreichen Bug-Fixes und Performance Verbesserungen wartet diese CTP mit der Unterstützung für Visual Studio 2008 Beta 2 und Microsoft Silverlight RC auf.


text:
- hotfix `OutOfMemoryException` (stackoverflow) when calling  `Activity#getLastCompositeCustomNonConfigurationInstance()` (#21) #22

## 0.2.0

- `FragmentPlugin` can now be added to `CompositeDialogFragment` #16
- Updated to support library version `23.4.0`
- Project got split up into different modules #20

```gradle
dependencies {

    // contains CompositeActivity
    compile 'com.pascalwelsch.compositeandroid:activity:0.2.0'

    // contains CompositeFragment and CompositeDialogFragment
    compile 'com.pascalwelsch.compositeandroid:fragment:0.2.0'

    // core module (not required, only abstract classes and utils)
    compile 'com.pascalwelsch.compositeandroid:core:0.2.0'
}
```

## 0.1.2

- Hotfix of crashes caused by type problems #11 #12

```gradle
dependencies {
    compile 'com.pascalwelsch.compositeandroid:activity:0.1.2'
}
```

## 0.1.1 (do not use, major bugs)

- Added support for DialogFragments (`CompositeDialogFragment`) #8
- plugin callbacks `onAddedToDelegate`, `onRemovedFromDelegated` when original is set #9

```gradle
dependencies {
    compile 'com.pascalwelsch.compositeandroid:activity:0.1.1'
}
```

## 0.1

- Added support for Fragments (`CompositeFragment`) #4
- Fixed threading problems #1

```gradle
dependencies {
    compile 'com.pascalwelsch.compositeandroid:activity:0.1'
}
```

## 0.1-alpha (do not use, major bugs)

initial release

- composition for `Activity`

```gradle
dependencies {
    compile 'com.pascalwelsch.compositeandroid:activity:0.1-alpha1'
}
```


text:
def addtodict(word, count, lexicon):
	'''Adds an integer (count) to dictionary (lexicon) under
	the key (word), or increments lexicon[word] if key present. '''

	if word in lexicon:
		lexicon[word] += count
	else:
		lexicon[word] = count

def sortkeysbyvalue(lexicon, whethertoreverse = False):
	'''Accepts a dictionary where keys point to a (presumably numeric) value, and
	returns a list of keys sorted by value.'''

	tuplelist = list()
	for key, value in lexicon.items():
		tuplelist.append((value, key))

	tuplelist = sorted(tuplelist, reverse = whethertoreverse)
	return tuplelist


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.chengqi.mycoderepo.layouts.GridLayoutActivity">

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:columnCount="4"
        android:rowCount="5">

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="1"
            android:id="@+id/button47" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="2"
            android:id="@+id/button48" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="3"
            android:id="@+id/button49" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="/"
            android:id="@+id/button50" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="4"
            android:id="@+id/button51" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="5"
            android:id="@+id/button52" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="6"
            android:id="@+id/button53" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="X"
            android:id="@+id/button54" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="7"
            android:id="@+id/button55" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="8"
            android:id="@+id/button56" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="9"
            android:id="@+id/button57" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="-"
            android:id="@+id/button58" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="0"
            android:id="@+id/button59"
            android:layout_columnSpan="2"
            android:layout_gravity="fill_horizontal" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="."
            android:id="@+id/button60" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="+"
            android:id="@+id/button61"
            android:layout_rowSpan="2"
            android:layout_gravity="fill_vertical" />

        <Button
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:text="="
            android:id="@+id/button62"
            android:layout_columnSpan="3"
            android:layout_gravity="fill_horizontal" />

    </GridLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="excel"
        android:id="@+id/button78"
        android:layout_alignParentBottom="true" />

</RelativeLayout>


text:
/**
 * Uses the new array typed in javascript to binary base64 encode/decode
 * at the moment just decodes a binary base64 encoded
 * into either an ArrayBuffer (decodeArrayBuffer)
 * or into an Uint8Array (decode)
 *
 * References:
 * https://developer.mozilla.org/en/JavaScript_typed_arrays/ArrayBuffer
 * https://developer.mozilla.org/en/JavaScript_typed_arrays/Uint8Array
 */
/**
 * license inazumatv.com
 * author (at)taikiken / http://inazumatv.com
 * date 2014/07/16 - 14:36
 *
 * Copyright (c) 2011-2014 inazumatv.com, inc.
 *
 * Distributed under the terms of the MIT license.
 * http://www.opensource.org/licenses/mit-license.html
 *
 * This notice shall be included in all copies or substantial portions of the Software.
 *
 * https://github.com/danguer/blog-examples/blob/master/js/base64-binary.js
 * http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/
 *
 *      var uintArray = Base64Binary.decode(base64_string);
 *      var byteArray = Base64Binary.decodeArrayBuffer(base64_string);
 */
( function ( window ){
    "use strict";
    var document = window.document
    ;
    var Base64Binary = {
        _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

        /* will return a  Uint8Array type */
        decodeArrayBuffer: function( input ) {
            var bytes = ( input.length / 4 ) * 3;
            var ab = new ArrayBuffer( bytes );
            this.decode( input, ab );

            return ab;
        },

        decode: function( input, arrayBuffer ) {
            //get last chars to see if are valid
            var lkey1 = this._keyStr.indexOf( input.charAt( input.length - 1 ) );
            var lkey2 = this._keyStr.indexOf( input.charAt( input.length - 2 ) );

            var bytes = ( input.length / 4 ) * 3;
            if ( lkey1 === 64 ) { bytes--; } //padding chars, so skip
            if ( lkey2 === 64 ) { bytes--; } //padding chars, so skip

            var uarray;
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            var j = 0;

            if ( arrayBuffer ) {

                uarray = new Uint8Array( arrayBuffer );
            } else {

                uarray = new Uint8Array( bytes );
            }

            input = input.replace( /[^A-Za-z0-9\+\/\=]/g, "" );

            for ( i = 0; i < bytes; i += 3 ) {
                //get the 3 octects in 4 ascii chars
                enc1 = this._keyStr.indexOf( input.charAt( j++ ) );
                enc2 = this._keyStr.indexOf( input.charAt( j++ ) );
                enc3 = this._keyStr.indexOf( input.charAt( j++ ) );
                enc4 = this._keyStr.indexOf( input.charAt( j++ ) );

                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;

                uarray[i] = chr1;
                if ( enc3 !== 64 ) { uarray[ i + 1 ] = chr2; }
                if ( enc4 !== 64 ) { uarray[ i + 2 ] = chr3; }
            }

            return uarray;
        }
    };
}( window ) );


text:
Filename::Filename(const std::string &n, const std::string &delim)
  : name{n}, path_delimiter{delim} {}

Filename& Filename::operator=(const std::string &n) {
  name = n;
  return *this;
}

Filename& Filename::operator=(const Filename &n) {
  name = n.name;
  path_delimiter = n.path_delimiter;
  return *this;
}

Filename::~Filename() {}

const std::string& Filename::get_absolute_name() const { return name; }

const std::string Filename::get_name() const {
  Tokenizer tokenizer{path_delimiter};
  auto tokens{tokenizer.tokenize(name)};
  return tokens.back();
}

const std::string& Filename::get_path_delimiter() const {
  return path_delimiter;
}

bool Filename::operator==(const std::string &n) const { return name == n; }

bool Filename::operator==(const Filename &n) const {
  return name == n.name && path_delimiter == n.path_delimiter;
}

bool Filename::operator!=(const std::string &n) const { return name != n; }

bool Filename::operator!=(const Filename &n) const {
  return name != n.name && path_delimiter != n.path_delimiter;
}

void Filename::set_name(const std::string &n) { name = n; }

void Filename::set_path_delimiter(const std::string &delim) {
  path_delimiter = delim;
}

std::vector<std::string> Filename::split() const {
  Tokenizer tokenizer{path_delimiter};
  return tokenizer.tokenize(name);
}

// Friends
std::ostream& operator<<(std::ostream &out, const Filename &n) {
  return out << n.name;
}


text:
/*eslint no-process-env:0, new-cap:0*/
/*global require, exports*/

(function () {
  'use strict';

  var fs = require('fs');
  var CoffeeScript = require('coffee-script');
  var CoffeeLint = require('coffeelint/lib/coffeelint');
  var Configfinder = require('coffeelint/lib/configfinder');

  var currentConfig;
  var currentProjectRoot;
  var domainName = 'zaggino.brackets-coffeelint';
  var domainManager = null;
  var noop = function () {};

  function _setProjectRoot(projectRoot) {
    // set it to empty in case reading coffeelint.json fails
    currentConfig = null;
    // read coffeelint.json from current project
    if (!projectRoot) { return; }
    var configFilePath = projectRoot + 'coffeelint.json';
    try {
      if (fs.statSync(configFilePath).isFile()) {
        currentConfig = JSON.parse(fs.readFileSync(configFilePath, {encoding: 'utf-8'}));
      }
    } catch (e) {
      // no action required
      noop(e);
    }
  }

  require('enable-global-packages').on('ready', function () {
    // global packages are available now
    _setProjectRoot(currentProjectRoot);
  });

  function lintFile(fullPath, projectRoot) {
    if (projectRoot !== currentProjectRoot) {
      _setProjectRoot(projectRoot);
      currentProjectRoot = projectRoot;
    }
    var errorReport = new CoffeeLint.getErrorReport();
    var source = fs.readFileSync(fullPath, {encoding: 'utf-8'});
    var config = currentConfig || Configfinder.getConfig(fullPath);
    var literate = CoffeeScript.helpers.isLiterate(fullPath);
    errorReport.lint(fullPath, source, config, literate);
    return errorReport.getErrors(fullPath);
  }

  exports.init = function (_domainManager) {
    domainManager = _domainManager;

    if (!domainManager.hasDomain(domainName)) {
      domainManager.registerDomain(domainName, {
        major: 0,
        minor: 1
      });
    }

    domainManager.registerCommand(
      domainName,
      'lintFile', // command name
      lintFile, // handler function
      false, // is not async
      'lint given file with eslint', // description
      [
        {
          name: 'fullPath',
          type: 'string'
        },
        {
          name: 'projectRoot',
          type: 'string'
        }
      ], [
        {
          name: 'report',
          type: 'object'
        }
      ]
    );

  };

}());


text:
set -x

cur=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)
. ${cur}/../../functestslib.sh

SF_ROOT=${SF_ROOT:-"/root/puppet-bootstrapper"}
SF_SUFFIX=${SF_SUFFIX:-"tests.dom"}

function run {
    local cmd=$1
    ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@`get_ip puppetmaster` "cd puppet-bootstrapper/tools/provisioner_checker; SF_SUFFIX=${SF_SUFFIX} SF_ROOT=${SF_ROOT} python $cmd.py"
    ERROR=$?
}

run $1
exit $[ ${ERROR} ]


text:
@implementation MongoConnection (Diagnostics)

- (NSDictionary *) serverBuildInfo {
    return [self runCommandWithName:@"buildInfo" onDatabaseName:@"admin" error:nil];
}

- (NSString *) serverVersion {
    return [[self serverBuildInfo] objectForKey:@"version"];
}

- (NSUInteger) serverMaxBSONObjectSize {
    return [[[self serverBuildInfo] objectForKey:@"maxBsonObjectSize"] unsignedIntegerValue];
}

- (NSDictionary *) serverReplicationInfo {
    return [self runCommandWithName:@"isMaster" onDatabaseName:@"admin" error:nil];
}

- (NSDictionary *) serverStatus {
    return [self runCommandWithName:@"serverStatus" onDatabaseName:@"admin" error:nil];
}

- (NSDictionary *) storageStatisticsForDatabaseName:(NSString *) databaseName
                                              scale:(NSUInteger) scale {
    OrderedDictionary *command = [OrderedDictionary dictionary];
    [command setObject:@1 forKey:@"dbStats"];
    [command setObject:@(scale) forKey:@"scale"];

    return [self runCommandWithOrderedDictionary:command onDatabaseName:databaseName error:nil];
}

+ (NSString *) _stringForFilterOption:(MongoLogFilterOption) filterOption {
    switch (filterOption) {
        case MongoLogFilterOptionGlobal: return @"global";
        case MongoLogFilterOptionReplicaSet: return @"rs";
        case MongoLogFilterOptionStartupWarnings: return @"startupWarnings";
        default: return nil;
    }
}

- (NSArray *) serverLogMessagesWithFilter:(MongoLogFilterOption) filterOption {
    NSString *filterOptionString = [self.class _stringForFilterOption:filterOption];
    if (!filterOptionString)
        [NSException raise:NSInvalidArgumentException format:@"Invalid filter option"];

    NSDictionary *response = [self runCommandWithName:@"getLog"
                                                value:filterOptionString
                                            arguments:nil
                                       onDatabaseName:@"admin"
                                                error:nil];
    return [response objectForKey:@"log"];
}

- (NSArray *) allDatabases {
    NSDictionary *dict = [self runCommandWithName:@"listDatabases" onDatabaseName:@"admin" error:nil];
    NSMutableArray *result = [NSMutableArray array];
    for (NSDictionary *db in [dict objectForKey:@"databases"])
        [result addObject:[db objectForKey:@"name"]];
    return [NSArray arrayWithArray:result];
}

- (NSArray *) allCommands {
    NSDictionary *dict = [self runCommandWithName:@"listCommands" onDatabaseName:@"admin" error:nil];
    return [dict objectForKey:@"commands"];
}

- (BOOL) pingWithError:(NSError * __autoreleasing *) outError {
    NSError *error = nil;
    [self runCommandWithName:@"ping" onDatabaseName:@"admin" error:&error];
    if (outError) *outError = error;
    return error == nil;
}

@end


text:
Note=Article 2.2 Annotation: Data sharing activities involve many technical aspects, but the parties should identify the principles that they want the data sharing to reflect. The Model Agreement provides principles associated with effective and fair data sharing activities. Including such guiding principles in the data sharing agreement allows these principles to inform how the parties implement data and benefits sharing and interact with each other.

Ti=Principles

Intro.sec=Through this {_Agreement}, the {_Parties} create and will implement shared rules and cooperative mechanisms that are:

Legitimate.=[G/ChathamHouseOrg/DataSharing/Sec/PurposeAndPrinciples/Principles/Legitimate/0.md]

Effective.=[G/ChathamHouseOrg/DataSharing/Sec/PurposeAndPrinciples/Principles/Effective/0.md]

Transparent.=[G/ChathamHouseOrg/DataSharing/Sec/PurposeAndPrinciples/Principles/Transparent/0.md]

Sustainable.=[G/ChathamHouseOrg/DataSharing/Sec/PurposeAndPrinciples/Principles/Sustainable/0.md]

PrivacyPreserving.=[G/ChathamHouseOrg/DataSharing/Sec/PurposeAndPrinciples/Principles/PrivacyPreserving/0.md]

Equitable.=[G/ChathamHouseOrg/DataSharing/Sec/PurposeAndPrinciples/Principles/Equitable/0.md]

=[G/Z/ol/Base]

Extro.sec=These principles shall inform the interpretation and implementation of the {_Agreement}, including public health surveillance data and benefits sharing activities conducted under it, the resolution of disputes that may arise, and any decision to terminate the {_Agreement}.

sec={Intro.sec}

{Legitimate.sec};
{Effective.sec};
{Transparent.sec};
{Sustainable.sec};
{PrivacyPreserving.sec}; and
{Equitable.sec}.
{Extro.sec}

=[G/Z/ol-a/s6]


text:
title: Announcing netzmq
layout: post
redirect_from:
 - /post/14298996994/announcing-netzmq
---

Whether or not it was necessary, the world now has another set of .NET bindings for [ZeroMQ](http://www.zeromq.org/).

[netzmq][netzmq-repo], a project that I've been working on for the past two months, is ready for alpha testing. It has not been hardened for production use, but that's what I plan to do for the next two months (or so).

If you're feeling brave, you can reference the [NuGet package][netzmq-nuget] or clone the [repository][netzmq-repo].

## Doesn't this already exist?

Short answer: no with an "if", long answer: yes with a "but".[^rev]

The [official .NET bindings](https://github.com/zeromq/clrzmq2) work. They are still officially maintained, though the pull requests are slowly piling up. The API itself strays from modern, idiomatic C# in that it relies on global static variables and does not provide interfaces, which makes unit testing quite challenging. Finally, the Any CPU platform is not supported[^pull], so client projects must target x86 or x64 explicitly.

These are not deal breakers.

Maintainers can be added to deal with pull requests. Client projects can create socket wrappers for testing purposes. And x86 is [probably good enough][anycpu-trouble] until we start sending 2GB+ messages, at which point we can recompile for x64.

But, as is the wont of a naïve programmer, I decided to toss it all and start from scratch. The result is netzmq.

## Why use netzmq?

Allow me to enumerate:

1. Clean API — behavioural interfaces, inversion of control and no global variables. Test and mock to your heart's content. Note that client projects must manage ZMQ Context lifetime scopes manually, which a good DI library can help with.

2. Any CPU — it can be advantageous for .NET projects to target the Any CPU platform, especially in heterogeneous deployment environments. Since ZMQ is a native C library and Windows does not support universal binaries, libzmq must be compiled separately for 32-bit and 64-bit platforms. Normally, this restriction would bubble up to netzmq, but I circumvented it with magic a common technique that is beyond the scope of this post. The downsides are increased complexity on the native/manged boundary and a small performance hit on application start, but the resulting flexibility is worth it.

3. Performance — instead of traditional P/Invoke interop, netzmq uses a C++/CLI proxy project to interface with libzmq. Aside from a 10-15% performance boost[^cit], this also keeps the API layer decoupled from the interop layer (read: more testable). In the future, a P/Invoke-based interop layer can be added to target the Mono CLR, which does not support C++/CLI Mixed mode.

More fact than feature, but netzmq currently targets libzmq-3.0, which is nearing an official release. An effort will be made to always support the latest stable libzmq while providing support for legacy releases, where appropriate.

## The road to 1.0

The ZMQ API is quite small, so netzmq already supports all core functionality and the basic devices. Most of the work in the next couple months will be writing documentation and examples, as well as a P/Invoke-based interop layer for Mono support. Along the way, the ZMQ lat/thr programs will be added for your benchmarking pleasure.

Now for a *caveat emptor*: until netzmq has been rigorously field tested, **please do not use it in mission-critical systems**. Play with it, break it and log issues on [GitHub][netzmq-repo], but do not use it to build your multi-million dollar high frequency trading system.

At least not yet.

[^rev]: Reverend Lovejoy, paraphrased
[^pull]: My pull request deals with this, albeit naively. netzmq's implementation is more robust.
[^cit]: \[Citation needed\]

[netzmq-repo]: https://github.com/jgoz/netzmq
[netzmq-nuget]: http://nuget.org/List/Packages/netzmq
[anycpu-trouble]: http://blogs.msdn.com/b/rmbyers/archive/2009/06/09/anycpu-exes-are-usually-more-trouble-then-they-re-worth.aspx