text:
'use strict';

var deferred = require('deferred')
  , resolve  = require('path').resolve
  , path     = resolve(__dirname, '../__playground/lib/lintignore-mode');

module.exports = function (t, a) {
	var mode = require('fs2/lib/ignore-modes').lint;

	a(mode.filename, '.lintignore', "Filename");
	return {
		Regular: function (a, d) {
			deferred(mode.isRoot(resolve(path, 'foo'))(function (result) {
				a(result, false);
			}), mode.isRoot(resolve(path))(function (result) {
				a(result, true);
			}))(false).done(d, d);
		},
		Watch: function (a, d) {
			var w1, w2;
			w1 = mode.isRootWatcher(resolve(path, 'foo'));
			w2 = mode.isRootWatcher(resolve(path));
			deferred(w1(function (result) { a(result, false); }),
				w2(function (result) { a(result, true); }))(function () {
				w1.close();
				w2.close();
			}).done(d, d);
		}
	};
};


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" >

    <!-- Author Image | Author Name / Story | Time -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageButton
            android:id="@+id/overflow_button"
            style="?attr/buttonBarButtonStyle"
            android:layout_width="@dimen/dip_48"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:contentDescription="@string/more"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:src="?attr/cardOverflowIcon" />

        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/author_data"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/overflow_button"
            android:background="@android:color/transparent"
            android:baselineAligned="false"
            android:orientation="horizontal"
            android:paddingBottom="@dimen/klyph_stream_item_profile_padding"
            android:paddingLeft="@dimen/klyph_stream_item_profile_padding"
            android:paddingTop="@dimen/klyph_stream_item_profile_padding" >

            <com.abewy.android.apps.klyph.widget.ProfileImageView
                android:id="@+id/author_profile_image"
                android:layout_width="@dimen/profile_image_size"
                android:layout_height="@dimen/profile_image_size"
                android:layout_centerVertical="true" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="@dimen/klyph_stream_item_profile_padding"
                android:layout_marginRight="@dimen/klyph_stream_item_profile_padding"
                android:background="@android:color/transparent"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/story"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@android:color/transparent"
                    android:textColor="?android:attr/textColorSecondary" />

                <TextView
                    android:id="@+id/post_time"
                    style="@style/Klyph.Stream.TimeText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/shared_author_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="@dimen/klyph_stream_item_part_padding" >

        <View
            android:id="@+id/divider"
            style="@style/Klyph.ListItem.Separator.Thin"
            android:layout_width="match_parent"
            android:layout_marginBottom="@dimen/ckoobafe_stream_item_padding"
            android:layout_marginLeft="0dip"
            android:layout_marginRight="0dip"
            android:layout_marginTop="0dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:baselineAligned="false"
            android:orientation="horizontal" >

            <com.abewy.android.apps.klyph.widget.ProfileImageView
                android:id="@+id/shared_author_profile_image"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginLeft="@dimen/klyph_stream_item_profile_padding" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:orientation="vertical"
                android:paddingLeft="@dimen/ckoobafe_stream_item_padding"
                android:paddingRight="@dimen/ckoobafe_stream_item_padding" >

                <TextView
                    android:id="@+id/shared_story"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="?android:attr/textColorSecondary" />

                <TextView
                    android:id="@+id/shared_post_time"
                    style="@style/Klyph.Stream.TimeText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

    <!-- Message -->

    <TextView
        android:id="@+id/message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="@android:color/transparent"
        android:ellipsize="end"
        android:lineSpacingMultiplier="1.3"
        android:paddingBottom="@dimen/klyph_stream_item_part_padding"
        android:textColor="?android:attr/textColorSecondary"
        android:textIsSelectable="false" />

    <!-- Image -->

    <FrameLayout
        android:id="@+id/post_photo_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.abewy.android.extended.widget.RatioImageView
            android:id="@+id/post_photo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitXY" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="4dp"
            android:background="@color/black_60_percent"
            android:orientation="vertical"
            android:padding="4dp" >

            <TextView
                android:id="@+id/post_video_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="2"
                android:paddingLeft="2dip"
                android:paddingRight="2dip"
                android:textColor="@color/white"
                android:textSize="@dimen/klyph_stream_video_title" />

            <TextView
                android:id="@+id/post_video_url"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="2"
                android:paddingLeft="2dip"
                android:paddingRight="2dip"
                android:textColor="@color/white"
                android:textSize="@dimen/klyph_stream_video_desc" />
        </LinearLayout>

        <ImageView
            android:id="@+id/post_video_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="?attr/playOverVideoIcon" />
    </FrameLayout>

    <!-- Album -->

    <it.sephiroth.android.library.widget.HListView
        android:id="@+id/stream_album"
        android:layout_width="match_parent"
        android:layout_height="@dimen/klyph_stream_album_height"
        app:dividerWidth="0dip" />

    <!-- Link / Video / App -->

    <FrameLayout
        android:id="@+id/stream_link"
        android:layout_width="match_parent"
        android:layout_height="@dimen/stream_link_height"
        android:foreground="?attr/streamSelector" >

        <com.abewy.android.apps.klyph.widget.KlyphImageView
            android:id="@+id/stream_link_image_background"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop" />

        <com.abewy.android.apps.klyph.widget.KlyphImageView
            android:id="@+id/post_picture_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="?attr/playOverVideoIcon" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="#99000000"
            android:orientation="vertical"
            android:padding="@dimen/stream_link_padding" >

            <TextView
                android:id="@+id/post_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="2"
                android:textColor="@android:color/white"
                android:textSize="@dimen/stream_link_title_size"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/post_caption"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="marquee"
                android:maxLines="2"
                android:textColor="@android:color/white"
                android:textStyle="normal" />

            <TextView
                android:id="@+id/post_description"
                style="@style/Klyph.ListItem.SecondaryText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="all"
                android:ellipsize="end"
                android:maxLines="3"
                android:textColor="@color/dark_theme_tertiary"
                android:textSize="12sp" />
        </LinearLayout>
    </FrameLayout>

    <!-- Action Bar -->

    <LinearLayout
        android:id="@+id/button_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <View
            android:id="@+id/button_bar_divider"
            style="@style/Klyph.ListItem.Separator"
            android:layout_marginBottom="0dp"
            android:layout_marginLeft="1dip"
            android:layout_marginRight="1dip"
            android:layout_marginTop="0dp" />

        <include layout="@layout/include_button_bar" />
    </LinearLayout>

</merge>

redpajama_set_name: RedPajamaGithub


text:
import { select, format, time } from 'd3';

export default function drawPoints(marks) {
    let chart = this;
    let config = this.config;

    let point_supergroups = this.svg
        .selectAll('.point-supergroup')
        .data(marks, (d, i) => i + '-' + d.per.join('-'));

    point_supergroups.enter().append('g').attr('class', d => 'supergroup point-supergroup ' + d.id);

    point_supergroups.exit().remove();

    let points = point_supergroups.selectAll('.point').data(d => d.data, d => d.key);
    let oldPoints = points.exit();

    let oldPointsTrans = config.transitions
        ? oldPoints.selectAll('circle').transition()
        : oldPoints.selectAll('circle');
    oldPointsTrans.attr('r', 0);

    let oldPointGroupTrans = config.transitions ? oldPoints.transition() : oldPoints;
    oldPointGroupTrans.remove();

    let nupoints = points.enter().append('g').attr('class', d => d.key + ' point');
    nupoints.append('circle').attr('class', 'wc-data-mark').attr('r', 0);
    nupoints.append('title');
    //static attributes
    points
        .select('circle')
        .style('clip-path', `url(#${chart.id})`)
        .attr(
            'fill-opacity',
            config.fill_opacity || config.fill_opacity === 0 ? config.fill_opacity : 0.6
        )
        .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]))
        .attr('stroke', d => this.colorScale(d.values.raw[0][config.color_by]));
    //attach mark info
    points.each(function(d) {
        let mark = select(this.parentNode).datum();
        d.mark = mark;
        select(this).select('circle').attr(mark.attributes);
    });
    //animated attributes
    let pointsTrans = config.transitions
        ? points.select('circle').transition()
        : points.select('circle');
    pointsTrans
        .attr('r', d => d.mark.radius || config.flex_point_size)
        .attr('cx', d => {
            let x_pos = this.x(d.values.x) || 0;
            return config.x.type === 'ordinal' ? x_pos + this.x.rangeBand() / 2 : x_pos;
        })
        .attr('cy', d => {
            let y_pos = this.y(d.values.y) || 0;
            return config.y.type === 'ordinal' ? y_pos + this.y.rangeBand() / 2 : y_pos;
        });

    points.select('title').text(d => {
        let tt = d.mark.tooltip || '';
        let xformat = config.x.summary === 'percent'
            ? format('0%')
            : config.x.type === 'time' ? time.format(config.x.format) : format(config.x.format);
        let yformat = config.y.summary === 'percent'
            ? format('0%')
            : config.y.type === 'time' ? time.format(config.y.format) : format(config.y.format);
        return tt
            .replace(
                /\$x/g,
                config.x.type === 'time' ? xformat(new Date(d.values.x)) : xformat(d.values.x)
            )
            .replace(
                /\$y/g,
                config.y.type === 'time' ? yformat(new Date(d.values.y)) : yformat(d.values.y)
            )
            .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig]);
    });

    //Link to the d3.selection from the data
    point_supergroups.each(function(d) {
        d.supergroup = select(this);
        d.groups = d.supergroup.selectAll('g.point');
        d.circles = d.groups.select('circle');
    });

    return points;
}


text:
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
//

var insertSight = function(db, options){
	var travelSight = options.data;
	db.collection('countryInfo').updateOne(
	{
		"countryName" : options.countryName
	},
	{
		"$addToSet": {"travel": travelSight}
	}, function(err, result){
		assert.equal(err, null);
		// If a film was added (i.e. the film didn't already exist)
		if(result.result.nModified == 1){
			totalSights(db, null, function(totalNumberOfSights){
				options.io.sockets.emit("updateTravelTotal", {total: totalNumberOfSights});
			})
			// socketsService().totalFilms(options.client);
			console.log("Inserted " + travelSight.sightName + " into " + options.countryName);
		}
	})
}

var totalSights = function(db, options, callback){
	var cursor = db.collection('countryInfo').find();
	var numberOfSights = 0;
    cursor.each(function(err, doc) {
	    assert.equal(err, null);

	    if (doc && doc.travel) {

	    	numberOfSights += doc.travel.length;
        } else if (doc == null) {
	      	callback(numberOfSights);
	    }
    });
}

//
var selectSights = function(db, options, callback){
	var cursor = db.collection('countryInfo').find( { "countryName": options.countryName } );

    cursor.each(function(err, doc) {
	    assert.equal(err, null);

	    if (doc && doc.travel && doc.travel.length > 0) {
	    	var l = doc.travel.length;
	        // film = doc.films[Math.floor(Math.random()*l)];
	        callback(doc.travel);
        } else if (doc != null) {
	      	// this will always get run - after the last object
	      	// is reached there will be a null object
	      	var travel = [];
	      	callback(travel);
	    }
    });

}

