text:
oauth2_proxy
=================

(This project was renamed from Google Auth Proxy - May 2015)

A reverse proxy and static file server that provides authentication using Providers (Google, Github, and others)
to validate accounts by email, domain or group.

[![Build Status](https://secure.travis-ci.org/bitly/oauth2_proxy.png?branch=master)](http://travis-ci.org/bitly/oauth2_proxy)

![Sign In Page](https://cloud.githubusercontent.com/assets/45028/4970624/7feb7dd8-6886-11e4-93e0-c9904af44ea8.png)

## Architecture

![OAuth2 Proxy Architecture](https://cloud.githubusercontent.com/assets/45028/8027702/bd040b7a-0d6a-11e5-85b9-f8d953d04f39.png)

## Installation

1. Download [Prebuilt Binary](https://github.com/bitly/oauth2_proxy/releases) (current release is `v2.0.1`) or build with `$ go get github.com/bitly/oauth2_proxy` which will put the binary in `$GOROOT/bin`
2. Select a Provider and Register an OAuth Application with a Provider
3. Configure OAuth2 Proxy using config file, command line options, or environment variables
4. Configure SSL or Deploy behind a SSL endpoint (example provided for Nginx)

## OAuth Provider Configuration

You will need to register an OAuth application with a Provider (Google, Github or another provider), and configure it with Redirect URI(s) for the domain you intend to run `oauth2_proxy` on.

Valid providers are :

* [Google](#google-auth-provider) *default*

* [Azure](#azure-auth-provider)
* [GitHub](#github-auth-provider)
* [LinkedIn](#linkedin-auth-provider)
* [MyUSA](#myusa-auth-provider)

The provider can be selected using the `provider` configuration value.

### Google Auth Provider

For Google, the registration steps are:

1. Create a new project: https://console.developers.google.com/project
2. Choose the new project from the top right project dropdown (only if another project is selected)
3. In the project Dashboard center pane, choose **"Enable and manage APIs"**
4. In the left Nav pane, choose **"Credentials"**
5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save.
6. In the center pane, choose **"Credentials"** tab.
   * Open the **"New credentials"** drop down
   * Choose **"OAuth client ID"**
   * Choose **"Web application"**
   * Application name is freeform, choose something appropriate
   * Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com`
   * Authorized redirect URIs is the location of oath2/callback ex: `https://internal.yourcompany.com/oauth2/callback`
   * Choose **"Create"**
4. Take note of the **Client ID** and **Client Secret**

It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the account is still authorized.

#### Restrict auth to specific Google groups on your domain. (optional)

1. Create a service account: https://developers.google.com/identity/protocols/OAuth2ServiceAccount and make sure to download the json file.
2. Make note of the Client ID for a future step.
3. Under "APIs & Auth", choose APIs.
4. Click on Admin SDK and then Enable API.
5. Follow the steps on https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account and give the client id from step 2 the following oauth scopes:
```
https://www.googleapis.com/auth/admin.directory.group.readonly
https://www.googleapis.com/auth/admin.directory.user.readonly
```
6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access.
7. Create or choose an existing administrative email address on the Gmail domain to assign to the ```google-admin-email``` flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from step 5 for the reason why.
8. Create or choose an existing email group and set that email to the ```google-group``` flag. You can pass multiple instances of this flag with different groups
and the user will be checked against all the provided groups.
9. Lock down the permissions on the json file downloaded from step 1 so only oauth2_proxy is able to read the file and set the path to the file in the ```google-service-account-json``` flag.
10. Restart oauth2_proxy.

Note: The user is checked against the group members list on initial authentication and every time the token is refreshed ( about once an hour ).

### Azure Auth Provider

1. [Add an application](https://azure.microsoft.com/en-us/documentation/articles/active-directory-integrating-applications/) to your Azure Active Directory tenant.
2. On the App properties page provide the correct Sign-On URL ie `https//internal.yourcompany.com/oauth2/callback`
3. If applicable take note of your `TenantID` and provide it via the `--azure-tenant=<YOUR TENANT ID>` commandline option. Default the `common` tenant is used.

The Azure AD auth provider uses `openid` as it default scope. It uses `https://graph.windows.net` as a default protected resource. It call to `https://graph.windows.net/me` to get the email address of the user that logs in.

### GitHub Auth Provider

1. Create a new project: https://github.com/settings/developers
2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback`

The GitHub auth provider supports two additional parameters to restrict authentication to Organization or Team level access. Restricting by org and team is normally accompanied with `--email-domain=*`

    -github-org="": restrict logins to members of this organisation
    -github-team="": restrict logins to members of this team

### LinkedIn Auth Provider

For LinkedIn, the registration steps are:

1. Create a new project: https://www.linkedin.com/secure/developer
2. In the OAuth User Agreement section:
   * In default scope, select r_basicprofile and r_emailaddress.
   * In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback`
3. Fill in the remaining required fields and Save.
4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key**

### MyUSA Auth Provider

The [MyUSA](https://alpha.my.usa.gov) authentication service ([GitHub](https://github.com/18F/myusa))

### Microsoft Azure AD Provider

For adding an application to the Microsoft Azure AD follow [these steps to add an application](https://azure.microsoft.com/en-us/documentation/articles/active-directory-integrating-applications/).

Take note of your `TenantId` if applicable for your situation. The `TenantId` can be used to override the default `common` authorization server with a tenant specific server.

## Email Authentication

To authorize by email domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use `--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresse use `--email-domain=*`.

## Configuration

`oauth2_proxy` can be configured via [config file](#config-file), [command line options](#command-line-options) or [environment variables](#environment-variables).

### Config File

An example [oauth2_proxy.cfg](contrib/oauth2_proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `-config=/etc/oauth2_proxy.cfg`

### Command Line Options

```
Usage of oauth2_proxy:
  -approval-prompt="force": Oauth approval_prompt
  -authenticated-emails-file="": authenticate against emails via file (one per line)
  -azure-tenant="common": go to a tenant-specific or common (tenant-independent) endpoint.
  -basic-auth-password="": the password to set when passing the HTTP Basic Auth header
  -client-id="": the OAuth Client ID: ie: "123456.apps.googleusercontent.com"
  -client-secret="": the OAuth Client Secret
  -config="": path to config file
  -cookie-domain="": an optional cookie domain to force cookies to (ie: .yourcompany.com)*
  -cookie-expire=168h0m0s: expire timeframe for cookie
  -cookie-httponly=true: set HttpOnly cookie flag
  -cookie-name="_oauth2_proxy": the name of the cookie that the oauth_proxy creates
  -cookie-refresh=0: refresh the cookie after this duration; 0 to disable
  -cookie-secret="": the seed string for secure cookies
  -cookie-secure=true: set secure (HTTPS) cookie flag
  -custom-templates-dir="": path to custom html templates
  -display-htpasswd-form=true: display username / password login form if an htpasswd file is provided
  -email-domain=: authenticate emails with the specified domain (may be given multiple times). Use * to authenticate any email
  -github-org="": restrict logins to members of this organisation
  -github-team="": restrict logins to members of this team
  -google-admin-email="": the google admin to impersonate for api calls
  -google-group=: restrict logins to members of this google group (may be given multiple times).
  -google-service-account-json="": the path to the service account json credentials
  -htpasswd-file="": additionally authenticate against a htpasswd file. Entries must be created with "htpasswd -s" for SHA encryption
  -http-address="127.0.0.1:4180": [http://]<addr>:<port> or unix://<path> to listen on for HTTP clients
  -https-address=":443": <addr>:<port> to listen on for HTTPS clients
  -login-url="": Authentication endpoint
  -pass-access-token=false: pass OAuth access_token to upstream via X-Forwarded-Access-Token header
  -pass-basic-auth=true: pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream
  -pass-host-header=true: pass the request Host Header to upstream
  -profile-url="": Profile access endpoint
  -provider="google": OAuth provider
  -proxy-prefix="/oauth2": the url root path that this proxy should be nested under (e.g. /<oauth2>/sign_in)
  -redeem-url="": Token redemption endpoint
  -redirect-url="": the OAuth Redirect URL. ie: "https://internalapp.yourcompany.com/oauth2/callback"
  -resource="": the resource that is being protected. ie: "https://graph.windows.net". Currently only used in the Azure provider.
  -request-logging=true: Log requests to stdout
  -scope="": Oauth scope specification
  -signature-key="": GAP-Signature request signature key (algorithm:secretkey)
  -skip-auth-regex=: bypass authentication for requests path's that match (may be given multiple times)
  -tls-cert="": path to certificate file
  -tls-key="": path to private key file
  -upstream=: the http url(s) of the upstream endpoint or file:// paths for static files. Routing is based on the path
  -validate-url="": Access token validation endpoint
  -version=false: print version string
```

See below for provider specific options

### Upstreams Configuration

`oauth2_proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers or serve static files from the file system. HTTP and HTTPS upstreams are configured by providing a URL such as `http://127.0.0.1:8080/` for the upstream parameter, that will forward all authenticated requests to be forwarded to the upstream server. If you instead provide `http://127.0.0.1:8080/some/path/` then it will only be requests that start with `/some/path/` which are forwarded to the upstream.

Static file paths are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2_proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at. `file:///var/www/static/#/static/` will ie. make `/var/www/static/` available at `http://[oauth2_proxy url]/static/`.

Multiple upstreams can either be configured by supplying a comma separated list to the `-upstream` parameter, supplying the parameter multiple times or provinding a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with.

### Environment variables

The environment variables `OAUTH2_PROXY_CLIENT_ID`, `OAUTH2_PROXY_CLIENT_SECRET`, `OAUTH2_PROXY_COOKIE_SECRET`, `OAUTH2_PROXY_COOKIE_DOMAIN` and `OAUTH2_PROXY_COOKIE_EXPIRE` can be used in place of the corresponding command-line arguments.

## SSL Configuration

There are two recommended configurations.

1) Configure SSL Terminiation with OAuth2 Proxy by providing a `--tls-cert=/path/to/cert.pem` and `--tls-key=/path/to/cert.key`.

The command line to run `oauth2_proxy` in this configuration would look like this:

```bash
./oauth2_proxy \
   --email-domain="yourcompany.com"  \
   --upstream=http://127.0.0.1:8080/ \
   --tls-cert=/path/to/cert.pem \
   --tls-key=/path/to/cert.key \
   --cookie-secret=... \
   --cookie-secure=true \
   --provider=... \
   --client-id=... \
   --client-secret=...
```

2) Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ....

Because `oauth2_proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an
external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or
`--http-address="http://:4180"`.

Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2_proxy` on port `4180`.
`oauth2_proxy` will then authenticate requests for an upstream application. The external endpoint for this example
would be `https://internal.yourcompany.com/`.

An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL
via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security):

```
server {
    listen 443 default ssl;
    server_name internal.yourcompany.com;
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/cert.key;
    add_header Strict-Transport-Security max-age=2592000;

    location / {
        proxy_pass http://127.0.0.1:4180;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_connect_timeout 1;
        proxy_send_timeout 30;
        proxy_read_timeout 30;
    }
}
```

The command line to run `oauth2_proxy` in this configuration would look like this:

```bash
./oauth2_proxy \
   --email-domain="yourcompany.com"  \
   --upstream=http://127.0.0.1:8080/ \
   --cookie-secret=... \
   --cookie-secure=true \
   --provider=... \
   --client-id=... \
   --client-secret=...
```

## Endpoint Documentation

OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable.

* /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info
* /ping - returns an 200 OK response
* /oauth2/sign_in - the login page, which also doubles as a sign out page (it clears cookies)
* /oauth2/start - a URL that will redirect to start the OAuth cycle
* /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url.
* /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](#nginx-auth-request)

## Request signatures

If `signature_key` is defined, proxied requests will be signed with the
`GAP-Signature` header, which is a [Hash-based Message Authentication Code
(HMAC)](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code)
of selected request information and the request body [see `SIGNATURE_HEADERS`
in `oauthproxy.go`](./oauthproxy.go).

`signature_key` must be of the form `algorithm:secretkey`, (ie: `signature_key = "sha1:secret0"`)

For more information about HMAC request signature validation, read the
following:

* [Amazon Web Services: Signing and Authenticating REST
  Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html)
* [rc3.org: Using HMAC to authenticate Web service
  requests](http://rc3.org/2011/12/02/using-hmac-to-authenticate-web-service-requests/)

## Logging Format

OAuth2 Proxy logs requests to stdout in a format similar to Apache Combined Log.

```
<REMOTE_ADDRESS> - <user@domain.com> [19/Mar/2015:17:20:19 -0400] <HOST_HEADER> GET <UPSTREAM_HOST> "/path/" HTTP/1.1 "<USER_AGENT>" <RESPONSE_CODE> <RESPONSE_BYTES> <REQUEST_DURATION>
```

## Adding a new Provider

Follow the examples in the [`providers` package](providers/) to define a new
`Provider` instance. Add a new `case` to
[`providers.New()`](providers/providers.go) to allow `oauth2_proxy` to use the
new `Provider`.

## Configuring for use with the Nginx `auth_request` directive

The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2_proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example:

```nginx
server {
  listen 443 ssl spdy;
  server_name ...;
  include ssl/ssl.conf;

  location = /auth {
    internal;
    proxy_pass http://127.0.0.1:4180;
  }

  location / {
    auth_request /auth;
    error_page 401 = ...;

    root /path/to/the/site;
    default_type text/html;
    charset utf-8;
    charset_types application/json utf-8;
  }
}
```

redpajama_set_name: RedPajamaGithub


text:
- [demo1](http://ci-capstone.lloricmayugagarcia.com)
- [demo2](http://ci-capstone.sprikiwiki.club/)

## Frameworks used
Platform|Framework
--------------------- | ----------------------------
 PHP Framework        | [CodeIgniter 3.1.4](http://codeigniter.com).
 Admin UI Framework   | [matrix-admin Bootstrap](http://matrixadmin.themedesigner.in/).

## Library used

 Name | Repository
-------------------------- | ----------------------
 Login Authentication      | [CodeIgniter-Ion-Auth](https://github.com/benedmunds/CodeIgniter-Ion-Auth).
 Migration Authentication  | [codeigniter-ion-auth-migration](https://github.com/iamfiscus/codeigniter-ion-auth-migration).
 Error Log                 | [CodeIgniter-Log-Library](https://github.com/appleboy/CodeIgniter-Log-Library).
 Excel Export              | [Codeigniter-Excel-Export](https://github.com/jiji262/Codeigniter-Excel-Export).
 Core My_Model             | [CodeIgniter-MY_Model](https://github.com/avenirer/CodeIgniter-MY_Model).
 Translator                | [codeigniter3-translations](https://github.com/bcit-ci/codeigniter3-translations).

## Installation

- Create first a databse named ``ci_capstone`` .
- then just run/execute the website, ``tables`` in ``database`` will automatically migrate.

- OR you can just import in databse a sample data from ``sample_data/ci_capstone.sql``.

## Default Login

Username | Password
-------- | -----------
administrator|mypasswordisadmin1

## Screencapture
-Updated overview over the Admin Panel
![screenshot at 2017-04-09 21-26-03](https://cloud.githubusercontent.com/assets/8251344/24837640/50a98c44-1d6b-11e7-95b8-11c754f8c81d.png)

## Note:
### production ENVIRONMENT
- compress html, for fast renderring page in live server
- csrf_protection is enabled (set to TRUE), for prevent malicious/unnecessary behavior in submitting forms
- errors log save to database,then not directly seen in browsers,

### developing ENVIRONMENT
- compress html disabled, for easy monitoring html output (easy debugging)
- csrf_protection is disabled (set to FALSE), for easy submitting forms, for testing in big forms
- errors log disabled, directly promt in browser,
- database set to localhost

### ..
- all is this set up in application/config/{ENVIRONMENT_FOLDER_NAMES}/config.php

### Thanks to our team.

- [Jink Po](https://github.com/shikai06)
- [Edzar Calibod](https://github.com/iEdzar)

### Specially of Senior Programmer's suggesting.

- [Marcelius Dagpin](https://github.com/mardagz)
- [Jicking Bebiro](https://github.com/jicking)


text:
using System;
using System.Data;
using System.Reflection;
using System.Reflection.Emit;

using AutoMapper.Configuration.Conventions;
using AutoMapper.Data.Utils;
using AutoMapper.Internal;
using AutoMapper.Utils;

using static System.Reflection.Emit.OpCodes;

using TypeExtensions = AutoMapper.Utils.TypeExtensions;

namespace AutoMapper.Data.Configuration.Conventions
{
    public class DataRecordMemberConfiguration : ISourceToDestinationNameMapper
    {
        public MemberInfo GetSourceMember(TypeDetails sourceTypeDetails, Type destType, Type destMemberType, string nameToSearch)
        {
            if (TypeExtensions.IsAssignableFrom(typeof(IDataRecord), sourceTypeDetails.Type))
            {
                var returnType = destMemberType;
                // TODO: The return type really should be the type of the field in the reader.
                // TODO: Remove the previous comment. We're going to add value conversion functionality, so using the destination
                //       type here can be done safely.
                var method = new DynamicMethod($"Get{nameToSearch.Replace(".", string.Empty) }", returnType, new[] { typeof(IDataRecord) }, true);
                var il = method.GetILGenerator();

                EmitPropertyMapping(il, destType, destMemberType, nameToSearch);
                il.Emit(Ret);

                return method;
            }
            return null;
        }

        public void Merge(ISourceToDestinationNameMapper otherNamedMapper)
        {
        }

        private void EmitPropertyMapping(ILGenerator il, Type destType, Type destMemberType, string nameToSearch)
        {
            var returnType = destMemberType;
            var fieldValueLocal = il.DeclareLocal(typeof(object));
            var returnValueLocal = il.DeclareLocal(returnType);
            var tryGetValueMethod = DataReaderHelper.TryGetValueMethod;
            var dbNullElseLabel = il.DefineLabel();
            var dbNullLabel = il.DefineLabel();
            var endIfDbNullLabel = il.DefineLabel();
            var getDbNullValueField = DataReaderHelper.DbNullValueField;
            var underlyingType = Nullable.GetUnderlyingType(destMemberType);
            var isNullable = (underlyingType != null);

            // Call TryGetValue
            il.Emit(Ldarg_0);
            il.Emit(Ldstr, nameToSearch);
            il.Emit(Ldloca_S, fieldValueLocal);
            il.Emit(Call, tryGetValueMethod);

            if (IsNestedObject(destMemberType))
            {
                var ctor = destMemberType.GetConstructor(Type.EmptyTypes);

                if (ctor != null)
                {
                    MethodInfo setMethod;
                    var objValueLocal = il.DeclareLocal(destMemberType);
                    var refersToMethod = DataReaderHelper.RefersToMethod;
                    var elseRefersToLabel = il.DefineLabel();
                    var endIfRefersToLabel = il.DefineLabel();

                    // If there are non-null fields referring to the nested property...
                    il.Emit(Ldarg_0);
                    il.Emit(Ldstr, nameToSearch);
                    il.Emit(Call, refersToMethod);
                    il.Emit(Brfalse, elseRefersToLabel);
                    il.Emit(Newobj, ctor);
                    il.Emit(Stloc, objValueLocal);

                    foreach (PropertyInfo property in TypeExtensions.GetProperties(destMemberType))
                    {
                        if (property.CanWrite)
                        {
                            setMethod = TypeExtensions.GetSetMethod(property, true);
                            il.Emit(Ldloc, objValueLocal);
                            EmitPropertyMapping(il, destMemberType, property.PropertyType, $"{nameToSearch}.{property.Name}");
                            il.Emit(Callvirt, setMethod);
                        }
                    }
                    il.Emit(Br, endIfRefersToLabel);

                    // else do this...
                    il.MarkLabel(elseRefersToLabel);
                    il.Emit(Ldnull);
                    il.Emit(Stloc, objValueLocal);
                    il.MarkLabel(endIfRefersToLabel);

                    il.Emit(Ldloc, objValueLocal);
                    il.Emit(Stloc, fieldValueLocal);
                }
            }

            il.Emit(Pop);

            // Test if field value == null
            il.Emit(Ldloc, fieldValueLocal);
            il.Emit(Ldnull);
            il.Emit(Beq_S, dbNullLabel);

            // Test if field value == DBNull (skipped when source field does not exist)
            il.Emit(Ldloc, fieldValueLocal);
            il.Emit(Ldsfld, getDbNullValueField);
            il.Emit(Bne_Un_S, dbNullElseLabel);

            // If so...
            il.MarkLabel(dbNullLabel);
            il.Emit(Ldloca_S, returnValueLocal);
            il.Emit(Initobj, destMemberType);
            il.Emit(Br_S, endIfDbNullLabel);

            // else
            il.MarkLabel(dbNullElseLabel);
            il.Emit(Ldloc, fieldValueLocal);
            if (isNullable)
            {
                var nullableCtor = destMemberType.GetConstructor(new[] { underlyingType });
                il.Emit(Unbox_Any, underlyingType);
                il.Emit(Newobj, nullableCtor);
            }
            else
            {
            il.Emit(Unbox_Any, destMemberType);
            }
            il.Emit(Stloc, returnValueLocal);

            // end if
            il.MarkLabel(endIfDbNullLabel);

            // return
            il.Emit(Ldloc, returnValueLocal);
        }

        private bool IsNestedObject(Type type)
        {
            Type resolvedtype = Nullable.GetUnderlyingType(type) ?? type;

            return !resolvedtype.IsPrimitive();
        }
    }
}


text:
package com.challengercity.datura.server.saves;

import com.challengercity.datura.Item;

/**
 *
 * @author Ben Sergent V/ha1fBit
 */
public class DataPlayer {

    public String username;
    public int posX;
    public int posY;
    public String room;
    public Item[] inv;

    public DataPlayer() {
    }

    public DataPlayer(String username, int posX, int posY, String room, Item[] inv) {
        this.username = username;
        this.posX = posX;
        this.posY = posY;
        this.inv = inv;
        this.room = room;
    }

}


text:
**Table of Contents**

- [1 Development environment](#1-development-environment)
  - [eclipse](#eclipse)
    - [Test application project configuration](#test-application-project-configuration)
  - [intelliJ](#intellij)
    - [AspectJ activation](#aspectj-activation)
    - [Test Application Project configuration](#test-application-project-configuration-1)
    - [Version control](#version-control)
  - [Sign artifact for deploy phase](#sign-artifact-for-deploy-phase)
  - [Git key for release](#git-key-for-release)
  - [Maven configuration](#maven-configuration)
  - [Oracle library for core compile](#oracle-library-for-core-compile)
  - [Download drivers](#download-drivers)
- [2 Execution environment](#2-execution-environment)
  - [Installing Appium](#installing-appium)
  - [Configuring Android for tests](#configuring-android-for-tests)
  - [Configuring iOS for tests](#configuring-ios-for-tests)

### 1 Development environment ###

#### eclipse ####
SeleniumRobot is developed using eclipse IDE. Following plugins are mandatory:

- aspectj plugin (AJDT): use the dev version for aspectj 9 (the version used by maven) as older versions are not compatible with recent eclipse versions: http://download.eclipse.org/tools/ajdt/47_aj9/dev/update
- m2e plugin (maven)
- subeclipse (if using SVN for test application)
- TestNG (execute testNG tests)

SeleniumRobot needs Java 8 to be compiled.

It has also been tested with IntelliJ, however this requires the AspectJ compiler plugin which is not available in community version. A solution may be to compile seleniumRobot using maven.

Sometimes, eclipse does not get the same environment variables than the system. This can block mobile testing when it search for `node` installed on system. Simply add the path to node installation to `PATH` environment variable (e.g: `$PATH:/usr/local/bin`)

##### Test application project configuration #####
When developping test application on eclipse, `core` aspects must be woven by IDE when tests are launched from it.
Convert project to aspectJ project:
Right click on project -> Configure -> convert as AspectJ project

Therefore, right click on test application project -> properties -> Build path -> AspectJ Build -> Aspect Path.
Add either the `core` project if you have it in eclipse or add the `core-x.y.z.jar` file.

#### intelliJ ####
IntelliJ Ultimate can be used to develop test applications (or seleniumrobot project itself) but requires some configuration to activate AspectJ. TestNG plugins must also be installed

##### AspectJ activation #####
This step must be done only once to make IntelliJ work with aspectJ
- follow this guide to configure AspectJ for IntelliJ: [https://www.jetbrains.com/help/idea/aspectj.html](https://www.jetbrains.com/help/idea/aspectj.html)
- File -> Settings -> Plugins: add aspectJ plugins (search aspectJ in search box and tick all)

##### Test Application Project configuration #####
- Import the project (from eclipse or from maven)
- By default, project is not seen as a maven one if imported from eclipse, so, right click on project -> add framework -> select maven
- File -> Settings -> Build -> Compiler -> Java Compiler:

	- select Ajc compiler

	- configure path to aspectj compiler (aspectjtools.jar should be available somewhere if aspectJ activation has been done correctly)
	- choose the correct project bytecode version

	- add module and choose the correct per module bytecode version

	- select "delegate to javac"

- File -> Settings -> Build -> Required plugins: add "AspectJ support"
- File -> Project Structure -> Project: select the right SDK version and language level
- File -> Project Structure -> Modules: for the existing module

	- source tab: select the right language level

	- dependencies tab: remove eclipse specific dependencies (if project was previously imported from eclipse)

- File -> Project Structure -> Facects:
	- add aspectj for the current module

	- tick "post-compile weave mode"

	- add seleniumRobot:core dependency in aspect path (in case of a test application. If developing core, aspect path are selenium-api and remode-remote-driver)

##### Version control #####
IntelliJ generate a lot of files. If you want to share the project through version control, some files may be excluded.
See
[https://intellij-support.jetbrains.com/hc/en-us/articles/206544839-How-to-manage-projects-under-Version-Control-Systems](https://intellij-support.jetbrains.com/hc/en-us/articles/206544839-How-to-manage-projects-under-Version-Control-Systems)

As maven project, I remove `.idea/workspace.xml`, and all XML files under `.idea/libraries`

#### Sign artifact for deploy phase ####
OSS needs artifacts to be signed before being deployed
Therefore, generated a GPG key (it will ask a name and a password)

	gpg --gen-key

Copy key to a public key server

	gpg2 --keyserver hkp://pgp.mit.edu --send-key <key_name>

#### Git key for release ####
In order for maven to push tags on release, a key must be generated for SSH connection

    ssh-keygen -t rsa -C '<key name>'
Copy the generated public key to Github
Check connection (it should reply: You've successfuly authenticated)

    ssh git@github.com

#### Maven configuration ####
Maven 3 is required

Following configurations should be placed in user `settings.xml` file:

For GPG

```xml
	<profile>
		<id>gpg</id>
		<activation>
			<activeByDefault>true</activeByDefault>
		</activation>
      <properties>
        <gpg.executable>gpg2</gpg.executable>
        <gpg.passphrase><your key password></gpg.passphrase>
      </properties>
    </profile>
```

For Sonar analysis

```xml
	<profile>
		<id>sonar</id>
		<activation>
			<activeByDefault>true</activeByDefault>
		</activation>
		<properties>
			<sonar.host.url>http://server:9000</sonar.host.url>
		</properties>
	</profile>
```

For publishing artifacts to OSS Sonatype server

```xml
	<server>
      <id>ossrh</id>
      <username><your_user></username>
      <password><your_password></password>
    </server>
```

#### Oracle library for core compile ####

In order to compile core artifact, you must have the ojdb6.jar file
To have it, use the [https://repo.jenkins-ci.org](https://repo.jenkins-ci.org) repository (add the following in settings.xml)

```xml
	<mirrors>
	    <mirror>
	      <mirrorOf>*</mirrorOf>
	      <name>public</name>
	      <url>https://repo.jenkins-ci.org/public</url>
	      <id>public</id>
	    </mirror>
	  </mirrors>
```

#### Download drivers ####
From seleniumRobot 3.3.0, drivers are not provided anymore with source code, they are downloaded by a maven build (driver-download module)
To setup environment, execute `mvn clean compile` on project `driver-download`
If you are behind a corporate proxy, you should already have your settings.xml configured to use it.
/!\ you *MUST* have a configuration for http *and* https proxy. Else, download won't be possible

### 2 Execution environment ###
Execution environment needs at least Java 8. SeleniumRobot is compatible with Windows, Mac OS and Linux.
Depending on your tests, you should consider install:

- A browser
- Appium
- Android SDK / Genymotion to test on android simulator / emulator
- XCode (Mac OS X) to test on iPhone Simulator

#### Installing Appium ####
Either install it with .dmg on Mac or .exe on Windows or through npm `npm install -g appium`
Set `APPIUM_HOME` environment variable to point to path where appium has been installed:
- On Windows, using .exe, it's `<root path where Appium.exe is located>/resources/app`
- On Mac, using .dmg, it will be `/Applications/Appium.app/Contents/Resources/app`
- On any platform using npm installation, it will be the path where root `node_modules` folder has been created. This folder should contain an `appium` subfolder

On Linux/Mac systems, you can add `export APPIUM_HOME=<path to appium>` to the `.bash_profile` file in home directory

When running seleniumRobot from eclipse, it may not inherit the user environment variables, so set it in Run Configuration

#### Configuring Android for tests ####
- Install android SDK (the zip/command line tools version is enough) into `<ANDROID_SDK_ROOT>/cmdline-tools` : [https://developer.android.com/studio/index.html#downloads](https://developer.android.com/studio/index.html#downloads)
- Install additional components (This can be done through Android Studio)

```
	sdkmanager.bat --install extras;intel;Hardware_Accelerated_Execution_Manager
	sdkmanager.bat --install platform-tools
```

- Install new images (This can be done through Android Studio)

```
	sdkmanager.bat --install system-images;android-30;google_apis_playstore;x86
	sdkmanager.bat --install build-tools;30.0.2
	sdkmanager.bat --install platforms;android-30
```

- Create a virtual machine (activate graphic acceleration) and start it. You should be able to use your Android virtual device: `avdmanager create avd -n <avd_name> -k system-images;android-30;google_apis;x86 -c 200M -p D:\tmp\avd`
- Add `ANDROID_HOME` / `ANDROID_SDK_ROOT` environment variable pointing to root of android tools. This is the directory where all android tools are (This is the root folder containing 'platform-tools', 'system-images', ... folders)
- Start emulator (from Android Studio or command line): `emulator -avd <avd_name> -netdelay none -netspeed full -port 5560 -no-snapshot-load`

#### Configuring iOS for tests ####
Follow appium instruction here [http://appium.io/slate/en/master/?ruby#running-appium-on-mac-os-x] (http://appium.io/slate/en/master/?ruby#running-appium-on-mac-os-x)
As of June 2017, it asks for (simulator and real device):
- install xcode
- install xcode-select
- install homebrew (see homebrew website)
- `brew install carthage`

Check installation with appium-doctor:
- `npm install appium-doctor`
- in node_modules/appium-doctor, `node . --ios`

For use with a real iOS device, follow instructions here:
[http://appium.io/slate/en/master/?ruby#appium-on-real-ios-devices] (http://appium.io/slate/en/master/?ruby#appium-on-real-ios-devices)
[https://github.com/appium/appium-xcuitest-driver#real-devices] (https://github.com/appium/appium-xcuitest-driver#real-devices)
[https://github.com/appium/appium-xcuitest-driver/blob/master/docs/real-device-config.md] (https://github.com/appium/appium-xcuitest-driver/blob/master/docs/real-device-config.md)
For real device only:
- `brew install libimobiledevice`
- `npm install -g ios-deploy`

An Apple Developper account is also mandatory. Add your real devices to list of devices and assign it to a iOS development profile

Automatic configuration should be enough, but give a try to manual configuration if something goes wrong


text:
PART_NAME=linux

platform_check_image() {
	[ "$ARGC" -gt 1 ] && return 1

	case "$(get_magic_word "$1")" in
		# .trx files
		4844) return 0;;
		*)
			echo "Invalid image type. Please use only .trx files"
			return 1
		;;
	esac
}

# use default for platform_do_upgrade()


text:
<?php

/**
 * Catalog category attribute api
 *
 * @category   Mage
 * @package    Mage_Catalog
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Catalog_Model_Category_Attribute_Api extends Mage_Catalog_Model_Api_Resource
{
    public function __construct()
    {
        $this->_storeIdSessionField = 'category_store_id';
    }

    /**
     * Retrieve category attributes
     *
     * @return array
     */
    public function items()
    {
        $attributes = Mage::getModel('catalog/category')->getAttributes();
        $result = array();

        foreach ($attributes as $attribute) {
            /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
            if ($this->_isAllowedAttribute($attribute)) {
                if (!$attribute->getId() || $attribute->isScopeGlobal()) {
                    $scope = 'global';
                } elseif ($attribute->isScopeWebsite()) {
                    $scope = 'website';
                } else {
                    $scope = 'store';
                }

                $result[] = array(
                    'attribute_id' => $attribute->getId(),
                    'code'         => $attribute->getAttributeCode(),
                    'type'         => $attribute->getFrontendInput(),
                    'required'     => $attribute->getIsRequired(),
                    'scope'        => $scope
                );
            }
        }

        return $result;
    }

    /**
     * Retrieve category attribute options
     *
     * @param int|string $attributeId
     * @param string|int $store
     * @return array
     */
    public function options($attributeId, $store = null)
    {
        $attribute = Mage::getModel('catalog/category')
            ->setStoreId($this->_getStoreId($store))
            ->getResource()
            ->getAttribute($attributeId);

        if (!$attribute) {
            $this->_fault('not_exists');
        }

        $result = array();
        if ($attribute->usesSource()) {
            foreach ($attribute->getSource()->getAllOptions(false) as $optionId=>$optionValue) {
                if (is_array($optionValue)) {
                    $result[] = $optionValue;
                } else {
                    $result[] = array(
                        'value' => $optionId,
                        'label' => $optionValue
                    );
                }
            }
        }

        return $result;
    }
} // Class Mage_Catalog_Model_Category_Attribute_Api End


text:
title: Functional Reactive Programming in Ruby (Part 3)
layout: post
date: 2015-01-04 22:16
categories: frp ruby roguelikes
---

### Last time(s)
I talked about functional reactive programming and how I felt it would be useful in building a roguelike video game in Ruby.

If you're interested in the code, it's over [here](http://github.com/NaleagDeco/ykwya-roguelike). My apologies if it isn't as easily deployable as it should be.

Anyway, let's get to it <3

### Creating the world Functionally
Before we even think about input and output, let's think the functional programming. I wanted to have monsters, potions, gold, a player, and some terrain. I also want a status message to be displayed to the player. You'll want to look at the code for the full story, but here's the crux of my code for creating a new game.

{% highlight ruby %}
def create_game(player)

  terrain = build_dungeon
  unplaced_monsters = build_monsters
  unplaced_potions = build_potions
  unplaced_gold = build_gold

  # Shuffle to enable random placement
  empty_terrain = terrain.select { |coords, tile| tile.is_a? YKWYA::Empty }.keys.shuffle

  {
    player: player.clone,
    terrain: terrain,
    player_coords: empty_terrain.pop,
    stairway_coords: empty_terrain.pop,
    potions: empty_terrain.pop(unplaced_potions.size).zip(unplaced_potions),
    monsters: empty_terrain.pop(unplaced_monsters.size).zip(unplaced_monsters),
    gold: empty_terrain.pop(unplaced_gold.size).zip(unplaced_gold),
    status: 'Welcome to YKWYA!'
  }
end
{% endhighlight %}

Doesn't it look really weird? (It probably looks even weirder if you're comfortable in Ruby. Because I'm trying to minimize the amount of state changes I make, I'm not writing idiomatic Ruby. In many ways, my code reminds me of Scala, which attempts to put a functional-friendly syntax on top of Java but is basically just Java.

In essence, I'm
1. Creating the terrain, monsters, etc… Usually this was a list of generated objects and the coordinates they'd live on. In the case of the terrain, it was a giant hash table because I didn't feel like doing anything fancier.
2. Put everything into a giant hash table, and return it!

Pretty simple, eh? (The fun stuff is in how you generate everything :P)

You'll notice that I passed the player in as an argument and cloned it. I could have easily just created the player object inside, but I wanted my character creation logic to create the player first so users had choice of what kind of character they played.
It's actually kind of handy, because that `.clone` is important:  Since Ruby doesn't copy objects, I don't want to pass that original player b/c then I might accidentally modify it from multiple parts of my code. You'll see `.clone` all over my code, which is my fault for using a language not designed for this.

### Modifying the world functionally
Ultimately, every turn of my simple roguelike consists of two steps:

1. The player performs an act (gets potion or gold, attacks a player, moves, or doesn't move)
2. All monsters act (move around or attack.)

Like all complex software, this won't necessarily be super easy. You'll wind up having to juggle a bunch of different pieces of data that depend on each other, but the nice thing is that all of this data is collected into one object that you can pass around from function to function.

I've found that it's a lot easier if you break all of your operations into little chunks:

* Does the player move or attack
* What happens when the player picks up an item / attacks a monster
* Did the world change (a door opened, a trap activated)
* What do the monsters do?

I have no strong design basis for this, but I'd also recommend you use functions that generally take in the entire game state object and return one as well. This allows you to always have all the dependencies you need and you can then write all logic as a chain of calls that are always consistent at any step.

### Next time
We'll implement the reactive bit so you can type commands and see things!


text:
'use strict';

const catw        = require('catw');
const fs          = require('fs');
const chalk       = require('chalk');
const babel       = require('babel-core');
const path        = require('path');
const less        = require('less');
const concat      = require('concat');
const manifests   = {
  app: require('./manifests/app.js'),
  vendor: require('./manifests/vendor.js')
};

catw('client/**/*.js', function() {
  let src = './public/app.js';
  concat(manifests.app, src, function() {
    let result = babel.transform(fs.readFileSync(src).toString(), {
      'presets': ['es2015']
    });
    fs.writeFile(src, result.code, function(err) {
      if (err) {
        process.stdout.write(chalk.red(err));
      }
      else {
        process.stdout.write(chalk.yellow('App JS Updated \n'));
      }
    });
  });
});

catw('node_modules/arishill-mithril/distr/arishill-mithril.js', function() {
  let src = './public/vendor.js';
  concat(manifests.vendor, src, function() {
    process.stdout.write(chalk.yellow('Vendor JS Updated \n'));
  });
});

catw('client/**/*.less', function(stream) {
  let w = stream.pipe(fs.createWriteStream('public/bundle.less'));
  w.on('close', function () {
    let src = 'public/bundle.less';
    less.render(fs.readFileSync(src).toString(), {
        filename: path.resolve(src),
    }, function(e, output) {
      fs.writeFile('public/app.css', output.css, function(err) {
        if (err) { process.stdout.write(chalk.red(err)); }
        fs.unlinkSync(src);
        process.stdout.write(chalk.green('CSS Updated \n'));
      });
    });
  });
});

catw('node_modules/arishill-aesop/distr/aesop.min.css', function(stream) {
  let w = stream.pipe(fs.createWriteStream('public/aesop.css'));
  w.on('close', function (err) {
    if (err) {
      process.stdout.write(chalk.red(err));
    }
    else {
      process.stdout.write(chalk.magenta('Aesop Updated \n'));
    }
  });
});


text:
package nl.esciencecenter.xenon.jobs;

import nl.esciencecenter.xenon.XenonException;

/**
 * Signals that a unknown scheduler was provided.
 *
 * @author Jason Maassen <J.Maassen@esciencecenter.nl>
 * @version 1.0
 * @since 1.0
 */
public class NoSuchSchedulerException extends XenonException {

    private static final long serialVersionUID = 1L;

    public NoSuchSchedulerException(String adaptorName, String message, Throwable t) {
        super(adaptorName, message, t);
    }

    public NoSuchSchedulerException(String adaptorName, String message) {
        super(adaptorName, message);
    }
}


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright 2005-2007 the Seasar Foundation and the Others.            |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License");      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// |                                                                      |
// |     http://www.apache.org/licenses/LICENSE-2.0                       |
// |                                                                      |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an "AS IS" BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,                        |
// | either express or implied. See the License for the specific language |
// | governing permissions and limitations under the License.             |
// +----------------------------------------------------------------------+
// | Authors: nowel                                                       |
// +----------------------------------------------------------------------+
// $Id: $
//
/**
 * @author nowel
 * @package org.seasar.s2dao
 */
interface S2Dao_AnnotationReaderFactory {

    public function initialize();

    public function isInitialized();

    public function setUseCommentAnnotation($useComment);

    public function getUseCommentAnnotation();

    public function createDaoAnnotationReader(S2Container_BeanDesc $daoBeanDesc);

    public function createBeanAnnotationReader($beanClass);
}
?>


text:
set -e
echo ""
echo "*** Testing that the CDL examples produced same files as C examples."
echo "*** checking simple_xy.nc..."
cmp simple_xy.nc ../C/simple_xy.nc

echo "*** checking sfc_pres_temp.nc..."
cmp sfc_pres_temp.nc ../C/sfc_pres_temp.nc

echo "*** checking pres_temp_4D.nc..."
cmp pres_temp_4D.nc ../C/pres_temp_4D.nc

echo "*** All CDL example comparisons worked!"
exit 0


text:
class MessageContents {
public:
  MessageContents(void *data, size_t byteLength) :
    data_(data), byteLength_(byteLength) {}

  inline void *Data() const { return data_; }
  inline size_t ByteLength() const { return byteLength_; }

private:
  void *data_;
  size_t byteLength_;
};

#endif


text:
template <typename T>
struct Pair
{
	T first;
	T second;
};

template <typename Container>
Pair<typename Container::value_type> findMinMax(const Container& container)
{
	if (container.empty())
		return Pair<typename Container::value_type> {0, 0};

	Pair<typename Container::value_type> minMax {container[0], container[0]};

	for (size_t i = 1, containerSize = container.size(); i < containerSize; ++i)
	{
		const auto item = container[i];
		if (item < minMax.first)
			minMax.first = item;
		else if (item > minMax.second)
			minMax.second = item;
	}

	return minMax;
}


text:
package cn.edu.hdu.infosys.controller.news;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.hdu.infosys.service.news.INewsService;

/**
 *
 *
 *
 * @author    Pi Chen
 * @version   infosys V1.0.0, 2016年12月13日
 * @see
 * @since     infosys V1.0.0
 */
@RestController
@RequestMapping(value = "/news")
public class newsStatController
{

    @Autowired
    private INewsService newsService;
    /**
     *
     * 当前系统新闻每年总记录数
     *
     * @return
     */
    @RequestMapping(value = "/yearcount", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public ResponseEntity<Map<String, Object>> getYearCount(
        @RequestParam(value = "from", defaultValue = "2000") int from,
        @RequestParam(value = "to", defaultValue = "2016") int to)
    {
        Map<String, Object> data = new HashMap<String, Object>();

        for(int i = from; i<=to; i++){
            data.put(i+"", newsService.getYearCount(i));
        }
        return new ResponseEntity<Map<String, Object>>(data, HttpStatus.OK);
    }

    @RequestMapping(value = "/monthdata", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public ResponseEntity<Map<String, Object>> getByMonth(
        @RequestParam(value = "month", defaultValue = "2000-01") String month,
        @RequestParam(value = "offset", defaultValue = "0") long offset,
        @RequestParam(value = "limit", defaultValue = "10") long limit)
    {
        Map<String, Object> data = new HashMap<String, Object>();

        data.put("rstData", newsService.findByMonth(month,  offset,  limit));
        data.put("totalNum", newsService.getCount(month));
        return new ResponseEntity<Map<String, Object>>(data, HttpStatus.OK);
    }
}


text:
class CardsController < ApplicationController
	def index
	end

	def sent
		@user = User.first
		@cards = @user.user_cards
		render json: @cards.map { |card|
        {id: card.id,
        	recipient: User.find(card.recipient.id).username,
        greeting: card.card.greeting,
        message: card.card.message}
      }
	end

	def show
	end
end


text:
using namespace llvm;

namespace {
TEST(DIEHashTest, Data1) {
  DIEHash Hash;
  DIE Die(dwarf::DW_TAG_base_type);
  DIEInteger Size(4);
  Die.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Size);
  uint64_t MD5Res = Hash.computeTypeSignature(Die);
  ASSERT_EQ(0x1AFE116E83701108ULL, MD5Res);
}

// struct {};
TEST(DIEHashTest, TrivialType) {
  DIE Unnamed(dwarf::DW_TAG_structure_type);
  DIEInteger One(1);
  Unnamed.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

  // Line and file number are ignored.
  Unnamed.addValue(dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, &One);
  Unnamed.addValue(dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, &One);
  uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed);

  // The exact same hash GCC produces for this DIE.
  ASSERT_EQ(0x715305ce6cfd9ad1ULL, MD5Res);
}

// struct foo { };
TEST(DIEHashTest, NamedType) {
  DIE Foo(dwarf::DW_TAG_structure_type);
  DIEInteger One(1);
  DIEString FooStr(&One, "foo");
  Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);
  Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

  uint64_t MD5Res = DIEHash().computeTypeSignature(Foo);

  // The exact same hash GCC produces for this DIE.
  ASSERT_EQ(0xd566dbd2ca5265ffULL, MD5Res);
}

// namespace space { struct foo { }; }
TEST(DIEHashTest, NamespacedType) {
  DIE CU(dwarf::DW_TAG_compile_unit);

  auto Space = make_unique<DIE>(dwarf::DW_TAG_namespace);
  DIEInteger One(1);
  DIEString SpaceStr(&One, "space");
  Space->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &SpaceStr);
  // DW_AT_declaration is ignored.
  Space->addValue(dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, &One);
  // sibling?

  auto Foo = make_unique<DIE>(dwarf::DW_TAG_structure_type);
  DIEString FooStr(&One, "foo");
  Foo->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);
  Foo->addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

  DIE &N = *Foo;
  Space->addChild(std::move(Foo));
  CU.addChild(std::move(Space));

  uint64_t MD5Res = DIEHash().computeTypeSignature(N);

  // The exact same hash GCC produces for this DIE.
  ASSERT_EQ(0x7b80381fd17f1e33ULL, MD5Res);
}

// struct { int member; };
TEST(DIEHashTest, TypeWithMember) {
  DIE Unnamed(dwarf::DW_TAG_structure_type);
  DIEInteger Four(4);
  Unnamed.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Four);

  DIE Int(dwarf::DW_TAG_base_type);
  DIEString IntStr(&Four, "int");
  Int.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &IntStr);
  Int.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Four);
  DIEInteger Five(5);
  Int.addValue(dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, &Five);

  DIEEntry IntRef(Int);

  auto Member = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString MemberStr(&Four, "member");
  Member->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemberStr);
  DIEInteger Zero(0);
  Member->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1,
                   &Zero);
  Member->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &IntRef);

  Unnamed.addChild(std::move(Member));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed);

  ASSERT_EQ(0x5646aa436b7e07c6ULL, MD5Res);
}

// struct foo { int mem1, mem2; };
TEST(DIEHashTest, ReusedType) {
  DIE Unnamed(dwarf::DW_TAG_structure_type);
  DIEInteger Eight(8);
  Unnamed.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);

  DIEInteger Four(4);
  DIE Int(dwarf::DW_TAG_base_type);
  DIEString IntStr(&Four, "int");
  Int.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &IntStr);
  Int.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Four);
  DIEInteger Five(5);
  Int.addValue(dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, &Five);

  DIEEntry IntRef(Int);

  auto Mem1 = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString Mem1Str(&Four, "mem1");
  Mem1->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &Mem1Str);
  DIEInteger Zero(0);
  Mem1->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1,
                 &Zero);
  Mem1->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &IntRef);

  Unnamed.addChild(std::move(Mem1));

  auto Mem2 = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString Mem2Str(&Four, "mem2");
  Mem2->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &Mem2Str);
  Mem2->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1,
                 &Four);
  Mem2->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &IntRef);

  Unnamed.addChild(std::move(Mem2));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed);

  ASSERT_EQ(0x3a7dc3ed7b76b2f8ULL, MD5Res);
}

// struct foo { static foo f; };
TEST(DIEHashTest, RecursiveType) {
  DIE Foo(dwarf::DW_TAG_structure_type);
  DIEInteger One(1);
  Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);
  DIEString FooStr(&One, "foo");
  Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

  auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString MemStr(&One, "mem");
  Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
  DIEEntry FooRef(Foo);
  Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooRef);
  // DW_AT_external and DW_AT_declaration are ignored anyway, so skip them.

  Foo.addChild(std::move(Mem));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Foo);

  ASSERT_EQ(0x73d8b25aef227b06ULL, MD5Res);
}

// struct foo { foo *mem; };
TEST(DIEHashTest, Pointer) {
  DIE Foo(dwarf::DW_TAG_structure_type);
  DIEInteger Eight(8);
  Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  DIEString FooStr(&Eight, "foo");
  Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

  auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString MemStr(&Eight, "mem");
  Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
  DIEInteger Zero(0);
  Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, &Zero);

  DIE FooPtr(dwarf::DW_TAG_pointer_type);
  FooPtr.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  DIEEntry FooRef(Foo);
  FooPtr.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooRef);

  DIEEntry FooPtrRef(FooPtr);
  Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooPtrRef);

  Foo.addChild(std::move(Mem));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Foo);

  ASSERT_EQ(0x74ea73862e8708d2ULL, MD5Res);
}

// struct foo { foo &mem; };
TEST(DIEHashTest, Reference) {
  DIE Foo(dwarf::DW_TAG_structure_type);
  DIEInteger Eight(8);
  Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  DIEString FooStr(&Eight, "foo");
  Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

  auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString MemStr(&Eight, "mem");
  Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
  DIEInteger Zero(0);
  Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, &Zero);

  DIE FooRef(dwarf::DW_TAG_reference_type);
  FooRef.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  DIEEntry FooEntry(Foo);
  FooRef.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooEntry);

  DIE FooRefConst(dwarf::DW_TAG_const_type);
  DIEEntry FooRefRef(FooRef);
  FooRefConst.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooRefRef);

  DIEEntry FooRefConstRef(FooRefConst);
  Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooRefConstRef);

  Foo.addChild(std::move(Mem));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Foo);

  ASSERT_EQ(0xa0b15f467ad4525bULL, MD5Res);
}

// struct foo { foo &&mem; };
TEST(DIEHashTest, RValueReference) {
  DIE Foo(dwarf::DW_TAG_structure_type);
  DIEInteger Eight(8);
  Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  DIEString FooStr(&Eight, "foo");
  Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

  auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString MemStr(&Eight, "mem");
  Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
  DIEInteger Zero(0);
  Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, &Zero);

  DIE FooRef(dwarf::DW_TAG_rvalue_reference_type);
  FooRef.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  DIEEntry FooEntry(Foo);
  FooRef.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooEntry);

  DIE FooRefConst(dwarf::DW_TAG_const_type);
  DIEEntry FooRefRef(FooRef);
  FooRefConst.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooRefRef);

  DIEEntry FooRefConstRef(FooRefConst);
  Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooRefConstRef);

  Foo.addChild(std::move(Mem));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Foo);

  ASSERT_EQ(0xad211c8c3b31e57ULL, MD5Res);
}

// struct foo { foo foo::*mem; };
TEST(DIEHashTest, PtrToMember) {
  DIE Foo(dwarf::DW_TAG_structure_type);
  DIEInteger Eight(8);
  Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  DIEString FooStr(&Eight, "foo");
  Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

  auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString MemStr(&Eight, "mem");
  Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
  DIEInteger Zero(0);
  Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, &Zero);

  DIE PtrToFooMem(dwarf::DW_TAG_ptr_to_member_type);
  DIEEntry FooEntry(Foo);
  PtrToFooMem.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FooEntry);
  PtrToFooMem.addValue(dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
                       &FooEntry);

  DIEEntry PtrToFooMemRef(PtrToFooMem);
  Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &PtrToFooMemRef);

  Foo.addChild(std::move(Mem));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Foo);

  ASSERT_EQ(0x852e0c9ff7c04ebULL, MD5Res);
}

// Check that the hash for a pointer-to-member matches regardless of whether the
// pointed-to type is a declaration or a definition.
//
//   struct bar; // { };
//   struct foo { bar foo::*mem; };
TEST(DIEHashTest, PtrToMemberDeclDefMatch) {
  DIEInteger Zero(0);
  DIEInteger One(1);
  DIEInteger Eight(8);
  DIEString FooStr(&Eight, "foo");
  DIEString BarStr(&Eight, "bar");
  DIEString MemStr(&Eight, "mem");
  uint64_t MD5ResDecl;
  {
    DIE Bar(dwarf::DW_TAG_structure_type);
    Bar.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &BarStr);
    Bar.addValue(dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, &One);

    DIE Foo(dwarf::DW_TAG_structure_type);
    Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
    Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

    auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
    Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
    Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1,
                  &Zero);

    DIE PtrToFooMem(dwarf::DW_TAG_ptr_to_member_type);
    DIEEntry BarEntry(Bar);
    PtrToFooMem.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &BarEntry);
    DIEEntry FooEntry(Foo);
    PtrToFooMem.addValue(dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
                         &FooEntry);

    DIEEntry PtrToFooMemRef(PtrToFooMem);
    Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &PtrToFooMemRef);

    Foo.addChild(std::move(Mem));

    MD5ResDecl = DIEHash().computeTypeSignature(Foo);
  }
  uint64_t MD5ResDef;
  {
    DIE Bar(dwarf::DW_TAG_structure_type);
    Bar.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &BarStr);
    Bar.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

    DIE Foo(dwarf::DW_TAG_structure_type);
    Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
    Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

    auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
    Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
    Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1,
                  &Zero);

    DIE PtrToFooMem(dwarf::DW_TAG_ptr_to_member_type);
    DIEEntry BarEntry(Bar);
    PtrToFooMem.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &BarEntry);
    DIEEntry FooEntry(Foo);
    PtrToFooMem.addValue(dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
                         &FooEntry);

    DIEEntry PtrToFooMemRef(PtrToFooMem);
    Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &PtrToFooMemRef);

    Foo.addChild(std::move(Mem));

    MD5ResDef = DIEHash().computeTypeSignature(Foo);
  }
  ASSERT_EQ(MD5ResDef, MD5ResDecl);
}

// Check that the hash for a pointer-to-member matches regardless of whether the
// pointed-to type is a declaration or a definition.
//
//   struct bar; // { };
//   struct foo { bar bar::*mem; };
TEST(DIEHashTest, PtrToMemberDeclDefMisMatch) {
  DIEInteger Zero(0);
  DIEInteger One(1);
  DIEInteger Eight(8);
  DIEString FooStr(&Eight, "foo");
  DIEString BarStr(&Eight, "bar");
  DIEString MemStr(&Eight, "mem");
  uint64_t MD5ResDecl;
  {
    DIE Bar(dwarf::DW_TAG_structure_type);
    Bar.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &BarStr);
    Bar.addValue(dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, &One);

    DIE Foo(dwarf::DW_TAG_structure_type);
    Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
    Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

    auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
    Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
    Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1,
                  &Zero);

    DIE PtrToFooMem(dwarf::DW_TAG_ptr_to_member_type);
    DIEEntry BarEntry(Bar);
    PtrToFooMem.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &BarEntry);
    PtrToFooMem.addValue(dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
                         &BarEntry);

    DIEEntry PtrToFooMemRef(PtrToFooMem);
    Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &PtrToFooMemRef);

    Foo.addChild(std::move(Mem));

    MD5ResDecl = DIEHash().computeTypeSignature(Foo);
  }
  uint64_t MD5ResDef;
  {
    DIE Bar(dwarf::DW_TAG_structure_type);
    Bar.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &BarStr);
    Bar.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

    DIE Foo(dwarf::DW_TAG_structure_type);
    Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
    Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

    auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
    Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
    Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1,
                  &Zero);

    DIE PtrToFooMem(dwarf::DW_TAG_ptr_to_member_type);
    DIEEntry BarEntry(Bar);
    PtrToFooMem.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &BarEntry);
    PtrToFooMem.addValue(dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
                         &BarEntry);

    DIEEntry PtrToFooMemRef(PtrToFooMem);
    Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &PtrToFooMemRef);

    Foo.addChild(std::move(Mem));

    MD5ResDef = DIEHash().computeTypeSignature(Foo);
  }
  // FIXME: This seems to be a bug in the DWARF type hashing specification that
  // only uses the brief name hashing for types referenced via DW_AT_type. In
  // this case the type is referenced via DW_AT_containing_type and full hashing
  // causes a hash to differ when the containing type is a declaration in one TU
  // and a definition in another.
  ASSERT_NE(MD5ResDef, MD5ResDecl);
}

