text:
<?php

class Sabre_VObject_Component extends Sabre_VObject_Element {

    /**
     * Name, for example VEVENT
     *
     * @var string
     */
    public $name;

    /**
     * Children properties and components
     *
     * @var array
     */
    public $children = array();

    /**
     * If coponents are added to this map, they will be automatically mapped
     * to their respective classes, if parsed by the reader or constructed with
     * the 'create' method.
     *
     * @var array
     */
    static public $classMap = array(
        'VCALENDAR'     => 'Sabre_VObject_Component_VCalendar',
        'VEVENT'        => 'Sabre_VObject_Component_VEvent',
        'VTODO'         => 'Sabre_VObject_Component_VTodo',
        'VJOURNAL'      => 'Sabre_VObject_Component_VJournal',
        'VALARM'        => 'Sabre_VObject_Component_VAlarm',
    );

    /**
     * Creates the new component by name, but in addition will also see if
     * there's a class mapped to the property name.
     *
     * @param string $name
     * @param string $value
     * @return Sabre_VObject_Component
     */
    static public function create($name, $value = null) {

        $name = strtoupper($name);

        if (isset(self::$classMap[$name])) {
            return new self::$classMap[$name]($name, $value);
        } else {
            return new self($name, $value);
        }

    }

    /**
     * Creates a new component.
     *
     * By default this object will iterate over its own children, but this can
     * be overridden with the iterator argument
     *
     * @param string $name
     * @param Sabre_VObject_ElementList $iterator
     */
    public function __construct($name, Sabre_VObject_ElementList $iterator = null) {

        $this->name = strtoupper($name);
        if (!is_null($iterator)) $this->iterator = $iterator;

    }

    /**
     * Turns the object back into a serialized blob.
     *
     * @return string
     */
    public function serialize() {

        $str = "BEGIN:" . $this->name . "\r\n";

        /**
         * Gives a component a 'score' for sorting purposes.
         *
         * This is solely used by the childrenSort method.
         *
         * A higher score means the item will be higher in the list
         *
         * @param Sabre_VObject_Node $n
         * @return int
         */
        $sortScore = function($n) {

            if ($n instanceof Sabre_VObject_Component) {
                // We want to encode VTIMEZONE first, this is a personal
                // preference.
                if ($n->name === 'VTIMEZONE') {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                // VCARD version 4.0 wants the VERSION property to appear first
                if ($n->name === 'VERSION') {
                    return 3;
                } else {
                    return 2;
                }
            }

        };

        usort($this->children, function($a, $b) use ($sortScore) {

            $sA = $sortScore($a);
            $sB = $sortScore($b);

            if ($sA === $sB) return 0;

            return ($sA > $sB) ? -1 : 1;

        });

        foreach($this->children as $child) $str.=$child->serialize();
        $str.= "END:" . $this->name . "\r\n";

        return $str;

    }

    /**
     * Adds a new component or element
     *
     * You can call this method with the following syntaxes:
     *
     * add(Sabre_VObject_Element $element)
     * add(string $name, $value)
     *
     * The first version adds an Element
     * The second adds a property as a string.
     *
     * @param mixed $item
     * @param mixed $itemValue
     * @return void
     */
    public function add($item, $itemValue = null) {

        if ($item instanceof Sabre_VObject_Element) {
            if (!is_null($itemValue)) {
                throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject');
            }
            $item->parent = $this;
            $this->children[] = $item;
        } elseif(is_string($item)) {

            if (!is_scalar($itemValue)) {
                throw new InvalidArgumentException('The second argument must be scalar');
            }
            $item = Sabre_VObject_Property::create($item,$itemValue);
            $item->parent = $this;
            $this->children[] = $item;

        } else {

            throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string');

        }

    }

    /**
     * Returns an iterable list of children
     *
     * @return Sabre_VObject_ElementList
     */
    public function children() {

        return new Sabre_VObject_ElementList($this->children);

    }

    /**
     * Returns an array with elements that match the specified name.
     *
     * This function is also aware of MIME-Directory groups (as they appear in
     * vcards). This means that if a property is grouped as "HOME.EMAIL", it
     * will also be returned when searching for just "EMAIL". If you want to
     * search for a property in a specific group, you can select on the entire
     * string ("HOME.EMAIL"). If you want to search on a specific property that
     * has not been assigned a group, specify ".EMAIL".
     *
     * Keys are retained from the 'children' array, which may be confusing in
     * certain cases.
     *
     * @param string $name
     * @return array
     */
    public function select($name) {

        $group = null;
        $name = strtoupper($name);
        if (strpos($name,'.')!==false) {
            list($group,$name) = explode('.', $name, 2);
        }

        $result = array();
        foreach($this->children as $key=>$child) {

            if (
                strtoupper($child->name) === $name &&
                (is_null($group) || ( $child instanceof Sabre_VObject_Property && strtoupper($child->group) === $group))
            ) {

                $result[$key] = $child;

            }
        }

        reset($result);
        return $result;

    }

    /**
     * This method only returns a list of sub-components. Properties are
     * ignored.
     *
     * @return array
     */
    public function getComponents() {

        $result = array();
        foreach($this->children as $child) {
            if ($child instanceof Sabre_VObject_Component) {
                $result[] = $child;
            }
        }

        return $result;

    }

    /* Magic property accessors {{{ */

    /**
     * Using 'get' you will either get a property or component,
     *
     * If there were no child-elements found with the specified name,
     * null is returned.
     *
     * @param string $name
     * @return Sabre_VObject_Property
     */
    public function __get($name) {

        $matches = $this->select($name);
        if (count($matches)===0) {
            return null;
        } else {
            $firstMatch = current($matches);
            /** @var $firstMatch Sabre_VObject_Property */
            $firstMatch->setIterator(new Sabre_VObject_ElementList(array_values($matches)));
            return $firstMatch;
        }

    }

    /**
     * This method checks if a sub-element with the specified name exists.
     *
     * @param string $name
     * @return bool
     */
    public function __isset($name) {

        $matches = $this->select($name);
        return count($matches)>0;

    }

    /**
     * Using the setter method you can add properties or subcomponents
     *
     * You can either pass a Sabre_VObject_Component, Sabre_VObject_Property
     * object, or a string to automatically create a Property.
     *
     * If the item already exists, it will be removed. If you want to add
     * a new item with the same name, always use the add() method.
     *
     * @param string $name
     * @param mixed $value
     * @return void
     */
    public function __set($name, $value) {

        $matches = $this->select($name);
        $overWrite = count($matches)?key($matches):null;

        if ($value instanceof Sabre_VObject_Component || $value instanceof Sabre_VObject_Property) {
            $value->parent = $this;
            if (!is_null($overWrite)) {
                $this->children[$overWrite] = $value;
            } else {
                $this->children[] = $value;
            }
        } elseif (is_scalar($value)) {
            $property = Sabre_VObject_Property::create($name,$value);
            $property->parent = $this;
            if (!is_null($overWrite)) {
                $this->children[$overWrite] = $property;
            } else {
                $this->children[] = $property;
            }
        } else {
            throw new InvalidArgumentException('You must pass a Sabre_VObject_Component, Sabre_VObject_Property or scalar type');
        }

    }

    /**
     * Removes all properties and components within this component.
     *
     * @param string $name
     * @return void
     */
    public function __unset($name) {

        $matches = $this->select($name);
        foreach($matches as $k=>$child) {

            unset($this->children[$k]);
            $child->parent = null;

        }

    }

    /* }}} */

    /**
     * This method is automatically called when the object is cloned.
     * Specifically, this will ensure all child elements are also cloned.
     *
     * @return void
     */
    public function __clone() {

        foreach($this->children as $key=>$child) {
            $this->children[$key] = clone $child;
            $this->children[$key]->parent = $this;
        }

    }

}


text:
<?php
/*
 *---------------------------------------------------------------
 * Main CCF configuration
 *---------------------------------------------------------------
 *
 * Take a look at the core main configuration file to see
 * what options are around. .../CCF/vendor/clancats/core/config/main.config.php
 */
return array(

	/*
	 * URL configuration
	 */
	'url'	=> array(
		// if not in the root directory set the path offset.
		'path'		=> '/',
	),

	/*
	 * Security
	 */
	'security' => array(
		// it is really important that you choose your own one!
		'salt' => 'HdD21Ut/}Ã&:ÄhP¶\ZB{œN}9{O?+$,+',
	),
);

redpajama_set_name: RedPajamaGithub


text:
title: Develop with Docker Engine API
description: Using Docker APIs to automate Docker tasks in your language of choice
keywords: developing, api
redirect_from:
- /engine/reference/api/
- /engine/reference/api/docker_remote_api/
- /reference/api/
- /reference/api/docker_remote_api/
- /reference/api/docker_remote_api_v1.0/
- /reference/api/docker_remote_api_v1.1/
- /reference/api/docker_remote_api_v1.2/
- /reference/api/docker_remote_api_v1.3/
- /reference/api/docker_remote_api_v1.4/
- /reference/api/docker_remote_api_v1.5/
- /reference/api/docker_remote_api_v1.6/
- /reference/api/docker_remote_api_v1.7/
- /reference/api/docker_remote_api_v1.8/
- /reference/api/docker_remote_api_v1.9/
- /reference/api/docker_remote_api_v1.10/
- /reference/api/docker_remote_api_v1.11/
- /reference/api/docker_remote_api_v1.12/
- /reference/api/docker_remote_api_v1.13/
- /reference/api/docker_remote_api_v1.14/
- /reference/api/docker_remote_api_v1.15/
- /reference/api/docker_remote_api_v1.16/
- /reference/api/docker_remote_api_v1.17/
---

Docker provides an API for interacting with the Docker daemon (called the Docker
Engine API), as well as SDKs for Go and Python. The SDKs allow you to build and
scale Docker apps and solutions quickly and easily. If Go or Python don't work
for you, you can use the Docker Engine API directly.

For information about Docker Engine SDKs, see [Develop with Docker Engine SDKs](/engine/api/sdk/).

The Docker Engine API is a RESTful API accessed by an HTTP client such as `wget` or
`curl`, or the HTTP library which is part of most modern programming languages.

## View the API reference

You can
[view the reference for the latest version of the API](/engine/api/latest/)
or [choose a specific version](/engine/api/version-history/).

## Versioned API and SDK

The version of the Docker Engine API you should use depends upon the version of
your Docker daemon and Docker client.

A given version of the Docker Engine SDK supports a specific version of the
Docker Engine API, as well as all earlier versions. If breaking changes occur,
they are documented prominently.

> Daemon and client API mismatches
>
> The Docker daemon and client do not necessarily need to be the same version
> at all times. However, keep the following in mind.
>
> - If the daemon is newer than the client, the client does not know about new
>   features or deprecated API endpoints in the daemon.
>
> - If the client is newer than the daemon, the client can request API
>   endpoints that the daemon does not know about.

A new version of the API is released when new features are added. The Docker API
is backward-compatible, so you do not need to update code that uses the API
unless you need to take advantage of new features.

To see the highest version of the API your Docker daemon and client support, use
`docker version`:

```console
$ docker version

Client: Docker Engine - Community
 Version:           20.10.0
 API version:       1.41
 Go version:        go1.13.15
 Git commit:        7287ab3
 Built:             Tue Dec  8 19:00:39 2020
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true
Server: Docker Engine - Community
 Engine:
  Version:          20.10.0
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       eeddea2
  Built:            Tue Dec  8 18:58:12 2020
  OS/Arch:          linux/amd64
  ...
```

You can specify the API version to use, in one of the following ways:

- When using the SDK, use the latest version you can, but at least the version
  that incorporates the API version with the features you need.

- When using `curl` directly, specify the version as the first part of the URL.
  For instance, if the endpoint is `/containers/`, you can use
  `/v1.41/containers/`.

- To force the Docker CLI or the Docker Engine SDKs to use an old version
  of the API than the version reported by `docker version`, set the
  environment variable `DOCKER_API_VERSION` to the correct version. This works
  on Linux, Windows, or macOS clients.