var travelAccess = function(){

	return {
		selectSights : selectSights,
		insertSight : insertSight,
		totalSights : totalSights
	}
}

module.exports = travelAccess;


text:
import { FlutterCapabilities } from "../capabilities/flutter";

export function getFutterWebRenderer(flutterCapabilities: FlutterCapabilities, renderer: "auto" | "html" | "canvaskit") {
	if (!flutterCapabilities.supportsWebRendererOption)
		return;

	if (!renderer || renderer === "auto")
		return;

	return renderer;
}


text:
function f = abs(f, varargin)
%ABS   Absolute value of a CHEBTECH object.
%   ABS(F) returns the absolute value of F, where F is a CHEBTECH object with no
%   roots in [-1 1]. If ~isempty(roots(F)), then ABS(F) will return garbage
%   with no warning. F may be complex.

%  Copyright 2014 by The University of Oxford and The Chebfun Developers.
%  See http://www.chebfun.org/ for Chebfun information.

if ( isreal(f) || isreal(1i*f) )
    % Convert to values and then compute ABS().
    values = f.coeffs2vals(f.coeffs);
    values = abs(values);
    f.coeffs = f.vals2coeffs(values);
else
    f = compose(f, @abs, [], [], varargin{:});
end

end


text:
import nuke
import imath
import IECore

__getters = {}
__setters = {}

##########################################################################
# public functions
##########################################################################

def registerAccessors( knobType, get, set = None ) :

	assert( not knobType in __getters )
	__getters[knobType] = get

	if set :
		assert( not knobType in __setters )
		__setters[knobType] = set

## \todo Support more knob types
def getKnobValue( knob, **kwArgs ) :

	f = __getters.get( knob.__class__, None )
	if not f :
		raise RuntimeError( "No get accessor registered for type %s", str( knob.__class__ ) )

	return f( knob, **kwArgs )

def setKnobValue( knob, value, **kwArgs ) :

	f = __setters.get( knob.__class__, None )
	if not f :
		raise RuntimeError( "No set accessor registered for type %s", str( knob.__class__ ) )

	return f( knob, value, **kwArgs )

##########################################################################
# accessor implementations
##########################################################################

# XY Knob

def __getXY( knob, resultType=imath.V2f ) :

	return resultType( knob.getValue( 0 ), knob.getValue( 1 ) )

def __setXY( knob, value ) :

	knob.setValue( value[0], 0 )
	knob.setValue( value[1], 1 )

registerAccessors( nuke.XY_Knob, __getXY, __setXY )

# XYZ Knob

def __getXYZ( knob, resultType=imath.V3f ) :

	return resultType( knob.getValue( 0 ), knob.getValue( 1 ), knob.getValue( 2 ) )

def __setXYZ( knob, value ) :

	knob.setValue( value[0], 0 )
	knob.setValue( value[1], 1 )
	knob.setValue( value[2], 2 )

registerAccessors( nuke.XYZ_Knob, __getXYZ, __setXYZ )
registerAccessors( nuke.Scale_Knob, __getXYZ, __setXYZ )

# Color Knob

def __getColor( knob, resultType=imath.Color3f ) :

	return resultType( knob.getValue( 0 ), knob.getValue( 1 ), knob.getValue( 2 ) )

def __setColor( knob, value ) :

	knob.setValue( value[0], 0 )
	knob.setValue( value[1], 1 )
	knob.setValue( value[2], 2 )

registerAccessors( nuke.Color_Knob, __getColor, __setColor )

# String Knob

def __getString( knob, resultType=str ) :

	return resultType( knob.getText() )

def __setString( knob, value ) :

	knob.setValue( str( value ) )

registerAccessors( nuke.EvalString_Knob, __getString, __setString )

# Box3 Knob

def __getBox3( knob, resultType=imath.Box3f ) :

	vectorType = imath.V3f
	if resultType == imath.Box3d :
		vectorType = imath.V3d

	value = knob.getValue()
	return resultType( vectorType( *value[:3] ), vectorType( *value[3:] ) )

def __setBox3( knob, value ) :

	knob.setX( value.min[0] )
	knob.setY( value.min[1] )
	knob.setN( value.min[2] )

	knob.setR( value.max[0] )
	knob.setT( value.max[1] )
	knob.setF( value.max[2] )

registerAccessors( nuke.Box3_Knob, __getBox3, __setBox3 )


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>src/transport/NodeMqttTransport.js - webduino-js</title>
    <link rel="stylesheet" href="">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="stylesheet" href="../assets/css/custom.css">
    <link rel="stylesheet" href="../assets/css/lucid.css">
    <link rel="stylesheet" href="../assets/vendor/bootstrap/css/bootstrap.css">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            webduino-js

                    API Docs for Version: 0.7.0

        <form class="navbar-form pull-right" style="line-height: 40px; height: 40px;">
            <input style="margin-top: 0;" type="text" class="search-query" placeholder="Search for classes/modules..." data-obj='["classes/webduino.Board", "classes/webduino.EventEmitter", "classes/webduino.Module", "classes/webduino.module.ADXL345", "classes/webduino.module.Barcode", "classes/webduino.module.Button", "classes/webduino.module.Buzzer", "classes/webduino.module.Dht", "classes/webduino.module.HX711", "classes/webduino.module.IRLed", "classes/webduino.module.IRRecv", "classes/webduino.module.Led", "classes/webduino.module.Max7219", "classes/webduino.module.Photocell", "classes/webduino.module.RFID", "classes/webduino.module.RGBLed", "classes/webduino.module.Soil", "classes/webduino.module.Ultrasonic", "classes/webduino.Transport", "classes/webduino.transport.MqttTransport", "classes/webduino.transport.NodeMqttTransport"]'>
        </form>

webduino.Board

webduino.EventEmitter

webduino.Module

webduino.module.ADXL345

webduino.module.Barcode

webduino.module.Button

webduino.module.Buzzer

webduino.module.Dht

webduino.module.HX711

webduino.module.IRLed

webduino.module.IRRecv

webduino.module.Led

webduino.module.Max7219

webduino.module.Photocell

webduino.module.RFID

webduino.module.RGBLed

webduino.module.Soil

webduino.module.Ultrasonic

webduino.Transport

webduino.transport.MqttTransport

webduino.transport.NodeMqttTransport

    <form id="options-form" class="form-inline pull-right">
        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

    </form>

src/transport/NodeMqttTransport.js File

'use strict';

var mqtt = require('mqtt'),
  webduino = require('../webduino');

var push = Array.prototype.push;

var Transport = webduino.Transport,
  TransportEvent = webduino.TransportEvent,
  util = webduino.util,
  proto;

var STATUS = {
  OK: 'OK'
};

var TOPIC = {
  PING: '/PING',
  PONG: '/PONG',
  STATUS: '/STATUS'
};

var MQTT_EVENTS = {
  CONNECT: 'connect',
  MESSAGE: 'message',
  CLOSE: 'close',
  ERROR: 'error'
};

/**
 * Conveying messages over MQTT protocol, in Node.JS.
 *
 * @namespace webduino.transport
 * @class NodeMqttTransport
 * @constructor
 * @param {Object} options Options to build a proper transport
 * @extends webduino.Transport
 */
function NodeMqttTransport(options) {
  Transport.call(this, options);

  this._options = options;
  this._client = null;
  this._sendTimer = null;
  this._buf = [];

  this._status = '';

  this._connHandler = onConnect.bind(this);
  this._messageHandler = onMessage.bind(this);
  this._sendOutHandler = sendOut.bind(this);
  this._disconnHandler = onDisconnect.bind(this);
  this._errorHandler = onError.bind(this);

  init(this);
}

function init(self) {
  self._client = mqtt.connect(self._options.server, {
    clientId: '_' + self._options.device + (self._options.multi ? '.' + util.randomId() : ''),
    username: self._options.login || '',
    password: Buffer.from(self._options.password || ''),
    keepalive: NodeMqttTransport.KEEPALIVE_INTERVAL,
    reconnectPeriod: self._options.autoReconnect ? NodeMqttTransport.RECONNECT_PERIOD * 1000 : 0,
    connectTimeout: NodeMqttTransport.CONNECT_TIMEOUT * 1000
  });
  self._client.on(MQTT_EVENTS.CONNECT, self._connHandler);
  self._client.on(MQTT_EVENTS.MESSAGE, self._messageHandler);
  self._client.on(MQTT_EVENTS.CLOSE, self._disconnHandler);
  self._client.on(MQTT_EVENTS.ERROR, self._errorHandler);
}

function onConnect() {
  this._client.subscribe(this._options.device + TOPIC.PONG);
  this._client.subscribe(this._options.device + TOPIC.STATUS);
}

function onMessage(topic, message) {
  try {
    var dest = topic,
      oldStatus = this._status;

    switch (dest.substr(dest.lastIndexOf('/') + 1)) {

    case 'STATUS':
      this._status = message.toString();
      detectStatusChange(this, this._status, oldStatus);
      break;

    default:
      (this._status === STATUS.OK) && this.emit(TransportEvent.MESSAGE, message);
      break;

    }
  } catch (err) {
    this.emit(TransportEvent.ERROR, err);
  }
}

function detectStatusChange(self, newStatus, oldStatus) {
  if (newStatus === oldStatus) {
    if (newStatus === STATUS.OK) {
      // Device reconnected
      self.emit(TransportEvent.REOPEN);
    }
    return;
  }

  if (newStatus === STATUS.OK) {
    self.emit(TransportEvent.OPEN);
  } else {
    self.emit(TransportEvent.ERROR, new Error('board connection failed.'));
  }
}

function onDisconnect() {
  if (this._client.disconnecting || !this._options.autoReconnect) {
    this._client.removeAllListeners();
    delete this._client;
    this.emit(TransportEvent.CLOSE);
  }
}

function onError(error) {
  this.emit(TransportEvent.ERROR, error);
}

function sendOut() {
  var payload = Buffer.from(this._buf);
  this.isOpen && this._client.publish(this._options.device + TOPIC.PING, payload, {
    qos: 0
  });
  clearBuf(this);
}

function clearBuf(self) {
  self._buf = [];
  clearImmediate(self._sendTimer);
  self._sendTimer = null;
}

NodeMqttTransport.prototype = proto = Object.create(Transport.prototype, {

  constructor: {
    value: NodeMqttTransport
  },

  isOpen: {
    get: function () {
      return this._client && this._client.connected;
    }
  }

});

proto.send = function (payload) {
  if (this._buf.length + payload.length + this._options.device.length + TOPIC.PING.length + 4 >
    NodeMqttTransport.MAX_PACKET_SIZE) {
    this._sendOutHandler();
  }
  push.apply(this._buf, payload);
  if (!this._sendTimer) {
    this._sendTimer = setImmediate(this._sendOutHandler);
  }
};