// struct { } a;
// struct foo { decltype(a) mem; };
TEST(DIEHashTest, RefUnnamedType) {
  DIEInteger Zero(0);
  DIEInteger One(1);
  DIEInteger Eight(8);
  DIEString FooStr(&Zero, "foo");
  DIEString MemStr(&Zero, "mem");

  DIE Unnamed(dwarf::DW_TAG_structure_type);
  Unnamed.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

  DIE Foo(dwarf::DW_TAG_structure_type);
  Foo.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  Foo.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);

  auto Mem = make_unique<DIE>(dwarf::DW_TAG_member);
  Mem->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &MemStr);
  Mem->addValue(dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, &Zero);

  DIE UnnamedPtr(dwarf::DW_TAG_pointer_type);
  UnnamedPtr.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Eight);
  DIEEntry UnnamedRef(Unnamed);
  UnnamedPtr.addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &UnnamedRef);

  DIEEntry UnnamedPtrRef(UnnamedPtr);
  Mem->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &UnnamedPtrRef);

  Foo.addChild(std::move(Mem));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Foo);

  ASSERT_EQ(0x954e026f01c02529ULL, MD5Res);
}

// struct { struct foo { }; };
TEST(DIEHashTest, NestedType) {
  DIE Unnamed(dwarf::DW_TAG_structure_type);
  DIEInteger One(1);
  Unnamed.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

  auto Foo = make_unique<DIE>(dwarf::DW_TAG_structure_type);
  DIEString FooStr(&One, "foo");
  Foo->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FooStr);
  Foo->addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

  Unnamed.addChild(std::move(Foo));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed);

  // The exact same hash GCC produces for this DIE.
  ASSERT_EQ(0xde8a3b7b43807f4aULL, MD5Res);
}

