text:
---
title: Raytracing - Reflecting Materials
layout: post
image: 2018-07-30-raytracing-reflecting-materials/raytracing-reflecting-0.jpg
---

Chapter 8 study note. Breakdown topics about ```Material``` base class, types of reflection, vector maths for calculating mirror reflection ray and blurry reflection implementation.

# Material Base Class
Objects with different materials scatter the lights in different ways. It tells how rays interact with the surface.

When abstracting materials as a class, it should include functionalities like:
- taking the incoming ray ```ray& r_in``` and output reflected ray ```ray& scattered```;
- calculating how much the ray should be attenuated - ```vec3& attenuation```;
- gathering the info related to hit point and save into a ```hit_record``` struct ```rec```.

And for ```struct hit_record```, it packs up info like:
- parameter ```t``` of the ray that locates the intersection point;
- position of intersection point ```p```;
- surface normal of intersection point ```normal```;
- and also includes a reference to the material of the hit surface.

So we create an abstract class ```material``` with a definition of a pure virtual function ```scatter()``` that take care of all the functionalities mentioned above. Note that an abstract class constructs no objects but works as a template for its children.
```c
#include "hitable.h"

/*
struct hit_record{
    float t;
    vec3 p;
    vec3 normal;
    material *mat_ptr;
};
*/

class material {
public:
    virtual bool scatter(
        const ray& r_in,
        const hit_record& rec,
        vec3& attenuation,
        ray& scattered) const = 0;
};
```

Here we create ```lambertian``` (diffuse material) and ```metal``` (reflecting material) material classes that inherited from ```material``` class. The children of an abstract class have to implement the pure virtual function.

# Lambertian Material
Lambertian Material is an alternative technical name of **diffuse material**. Here we refractor the code about diffuse material from previous post.
> Lambertian reflectance is the property that defines an **ideal** "matte" or diffusely reflecting surface. The apparent brightness of a Lambertian surface to an observer is the same regardless of the observer's angle of view. More technically, the surface's luminance is **isotropic**, and the luminous intensity obeys **Lambert's cosine law**.

```c
#include "material.h"

vec3 random_in_unit_sphere() {
    vec3 p;
    do{
        float random = drand48();
        p = 2.0 * vec3(random, random, random) - vec3(1,1,1);
    } while (p.squared_length() >= 1.0);
    return p;
}

class lambertian : public material {
public:
    lambertian(const vec3& a) : albedo(a) {}

    virtual bool scatter(
        const ray& r_in,
        const hit_record& rec,
        vec3& attenuation,
        ray& scattered) const {

        vec3 target = rec.p + rec.normal + random_in_unit_sphere();
        scattered = ray(rec.p, target - rec.p);
        attenuation = albedo;
        return true;
    }

    vec3 albedo;
};
```
# Reflecting Materials
- **Polished** - A polished reflection is an undisturbed reflection, like a mirror or chrome.
- **Blurry** - A blurry reflection means that tiny random bumps on the surface of the material cause the reflection to be blurry.
- **Metallic** - A reflection is metallic if the highlights and reflections retain the color of the reflective object.
- **_Glossy_** - This term can be misused. Sometimes, it is a setting which is the opposite of blurry (e.g. when "glossiness" has a low value, the reflection is blurry). However, some people use the term "glossy reflection" as a synonym for "blurred reflection". Glossy used in this context means that the reflection is actually blurred. (More later.)

# Polished Reflecting Material
## Reflection Vector

From the figure above, we get

$$\vec r = \vec v - (-2 * \vert \vec a\vert  * \vec n)$$

where $\vert \vec a\vert  = \vert \vec v\vert  * cos(\theta)$.

Since $dot(\vec v, \vec n) = \vert \vec v\vert \vert \vec n\vert cos(\pi - \theta) = -\vert \vec v\vert cos(\theta)$, so $\vert \vec a\vert  = -dot(\vec v, \vec n)$, and

$$\vec r = \vec v - (2 * dot(\vec v, \vec n) * \vec n)$$

```c
vec3 reflect(const vec3& v, const vec3& n) {
    return v - 2 * dot(v,n) * n;
}
```

> Note that here I'm deriving the calculation of the reflection vector according to the code from the book. Conventionally the direction of the incident vector is defined pointing toward the light source!

And the rest of code for metal material subclass is

```c
#include "material.h"

class metal : public material {
public:
    metal(const vec3& a, float f) : albedo(a) {}

    virtual bool scatter(
        const ray& r_in,
        const hit_record& rec,
        vec3& attenuation,
        ray& scattered) const {

        vec3 reflected = reflect(unit_vector(r_in.direction()), rec.normal);
        scattered = ray(rec.p, reflected);
        attenuation = albedo;
        return (dot(scattered.direction(), rec.normal) > 0);
    }

    vec3 albedo;
};
```

# Blurry Reflecting Material
To render a blurry reflecting look, we just need to add a little random vector ```random_in_unit_sphere()``` when calculating the directions of the reflected rays. Here we scale the random vector with a (0,1) float ```fuzz```.

```c
#include "lambertian.h" // random_in_unit_sphere()

// new constructor
metal(const vec3& a, float f) : albedo(a) {
    if (f<1) fuzz = f;
    else fuzz = 1;
}

    virtual bool scatter(
        const ray& r_in,
        const hit_record& rec,
        vec3& attenuation,
        ray& scattered) const {

        vec3 reflected = reflect(unit_vector(r_in.direction()), rec.normal);
        scattered = ray(rec.p, reflected + fuzz * random_in_unit_sphere()); // random
        attenuation = albedo;
        return (dot(scattered.direction(), rec.normal) > 0);
    }

    vec3 albedo;
    float fuzz; // random intensity
};
```


text:
package org.antlr.codebuff;

public enum FeatureType {
	TOKEN(12), RULE(14), INT(12), BOOL(5), // bool can be -1 meaning don't know
	INFO_FILE(15), INFO_LINE(4), INFO_CHARPOS(4),
	UNUSED(0);
	public int displayWidth;

	FeatureType(int displayWidth) {
		this.displayWidth = displayWidth;
	}
}

redpajama_set_name: RedPajamaGithub


text: Is responsible for managing stock items. Informs other services if stock is low.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <title>ROBLOX Markup Language Reference</title>
    <link rel="stylesheet" href="../ldoc.css" type="text/css" />

<big></big>

ROBLOX Markup Language

Index

Contents

Introduction to ROBLOX Style Sheets

Selectors

Selecting Children

Setting the RossDoc

When to Use RoSS

Topics

01-Introduction

02-BasicRoML

03-LibraryCustomObjects

04-AdvancedRoML

05-RoSS

06-DefiningCustomObjects

Modules

CompilerPropertyFilter

CustomObject

SpriteSheet

File

RomlCompiler

RomlParser

RossCompiler

RossParser

Array

String

Table

Classes

AnonymousTableBlock

Block

ConditionalBlock

DoBlock

DoubleBlock

ForBlock

FunctionBlock

IfBlock

IfElseBlock

InnerMetatableBlock

Line

MainBlock

MainBlock

MainRossBlock

MetatableBlock

RequireLine

SpaceBlock

StackBlock

TableAssignmentBlock

TableBlock

LiteralString

VariableNamer

Stack

MainRossBlock

Event

ObjectBuilder

RomlDoc

RomlObject

RomlVar

RossDoc

Tester

HashMap

Examples

event.moon

ROBLOX Style Sheets

Introduction to ROBLOX Style Sheets

ROBLOX Style Sheets (RoSS) is another small language defined by the RoML library.
It is used to set properties of objects created by RoML.
If you've used CSS, RoSS is designed to work very similar.

Selectors

To be able to set properties of an object, we must first write a selector to know which objects the properties belong to.
A selector has an optional object name, followed by a class name or an id name.
Below are a few examples.

Object selector: Part

Class selector: .Red

Id selector: #Part1

Object with class selector: Part.Red

Object with id selector: Part#Part1

Each property you set is on it's own line.
Like RoML, whitespace matters in RoSS.
Properties that are tabbed and below a selector line are associated with that selector:

 Part.White
    Name: "White Part"
    BrickColor: 1001

As you can see, short hand properties work here as well.
There are some extra rules you should note, however:

If the property is Position or Size, you must include the object name otherwise it will assume a Vector3 even for Gui classes.

If the property is the Style Enum, you must also include the object name because there are 4 different Style Enums depending on the ROBLOX object.

If the object is a custom object, you must include the object name so that the custom object's filters can be used.

Other than that, the object name is optional.

Selecting Children

Selecting children within a large structure is not all that much more difficult.
Just simply include multiple selectors, separated by a space.
Take the following RoML file for example:

 %Model
    %Part#Part1
 %Part#Part2

And the following RoSS file:

 Model Part
    BrickColor: Bright red

Only the Part with the id of "Part1" would be colored red.
This is because the Part with id of "Part2" is not a child of a Model object.

Setting the RossDoc

We can set an initial RossDoc in the constructor for our RomlDoc, just like variables.
Let's take a look at the project structure for this example assuming our RoML and RoSS are the examples from the last section:

game
 |
 +-- ServerScriptService
      |
      +-- lib (Folder)
      |    |
      |    +-- roml (Folder)
      |    |    |
      |    |    +-- StyledRoML (ModuleScript)
      |    |
      |    +-- ross (Folder)
      |         |
      |         +-- TestRoSS (ModuleScript)
      |
      +-- src (Folder)
           |
           +-- roml (Folder)
           |    |
           |    +-- StyledRoML.roml (ModuleScript)
           |
           +-- ross (Folder)
                |
                +-- TestRoSS.ross (ModuleScript)

So now we may set our RoSS file when constructing our RoML:

local StyledRoML = require(game.ServerScriptService.lib.roml.StyledRoML)
local TestRoSS = require(game.ServerScriptServer.lib.ross.TestRoSS)