proto.close = function () {
  if (this._client) {
    if (this._client.connected) {
      this._client.end();
    } else {
      this._client.removeAllListeners();
      delete this._client;
    }
  }
};

proto.flush = function () {
  if (this._buf && this._buf.length) {
    this._sendOutHandler();
  }
};

/**
 * Reconnect period when MQTT connection goes down. Measured in seconds.
 *
 * @property RECONNECT_PERIOD
 * @type {Number}
 * @static
 */
NodeMqttTransport.RECONNECT_PERIOD = 1;

/**
 * MQTT keepalive interval. Measured in seconds.
 *
 * @property KEEPALIVE_INTERVAL
 * @type {Number}
 * @static
 */
NodeMqttTransport.KEEPALIVE_INTERVAL = 15;

/**
 * Time to wait before throwing connection timeout exception. Measured in seconds.
 *
 * @property CONNECT_TIMEOUT
 * @type {Number}
 * @static
 */
NodeMqttTransport.CONNECT_TIMEOUT = 30;

/**
 * Maximum packet size in KB.
 *
 * @property MAX_PACKET_SIZE
 * @type {Number}
 * @static
 */
NodeMqttTransport.MAX_PACKET_SIZE = 128;

module.exports = NodeMqttTransport;


text:
using System;
using Couchbase.Lite.Store;

#if SQLITE
namespace Couchbase.Lite.Storage.SystemSQLite
#elif CUSTOM_SQLITE
namespace Couchbase.Lite.Storage.CustomSQLite
#else
namespace Couchbase.Lite.Storage.SQLCipher
#endif
{

    /// <summary>
    /// An interface for describing an object that can interface with a SQLite database
    /// </summary>
    internal interface ISQLiteStorageEngine
    {

        /// <summary>
        /// Gets the last error code encountered by SQLite (note
        /// that this does not always indicate an error)
        /// </summary>
        int LastErrorCode { get; }

        /// <summary>
        /// Opens the database
        /// </summary>
        /// <param name="path">The path where the database exists</param>
        /// <param name="readOnly">Whether or not this storage engine is readonly</param>
        /// <param name="schema">The schema to use to create the database initially</param>
        /// <param name="encryptionKey">A key for encrypting the database</param>
        bool Open(string path, bool readOnly, string schema, SymmetricKey encryptionKey);

        /// <summary>
        /// Gets the user version of the database
        /// </summary>
        /// <returns>The user version of the database</returns>
        int GetVersion();

        /// <summary>
        /// Sets the user version of the database
        /// </summary>
        /// <param name="version">The user version of the database</param>
        void SetVersion(Int32 version);

        /// <summary>
        /// Gets whether or not the database is open
        /// </summary>
        /// <value><c>true</c> if this instance is open; otherwise, <c>false</c>.</value>
        bool IsOpen { get; }

        bool InTransaction { get; }

        bool RunInTransaction(RunInTransactionDelegate block);

        /// <summary>
        /// Executes a SQL command (modification)
        /// </summary>
        /// <param name="sql">The SQL format string</param>
        /// <param name="paramArgs">The SQL string arguments</param>
        int ExecSQL(string sql, params object[] paramArgs);

        /// <summary>
        /// Executes a SQL query (i.e. the changes in the current transaction will not be shown)
        /// </summary>
        /// <returns>An iterator containing the results of the query</returns>
        /// <param name="sql">The SQL format string</param>
        /// <param name="paramArgs">The SQL string arguments</param>
        Cursor RawQuery(string sql, params Object[] paramArgs);

        /// <summary>
        /// Performs an INSERT operation
        /// </summary>
        /// <param name="table">The table to insert into</param>
        /// <param name="nullColumnHack">Reserved</param>
        /// <param name="values">The values to insert</param>
        /// <returns>The ID of the inserted object</returns>
        /// <remarks>
        /// If the data already exists this method will throw an exception
        /// </remarks>
        long Insert(string table, string nullColumnHack, ContentValues values);

        /// <summary>
        /// Performs an INSERT operation with a strategy for handling existing data
        /// </summary>
        /// <returns>The ID of the inserted row</returns>
        /// <param name="table">The table to insert into</param>
        /// <param name="nullColumnHack">Reserved</param>
        /// <param name="initialValues">The values to insert</param>
        /// <param name="conflictResolutionStrategy">The strategy to use when data already exists</param>
        long InsertWithOnConflict(string table, string nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy);

        /// <summary>
        /// Performs an UPDATE operation
        /// </summary>
        /// <param name="table">The table to update</param>
        /// <param name="values">The new values</param>
        /// <param name="whereClause">The formatted where clause (i.e. WHERE foo = bar)</param>
        /// <param name="whereArgs">The formatted where args</param>
        /// <returns>The number of rows updated</returns>
        int Update(string table, ContentValues values, string whereClause, params String[] whereArgs);

        /// <summary>
        /// Performs a DELETE operation
        /// </summary>
        /// <param name="table">The table to delete from</param>
        /// <param name="whereClause">The formatted where clause (i.e. WHERE foo = bar)</param>
        /// <param name="whereArgs">The formatted where args</param>
        int Delete(string table, string whereClause, params String[] whereArgs);

        /// <summary>
        /// Closes the connection to the SQLite database
        /// </summary>
        void Close();
    }
}


text:
import Ember from 'ember';
import EuiInput from 'emberui/components/eui-input';

export default EuiInput;


text:
package herddb.index.blink;

import java.io.IOException;
import java.util.Map;

/**
 * @author diego.salvi
 */
public interface BLinkIndexDataStorage<X,Y> {

    public static final long NEW_PAGE = -1;

    /**
     * Load an internal node data page.
     */
    public void loadNodePage(long pageId, Map<X,Long> data) throws IOException;

    /**
     * Load a leaf node data page.
     */
    public void loadLeafPage(long pageId, Map<X,Y> data) throws IOException;

    /**
     * Create a new internal node page for given data.
     */
    public long createNodePage(Map<X,Long> data) throws IOException;

    /**
     * Create a new leaf node page for given data.
     */
    public long createLeafPage(Map<X,Y> data) throws IOException;

    /**
     * Overwrite an existing internal node page with given data.
     */
    public void overwriteNodePage(long pageId, Map<X,Long> data) throws IOException;

    /**
     * Overwrite an existing leaf node page with given data.
     */
    public void overwriteLeafPage(long pageId, Map<X,Y> data) throws IOException;

}


text:
package io.quarkus.it.resteasy.reactive.elytron;

import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;

import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;
import io.restassured.common.mapper.TypeRef;
import io.restassured.specification.RequestSpecification;

@QuarkusTest
public class FruitResourceTest {

    public static final TypeRef<List<Fruit>> FRUIT_LIST_TYPE_REF = new TypeRef<>() {
    };
    public static final TypeRef<Fruit> FRUIT_TYPE_REF = new TypeRef<>() {
    };

    @Test
    void testAllNoSecurity() {
        String path = "all-no-security";
        List<Fruit> noUserResponse = verifySuccessAndExtractFruits(path, null, FRUIT_LIST_TYPE_REF);
        assertThat(noUserResponse).containsOnly(Fruit.APPLE, Fruit.PINEAPPLE);

        List<Fruit> employeeResponse = verifySuccessAndExtractFruits(path, "john", FRUIT_LIST_TYPE_REF);
        assertThat(employeeResponse).containsOnly(Fruit.APPLE, Fruit.PINEAPPLE);

        List<Fruit> managerResponse = verifySuccessAndExtractFruits(path, "mary", FRUIT_LIST_TYPE_REF);
        assertThat(managerResponse).containsOnly(Fruit.APPLE, Fruit.PINEAPPLE);
    }

    @Test
    void testAllWithSecurity() {
        String path = "all-with-security";
        List<Fruit> noUserResponse = verifySuccessAndExtractFruits(path, null, FRUIT_LIST_TYPE_REF);
        assertThat(noUserResponse).hasSize(2).allSatisfy(f -> {
            assertThat(f.getDescription()).isNull();
            assertThat(f.getId()).isNull();
        }).extracting("name").containsOnly(Fruit.APPLE.getName(), Fruit.PINEAPPLE.getName());

        List<Fruit> employeeResponse = verifySuccessAndExtractFruits(path, "john", FRUIT_LIST_TYPE_REF);
        assertThat(employeeResponse).hasSize(2).allSatisfy(f -> {
            assertThat(f.getDescription()).isNull();
            assertThat(f.getId()).isPositive();
        }).extracting("name").containsOnly(Fruit.APPLE.getName(), Fruit.PINEAPPLE.getName());

        List<Fruit> managerResponse = verifySuccessAndExtractFruits(path, "mary", FRUIT_LIST_TYPE_REF);
        assertThat(managerResponse).containsOnly(Fruit.APPLE, Fruit.PINEAPPLE);

        List<Fruit> internResponse = verifySuccessAndExtractFruits(path, "poul", FRUIT_LIST_TYPE_REF);
        assertThat(internResponse).hasSize(2).allSatisfy(f -> {
            assertThat(f.getDescription()).isNull();
            assertThat(f.getId()).isNull();
        }).extracting("name").containsOnly(Fruit.APPLE.getName(), Fruit.PINEAPPLE.getName());
    }

    @Test
    void testSingleNoSecurity() {
        String path = "single-no-security";
        Fruit noUserResponse = verifySuccessAndExtractFruits(path, null, FRUIT_TYPE_REF);
        assertThat(noUserResponse).isEqualTo(Fruit.APPLE);

        Fruit employeeResponse = verifySuccessAndExtractFruits(path, "john", FRUIT_TYPE_REF);
        assertThat(employeeResponse).isEqualTo(Fruit.APPLE);

        Fruit managerResponse = verifySuccessAndExtractFruits(path, "mary", FRUIT_TYPE_REF);
        assertThat(managerResponse).isEqualTo(Fruit.APPLE);
    }

    @Test
    void testSingleWithSecurity() {
        String path = "single-with-security";
        Fruit noUserResponse = verifySuccessAndExtractFruits(path, null, FRUIT_TYPE_REF);
        assertThat(noUserResponse.getDescription()).isNull();
        assertThat(noUserResponse.getId()).isNull();
        assertThat(noUserResponse.getName()).isEqualTo(Fruit.APPLE.getName());

        Fruit employeeResponse = verifySuccessAndExtractFruits(path, "john", FRUIT_TYPE_REF);
        assertThat(employeeResponse.getDescription()).isNull();
        assertThat(employeeResponse.getId()).isEqualTo(Fruit.APPLE.getId());
        assertThat(employeeResponse.getName()).isEqualTo(Fruit.APPLE.getName());

        Fruit managerResponse = verifySuccessAndExtractFruits(path, "mary", FRUIT_TYPE_REF);
        assertThat(managerResponse).isEqualTo(Fruit.APPLE);

        Fruit internResponse = verifySuccessAndExtractFruits(path, "poul", FRUIT_TYPE_REF);
        assertThat(internResponse.getDescription()).isNull();
        assertThat(internResponse.getId()).isNull();
        assertThat(internResponse.getName()).isEqualTo(Fruit.APPLE.getName());
    }