// struct { static void func(); };
TEST(DIEHashTest, MemberFunc) {
  DIE Unnamed(dwarf::DW_TAG_structure_type);
  DIEInteger One(1);
  Unnamed.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);

  auto Func = make_unique<DIE>(dwarf::DW_TAG_subprogram);
  DIEString FuncStr(&One, "func");
  Func->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FuncStr);

  Unnamed.addChild(std::move(Func));

  uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed);

  // The exact same hash GCC produces for this DIE.
  ASSERT_EQ(0xd36a1b6dfb604ba0ULL, MD5Res);
}

// struct A {
//   static void func();
// };
TEST(DIEHashTest, MemberFuncFlag) {
  DIE A(dwarf::DW_TAG_structure_type);
  DIEInteger One(1);
  DIEString AStr(&One, "A");
  A.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &AStr);
  A.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);
  A.addValue(dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, &One);
  A.addValue(dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, &One);

  auto Func = make_unique<DIE>(dwarf::DW_TAG_subprogram);
  DIEString FuncStr(&One, "func");
  DIEString FuncLinkage(&One, "_ZN1A4funcEv");
  DIEInteger Two(2);
  Func->addValue(dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, &One);
  Func->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FuncStr);
  Func->addValue(dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, &One);
  Func->addValue(dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, &Two);
  Func->addValue(dwarf::DW_AT_linkage_name, dwarf::DW_FORM_strp, &FuncLinkage);
  Func->addValue(dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, &One);

  A.addChild(std::move(Func));

  uint64_t MD5Res = DIEHash().computeTypeSignature(A);

  // The exact same hash GCC produces for this DIE.
  ASSERT_EQ(0x8f78211ddce3df10ULL, MD5Res);
}