StyledRoML.new(game.Workspace, {}, TestRoSS.new())

But we may also update the style sheet at runtime, just like we can with variables.
Let's create another RoSS script, TestRoSS2:

 Model Part
    BrickColor: 1001

Then we can use the RomlDoc.SetStyleSheet to change the style sheet:

local StyledRoML = require(game.ServerScriptService.lib.roml.StyledRoML)
local TestRoSS = require(game.ServerScriptServer.lib.ross.TestRoSS)
local TestRoSS2 = require(game.ServerScriptServer.lib.ross.TestRoSS2)

styledRoML = StyledRoML.new(game.Workspace, {}, TestRoSS.new())

wait(5)

styledRoML:SetStyleSheet(TestRoSS2.new())

After 5 seconds, the Part inside the Model changes from red to white!

When to Use RoSS

So there are two methods of setting properties inside of the RoML library.
There is not correct way to set them, but I suggest using the following rules of thumb to know when to set properties inside the RoML or RoSS files:

If the property is a variable property, use RoML.

Otherwise, use RoSS.

With these rules, you can help keep your code neat and organized.

generated by LDoc 1.4.3
Last updated 2016-07-26 16:56:15


text:
Em.Object.reopen({
	toJSON: function() {
		var v, ret = [], recursed = {};
		if (this.toArray) {
			return this.toArray().map(function(d) {
				return d && d.toJSON ? d.toJSON : d;
			});
		}
		for (var key in this) {
			v = this[key];
			if (v === 'toString') {
				continue;
			} // ignore useless items
			if (Ember.typeOf(v) === 'function' ||
					Em.typeOf(v) === 'class' ||
					key === 'concatenatedProperties' ||
					key === 'isDestroyed' ||
				key === 'isDestroying') {
				continue;
			}
			if (v && v.toArray) {
				recursed[key] = v.toArray().map(function(a) {
					return a && a.toJSON ? a.toJSON() : a;
				});
			} else if (v && v.toJSON) {
				recursed[key] = v.toJSON();
			}
			ret.push(key);
		}
		return $.extend(this.getProperties.apply(this, ret), recursed);
	}
});

Em.JSONify = function(obj) {
	if (!obj) {
		return obj;
	} else if (obj.toJSON) {
		return obj.toJSON();
	} else if (obj.toArray) {
		return obj.toArray().map(function(d) {
			return d && d.toJSON ? d.toJSON() : d;
		});
	}
};

Em.computed.parallel = {

	map: function(data, fn) {
		return Em.computed.promise([], function() {
			return new Parallel(Em.JSONify(this.get(data))).map(fn);
		});
	},

	reduce: function(data, fn, initValue) {
		return Em.computed.promise(initValue, function() {
			return new Parallel(Em.JSONify(this.get(data))).reduce(fn);
		});
	},

	spawn: function(data, fn, initValue) {
		return Em.computed.promise(initValue, function() {
			return new Parallel(Em.JSONify(this.get(data))).spawn(fn);
		});
	}

};

Em.computed.promise = function(defaultValue, fn) {
	if (typeof fn == 'undefined') {
		fn = defaultValue;
		defaultValue = undefined;
	}

	return Em.computed(function(propertyName, value) {
		if (arguments.length == 2) {
			return value;
		}

		var self = this;
		self.set(propertyName + 'Promise',
			new Em.RSVP.Promise(function(resolve, reject) {
				resolve(fn.call(self));
			}).then(function(data) {
				if (self.get(propertyName) !== data) {
					self.set(propertyName, data);
				}

				return data;
			}));

		return defaultValue;
	});
};


text:
package template

import (
	"fmt"
	"go/types"
	"strings"

	"github.com/matryer/moq/internal/registry"
)

// Data is the template data used to render the Moq template.
type Data struct {
	PkgName         string
	SrcPkgQualifier string
	Imports         []*registry.Package
	Mocks           []MockData
	StubImpl        bool
	SkipEnsure      bool
}

// MocksSomeMethod returns true of any one of the Mocks has at least 1
// method.
func (d Data) MocksSomeMethod() bool {
	for _, m := range d.Mocks {
		if len(m.Methods) > 0 {
			return true
		}
	}

	return false
}

// MockData is the data used to generate a mock for some interface.
type MockData struct {
	InterfaceName string
	MockName      string
	TypeParams    []TypeParamData
	Methods       []MethodData
}

// MethodData is the data which represents a method on some interface.
type MethodData struct {
	Name    string
	Params  []ParamData
	Returns []ParamData
}

// ArgList is the string representation of method parameters, ex:
// 's string, n int, foo bar.Baz'.
func (m MethodData) ArgList() string {
	params := make([]string, len(m.Params))
	for i, p := range m.Params {
		params[i] = p.MethodArg()
	}
	return strings.Join(params, ", ")
}

// ArgCallList is the string representation of method call parameters,
// ex: 's, n, foo'. In case of a last variadic parameter, it will be of
// the format 's, n, foos...'
func (m MethodData) ArgCallList() string {
	params := make([]string, len(m.Params))
	for i, p := range m.Params {
		params[i] = p.CallName()
	}
	return strings.Join(params, ", ")
}

// ReturnArgTypeList is the string representation of method return
// types, ex: 'bar.Baz', '(string, error)'.
func (m MethodData) ReturnArgTypeList() string {
	params := make([]string, len(m.Returns))
	for i, p := range m.Returns {
		params[i] = p.TypeString()
	}
	if len(m.Returns) > 1 {
		return fmt.Sprintf("(%s)", strings.Join(params, ", "))
	}
	return strings.Join(params, ", ")
}

// ReturnArgNameList is the string representation of values being
// returned from the method, ex: 'foo', 's, err'.
func (m MethodData) ReturnArgNameList() string {
	params := make([]string, len(m.Returns))
	for i, p := range m.Returns {
		params[i] = p.Name()
	}
	return strings.Join(params, ", ")
}

type TypeParamData struct {
	ParamData
	Constraint types.Type
}

// ParamData is the data which represents a parameter to some method of
// an interface.
type ParamData struct {
	Var      *registry.Var
	Variadic bool
}

// Name returns the name of the parameter.
func (p ParamData) Name() string {
	return p.Var.Name
}

// MethodArg is the representation of the parameter in the function
// signature, ex: 'name a.Type'.
func (p ParamData) MethodArg() string {
	if p.Variadic {
		return fmt.Sprintf("%s ...%s", p.Name(), p.TypeString()[2:])
	}
	return fmt.Sprintf("%s %s", p.Name(), p.TypeString())
}

// CallName returns the string representation of the parameter to be
// used for a method call. For a variadic paramter, it will be of the
// format 'foos...'.
func (p ParamData) CallName() string {
	if p.Variadic {
		return p.Name() + "..."
	}
	return p.Name()
}

// TypeString returns the string representation of the type of the
// parameter.
func (p ParamData) TypeString() string {
	return p.Var.TypeString()
}


text:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
using System.Xaml;
using TakeAshUtility;

namespace WpfUtility {

    /// <summary>
    /// Translation Extension for XAML Markup
    /// </summary>
    /// <remarks>
    /// <list type="bullet">
    /// <item>[XAML のマークアップ拡張を使った WPF での国際化 | プログラマーズ雑記帳](http://yohshiy.blog.fc2.com/blog-entry-242.html)</item>
    /// <item>[Internationalization in .NET and WPF - Lorenz Cuno Klopfenstein - Klopfenstein.net](http://www.klopfenstein.net/lorenz.aspx/internationalization-in-net-and-wpf-presentation-foundation)</item>
    /// <item>[Accessing "current class" from WPF custom MarkupExtension - Stack Overflow](http://stackoverflow.com/questions/3047448)</item>
    /// </list>
    /// </remarks>
    [MarkupExtensionReturnType(typeof(string))]
    public class TrExtension :
        MarkupExtension {

        public const string AssemblyKey = "TrExtension_Assembly";
        const string NotFoundError = "#NotFound#";

        string _key;

        public string Assembly { get; set; }

        public TrExtension(string key) {
            _key = key;
        }

        public override object ProvideValue(IServiceProvider serviceProvider) {
            if (String.IsNullOrEmpty(_key)) {
                return NotFoundError;
            }
            var resourceManager = ResourceHelper.GetResourceManager(
                this.Assembly ??
                GetAssemblyNameFromStaticResource(serviceProvider) ??
                GetAssemblyNameFromDynamicResource()
            ) ?? ResourceHelper.GetResourceManager(GetTypeOfRootObject(serviceProvider));
            return resourceManager != null ?
                (resourceManager.GetString(_key) ?? _key) :
                _key;
        }

        private string GetAssemblyNameFromStaticResource(IServiceProvider serviceProvider) {
            try {
                return serviceProvider.GetService<IXamlSchemaContextProvider>() == null ?
                    null :
                    new StaticResourceExtension(AssemblyKey).ProvideValue(serviceProvider) as string;
            }
            catch {
                return null;
            }
        }

        private string GetAssemblyNameFromDynamicResource() {
            return Application.Current.TryFindResource(AssemblyKey) as string;
        }

        private Type GetTypeOfRootObject(IServiceProvider serviceProvider) {
            var rootObjectProvider = serviceProvider.GetService<IRootObjectProvider>();
            return rootObjectProvider == null ?
                null :
                rootObjectProvider.RootObject.GetType();
        }
    }
}