    private <T> T verifySuccessAndExtractFruits(String path, String user, TypeRef<T> typeRef) {
        RequestSpecification given = given();
        if (user != null) {
            given = given.auth().preemptive().basic(user, Users.password(user));
        }
        return given
                .when()
                .get("/fruit/" + path)
                .then()
                .statusCode(200)
                .extract().body().as(typeRef);
    }
}


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SumNumbers.Startup))]
namespace SumNumbers
{
    public partial class Startup {
        public void Configuration(IAppBuilder app) {
            ConfigureAuth(app);
        }
    }
}


text:
<?php
namespace PhalconX\Enum;

use PhalconX\Exception;
use PhalconX\Test\TestCase;

class BooleanTest extends TestCase
{
    /**
     * @dataProvider booleans
     */
    public function testValueOf($value, $expect)
    {
        $val = Boolean::valueOf($value);
        // var_export([$value, $val, $expect]);
        $this->assertEquals($val, $expect);
    }

    public function booleans()
    {
        return [
            [1, true],
            ["1", true],
            ['true', true],
            [true, true],
            [0, false],
            ["0", false],
            ['false', false],
            [false, false],
            ['t', null],
            [2, null]
        ];
    }
}


text:
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using Bloop.Infrastructure.Storage;
using System.IO;

namespace Bloop.Plugin.CMD
{
    public class CMDStorage : JsonStrorage<CMDStorage>
    {
        [JsonProperty]
        public bool ReplaceWinR { get; set; }

        [JsonProperty]
        public bool LeaveCmdOpen { get; set; }

        [JsonProperty]
        public Dictionary<string, int> CMDHistory = new Dictionary<string, int>();

        protected override string ConfigFolder
        {
            get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
        }

        protected override string ConfigName
        {
            get { return "CMDHistory"; }
        }

        protected override CMDStorage LoadDefault()
        {
            ReplaceWinR = true;
            return this;
        }

        public void AddCmdHistory(string cmdName)
        {
            if (CMDHistory.ContainsKey(cmdName))
            {
                CMDHistory[cmdName] += 1;
            }
            else
            {
                CMDHistory.Add(cmdName, 1);
            }
            Save();
        }

    }
}


text:
Example of a .NET Core implementation of the new Bungie Auth

This is a simple example of how to use the new Bungie OAuth authentication in .NET.
This example is made in .NET Core, but should work as a base for anything else C#.

Please note the following:

-  __Is not meant to be highly secure__. Just Works
-  I'm not using any best practices or something like that. Again, just works.
- Any question related to this, should be made on GitHub, or the Bungie.net's dev community.

Somehow my project creation flow managed to avoid licensing stuff. __This is MIT licensed__.

## References:
- User Secrets: https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets
- .NET new Configuration stuff: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