// Derived from:
// struct A {
//   const static int PI = -3;
// };
// A a;
TEST(DIEHashTest, MemberSdata) {
  DIE A(dwarf::DW_TAG_structure_type);
  DIEInteger One(1);
  DIEString AStr(&One, "A");
  A.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &AStr);
  A.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);
  A.addValue(dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, &One);
  A.addValue(dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, &One);

  DIEInteger Four(4);
  DIEInteger Five(5);
  DIEString FStr(&One, "int");
  DIE IntTyDIE(dwarf::DW_TAG_base_type);
  IntTyDIE.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Four);
  IntTyDIE.addValue(dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, &Five);
  IntTyDIE.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FStr);

  DIEEntry IntTy(IntTyDIE);
  auto PITyDIE = make_unique<DIE>(dwarf::DW_TAG_const_type);
  PITyDIE->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &IntTy);

  DIEEntry PITy(*PITyDIE);
  auto PI = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString PIStr(&One, "PI");
  DIEInteger Two(2);
  DIEInteger NegThree(-3);
  PI->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &PIStr);
  PI->addValue(dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, &One);
  PI->addValue(dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, &Two);
  PI->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &PITy);
  PI->addValue(dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, &One);
  PI->addValue(dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, &One);
  PI->addValue(dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, &NegThree);

  A.addChild(std::move(PI));

  uint64_t MD5Res = DIEHash().computeTypeSignature(A);
  ASSERT_EQ(0x9a216000dd3788a7ULL, MD5Res);
}