text:
(function () {
    'use strict';

    angular
        .module('fc.merchandising')
        .controller('OrganisationalHierarchyMasterCtrl', hierarchyMaster)
        .controller('OrganisationalHierarchyDetailCtrl', hierarchyDetail);

    hierarchyMaster.$inject = [
        "lodash",
        "rx",
        "$modal",
        "$scope",
        "$stateParams",
        "$translate",
        "orgHierarchyDataSvc",
        "throttleValue",
        "merchandisingConstants"
    ];

    function hierarchyMaster(_, Rx, $modal, $scope, $stateParams, $translate, hierarchyDataSvc, throttleValue, constants) {
        /* jshint validthis: true */
        var vm = this,
            _hierarchyDetailModalOptions = null,
            _selectionEnum = {"none": 0, "some": 1, "all": 2},
            _currentPage = null,
            _pageSize = null,
            _pin = null,
            _totalServerItems = null,
            _hierarchyId = null,
            _parentHierId = null,
            _parentEngine = null;

        vm.activate = activate;
        vm.activateItems = activateItems;
        vm.allFields = [];
        vm.cancelChanges = cancelChanges;
        vm.createHierarchy = createHierarchy;
        vm.customFields = [];
        vm.edit = edit;
        vm.getSelectionKey = getSelectionKey;
        vm.filter = null;
        vm.fields = [];
        vm.formFields = {};
        vm.getStatusToggleKey = getStatusToggleKey;
        vm.hasNextPage = hasNextPage;
        vm.hasParent = hasParent;
        vm.isFieldSelected = isFieldSelected;
        vm.loadNextPage = loadNextPage;
        vm.modelName = "hierarchy";
        vm.deactivateItems = deactivateItems;
        vm.saveChanges = saveChanges;
        vm.selectAll = selectAll;
        vm.selected = null;
        vm.showInactive = false;
        vm.hierarchies = [];
        vm.hierarchy = null;
        vm.title = null;
        vm.toggleFilterField = toggleFilterField;
        vm.toggleSelection = toggleSelection;
        vm.validationData = null;

        activate();

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        function activate() {
            _hierarchyDetailModalOptions = {
                templateUrl: "merchandising/templates/modal.tpl.html",
                controller: "OrganisationalHierarchyDetailCtrl as vm",
                size: 'lg'
            };

            vm.validationData = {
                parent:{
                    required: true
                },
                code: {
                    required: true
                },
                description: {
                    required: false
                },
                location: {
                    required: true
                },
                name: {
                    required: true
                },
                address1: {
                    required: true
                },
                phone1: {
                    required: true
                },
                fax1: {
                    required: true
                },
                email1: {
                    required: true
                },
                pin: {
                    required: true
                },
                registration: {
                    required: true
                }
            };
            load();
        }

        function activateItems(item) {
            // NOTE:...................................................
            // If we passed a hierarchy, assume the activation of the single said hierarchy.
            // else, assume the activation of all selected hierarchies.

            changeActivation(item, true);
        }

        function cancelChanges() {
            vm.hierarchy = null;
        }

        function changeActivation(hierarchy, newStatus) {
            // We need a status specified.
            if (newStatus !== true && newStatus !== false) {
                return;
            }

            var toTranslate = [
                "fc.ACTION_WARNING_MESSAGE_TEMPLATE",
                "fc.SUCCESS_ALERT_TITLE",
                "fc.ACTION_SUCCESS_MESSAGE_TEMPLATE",
                "fc.FAIL_ALERT_TITLE",
                "fc.ACTION_FAIL_MESSAGE_TEMPLATE",
                "fc.DELETE_ACTION_PRESENT",
                "fc.DELETE_ACTION_PAST",
                "fc.RESTORE_ACTION_PRESENT",
                "fc.RESTORE_ACTION_PAST",
                "fc.NO_TEXT",
                "fc.YES_TEXT"
            ];

            $translate(toTranslate).then(function (translations) {
                var warningTemplate = translations["fc.ACTION_WARNING_MESSAGE_TEMPLATE"],
                    successAlertTitle = translations["fc.SUCCESS_ALERT_TITLE"],
                    successTemplate = translations["fc.ACTION_SUCCESS_MESSAGE_TEMPLATE"],
                    failAlertTitle = translations["fc.FAIL_ALERT_TITLE"],
                    failTemplate = translations["fc.ACTION_FAIL_MESSAGE_TEMPLATE"],
                    deleteActionPresent = translations["fc.DELETE_ACTION_PRESENT"],
                    deleteActionPast = translations["fc.DELETE_ACTION_PAST"],
                    restoreActionPresent = translations["fc.RESTORE_ACTION_PRESENT"],
                    restoreActionPast = translations["fc.RESTORE_ACTION_PAST"],
                    noText = translations["fc.NO_TEXT"],
                    yesText = translations["fc.YES_TEXT"];

                var pageTitle = vm.title;
                var selectedHierarchies = [],
                    actionPast = newStatus ? restoreActionPast : deleteActionPast,
                    actionPresent = newStatus ? restoreActionPresent : deleteActionPresent;

                if (!hierarchy) {
                    selectedHierarchies = _.filter(vm.hierarchies, function (ent) {
                        // Deselect items that won't be changed.
                        if (ent.active === newStatus) {
                            ent.isSelected = false;
                        }

                        return ent.isSelected;
                    });

                    // Can't change the state.
                    if (selectedHierarchies.length < 1) {
                        refreshSelection();
                        return;
                    }

                    refreshSelection();
                }

                var performChange = function (hierarchy) {
                    // If we get an hierarchy, change it else change all selected hierarchies.
                    var toChange = null;

                    if (hierarchy) {
                        toChange = hierarchy.id;
                    } else {
                        // Do nothing if there was no selection.
                        if (vm.selected === _selectionEnum.none) {
                            return;
                        }

                        // Fetch the selected hierarchies.
                        toChange = _.map(selectedHierarchies, function (hierarchy) {
                            return hierarchy.id;
                        });
                    }

                    if (newStatus === true) {
                        hierarchyDataSvc.activateHierarchiesData(_hierarchyId, toChange).then(afterChangeCb);
                    } else {
                        hierarchyDataSvc.deactivateHierarchiesData(_hierarchyId, toChange).then(afterChangeCb);
                    }
                };

                var afterChangeCb = function(response) {
                    var changedCount = response.length;
                    var message = null;
                    var title = changedCount > 0 ? successAlertTitle : failAlertTitle;
                    var color = changedCount > 0 ? "#659265" : "#C46A69";
                    var icon = "fa fa-2x fadeInRight animated " + (changedCount > 0 ? "fa-check" : "fa-times");

                    if (changedCount > 0) {
                        var msgData = {action: _.string.humanize(actionPast), count: changedCount};

                        message = _.string.sprintf(successTemplate, msgData);

                        var updateItem = function (ent) {
                            // If we are not showing inactive items, add the newly activated item.
                            if (!vm.showInactive) {
                                updateHierarchies(ent, !newStatus);
                            } else {
                                var idx = vm.hierarchies.indexOf(ent);

                                // Replace with new from data store.
                                if (idx >= 0) {
                                    var match = _(response).filter(function (resp) {
                                        return resp.id === ent.id;
                                    }).first();

                                    // Damn...we can't use splice here...
                                    angular.extend(vm.hierarchies[idx], match);
                                }
                            }
                        };

                        if (changedCount === 1 && hierarchy) {
                            updateItem(hierarchy);
                        } else {
                            _(selectedHierarchies).filter(function (hierarchy) {
                                return _.any(response, {id: hierarchy.id});
                            }).forEach(function (hierarchy) {
                                updateItem(hierarchy);
                            });
                        }

                        if (!vm.showInactive) {
                            if (newStatus) {
                                // If we are not showing inactive, remove extra items.
                                var startIndex = vm.hierarchies.length - (1 + changedCount);
                                vm.hierarchies.splice(startIndex, changedCount);
                            } else {
                                // If we are not showing inactive, load extra items to fill up the remaining slots.
                                fetchHierarchies(_currentPage, _pageSize, changedCount);
                            }
                        }
                    } else {
                        message = _.string.sprintf(failTemplate, {action: actionPresent, data: pageTitle.toLowerCase()});
                    }

                    if ($.smallBox) {
                        $.smallBox({
                            title : title,
                            content : "" + message + "",
                            color : color,
                            iconSmall : icon,
                            timeout : 4000
                        });
                    } else {
                        alert(message);
                    }
                };

                var content = null;

                // Show message box.
                if ($.SmartMessageBox) {
                    var textColor = newStatus ? "txt-color-green" : "txt-color-red";
                    var title = " ";
                    title += _.string.humanize(actionPresent);

                    // Set the messages depending on whether we're restoring a single hierarchy or a selection.
                    if (hierarchy) {
                        title += " " + hierarchy.name;
                        if (hierarchy.location) {
                            title += " "+ hierarchy.location +"?";
                        }

                        content = _.string.sprintf(warningTemplate, {
                            action: actionPresent,
                            count: 1
                        });
                    } else {
                        title += " ";
                        title += selectedHierarchies.length;
                        title += " "+ pageTitle.toLowerCase() +"?";

                        content = _.string.sprintf(warningTemplate, {
                            action: actionPresent,
                            count: selectedHierarchies.length
                        });
                    }

                    $.SmartMessageBox({
                        title : title,
                        content : content,
                        buttons : '[' + noText + '][' + yesText + ']'
                    }, function(button) {
                        if (button === yesText) {
                            performChange(hierarchy);
                        }
                    });
                } else {
                    content = _.string.sprintf(warningTemplate, {action: actionPresent, count: selectedHierarchies.length || 1});
                    if (confirm(content)) {
                        performChange(hierarchy);
                    }
                }
            });
        }

        function createHierarchy() {
            vm.hierarchy = {};
        }

        function deactivateItems(item) {
            // NOTE:...................................................
            // If we passed an hierarchy, assume the deactivation of the single said hierarchy.
            // else, assume the deactivation of all selected hierarchies.

            changeActivation(item, false);
        }

        function edit(item) {
            if (!item) {
                return;
            }

            // Use extend to prevent reference copying so we can edit the item in isolation.
            var hierarchy = angular.extend({}, item);

            if (_parentHierId) {
                hierarchyDataSvc.getHierarchyData(_parentHierId, hierarchy.parentId).then(function (data) {
                    hierarchy.parent = data;
                });
            }

            // Setup modal options.
            _hierarchyDetailModalOptions.resolve = {
                data: function () {
                    return {
                        customFields: vm.customFields,
                        formFields: vm.formFields,
                        hasParent: hasParent,
                        hierarchy: hierarchy,
                        hierarchyId: _hierarchyId,
                        modelName: vm.modelName,
                        parentDataset: vm.parentDataset,
                        validationData: vm.validationData
                    };
                }
            };

            // Open modal popup.
            var modalInstance = $modal.open(_hierarchyDetailModalOptions);

            modalInstance.result.then(function (editedEntity) {
                // We selected ok...
                angular.extend(item, editedEntity);
            }, function () {
                // We cancelled the search...
                // Do nothing...
            });
        }

        function fetchHierarchies(page, pageSize, replaceRemoved, refresh) {
            var filterOptions = {_search: vm.filter && vm.filter.length > 0, query: vm.filter, fields: vm.fields};

            hierarchyDataSvc.getHierarchiesData(_hierarchyId, page, pageSize, filterOptions, vm.showInactive, replaceRemoved, refresh)
                .then(function (data) {
                    _currentPage = data.page;
                    _pageSize = data.maxItems;
                    _pin = data.pin;
                    _parentHierId = data.parentId;
                    _totalServerItems = data.inlineCount;
                    vm.allFields = [];

                    vm.customFields = data.customFields;

                    if (data.name && vm.title !== data.name) {
                        vm.title = data.name;
                    }

                    if (refresh) {
                        vm.hierarchies = [];
                    }

                    if (_parentHierId) {
                        vm.validationData.parent = {required: true};
                        initTypeahead();
                    }

                    // Setup dynamic form fields.
                    vm.formFields.code = true;
                    vm.formFields.name = true;
                    vm.allFields.push("code", "name");

                    // Entity fields.
                    if (_pin === 1) {
                        vm.formFields.description = true;
                        vm.formFields.location = true;
                        vm.allFields.push("location", "description");
                    }

                    // Middle hierarchy fields
                    if (!_pin) {
                        vm.formFields.customFields = data.customFields && data.customFields.length > 0;
                    }

                    // Fields in hierarchies with parents i.e. with a parentHierId.
                    vm.formFields.parent = _parentHierId;

                    // Branch fields
                    if (_pin === 2) {
                        vm.formFields.address1 = true;
                        vm.formFields.address2 = true;
                        vm.formFields.address3 = true;
                        vm.formFields.address4 = true;
                        vm.formFields.phone1 = true;
                        vm.formFields.phone2 = true;
                        vm.formFields.phone3 = true;
                        vm.formFields.phone4 = true;
                        vm.formFields.fax1 = true;
                        vm.formFields.fax2 = true;
                        vm.formFields.email1 = true;
                        vm.formFields.email2 = true;
                        vm.formFields.branchIsWarehouse = true;
                        vm.formFields.pin = true;
                        vm.formFields.registration = true;

                        vm.allFields.push("address1", "address2", "address3", "address4");
                        vm.allFields.push("phone1", "phone2", "phone3", "phone4");
                        vm.allFields.push("email1", "email2");
                        vm.allFields.push("fax1", "fax2");
                        vm.allFields.push("pin", "registration");
                    }

                    updateHierarchies(data.results);
                }, function (error) {

                });
        }

        function getSelectionKey() {
            return vm.selected ? "fc.CLEAR_SELECTION_TEXT" : "fc.SELECT_ALL_TEXT";
        }

        function getStatusToggleKey() {
            return vm.showInactive ? 'fc.HIDE_INACTIVE_TEXT' : 'fc.SHOW_INACTIVE_TEXT';
        }

        function hasNextPage() {
            var alreadyLoadedItems = (Math.max((_currentPage - 1), 0) * _pageSize) + vm.hierarchies.length;

            return alreadyLoadedItems < _totalServerItems;
        }

        function hasParent() {
            return _parentHierId;
        }

        function initTypeahead() {
            // Extend to prevent changing the constants...fixes issue with fetching incorrect parent.
            var engineRemote = angular.extend({}, constants.suggestions.hierarchy.remote);
            engineRemote.url = engineRemote.url.replace("@{type}", "organisational").replace("@{hierarchyId}", _parentHierId);

            _parentEngine = new Bloodhound({
                datumTokenizer: function(d) {
                    return Bloodhound.tokenizers.whitespace(d[constants.suggestions.hierarchy.displayKey]);
                },
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                remote: engineRemote
            });

            _parentEngine.initialize();

            vm.typeaheadOptions = {
                hint: true,
                highlight: true,
                minLength: 1
            };
            vm.parentDataset = {
                name: "parent",
                displayKey: constants.suggestions.hierarchy.displayKey,
                source: _parentEngine.ttAdapter(),
                templates: constants.suggestions.hierarchy.templates
            };
        }

        function isFieldSelected(field) {
            return _.contains(vm.fields, field);
        }

        function load() {
            _hierarchyId = $stateParams.id;
            var subject = new Rx.Subject();
            subject.throttle(throttleValue).distinctUntilChanged().subscribe(function () {
                fetchHierarchies(_currentPage, _pageSize, null, true);
            });

            $scope.$watch(function () {
                return vm.filter;
            }, function (newValues) {
                subject.onNext(newValues);
            });

            $scope.$watchCollection(function () {
                return vm.fields;
            }, function (newValues) {
                subject.onNext(newValues);
            });

            $scope.$watch(function() {
                return vm.showInactive;
            }, function (newValue, oldValue) {
                if (newValue === oldValue) {
                    return;
                }

                fetchHierarchies(_currentPage, _pageSize, null, true);
            });
        }

        function loadNextPage() {
            fetchHierarchies(_currentPage + 1, _pageSize);
        }

        function refreshSelection() {
            // Use _.pluck style callback shorthand...
            var someSelected = _.any(vm.hierarchies, "isSelected");

            // NOTE: lodash always returns true when all is an empty array. Bug or by design?
            var allSelected = someSelected && _.all(vm.hierarchies, "isSelected");
            if (allSelected) {
                vm.selected = _selectionEnum.all;
            } else if (someSelected) {
                vm.selected = _selectionEnum.some;
            } else {
                vm.selected = _selectionEnum.none;
            }
        }

        function saveChanges() {
            vm.isSaving = true;

            if (vm.hierarchy.parent && vm.hierarchy.parent.id) {
                vm.hierarchy.parentId = vm.hierarchy.parent.id;
                delete vm.hierarchy.parent;
            }

            hierarchyDataSvc.createHierarchyData(_hierarchyId, vm.hierarchy).then(function (data) {
                updateHierarchies(data);
                vm.hierarchy = null;
                vm.isSaving = false;
            });
        }

        function selectAll() {
            if (!vm.selected || vm.selected === _selectionEnum.none) {
                _.forEach(vm.hierarchies, function(hierarchy) {
                    hierarchy.isSelected = true;
                });
            } else {
                _.forEach(vm.hierarchies, function(hierarchy) {
                    hierarchy.isSelected = false;
                });
            }

            refreshSelection();
        }

        function toggleFilterField(field) {
            var index = vm.fields.indexOf(field);

            if (index >= 0) {
                vm.fields.splice(index, 1)
            } else {
                vm.fields.push(field);
            }
        }

        function toggleSelection(item) {
            item.isSelected = !item.isSelected;

            refreshSelection();
        }

        function updateHierarchies(data, remove) {
            if (!_.isArray(vm.hierarchies)) {
                vm.hierarchies = [];
            }

            var index = -1;

            var updateSingle = function (item) {
                if (remove) {
                    index = vm.hierarchies.indexOf(item);

                    if (index >= 0) {
                        vm.hierarchies.splice(index, 1);
                    }
                } else {
                    vm.hierarchies.push(item);
                }
            };

            if (_.isArray(data)) {
                _.forEach(data, function (item) {
                    updateSingle(item);
                });
            } else {
                updateSingle(data);
            }

            refreshSelection();
        }
    }

    hierarchyDetail.$inject = ["$modalInstance", "orgHierarchyDataSvc", "data"];

    function hierarchyDetail($modalInstance, hierarchyDataSvc, data) {
        var vm = this,
            _hierarchyId = data.hierarchyId;

        vm.cancelChanges = cancelChanges;
        vm.customFields = data.customFields;
        vm.hasParent = data.hasParent;
        vm.modelName = data.modelName;
        vm.formFields = data.formFields;
        vm.parentDataset = data.parentDataset;
        vm.saveChanges = saveChanges;
        vm.title = data.hierarchy.name;
        vm.validationData = data.validationData;

        activate();

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        function activate() {
            // Set the model...
            vm[vm.modelName] = data[vm.modelName]
        }

        function cancelChanges() {
            $modalInstance.dismiss();
        }

        function saveChanges() {
            vm.isSaving = true;

            if (vm.hierarchy.parent && vm.hierarchy.parent.id) {
                vm.hierarchy.parentId = vm.hierarchy.parent.id;
                delete vm.hierarchy.parent;
            }

            hierarchyDataSvc.updateHierarchyData(_hierarchyId, vm.hierarchy.id, vm.hierarchy).then(function (data) {
                $modalInstance.close(data);
                vm.hierarchy = null;
                vm.isSaving = false;
            });
        }
    }
})();


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>B5500 Emulator Magnetic Tape Loader</title>