## Running the Example
- Clone the Repo. You're here, you should know how it works.
- Restore the thing, using dotnet restore
- Save the API Key and your Auth URL (from https://bungie.net/developer) into the UserSecrets storage (https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets).
     - Use "ApiKey" and "AuthURL" to store string values.
     - You might want to run the site first to get the URL Visual Studio / Kestrel gives you. If on Mac or Linux, should be something like https://localhost:5000/. On Windows it's the same unless you run it on Visual Studio (full).
- Run the thing. Should work.


text:
namespace tao::json
{
   template< typename T, typename... Ts >
   struct deque_traits
      : internal::array_traits< std::deque< T, Ts... > >
   {
      template< template< typename... > class Traits, typename... With >
      static void to( const basic_value< Traits >& v, std::deque< T, Ts... >& r, With&... with )
      {
         const auto& a = v.get_array();
         for( const auto& i : a ) {
            r.emplace_back( i.template as_with< T >( with... ) );
         }
      }

      template< template< typename... > class Traits, typename Producer >
      static void consume( Producer& parser, std::vector< T, Ts... >& v )
      {
         auto s = parser.begin_array();
         while( parser.element_or_end_array( s ) ) {
            v.emplace_back( json::consume< T, Traits >( parser ) );
         }
      }
   };

}  // namespace tao::json

#endif


text:
export default function () {
  'ngInject'
  return {
    restrict: 'A',
    controller: function ($scope, $element, $attrs) {
      'ngInject'
      let scopeVariable = $attrs.ganttContainerWidthListener
      if (scopeVariable === '') {
        scopeVariable = 'ganttContainerWidth'
      }

      let effectiveScope = $scope

      while (scopeVariable.indexOf('$parent.') === 0) {
        scopeVariable = scopeVariable.substring('$parent.'.length)
        effectiveScope = effectiveScope.$parent
      }

      effectiveScope.$watch(function () {
        let el = $element[0].parentElement ? $element[0].parentElement.parentElement : undefined
        if (el) {
          let width = el.offsetWidth

          let style = getComputedStyle(el)
          width = width - parseInt(style.marginLeft, 10) - parseInt(style.marginRight, 10)

          return width
        }
        return 0
      }, function (newValue) {
        if (newValue > 0) {
          effectiveScope[scopeVariable] = newValue
        }
      })
    }
  }
}


text:
#pragma checksum "C:\Users\DonCampos\Source\Workspaces\InfoApp\InfoAppWindows8\App8\App8.Windows\SchoolActivities.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "3832373609D898E33544AD9CE374B2FF"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace App8
{
    partial class SchoolActivities : global::Windows.UI.Xaml.Controls.Page
    {
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private global::Windows.UI.Xaml.Controls.Page pageRoot;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private global::Windows.UI.Xaml.Controls.FlipView FlipView1;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private global::Windows.UI.Xaml.Controls.Button backButton;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private global::Windows.UI.Xaml.Controls.TextBlock pageTitle;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private bool _contentLoaded;

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent()
        {
            if (_contentLoaded)
                return;

            _contentLoaded = true;
            global::Windows.UI.Xaml.Application.LoadComponent(this, new global::System.Uri("ms-appx:///SchoolActivities.xaml"), global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application);

            pageRoot = (global::Windows.UI.Xaml.Controls.Page)this.FindName("pageRoot");
            FlipView1 = (global::Windows.UI.Xaml.Controls.FlipView)this.FindName("FlipView1");
            backButton = (global::Windows.UI.Xaml.Controls.Button)this.FindName("backButton");
            pageTitle = (global::Windows.UI.Xaml.Controls.TextBlock)this.FindName("pageTitle");
        }
    }
}


text:
main {
  padding: 1em;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  margin-top: 50px;
  display: block;
}


text:
You can share text, URL, or file to other apps using AppFramework.clipboard.share() method. Notice that share file functionality is supported on all platforms and share text or URL is only supported on macOS, iOS, and Android platforms.

[Interapp communication API Guide](http://doc.arcgis.com/en/appstudio/api-guide/apisystemfunctions.htm#ESRI_SECTION2_0B8E45C527124BDAAAB7BF8E53C6BEE9)

[Resource Level](https://geonet.esri.com/groups/appstudio/blog/2016/12/06/how-to-describe-our-resources-in-terms-of-difficulty-complexity-and-time-to-digest): 🍌

## Instructions to run this sample in AppStudio Desktop

1. Download the `.zip` file
2. Unzip and copy this folder into AppStudio Apps folder (Windows: `C:\Users\<username>\ArcGIS\AppStudio\Apps` Mac or linux: `Home\ArcGIS\AppStudio\Apps`)
3. The new app will now appear in the AppStudio Desktop. Run the application or open it in the bundled Qt-Creator IDE to look at the code and modify.

## Issues

Find a bug or want to request a new feature?  Please let us know by submitting an issue.

## Contributing

Esri welcomes contributions from anyone and everyone. Please see our [guidelines for contributing](https://github.com/esri/contributing).

## Licensing
Copyright 2021 Esri

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

A copy of the license is available in the repository's [license.txt](license.txt) file.

[](Esri Tags: ArcGIS Runtime SDK Qt QML JavaScript iOS Android Xamarin Ionic PhoneGap Mac linux Windows Apps samples templates appstudio)
[](Esri Language: Qt QML JavaScript)


text:
startWebServer(){
    echo "Starting web server..."
    cd app/scripts
    echo "------------------------------------------"
    echo "Open the browser on host machine and navigate to:"
    echo "http://localhost:8080/"
    echo "------------------------------------------"
    php -S 0.0.0.0:8080

}
clear
cp /app/scripts/compare.py /root/openface/demos/compare.py
echo "--------------------------------------"
echo " Image Comparison App"
echo "--------------------------------------"

if which php >/dev/null; then
    startWebServer
else
    echo "Initializing app..."
    echo "Getting the latest package information..."
    apt-get update
    echo "Installing PHP and server libraries..."
    apt-get install php5-common libapache2-mod-php5 php5-cli
    echo "---------------------------------------------------------------------"
    echo "Libraries are installed. Please do following to preserve Docker changes:"
    echo " - Open new terminal instance on host machine"
    echo " - Execute 'docker ps -l'"
    echo " - Get the Container Instance ID"
    echo " - Execute 'docker commit <ID> bamos/openface'"
    echo " - Note: If you skip these steps, you may need to repeat this process next time"
    echo "------------------------------"
    echo "Press any key to continue...>"
    read input_variable
    #Replace the original compare.py file with our file that does not throws exceptions, and can skip issues when they occur
    #It's required to do this only once
    #Check from time to time and compare this file with original from GitHub to see if there are any major changes.
    #If there are some changes after some time in new version, please update the /app/scripts/compare.py file and add required changes to handle exceptions

    startWebServer
fi


text:
import React from 'react';
import { Switch, Route } from 'react-router';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

import Helmet from 'react-helmet';
import { CodeSplit } from 'code-split-component';

import './sass/style.scss';

// Pages
import Home from './Home/home';
import Blog from './Blog/blog';
import Work from './Showcase/showcase';
import NotFound from './NotFound/notfound';

import { safeConfigGet } from '../../utils/config';

import * as _ from 'lodash';

function App() {
  return (
    <div>
	      {/*
	        All of the following will be injected into our page header.
	        @see https://github.com/nfl/react-helmet
	      */}
	      <Helmet
	        htmlAttributes={safeConfigGet(['htmlPage', 'htmlAttributes'])}
	        titleTemplate={safeConfigGet(['htmlPage', 'titleTemplate'])}
	        defaultTitle={safeConfigGet(['htmlPage', 'defaultTitle'])}
	        meta={safeConfigGet(['htmlPage', 'meta'])}
	        link={safeConfigGet(['htmlPage', 'links'])}
	        script={safeConfigGet(['htmlPage', 'scripts'])}
	      >
          <meta http-equiv="Content-Security-Policy" content="default-src 'self' https://www.youtube.com; options inline-script" />
        </Helmet>

        <Route render={({ location }) => (
          <ReactCSSTransitionGroup
            transitionName="fade"
            transitionEnterTimeout={300}
            transitionLeaveTimeout={300}
          >
          <Switch key={location.key}>
    	    	<Route
    	    		exact
    	    		path="/"
    	    		component={Home}
    	    	/>

            <Route
    	    		path="/writings/:id"
    	    		component={Blog}
    	    	/>

            <Route
    	    		path="/work/:id"
    	    		component={Work}
    	    	/>

    	    	<Route component={NotFound} />
          </Switch>
          </ReactCSSTransitionGroup>
        )}/>
    </div>
  );
}

export default App;


text:
package org.apache.axis2.jaxws.utility;

import org.apache.axis2.jaxws.ExceptionFactory;
import org.apache.axis2.jaxws.i18n.Messages;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.activation.DataHandler;
import javax.imageio.ImageIO;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.WebServiceException;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Provides utilities to convert an object into a different kind of Object. For example, convert a
 * String[] into a List<String>
 */
public class ConvertUtils {

    private static final Log log = LogFactory.getLog(ConvertUtils.class);

    /**
     * This method should return true if the convert method will succeed.
     *

     * Note that any changes to isConvertable() must also be accompanied by similar changes to
     * convert()
     *
     * @param obj  source object or class
     * @param dest destination class
     * @return boolean true if convert(..) can convert obj to the destination class
     */
    public static boolean isConvertable(Object obj, Class dest) {
        Class src = null;

        if (obj != null) {
            if (obj instanceof Class) {
                src = (Class)obj;
            } else {
                src = obj.getClass();
            }
        }

        if (dest == null) {
            return false;
        }

        if (src == null) {
            return true;
        }

        // If we're directly assignable, we're good.
        if (dest.isAssignableFrom(src)) {
            return true;
        }

        // If it's a wrapping conversion, we're good.
        if (JavaUtils.getWrapperClass(src) == dest) {
            return true;
        }
        if (JavaUtils.getWrapperClass(dest) == src) {
            return true;
        }

        // If it's List -> Array or vice versa, we're good.
        if ((Collection.class.isAssignableFrom(src) || src.isArray()) &&
                (Collection.class.isAssignableFrom(dest) || dest.isArray())) {

            // TODO this should consider the component types instead of returning true.
            return true;
        }

        // Allow mapping of HashMaps to Hashtables
        if (src == HashMap.class && dest == Hashtable.class)
            return true;

        // Allow mapping of Calendar to Date
        if (Calendar.class.isAssignableFrom(src) && dest == Date.class) {
            return true;
        }

        if (src.isPrimitive()) {
            return isConvertable(JavaUtils.getWrapperClass(src), dest);
        }

        if (InputStream.class.isAssignableFrom(src) && dest == byte[].class) {
            return true;
         }

         if (Source.class.isAssignableFrom(src) && dest == byte[].class) {
             return true;
         }

         if (DataHandler.class.isAssignableFrom(src) && isConvertable(byte[].class, dest)) {
            return true;
        }

        if (DataHandler.class.isAssignableFrom(src) && dest == Image.class) {
            return true;
        }

        if (DataHandler.class.isAssignableFrom(src) && dest == Source.class) {
            return true;
        }

        if (byte[].class.isAssignableFrom(src) && dest == String.class) {
            return true;
        }

        // If it's a MIME type mapping and we want a DataHandler,
        // then we're good.
        // REVIEW Do we want to support this
        /*
        if (dest.getName().equals("javax.activation.DataHandler")) {
            String name = src.getName();
            if (src == String.class
                    || src == java.awt.Image.class
                    || name.equals("javax.mail.internet.MimeMultipart")
                    || name.equals("javax.xml.transform.Source"))
                return true;
        }
        */

        return false;
    }

    /**
     * Utility function to convert an Object to some desired Class.
     *

     * Normally this is used for T[] to List<T> processing. Other conversions are also done (i.e.
     * HashMap <->Hashtable, etc.)
     *

     * Use the isConvertable() method to determine if conversion is possible. Note that any changes
     * to convert() must also be accompanied by similar changes to isConvertable()
     *
     * @param arg       the array to convert
     * @param destClass the actual class we want
     * @return object of destClass if conversion possible, otherwise returns arg
     */
    public static Object convert(Object arg, Class destClass) throws WebServiceException {
        if (destClass == null) {
            return arg;
        }

        if (arg != null && destClass.isAssignableFrom(arg.getClass())) {
            return arg;
        }

        if (log.isDebugEnabled()) {
            String clsName = "null";
            if (arg != null) clsName = arg.getClass().getName();
            log.debug("Converting an object of type " + clsName + " to an object of type " +
                    destClass.getName());
        }

        // Convert between Calendar and Date
        if (arg instanceof Calendar && destClass == Date.class) {
            return ((Calendar)arg).getTime();
        }

        // Convert between HashMap and Hashtable
        if (arg instanceof HashMap && destClass == Hashtable.class) {
            return new Hashtable((HashMap)arg);
        }

        if (arg instanceof InputStream && destClass == byte[].class) {

            try {
                InputStream is = (InputStream) arg;
                return getBytesFromStream(is);
            } catch (IOException e) {
                throw ExceptionFactory.makeWebServiceException(e);
            }
        }

        if (arg instanceof Source && destClass == byte[].class) {
            try {
                if (arg instanceof StreamSource) {
                    InputStream is = ((StreamSource) arg).getInputStream();
                    if (is != null) {
                        return getBytesFromStream(is);
                    }
                }
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                Result result = new StreamResult(out);
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.transform((Source) arg, result);
                byte[] bytes = out.toByteArray();
                return bytes;

            } catch (Exception e) {
                throw ExceptionFactory.makeWebServiceException(e);
            }
        }

        if (arg instanceof DataHandler) {
            try {
                InputStream is = ((DataHandler) arg).getInputStream();
                if (destClass == Image.class) {
                    return ImageIO.read(is);
                } else if (destClass == Source.class) {
                    return new StreamSource(is);
                }
                byte[] bytes = getBytesFromStream(is);
                return convert(bytes, destClass);
            } catch (Exception e) {
                throw ExceptionFactory.makeWebServiceException(e);
            }
        }

        if (arg instanceof byte[] && destClass == String.class) {
            return new String((byte[]) arg);
        }

        // If the destination is an array and the source
        // is a suitable component, return an array with
        // the single item.
        /* REVIEW do we need to support atomic to array conversion ?
        if (arg != null &&
            destClass.isArray() &&
            !destClass.getComponentType().equals(Object.class) &&
            destClass.getComponentType().isAssignableFrom(arg.getClass())) {
            Object array =
                Array.newInstance(destClass.getComponentType(), 1);
            Array.set(array, 0, arg);
            return array;
        }
        */

        // Return if no conversion is available
        if (!(arg instanceof Collection ||
                (arg != null && arg.getClass().isArray()))) {
            return arg;
        }

        if (arg == null) {
            return null;
        }

        // The arg may be an array or List
        Object destValue = null;
        int length = 0;
        if (arg.getClass().isArray()) {
            length = Array.getLength(arg);
        } else {
            length = ((Collection)arg).size();
        }

        try {
            if (destClass.isArray()) {
                if (destClass.getComponentType().isPrimitive()) {

                    Object array = Array.newInstance(destClass.getComponentType(),
                                                     length);
                    // Assign array elements
                    if (arg.getClass().isArray()) {
                        for (int i = 0; i < length; i++) {
                            Array.set(array, i, Array.get(arg, i));
                        }
                    } else {
                        int idx = 0;
                        for (Iterator i = ((Collection)arg).iterator();
                             i.hasNext();) {
                            Array.set(array, idx++, i.next());
                        }
                    }
                    destValue = array;

                } else {
                    Object [] array;
                    try {
                        array = (Object [])Array.newInstance(destClass.getComponentType(),
                                                             length);
                    } catch (Exception e) {
                        return arg;
                    }

                    // Use convert to assign array elements.
                    if (arg.getClass().isArray()) {
                        for (int i = 0; i < length; i++) {
                            array[i] = convert(Array.get(arg, i),
                                               destClass.getComponentType());
                        }
                    } else {
                        int idx = 0;
                        for (Iterator i = ((Collection)arg).iterator();
                             i.hasNext();) {
                            array[idx++] = convert(i.next(),
                                                   destClass.getComponentType());
                        }
                    }
                    destValue = array;
                }
            } else if (Collection.class.isAssignableFrom(destClass)) {
                Collection newList = null;
                try {
                    // if we are trying to create an interface, build something
                    // that implements the interface
                    if (destClass == Collection.class || destClass == List.class) {
                        newList = new ArrayList();
                    } else if (destClass == Set.class) {
                        newList = new HashSet();
                    } else {
                        newList = (Collection)destClass.newInstance();
                    }
                } catch (Exception e) {
                    // No FFDC code needed
                    // Couldn't build one for some reason... so forget it.
                    return arg;
                }

                if (arg.getClass().isArray()) {
                    for (int j = 0; j < length; j++) {
                        newList.add(Array.get(arg, j));
                    }
                } else {
                    for (Iterator j = ((Collection)arg).iterator();
                         j.hasNext();) {
                        newList.add(j.next());
                    }
                }
                destValue = newList;
            } else {
                destValue = arg;
            }
        } catch (Throwable t) {
            throw ExceptionFactory.
              makeWebServiceException(
                                    Messages.getMessage("convertUtils",
                                                        arg.getClass().toString(),
                                                        destClass.toString()),
                                    t);
        }

        return destValue;
    }

    private static byte[] getBytesFromStream(InputStream is) throws IOException {
        // TODO This code assumes that available is the length of the stream.
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        return bytes;
    }
}


text:
#pragma once

#include "AclFiltering.h"

class UrlRewrite;

#define BUILD_TABLE_MAX_ARGS 2048

// Remap inline options
#define REMAP_OPTFLG_MAP_WITH_REFERER 0x0001u /* "map_with_referer" option */
#define REMAP_OPTFLG_PLUGIN 0x0002u           /* "plugin=" option (per remap plugin) */
#define REMAP_OPTFLG_PPARAM 0x0004u           /* "pparam=" option (per remap plugin option) */
#define REMAP_OPTFLG_METHOD 0x0008u           /* "method=" option (used for ACL filtering) */
#define REMAP_OPTFLG_SRC_IP 0x0010u           /* "src_ip=" option (used for ACL filtering) */
#define REMAP_OPTFLG_ACTION 0x0020u           /* "action=" option (used for ACL filtering) */
#define REMAP_OPTFLG_INTERNAL 0x0040u         /* only allow internal requests to hit this remap */
#define REMAP_OPTFLG_IN_IP 0x0080u            /* "in_ip=" option (used for ACL filtering)*/
#define REMAP_OPTFLG_MAP_ID 0x0800u           /* associate a map ID with this rule */
#define REMAP_OPTFLG_INVERT 0x80000000u       /* "invert" the rule (for src_ip at least) */
#define REMAP_OPTFLG_ALL_FILTERS (REMAP_OPTFLG_METHOD | REMAP_OPTFLG_SRC_IP | REMAP_OPTFLG_ACTION | REMAP_OPTFLG_INTERNAL)

struct BUILD_TABLE_INFO {
  BUILD_TABLE_INFO();
  ~BUILD_TABLE_INFO();

  unsigned long remap_optflg;
  int paramc;
  int argc;
  char *paramv[BUILD_TABLE_MAX_ARGS];
  char *argv[BUILD_TABLE_MAX_ARGS];

  bool ip_allow_check_enabled_p;
  bool accept_check_p;
  acl_filter_rule *rules_list; // all rules defined in config files as .define_filter foobar @src_ip=.....
  UrlRewrite *rewrite;         // Pointer to the UrlRewrite object we are parsing for.

  // Clear the argument vector.
  void reset();

  // noncopyable
  BUILD_TABLE_INFO(const BUILD_TABLE_INFO &) = delete;            // disabled
  BUILD_TABLE_INFO &operator=(const BUILD_TABLE_INFO &) = delete; // disabled
};

const char *remap_parse_directive(BUILD_TABLE_INFO *bti, char *errbuf, size_t errbufsize);

const char *remap_validate_filter_args(acl_filter_rule **rule_pp, const char **argv, int argc, char *errStrBuf,
                                       size_t errStrBufSize);

unsigned long remap_check_option(const char **argv, int argc, unsigned long findmode = 0, int *_ret_idx = nullptr,
                                 const char **argptr = nullptr);

bool remap_parse_config(const char *path, UrlRewrite *rewrite);


text:
package com.xmomen.module.account.service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xmomen.framework.mybatis.dao.MybatisDao;
import com.xmomen.module.account.mapper.UserMapper;
import com.xmomen.module.account.model.CreateUser;
import com.xmomen.module.account.web.controller.vo.UpdateUserVo;
import com.xmomen.module.system.entity.SysUserOrganization;
import com.xmomen.module.system.entity.SysUserOrganizationExample;
import com.xmomen.module.user.entity.SysPermissions;
import com.xmomen.module.user.entity.SysRoles;
import com.xmomen.module.user.entity.SysUsers;
import com.xmomen.module.user.entity.SysUsersExample;
import com.xmomen.module.user.entity.SysUsersRoles;
import com.xmomen.module.user.entity.SysUsersRolesExample;

/**
 *
User: Zhang Kaitao
 *
Date: 14-1-28
 *
Version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    private PasswordHelper passwordHelper;

    public void setPasswordHelper(PasswordHelper passwordHelper) {
        this.passwordHelper = passwordHelper;
    }

    @Autowired
    MybatisDao mybatisDao;

    @Autowired(required = false)
    UserMapper userMapper;

    /**
     * 创建用户
     *
     * @param user
     */
    @Transactional
    public SysUsers createUser(CreateUser user) {
        //加密密码
        String salt = passwordHelper.getSalt();
        String newPassword = passwordHelper.encryptPassword(user.getPassword(), salt);
        SysUsers sysUsers = new SysUsers();
        sysUsers.setSalt(UUID.randomUUID().toString().toUpperCase());
        sysUsers.setUsername(user.getUsername());
        sysUsers.setEmail(user.getEmail());
        sysUsers.setRealname(user.getRealname());
        sysUsers.setAge(user.getAge());
        sysUsers.setOfficeTel(user.getOfficeTel());
        sysUsers.setPhoneNumber(user.getPhoneNumber());
        sysUsers.setQq(user.getQq());
        sysUsers.setSex(user.getSex());
        sysUsers.setSalt(salt);
        sysUsers.setPassword(newPassword);
        sysUsers.setLocked(user.getLocked() ? 1 : 0);
        sysUsers = mybatisDao.saveByModel(sysUsers);
        for (int userGroupId : user.getUserGroupIds()) {
            SysUsersRoles userRoles = new SysUsersRoles();
            userRoles.setRoleId(userGroupId);
            userRoles.setUserId(sysUsers.getId());
            mybatisDao.save(userRoles);
        }
        SysUserOrganization userOrganization = new SysUserOrganization();
        userOrganization.setOrganizationId(user.getOrganizationId());
        userOrganization.setUserId(sysUsers.getId());
        mybatisDao.save(userOrganization);
        return sysUsers;
    }

    /**
     * 更新用户
     *
     * @param updateUserVo
     */
    @Transactional
    @Override
    public void updateUser(UpdateUserVo updateUserVo) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setId(updateUserVo.getId());
        sysUsers.setUsername(updateUserVo.getUsername());
        sysUsers.setEmail(updateUserVo.getEmail());
        sysUsers.setLocked(updateUserVo.getLocked() ? 1 : 0);
        sysUsers.setAge(updateUserVo.getAge());
        sysUsers.setOfficeTel(updateUserVo.getOfficeTel());
        sysUsers.setPhoneNumber(updateUserVo.getPhoneNumber());
        sysUsers.setSex(updateUserVo.getSex());
        sysUsers.setQq(updateUserVo.getQq());
        sysUsers.setRealname(updateUserVo.getRealName());
        //更新权限
        SysUsersRolesExample sysUsersRolesExample = new SysUsersRolesExample();
        sysUsersRolesExample.createCriteria().andUserIdEqualTo(sysUsers.getId());
        mybatisDao.deleteByExample(sysUsersRolesExample);
        for (int userGroupId : updateUserVo.getUserGroupIds()) {
            SysUsersRoles userRoles = new SysUsersRoles();
            userRoles.setRoleId(userGroupId);
            userRoles.setUserId(sysUsers.getId());
            mybatisDao.save(userRoles);
        }
        SysUserOrganizationExample sysUserOrganizationExample = new SysUserOrganizationExample();
        sysUserOrganizationExample.createCriteria().andUserIdEqualTo(sysUsers.getId());
        mybatisDao.deleteByExample(sysUserOrganizationExample);
        SysUserOrganization userOrganization = new SysUserOrganization();
        userOrganization.setOrganizationId(updateUserVo.getOrganizationId());
        userOrganization.setUserId(sysUsers.getId());
        mybatisDao.save(userOrganization);
        mybatisDao.save(sysUsers);
    }

    /**
     * 修改密码
     *
     * @param userId
     * @param newPassword
     */
    @Transactional
    public void changePassword(Integer userId, String newPassword) {
        SysUsers user = mybatisDao.selectByPrimaryKey(SysUsers.class, userId);
        String salt = passwordHelper.getSalt();
        newPassword = passwordHelper.encryptPassword(newPassword, salt);
        user.setPassword(newPassword);
        user.setSalt(salt);
        mybatisDao.update(user);
    }

    @Override
    public void changePassword(String username, String currentPassword, String newPassword) {
        SysUsers sysUsers = new SysUsers();
        sysUsers.setUsername(username);
        sysUsers = mybatisDao.selectOneByModel(sysUsers);
        String currentRealPwd = passwordHelper.encryptPassword(currentPassword, sysUsers.getSalt());
        if (sysUsers == null || !sysUsers.getPassword().equals(currentRealPwd)) {
            throw new IllegalArgumentException("当前密码错误");
        }
        String newSalt = passwordHelper.getSalt();
        String newCurrentRealPwd = passwordHelper.encryptPassword(newPassword, newSalt);
        userMapper.resetPassword(username, currentRealPwd, newCurrentRealPwd, newSalt);
    }

    /**
     * 添加用户-角色关系
     *
     * @param userId
     * @param roleIds
     */
    @Transactional
    public void correlationRoles(Integer userId, Integer... roleIds) {
        for (int i = 0; i < roleIds.length; i++) {
            Integer roleId = roleIds[i];
            SysUsersRoles sysUsersRoles = new SysUsersRoles();
            sysUsersRoles.setUserId(userId);
            sysUsersRoles.setRoleId(roleId);
            mybatisDao.insert(sysUsersRoles);
        }
    }

    /**
     * 移除用户-角色关系
     *
     * @param userId
     * @param roleIds
     */
    public void uncorrelationRoles(Integer userId, Integer... roleIds) {
        SysUsersRolesExample sysUsersRolesExample = new SysUsersRolesExample();
        sysUsersRolesExample.createCriteria()
                .andUserIdEqualTo(userId)
                .andRoleIdIn(Arrays.asList(roleIds));
        mybatisDao.deleteByExample(sysUsersRolesExample);
    }

    /**
     * 根据用户名查找用户
     *
     * @param username
     * @return
     */
    public SysUsers findByUsername(String username) {
        SysUsersExample sysUsersExample = new SysUsersExample();
        sysUsersExample.createCriteria().andUsernameEqualTo(username);
        sysUsersExample.or().andEmailEqualTo(username);
        sysUsersExample.or().andPhoneNumberEqualTo(username);
        List<SysUsers> userses = mybatisDao.selectByExample(sysUsersExample);
        return userses.size() > 0 ? userses.get(0) : null;
    }

    /**
     * 根据用户名查找其角色
     *
     * @param username
     * @return
     */
    public Set<String> findRoles(String username) {
        List<SysRoles> sysRolesList = userMapper.getRoleList(username);
        Set<String> roles = new HashSet();
        for (int i = 0; i < sysRolesList.size(); i++) {
            roles.add(sysRolesList.get(i).getRole());
        }
        return roles;
    }

    /**
     * 根据用户名查找其权限
     *
     * @param username
     * @return
     */
    public Set<String> findPermissions(String username) {
        List<SysPermissions> sysPermissionsList = userMapper.getPermissionList(username);
        Set<String> permissions = new HashSet();
        for (int i = 0; i < sysPermissionsList.size(); i++) {
            permissions.add(sysPermissionsList.get(i).getPermission());
        }
        return permissions;
    }

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.05.03 at 03:55:56 PM CEST
//

package org.fiteagle.north.sfa.aaa.jaxbClasses;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 * A credential granting privileges or a ticket.
 *
 *
Java class for credentials complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="credentials">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{}credential"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "credentials", propOrder = {
    "credential"
})
@XmlSeeAlso({
    org.fiteagle.north.sfa.aaa.jaxbClasses.SignedCredential.class
})
public class Credentials {

    @XmlElement(required = true)
    protected Credential credential;

    /**
     * Gets the value of the credential property.
     *
     * @return
     *     possible object is
     *     {@link Credential }
     *
     */
    public Credential getCredential() {
        return credential;
    }

    /**
     * Sets the value of the credential property.
     *
     * @param value
     *     allowed object is
     *     {@link Credential }
     *
     */
    public void setCredential(Credential value) {
        this.credential = value;
    }

}


text:
Simulates Milton Bradley's The Game of Life to generate statistics and evaluate strategies.  See the blog post below for a summary of the objective and results:

http://jonlyons.net/blog/2016/09/06/how-to-be-a-winner-at-the-game-of-life


text:
Tools for building PyQt5 and SIP and creating Python Wheels in a platform
specific fashion.

Because PyQt5 v5.6 is current (6/23/2016) broken for QGraphicsItem.itemChange
overloading IT is necessary to stick to version 5.5.1 or less, and so I created
these wheel builder modules.


text:
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <sstream>

#ifndef _WIN32
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#else
#include <ws2tcpip.h>
#include <iphlpapi.h>
#endif

#include <logger/assertions.hpp>
#include <network/net_util.hpp>
#include "export.hpp"

#define NUM_VM_MAC_ADDRS 8
#define MAC_PREFIX_SIZE 3
namespace graphlab {

bool str_to_ip(const char* c, uint32_t& out) {
  if (c == NULL) return false;
  else return inet_pton(AF_INET, c, &out) > 0;
}

bool ip_to_str(uint32_t ip, std::string& out) {
  char ipstring[INET_ADDRSTRLEN] = {0};
  const char* ret = inet_ntop(AF_INET, &ip, ipstring, INET_ADDRSTRLEN);
  if (ret == NULL) return false;
  out = std::string(ipstring);
  return true;
}

// Only IPv4
bool get_interface_ip_in_subnet(uint32_t subnet_id, uint32_t subnet_mask, uint32_t &ip) {
  bool success = false;

#ifndef _WIN32
  // code adapted from
  struct ifaddrs * ifAddrStruct = NULL;
  getifaddrs(&ifAddrStruct);
  struct ifaddrs * firstifaddr = ifAddrStruct;
  ASSERT_NE(ifAddrStruct, NULL);
  while (ifAddrStruct != NULL) {
    if (ifAddrStruct->ifa_addr != NULL &&
        ifAddrStruct->ifa_addr->sa_family == AF_INET) {
      char* tmpAddrPtr = NULL;
      // check it is IP4 and not lo0.
      tmpAddrPtr = (char*)&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
      ASSERT_NE(tmpAddrPtr, NULL);
      if (tmpAddrPtr[0] != 127) {
        memcpy(&ip, tmpAddrPtr, 4);
        // test if it matches the subnet
        if ((ip & subnet_mask) == subnet_id) {
          success = true;
          break;
        }
      }
      //break;
    }
    ifAddrStruct=ifAddrStruct->ifa_next;
  }
  freeifaddrs(firstifaddr);

#else
  ULONG buf_size = 15000;
  ULONG ret;
  int iterations = 0;
  int max_tries = 3;
  IP_ADAPTER_ADDRESSES *addresses;

  do {
    std::cerr << "Allocating " << buf_size << " bytes for addresses" << std::endl;
    addresses = (IP_ADAPTER_ADDRESSES *)malloc(buf_size);
    if(addresses == NULL) {
      return success;
    }
    ret = GetAdaptersAddresses(AF_INET, 0, NULL, addresses, &buf_size);

    if(ret == ERROR_BUFFER_OVERFLOW) {
      free(addresses);
      addresses = NULL;
    }

    ++iterations;
  } while((ret == ERROR_BUFFER_OVERFLOW) && (iterations < max_tries));

  if(ret == NO_ERROR) {
    IP_ADAPTER_ADDRESSES *first_struct = addresses;
    IP_ADAPTER_ADDRESSES *cur_struct = addresses;
    for(; cur_struct != NULL; cur_struct = cur_struct->Next) {
      PIP_ADAPTER_UNICAST_ADDRESS first_addr = cur_struct->FirstUnicastAddress;
      PIP_ADAPTER_UNICAST_ADDRESS cur_addr = first_addr;

      // Some interface-level checking

      // Check if operational
      if(cur_struct->OperStatus != IfOperStatusUp) {
        std::cerr << "Not operational!" << std::endl;
        continue;
      }

      // Check if loopback
      std::cerr << "iftype: " << cur_struct->IfType << std::endl;
      if(cur_struct->IfType == IF_TYPE_SOFTWARE_LOOPBACK) {
        std::cerr << "loopback, skipping." << std::endl;
        continue;
      }

      // Check if a VM adapter.  Certain VM makers always use the same prefixes
      // on their MAC addresses.  This is the only way I can find to tell apart
      // a real IP from one that's just meant to talk to a VM on your machine.
      DWORD mac_addr_len = cur_struct->PhysicalAddressLength;

      if(mac_addr_len == 6) {
        // The first three bytes of known MAC addresses from different types of
        // VMs are the LAST three bytes in these integers.  First byte is all
        // zeroes and meaningless.
        unsigned known_vm_mac_prefixes[NUM_VM_MAC_ADDRS] = {
          0x00080027, // virtualbox
          0x00000569, // vmware
          0x00000c29, // vmware
          0x00005056, // vmware
          0x00001c42, // parallels
          0x000003ff, // microsoft virtual pc
          0x00000f4b, // virtual iron 4
          0x0000163e, // oracle vm, xen
        };

        // Get the MAC address into the same form as above.
        unsigned comparable_mac_addr = 0;
        comparable_mac_addr |= ((unsigned)cur_struct->PhysicalAddress[0] << 16);
        comparable_mac_addr |= ((unsigned)cur_struct->PhysicalAddress[1] << 8);
        comparable_mac_addr |= (unsigned)cur_struct->PhysicalAddress[2];

        bool match = false;
        for(int i = 0; i < NUM_VM_MAC_ADDRS; ++i) {
          if(comparable_mac_addr == known_vm_mac_prefixes[i]) {
            match = true;
            break;
          }
        }
        if(match) {
          continue;
        }
      } else {
        // This isn't a real MAC address, so this probably won't really send
        // packets.
        continue;
      }

      // Main goal: Iterate over each unicast address on this interface.  Use some criteria to pick what a good one is.
      //
      // To get the address:
      // 1. Get the Address field, which is a pointer to a SOCKET_ADDRESS structure
      // 2. Get the lpSockaddr field, which is a pointer to a sockaddr structure
      // 3. Cast struct sockaddr to sockaddr_in and get the sin_addr field
      std::cerr << "Found interface" << std::endl;
      while(cur_addr != NULL) {

        //
        //NOTE: The one, the one, don't go for the one.
        struct sockaddr_in *the_one =
          (struct sockaddr_in *)cur_addr->Address.lpSockaddr;
        char *tmp_addr_ptr = NULL;
        if(the_one != NULL) {
          tmp_addr_ptr = (char *)&the_one->sin_addr;
        }
        if(tmp_addr_ptr == NULL) {
          cur_addr = cur_addr->Next;
          continue;
        }
        std::string t;
        uint32_t ip_to_print;
        memcpy(&ip_to_print, tmp_addr_ptr, 4);
        ip_to_str(ip_to_print, t);
        std::cerr << "Found IP address: " << t << std::endl;

        memcpy(&ip, tmp_addr_ptr, 4);
        // Test if matches subnet
        if((ip & subnet_mask) == subnet_id) {
          std::cerr << "Match!" << std::endl;
          success = true;

          // We're done
          cur_struct = NULL;
          break;
        }

        cur_addr = cur_addr->Next;
      }
      if(cur_struct == NULL)
        break;
    }
  } else {
    std::cerr << "Error retrieving adapter addresses: " << ret << std::endl;
  }

  free(addresses);
#endif
  return success;
}

EXPORT std::string get_local_ip_as_str(bool print) {
  uint32_t ip = get_local_ip(print);
  if (ip == 0) return "127.0.0.1";
  else {
    std::string out;
    bool ip_conversion_success = ip_to_str(ip, out);
    ASSERT_TRUE(ip_conversion_success);
    return out;
  }
}

EXPORT uint32_t get_local_ip(bool print) {
  // see if GRAPHLAB_SUBNET environment variable is set
  char* c_subnet_id = getenv("GRAPHLAB_SUBNET_ID");
  char* c_subnet_mask = getenv("GRAPHLAB_SUBNET_MASK");
  uint32_t subnet_id = 0;
  uint32_t subnet_mask = 0;
  std::string str_subnet_id, str_subnet_mask;
  // try to convert to a valid address when possible
  if (c_subnet_id != NULL) {
    if (!str_to_ip(c_subnet_id, subnet_id)) {
      std::cerr << "Unable to convert GRAPHLAB_SUBNET_ID to a valid address. Cannot continue\n";
      exit(1);
    }
  }
  if (c_subnet_mask != NULL) {
    if (!str_to_ip(c_subnet_mask, subnet_mask)) {
      std::cerr << "Unable to convert GRAPHLAB_SUBNET_MASK to a valid address. Cannot continue\n";
      exit(1);
    }
  }

  // error checking.
  // By the end of this block, we should either have both subnet_id and subnet_mask filled
  // to reasonable values, or are dead.

  if (c_subnet_id == NULL && c_subnet_mask != NULL) {
    // If subnet mask specified but not subnet ID, we cannot continue.
    std::cerr << "GRAPHLAB_SUBNET_MASK specified, but GRAPHLAB_SUBNET_ID not specified.\n";
    std::cerr << "We cannot continue\n";
    exit(1);
  }
  if (c_subnet_id != NULL && c_subnet_mask == NULL) {
    if (print) {
      std::cerr << "GRAPHLAB_SUBNET_ID specified, but GRAPHLAB_SUBNET_MASK not specified.\n";
      std::cerr << "We will try to guess a subnet mask\n";
    }
    // if subnet id specified, but not subnet mask. We can try to guess a mask
    // by finding the first "on" bit in the subnet id, and matching everything
    // to the left of it.
    // easiest way to do that is to left extend the subnet_id
    subnet_mask = subnet_id;
    subnet_mask = ntohl(subnet_mask);
    subnet_mask = subnet_mask | (subnet_mask << 1);
    subnet_mask = subnet_mask | (subnet_mask << 2);
    subnet_mask = subnet_mask | (subnet_mask << 4);
    subnet_mask = subnet_mask | (subnet_mask << 8);
    subnet_mask = subnet_mask | (subnet_mask << 16);
    subnet_mask = htonl(subnet_mask);
  }
  else {
    if (print) {
      std::cerr << "GRAPHLAB_SUBNET_ID/GRAPHLAB_SUBNET_MASK environment variables not defined.\n";
      std::cerr << "Using default values\n";
    }
  }
  ip_to_str(subnet_id, str_subnet_id);
  ip_to_str(subnet_mask, str_subnet_mask);

  uint32_t ip(0);
  bool success = get_interface_ip_in_subnet(subnet_id, subnet_mask, ip);

  // make sure this is a valid subnet address.
  if (print) {
      std::cerr << "Subnet ID: " << str_subnet_id << "\n";
      std::cerr << "Subnet Mask: " << str_subnet_mask << "\n";
      std::cerr << "Will find first IPv4 non-loopback address matching the subnet" << std::endl;
  }
  if (!success) {
    // if subnet addresses specified, and if we cannot find a valid network. Fail."
    if (c_subnet_id != NULL) {
      std::cerr << "Unable to find a network matching the requested subnet\n";
      exit(1);
    } else {
      std::cerr << "Unable to find any valid IPv4 address. Defaulting to loopback\n";
    }
  }
  return ip;
}

// TODO: This is broken on Windows, but is only used by RPC, so putting it off
EXPORT std::pair<size_t, int> get_free_tcp_port() {
#ifndef _WIN32
  int sock = socket(AF_INET, SOCK_STREAM, 0);
  // uninteresting boiler plate. Set the port number and socket type
  sockaddr_in my_addr;
  my_addr.sin_family = AF_INET;
  my_addr.sin_port = 0; // port 0.
  my_addr.sin_addr.s_addr = INADDR_ANY;
  memset(&(my_addr.sin_zero), '\0', 8);
  if (bind(sock, (sockaddr*)&my_addr, sizeof(my_addr)) < 0){
    logger(LOG_FATAL, "Failed to bind to a port 0! Unable to acquire a free TCP port!");
  }
  // get the sock information
  socklen_t slen;
  sockaddr addr;
  slen = sizeof(sockaddr);
  if (getsockname(sock, &addr, &slen) < 0) {
    logger(LOG_FATAL, "Failed to get port information about bound socket");
  }
  size_t freeport = ntohs(((sockaddr_in*)(&addr))->sin_port);
  std::pair<size_t, int> ret(freeport, sock);
  return ret;
#else
  log_and_throw("This function not supported on Windows");
#endif
}

} // namespace graphlab


text:
extern NSString* const FKApplicationRunLoopMode;

extern NSString* const FCGIKit;

extern NSString* const FKErrorKey;
extern NSString* const FKErrorFileKey;
extern NSString* const FKErrorLineKey;
extern NSString* const FKErrorDomain;

extern NSString* const FKConnectionInfoKey;
extern NSString* const FKConnectionInfoPortKey;
extern NSString* const FKConnectionInfoInterfaceKey;

extern NSUInteger const FKDefaultPortNumber;

extern NSString* const FKRecordKey;
extern NSString* const FKSocketKey;
extern NSString* const FKDataKey;
extern NSString* const FKRequestKey;
extern NSString* const FKResponseKey;
extern NSString* const FKResultKey;
extern NSString* const FKApplicationStatusKey;
extern NSString* const FKProtocolStatusKey;

extern NSString* const FKRoutesKey;
extern NSString* const FKRoutePathKey;
extern NSString* const FKRouteControllerKey;
extern NSString* const FKRouteNibNameKey;
extern NSString* const FKRouteUserInfoKey;

extern NSString* const FKFileNameKey;
extern NSString* const FKFileTmpNameKey;
extern NSString* const FKFileSizeKey;
extern NSString* const FKFileContentTypeKey;

extern NSString* const FKApplicationWillFinishLaunchingNotification;
extern NSString* const FKApplicationDidFinishLaunchingNotification;
extern NSString* const FKApplicationWillTerminateNotification;

@class FCGIRequest, FKHTTPRequest, FKHTTPResponse;
@protocol AsyncSocketDelegate;

extern id FKApp;
extern int FKApplicationMain(int argc, const char **argv, id<FKApplicationDelegate> delegate);

@interface FKApplication : NSObject<GCDAsyncSocketDelegate> {
	NSObject<FKApplicationDelegate> *_delegate;
	NSUInteger _maxConnections;
	NSUInteger _portNumber;
	NSString* _listenIngInterface;

	BOOL _isListeningOnAllInterfaces;
	BOOL _isRunning;

	NSMutableDictionary* _environment;

	BOOL firstRunCompleted;
	BOOL shouldKeepRunning;
	BOOL isWaitingOnTerminateLaterReply;

	NSTimer* waitingOnTerminateLaterReplyTimer;
	CFRunLoopObserverRef mainRunLoopObserver;

	dispatch_queue_t _socketQueue;
	NSOperationQueue* _workerQueue;

	GCDAsyncSocket *_listenSocket;
	NSMutableArray* _connectedSockets;
	NSMutableDictionary* _currentRequests;

	NSArray* _startupArguments;

	NSMutableDictionary* _viewControllers;
}

@property (nonatomic, assign) NSObject<FKApplicationDelegate> *delegate;
@property (atomic, assign) NSUInteger maxConnections;
@property (atomic, assign) NSUInteger portNumber;
@property (nonatomic, retain) NSString* listeningInterface;
@property (atomic, readonly) BOOL isListeningOnAllInterfaces;
@property (atomic, readonly) BOOL isRunning;
@property (nonatomic, retain) GCDAsyncSocket* listenSocket;
@property (nonatomic, retain) NSMutableArray* connectedSockets;
@property (nonatomic, retain) NSMutableDictionary* currentRequests;
@property (nonatomic, readonly, retain) NSArray* startupArguments;
@property (nonatomic, retain) NSMutableDictionary* viewControllers;
@property (nonatomic, readonly, copy) NSDictionary *infoDictionary;
@property (nonatomic, readonly, copy) NSDictionary *dumpConfig;
@property (nonatomic, readonly, copy) NSString *temporaryDirectoryLocation;
@property (nonatomic, retain) NSOperationQueue *workerQueue;

+ (FKApplication *)sharedApplication;

- (instancetype) initWithArguments:(const char **)argv count:(int)argc;

- (void)terminate:(id)sender;
- (void)replyToApplicationShouldTerminate:(BOOL)shouldTerminate;

- (void)run;
- (void)stop:(id)sender;

- (void)presentError:(NSError*)error;

- (void)writeDataToStderr:(NSDictionary *)info;
- (void)writeDataToStdout:(NSDictionary *)info;
- (void)finishRequest:(FCGIRequest*)request;
- (void)finishRequestWithError:(NSDictionary*)userInfo;

@end


text:
FinanceRegister.ProductController = Ember.ObjectController.extend({

});


text:
#ifndef ENCLAVE_T_H__
#define ENCLAVE_T_H__

#include <stdint.h>
#include <wchar.h>
#include <stddef.h>
#include "sgx_edger8r.h" /* for sgx_ocall etc. */

#include "user_types.h"

#include <stdlib.h> /* for size_t */

#define SGX_CAST(type, item) ((type)(item))

#ifdef __cplusplus
extern "C" {
#endif

typedef struct struct_foo_t {
	uint32_t struct_foo_0;
	uint64_t struct_foo_1;
} struct_foo_t;

typedef enum enum_foo_t {
	ENUM_FOO_0 = 0,
	ENUM_FOO_1 = 1,
} enum_foo_t;

typedef union union_foo_t {
	uint32_t union_foo_0;
	uint32_t union_foo_1;
	uint64_t union_foo_3;
} union_foo_t;

size_t get_buffer_len(const char* val);

int ecall_set_parsed_section_info(const char* name, int type, uint64_t val);
void ecall_type_char(char val);
void ecall_type_int(int val);
void ecall_type_float(float val);
void ecall_type_double(double val);
void ecall_type_size_t(size_t val);
void ecall_type_wchar_t(wchar_t val);
void ecall_type_struct(struct struct_foo_t val);
void ecall_type_enum_union(enum enum_foo_t val1, union union_foo_t* val2);
size_t ecall_pointer_user_check(void* val, size_t sz);
void ecall_pointer_in(int* val);
void ecall_pointer_out(int* val);
void ecall_pointer_in_out(int* val);
void ecall_pointer_string(char* str);
void ecall_pointer_string_const(const char* str);
void ecall_pointer_size(void* ptr, size_t len);
void ecall_pointer_count(int* arr, int cnt);
void ecall_pointer_isptr_readonly(buffer_t buf, size_t len);
void ecall_pointer_sizefunc(char* buf);
void ocall_pointer_attr();
void ecall_array_user_check(int arr[4]);
void ecall_array_in(int arr[4]);
void ecall_array_out(int arr[4]);
void ecall_array_in_out(int arr[4]);
void ecall_array_isary(array_t arr);
void ecall_function_calling_convs();
void ecall_function_public();
int ecall_function_private();
void ecall_malloc_free();
void ecall_sgx_cpuid(int cpuinfo[4], int leaf);
void ecall_exception();
void ecall_map();
size_t ecall_increase_counter();
void ecall_producer();
void ecall_consumer();
void ecall_dump_data0(int n, size_t size);
void ecall_dump_data1(int n, size_t size);
void ecall_dump_data2(int n, size_t size);
void ecall_dump_data3(int n, size_t size);
void ecall_dump_data4(int n, size_t size);
void ecall_dump_data5(int n, size_t size);
void ecall_dump_data6(int n, size_t size);
void ecall_dump_data7(int n, size_t size);
void ecall_test_ctx_switch(void* buffer, int n);
int ecall_simple_ctx_swich(int n);

sgx_status_t SGX_CDECL ocall_print_string(const char* str);
sgx_status_t SGX_CDECL ocall_write0(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write1(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write2(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write3(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write4(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write5(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write6(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write7(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write8(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_write9(void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_context_switch(int* retval, int dummy1, int dummy2);
sgx_status_t SGX_CDECL ocall_dummy_clone_process(int* retval);
sgx_status_t SGX_CDECL ocall_fork(int* retval, void* buffer, int bufsiz);
sgx_status_t SGX_CDECL ocall_pointer_user_check(int* val);
sgx_status_t SGX_CDECL ocall_pointer_in(int* val);
sgx_status_t SGX_CDECL ocall_pointer_out(int* val);
sgx_status_t SGX_CDECL ocall_pointer_in_out(int* val);
sgx_status_t SGX_CDECL memccpy(void** retval, void* dest, const void* src, int val, size_t len);
sgx_status_t SGX_CDECL ocall_function_allow();
sgx_status_t SGX_CDECL sgx_oc_cpuidex(int cpuinfo[4], int leaf, int subleaf);
sgx_status_t SGX_CDECL sgx_thread_wait_untrusted_event_ocall(int* retval, const void* self);
sgx_status_t SGX_CDECL sgx_thread_set_untrusted_event_ocall(int* retval, const void* waiter);
sgx_status_t SGX_CDECL sgx_thread_setwait_untrusted_events_ocall(int* retval, const void* waiter, const void* self);
sgx_status_t SGX_CDECL sgx_thread_set_multiple_untrusted_events_ocall(int* retval, const void** waiters, size_t total);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif


text:
//
//  ESPNetUtil.h
//  EspTouchDemo
//
//  Created by 白 桦 on 5/15/15.
//  Copyright (c) 2015 白 桦. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ESP_NetUtil : NSObject

/**
 * get the local ip address by IOS System
 *
 */
+ (NSData *) getLocalInetAddress;

/**
 * parse InetAddress
 */
+ (NSData *) parseInetAddrByData: (NSData *) inetAddrData andOffset: (int) offset andCount: (int) count;

/**
 * descrpion inetAddrData for print pretty
 */
+ (NSString *) descriptionInetAddrByData: (NSData *) inetAddrData;

/**
 * parse bssid
 *
 * @param bssid the bssid
 * @return byte converted from bssid
 */
+ (NSData *) parseBssid2bytes: (NSString *) bssid;

@end