// Derived from:
// struct A {
//   const static float PI = 3.14;
// };
// A a;
TEST(DIEHashTest, MemberBlock) {
  DIE A(dwarf::DW_TAG_structure_type);
  DIEInteger One(1);
  DIEString AStr(&One, "A");
  A.addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &AStr);
  A.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &One);
  A.addValue(dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, &One);
  A.addValue(dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, &One);

  DIEInteger Four(4);
  DIEString FStr(&One, "float");
  auto FloatTyDIE = make_unique<DIE>(dwarf::DW_TAG_base_type);
  FloatTyDIE->addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Four);
  FloatTyDIE->addValue(dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, &Four);
  FloatTyDIE->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &FStr);

  DIEEntry FloatTy(*FloatTyDIE);
  auto PITyDIE = make_unique<DIE>(dwarf::DW_TAG_const_type);
  PITyDIE->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &FloatTy);

  DIEEntry PITy(*PITyDIE);
  auto PI = make_unique<DIE>(dwarf::DW_TAG_member);
  DIEString PIStr(&One, "PI");
  DIEInteger Two(2);
  PI->addValue(dwarf::DW_AT_name, dwarf::DW_FORM_strp, &PIStr);
  PI->addValue(dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, &One);
  PI->addValue(dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, &Two);
  PI->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, &PITy);
  PI->addValue(dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, &One);
  PI->addValue(dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, &One);

  DIEBlock PIBlock;
  DIEInteger Blk1(0xc3);
  DIEInteger Blk2(0xf5);
  DIEInteger Blk3(0x48);
  DIEInteger Blk4(0x40);

  PIBlock.addValue((dwarf::Attribute)0, dwarf::DW_FORM_data1, &Blk1);
  PIBlock.addValue((dwarf::Attribute)0, dwarf::DW_FORM_data1, &Blk2);
  PIBlock.addValue((dwarf::Attribute)0, dwarf::DW_FORM_data1, &Blk3);
  PIBlock.addValue((dwarf::Attribute)0, dwarf::DW_FORM_data1, &Blk4);

  PI->addValue(dwarf::DW_AT_const_value, dwarf::DW_FORM_block1, &PIBlock);

  A.addChild(std::move(PI));

  uint64_t MD5Res = DIEHash().computeTypeSignature(A);
  ASSERT_EQ(0x493af53ad3d3f651ULL, MD5Res);
}
}