<meta name="Author" content="Nigel Williams & Paul Kimpel">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Style-Type" content="text/css">
<link id=defaultStyleSheet rel=stylesheet type="text/css" href="B5500Common.css">
<link id=tapeLoadStyleSheet rel=stylesheet type="text/css" href="B5500MagTapeDrive.css">

    <input id=MTLoadFileSelector type=file size=60>

        Format
        <select id=MTLoadFormatSelect>
            <option value="blank" selected>(blank tape)
            <option value="bcd">.bcd Image

            <option value="aev">ASCII Even Parity
            <option value="aod">ASCII Odd Parity
        </select>

        <input id=MTLoadWriteRingCheck type=checkbox checked value="1">
        Write Ring

        Tape Length
        <select id=MTLoadTapeLengthSelect>
            <option value="600">600 feet
            <option value="1200">1200 feet
            <option value="2400" selected>2400 feet
        </select>

    <button id=MTLoadCancelBtn class="redButton">Cancel</button>
    <button id=MTLoadOKBtn class="greenButton">OK</button>


text:
package org.nd4j.parameterserver.distributed.v2.messages;

import org.agrona.concurrent.UnsafeBuffer;
import org.nd4j.common.util.SerializationUtils;

import java.io.ByteArrayInputStream;
import java.io.Serializable;