  ```console
  $ DOCKER_API_VERSION='1.41'
  ```

  While the environment variable is set, that version of the API is used, even
  if the Docker daemon supports a newer version. This environment variable
  disables API version negotiation, and as such should only be used if you must
  use a specific version of the API, or for debugging purposes.

- The Docker Go SDK allows you to enable API version negotiation, automatically
  selects an API version that is supported by both the client, and the Docker Engine
  that is used.

- For the SDKs, you can also specify the API version programmatically, as a
  parameter to the `client` object. See the
  [Go constructor](https://github.com/moby/moby/blob/v19.03.6/client/client.go#L119){: target="_blank" rel="noopener" class="_"}
  or the
  [Python SDK documentation for `client`](https://docker-py.readthedocs.io/en/stable/client.html){: target="_blank" rel="noopener" class="_"}.

### API version matrix

{% include api-version-matrix.md %}

### Archived API versions

Documentation for older versions of the API has been archived, but can be found
in the [docker code repository on GitHub](https://github.com/moby/moby/tree/v1.9.1/docs/reference/api){: target="_blank" rel="noopener" class="_"}


text:
/// <autosync enabled="true" />
/// <reference path="core/jquery/jquery-2.1.1.js" />
/// <reference path="core/jquery/jquery.validate.js" />
/// <reference path="core/jquery/jquery.validate.unobtrusive.js" />
/// <reference path="core/various/modernizr-2.8.3.js" />
/// <reference path="core/various/respond.js" />
/// <reference path="core/various/respond.matchmedia.addlistener.js" />
/// <reference path="core/angular/angular-mocks.js" />
/// <reference path="core/angular/angular.js" />
/// <reference path="angular/back-img-directive.js" />
/// <reference path="angular/bodyctrl.js" />
/// <reference path="angular/frontpage/frontpagectrl.js" />
/// <reference path="core/bootstrap/bootstrap.min.js" />
/// <reference path="npm.js" />
/// <reference path="core/angular/angular-route.min.js" />
/// <reference path="angular/recruitment/recruitmentctrl.js" />


text:
import moment from 'moment';
import Needle from './needle';
import { SamayType } from '../constants';

export default class TODNeedle extends Needle {

  stitch(parsedInfo) {
    const hasOnlyTime = !parsedInfo.relativeDayParser && !parsedInfo.dowParser &&
      !parsedInfo.dateParser && !parsedInfo.numberRelativeParser && !!parsedInfo.todParser;

    if (hasOnlyTime) {
      const secondsOfDay = super.extractTime(parsedInfo);
      const finalDT = moment();
      finalDT.hours(0);
      finalDT.minutes(0);
      finalDT.seconds(0);
      finalDT.milliseconds(0);
      finalDT.add(secondsOfDay, 's');
      return { value: finalDT, samayType: SamayType.TIME_OF_DAY, hasTime: true };
    }
    return super.stitch(parsedInfo);
  }

}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <link rel="stylesheet" href="css/binaryCalculator.css" type="text/css"/>
        <title>Binary Calculator</title>

            <button id="btn0" class="btn numbers">0</button>
            <button id="btn1" class="btn numbers">1</button>
            <button id="btnClr" class="btn control-key">C</button>
            <button id="btnEql" class="btn control-key">=</button>
            <button id="btnSum" class="btn operation-key">+</button>
            <button id="btnSub" class="btn operation-key">-</button>
            <button id="btnMul" class="btn operation-key">*</button>
            <button id="btnDiv" class="btn operation-key">/</button>


text:
h2{font-size: 12px;color: #000000;padding:10px 0;}
.mceActionPanel{margin:20px 0;padding-bottom: 5px;}
.diy{margin:5px 5px -5px 10px;}
.section{background: #EFEFEF;margin: 30px 0;}
ul#gda-tabs{height: 28px;line-height: 25px;list-style: none;border-bottom: 1px solid #DDD;background: none;padding: 0px;}
#gda-tabs li{float: left;display: inline;margin: 0 1px -1px 0;padding: 0 13px 1px;color: #777;cursor: pointer;background: #F9F9F9;border: 1px solid #E4E4E4;border-bottom: 1px solid #F9F9F9;position: relative;height: auto !important ;line-height: inherit !important;}
#gda-tabs li:hover,
.vertical #gda-tabs li:hover{color: #F70;padding: 0 13px;background: #FFFFDF;border: 1px solid #FFCA95;}
#gda-tabs li.current{color: #444;background: #EFEFEF;padding: 0 13px 2px;border: 1px solid #D4D4D4;border-bottom: 1px solid #EFEFEF;}
.box{display: none;border: 1px solid #D4D4D4;border-width: 0 1px 1px;background: #EFEFEF;padding: 0 12px;padding-bottom: 15px;}
.box.visible{display: block;}
.error{border: 1px solid red;}
/* custom */
#grpdocsa-popup{background: #f1f1f1;position: absolute;top: 200px;left: 400px;width: 400px;border: 1px solid #999;color: #555;display: none;}
#grpdocsa-dialog-header{background: rgb(58, 58, 58);color: #f1f1f1;font-size: 14px;text-align: center;padding: 3px 0;}
#gda-dialog{padding: 10px;}
#shortcode{width:398px;}
#info-wrapper td{padding-bottom:5px;}
.dwl_gray strong{padding-right:15px;}


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="generator" content="Hugo 0.26" />

  <title>Open Source · StatSnips</title>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/0.6.2/pure-min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/0.6.2/grids-responsive-min.css">

  <link rel="stylesheet" href="../../css/side-menu.css">

  <link rel="stylesheet" href="../../css/blackburn.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet" type="text/css">

  <link rel="alternate" type="application/rss+xml" title="StatSnips" href="https://statsnips.github.io/tags/open-source/index.xml" />

  <link rel="shortcut icon" href="https://statsnips.github.ioimg/favicon.ico" type="image/x-icon" />

  <img src="https://raw.githubusercontent.com/StatSnips/statsnips.github.io/master/images/logo.png" height=25

          Home

          About

          Archive

          Authors

          Contact

          Blog GitHub

      RSS

      Twitter

      LinkedIn

      GitHub

      GitLab

      Stack Overflow

    © 2017-2018 StatSnips. Distributed Under a MIT License.

    Built with Hugo and Blogdown
    Theme Blackburn

Open Source

Hello World

    <time>12 Dec 2016</time>

      Alvin Thomas

      General /

      Open Source

  You might not think that programmers are artists, but programming is an extremely creative profession. It's logic-based creativity. - John Romero
 I hope to use this space to post code snippets to make my life and the lives of other statistical programmers easier. As an epidemiologist, I use data from national registries and clinical trials to answer interesting questions in public health, surgery, and medicine. I code mostly in Stata and R, but I'm always interested in optimizing my workflow and learning new techniques.

    Read more


text:
class CreateCampaigns < ActiveRecord::Migration
  def change
    create_table :campaigns do |t|
      t.string :name
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :campaigns, :users
  end
end


text:
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime;

namespace System.Threading
{
    //
    // Methods for accessing memory with volatile semantics.
    //
    public unsafe static class Volatile
    {
        #region Boolean
        private struct VolatileBoolean { public volatile Boolean Value; }

        public static Boolean Read(ref Boolean location)
        {
            fixed (Boolean* p = &location)
            {
                return ((VolatileBoolean*)p)->Value;
            }
        }

        public static void Write(ref Boolean location, Boolean value)
        {
            fixed (Boolean* p = &location)
            {
                ((VolatileBoolean*)p)->Value = value;
            }
        }
        #endregion

        #region Byte
        private struct VolatileByte { public volatile Byte Value; }

        public static Byte Read(ref Byte location)
        {
            fixed (Byte* p = &location)
            {
                return ((VolatileByte*)p)->Value;
            }
        }

        public static void Write(ref Byte location, Byte value)
        {
            fixed (Byte* p = &location)
            {
                ((VolatileByte*)p)->Value = value;
            }
        }
        #endregion

        #region Double

        public static Double Read(ref Double location)
        {
            fixed (Double* p = &location)
            {
                Int64 result = Read(ref *(Int64*)p);
                return *(double*)&result;
            }
        }

        public static void Write(ref Double location, Double value)
        {
            fixed (Double* p = &location)
            {
                Write(ref *(Int64*)p, *(Int64*)&value);
            }
        }
        #endregion

        #region Int16
        private struct VolatileInt16 { public volatile Int16 Value; }

        public static Int16 Read(ref Int16 location)
        {
            fixed (Int16* p = &location)
            {
                return ((VolatileInt16*)p)->Value;
            }
        }

        public static void Write(ref Int16 location, Int16 value)
        {
            fixed (Int16* p = &location)
            {
                ((VolatileInt16*)p)->Value = value;
            }
        }
        #endregion

        #region Int32
        private struct VolatileInt32 { public volatile Int32 Value; }

        public static Int32 Read(ref Int32 location)
        {
            fixed (Int32* p = &location)
            {
                return ((VolatileInt32*)p)->Value;
            }
        }

        public static void Write(ref Int32 location, Int32 value)
        {
            fixed (Int32* p = &location)
            {
                ((VolatileInt32*)p)->Value = value;
            }
        }
        #endregion

        #region Int64

        public static Int64 Read(ref Int64 location)
        {
#if BIT64
            fixed (Int64* p = &location)
            {
                return (Int64)Read(ref *(IntPtr*)p);
            }
#else
            return Interlocked.CompareExchange(ref location, 0, 0);
#endif
        }

        public static void Write(ref Int64 location, Int64 value)
        {
#if BIT64
            fixed (Int64* p = &location)
            {
                Write(ref *(IntPtr*)p, (IntPtr)value);
            }
#else
            Interlocked.Exchange(ref location, value);
#endif
        }
        #endregion

        #region IntPtr
        private struct VolatileIntPtr { public volatile IntPtr Value; }

        public static IntPtr Read(ref IntPtr location)
        {
            fixed (IntPtr* p = &location)
            {
                return ((VolatileIntPtr*)p)->Value;
            }
        }

        public static void Write(ref IntPtr location, IntPtr value)
        {
            fixed (IntPtr* p = &location)
            {
                ((VolatileIntPtr*)p)->Value = value;
            }
        }
        #endregion

        #region SByte
        private struct VolatileSByte { public volatile SByte Value; }

        [CLSCompliant(false)]
        public static SByte Read(ref SByte location)
        {
            fixed (SByte* p = &location)
            {
                return ((VolatileSByte*)p)->Value;
            }
        }

        [CLSCompliant(false)]
        public static void Write(ref SByte location, SByte value)
        {
            fixed (SByte* p = &location)
            {
                ((VolatileSByte*)p)->Value = value;
            }
        }
        #endregion

        #region Single
        private struct VolatileSingle { public volatile Single Value; }

        public static Single Read(ref Single location)
        {
            fixed (Single* p = &location)
            {
                return ((VolatileSingle*)p)->Value;
            }
        }

        public static void Write(ref Single location, Single value)
        {
            fixed (Single* p = &location)
            {
                ((VolatileSingle*)p)->Value = value;
            }
        }
        #endregion

        #region UInt16
        private struct VolatileUInt16 { public volatile UInt16 Value; }

        [CLSCompliant(false)]
        public static UInt16 Read(ref UInt16 location)
        {
            fixed (UInt16* p = &location)
            {
                return ((VolatileUInt16*)p)->Value;
            }
        }

        [CLSCompliant(false)]
        public static void Write(ref UInt16 location, UInt16 value)
        {
            fixed (UInt16* p = &location)
            {
                ((VolatileUInt16*)p)->Value = value;
            }
        }
        #endregion

        #region UInt32
        private struct VolatileUInt32 { public volatile UInt32 Value; }

        [CLSCompliant(false)]
        public static UInt32 Read(ref UInt32 location)
        {
            fixed (UInt32* p = &location)
            {
                return ((VolatileUInt32*)p)->Value;
            }
        }

        [CLSCompliant(false)]
        public static void Write(ref UInt32 location, UInt32 value)
        {
            fixed (UInt32* p = &location)
            {
                ((VolatileUInt32*)p)->Value = value;
            }
        }
        #endregion

        #region UInt64

        [CLSCompliant(false)]
        public static UInt64 Read(ref UInt64 location)
        {
            fixed (UInt64* p = &location)
            {
                return (UInt64)Read(ref *(Int64*)p);
            }
        }

        [CLSCompliant(false)]
        public static void Write(ref UInt64 location, UInt64 value)
        {
            fixed (UInt64* p = &location)
            {
                Write(ref *(Int64*)p, (Int64)value);
            }
        }
        #endregion

        #region UIntPtr
        private struct VolatileUIntPtr { public volatile UIntPtr Value; }

        [CLSCompliant(false)]
        public static UIntPtr Read(ref UIntPtr location)
        {
            fixed (UIntPtr* p = &location)
            {
                return ((VolatileUIntPtr*)p)->Value;
            }
        }

        [CLSCompliant(false)]
        public static void Write(ref UIntPtr location, UIntPtr value)
        {
            fixed (UIntPtr* p = &location)
            {
                ((VolatileUIntPtr*)p)->Value = value;
            }
        }
        #endregion

        #region T

        public static T Read<T>(ref T location) where T : class
        {
            //@TODO: need intrinsic implementation of Volatile.Read<T>, or some way to take the address of a reference.
            return Interlocked.CompareExchange(ref location, null, null);
        }

        public static void Write<T>(ref T location, T value) where T : class
        {
            //@TODO: need intrinsic implementation of Volatile.Write<T>, or some way to take the address of a reference.
            Interlocked.Exchange(ref location, value);
        }
        #endregion
    }
}


text:
// TADlg.cpp : implementation file
//

#include "stdafx.h"
#include "TA.h"
#include "TADlg.h"
#include "afxdialogex.h"
#include "resource.h"
#include "DlgPreview.h"
#include "../rui/RUIServerPeer.h"
#include "DlgSerial.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

UINT WM_TA_INIT			= ::RegisterWindowMessage(_T("WM_TA_INIT" ));
UINT WM_TA_STATEUPDATE	= ::RegisterWindowMessage(_T("WM_TA_STATEUPDATE" ));
UINT WM_TA_LOG			= ::RegisterWindowMessage(_T("WM_TA_LOG"));
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnEditCut();
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
	ON_COMMAND(ID_EDIT_CUT, &CAboutDlg::OnEditCut)
END_MESSAGE_MAP()

// CTADlg dialog

CString getIPAddress();
CString GetVersionInfo(HMODULE hLib);

CTADlg::CTADlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CTADlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_pra = NULL;
	m_preview = NULL;
}

CTADlg::~CTADlg()
{
		//--- set TA log callback
	m_pra->SetIncomingTALogCallback(0,0);
	m_pra->exit_ra();
	delete m_pra; m_pra = NULL;
}

void CTADlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_STATIC_STATUS, m_status);
	DDX_Control(pDX, IDC_EDIT_TALOG, m_talog);
	DDX_Control(pDX, IDC_LIST_DEVICE, m_devList);
	DDX_Control(pDX, IDC_EDIT_TANAME, m_taName);
	DDX_Control(pDX, IDC_IPADDRESS, m_taIP);
	DDX_Control(pDX, IDC_IPPORT, m_taPort);
	DDX_Control(pDX, IDC_INFO_INTERNALIP, m_taInternalIP);
	DDX_Control(pDX, IDC_CHECK_AUTOSTART, m_bAutoStart);
	DDX_Control(pDX, IDC_COMBO_AUDIO, m_audioList);
	DDX_Control(pDX, IDC_CHECK_FORCE_MONKEY, m_bForceMonkey);
}

BEGIN_MESSAGE_MAP(CTADlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_START, &CTADlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_STOP, &CTADlg::OnBnClickedButtonStop)
	ON_BN_CLICKED(IDC_BUTTON_PREVIEW, &CTADlg::OnBnClickedButtonPreview)
	ON_MESSAGE(WM_PREVIEW_CLOSED, &CTADlg::OnPreviewWindowClosed)
	ON_BN_CLICKED(IDC_BUTTON_CHANGE_TASERIAL, &CTADlg::OnBnClickedButtonChangeTaserial)
	ON_REGISTERED_MESSAGE(WM_RUIC_RESTART_ENCODER   , OnRUICMD_RestartEncoder  )
	ON_REGISTERED_MESSAGE(WM_RUIC_START_STREAMING   , OnRUICMD_StartStreaming  )
	ON_REGISTERED_MESSAGE(WM_UPDATE_CONNECTION      , OnUpdateConnection       )
	ON_BN_CLICKED(IDC_BUTTON_RESCAN, &CTADlg::OnBnClickedButtonRescan)
	ON_BN_CLICKED(IDC_CHECK_AUTOSTART, &CTADlg::OnBnClickedCheckAutostart)
	ON_BN_CLICKED(IDC_CHECK_FORCE_MONKEY, &CTADlg::OnBnClickedCheckForceMonkey)
	ON_REGISTERED_MESSAGE(WM_TA_INIT , taInit )
	ON_REGISTERED_MESSAGE(WM_TA_STATEUPDATE , RefreshTAState )
	ON_REGISTERED_MESSAGE(WM_TA_LOG , OnTALog )
	ON_WM_CLOSE()
	ON_WM_DESTROY()
	ON_WM_ACTIVATE()
	ON_WM_MOUSEACTIVATE()
	ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

// CTADlg message handlers

BOOL CTADlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	//SetTimer(0x0012, 1000, NULL);
	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}
	CString title; title.LoadString(IDS_TA);
	title.Append(" (");
	title.Append(GetVersionInfo(0));
	title.Append(")");
	this->SetWindowText(title);

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	setStatus(IDS_RA_INITIALIZE);

	PostMessage(WM_TA_INIT,0,0);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTADlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTADlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTADlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CTADlg::lock_control(bool bSet)
{
	m_devList.EnableWindow(!bSet);
	GetDlgItem(IDC_BUTTON_START)->EnableWindow(!bSet);
	GetDlgItem(IDC_BUTTON_STOP)->EnableWindow(bSet);
	GetDlgItem(IDC_BUTTON_PREVIEW)->EnableWindow(bSet);
	GetDlgItem(IDC_BUTTON_RESCAN)->EnableWindow(!bSet);
	GetDlgItem(IDC_BUTTON_CHANGE_TASERIAL)->EnableWindow(!bSet);
	GetDlgItem(IDC_IPADDRESS)->EnableWindow(!bSet);
	GetDlgItem(IDC_IPPORT)->EnableWindow(!bSet);
	GetDlgItem(IDC_COMBO_AUDIO)->EnableWindow(!bSet);
	GetDlgItem(IDC_CHECK_FORCE_MONKEY)->EnableWindow(!bSet);
}

void CTADlg::lock_control_all(bool bSet)
{
	m_devList.EnableWindow(bSet);
	GetDlgItem(IDC_BUTTON_START)->EnableWindow(bSet);
	GetDlgItem(IDC_BUTTON_STOP)->EnableWindow(bSet);
	GetDlgItem(IDC_BUTTON_PREVIEW)->EnableWindow(bSet);
	GetDlgItem(IDC_BUTTON_RESCAN)->EnableWindow(bSet);
	GetDlgItem(IDC_BUTTON_CHANGE_TASERIAL)->EnableWindow(bSet);
	GetDlgItem(IDC_IPADDRESS)->EnableWindow(bSet);
	GetDlgItem(IDC_IPPORT)->EnableWindow(bSet);
	GetDlgItem(IDC_COMBO_AUDIO)->EnableWindow(bSet);
	GetDlgItem(IDC_CHECK_FORCE_MONKEY)->EnableWindow(bSet);
}

LRESULT CTADlg::RefreshTAState(WPARAM wParam, LPARAM lParam)
{
	int bDev = (int)wParam;

	if( bDev )
	{
		CString buf;

		buf.Format("%d", m_pra->m_fbcWidth);
		SetDlgItemText(IDC_INFO_WIDTH, buf);

		buf.Format("%d", m_pra->m_fbcHeight);
		SetDlgItemText(IDC_INFO_HEIGHT, buf);

		buf.Format("%d", m_pra->m_fbcBPP);
		SetDlgItemText(IDC_INFO_BPP, buf);
		if( m_pra->m_state >= TA_STATE_START_SERVICE && m_pra->m_state < TA_STATE_SERVICE_STOP)
			lock_control(true);

		SetDlgItemText(IDC_INFO_MODEL, m_pra->m_devModel);
		SetDlgItemText(IDC_INFO_MANUFACTURER, m_pra->m_devManufacture);
		SetDlgItemText(IDC_INFO_BUILD, m_pra->m_devBuild);
		SetDlgItemText(IDC_INFO_SDK, m_pra->m_devSDKVer);
		SetDlgItemText(IDC_INFO_SERIAL, m_pra->m_devBuildSerial);
		SetDlgItemText(IDC_INFO_IMEI, m_pra->m_devIMEI);
		SetDlgItemText(IDC_INFO_USIM, m_pra->m_devUSIM);
		SetDlgItemText(IDC_INFO_USIM, m_pra->m_devSIMSerial);
		SetDlgItemText(IDC_INFO_PHONENO, m_pra->m_devPhoneNO);

		buf.Format("%4.1f", m_pra->m_devTemperature / 10.0f);
		SetDlgItemText(IDC_INFO_TEMP, buf);

		buf.Format("%d %%", m_pra->m_devBattLvl);
		SetDlgItemText(IDC_INFO_BATLEVEL, buf);

		if( m_pra->m_devStatus & TDC_STATUS_SCREENON )
		{
			SetDlgItemText(IDC_INFO_SCREEN, "ON");
		}
		else
		{
			SetDlgItemText(IDC_INFO_SCREEN, "OFF");
		}

		if( m_pra->m_fbcTouch  )
		{
			SetDlgItemText(IDC_INFO_EVENTMETHOD, "RAW");
		}
		else
		{
			SetDlgItemText(IDC_INFO_EVENTMETHOD, "Monkey");
		}

		buf = "";
		if ( m_pra->m_devStatus & TDC_STATUS_ROTATEAUTO )
			buf = "Auto ";

		int nRotate = m_pra->m_devStatus & TDC_STATUS_ROTATE;
		switch( nRotate )
		{
		case 0 : buf += "(0)"; break;
		case 1 : buf += "(90)"; break;
		case 2 : buf += "(180)"; break;
		case 3 : buf += "(270)"; break;
		}

		SetDlgItemText(IDC_INFO_ROTATION, buf);

	// Command Socket
	}
	else
	{
		// IDC_STATIC_SYSTIME
		CString time;
		SYSTEMTIME st;
		::GetLocalTime(&st);
		time.Format("%d-%d-%d %d:%d:%d",
			st.wYear,
			st.wMonth,
			st.wDay,
			st.wHour,
			st.wMinute,
			st.wSecond);
		SetDlgItemText(IDC_STATIC_SYSTIME, time);

		// IDC_STATIC_FBC
		if( m_pra->m_hfbcThread )
			SetDlgItemText(IDC_STATIC_FBC, "Working");
		else
			SetDlgItemText(IDC_STATIC_FBC, "Stopped");

		// IDC_STATIC_TDC
		if( m_pra->m_htdcThread )
			SetDlgItemText(IDC_STATIC_TDC, "Working");
		else
			SetDlgItemText(IDC_STATIC_TDC, "Stopped");

		// IDC_STATIC_EVT
		if( m_pra->m_monkeysock != INVALID_SOCKET )
			SetDlgItemText(IDC_STATIC_EVT, "Working");
		else
			SetDlgItemText(IDC_STATIC_EVT, "Stopped");

		// IDC_STATIC_CLIENT
		if( m_pra->m_state == TA_STATE_CLIENT_CONNECTED )
		{
			SetDlgItemText(IDC_STATIC_CLIENT, m_pra->m_clientIP);
			SetDlgItemText(IDC_INFO_CLIENT_ID, m_pra->m_clientReserveID);
			setStatus(IDS_RA_CONNECTED);
			CString fps;
			fps.Format("%5.2f (%5.2f)kBps", m_pra->m_serverFps, m_pra->m_serverBps);
			SetDlgItemText(IDC_INFO_FPS, fps);

			fps.Format("%5.2f (%5.2f)kBps", m_pra->m_clientFps, m_pra->m_clientBps);
			SetDlgItemText(IDC_INFO_CLIENT_FPS, fps);

			fps = DwordToTimedate(m_pra->m_clientValidStart);
			SetDlgItemText(IDC_STATIC_VALID_FROM, fps);

			fps = DwordToTimedate(m_pra->m_clientValidEnd);
			SetDlgItemText(IDC_STATIC_VALID_TO, fps);

		}
		else {
			SetDlgItemText(IDC_STATIC_CLIENT, "not connected");
			SetDlgItemText(IDC_INFO_CLIENT_ID, "");

			if( m_pra->m_state < TA_STATE_READY )
				setStatus(IDS_RA_INITIALIZE);
			else if( m_pra->m_state <= TA_STATE_AFTER_CLIENT_REINIT)
				setStatus(IDS_RA_WAITCLIENT);
			else if( m_pra->m_state > TA_STATE_AFTER_CLIENT_REINIT)
				setStatus(IDS_RA_STOPPED);
			SetDlgItemText(IDC_INFO_FPS, "");
			SetDlgItemText(IDC_INFO_CLIENT_FPS, "");
			SetDlgItemText(IDC_STATIC_VALID_FROM, "");
			SetDlgItemText(IDC_STATIC_VALID_TO, "");
		}

		if( m_pra->m_opt_screen ) // h.264
		{
			CString method;
			method = "H.264 ";
			if( m_pra->m_opt_h264_quality == 1 )
				method += "(Low)";
			else if( m_pra->m_opt_h264_quality == 2 )
				method += "(High)";
			else
				method += "(Normal)";

			SetDlgItemText(IDC_STATIC_SCRMETHOD, method);
		}
		else
		{
			SetDlgItemText(IDC_STATIC_SCRMETHOD, "Image");
		}

		if( m_pra->m_bStreamingAudio ) // h.264
			SetDlgItemText(IDC_STATIC_AUDIO, "ON");
		else
			SetDlgItemText(IDC_STATIC_AUDIO, "OFF");

	}

	return 0;
}

LRESULT CTADlg::taInit(WPARAM wParam, LPARAM lParam)
{
	lock_control_all(0);
	//--- Create RuiAgent
	m_pra = new RA(this);

	//--- set TA log callback
	m_pra->SetIncomingTALogCallback(OnImcomingTALog, this);

	//--- set TA state callback
	m_pra->SetTAStateReportCallback(OnTAState, this);

	//--- Init RA
	if( m_pra->init_ra() < 1 )
	{
		m_pra->DeviceStatusToPOC(8, 1, "Service Init Failed");
		m_pra->set_state(TA_STATE_ERR_INIT_RA);
		MessageBeep(-1);
	}

	//-- restore window position
	{
		char inifile[MAX_PATH];
		sprintf_s(inifile, "%s\\%s", m_pra->m_ModulePath, RUIINI);

		int x, y;
		x = GetPrivateProfileInt("TA", "x", -1, inifile);
		y  =  GetPrivateProfileInt("TA", "y", -1, inifile);
		if( x > 0 && y > 0 )
		{
			//m_pra->ta_log("\tRestore windows pos(%d,%d)", x, y);
			ShowWindow(SW_SHOW);
			SetWindowPos(&wndTopMost, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
		}
	}
	m_devList.ResetContent();
	for(int i=0; i< MAX_TD; i++)
	{
		if( m_pra->m_devSerial[i][0] )
			m_devList.AddString((LPCSTR)m_pra->m_devSerial[i]);
		else
			break;
	}

	m_audioList.ResetContent();
	CWaveInDevice* pDev = m_pra->m_waveInDeviceList.GetFirst();
	while( pDev )
	{
		m_audioList.AddString(pDev->GetDeviceName());
		pDev = m_pra->m_waveInDeviceList.GetNext(pDev);
	}

	m_bAutoStart.SetCheck(m_pra->m_bAutoStart);
	m_bForceMonkey.SetCheck(m_pra->m_bForceMonkey);

	//--- set control
	m_taName.SetWindowText(m_pra->m_taSerial);

	if( m_pra->m_devIndex >= 0 )
		m_devList.SetCurSel(m_pra->m_devIndex);
	else {
		//Message(IDS_TD_NOT_SET, MB_OK);
	}

	//m_pra->ta_log("audioIndex:%d", m_pra->m_audioIndex);
	if( m_pra->m_audioIndex >= 0 )
		m_audioList.SetCurSel(m_pra->m_audioIndex);

	m_taInternalIP.SetWindowText(getIPAddress());

	m_talog.SetLimitText(655350);

	m_taIP.SetAddress(m_pra->m_devExternalIP);
	char intbuf[12];
	sprintf_s(intbuf,"%d", m_pra->m_devExternalPort);
	m_taPort.SetWindowText( intbuf);
	lock_control(false);

	setStatus(IDS_RA_STOPPED);

	if(m_pra->m_bFirstRun)
	{
		ShowFirstRun(1);
	}
	if( m_pra->m_bAutoStart && m_pra->m_devIndex >= 0 && m_devList.GetCurSel() !=  LB_ERR)
	{
		//Sleep(1000);
		m_pra->ta_log("[Auto Start]");
		m_pra->ShowProgress(1, "Prepare Start Service", 1);
		Sleep(1000);
		m_pra->ShowProgress(0);
		OnBnClickedButtonStart();
	}

	return 0;
}

void CTADlg::ShowFirstRun(bool bShow)
{
	GetDlgItem(IDC_STATIC_1)->ShowWindow(bShow ? SW_SHOW : SW_HIDE);
	GetDlgItem(IDC_STATIC_2)->ShowWindow(bShow ? SW_SHOW : SW_HIDE);
	GetDlgItem(IDC_STATIC_3)->ShowWindow(bShow ? SW_SHOW : SW_HIDE);
	GetDlgItem(IDC_STATIC_4)->ShowWindow(bShow ? SW_SHOW : SW_HIDE);
	GetDlgItem(IDC_STATIC_5)->ShowWindow(bShow ? SW_SHOW : SW_HIDE);
}

void CTADlg::OnBnClickedButtonStart()
{
	if( (m_pra->m_devIndex = m_devList.GetCurSel()) ==  LB_ERR ) {
		m_pra->set_state(TA_STATE_ERR_DEVNOTFOUND);
		m_pra->DeviceStatusToPOC(8, 0, "Device not found error");
		Message(IDS_TD_NOT_SET, MB_OK | MB_ICONSTOP);
		return;
	}

	m_pra->ta_log("\t### Start Service Condition #####");
	m_pra->ta_log("\t\tTA Serial   \t: %s", m_pra->m_taSerial);
	m_pra->ta_log("\t\tADB Device  \t: %s", m_pra->m_devSerial[m_pra->m_devIndex]);
	m_pra->m_audioIndex = m_audioList.GetCurSel();
	if( m_pra->m_audioIndex >= 0 )
	{
		m_pra->ta_log("\t\tAudio Device\t: %s", m_pra->m_waveInDeviceList.GetAt(m_pra->m_audioIndex)->GetDeviceName());
		lstrcpy(m_pra->m_audioName, m_pra->m_waveInDeviceList.GetAt(m_pra->m_audioIndex)->GetDeviceName());
	}
	else
		m_pra->ta_log("\t\tAudio Device\t: WAVE_MAPPER(-1)");

	DWORD dwAddress;
	m_taIP.GetAddress(dwAddress);
	if( dwAddress == 0 )
	{
		m_pra->ta_log("ERR GetIP Address Failed");
		Message(IDS_IP_NOT_SET, MB_OK | MB_ICONSTOP);
		return;
	}
	CString csBuf;
	m_taIP.GetAddress(m_pra->m_devExternalIP);

	m_taPort.GetWindowText(csBuf);
	m_pra->m_devExternalPort = atoi(csBuf);

	IN_ADDR ip;
	ip.S_un.S_addr = m_pra->m_devExternalIP;
	m_pra->ta_log("\t\tListen IP   \t:%d.%d.%d.%d(%d)", ip.S_un.S_un_b.s_b4, ip.S_un.S_un_b.s_b3, ip.S_un.S_un_b.s_b2, ip.S_un.S_un_b.s_b1, m_pra->m_devExternalPort);
	m_pra->ta_log("\t#################################");

	setStatus(IDS_RA_STARTING);

	m_pra->m_bFirstRun = 0;
	ShowFirstRun(0);
	m_pra->save_ini();

	CWaitCursor waitcursor;
	lock_control(true);
	// start rui server
	if( m_pra->start_ta_service() <= 0 )
	{
		m_pra->set_state(TA_STATE_ERR_START_SERVICE);
		m_pra->DeviceStatusToPOC(8, 1, "Service Error");
		Message(IDS_TA_START_FAILED, MB_OK | MB_ICONSTOP);
		setStatus(IDS_RA_STOPPED);
		lock_control(false);
	} else {
		CString title; title.LoadString(IDS_TA);
		title.Append(" (");
		title.Append(GetVersionInfo(0));
		title.Append(")-(");
		title.Append(m_pra->m_taSerial);
		title.Append(":");
		CString buf;
		buf.Format("%d)",m_pra->m_devExternalPort);
		title.Append(buf);
		this->SetWindowText(title);
		setStatus(IDS_RA_WAITCLIENT);
		PostMessage(WM_TA_STATEUPDATE,0,0);
		//RefreshTAState();
	}
}

void CTADlg::OnBnClickedButtonStop()
{
	if( m_preview != NULL )
	{
		m_preview->DestroyWindow();
		m_preview = NULL;
	}

	CString title; title.LoadString(IDS_TA);
	title.Append(" (");
	title.Append(GetVersionInfo(0));
	title.Append(")");
	this->SetWindowText(title);

	m_pra->stop_ta_service();
	lock_control(false);
	m_pra->set_state(TA_STATE_SERVICE_STOP_DONE);
	setStatus(IDS_RA_STOPPED);
}

LRESULT CTADlg::OnTALog(WPARAM wParam, LPARAM lParam)
//void CTADlg::OnTALog(BYTE* buffer, int size)
{
	BYTE* buffer = (BYTE*)wParam;
	int size = (int)lParam;

	if( m_talog.GetSafeHwnd() == 0 )
		return 0;

	char buf[2048];
	//char *buf = (char*)malloc(size+1);
	_ASSERTE( _CrtCheckMemory( ) );
	memcpy(buf, (char*)buffer, size);
	buf[size] = 0;

	free(buffer);
	int nLength = m_talog.GetWindowTextLength();
	if( nLength + size > 32768 )
	{
		int nline = m_talog.GetLineCount();
		int nchar = m_talog.LineIndex(nline/2);
		m_talog.SetSel(0, nchar, 1);
		m_talog.ReplaceSel("\r\n");
		nLength = m_talog.GetWindowTextLength();
	}
	m_talog.SetSel(nLength+1, -1,1);
	m_talog.ReplaceSel(buf);
	m_talog.LineScroll(m_talog.GetLineCount());
	//free(buf);

	return 1;
}

void CTADlg::setStatus(UINT idMsg)
{
	CString msg;
	msg.LoadString(idMsg);
	m_status.SetWindowText(msg);
}

void CTADlg::OnBnClickedButtonPreview()
{
	if( GetKeyState(VK_CONTROL) & 0x8000 )
	{
		m_pra->ta_log("[force reinit for test]");
		m_pra->m_bInitRequiredTime = timedateToDword();
		m_pra->m_bInitRequired = 1;
		return;
	}

	//m_pra->ShutdownSocket(m_pra->m_clientSock);
	//m_pra->m_clientSock = INVALID_SOCKET;
	//return;

	if( m_preview )
	{
		m_preview->SetWindowPos(&wndTopMost, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE);
		return;
	}
	m_preview = new CDlgPreview(m_pra, this);
	m_preview->Create(CDlgPreview::IDD);
	m_preview->ShowWindow(SW_SHOW);
}

LRESULT CTADlg::OnPreviewWindowClosed(WPARAM wParam, LPARAM lParam)
{
	//delete m_preview;
	m_preview = NULL;

	return 0;
}

void CTADlg::OnBnClickedButtonChangeTaserial()
{
	DlgSerial dlg;
	m_taName.GetWindowText(dlg.m_Serial);

	if( dlg.DoModal() == IDOK )
	{
		m_taName.SetWindowText(dlg.m_Serial);
		lstrcpy(m_pra->m_taSerial, dlg.m_Serial);
		m_pra->save_ini();
	}
	//IDC_EDIT_TANAME
}

LRESULT CTADlg::OnRUICMD_RestartEncoder(WPARAM wParam, LPARAM lParam)
{
	//m_pra->ta_log(_T("[/RestartEncoder]"));

	m_pra->Video_StopEncoder();
	m_pra->Video_StartEncoder();
//	m_pra->m_bCaptureFlag = TRUE;

	return 0;
}

LRESULT CTADlg::OnRUICMD_StartStreaming(WPARAM wParam, LPARAM lParam)
{
	BYTE			nField0, nField1, nField2, nField3;
	RUIServerPeer*	pPeer = (RUIServerPeer*) lParam;
	if (pPeer != NULL)
	{
		pPeer->SetClientStreaming(TRUE);

		pPeer->GetPeerIP(nField0, nField1, nField2, nField3);
	}

	//m_pra->ta_log(_T("[%d.%d.%d.%d/StartStreaming]"), nField0, nField1, nField2, nField3);

	return 0;
}

// [neuromos] !ÀÌ°ÍÀ» RUITCPSockServer·Î ¿Å±â°í ½ÍÀ¸³ª PostMessage ÀÌ¿ÜÀÇ ¹æ¹ýÀÌ ¾Ö¸ÅÇÏ´Ù.
LRESULT CTADlg::OnUpdateConnection(WPARAM wParam, LPARAM lParam) // TCP ¼ÒÄÏ¿¡¼¸¸ »ç¿ëµÊ
{
	UINT			uEvent = (UINT) wParam;
	RUIServerPeer*	pPeer  = reinterpret_cast <RUIServerPeer*> (lParam);

	if (pPeer != NULL)
	{
		if (uEvent == EVT_CONSUCCESS) // Á¢¼Ó¿¡ ¼º°øÇÏ¿´´Ù¸é ´Ù¸¥ ¼¹ö¸¦ ½ÃÀÛÇÑ´Ù.
		{
			BYTE	nField0;
			BYTE	nField1;
			BYTE	nField2;
			BYTE	nField3;
			pPeer->GetPeerIP(nField0, nField1, nField2, nField3);

			CString	strIP;
			strIP.Format(_T("%d.%d.%d.%d"), nField0, nField1, nField2, nField3);

			//m_pra->ta_log(_T("Client Connected. (%s)"), (LPCTSTR) strIP);

			// [neuromos] RUITCPSockPeer::RUITCPSockPeer()¿¡¼ È£ÃâÇÑ´Ù. ¸Þ¼¼Áö°¡ ¸ÕÀú ¿Â´Ù¸é ¿À·ù ¹ß»ý!
//			pPeer->ResetSyncTick();

			if (! m_pra->m_bUseUDP)
				Sleep(100);
			else
				m_pra->Video_CreateUDPSock(pPeer, (LPCTSTR) strIP);

			InitIppExtensionParam_Connect(&(m_pra->m_ieParam));
			m_pra->m_ieParam.m_pEncoder = (void*) m_pra->m_threadEncoder.GetEncoder();

			//m_pra->m_TCPSockServer.StartServer();
		}

		else if (uEvent == EVT_CONFAILURE || uEvent == EVT_CONDROP)
		{
			if( m_pra->m_state < TA_STATE_SERVICE_STOP )
			{
				BYTE	nField0;
				BYTE	nField1;
				BYTE	nField2;
				BYTE	nField3;
				pPeer->GetPeerIP(nField0, nField1, nField2, nField3);

				//m_pra->ta_log(_T("Client Disconnected. (%d.%d.%d.%d)"), nField0, nField1, nField2, nField3);

				m_pra->Video_DestroyUDPSock(pPeer);
				pPeer->StopComm();
				//m_pra->m_TCPSockServer.StartServer();
			}
		}
	}

	return 1L;
}

CString getIPAddress()
{
	CString str;
	str.Empty();
 	//if ( gethostname("localhost", 256) == 0)
 	{
		PHOSTENT HostInfo;
		char* IPAdd;
		//printf("Host name: %s\n", name);
		if((HostInfo = gethostbyname("")) != NULL)
		{
			int nCount = 0;
			while(HostInfo->h_addr_list[nCount])
			{
				IPAdd = inet_ntoa(*(struct in_addr *)HostInfo->h_addr_list[nCount]);

				if(nCount > 0 ) str.Append(" / ");
				str.Append(IPAdd);
				++nCount;
			}
		}
 	}
	return str;
}

CString GetVersionInfo(HMODULE hLib)
{
  CString csRet;

  if (hLib == NULL)
    hLib = AfxGetResourceHandle();

  HRSRC hVersion = FindResource( hLib,
    MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION );
  if (hVersion != NULL)
  {
    HGLOBAL hGlobal = LoadResource( hLib, hVersion );
    if ( hGlobal != NULL)
    {

      LPVOID versionInfo  = LockResource(hGlobal);
      if (versionInfo != NULL)
      {
        DWORD vLen,langD;
        BOOL retVal;

        LPVOID retbuf=NULL;

        static char fileEntry[256];

        sprintf_s(fileEntry,"\\VarFileInfo\\Translation");
        retVal = VerQueryValue(versionInfo,fileEntry,&retbuf,(UINT *)&vLen);
        if (retVal && vLen==4)
        {
          memcpy(&langD,retbuf,4);
          sprintf_s(fileEntry, "\\StringFileInfo\\%02X%02X%02X%02X\\FileVersion",
                  (langD & 0xff00)>>8,langD & 0xff,(langD & 0xff000000)>>24,
                  (langD & 0xff0000)>>16);
        }
        else
          sprintf_s(fileEntry, "\\StringFileInfo\\%04X04B0\\FileVersion",
            GetUserDefaultLangID());

        if (VerQueryValue(versionInfo,fileEntry,&retbuf,(UINT *)&vLen))
          csRet = (char*)retbuf;
      }
    }

    UnlockResource( hGlobal );
    FreeResource( hGlobal );
  }

  return csRet;
}

void CAboutDlg::OnEditCut()
{
	// TODO: Add your command handler code here
}

void CTADlg::OnBnClickedButtonRescan()
{
	CWaitCursor waitcursor;

	m_devList.ResetContent();
	m_audioList.ResetContent();

	m_pra->ScanDevices();
	for(int i=0; i< MAX_TD; i++)
	{
		if( m_pra->m_devSerial[i][0] )
			m_devList.AddString((LPCSTR)m_pra->m_devSerial[i]);
		else
			break;
	}

	CWaveInDevice* pDev = m_pra->m_waveInDeviceList.GetFirst();
	while( pDev )
	{
		m_audioList.AddString(pDev->GetDeviceName());
		pDev = m_pra->m_waveInDeviceList.GetNext(pDev);
	}

	if( m_pra->m_devIndex >= 0 )
		m_devList.SetCurSel(m_pra->m_devIndex);
	else {
		Message(IDS_TD_NOT_SET, MB_OK);
	}

	if( m_pra->m_audioIndex >= 0 )
		m_audioList.SetCurSel(m_pra->m_audioIndex);

	m_pra->save_ini();
}

void CTADlg::OnBnClickedCheckAutostart()
{
	m_pra->m_bAutoStart = m_bAutoStart.GetCheck();

	m_pra->save_ini();
}

void CTADlg::OnBnClickedCheckForceMonkey()
{
	m_pra->m_bForceMonkey = m_bForceMonkey.GetCheck();

	m_pra->save_ini();
}

void CTADlg::OnDestroy()
{
	CRect rt;

	GetWindowRect(rt);
	TRACE("%d,%d\n", rt.left, rt.top);
	if( m_pra )
	{
		char inifile[MAX_PATH];
		char intbuf[64];
		sprintf_s(inifile, "%s\\%s", m_pra->m_ModulePath, RUIINI);

		itoa(rt.left, intbuf, 10);
		WritePrivateProfileString("TA", "x", intbuf, inifile);

		itoa(rt.top, intbuf, 10);
		WritePrivateProfileString("TA", "y", intbuf, inifile);
	}

	CDialogEx::OnDestroy();

	// TODO: Add your message handler code here
}

void CTADlg::OnLButtonDown(UINT nFlags, CPoint point)
{
	if( m_pra && m_pra->m_state >= TA_STATE_ERR_DEVNOTFOUND )
	{
		m_pra->set_state(TA_STATE_SERVICE_STOP_DONE);
	}

	CDialogEx::OnLButtonDown(nFlags, point);
}


text:
var child_process = require('child_process');
var path = require('path');
var fs = require('fs');
var readline = require('readline');
var chalk = require('chalk');
var StaticServer = require('static-server');
var proxyTool = require('./lib/proxyTools.js');
var defaults = require('./lib/defaults.js');

/**
 * 初始化gfe-proxy
 */
exports.init = function(config) {
    proxyTool.runProxy();
    stopProxyAddLisener();
    if (config.staticServer) {
        startStaticServer(config.staticServerHostname, config.staticServerPort);
    } else {
        runSuccTipsForGfeProxy();
        friendshipTips();
    }

    var cp = child_process.spawn('node', [
        '--harmony',
        path.join(__dirname, '/lib/app.js'),
        '--config=' + JSON.stringify(config)
    ]);

    cp.on('error', function(err) {
        console.log(err);
    });

    cp.on('exit', function() {
        proxyTool.stopProxy();
    });

    cp.stdout.pipe(process.stdout);
    cp.stderr.pipe(process.stderr);
};

/**
 * 手动清除代理
 */
exports.stopProxy = function() {
    proxyTool.stopProxy();
};

/**
 * 为停止代理添加监听器,用户退出时重置代理
 */
function stopProxyAddLisener() {
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    rl.on('SIGINT', function() {
        proxyTool.stopProxy();
        console.log(chalk.green.bold('  gfe-proxy 已正常停止!'));
        console.log();
        process.exit();
    });
}

/**
 * 启动static-server,用来代理被挂载目录
 * @param {String} server的端口号
 */
function startStaticServer(hostname, port) {
    var server = new StaticServer({
        rootPath: process.cwd(),
        port: port,
        host: hostname,
        templates: {}
    });

    server.start(function() {
        runSuccTipsForGfeProxy();
        runSuccTipsForStaticServer(hostname, port);
        friendshipTips();
    });
}

/**
 * gfe-proxy启动成功提示
 */
function runSuccTipsForGfeProxy() {
    console.log(chalk.green.bold('  gfe-proxy已成功启动!'));
}

/**
 * static-server启动成功提示
 */
function runSuccTipsForStaticServer(hostname, port) {
    console.log();
    console.log(chalk.blue('*'), '本地静态服务器运行地址 :', chalk.cyan.bold('http://' + hostname + ':' + port));
}

/**
 * 启动成功友情提示
 */
function friendshipTips() {
    console.log();
    console.log(chalk.red.bold('  友情提醒:'));
    console.log(chalk.blue('*'), '      1、请使用', chalk.yellow.bold('Ctrl+C'), '组合键来停止 gfe-proxy!');
    console.log(chalk.blue('*'), '      2、异常关闭 gfe-proxy 会导致不能上网,请执行 gfe-proxy stop 命令!');
    console.log(chalk.blue('*'), '      3、异常关闭指非 Ctrl+C 方式停止 gfe-proxy 外的所有场景,');
    console.log(chalk.blue('*'), '         如:手动关闭或从任务管理器直接结束正在运行 gfe-proxy 的命令窗口!');
    console.log();
}


text:
#pragma once

#include <vector>
#include <queue>
#include <random>
#include <inttypes.h>

#include "debugging.h"
#include "base/logging.h"

namespace base {

typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;

class SparseInt {
public:
    static size_t buf_size(char byte0);
    static size_t val_size(i64 val);
    static size_t dump(i32 val, char* buf);
    static size_t dump(i64 val, char* buf);
    static i32 load_i32(const char* buf);
    static i64 load_i64(const char* buf);
};

class v32 {
    i32 val_;
public:
    v32(i32 v = 0): val_(v) { }
    void set(i32 v) {
        val_ = v;
    }
    i32 get() const {
        return val_;
    }
    size_t val_size() const {
        return SparseInt::val_size(val_);
    }
};

class v64 {
    i64 val_;
public:
    v64(i64 v = 0): val_(v) { }
    void set(i64 v) {
        val_ = v;
    }
    i64 get() const {
        return val_;
    }
    size_t val_size() const {
        return SparseInt::val_size(val_);
    }
};

class NoCopy {
    MAKE_NOCOPY(NoCopy);
protected:
    NoCopy() {}
    virtual ~NoCopy() = 0;
};
inline NoCopy::~NoCopy() {}

/**
 * Note: All sub class of RefCounted *MUST* have protected destructor!
 * This prevents accidentally deleting the object.
 * You are only allowed to cleanup with release() call.
 * This is thread safe.
 */
class RefCounted: public NoCopy {
    volatile int refcnt_;
protected:
    virtual ~RefCounted() = 0;
public:
    RefCounted(): refcnt_(1) {}
    int ref_count() {
        return refcnt_;
    }
    RefCounted* ref_copy() {
        __sync_add_and_fetch(&refcnt_, 1);
        return this;
    }
    int release() {
        int r = __sync_sub_and_fetch(&refcnt_, 1);
        verify(r >= 0);
        if (r == 0) {
            delete this;
        }
        return r;
    }
};
inline RefCounted::~RefCounted() {}

class Counter: public NoCopy {
    volatile i64 next_;
public:
    Counter(i64 start = 0) : next_(start) { }
    i64 peek_next() const {
        return next_;
    }
    i64 next(i64 step = 1) {
        return __sync_fetch_and_add(&next_, step);
    }
    void reset(i64 start = 0) {
        next_ = start;
    }
};

class Timer {
public:
    Timer() { reset(); }
    void start();
    void stop();
    void reset();
    double elapsed() const;
private:
    struct timeval begin_;
    struct timeval end_;
};

class Rand: public NoCopy {
    std::mt19937 rand_;
public:
    Rand();
    std::mt19937::result_type next() {
        return rand_();
    }
    // [lower, upper)
    std::mt19937::result_type next(int lower, int upper) {
        return lower + rand_() % (upper - lower);
    }
    std::mt19937::result_type operator() () {
        return rand_();
    }
};

template<class T>
class Enumerator {
public:
    virtual ~Enumerator() {}
    virtual bool has_next() = 0;
    operator bool() {
        return this->has_next();
    }
    virtual T next() = 0;
    T operator() () {
        return this->next();
    }
};

// keep min-ordering
template<class T, class Compare = std::greater<T>>
class MergedEnumerator: public Enumerator<T> {
    struct merge_helper {
        T data;
        Enumerator<T>* src;

        merge_helper(const T& d, Enumerator<T>* s): data(d), src(s) {}

        bool operator < (const merge_helper& other) const {
            return Compare()(data, other.data);
        }
    };

    std::priority_queue<merge_helper, std::vector<merge_helper>> q_;

public:
    void add_source(Enumerator<T>* src) {
        if (src->has_next()) {
            q_.push(merge_helper(src->next(), src));
        }
    }
    bool has_next() {
        return !q_.empty();
    }
    T next() {
        const merge_helper& mh = q_.top();
        T ret = mh.data;
        Enumerator<T>* src = mh.src;
        q_.pop();
        if (src->has_next()) {
            q_.push(merge_helper(src->next(), src));
        }
        return ret;
    }
};

} // namespace base


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TransactionRequired.cs" company="Ginx Corp.">
//   Copyright © 2013 · Ginx Corp. · All rights reserved.
// </copyright>
// <summary>
//   Defines the TransactionRequired type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GinxFx.Data.NH
{
    using System;

    using NHibernate;

    /// <summary>
    /// Indicates that a block of code requires a transaction.
    /// If a transaction are already open, this class will reuse it and the context which opened the transaction will
    /// be responsible for commit it or rollback it.
    /// Multiple <see cref="TransactionRequired"/> can be opened in a call context, the first (also the top level)
    /// transaction required will be responsible for commits the transaction.
    /// </summary>
    public sealed class TransactionRequired : IDisposable
    {
        /// <summary>
        /// A flag indicating that this instance is responsible for commit the transaction.
        /// </summary>
        private readonly bool shouldCommit;

        /// <summary>
        /// A flag indicating that this transaction was completed.
        /// </summary>
        private bool completed;

        /// <summary>
        /// The current transaction.
        /// </summary>
        private ITransaction transaction;

        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionRequired"/> class.
        /// </summary>
        /// <param name="session">
        /// The session.
        /// </param>
        public TransactionRequired(ISession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            this.transaction = session.Transaction;

            if (IsOpenTransaction(this.transaction))
            {
                return;
            }

            this.transaction = session.BeginTransaction();
            this.shouldCommit = true;
        }

        /// <summary>
        /// Commits the transaction if this instance is responsible for it.
        /// </summary>
        public void Commit()
        {
            if (!this.shouldCommit)
            {
                return;
            }

            if (this.completed)
            {
                throw new InvalidOperationException(
                    "The current transaction is already committed. You should dispose the transaction.");
            }

            this.completed = true;

            try
            {
                if (IsOpenTransaction(this.transaction))
                {
                    this.transaction.Commit();
                    this.transaction = null;
                }
            }
            catch (StaleObjectStateException)
            {
                // TODO: Object was altered by other session
                this.Rollback();
                throw;
            }
            catch (HibernateException)
            {
                this.Rollback();
                throw;
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (!this.shouldCommit)
            {
                return;
            }

            this.Rollback();
        }

        /// <summary>
        /// Rollbacks the transaction.
        /// </summary>
        public void Rollback()
        {
            if (!this.shouldCommit)
            {
                return;
            }

            this.completed = true;

            if (IsOpenTransaction(this.transaction))
            {
                this.transaction.Rollback();
            }

            this.transaction = null;
        }

        /// <summary>
        /// Check if a transaction is already open.
        /// </summary>
        /// <param name="transaction">
        /// The transaction.
        /// </param>
        /// <returns>
        /// <c>true</c> if the <paramref name="transaction"/> is open, <c>false</c> otherwise.
        /// </returns>
        private static bool IsOpenTransaction(ITransaction transaction)
        {
            return transaction != null && transaction.IsActive && !transaction.WasCommitted
                   && !transaction.WasRolledBack;
        }
    }
}


text:
class CardinalDirection
  attr_reader :name

  def left
    left_name = DIRECTIONS[ (DIRECTIONS.index(name) + 1) % 4 ]

    self.class.send left_name
  end

  def right
    right_name = DIRECTIONS[ (DIRECTIONS.index(name) - 1) % 4 ]

    self.class.send right_name
  end

  private

  DIRECTIONS = [:north, :west, :south, :east]

  def initialize(name)
    @name = name
  end

  def self.north
    @north ||= CardinalDirection.new(:north)
  end

  def self.south
    @south ||= CardinalDirection.new(:south)
  end

  def self.east
    @east ||= CardinalDirection.new(:east)
  end

  def self.west
    @west ||= CardinalDirection.new(:west)
  end
end


text:
module Testing
  module SiegeLoadTestsHelper

    def asset_link(path)
      "/testing/siege_load_test/assets/#{path}"
    end

    # menu highlighting
    def highlight(name)
      (@highlight == name) ? ' highlighted' : nil
    end

    def f_prec(text)
      if text.is_a? Float
        "%.2f" % text
      else
        text
      end
    end
  end
end