text:
package archive

import (
	"context"

	"go-common/app/admin/main/feed/conf"
	"go-common/app/service/main/archive/api"
	arcrpc "go-common/app/service/main/archive/api/gorpc"
	"go-common/app/service/main/archive/model/archive"
	"go-common/library/log"
)

// Dao is archive dao.
type Dao struct {
	// rpc
	arcRPC *arcrpc.Service2
}

// New account dao.
func New(c *conf.Config) (d *Dao) {
	d = &Dao{
		arcRPC: arcrpc.New2(c.ArchiveRPC),
	}
	return
}

// Archive3 get archive.
func (d *Dao) Archive3(c context.Context, aid int64) (a *api.Arc, err error) {
	arg := &archive.ArgAid2{Aid: aid}
	if a, err = d.arcRPC.Archive3(c, arg); err != nil {
		log.Error("d.arcRPC.Archive3(%v) error(%+v)", arg, err)
		return
	}
	return
}


text:
Handy utility methods I use in my Ruby code (and wheels I've reinvented)

## Installation

Add this line to your application's Gemfile:

    gem 'ktutils'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install ktutils

## Usage

To pull everything into your code

    require 'ktutils'

You probably don't want to pull in everything at once, you'll only need one
or two modules/classes at a time.

    require 'ktutils/os'

## Utilities

### OS Detection

Determine if you're running on windows, linux or mac. Now supports jruby!

    require 'ktutils/os'

### Template Parsing

Brute force template parsing.

    require 'ktutils/parse_template'

## TODOs

+ TESTS!

## Contributing

1. Fork it ( https://github.com/[my-github-username]/ktutils/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Issue CLOSED-STREAM-OPERATIONS:ALLOW-INQUIRY Summary</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="../Issues/iss052.html">
<LINK REL=UP HREF="../Issues/Issues-Alphabetical.html">
<LINK REL=NEXT HREF="../Issues/iss054.html">

Issue CLOSED-STREAM-OPERATIONS:ALLOW-INQUIRY Summary

These passages are relevant to issue <TT>CLOSED-STREAM-OPERATIONS:ALLOW-INQUIRY</TT>:

File Operations on Open and Closed Streams

Function CLOSE

Function COMPILE-FILE-PATHNAME

Function LOGICAL-PATHNAME

Function MERGE-PATHNAMES

Function PATHNAME

Function PROBE-FILE

Function STREAMP

Function TRANSLATE-LOGICAL-PATHNAME

Function TRUENAME

Glossary Section ``S''

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.


text:
package de.longri.cachebox3.settings;

import de.longri.cachebox3.gui.menu.QuickAction;
import de.longri.cachebox3.settings.types.SettingsList;

/**
 * Created by Longri on 12.01.2017.
 */
public abstract class Settings_Const {

    public static final SettingsList settingsList = new SettingsList();

    protected static final de.longri.cachebox3.settings.types.SettingMode DEVELOPER = de.longri.cachebox3.settings.types.SettingMode.DEVELOPER;
    protected static final de.longri.cachebox3.settings.types.SettingMode NORMAL = de.longri.cachebox3.settings.types.SettingMode.Normal;
    protected static final de.longri.cachebox3.settings.types.SettingMode EXPERT = de.longri.cachebox3.settings.types.SettingMode.Expert;
    protected static final de.longri.cachebox3.settings.types.SettingMode NEVER = de.longri.cachebox3.settings.types.SettingMode.Never;

    protected static final Integer Level[] = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21};
    protected static final Integer CrossLevel[] = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21};

    protected static final String FOUND = "
###finds##, ##time##, Found it with Cachebox!";
    protected static final String ATTENDED = "
###finds##, ##time##, Have been there!";
    protected static final String WEBCAM = "
###finds##, ##time##, Photo taken!";
    protected static final String DNF = "
##time##. Could not find the cache!";
    protected static final String LOG = "Logged it with Cachebox!";
    protected static final String DISCOVERED = "
 ##time##, Discovered it with Cachebox!";
    protected static final String VISITED = "
 ##time##, Visited it with Cachebox!";
    protected static final String DROPPED = "
 ##time##, Dropped off with Cachebox!";
    protected static final String PICKED = "
 ##time##, Picked it with Cachebox!";
    protected static final String GRABBED = "
 ##time##, Grabbed it with Cachebox!";

    protected static final Integer[] approach = new Integer[]{0, 2, 10, 25, 50, 100, 200, 500, 1000};
    public static final Integer[] trackDistanceArray = new Integer[]{1, 3, 5, 10, 20};
    protected static final String DefaultQuickButtons = QuickAction.WaypointView.ordinal() + ","
            + QuickAction.Hint.ordinal() + ","
            + QuickAction.Spoiler.ordinal() + ","
            + QuickAction.QuickDrafts.ordinal() + ","
            + QuickAction.AutoResort.ordinal() + ","
            + QuickAction.NotesView.ordinal() + ","
            + QuickAction.LogView.ordinal() + ","
            + QuickAction.Solver.ordinal() + ","
            ;

}