public interface VoidMessage extends Serializable {
    /**
     * This method returns unique messageId
     * @return
     */
    String getMessageId();

    /**
     * This message allows to set messageId
     */
    //void setMessageId();

    /**
     * This method returns Id of originator
     * @return
     */
    String getOriginatorId();

    /**
     * This method allows to set originator id
     * PLEASE NOTE: This method must be used only from Transport context
     */
    void setOriginatorId(String id);

    /**
     * This method serializes this VoidMessage into UnsafeBuffer
     *
     * @return
     */
    default UnsafeBuffer asUnsafeBuffer() {
        return new UnsafeBuffer(SerializationUtils.toByteArray(this));
    }

    static VoidMessage fromBytes(byte[] bytes) {
        return SerializationUtils.readObject(new ByteArrayInputStream(bytes));
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import Radium from 'radium';
import MDL from './MdlComponents';
import Dialog from './Dialog';
import {History} from 'react-router';

let ProcRuntimeSection = React.createClass({
  mixins: [History],

  contextTypes: {
    theme: React.PropTypes.object,
  },

  render() {
    const {theme} = this.context;
    const {proc, fullname} = this.props;
    return (

{`运行时状况 [Up/Total = ${proc.upCount()}/${proc.numinstances}]`}

        <MDL.Table style={theme.dataTable}
          cols={[
            { title: 'ID(点击进入)', number: false },
            { title: '容器名称', number: false },
            { title: '节点IP', number: false },
            { title: '容器IP', number: false },
            { title: '容器端口', number: true },
            { title: '实时日志', number: false },
            { title: '环境变量', number: false },
          ]}
          rows={ _.map(proc.pods, (pod) => [pod.containerid.substring(0, 12), pod.containername, pod.nodeip, pod.containerip, pod.containerport, 'LOG', '点击查看']) }
          trStyle={(section, index) => {
            if (section === 'head') return {};
            return theme.colorStyle(proc.pods[index].status === 'True' ? 'success' : 'error');
          }}
          tdClickable={ (rowIndex, colIndex) => {
            switch (colIndex) {
              case 0:
                return (evt) => this.openTerminal(proc.pods[rowIndex]);
              case 5:
                return (evt) => this.openTerminalAttach(proc.pods[rowIndex]);
              case 6:
                return (evt) => this.showPodEnvDialog(proc.pods[rowIndex]);
            }
            return null;

          }} />

    );
  },

  showPodEnvDialog(showPod) {
    const mountNode = document.getElementById('dialog');
    const {fullname, proc} = this.props;
    const dialog = (
      <Dialog title={`运行时环境变量`}
          buttons={[
            { title: '好的' },
          ]}>

下面列出 {`proc - ${fullname}`} 运行时环境变量。

          {
            showPod.envs.map((env, index) => {
              return <li key={`${index}`}>{env}

            })
          }

      </Dialog>
    );
    ReactDOM.render(dialog, mountNode);
  },

  openTerminal(podInfo) {
    const appName = this.extractFromEnv(podInfo.envs, "LAIN_APPNAME");
    const procName = this.extractFromEnv(podInfo.envs, "LAIN_PROCNAME");
    const instanceNo = this.extractFromEnv(podInfo.envs, "DEPLOYD_POD_INSTANCE_NO");
    window.open(`/archon/apps/${appName}/proc/${procName}/instance/${instanceNo}/enter`, '_blank');
  },

  openTerminalAttach(podInfo) {
    const appName = this.extractFromEnv(podInfo.envs, "LAIN_APPNAME");
    const procName = this.extractFromEnv(podInfo.envs, "LAIN_PROCNAME");
    const instanceNo = this.extractFromEnv(podInfo.envs, "DEPLOYD_POD_INSTANCE_NO");
    window.open(`/archon/apps/${appName}/proc/${procName}/instance/${instanceNo}/attach`, '_blank');
  },

  extractFromEnv(env, key) {
    for (let i = 0; i < env.length; i++) {
      let index = env[i].indexOf('=');
      if (index >= 0 && env[i].substring(0, index) == key) {
        return env[i].substring(index+1);
      }
    }
    return "-";
  },

});

export default Radium(ProcRuntimeSection);


text:
package org.jetbrains.idea.maven;

import com.intellij.execution.wsl.WSLDistribution;
import com.intellij.execution.wsl.WslDistributionManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.module.StdModuleTypes;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl;
import com.intellij.openapi.roots.ex.ProjectRootManagerEx;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.rt.execution.junit.FileComparisonFailure;
import com.intellij.testFramework.*;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.maven.indices.MavenIndicesManager;
import org.jetbrains.idea.maven.project.*;
import org.jetbrains.idea.maven.server.MavenServerManager;
import org.jetbrains.idea.maven.utils.MavenProgressIndicator;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;

public abstract class MavenTestCase extends UsefulTestCase {
  protected static final String MAVEN_COMPILER_PROPERTIES = "<properties>\n" +
                                                            "        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n" +
                                                            "        <maven.compiler.source>1.7</maven.compiler.source>\n" +
                                                            "        <maven.compiler.target>1.7</maven.compiler.target>\n" +
                                                            "</properties>\n";
  protected static final MavenConsole NULL_MAVEN_CONSOLE = new NullMavenConsole();
  private MavenProgressIndicator myProgressIndicator;
  private WSLDistribution myWSLDistribution;

  private File ourTempDir;

  protected IdeaProjectTestFixture myTestFixture;

  @NotNull
  protected Project myProject;

  protected File myDir;
  protected VirtualFile myProjectRoot;

  protected VirtualFile myProjectPom;
  protected List<VirtualFile> myAllPoms = new ArrayList<>();

  @Override
  protected void setUp() throws Exception {
    super.setUp();

    setUpFixtures();
    myProject = myTestFixture.getProject();
    setupWsl();
    ensureTempDirCreated();

    myDir = new File(ourTempDir, getTestName(false));
    FileUtil.ensureExists(myDir);

    myProgressIndicator = new MavenProgressIndicator(myProject, new EmptyProgressIndicator(ModalityState.NON_MODAL), null);

    MavenWorkspaceSettingsComponent.getInstance(myProject).loadState(new MavenWorkspaceSettings());

    String home = getTestMavenHome();
    if (home != null) {
      getMavenGeneralSettings().setMavenHome(home);
    }

    EdtTestUtil.runInEdtAndWait(() -> {
      restoreSettingsFile();

      try {
        WriteAction.run(this::setUpInWriteAction);
      } catch (Throwable e) {
        try {
          tearDown();
        }
        catch (Exception e1) {
          e1.printStackTrace();
        }
        throw new RuntimeException(e);
      }
    });
  }

  private void setupWsl() {
    String wslMsId = System.getProperty("wsl.distribution.name");
    if (wslMsId == null) return;
    List<WSLDistribution> distributions = WslDistributionManager.getInstance().getInstalledDistributions();
    if (distributions.isEmpty()) throw new IllegalStateException("no WSL distributions configured!");
    myWSLDistribution = distributions.stream().filter(it -> wslMsId.equals(it.getMsId())).findFirst().orElseThrow(
      () -> new IllegalStateException("Distribution " + wslMsId + " was not found"));
    String jdkPath = System.getProperty("wsl.jdk.path");
    if (jdkPath == null) {
      jdkPath = "/usr/lib/jvm/java-11-openjdk-amd64";
    }

    Sdk wslSdk = getWslSdk(myWSLDistribution.getWindowsPath(jdkPath));
    WriteAction.runAndWait(() -> ProjectRootManagerEx.getInstanceEx(myProject).setProjectSdk(wslSdk));
    assertTrue(new File(myWSLDistribution.getWindowsPath(myWSLDistribution.getUserHome())).isDirectory());
  }

  private Sdk getWslSdk(String jdkPath) {
    Sdk sdk = ContainerUtil.find(ProjectJdkTable.getInstance().getAllJdks(), it -> jdkPath.equals(it.getHomePath()));
    ProjectJdkTable jdkTable = ProjectJdkTable.getInstance();
    for (Sdk existingSdk : jdkTable.getAllJdks()) {
      if (existingSdk == sdk) return sdk;
    }
    Sdk newSdk = JavaSdk.getInstance().createJdk("Wsl JDK For Tests", jdkPath);
    WriteAction.runAndWait(() -> jdkTable.addJdk(newSdk, myProject));
    return newSdk;
  }

  @Override
  protected void tearDown() throws Exception {
    String basePath = myProject.getBasePath();
    new RunAll(
      () -> MavenServerManager.getInstance().shutdown(true),
      () -> checkAllMavenConnectorsDisposed(),
      () -> MavenArtifactDownloader.awaitQuiescence(100, TimeUnit.SECONDS),
      () -> myProject = null,
      () -> EdtTestUtil.runInEdtAndWait(() -> tearDownFixtures()),
      () -> {
        Project defaultProject = ProjectManager.getInstance().getDefaultProject();
        MavenIndicesManager mavenIndicesManager = defaultProject.getServiceIfCreated(MavenIndicesManager.class);
        if (mavenIndicesManager != null) {
          mavenIndicesManager.clear();
        }
      },
      () -> deleteDirOnTearDown(myDir),
      () -> {
        if (myWSLDistribution != null) {
          deleteDirOnTearDown(new File(basePath));
        }
      },
      () -> super.tearDown()
    ).run();
  }

  private void checkAllMavenConnectorsDisposed() {
    assertEmpty("all maven connectors should be disposed", MavenServerManager.getInstance().getAllConnectors());
  }

  private void ensureTempDirCreated() throws IOException {
    if (ourTempDir != null) return;

    if (myWSLDistribution == null) {
      ourTempDir = new File(FileUtil.getTempDirectory(), "mavenTests");
    }
    else {
      ourTempDir = new File(myWSLDistribution.getWindowsPath("/tmp"), "mavenTests");
    }

    FileUtil.delete(ourTempDir);
    FileUtil.ensureExists(ourTempDir);
  }

  protected void setUpFixtures() throws Exception {
    String wslMsId = System.getProperty("wsl.distribution.name");
    if (wslMsId != null) {
      Path path = TemporaryDirectory
        .generateTemporaryPath(FileUtil.sanitizeFileName(getName(), false), Paths.get("\\\\wsl$\\" + wslMsId + "\\tmp"));
      myTestFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getName(), path, false).getFixture();
    }
    else {
      myTestFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getName()).getFixture();
    }

    myTestFixture.setUp();
  }