text:
<!DOCTYPE html>

    <title>GDG Korea WebTech - WebRTC Demo</title>

        Local
        Remote

                <input type="text" id="myName" style="width:100px;">
                <input type="button" id="cmdBtn" style="width:60px;">


text:
package org.apache.camel.component.jcache.policy;

import java.net.URI;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;

import com.hazelcast.instance.HazelcastInstanceFactory;
import org.apache.camel.BindToRegistry;
import org.apache.camel.builder.RouteBuilder;
import org.junit.After;
import org.junit.Test;

//This test requires a registered CacheManager, but the others do not.
public class CacheManagerFromRegistryTest extends JCachePolicyTestBase {

    @BindToRegistry("cachemanager-hzsecond")
    private CacheManager cc = Caching.getCachingProvider().getCacheManager(URI.create("hzsecond"), null);

    // Register cacheManager in CamelContext. Set cacheName
    @Test
    public void testCacheManagerFromContext() throws Exception {
        final String key = randomString();

        // Send exchange
        Object responseBody = this.template().requestBody("direct:policy-context-manager", key);

        // Verify the cacheManager "hzsecond" registered in the CamelContext was
        // used
        assertNull(lookupCache("contextCacheManager"));
        CacheManager cacheManager = Caching.getCachingProvider().getCacheManager(URI.create("hzsecond"), null);
        Cache cache = cacheManager.getCache("contextCacheManager");

        assertEquals(generateValue(key), cache.get(key));
        assertEquals(generateValue(key), responseBody);
        assertEquals(1, getMockEndpoint("mock:value").getExchanges().size());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                JCachePolicy jcachePolicy = new JCachePolicy();
                jcachePolicy.setCacheName("contextCacheManager");

                from("direct:policy-context-manager").policy(jcachePolicy).to("mock:value");
            }
        };
    }

    @Override
    @After
    public void after() {
        super.after();
        CacheManager cacheManager = Caching.getCachingProvider().getCacheManager(URI.create("hzsecond"), null);
        cacheManager.getCacheNames().forEach(s -> cacheManager.destroyCache(s));
        Caching.getCachingProvider().close(URI.create("hzsecond"), null);

        // We need to shutdown the second instance using the Hazelcast api.
        // close(URI,ClassLoader) doesn't do that.
        HazelcastInstanceFactory.getHazelcastInstance("hzsecond").shutdown();
    }

}