  protected void setUpInWriteAction() throws Exception {
    File projectDir = new File(myDir, "project");
    projectDir.mkdirs();
    myProjectRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectDir);
  }

  protected MavenProgressIndicator getMavenProgressIndicator() {
    return myProgressIndicator;
  }

  protected static void deleteDirOnTearDown(File dir) {
    FileUtil.delete(dir);
    // cannot use reliably the result of the com.intellij.openapi.util.io.FileUtil.delete() method
    // because com.intellij.openapi.util.io.FileUtilRt.deleteRecursivelyNIO() does not honor this contract
    if (dir.exists()) {
      System.err.println("Cannot delete " + dir);
      //printDirectoryContent(myDir);
      dir.deleteOnExit();
    }
  }

  private static void printDirectoryContent(File dir) {
    File[] files = dir.listFiles();
    if (files == null) return;

    for (File file: files) {
      System.out.println(file.getAbsolutePath());

      if (file.isDirectory()) {
        printDirectoryContent(file);
      }
    }
  }

  protected void tearDownFixtures() throws Exception {
    try {
      myTestFixture.tearDown();
    }
    finally {
      myTestFixture = null;
    }
  }

  @Override
  protected void runTestRunnable(@NotNull ThrowableRunnable<Throwable> testRunnable) throws Throwable {
    try {
      if (runInWriteAction()) {
        WriteAction.runAndWait(() -> super.runTestRunnable(testRunnable));
      }
      else {
        super.runTestRunnable(testRunnable);
      }
    }
    catch (Throwable throwable) {
      if (ExceptionUtil.causedBy(throwable, HeadlessException.class)) {
        printIgnoredMessage("Doesn't work in Headless environment");
      }
      throw throwable;
    }
  }

  protected boolean runInWriteAction() {
    return false;
  }

  protected static String getRoot() {
    if (SystemInfo.isWindows) return "c:";
    return "";
  }

  protected static String getEnvVar() {
    if (SystemInfo.isWindows) {
      return "TEMP";
    }
    else if (SystemInfo.isLinux) return "HOME";
    return "TMPDIR";
  }

  protected MavenGeneralSettings getMavenGeneralSettings() {
    return MavenProjectsManager.getInstance(myProject).getGeneralSettings();
  }

  protected MavenImportingSettings getMavenImporterSettings() {
    return MavenProjectsManager.getInstance(myProject).getImportingSettings();
  }

  protected String getRepositoryPath() {
    String path = getRepositoryFile().getPath();
    return FileUtil.toSystemIndependentName(path);
  }

  protected File getRepositoryFile() {
    return getMavenGeneralSettings().getEffectiveLocalRepository();
  }

  protected void setRepositoryPath(String path) {
    getMavenGeneralSettings().setLocalRepository(path);
  }

  protected String getProjectPath() {
    return myProjectRoot.getPath();
  }

  protected String getParentPath() {
    return myProjectRoot.getParent().getPath();
  }

  protected String pathFromBasedir(String relPath) {
    return pathFromBasedir(myProjectRoot, relPath);
  }

  protected static String pathFromBasedir(VirtualFile root, String relPath) {
    return FileUtil.toSystemIndependentName(root.getPath() + "/" + relPath);
  }

  protected VirtualFile updateSettingsXml(String content) throws IOException {
    return updateSettingsXmlFully(createSettingsXmlContent(content));
  }

  protected VirtualFile updateSettingsXmlFully(@NonNls @Language("XML") String content) throws IOException {
    File ioFile = new File(myDir, "settings.xml");
    ioFile.createNewFile();
    VirtualFile f = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile);
    setFileContent(f, content, true);
    getMavenGeneralSettings().setUserSettingsFile(f.getPath());
    return f;
  }

  protected void deleteSettingsXml() throws IOException {
    WriteCommandAction.writeCommandAction(myProject).run(() -> {
      VirtualFile f = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myDir, "settings.xml"));
      if (f != null) f.delete(this);
    });
  }

  private static String createSettingsXmlContent(String content) {
    String mirror = System.getProperty("idea.maven.test.mirror",
                                       // use JB maven proxy server for internal use by default, see details at
                                       // https://confluence.jetbrains.com/display/JBINT/Maven+proxy+server
                                       "https://repo.labs.intellij.net/repo1");
    return "<settings>" +
           content +
           "<mirrors>" +
           "  <mirror>" +
           "    <id>jb-central-proxy</id>" +
           "    <url>" + mirror + "</url>" +
           "    <mirrorOf>external:*,!flex-repository</mirrorOf>" +
           "  </mirror>" +
           "</mirrors>" +
           "</settings>";
  }

  protected void restoreSettingsFile() throws IOException {
    updateSettingsXml("");
  }

  protected Module createModule(String name) {
    return createModule(name, StdModuleTypes.JAVA);
  }

  protected Module createModule(final String name, final ModuleType type) {
    try {
      return WriteCommandAction.writeCommandAction(myProject).compute(() -> {
        VirtualFile f = createProjectSubFile(name + "/" + name + ".iml");
        Module module = ModuleManager.getInstance(myProject).newModule(f.getPath(), type.getId());
        PsiTestUtil.addContentRoot(module, f.getParent());
        return module;
      });
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  protected VirtualFile createProjectPom(@NotNull @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) {
    return myProjectPom = createPomFile(myProjectRoot, xml);
  }

  protected VirtualFile createModulePom(String relativePath,
                                        @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) {
    return createPomFile(createProjectSubDir(relativePath), xml);
  }

  protected VirtualFile createPomFile(final VirtualFile dir,
                                      @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) {
    VirtualFile f = dir.findChild("pom.xml");
    if (f == null) {
      try {
        f = WriteAction.computeAndWait(() -> {
          VirtualFile res = dir.createChildData(null, "pom.xml");
          return res;
        });
      }
      catch (IOException e) {
        throw new RuntimeException(e);
      }
      myAllPoms.add(f);
    }
    setPomContent(f, xml);
    return f;
  }

  @NonNls
  @Language(value = "XML")
  public static String createPomXml(@NonNls @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) {
    return "<?xml version=\"1.0\"?>" +
           "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"" +
           "         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
           "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">" +
           "  <modelVersion>4.0.0</modelVersion>" +
           xml +
           "</project>";
  }

  protected VirtualFile createProfilesXmlOldStyle(String xml) {
    return createProfilesFile(myProjectRoot, xml, true);
  }

  protected VirtualFile createProfilesXmlOldStyle(String relativePath, String xml) {
    return createProfilesFile(createProjectSubDir(relativePath), xml, true);
  }

  protected VirtualFile createProfilesXml(String xml) {
    return createProfilesFile(myProjectRoot, xml, false);
  }

  protected VirtualFile createProfilesXml(String relativePath, String xml) {
    return createProfilesFile(createProjectSubDir(relativePath), xml, false);
  }

  private static VirtualFile createProfilesFile(VirtualFile dir, String xml, boolean oldStyle) {
    return createProfilesFile(dir, createValidProfiles(xml, oldStyle));
  }

  protected VirtualFile createFullProfilesXml(String content) {
    return createProfilesFile(myProjectRoot, content);
  }

  protected VirtualFile createFullProfilesXml(String relativePath, String content) {
    return createProfilesFile(createProjectSubDir(relativePath), content);
  }

  private static VirtualFile createProfilesFile(final VirtualFile dir, String content) {
    VirtualFile f = dir.findChild("profiles.xml");
    if (f == null) {
      try {
        f = WriteAction.computeAndWait(() -> {
          VirtualFile res = dir.createChildData(null, "profiles.xml");
          return res;
        });
      }
      catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    setFileContent(f, content, true);
    return f;
  }

  @Language("XML")
  private static String createValidProfiles(String xml, boolean oldStyle) {
    if (oldStyle) {
      return "<?xml version=\"1.0\"?>" +
             "<profiles>" +
             xml +
             "</profiles>";
    }
    return "<?xml version=\"1.0\"?>" +
           "<profilesXml>" +
           "<profiles>" +
           xml +
           "</profiles>" +
           "</profilesXml>";
  }

  protected void deleteProfilesXml() throws IOException {
    WriteCommandAction.writeCommandAction(myProject).run(() -> {
      VirtualFile f = myProjectRoot.findChild("profiles.xml");
      if (f != null) f.delete(this);
    });
  }

  protected void createStdProjectFolders() {
    createProjectSubDirs("src/main/java",
                         "src/main/resources",
                         "src/test/java",
                         "src/test/resources");
  }

  protected void createProjectSubDirs(String... relativePaths) {
    for (String path: relativePaths) {
      createProjectSubDir(path);
    }
  }

  protected VirtualFile createProjectSubDir(String relativePath) {
    File f = new File(getProjectPath(), relativePath);
    f.mkdirs();
    return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
  }

  protected VirtualFile createProjectSubFile(String relativePath) throws IOException {
    File f = new File(getProjectPath(), relativePath);
    f.getParentFile().mkdirs();
    f.createNewFile();
    return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
  }

  protected VirtualFile createProjectSubFile(String relativePath, String content) throws IOException {
    VirtualFile file = createProjectSubFile(relativePath);
    setFileContent(file, content, false);
    return file;
  }

  protected static void setPomContent(VirtualFile file, @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) {
    setFileContent(file, createPomXml(xml), true);
  }

  private static void setFileContent(final VirtualFile file, final String content, final boolean advanceStamps) {
    try {
      WriteAction.runAndWait(() -> {
        if (advanceStamps) {
          file.setBinaryContent(content.getBytes(StandardCharsets.UTF_8), -1, file.getTimeStamp() + 4000);
        }
        else {
          file.setBinaryContent(content.getBytes(StandardCharsets.UTF_8), file.getModificationStamp(), file.getTimeStamp());
        }
      });
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  protected static <T, U> void assertOrderedElementsAreEqual(Collection<U> actual, Collection<T> expected) {
    assertOrderedElementsAreEqual(actual, expected.toArray());
  }

  protected static <T> void assertUnorderedElementsAreEqual(@NotNull Collection<T> actual, @NotNull Collection<T> expected) {
    assertThat(actual).hasSameElementsAs(expected);
  }

  protected static void assertUnorderedPathsAreEqual(Collection<String> actual, Collection<String> expected) {
    assertEquals(new SetWithToString<>(new THashSet<>(expected, FileUtil.PATH_HASHING_STRATEGY)),
                 new SetWithToString<>(new THashSet<>(actual, FileUtil.PATH_HASHING_STRATEGY)));
  }

  protected static <T> void assertUnorderedElementsAreEqual(T[] actual, T... expected) {
    assertUnorderedElementsAreEqual(Arrays.asList(actual), expected);
  }

  protected static <T> void assertUnorderedElementsAreEqual(Collection<T> actual, T... expected) {
    assertUnorderedElementsAreEqual(actual, Arrays.asList(expected));
  }

  protected static <T, U> void assertOrderedElementsAreEqual(Collection<U> actual, T... expected) {
    String s = "\nexpected: " + Arrays.asList(expected) + "\nactual: " + new ArrayList<>(actual);
    assertEquals(s, expected.length, actual.size());

    List<U> actualList = new ArrayList<>(actual);
    for (int i = 0; i < expected.length; i++) {
      T expectedElement = expected[i];
      U actualElement = actualList.get(i);
      assertEquals(s, expectedElement, actualElement);
    }
  }

  protected static <T> void assertContain(List<? extends T> actual, T... expected) {
    List<T> expectedList = Arrays.asList(expected);
    assertTrue("expected: " + expectedList + "\n" + "actual: " + actual.toString(), actual.containsAll(expectedList));
  }

  protected static <T> void assertDoNotContain(List<T> actual, T... expected) {
    List<T> actualCopy = new ArrayList<>(actual);
    actualCopy.removeAll(Arrays.asList(expected));
    assertEquals(actual.toString(), actualCopy.size(), actual.size());
  }

  protected static void assertUnorderedLinesWithFile(String filePath, String expectedText) {
    try {
      assertSameLinesWithFile(filePath, expectedText);
    }
    catch (FileComparisonFailure e) {
      String expected = e.getExpected();
      String actual = e.getActual();
      assertUnorderedElementsAreEqual(expected.split("\n"), actual.split("\n"));
    }
  }

  protected boolean ignore() {
    //printIgnoredMessage(null);
    return false;
  }

  protected boolean hasMavenInstallation() {
    boolean result = getTestMavenHome() != null;
    if (!result) printIgnoredMessage("Maven installation not found");
    return result;
  }

  private void printIgnoredMessage(String message) {
    String toPrint = "Ignored";
    if (message != null) {
      toPrint += ", because " + message;
    }
    toPrint += ": " + getClass().getSimpleName() + "." + getName();
    System.out.println(toPrint);
  }

  protected <R, E extends Throwable> R runWriteAction(@NotNull ThrowableComputable<R, E> computable) throws E {
    return WriteCommandAction.writeCommandAction(myProject).compute(computable);
  }

  protected <E extends Throwable> void runWriteAction(@NotNull ThrowableRunnable<E> runnable) throws E {
    WriteCommandAction.writeCommandAction(myProject).run(runnable);
  }

  private static String getTestMavenHome() {
    return System.getProperty("idea.maven.test.home");
  }

  private static class SetWithToString<T> extends AbstractSet<T> {

    private final Set<T> myDelegate;

    SetWithToString(@NotNull Set<T> delegate) {
      myDelegate = delegate;
    }

    @Override
    public int size() {
      return myDelegate.size();
    }

    @Override
    public boolean contains(Object o) {
      return myDelegate.contains(o);
    }

    @NotNull
    @Override
    public Iterator<T> iterator() {
      return myDelegate.iterator();
    }

    @Override
    public boolean containsAll(Collection<?> c) {
      return myDelegate.containsAll(c);
    }

    @Override
    public boolean equals(Object o) {
      return myDelegate.equals(o);
    }

    @Override
    public int hashCode() {
      return myDelegate.hashCode();
    }
  }
}


text:
'use strict';

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default React.createClass({
  render() {
    const { text, style } = this.props;
    return (
      <Text style={[styles.default, style]}>{text}</Text>
    );
  }
});

const styles = StyleSheet.create({
  default: {
    fontSize: 17,
  },
});


text:
layout: base
---

Live Demo

To participate in the demonstration you will need:

Javascript enabled

A modern browser

All examples given are written with babel loaders to support es6 (stage-0) and JSX syntax.

Simple Example

This is the simplest implementation of React-Object-Table, an editable list of strings.

To allow editing, the table requires an onUpdate handler (refer to source code below).

Even this simple example supports:

Single cell editing

Familiar navigation and completion hotkeys such as the arrow keys and tab/enter

Multi column or row copy-paste (except on Firefox, where the required events do not
    exist)

  Loading ...

More Feature-Filled Example

This example demonstrates:

Read-only columns

A more complex update handler

The ability to add rows (handled outside the scope of React-Object-Table)

Row-level action handlers

A very basic custom renderer

  Loading ...

Customisation Example

This example demonstrates:

A more exciting custom renderer

A custom editor widget

Cell input validation (age column, confirmed to be positive integer in a reasonable
    range)

Very basic validation error exception handling

  Loading ...


text:
'use strict';

angular.module('snippetModule', [
    'detailSnippetModule',
    'postSnippetModule'
]);


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Storage.Queue;
using Microsoft.Azure.WebJobs.Host;

namespace Microsoft.Azure.WebJobs.Host.Queues
{
    internal static class CloudQueueMessageExtensions
    {
        private static PropertyHelper _idProp;
        private static PropertyHelper _popReceiptProp;

        static CloudQueueMessageExtensions()
        {
            IReadOnlyList<PropertyHelper> messageProperties = PropertyHelper.GetProperties(typeof(CloudQueueMessage));
            _idProp = messageProperties.Single(p => p.Name == nameof(CloudQueueMessage.Id));
            _popReceiptProp = messageProperties.Single(p => p.Name == nameof(CloudQueueMessage.PopReceipt));
        }

        /// <summary>
        /// Overwrites the message's Id and PopReceipt properties with the specified values, if different.
        /// </summary>
        public static void UpdateChangedProperties(this CloudQueueMessage message, string id, string popReceipt)
        {
            if (id != message.Id)
            {
                _idProp.SetValue(message, id);
            }

            if (popReceipt != message.PopReceipt)
            {
                _popReceiptProp.SetValue(message, popReceipt);
            }
        }
    }
}


text:
import keyMirror from 'keymirror';

export const ActionTypes = keyMirror({
  FETCH_QUEENSHOP_HOT: null,

  MEMBER_GET: null,
  MEMBER_CREATE: null
});

export const Shops = keyMirror({
  QUEENSHOP: null
});


text:
/**
 * @author Anas Nashif
 */

#ifndef WSMAN_SOAP_ENVELOPE_H_
#define WSMAN_SOAP_ENVELOPE_H_

#include "wsman-types.h"
#include "wsman-soap.h"
#include "wsman-soap-message.h"

#define ENFORCE_MUST_UNDERSTAND	"EnforceMustUnderstand"

/* special hash key to denote method args (where array elements have identical keys) */
#define METHOD_ARGS_KEY "method_args"

int wsman_is_valid_envelope(WsmanMessage * msg, WsXmlDocH doc);

char *wsman_get_soap_header_value( WsXmlDocH doc, const char *nsUri,
				  			const char *name);

WsXmlNodeH wsman_get_soap_header_element(WsXmlDocH doc, const char *nsUri,
					 const char *name);

WsXmlDocH wsman_build_soap_fault( const char *soapNsUri,
				 const char *faultNsUri, const char *code,
				 const char *subCode, const char *reason,
				 const char *detail);

WsXmlDocH wsman_create_response_envelope(WsXmlDocH rqstDoc, const char *action);

WsXmlDocH wsman_build_inbound_envelope( WsmanMessage * msg);

WsXmlDocH wsman_create_fault_envelope(
				      WsXmlDocH rqstDoc,
				      const char *code,
				      const char *subCodeNs,
				      const char *subCode,
				      const char *fault_action,
				      const char *lang,
				      const char *reason, const char *faultDetail);

char *wsman_get_class_name(WsContextH cntx);

char *wsman_get_method_name(WsContextH cntx);

hash_t *wsman_get_method_args(WsContextH cntx, const char *resource_uri);

int wsman_get_max_elements(WsContextH cntx, WsXmlDocH doc);

unsigned long wsman_get_max_envelope_size(WsContextH cntx, WsXmlDocH doc);

char *wsman_get_fragment_string(WsContextH cntx, WsXmlDocH doc);

void wsman_get_fragment_type(char *fragstr, int *fragment_flag, char **element,
	int *index);

void wsman_set_estimated_total(WsXmlDocH in_doc,
			       WsXmlDocH out_doc,
			       WsEnumerateInfo * enumInfo);

char *wsman_get_selector(WsContextH cntx, WsXmlDocH doc, const char *name,
			 const int index);

hash_t *wsman_get_selectors_from_epr(WsContextH cntx, WsXmlNodeH epr_node);

hash_t *wsman_get_selector_list(WsContextH cntx, WsXmlDocH doc);

hash_t *wsman_get_selector_list_from_filter(WsContextH cntx,
					    WsXmlDocH doc);

void wsman_add_selector(WsXmlNodeH baseNode, const char *name, const char *val);

char *wsman_get_action(WsContextH cntx, WsXmlDocH doc);

char *wsman_get_resource_uri(WsContextH cntx, WsXmlDocH doc);

int wsman_is_fault_envelope(WsXmlDocH doc);

void wsman_set_fault(WsmanMessage * msg,
		     WsmanFaultCodeType fault_code,
		     WsmanFaultDetailType fault_detail_code,
		     const char *details);

int wsman_is_identify_request(WsXmlDocH doc);
int wsman_check_identify(WsmanMessage * msg);

int wsman_is_event_related_request(WsXmlDocH doc);

int wsman_is_valid_xml_envelope(WsXmlDocH doc);

void wsman_add_namespace_as_selector(WsXmlDocH doc, const char *_namespace);

void wsman_add_fragement_for_header(WsXmlDocH indoc, WsXmlDocH outdoc);

char *wsman_get_option_set(WsContextH cntx, WsXmlDocH doc, const char *op);

int wsman_parse_enum_request(WsContextH cntx, WsEnumerateInfo * enumInfo);

int wsman_parse_event_request(WsXmlDocH doc, WsSubscribeInfo * subsInfo, WsmanFaultCodeType *faultcode,
	WsmanFaultDetailType *detailcode);

int wsman_parse_credentials(WsXmlDocH doc, WsSubscribeInfo * subsInfo, WsmanFaultCodeType *faultcode,
	WsmanFaultDetailType *detailcode);

void wsman_set_expiretime(WsXmlNodeH  node, unsigned long * expire, WsmanFaultCodeType *fault_code);

int time_expired(unsigned long lt);

WsXmlDocH wsman_create_doc(const char *rootname);

void wsman_destroy_doc(WsXmlDocH doc);

#endif


text:
package com.planet_ink.coffee_mud.Abilities.Thief;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings({"unchecked","rawtypes"})
public class Thief_UsePoison extends ThiefSkill
{
	@Override public String ID() { return "Thief_UsePoison"; }
	private final static String localizedName = CMLib.lang().L("Use Poison");
	@Override public String name() { return localizedName; }
	@Override protected int canAffectCode(){return 0;}
	@Override protected int canTargetCode(){return Ability.CAN_ITEMS;}
	@Override public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;}
	private static final String[] triggerStrings =I(new String[] {"POISON","USEPOISON"});
	@Override public int classificationCode(){return Ability.ACODE_THIEF_SKILL|Ability.DOMAIN_POISONING;}
	@Override public String[] triggerStrings(){return triggerStrings;}
	@Override public int usageType(){return USAGE_MOVEMENT|USAGE_MANA;}

	public List<Ability> returnOffensiveAffects(Physical fromMe)
	{
		final Vector offenders=new Vector();

		for(final Enumeration<Ability> a=fromMe.effects();a.hasMoreElements();)
		{
			final Ability A=a.nextElement();
			if((A!=null)&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_POISON))
				offenders.addElement(A);
		}
		return offenders;
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		if(commands.size()<2)
		{
			mob.tell(L("What would you like to poison, and which poison would you use?"));
			return false;
		}
		final Item target=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,(String)commands.elementAt(0));
		if((target==null)||(!CMLib.flags().canBeSeenBy(target,mob)))
		{
			mob.tell(L("You don't see '@x1' here.",((String)commands.elementAt(0))));
			return false;
		}
		if((!(target instanceof Food))
		&&(!(target instanceof Drink))
		&&(!(target instanceof Weapon)))
		{
			mob.tell(L("You don't know how to poison @x1.",target.name(mob)));
			return false;
		}
		final Item poison=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,CMParms.combine(commands,1));
		if((poison==null)||(!CMLib.flags().canBeSeenBy(poison,mob)))
		{
			mob.tell(L("You don't see '@x1' here.",CMParms.combine(commands,1)));
			return false;
		}
		final List<Ability> V=returnOffensiveAffects(poison);
		if((V.size()==0)||(!(poison instanceof Drink)))
		{
			mob.tell(L("@x1 is not a poison!",poison.name()));
			return false;
		}
		final Drink dPoison=(Drink)poison;

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_THIEF_ACT,L("<S-NAME> attempt(s) to poison <T-NAMESELF>."));
		if(mob.location().okMessage(mob,msg))
		{
			mob.location().send(mob,msg);
			if(success)
			{
				final Ability A=V.get(0);
				if(A!=null)
				{
					if(target instanceof Weapon)
						A.invoke(mob,target,true,adjustedLevel(mob,asLevel));
					else
						target.addNonUninvokableEffect(A);

					int amountToTake=dPoison.thirstQuenched()/5;
					if(amountToTake<1)
						amountToTake=1;
					dPoison.setLiquidRemaining(dPoison.liquidRemaining()-amountToTake);
					if(dPoison.disappearsAfterDrinking()
					||((dPoison instanceof RawMaterial)&&(dPoison.liquidRemaining()<=0)))
						dPoison.destroy();
				}

			}
		}
		return success;
	}

}