text:
'use strict';

// Runs `npm install` in cwd

var Promise = require('../ext/promise');
var chalk   = require('chalk');
var Task    = require('../models/task');

module.exports = Task.extend({
  // The command to run: can be 'install' or 'uninstall'
  command: '',
  // Message to send to ui.startProgress
  startProgressMessage: '',
  // Message to send to ui.writeLine on completion
  completionMessage: '',

  init: function() {
    this.npm = this.npm || require('npm');
  },
  // Options: Boolean verbose
  run: function(options) {
    this.ui.startProgress(chalk.green(this.startProgressMessage), chalk.green('.'));

    var npmOptions = {
      loglevel: options.verbose ? 'verbose' : 'error',
      logstream: this.ui.outputStream,
      color: 'always',
      'save-dev': !!options['save-dev'],
      'save-exact': !!options['save-exact']
    };
    var packages = options.packages || [];

    // npm otherwise is otherwise noisy, already submitted PR for npm to fix
    // misplaced console.log
    this.disableLogger();

    var load = Promise.denodeify(this.npm.load);

    return load(npmOptions)
      .then(function() {
        // if install is denodeified outside load.then(),
        // it throws "Call npm.load(config, cb) before using this command."
        var install = Promise.denodeify(this.npm.commands[this.command]);

        return install(packages);
      }.bind(this))
      .finally(this.finally.bind(this))
      .then(this.announceCompletion.bind(this));
  },

  announceCompletion: function() {
    this.ui.writeLine(chalk.green(this.completionMessage));
  },

  finally: function() {
    this.ui.stopProgress();
    this.restoreLogger();
  },

  disableLogger: function() {
    this.oldLog = console.log;
    console.log = function() {};
  },

  restoreLogger: function() {
    console.log = this.oldLog; // Hack, see above
  }
});


text:
==========================================================
 Event Loop Debugging Utils - ``kombu.asynchronous.debug``
==========================================================

.. contents::
    :local:
.. currentmodule:: kombu.asynchronous.debug

.. automodule:: kombu.asynchronous.debug
    :members:
    :undoc-members:


text:
package com.baidubce.services.moladb.model;

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
import com.baidubce.auth.BceCredentials;
import com.baidubce.model.AbstractBceRequest;
import com.baidubce.services.moladb.MolaDbConstants;
import com.baidubce.util.JsonUtils;

/**
 * Represents the input of a BatchGetItem operation.
 */
public class BatchGetItemRequest extends AbstractBceRequest {
    private Map<String, KeysAndAttributes> requestItems;

    /**
     * Constructs a new BatchGetItemRequest object.
     * Callers should use the setter or fluent setter (with...) methods to
     * initialize any additional object members.
     */
    public BatchGetItemRequest() {
    }

    /**
     * Set the request items for BatchGetItem operation.
     *
     * @param requestItems The request items for BatchGetItem operation.
     */
    public void setRequestItems(
            Map<String, KeysAndAttributes> requestItems) {
        this.requestItems = requestItems;
    }

    /**
     * Set the request items for BatchGetItem operation.
     *
     * @param reqItems The request items for BatchGetItem operation.
     * @return Returns a reference to the object so that method calls can be chained together.
     */
    public BatchGetItemRequest withRequestItems(
            Map<String, KeysAndAttributes> reqItems) {
        this.setRequestItems(reqItems);
        return this;
    }

    /**
     * Get the request Items set in this BatchGetItem operation.
     *
     * @return Returns the map of attributes with name and key.
     */
    public Map<String, KeysAndAttributes> getRequestItems() {
        return this.requestItems;
    }

    /**
     * Return a string representation of request information.
     *
     * @return A string representation of request information.
     */
    public String toString() {
        Map<String, Object> jsonObj = new HashMap<String, Object>();
        Map<String, Object> reqItems = new HashMap<String, Object>();
        Iterator<Entry<String, KeysAndAttributes>> iter = this.requestItems.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, KeysAndAttributes> entry = iter.next();
            String tableName = (String) entry.getKey();
            KeysAndAttributes val = (KeysAndAttributes) entry.getValue();
            reqItems.put(tableName, val.toJsonObj());
        }
        jsonObj.put(MolaDbConstants.JSON_REQUEST_ITEMS, reqItems);
        return JsonUtils.toJsonString(jsonObj);
    }

    @Override
    public BatchGetItemRequest withRequestCredentials(BceCredentials credentials) {
        this.setRequestCredentials(credentials);
        return this;
    }
}


text:
Deploy PrivateModule {
    By AzureAutomationModule {
        FromSource "https://pkgs.dev.azure.com/ORGANIZATION_NAME/PROJECT_NAME/_packaging/FEED_NAME/nuget/v2"
        To "AAName"
        WithOptions @{
            SourceIsAbsolute   = $true
            ModuleName         = "PrivateModule"
            # ModuleVersion     = '0.0.4'
            Force              = $true
            ResourceGroupName  = "AAResourceGroupName"
            StorageAccountName = "aadeploymentstor"
            Credential         = $script:credential
        }
        WithPreScript {
            $user = 'user@contoso.com'
            $password = ConvertTo-SecureString 'PAT_TOKEN' -AsPlainText -Force # PAT with permissions to read from the Artifacts feed
            $script:credential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList $user, $password
        }
    }
}


text:
<?xml version="1.0" ?>

<Node
	type="label"
	bhNodeID="idColorEmptyList"
	name="ColorEmptyList"
	nodeStyleID="ColorEmptyList.json"
	nodeInputControl="Label.fxml"
	onMovedFromChildToWS="onLiteralMovedToWS.js"
	initString="[...]">
</Node>


text:
/* eslint-env jest */
import React from 'react';
import { mount } from 'enzyme';
import omitProps from '../omitProps';

test('omitProps removes the some props of the new component', () => {
  const BaseComponent = jest.fn(() => null);
  const NewComponent = omitProps(['foo'])(BaseComponent);
  mount(<NewComponent foo={1} bar={1} />);
  expect(BaseComponent.mock.calls[0][0]).toEqual({ bar: 1 });
});


text:
var tape = require("tape"),
    sort = require("..");

function randomSort() {
    return (Math.random() * 2) - 1;
}

function createArray(count) {
    var array = new Array(count);

    while (count--) {
        array[count] = count;
    }

    return array;
}

function createCharArray(count) {
    var array = new Array(count);

    while (count--) {
        array[count] = String.fromCharCode(count);
    }

    return array;
}

tape("sort(array: Array, sortFunction: Function) Integers", function(assert) {
    var array = createArray(1000).sort(randomSort);
    assert.deepEqual(sort(array, null), createArray(1000), "should perform blocking sort on Integers");
    assert.end();
});
tape("sort(array: Array, sortFunction: Function, callback: Function) Integers", function(assert) {
    var array = createArray(1000).sort(randomSort);

    sort(array, null, function(array) {
        assert.deepEqual(array, createArray(1000), "should perform non blocking sort on Integers");
        assert.end();
    });
});

tape("sort(array: Array, sortFunction: Function) Characters", function(assert) {
    var array = createCharArray(255).sort(randomSort);
    assert.deepEqual(sort(array, null), createCharArray(255), "should perform blocking sort on Characters");
    assert.end();
});
tape("sort(array: Array, sortFunction: Function, callback: Function) Characters", function(assert) {
    var array = createCharArray(255).sort(randomSort);

    sort(array, null, function(array) {
        assert.deepEqual(array, createCharArray(255), "should perform non blocking sort on Characters");
        assert.end();
    });
});