text:
import time

from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping

try:
    import jinja2
except:
    jinja2 = None

import bork
import bork.groups
from bork import config

ephemeral0 = BlockDeviceType(ephemeral_name='ephemeral0')
ephemeral1 = BlockDeviceType(ephemeral_name='ephemeral1')
ephemeral2 = BlockDeviceType(ephemeral_name='ephemeral2')
ephemeral3 = BlockDeviceType(ephemeral_name='ephemeral3')

block_device_map = BlockDeviceMapping()
block_device_map['/dev/sdb'] = ephemeral0
block_device_map['/dev/sdc'] = ephemeral1
block_device_map['/dev/sdd'] = ephemeral2
block_device_map['/dev/sde'] = ephemeral3

def boot(conn, namespace, env, package, instance_type,
        zone='a', ami='ubuntu.12.04', num=1, branch='master',
        spot_price=None):

    is_cluster = (
        instance_type.startswith('cc2') or instance_type.startswith('cr1'))
    if is_cluster:
        ami += ':cluster'

    image = bork.buuks.amis['%s:%s' % (ami, conn.region.name)]

    p = bork.buuks.package(package)

    # booting from scratch
    bootstrap = bork.buuks.boot['boot.sh']

    bork.groups.ensure_groups(conn, namespace, env, p.groups())
    security_groups = [
        bork.groups.full_name(namespace, env, x) for x in p.groups()]

    kw = {}
    role = p.role
    if role:
        # TODO: update to take namespace
        if bork.roles.ensure_role(namespace, env, role):
            # give the role time to be created
            time.sleep(10)
        kw['instance_profile_name'] = 'aws-%s-%s-%s-instance-profile' % (
            namespace, env, role)

    user_data = jinja2.Template(bootstrap).render({
        'user': config.user,
        'package': package,
        'authorized_keys': bork.buuks.authorized_keys,
        'private_key': bork.buuks.private_key,
        'repos': p.repos(),
        })

    if not spot_price:
        r = conn.run_instances(
            image,
            min_count=num,
            max_count=num,
            instance_type=instance_type,
            security_groups=security_groups,
            placement=conn.region.name+zone,
            user_data=user_data,
            block_device_map=block_device_map,
            **kw)

        # give aws a chance to create the instances before tagging them
        time.sleep(2)
        for instance in r.instances:
            instance.add_tag('namespace', namespace)
            instance.add_tag('role', package)
            instance.add_tag('env', "%s.%s" % (namespace, env))
            instance.add_tag('owner', config.user)

    else:
        r = conn.request_spot_instances(
            spot_price,
            image,
            instance_type=instance_type,
            security_groups=security_groups,
            placement=conn.region.name+zone,
            user_data=user_data,
            block_device_map=block_device_map,
            **kw)

    return r


text:
#ifndef REPLACE_WINDOW_H
#define REPLACE_WINDOW_H

#include <Window.h>

class BString;
class BButton;
class BHandler;
class BMessage;
class BCheckBox;
class BTextControl;

class ReplaceWindow : public BWindow {
	public:
						ReplaceWindow(BRect frame, BHandler* _handler,
							BString* searchString, BString* replaceString,
							bool caseState, bool wrapState, bool backState);

		virtual void	MessageReceived(BMessage* message);
		virtual void	DispatchMessage(BMessage* message, BHandler* handler);
		virtual void	Show();

	private:
		void 			_SendMessage(uint32 what);
		void 			_ChangeUI();

		BTextControl	*fSearchString;
		BTextControl	*fReplaceString;
		BCheckBox		*fCaseSensBox;
		BCheckBox		*fWrapBox;
		BCheckBox		*fBackSearchBox;
		BCheckBox		*fAllWindowsBox;
		BButton			*fReplaceButton;
		BButton			*fReplaceAllButton;
		BButton			*fCancelButton;
		BHandler		*fHandler;
		bool			fUIchange;
};

#endif	// REPLACE_WINDOW_H