text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Network.Models;

namespace Microsoft.Azure.Management.Network
{
    /// <summary>
    /// The Network Resource Provider API includes operations for managing the
    /// Virtual network Gateway for your subscription.
    /// </summary>
    public partial interface IVirtualNetworkGatewayConnectionOperations
    {
        /// <summary>
        /// The Put VirtualNetworkGatewayConnection operation creates/updates a
        /// virtual network gateway connection in the specified resource group
        /// through Network resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The name of the virtual network gateway conenction.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Begin Create or update Virtual Network
        /// Gateway connection operation through Network resource provider.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for CreateOrUpdateVirtualNetworkGatewayConnection Api
        /// servive call
        /// </returns>
        Task<VirtualNetworkGatewayConnectionPutResponse> BeginCreateOrUpdatingAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, CancellationToken cancellationToken);

        /// <summary>
        /// The Delete VirtualNetworkGatewayConnection operation deletes the
        /// specifed virtual network Gateway connection through Network
        /// resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The name of the virtual network gateway connection.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// If the resource provide needs to return an error to any operation,
        /// it should return the appropriate HTTP error code and a message
        /// body as can be seen below.The message should be localized per the
        /// Accept-Language header specified in the original request such
        /// thatit could be directly be exposed to users
        /// </returns>
        Task<UpdateOperationResponse> BeginDeletingAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken);

        /// <summary>
        /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets
        /// the virtual network gateway connection shared key for passed
        /// virtual network gateway connection in the specified resource group
        /// through Network resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The virtual network gateway connection reset shared key Name.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Begin Reset Virtual Network Gateway
        /// connection shared key operation through Network resource provider.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for PutVirtualNetworkGatewayConnectionResetSharedKey Api
        /// servive call
        /// </returns>
        Task<ConnectionResetSharedKeyPutResponse> BeginResetSharedKeyAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken);

        /// <summary>
        /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
        /// virtual network gateway connection shared key for passed virtual
        /// network gateway connection in the specified resource group through
        /// Network resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The virtual network gateway connection name.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Begin Set Virtual Network Gateway
        /// conection Shared key operation throughNetwork resource provider.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for PutVirtualNetworkGatewayConnectionSharedKey Api
        /// servive call
        /// </returns>
        Task<ConnectionSharedKeyPutResponse> BeginSetSharedKeyAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken);

        /// <summary>
        /// The CreateOrUpdate Virtual network Gateway connection creates a new
        /// or updates an existing virtualnetwork gateway connection through
        /// Network resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The name of the virtual network gateway conenction.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Begin Create or update Virtual Network
        /// Gateway connection operation through Network resource provider.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request and error information regarding
        /// the failure.
        /// </returns>
        Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, CancellationToken cancellationToken);

        /// <summary>
        /// The Delete VirtualNetworkGatewayConnection operation deletes the
        /// specifed virtual network Gateway connection through Network
        /// resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The name of the virtual network gateway connection.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken);

        /// <summary>
        /// The Get VirtualNetworkGatewayConnection operation retrieves
        /// information about the specified virtual network gateway connection
        /// through Network resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The name of the virtual network gateway connection.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for GetVitualNetworkGatewayConnection Api servive call.
        /// </returns>
        Task<VirtualNetworkGatewayConnectionGetResponse> GetAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken);

        /// <summary>
        /// The Get VirtualNetworkGatewayConnectionSharedKey operation
        /// retrieves information about the specified virtual network gateway
        /// connection shared key through Network resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='connectionSharedKeyName'>
        /// The virtual network gateway connection shared key name.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for CheckConnectionSharedKey Api servive call
        /// </returns>
        Task<ConnectionSharedKeyResponse> GetSharedKeyAsync(string resourceGroupName, string connectionSharedKeyName, CancellationToken cancellationToken);

        /// <summary>
        /// The List VirtualNetworkGatewayConnections operation retrieves all
        /// the virtual network gateways connections created.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for ListVirtualNetworkGatewayConnections Api service call
        /// </returns>
        Task<VirtualNetworkGatewayConnectionListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken);

        /// <summary>
        /// The Reset VirtualNetworkGatewayConnectionSharedKey operation resets
        /// the virtual network gateway connection shared key for passed
        /// virtual network gateway connection in the specified resource group
        /// through Network resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The virtual network gateway connection name.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Begin Reset Virtual Network Gateway
        /// connection shared key operation through Network resource provider.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request and error information regarding
        /// the failure.
        /// </returns>
        Task<AzureAsyncOperationResponse> ResetSharedKeyAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken);

        /// <summary>
        /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the
        /// virtual network gateway connection shared key for passed virtual
        /// network gateway connection in the specified resource group through
        /// Network resource provider.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='virtualNetworkGatewayConnectionName'>
        /// The virtual network gateway connection name.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Begin Create or update Virtual Network
        /// Gateway connection shared key operation through Network resource
        /// provider.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request and error information regarding
        /// the failure.
        /// </returns>
        Task<AzureAsyncOperationResponse> SetSharedKeyAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken);
    }
}


text:
package com.jun.elephant.ui.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;

import com.jun.elephant.R;
import com.jun.elephant.common.BaseWebViewActivity;
import com.jun.elephant.global.Constants;
import com.jun.elephant.ui.widget.MultiStateView;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Jun on 2016/4/18.
 */
public class WebViewActivity extends BaseWebViewActivity {

    @BindView(R.id.toolBar)
    Toolbar mToolBar;
    @BindView(R.id.webView)
    WebView mWebView;
    @BindView(R.id.multiStateView)
    MultiStateView mMultiStateView;

    private String mWebUrl, mTitle;

    public static Intent newIntent(Context context, String title, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(Constants.Key.WEB_TITLE, title);
        intent.putExtra(Constants.Key.WEB_URL, url);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        mWebUrl = getIntent().getStringExtra(Constants.Key.WEB_URL);
        mTitle = getIntent().getStringExtra(Constants.Key.WEB_TITLE);
    }

    @Override
    public void initView() {
        super.initView();
        mToolBar.setTitle(mTitle);
    }

    @Override
    public void initLoad() {
        super.initLoad();

        mWebView.setWebViewClient(new WebAppClient(this, mMultiStateView, mWebView));
        mWebView.loadUrl(mWebUrl, getAuth());
    }

    @Override
    public void initListener() {
        super.initListener();
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void finish() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.finish();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
public class FieldVsOuter2 {
  public final String field = "xxx";

  private class Inner {
    public final String field = "yyy";

    public void foo() {
      System.out.println(<caret>field);
    }
  }
}


text:
package org.anddev.andengine.level.util.constants;

public interface LevelConstants
{
    public static final String TAG_LEVEL = "level";
    public static final String TAG_LEVEL_ATTRIBUTE_HEIGHT = "height";
    public static final String TAG_LEVEL_ATTRIBUTE_NAME = "name";
    public static final String TAG_LEVEL_ATTRIBUTE_UID = "uid";
    public static final String TAG_LEVEL_ATTRIBUTE_WIDTH = "width";
}


text:
"""
Filename:     plot_optical_depth.py
Author:       Damien Irving, irving.damien@gmail.com
Description:

"""

# Import general Python modules

import sys, os, pdb
import argparse
import matplotlib.pyplot as plt
import iris
import iris.plot as iplt
import seaborn
seaborn.set_context('talk')

# Import my modules

cwd = os.getcwd()
repo_dir = '/'
for directory in cwd.split('/')[1:]:
    repo_dir = os.path.join(repo_dir, directory)
    if directory == 'ocean-analysis':
        break

modules_dir = os.path.join(repo_dir, 'modules')
sys.path.append(modules_dir)

try:
    import general_io as gio
except ImportError:
    raise ImportError('Must run this script from anywhere within the ocean-analysis git repo')

# Define functions

experiment_colors = {}
experiment_colors['historical'] = 'green'
experiment_colors['historicalAA'] = 'blue'
experiment_colors['historicalGHG'] = 'red'
experiment_colors['historicalnoAA'] = 'orange'

region_styles = {}
region_styles['sh'] = 'dashed'
region_styles['nh'] = 'dashdot'
region_styles['global'] = 'solid'

def get_file_info(infile):
    """Strip information from the file name."""

    file_components = infile.split('/')
    fname = file_components[-1]
    metric, realm, model, experiment, mip, time = fname.split('_')
    assert 'historical' in experiment
    var, region, aggregator = metric.split('-')
    assert region in region_styles.keys()

    if experiment == 'historicalMisc':
        experiment = 'historicalAA'

    return experiment, model, region, mip

def main(inargs):
    """Run the program."""

    fig = plt.figure(figsize=[10, 10])
    for infile in inargs.infiles:
        cube = iris.load_cube(infile)
        experiment, model, region, mip = get_file_info(infile)

        color = experiment_colors[experiment]
        style = region_styles[region]
        iplt.plot(cube, color=color, linestyle=style, label=experiment+', '+region)
        plt.title(model + ', ' + mip[0:2])

    plt.legend(loc=2)
    plt.ylabel('Aerosol optical depth at 550nm')
    plt.xlabel('Year')
    plt.savefig(inargs.outfile, bbox_inches='tight')
    gio.write_metadata(inargs.outfile, file_info={infile: cube.attributes['history']})

if __name__ == '__main__':

    extra_info ="""
author:
  Damien Irving, irving.damien@gmail.com

note:

"""

    description=''
    parser = argparse.ArgumentParser(description=description,
                                     epilog=extra_info,
                                     argument_default=argparse.SUPPRESS,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("infiles", type=str, nargs='*', help="Input file names")
    parser.add_argument("outfile", type=str, help="Output file name")

    args = parser.parse_args()
    main(args)


text:
if(NOT input_file OR NOT output_file)
    message(FATAL_ERROR "You must specify input_file and output_file on the command line")
endif()

file(READ ${input_file} depend_text)

if (NOT "${depend_text}" STREQUAL "")
    string(REPLACE " /" "\n/" depend_text ${depend_text})
    string(REGEX REPLACE "^.*:" "" depend_text ${depend_text})
    string(REGEX REPLACE "[ \\\\]*\n" ";" depend_text ${depend_text})

    set(dependency_list "")

    foreach(file ${depend_text})
        string(REGEX REPLACE "^ +" "" file ${file})
        if(NOT EXISTS "${file}")
            message(WARNING " Removing non-existent dependency file: ${file}")
            set(file "")
        endif()

        if(NOT IS_DIRECTORY "${file}")
            get_filename_component(file_absolute "${file}" ABSOLUTE)
            list(APPEND dependency_list "${file_absolute}")
        endif()
    endforeach()
endif()

# Remove the duplicate entries and sort them.
list(REMOVE_DUPLICATES dependency_list)
list(SORT dependency_list)

foreach(file ${dependency_list})
    set(hip_hipcc_depend "${hip_hipcc_depend} \"${file}\"\n")
endforeach()

file(WRITE ${output_file} "# Generated by: FindHIP.cmake. Do not edit.\nSET(HIP_HIPCC_DEPEND\n ${hip_hipcc_depend})\n\n")
# vim: ts=4:sw=4:expandtab:smartindent


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Team Whiteeye 2 Bonus"</title>
		<link>http://bvs.wikidot.com/forum/t-141873/team-whiteeye-2-bonus</link>
		<description>Posts in the discussion thread "Team Whiteeye 2 Bonus"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:37:50 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-141873#post-545252</guid>
				<title>(no title)</title>
				<link>http://bvs.wikidot.com/forum/t-141873/team-whiteeye-2-bonus#post-545252</link>
				<description></description>
				<pubDate>Mon, 27 Jul 2009 06:04:43 +0000</pubDate>
				<wikidot:authorName>Nymphonomicon</wikidot:authorName>				<wikidot:authorUserId>91001</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Does this Team WhiteEye possess the same Zero Chakra as the previous Team WhiteEye?
 If not, I feel this is a huge ripoff to the players since the original Team WhiteEye is impossible to acquire after Season 1.

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
class AccessTokenExpired < StandardError; end

class User
  attr_accessor :meetup_token, :email, :confirmed_at, :profile_photo_url, :uuid, :is_admin, :name

  extend JanrainCapturable

  def member_application
    MemberApplication.find_by(user_uuid: uuid)
  end

  def mentor_application
    MentorApplication.find_by(user_uuid: uuid)
  end

  def is_admin?
    is_admin || false
  end

  def is_member?
    !member_application.nil? && member_application.approved?
  end

  def is_mentor?
    !mentor_application.nil? && mentor_application.approved?
  end

  def is_pending?
    !is_admin? && ((member_application && !is_member?) || (mentor_application && !is_mentor?))
  end

  def is_new?
    if member_application.nil? && mentor_application.nil? && !is_admin?
      preexistence = PreexistingMember.find_by(email: email)
      if preexistence
        preexistence.application_class.approve_me(self)
        false
      else
        true
      end
    else
      false
    end
  end

  def display_name
    if @display_rules['displayName'] == 'true'
      @display_name
    else
      '<hidden>'
    end
  end

  def about_me
    if @display_rules['aboutMe'] == 'true'
      @about_me
    else
      '<hidden>'
    end
  end

  def project_role(project)
    participation = Participation.where(user_uuid: uuid, project_id: project.id).take
    if !participation.nil?
      participation.role
    else
      nil
    end
  end

  def projects
    project_ids = participation_class.where(user_uuid: uuid).pluck(:project_id)
    Project.where(id: project_ids)
  end

  def claimed_meeting_requests
    if is_mentor?
      MeetingRequest.where(mentor_uuid: self.uuid)
    else
      MeetingRequest.where(["member_uuid = ? AND mentor_UUID IS NOT null", self.uuid])
    end
  end

  def open_meeting_requests
    if is_mentor?
      MeetingRequest.where(mentor_uuid: nil)
    else
      MeetingRequest.where(member_uuid: self.uuid, mentor_uuid: nil)
    end
  end

  def events
    if @events.nil?
      rsvped_event_ids = Set.new(EventRsvp.where(user_uuid: self.uuid).map(&:event_id))
      @events = Event.upcoming_events.keep_if { |event| rsvped_event_ids.include?(event.id) }
    else
      @events
    end
  end

  def events_without_rsvp
    Event.upcoming_events - events
  end

  def participation_class
    is_member? ? MemberParticipation : MentorParticipation
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Abies grandis var. idahoensis Silba

### Remarks
null


text:
If you have improvements to the Intel MKL-DNN code, please send us your pull
requests! For getting started, see GitHub
[howto](https://help.github.com/en/articles/about-pull-requests).

The current guidelines are work in progress.

## Pull request checklist

Before sending your pull requests, please make sure that you followed this
list.

* If you are contributing a new compute primitive, check the
  [library functionality guidelines](CONTRIBUTING.md#library_functionality_guidelines).
  It is strongly advised to first open an
  [RFC pull request](CONTRIBUTING.md#RFC_pull_requests) with a
  detailed explanation of expected use cases and performance benefits.

* Ensure that the changes are consistent with the
  [code contribution guidelines](CONTRIBUTING.md#code_contribution_guidelines).

* Check that the changes are consistent with the
  [coding style](CONTRIBUTING.md#coding_style).

* Check that [unit tests](CONTRIBUTING.md#unit_tests) pass.

## Library functionality guidelines

Intel MKL-DNN focuses on functionality that satisfies all of the following
criteria:

1. *Performance*: the functionality has material impact on a workload level.
   In other words, this means that for a new primitive it should be
   demonstrated that it brings visible performance improvement to some
   workload.

2. *Generality*: the functionality is useful in a wide range of deep learning
   applications. This implies that when introducing a new primitive, its API
   needs to be general enough to be integrated into multiple deep learning
   frameworks that have similar functionality.

3. *Complexity*: it is not trivial to implement the functionality directly in
   a deep learning application.

### RFC pull requests

It is strongly advised to open an RFC pull request when contributing new
primitives. In the RFC, please provide the following details:

* The expected performance benefit. This usually best presented as a profiling
  information from a workload showing that a particular operation takes
  significant percentage of the total time and thus is a good optimization
  candidate.

* The definition of the operation as an MKL-DNN primitive including interface
  and semantics. It is OK to have sketches for the interface, but the
  semantics should be fairly well defined.

* If possible, provide information about similar compute operations. Sometimes
  Intel MKL-DNN primitives are super-sets of operations available in the
  deep learning applications for the sake of greater portability across them.

## Code contribution guidelines

The code must be:

* *Tested*: Intel MKL-DNN uses gtests for lightweight functional testing and
  benchdnn for functionality that requires both performance and functional
  testing.

* *Documented*: Intel MKL-DNN uses Doxygen for inline comments in public header
  files that is used to build reference manual and markdown (also processed by
  Doxygen) for user guide.

* *Portable*: Intel MKL-DNN supports different operating systems, CPU and GPU
  architectures, compilers, and run-times. The new code should be complaint
  with the [System Requirements](README.md#system-requirements).

## Coding style

The general principle is to follow the style of existing / surrounding code.

Particularly:
* Use 4-space indentation.
* Limit line length to 80 columns.
* Do put spaces after `if`, `for`, `switch`; otherwise, do not put spaces
  around braces, parenthesis, square or angle brackets.
* Do put spaces around binary arithmetic operators.
* Avoid trailing and double spaces (unless used for indentation).
* Do not indent namespaces, `private:`, `public:`, `protected:` and case
  labels.
* Keep opening brace on the same line as the statement or function.

If in doubt, use the `clang-format`:
```sh
clang-format -style=file -i foo.cpp
```
This will format code using the `_clang_format` file found in the Intel
MKL-DNN top level directory.

Coding style is secondary to the general code design.

## Unit tests

Intel MKL-DNN uses gtests for lightweight functional testing and benchdnn for
performance and functional testing.

Be sure to extend the existing tests when fixing an issue.

Developing new benchdnn tests can be hard, so it is a good idea to start with
gtests first.


text:
using namespace std;
using namespace v8;
using namespace node;

namespace openvg_canvas {
namespace freeimage {

static Persistent<FunctionTemplate> image_constructor;

void Image::Initialize(Handle<Object> target) {
  SCOPE(freeimage_isolate);

  // Prepare constructor template
  Local<FunctionTemplate> constructor = FunctionTemplate::New(New);
  constructor->SetClassName(String::NewSymbol("Image"));
  constructor->InstanceTemplate()->SetInternalFieldCount(1);

  SET_TEMPLATE(image_constructor, freeimage_isolate, constructor);

  // Prototype
  Local<Template> proto = constructor->PrototypeTemplate();
  proto->Set("free"           , FunctionTemplate::New(Free           ));
  proto->Set("convertTo32Bits", FunctionTemplate::New(ConvertTo32Bits));
  proto->Set("saveToMemory"   , FunctionTemplate::New(SaveToMemory   ));
}

Image::Image() {}

Image::~Image() {
  SCOPE(freeimage_isolate);

  Local<Value> wrappedDIB = HANDLE->GetInternalField(0);
  if (wrappedDIB->IsNull()) return;

  FIBITMAP *dib = static_cast<FIBITMAP*>(Local<External>::Cast(wrappedDIB)->Value());

  // cout << "Freeing img " << hex << dib << dec << endl;

  FreeImage_Unload(dib);
}

V8_METHOD(Image::New) {
  SCOPE(freeimage_isolate);

  Image *image = new Image();
  image->Wrap(args.This());

  V8_RETURN(args.This());
}

Image *Image::New(FIBITMAP* dib) {
  SCOPE(freeimage_isolate);

  // cout << "Alloc'ing img " << hex << dib << dec << endl;

  Local<Object> jsImage = NEW_INSTANCE(freeimage_isolate, image_constructor);

  Image *image = ObjectWrap::Unwrap<Image>(jsImage);

  int w, h, pitch;
  FREE_IMAGE_TYPE type = FreeImage_GetImageType(dib);

  jsImage->SetInternalField(0, External::New(dib));
  jsImage->Set(String::NewSymbol("width"    ), Integer::New(w     = FreeImage_GetWidth(dib)));
  jsImage->Set(String::NewSymbol("height"   ), Integer::New(h     = FreeImage_GetHeight(dib)));
  jsImage->Set(String::NewSymbol("bpp"      ), Integer::New((int) FreeImage_GetBPP(dib)));
  jsImage->Set(String::NewSymbol("pitch"    ), Integer::New(pitch = FreeImage_GetPitch(dib)));
  jsImage->Set(String::NewSymbol("type"     ), Integer::New(type));
  jsImage->Set(String::NewSymbol("redMask"  ), Integer::New((int) FreeImage_GetRedMask(dib)));
  jsImage->Set(String::NewSymbol("greenMask"), Integer::New((int) FreeImage_GetGreenMask(dib)));
  jsImage->Set(String::NewSymbol("blueMask" ), Integer::New((int) FreeImage_GetBlueMask(dib)));

  BYTE *bits = FreeImage_GetBits(dib);

#ifdef NODE_BUFFER_TYPE_PRE_0_11
  node::Buffer *buf = node::Buffer::New((char*) bits, h * pitch);
  jsImage->Set(String::New("buffer"), V8_PERSISTENT(buf));
#else
  jsImage->Set(String::New("buffer"), Buffer::New((char*) bits, h * pitch));
#endif

  return image;
}

V8_METHOD(Image::Free) {
  SCOPE(freeimage_isolate);

  Local<Value> wrappedDIB = args.This()->GetInternalField(0);
  if (wrappedDIB->IsNull()) V8_RETURN_UNDEFINED;

  FIBITMAP *dib = static_cast<FIBITMAP*>(Local<External>::Cast(wrappedDIB)->Value());

  FreeImage_Unload(dib);

  args.This()->SetInternalField(0, Null());
  V8_RETURN_UNDEFINED;
}

V8_METHOD(Image::ConvertTo32Bits) {
  SCOPE(freeimage_isolate);

  Local<External> wrap = Local<External>::Cast(args.This()->GetInternalField(0));
  FIBITMAP *dib = static_cast<FIBITMAP*>(wrap->Value());

  FIBITMAP *conv = FreeImage_ConvertTo32Bits(dib);

  V8_RETURN(V8_PERSISTENT(Image::New(conv)));
}

V8_METHOD(Image::SaveToMemory) {
  SCOPE(freeimage_isolate);

  Local<External> wrap = Local<External>::Cast(args.This()->GetInternalField(0));
  FIBITMAP *dib = static_cast<FIBITMAP*>(wrap->Value());

  FREE_IMAGE_FORMAT fif = FIF_PNG;
  int flags = PNG_IGNOREGAMMA;

  BOOL convert = fif == FIF_JPEG && FreeImage_GetBPP(dib) != 24;
  if(convert) {
    dib = FreeImage_ConvertTo24Bits(dib);
  }

  BYTE *mem_buffer = NULL;
  DWORD file_size;
  FIMEMORY *hmem = FreeImage_OpenMemory();

  FreeImage_SaveToMemory(fif, dib, hmem, flags);

  if(convert) {
    FreeImage_Unload(dib);
  }

  FreeImage_AcquireMemory(hmem, &mem_buffer, &file_size);

#ifdef NODE_BUFFER_TYPE_PRE_0_11
  Buffer *slowBuffer = Buffer::New(file_size);
  memcpy(Buffer::Data(slowBuffer), (char*) mem_buffer, (size_t) file_size);

  Local<Object> globalObj = Context::GetCurrent()->Global();
  Local<Function> bufferConstructor = Local<Function>::Cast(globalObj->Get(String::New("Buffer")));
  Handle<Value> constructorArgs[3] = { slowBuffer->handle_, v8::Integer::New(file_size), v8::Integer::New(0) };
  Local<Object> actualBuffer = bufferConstructor->NewInstance(3, constructorArgs);
#else
  Local<Object> actualBuffer = Buffer::New(file_size);
  memcpy(Buffer::Data(actualBuffer), (char*) mem_buffer, (size_t) file_size);
#endif

  FreeImage_CloseMemory(hmem);

  V8_RETURN(scope.Close(actualBuffer));
}

}
}


text:
#include "entity-rom-data-editor.h"
#include "gui/imgui-combos.h"
#include "gui/imgui.h"
#include "gui/list-actions.h"
#include "gui/list-helpers.h"
#include "models/common/iterators.h"
#include "models/entity/entityromdata-error.h"

namespace UnTech::Gui {

using EntityRomStruct = UnTech::Entity::EntityRomStruct;

// EntityRomDataEditor Action Policies
struct EntityRomDataEditorData::AP {
    struct EntityRomData {
        using EditorT = EntityRomDataEditorData;
        using EditorDataT = UnTech::Entity::EntityRomData;

        static EditorDataT* getEditorData(EditorT& editor)
        {
            return &editor.entityRomData;
        }

        static EditorDataT* getEditorData(Project::ProjectFile& projectFile, const ItemIndex&)
        {
            return &projectFile.entityRomData;
        }
    };

    struct ListIds final : public EntityRomData {
        using ListT = std::vector<idstring>;
        using ListArgsT = std::tuple<>;
        using SelectionT = MultipleSelection;

        constexpr static size_t MAX_SIZE = 64;

        constexpr static auto SelectionPtr = &EditorT::listIdsSel;

        static ListT* getList(EditorDataT& entityRomData) { return &entityRomData.listIds; }
    };

    struct Structs final : public EntityRomData {
        using ListT = NamedList<Entity::EntityRomStruct>;
        using ListArgsT = std::tuple<>;
        using SelectionT = SingleSelection;

        constexpr static size_t MAX_SIZE = 255;

        constexpr static auto SelectionPtr = &EditorT::structsSel;

        static ListT* getList(EditorDataT& entityRomData) { return &entityRomData.structs; }
    };

    struct StructFields final : public EntityRomData {
        using ListT = std::vector<Entity::StructField>;
        using ListArgsT = std::tuple<unsigned>;
        using SelectionT = MultipleChildSelection;

        constexpr static size_t MAX_SIZE = 32;

        constexpr static auto SelectionPtr = &EditorT::structFieldsSel;

        static ListT* getList(EditorDataT& editorData, unsigned structIndex)
        {
            return getListField(Structs::getList(editorData), structIndex,
                                &EntityRomStruct::fields);
        }
    };

    struct FunctionTables final : public EntityRomData {
        using ListT = NamedList<Entity::EntityFunctionTable>;
        using ListArgsT = std::tuple<>;
        using SelectionT = SingleSelection;

        constexpr static size_t MAX_SIZE = 255;

        constexpr static auto SelectionPtr = &EditorT::functionTablesSel;

        static ListT* getList(EditorDataT& entityRomData) { return &entityRomData.functionTables; }
    };

    struct Entities final : public EntityRomData {
        using ListT = NamedList<Entity::EntityRomEntry>;
        using ListArgsT = std::tuple<>;
        using SelectionT = SingleSelection;

        constexpr static size_t MAX_SIZE = UnTech::Entity::MAX_N_ENTITY_ENTRIES;

        constexpr static auto SelectionPtr = &EditorT::entitiesSel;

        static constexpr EntityType entityType = EntityType::ENTITY;

        static ListT* getList(EditorDataT& editorData) { return &editorData.entities; }
    };

    struct Projectiles final : public EntityRomData {
        using ListT = NamedList<Entity::EntityRomEntry>;
        using ListArgsT = std::tuple<>;
        using SelectionT = SingleSelection;

        constexpr static size_t MAX_SIZE = UnTech::Entity::MAX_N_ENTITY_ENTRIES;

        constexpr static auto SelectionPtr = &EditorT::projectilesSel;

        static constexpr EntityType entityType = EntityType::PROJECTILE;

        static ListT* getList(EditorDataT& editorData) { return &editorData.projectiles; }
    };

    struct Players final : public EntityRomData {
        using ListT = NamedList<Entity::EntityRomEntry>;
        using ListArgsT = std::tuple<>;
        using SelectionT = SingleSelection;

        constexpr static size_t MAX_SIZE = UnTech::Entity::MAX_N_ENTITY_ENTRIES;

        constexpr static auto SelectionPtr = &EditorT::playersSel;

        static constexpr EntityType entityType = EntityType::PLAYER;

        static ListT* getList(EditorDataT& editorData) { return &editorData.players; }
    };
};

EntityRomDataEditorData::EntityRomDataEditorData(ItemIndex itemIndex)
    : AbstractEditorData(itemIndex)
{
}

bool EntityRomDataEditorData::loadDataFromProject(const Project::ProjectFile& projectFile)
{
    entityRomData = projectFile.entityRomData;

    return true;
}

void EntityRomDataEditorData::errorDoubleClicked(const AbstractError* error)
{
    using Type = Entity::EntityErrorType;

    listIdsSel.clearSelection();
    structsSel.clearSelection();
    structFieldsSel.clearSelection();
    functionTablesSel.clearSelection();
    entitiesSel.clearSelection();
    projectilesSel.clearSelection();
    playersSel.clearSelection();

    if (auto* e = dynamic_cast<const Entity::EntityError*>(error)) {
        switch (e->type) {
        case Type::LIST_ID:
            listIdsSel.setSelected(e->firstIndex);
            break;

        case Type::STRUCT:
            structsSel.setSelected(e->firstIndex);
            break;

        case Type::STRUCT_FIELD:
            structsSel.setSelected(e->firstIndex);
            structFieldsSel.setSelected(e->firstIndex, e->childIndex);
            break;

        case Type::ENTITY_FUNCTION_TABLE:
            functionTablesSel.setSelected(e->firstIndex);
            break;

        case Type::ENTITY_ROM_ENTRY:
            entitiesSel.setSelected(e->firstIndex);
            break;

        case Type::PROJECTILE_ROM_ENTRY:
            projectilesSel.setSelected(e->firstIndex);
            break;

        case Type::PLAYER_ROM_ENTRY:
            playersSel.setSelected(e->firstIndex);
            break;
        }
    }
}

void EntityRomDataEditorData::updateSelection()
{
    listIdsSel.update();
    structsSel.update();
    structFieldsSel.update(structsSel);
    functionTablesSel.update();
    entitiesSel.update();
    projectilesSel.update();
    playersSel.update();
}

EntityRomDataEditorGui::EntityRomDataEditorGui()
    : AbstractEditorGui()
    , _data(nullptr)
{
}

bool EntityRomDataEditorGui::setEditorData(AbstractEditorData* data)
{
    return (_data = dynamic_cast<EntityRomDataEditorData*>(data));
}

void EntityRomDataEditorGui::resetState()
{
}

void EntityRomDataEditorGui::editorClosed()
{
}

void EntityRomDataEditorGui::listIdsWindow()
{
    assert(_data);
    auto& entityRomData = _data->entityRomData;

    ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
    if (ImGui::Begin("EntityListIds")) {

        ListButtons<AP::ListIds>(_data);

        ImGui::BeginChild("Scroll");

        ImGui::Columns(2);
        ImGui::SetColumnWidth(0, 40);

        ImGui::Separator();
        ImGui::NextColumn();
        ImGui::Text("Name");
        ImGui::NextColumn();

        for (auto [i, listId] : enumerate(entityRomData.listIds)) {
            bool edited = false;

            ImGui::PushID(i);

            ImGui::Selectable(&_data->listIdsSel, i);
            ImGui::NextColumn();

            ImGui::SetNextItemWidth(-1);
            ImGui::InputIdstring("##Name", &listId);
            edited |= ImGui::IsItemDeactivatedAfterEdit();
            ImGui::NextColumn();

            if (edited) {
                ListActions<AP::ListIds>::itemEdited(_data, i);
            }

            ImGui::PopID();
        }

        ImGui::Columns(1);
        ImGui::Separator();

        ImGui::EndChild();
    }
    ImGui::End();
}

static bool parentCombo(const char* label, idstring* value, const NamedList<EntityRomStruct>& structs,
                        const unsigned structIndex)
{
    const idstring& currentStructName = structs.at(structIndex).name;

    return ImGui::IdStringCombo(label, value, structs, true,
                                [&](const EntityRomStruct& st) {
                                    return (st.name != currentStructName) ? &st.name : nullptr;
                                });
}

void EntityRomDataEditorGui::structsWindow()
{
    assert(_data);
    auto& entityRomData = _data->entityRomData;

    ImGui::SetNextWindowSize(ImVec2(600, 400), ImGuiCond_FirstUseEver);
    if (ImGui::Begin("Entity Rom Structs")) {

        NamedListSidebar<AP::Structs>(_data);

        ImGui::SameLine();

        ImGui::BeginGroup();
        ImGui::BeginChild("Item");
        {
            if (_data->structsSel.selectedIndex() < entityRomData.structs.size()) {
                auto& st = entityRomData.structs.at(_data->structsSel.selectedIndex());

                {
                    bool edited = false;

                    ImGui::InputIdstring("Name", &st.name);
                    if (ImGui::IsItemDeactivatedAfterEdit()) {
                        ListActions<AP::Structs>::selectedFieldEdited<
                            &UnTech::Entity::EntityRomStruct::name>(_data);
                    }

                    edited = parentCombo("Parent", &st.parent, entityRomData.structs, _data->structsSel.selectedIndex());
                    if (edited) {
                        ListActions<AP::Structs>::selectedFieldEdited<
                            &UnTech::Entity::EntityRomStruct::parent>(_data);
                    }

                    ImGui::InputText("Comment", &st.comment);
                    if (ImGui::IsItemDeactivatedAfterEdit()) {
                        ListActions<AP::Structs>::selectedFieldEdited<
                            &UnTech::Entity::EntityRomStruct::name>(_data);
                    }
                }

                ImGui::Separator();

                {
                    ListButtons<AP::StructFields>(_data);

                    ImGui::BeginChild("Scroll");

                    ImGui::Columns(5);
                    ImGui::SetColumnWidth(0, 40);

                    ImGui::Separator();
                    ImGui::NextColumn();
                    ImGui::Text("Name");
                    ImGui::NextColumn();
                    ImGui::Text("Type");
                    ImGui::NextColumn();
                    ImGui::Text("Default Value");
                    ImGui::NextColumn();
                    ImGui::Text("Comment");
                    ImGui::NextColumn();

                    const auto parentChain = generateStructChain(st.parent);

                    for (const auto& parentIndex : reverse(parentChain)) {
                        const auto& parent = entityRomData.structs.at(parentIndex);

                        for (auto [i, field] : enumerate(parent.fields)) {
                            ImGui::NextColumn();

                            ImGui::TextUnformatted(field.name);
                            ImGui::NextColumn();

                            ImGui::TextEnum(field.type);
                            ImGui::NextColumn();

                            ImGui::TextUnformatted(field.defaultValue);
                            ImGui::NextColumn();

                            ImGui::TextUnformatted(field.comment);
                            ImGui::NextColumn();
                        }
                    }

                    for (auto [i, field] : enumerate(st.fields)) {
                        bool edited = false;

                        ImGui::PushID(i);

                        ImGui::Selectable(&_data->structFieldsSel, i);
                        ImGui::NextColumn();

                        ImGui::SetNextItemWidth(-1);
                        ImGui::InputIdstring("##Name", &field.name);
                        edited |= ImGui::IsItemDeactivatedAfterEdit();
                        ImGui::NextColumn();

                        ImGui::SetNextItemWidth(-1);
                        edited |= ImGui::EnumCombo("##Type", &field.type);
                        ImGui::NextColumn();

                        ImGui::SetNextItemWidth(-1);
                        ImGui::InputText("##Default Value", &field.defaultValue);
                        edited |= ImGui::IsItemDeactivatedAfterEdit();
                        ImGui::NextColumn();

                        ImGui::SetNextItemWidth(-1);
                        ImGui::InputText("##Comment", &field.comment);
                        edited |= ImGui::IsItemDeactivatedAfterEdit();
                        ImGui::NextColumn();

                        if (edited) {
                            ListActions<AP::StructFields>::selectedListItemEdited(_data, i);
                        }

                        ImGui::PopID();
                    }

                    ImGui::Columns(1);
                    ImGui::Separator();

                    ImGui::EndChild();
                }
            }
        }
        ImGui::EndChild();
        ImGui::EndGroup();
    }
    ImGui::End();
}

void EntityRomDataEditorGui::functionTablesWindow(const UnTech::Project::ProjectFile& projectFile)
{
    assert(_data);
    auto& entityRomData = _data->entityRomData;

    ImGui::SetNextWindowSize(ImVec2(800, 400), ImGuiCond_FirstUseEver);
    if (ImGui::Begin("Entity Function Tables")) {

        ListButtons<AP::FunctionTables>(_data);

        ImGui::BeginChild("Scroll");

        ImGui::Columns(7);
        // ImGui::SetColumnWidth(0, 40);

        ImGui::Separator();
        ImGui::NextColumn();
        ImGui::Text("Name");
        ImGui::NextColumn();
        ImGui::Text("Entity Type");
        ImGui::NextColumn();
        ImGui::Text("Struct");
        ImGui::NextColumn();
        ImGui::Text("FS Export Order");
        ImGui::NextColumn();
        ImGui::Text("Parameter Type");
        ImGui::NextColumn();
        ImGui::Text("Comment");
        ImGui::NextColumn();
        ImGui::Separator();

        for (auto [i, ft] : enumerate(entityRomData.functionTables)) {
            bool edited = false;

            ImGui::PushID(i);

            ImGui::Selectable(&_data->functionTablesSel, i);
            ImGui::NextColumn();

            ImGui::SetNextItemWidth(-1);
            ImGui::InputIdstring("##Name", &ft.name);
            edited |= ImGui::IsItemDeactivatedAfterEdit();
            ImGui::NextColumn();

            ImGui::SetNextItemWidth(-1);
            edited |= ImGui::EnumCombo("##EntityType", &ft.entityType);
            ImGui::NextColumn();

            ImGui::SetNextItemWidth(-1);
            edited |= ImGui::IdStringCombo("##EntityStruct", &ft.entityStruct, entityRomData.structs, true);
            ImGui::NextColumn();

            ImGui::SetNextItemWidth(-1);
            edited |= ImGui::IdStringCombo("##ExportOrder", &ft.exportOrder, projectFile.frameSetExportOrders);
            ImGui::NextColumn();

            ImGui::SetNextItemWidth(-1);
            edited |= ImGui::EnumCombo("##ParameterType", &ft.parameterType);
            ImGui::NextColumn();

            ImGui::SetNextItemWidth(-1);
            ImGui::InputText("##Comment", &ft.comment);
            edited |= ImGui::IsItemDeactivatedAfterEdit();
            ImGui::NextColumn();

            if (edited) {
                ListActions<AP::FunctionTables>::itemEdited(_data, i);
            }

            ImGui::PopID();
        }

        ImGui::Columns(1);
        ImGui::Separator();

        ImGui::EndChild();
    }
    ImGui::End();
}

template <typename ActionPolicy>
void EntityRomDataEditorGui::entityEntriesWindow(const char* name,
                                                 const Project::ProjectFile& projectFile)
{
    using SelectionT = typename ActionPolicy::SelectionT;
    using EntityRomEntry = UnTech::Entity::EntityRomEntry;
    using EntityType = UnTech::Entity::EntityType;

    assert(_data);
    auto& entityRomData = _data->entityRomData;

    ImGui::SetNextWindowSize(ImVec2(600, 400), ImGuiCond_FirstUseEver);
    if (ImGui::Begin(name)) {

        NamedListSidebar<ActionPolicy>(_data);

        SelectionT& sel = _data->*ActionPolicy::SelectionPtr;
        NamedList<EntityRomEntry>* list = ActionPolicy::getList(entityRomData);

        ImGui::SameLine();

        ImGui::BeginGroup();
        ImGui::BeginChild("Item");
        {
            if (list && sel.selectedIndex() < list->size()) {
                auto& entry = list->at(sel.selectedIndex());

                bool edited = false;

                ImGui::InputIdstring("Name", &entry.name);
                edited |= ImGui::IsItemDeactivatedAfterEdit();

                edited |= ImGui::IdStringCombo("Function Table", &entry.functionTable, entityRomData.functionTables);

                const auto functionTable = entityRomData.functionTables.find(entry.functionTable);

                ImGui::InputText("Comment", &entry.comment);
                edited |= ImGui::IsItemDeactivatedAfterEdit();

                ImGui::Separator();

                edited |= ImGui::IdStringCombo("initialProjectileId", &entry.initialProjectileId, entityRomData.projectiles);

                if (ActionPolicy::entityType != EntityType::PLAYER) {
                    edited |= ImGui::IdStringCombo("initialListId", &entry.initialListId, entityRomData.listIds, false);
                }

                edited |= ImGui::IdStringCombo("frameSetId", &entry.frameSetId, projectFile.frameSets, false,
                                               [](auto& fsf) { return &fsf.name(); });

                if (ImGui::BeginCombo("displayFrame", u8Cast(entry.displayFrame))) {
                    auto frameSetIt = std::find_if(projectFile.frameSets.begin(), projectFile.frameSets.end(),
                                                   [&](auto& fs) { return fs.name() == entry.frameSetId; });

                    if (frameSetIt != projectFile.frameSets.end()) {
                        auto& fs = *frameSetIt;

                        if (fs.siFrameSet) {
                            edited |= ImGui::IdStringComboSelection(&entry.displayFrame, fs.siFrameSet->frames, false,
                                                                    [](auto& f) { return &f.name; });
                        }
                        else if (fs.msFrameSet) {
                            edited |= ImGui::IdStringComboSelection(&entry.displayFrame, fs.msFrameSet->frames, false,
                                                                    [](auto& f) { return &f.name; });
                        }
                    }

                    ImGui::EndCombo();
                }

                if (functionTable) {
                    const auto structChain = generateStructChain(functionTable->entityStruct);

                    ImGui::Separator();

                    unsigned id = 0;

                    for (const auto& sIndex : reverse(structChain)) {
                        auto& st = entityRomData.structs.at(sIndex);

                        for (auto [i, field] : enumerate(st.fields)) {
                            std::u8string& value = entry.fields[field.name];

                            ImGui::PushID(id++);

                            std::u8string label = stringBuilder(field.name, u8"###Field_", i);

                            ImGui::InputText(u8Cast(label), &value);
                            edited |= ImGui::IsItemDeactivatedAfterEdit();
                            if (ImGui::IsItemHovered() && !field.comment.empty()) {
                                ImGui::BeginTooltip();
                                ImGui::TextUnformatted(field.comment);
                                ImGui::EndTooltip();
                            }
                            ImGui::NextColumn();

                            ImGui::PopID();
                        }
                    }
                }

                if (edited) {
                    ListActions<ActionPolicy>::selectedItemEdited(_data);
                }
            }
        }
        ImGui::EndChild();
        ImGui::EndGroup();
    }
    ImGui::End();
}

void EntityRomDataEditorGui::processGui(const Project::ProjectFile& projectFile, const Project::ProjectData&)
{
    if (_data == nullptr) {
        return;
    }

    listIdsWindow();
    structsWindow();
    functionTablesWindow(projectFile);

    entityEntriesWindow<AP::Entities>("Entity ROM Entries", projectFile);

    entityEntriesWindow<AP::Projectiles>("Projectile ROM Entries", projectFile);

    entityEntriesWindow<AP::Players>("Player ROM Entries", projectFile);
}

// ::TODO replace with array_vector::
std::vector<unsigned> EntityRomDataEditorGui::generateStructChain(const idstring& name) const
{
    assert(_data);
    const auto& entityRomData = _data->entityRomData;

    std::vector<unsigned> items;
    items.reserve(8);

    unsigned sIndex = entityRomData.structs.indexOf(name);
    while (sIndex < entityRomData.structs.size()) {
        const bool containsParent = std::find(items.begin(), items.end(), sIndex) != items.end();
        if (containsParent) {
            items.clear();
            return items;
        }

        items.push_back(sIndex);

        const auto& st = entityRomData.structs.at(sIndex);
        sIndex = entityRomData.structs.indexOf(st.parent);
    }

    return items;
}

}


text:
cask 'iswiff' do
  version :latest
  sha256 :no_check

  url 'http://echoone.com/iswiff/iSwiff.dmg'
  name 'iSwiff'
  homepage 'https://echoone.com/iswiff/'

  app 'iSwiff.app'
end


text:
layout: links
permalink: /:title
forward_to: http://inertia-dashboard.github.io/
author: joshua.berl@tufts.edu
hidden: false
project: true
description: "inertia dashboard for your daily inspiration and depressive realism"
---


text:
package com.gazbert.bxbot.rest.api.security.authentication;

import static org.junit.Assert.assertEquals;

import org.junit.jupiter.api.Test;

/**
 * Tests a JWT Authentication Request behaves as expected.
 *
 * @author gazbert
 */
class TestJwtAuthenticationRequest {

  private static final String USERNAME = "bxbot-ui";
  private static final String PASSWORD = "InSearchOfLostTime";
  private static final String USERNAME2 = "bxbot-ui-2";
  private static final String PASSWORD2 = "InSearchOfLostTime2";

  @Test
  void testEmptyConstructorWorksAsExpected() {
    final JwtAuthenticationRequest jwtAuthenticationRequest = new JwtAuthenticationRequest();
    assertEquals("", jwtAuthenticationRequest.getUsername());
    assertEquals("", jwtAuthenticationRequest.getPassword());
  }

  @Test
  void testArgsConstructorWorksAsExpected() {
    final JwtAuthenticationRequest jwtAuthenticationRequest =
        new JwtAuthenticationRequest(USERNAME, PASSWORD);
    assertEquals(USERNAME, jwtAuthenticationRequest.getUsername());
    assertEquals(PASSWORD, jwtAuthenticationRequest.getPassword());
  }

  @Test
  void testSettersWorkAsExpected() {
    final JwtAuthenticationRequest jwtAuthenticationRequest =
        new JwtAuthenticationRequest(USERNAME, PASSWORD);
    jwtAuthenticationRequest.setUsername(USERNAME2);
    assertEquals(USERNAME2, jwtAuthenticationRequest.getUsername());
    jwtAuthenticationRequest.setPassword(PASSWORD2);
    assertEquals(PASSWORD2, jwtAuthenticationRequest.getPassword());
  }
}


text:
package randoop.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import randoop.field.FinalInstanceField;
import randoop.field.InstanceField;
import randoop.field.StaticField;
import randoop.field.StaticFinalField;
import randoop.operation.ConstructorCall;
import randoop.operation.EnumConstant;
import randoop.operation.FieldGet;
import randoop.operation.FieldSet;
import randoop.operation.MethodCall;
import randoop.operation.Operation;

/**
 * OperationExtractor is a {@link ClassVisitor} that creates a collection of
 * {@link Operation} objects through its visit methods as called by
 * {@link ReflectionManager#apply(Class)}.
 *
 * @see ReflectionManager
 * @see ClassVisitor
 *
 */
public class OperationExtractor implements ClassVisitor {

  private Set<Operation> operations;

  /**
   * Creates a visitor object that collects Operation objects corresponding to
   * class members visited by {@link ReflectionManager}. Stores
   * {@link Operation} objects in an ordered collection to ensure they are
   * strictly ordered once flattened to a list. This is needed to guarantee
   * determinism between Randoop runs with the same classes and parameters.
   */
  public OperationExtractor() {
    this.operations = new TreeSet<>();
  }

  public List<Operation> getOperations() {
    return new ArrayList<Operation>(operations);
  }

  /**
   * Collects the members of a collection of classes. Returns a filtered list of
   * {@code Operation} objects.
   *
   * @param classListing
   *          the collection of class objects from which to extract
   * @param predicate
   *          whether to include class members in results
   * @return list of {@code Operation} objects satisfying the predicate
   */
  public static List<Operation> getOperations(
      Collection<Class<?>> classListing, ReflectionPredicate predicate) {
    if (predicate == null) predicate = new DefaultReflectionPredicate();
    ReflectionManager mgr = new ReflectionManager(predicate);
    OperationExtractor op = new OperationExtractor();
    mgr.add(op);
    for (Class<?> c : classListing) {
      mgr.apply(c);
    }
    return op.getOperations();
  }

  /**
   * Creates a {@link ConstructorCall} object for the {@link Constructor}.
   *
   * @param c
   *          a {@link Constructor} object to be represented as an
   *          {@link Operation}.
   */
  @Override
  public void visit(Constructor<?> c) {
    operations.add(new ConstructorCall(c));
  }

  /**
   * Creates a {@link MethodCall} object for the {@link Method}.
   *
   * @param method
   *          a {@link Method} object to be represented as an {@link Operation}.
   */
  @Override
  public void visit(Method method) {
    operations.add(new MethodCall(method));
  }

  /**
   * Adds the {@link Operation} objects corresponding to getters and setters
   * appropriate to the kind of field.
   *
   * @param field
   *          a {@link Field} object to be represented as an {@link Operation}.
   */
  @Override
  public void visit(Field field) {
    int mods = field.getModifiers();

    if (Modifier.isStatic(mods)) {
      if (Modifier.isFinal(mods)) {
        StaticFinalField s = new StaticFinalField(field);
        operations.add(new FieldGet(s));
      } else {
        StaticField s = new StaticField(field);
        operations.add(new FieldGet(s));
        operations.add(new FieldSet(s));
      }
    } else {
      if (Modifier.isFinal(mods)) {
        FinalInstanceField i = new FinalInstanceField(field);
        operations.add(new FieldGet(i));
      } else {
        InstanceField i = new InstanceField(field);
        operations.add(new FieldGet(i));
        operations.add(new FieldSet(i));
      }
    }
  }

  /**
   * Creates a {@link EnumConstant} object for the {@link Enum}.
   *
   * @param e
   *          an {@link Enum} object to be represented as an {@link Operation}.
   */
  @Override
  public void visit(Enum<?> e) {
    operations.add(new EnumConstant(e));
  }

  @Override
  public void visitBefore(Class<?> c) {
    // nothing to do here
  }

  @Override
  public void visitAfter(Class<?> c) {
    // nothing to do here
  }
}


text:
using MagicalLifeAPI.Crafting;
using MagicalLifeAPI.Entity.AI.Task.Qualifications;
using MagicalLifeAPI.World.Base;
using ProtoBuf;
using System;
using System.Collections.Generic;

namespace MagicalLifeAPI.Entity.AI.Task.Tasks
{
    [ProtoContract]
    public class CraftSimpleItemTask : MagicalTask
    {
        /// <summary>
        /// The recipe used to craft a item.
        /// </summary>
        [ProtoMember(1)]
        protected SimpleItemRecipe SimpleRecipe { get; set; }

        [ProtoMember(2)]
        protected int Quantity { get; set; }

        public CraftSimpleItemTask(Guid boundID, SimpleItemRecipe simpleRecipe, int quantity)
            : base(Dependencies.CreateEmpty(), boundID, new List<Qualification>(), PriorityLayers.Default)
        {
            this.SimpleRecipe = simpleRecipe;
            this.Quantity = quantity;
        }

        protected CraftSimpleItemTask()
        {
            //Protobuf-net constructor
        }

        public override void MakePreparations(Living l)
        {
            //There's no preparations to make
        }

        public override void Reset()
        {
            //This method isn't being used yet
        }

        public override void Tick(Living l)
        {
            Item craft = this.SimpleRecipe.Craft(l.Inventory, this.Quantity);
            l.Inventory.AddItem(craft);
            this.CompleteTask();
        }

        public override bool CreateDependencies(Living l)
        {
            foreach (RequiredItem requiredItem in this.SimpleRecipe.RequiredItems)
            {
                this.Dependencies.PreRequisite.Add(new GrabItemQuantity(this.BoundID, requiredItem.Item.ItemID, requiredItem.Count, l.Dimension));
                this.Qualifications.Add(new IsItemAvailibleQualification(requiredItem.Item.ItemID, l.Dimension));
            }
            return true;
        }
    }
}


text:
<?php

namespace Onyx\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Soap\AutoDiscover;
use Onyx\Service\SoapDoctrineArrayOfTypeComplex;

class ServicesController extends AbstractActionController {

    /**
     * @var Doctrine\ORM\EntityManager
     */
    protected $em;

    /**
     * @return \Doctrine\ORM\EntityManager with the doctrine entity manager
     */
    public function getEntityManager() {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        }
        return $this->em;
    }

    /**
     * On soap requests, serve the service
     */
    public function soapAction() {
        $uri = $this->getRequest()->getUri();
        $soapURL = sprintf('%s://%s%s', $uri->getScheme(), $uri->getHost(), $uri->getPath());
        $wsdlURL = "{$soapURL}/wsdl";

        $soap = new \Zend\Soap\Server($wsdlURL);
        $soap->setClass('Onyx\Service\Soap', '', $this->getEntityManager());
        $soap->handle();

        exit();
    }

    /**
     * On WSDL request, serve the WSDL file
     */
    public function wsdlAction(){
        header("Content-Type: text/xml");
        $uri = $this->getRequest()->getUri();
        $soapURL = sprintf('%s://%s%s', $uri->getScheme(), $uri->getHost(), dirname($uri->getPath()));

        $autodiscover = new AutoDiscover();
        $autodiscover->setComplexTypeStrategy(new SoapDoctrineArrayOfTypeComplex());
        $autodiscover->setClass('Onyx\Service\Soap');

        //$autodiscover->setBindingStyle(array('style' => 'document'));
        //$autodiscover->setOperationBodyStyle(array('use' => 'literal'));
        $autodiscover->setUri($soapURL);
        $autodiscover->setServiceName("Onyx");

        $xml = $autodiscover->toXml();

        // Append the stylesheet
        $document = new \DOMDocument("1.0", "UTF-8");
        if($document->loadXML($xml)):
            $xpath = new \DOMXPath($document);
            $document->insertBefore($document->createProcessingInstruction("xml-stylesheet",'type="text/xsl" href="xsl"'), $xpath->evaluate('/*[1]')->item(0));
            $xml = $document->saveXML();
        endif;

        die($xml);
    }

    /**
     * Serve the XSL file for the WSDL document
     */
    public function xslAction(){
        die(file_get_contents(dirname(__FILE__)."/../Libs/xsl/wsdl-viewer.xsl"));
    }

}


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="radium-filter-behavior.html">
<dom-module id="radium-filter-querystring"></dom-module>
<!--
Faceless element for persisting/restoring selected filter terms to/from the querystring.

@element radium-filter-bar
@demo demo/index.html Basic demo
-->
<script>
  (function() {
    Polymer({
      is: 'radium-filter-querystring',

      properties: {
        /**
         * Querystring parameter name to use when persisting/restoring terms.
         */
        termParameterKey: {
          type: String,
          value: 'filter-term',
          observer: '_termParameterKeyChanged'
        }
      },

      behaviors: [RadiumFilterBehavior],

      observers: [
        '_termChanged(terms)'
      ],

      attached: function() {
        this._restoredQueryString = null;
        this._restoreFromQueryString();

        this._hashChangeListener = this._hashChanged.bind(this);
        window.addEventListener('hashchange', this._hashChangeListener);
      },

      detached: function() {
        window.removeEventListener('hashchange', this._hashChangeListener);
      },

      _getHash: function() {
        return window.location.hash.split('?')[0];
      },

      _getQueryString: function() {
        var queryString = document.location.hash.split('?')[1] || '';
        if (queryString[queryString.length - 1] === '/') {
          queryString = queryString.substring(0, queryString.length - 1);
        }
        return queryString;
      },

      _createQueryString: function() {
        return this.terms.map(function (term) {
          return this.termParameterKey + '=' + term.key + ':' + encodeURIComponent(term.value);
        }.bind(this)).join('&');
      },

      _persistToQueryString: function() {
        var currentQueryString = this._getQueryString();
        var queryString = this._createQueryString();
        if (queryString !== currentQueryString) {
          window.location.hash = this._getHash() + (queryString ? '?' + queryString : '');
        }
      },

      _restoreFromQueryString: function() {
        var previousQueryString = this._createQueryString();
        var queryString = this._getQueryString();
        if (queryString !== previousQueryString) {
          this.terms = queryString.split('&').reduce(function(result, parameter) {
            var parameterPair = parameter.split('=');
            var parameterKey = parameterPair[0], parameterValue = parameterPair[1];

            if (parameterKey === this.termParameterKey && parameterValue !== undefined) {
              var termPair = parameterValue.split(':');
              var termKey = termPair[0], termValue = termPair[1];

              if (termValue !== undefined) {
                result.push({
                  key: termKey,
                  value: decodeURIComponent(termValue)
                });
              }
            }

            return result;
          }.bind(this), []);
          this.notifyPath('terms', this.terms);

          // console.table(this.terms);

          this.fire('filter-restored', this.terms);
        }
      },

      _termChanged: function() {
        if (this.isAttached) {
          this._persistToQueryString();
        }
      },

      _termParameterKeyChanged: function() {
        if (this.isAttached) {
          this._restoreFromQueryString();
        }
      },

      _hashChanged: function() {
        var queryString = this._getQueryString();
        if (this._restoredQueryString !== queryString) {
          this._restoreFromQueryString();
          this._restoredQueryString = queryString;
        }
      }
    });
  })();
</script>


text:
import { IControllencyOptions } from "./IControllencyOptions";
import { IControllencyItem } from "./IControllencyItem";
import { EventEmitter } from "events";
import { IControllencyBufferedItem } from "./IControllencyBufferedItem";
import { ControllencyStatus } from "./ControllencyStatus";

/**
 * Use this class to limit the quantity of concurrent functions (Promises) that can be executed concurrently.
 * If more functions than maxConcurrency are pushed before the first maxConcurrency functions are resolved, they
 * will be stored in a lighweight in-memory queue, and launched as soon as those first function are being resolved.
 *
 * @export
 * @class Controllency
 * @extends {EventEmitter}
 */
export class Controllency extends EventEmitter {
    private maxConcurrency: number;
    private currentQuantityProcessing: number;
    private buffer: IControllencyBufferedItem[];
    private status: ControllencyStatus;

    /**
     * Creates an instance of Controllency.
     * @param {IControllencyOptions} [options]
     * @memberof Controllency
     */
    constructor(options?: IControllencyOptions | number) {
        super();

        if (typeof options === 'number') {
            options = {
                maxConcurrency: options
            };
        } else if (typeof options === 'undefined') {
            options = {
                maxConcurrency: 1
            };
        } else if (typeof options === 'object') {
            options.maxConcurrency = options.maxConcurrency || 1;
        } else {
            throw new Error('"options" must be an object or a number');
        }
        this.buffer = [];
        this.setMaxConcurrency(options.maxConcurrency);
        this.status = 'idle';
        this.currentQuantityProcessing = 0;
    }

    /**
     * Set the maximum quantity of concurrent promises that can be being processed at the same time.
     *
     * @param {number} maxConcurrency
     * @memberof Controllency
     */
    public setMaxConcurrency(maxConcurrency: number): void {
        if (typeof maxConcurrency !== 'number' ||
            Math.trunc(maxConcurrency) !== maxConcurrency || maxConcurrency <= 0) {
            throw new Error('maxConcurrency must be an integer');
        }
        this.maxConcurrency = maxConcurrency;
        this.proceed();
    }

    /**
     * Get the current maximum quantity of concurrent promises that can be being processed at the same time.
     *
     * @returns {number}
     * @memberof Controllency
     */
    public getMaxConcurrency(): number {
        return this.maxConcurrency;
    }

    /**
     * Get the current internal buffer of this Controllency object.
     * The promises that are currently being processed are included in this internal buffer. In other words,
     * this method returns que quantity of waiting functions in adition to the quantity of processing promises.
     *
     * @returns {number}
     * @memberof Controllency
     */
    public getBufferSize(): number {
        return this.buffer.length;
    }

    /**
     * Get the current status of this Controllency object. It can be 'paused', 'processing' or 'idle'.
     *
     * @returns {ControllencyStatus}
     * @memberof Controllency
     */
    public getStatus(): ControllencyStatus {
        return this.status;
    }

    /**
     * Set the current status of this Controllency object to 'paused'. This means that no new functions will
     * be fetched from the waiting internal queue until 'resume()' function is called. You can still continue
     * calling 'push()' function to queue new functions to be executed later.
     *
     * Important Note: all current processing Promises will continue being processed and resolved/rejected.
     *
     * @memberof Controllency
     */
    public pause(): void {
        this.status = 'paused';
    }

    /**
     * Remove the 'paused' status from this Controllency object. This action will cause that the status become
     * 'idle' or 'processing', depending on the state of the internal queue and current processing Promises.
     *
     * Important Note: by calling to this method, it will immediately start processing any available queued function.
     *
     * @memberof Controllency
     */
    public resume(): void {
        this.status = this.currentQuantityProcessing === 0 ? 'idle' : 'processing';
        this.proceed();
    }

    /**
     * Get the current quantity of processing Promises. This value could be maxConcurrency as maximum.
     *
     * @returns {number}
     * @memberof Controllency
     */
    public getCurrentQuantityProcessing(): number {
        return this.currentQuantityProcessing;
    }

    /**
     * Queue a new function to be executed as soon as posible. If the quantity of current processing Promises
     * is less than maxConcurrency, this function will be executed immediately. Else, it will be queued in-memory
     * to be executed as soon as posible (the order is preserved).
     *
     * You can pass directly the reference to the function to be executed, or you can pass the an object with
     * the function, the paremeters to execute that function, and the value for 'this' inside that function.
     *
     * @param {(ControllencyItem | (() => Promise<any>))} item
     * @memberof Controllency
     */
    public push(item: IControllencyItem | (() => Promise<any>)): void {
        if (typeof item === 'function') {
            item = {
                fn: item
            };
        }
        if (typeof item !== 'object') {
            throw new Error('"item" must be an object or a function');
        }
        if (!Array.isArray(item.params)) {
            item.params = (typeof item.params === 'undefined') ? [] : [item.params];
        }
        if (typeof item.fn !== 'function') {
            throw new Error('"fn" must be a function');
        }
        const bufferedItem: IControllencyBufferedItem = {
            bufferedDate: new Date(),
            fn: item.fn,
            params: item.params,
            processing: true,
            promise: null,
            thisObj: item.thisObj
        };
        this.buffer.push(bufferedItem);
        this.proceed();
    }

    private proceed(): void {
        if (this.maxConcurrency <= this.currentQuantityProcessing || this.status === 'paused') {
            return;
        }
        const quantityToStart = Math.min(
            this.maxConcurrency - this.currentQuantityProcessing,
            this.buffer.length - this.currentQuantityProcessing);
        const itemsToStart = this.buffer.slice(
            this.currentQuantityProcessing,
            this.currentQuantityProcessing + quantityToStart);
        this.currentQuantityProcessing += quantityToStart;
        this.status = this.currentQuantityProcessing === 0 ? 'idle' : 'processing';
        itemsToStart.forEach(this.startItem.bind(this));
    }

    private startItem(bufferedItem: IControllencyBufferedItem): void {
        bufferedItem.promise = Promise.resolve(bufferedItem.fn.apply(bufferedItem.thisObj, bufferedItem.params));
        bufferedItem.promise.then(
            this.onPromiseResolved.bind(this, bufferedItem),
            this.onPromiseRejected.bind(this, bufferedItem));
    }

    private onPromiseResolved(bufferedItem: IControllencyBufferedItem, result: any): void {
        this.currentQuantityProcessing -= 1;
        this.buffer.splice(this.buffer.indexOf(bufferedItem), 1);
        if (this.currentQuantityProcessing === 0 && this.status !== 'paused') {
            this.status = 'idle';
        }
        this.proceed();
        this.emit('resolved', result, bufferedItem);
    }

    private onPromiseRejected(bufferedItem: IControllencyBufferedItem, reason: any): void {
        this.currentQuantityProcessing -= 1;
        this.buffer.splice(this.buffer.indexOf(bufferedItem), 1);
        if (this.currentQuantityProcessing === 0 && this.status !== 'paused') {
            this.status = 'idle';
        }
        this.proceed();
        this.emit('rejected', reason, bufferedItem);
    }
}


text:
require 'test_helper'

class TestSgPostcode < Minitest::Test
  def setup
    Redis.new.flushall
  end

  def test_init_new_sg_postcode_array
    postcode_array = SgPostcode::Array.new([])
    assert_kind_of SgPostcode::Array, postcode_array
  end

  def test_convert_to_long_lat_array
    postcode_array = SgPostcode::Array.new([])
    postcode_array.convert
  end

  def test_real_convert
    array_convert =
      SgPostcode::Array
        .new(['546080', '238858'])
        .convert

    assert_kind_of Array, array_convert
    assert_equal 2, array_convert.count
    refute_operator array_convert.first, :key?, :density
    assert_operator array_convert.first, :key?, :format_address
  end

  def test_real_convert_with_density
    array_convert =
      SgPostcode::Array
        .new(['540000'] * 10)
        .convert

    assert_kind_of Array, array_convert
    assert_equal 1, array_convert.count
    assert_operator array_convert.first, :key?, :density
    assert_equal 10, array_convert.first[:density]
  end

  def test_real_convert_with_density2
    array_convert =
      SgPostcode::Array
        .new(['540000', '540000', '210000'])
        .convert

    assert_kind_of Array, array_convert
    assert_equal 2, array_convert.count
    assert_operator array_convert.first, :key?, :density
    assert_equal 2, array_convert.first[:density]
    refute_operator array_convert[1], :key?, :density
  end

  def test_invalid_convert
    array_convert =
      SgPostcode::Array
        .new(['Totally cannot exist', nil])
        .convert

    assert_kind_of Array, array_convert
  end

  def test_convert_with_options
    convert = SgPostcode::Array.new(['238438'], host: :Google)
    assert_kind_of Array, convert.convert
  end

  def test_non_cached
    converter = SgPostcode::Array.new(['238432'], cache: false)
    converter.convert

    redis = Redis.new
    store = SgPostcode::CacheAdapter.class_variable_get :@@hash_name

    assert_equal 0, redis.hkeys(store).length
  end
end


text:
package esilatest

/*
active_total object */
type GetFwLeaderboardsActiveTotalActiveTotal struct {
	/*
	 Amount of kills */
	Amount int32 `json:"amount,omitempty"`
	/*
	 faction_id integer */
	FactionId int32 `json:"faction_id,omitempty"`
}


text:
/**
 * Initialize global scripts including analytics and error handling
 */
export function initScripts() {
  // Initialize global scripts here
}


text:
using System;
using System.Reflection;
using Hydra.HydraCommon.Utils;
using UnityEditor;
using UnityEngine;

namespace Hydra.HydraCommon.Editor.Windows
{
	/// <summary>
	/// 	Unity's CurveEditorWindow is internal, so if we want to use it we need to get aggressive.
	/// </summary>
	public class CurveEditorWindowWrapper
	{
		public const string CURVE_EDITOR_WINDOW_TYPE_NAME = "CurveEditorWindow";
		public const string CURVE_EDITOR_WINDOW_SHARED_INSTANCE_FIELD_NAME = "s_SharedCurveEditor";
		public const string CURVE_EDITOR_WINDOW_CURVE_EDITOR_FIELD_NAME = "m_CurveEditor";
		public const string CURVE_EDITOR_WINDOW_COLOR_PROPERTY_NAME = "color";
		public const string CURVE_EDITOR_WINDOW_CURVE_PROPERTY_NAME = "curve";

		public const string CURVE_EDITOR_TYPE_NAME = "CurveEditor";
		public const string CURVE_EDITOR_FRAME_H_METHOD_NAME = "SetShownHRangeInsideMargins";
		public const string CURVE_EDITOR_FRAME_V_METHOD_NAME = "SetShownVRangeInsideMargins";

		public const string CURVE_EDITOR_WINDOW_POPUP_METHOD_NAME = "ShowCurvePopup";

		public const string BAD_MEMBER_NAMES_ERROR =
			"Can't use CurveEditorWindow in this version of Unity. " +
			"Dear Unity Technologies, please expose an API for the CurveEditorWindow.";

		private static readonly Type s_CurveEditorWindowType;
		private static readonly FieldInfo s_SharedInstanceField;
		private static readonly FieldInfo s_CurveEditorField;
		private static readonly PropertyInfo s_ColorProperty;
		private static readonly PropertyInfo s_CurveProperty;
		private static readonly MethodInfo s_PopupMethod;

		private static readonly MethodInfo s_FrameHMethod;
		private static readonly MethodInfo s_FrameVMethod;

		#region Properties

		/// <summary>
		/// 	Gets or sets the curve.
		/// </summary>
		/// <value>The curve.</value>
		public static AnimationCurve curve
		{
			get { return s_CurveProperty.GetValue(s_CurveEditorWindowType, null) as AnimationCurve; }
			set { s_CurveProperty.SetValue(s_CurveEditorWindowType, value, null); }
		}

		/// <summary>
		/// 	Gets or sets the color of the curve.
		/// </summary>
		/// <value>The color.</value>
		public static Color color
		{
			get { return (Color)s_ColorProperty.GetValue(s_CurveEditorWindowType, null); }
			set { s_ColorProperty.SetValue(s_CurveEditorWindowType, value, null); }
		}

		/// <summary>
		/// 	Gets the CurveEditorWindow instance.
		/// </summary>
		/// <value>The CurveEditorWindow instance.</value>
		public static EditorWindow curveEditorWindow { get { return s_SharedInstanceField.GetValue(null) as EditorWindow; } }

		/// <summary>
		/// 	Gets the curve editor.
		/// </summary>
		/// <value>The curve editor.</value>
		public static object curveEditor { get { return s_CurveEditorField.GetValue(curveEditorWindow); } }

		#endregion

		/// <summary>
		/// 	Initializes the <see cref="CurveEditorWindowWrapper"/> class.
		/// </summary>
		static CurveEditorWindowWrapper()
		{
			// Get the CurveEditorWindow type and members
			s_CurveEditorWindowType = ReflectionUtils.GetTypeByName(Assembly.GetAssembly(typeof(EditorWindow)),
																	CURVE_EDITOR_WINDOW_TYPE_NAME);
			if (s_CurveEditorWindowType == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);

			s_SharedInstanceField = ReflectionUtils.GetFieldByName(s_CurveEditorWindowType,
																   CURVE_EDITOR_WINDOW_SHARED_INSTANCE_FIELD_NAME);
			if (s_SharedInstanceField == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);

			s_CurveEditorField = ReflectionUtils.GetFieldByName(s_CurveEditorWindowType,
																CURVE_EDITOR_WINDOW_CURVE_EDITOR_FIELD_NAME);
			if (s_CurveEditorField == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);

			s_CurveProperty = ReflectionUtils.GetPropertyByName(s_CurveEditorWindowType, CURVE_EDITOR_WINDOW_CURVE_PROPERTY_NAME);
			if (s_CurveProperty == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);

			s_ColorProperty = ReflectionUtils.GetPropertyByName(s_CurveEditorWindowType, CURVE_EDITOR_WINDOW_COLOR_PROPERTY_NAME);
			if (s_ColorProperty == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);

			// Get the CurveEditor type and members
			Type curveEditorType = ReflectionUtils.GetTypeByName(Assembly.GetAssembly(typeof(EditorWindow)),
																 CURVE_EDITOR_TYPE_NAME);
			if (curveEditorType == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);

			s_FrameHMethod = ReflectionUtils.GetMethodByName(curveEditorType, CURVE_EDITOR_FRAME_H_METHOD_NAME);
			if (s_FrameHMethod == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);

			s_FrameVMethod = ReflectionUtils.GetMethodByName(curveEditorType, CURVE_EDITOR_FRAME_V_METHOD_NAME);
			if (s_FrameVMethod == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);

			// Finally the method for showing the curve editor window
			s_PopupMethod = ReflectionUtils.GetMethodByName(typeof(EditorGUI), CURVE_EDITOR_WINDOW_POPUP_METHOD_NAME);
			if (s_PopupMethod == null)
				throw new Exception(BAD_MEMBER_NAMES_ERROR);
		}

		#region Methods

		/// <summary>
		/// 	Shows the curve editor window.
		/// </summary>
		/// <param name="title">Title.</param>
		public static void ShowCurveEditorWindow(string title)
		{
			s_PopupMethod.Invoke(null, new object[] {null, new Rect()});

			curveEditorWindow.titleContent = new GUIContent(title);
		}

		/// <summary>
		/// 	Frame the specified area.
		/// </summary>
		/// <param name="area">Area.</param>
		public static void Frame(Rect area)
		{
			s_FrameHMethod.Invoke(curveEditor, new object[] {area.xMin, area.xMax});
			s_FrameVMethod.Invoke(curveEditor, new object[] {area.yMin, area.yMax});
		}

		#endregion
	}
}


text:
<!DOCTYPE html>

    <meta content="text/html;charset=UTF-8" http-equiv="Content-type" />
    <title>parslet - Parser construction</title>
    <meta content="Kaspar Schiess (http://absurd.li)" name="author" />
    <link href="images/favicon3.ico" rel="shortcut icon" />
    <link href="/parslet/stylesheets/site.css" rel="stylesheet" /><link href="/parslet/stylesheets/sh_whitengrey.css" rel="stylesheet" />

            about

            get started

            install

            docs

            contribute

            projects

          Parser construction

A parser is nothing more than a class that derives from
Parslet::Parser. The simplest parser that one could write would
look like this:

  class SimpleParser < Parslet::Parser
    rule(:a_rule) { str('simple_parser') }
    root(:a_rule)
  end

The language recognized by this parser is simply the string “simple_parser”.
Parser rules do look a lot like methods and are defined by

  rule(name) { definition_block }

Behind the scenes, this really defines a method that returns whatever you
return from it.

Every parser has a root. This designates where parsing should start. It is like
an entry point to your parser. With a root defined like this:

  root(:my_root)

you create a #parse method in your parser that will start parsing
by calling the #my_root method. You’ll also have a #root
(instance) method that is an alias of the root method. The following things are
really one and the same:

  SimpleParser.new.parse(string)
  SimpleParser.new.root.parse(string)
  SimpleParser.new.a_rule.parse(string)

Knowing these things gives you a lot of flexibility; I’ll explain why at the
end of the chapter. For now, just let me point out that because all of this is
Ruby, your favorite editor will syntax highlight parser code just fine.

Atoms: The inside of a parser

Matching strings of characters

A parser is constructed from parser atoms (or parslets, hence the name). The
atoms are what appear inside your rules (and maybe elsewhere). We’ve already
encountered an atom, the string atom:

  str('simple_parser')

This returns a Parslet::Atoms::Str instance. These parser atoms
all derive from Parslet::Atoms::Base and have essentially just
one method you can call: #parse. So this works:

  str('foobar').parse('foobar') # => "foobar"@0

The atoms are small parsers that can recognize languages and throw errors, just
like real Parslet::Parser subclasses.

Matching character ranges

The second parser atom you will have to know about allows you to match
character ranges:

  match('[0-9a-f]')

The above atom would match the numbers zero through nine and the letters ‘a’
to ‘f’ – yeah, you guessed right – hexadecimal numbers for example. The inside
of such a match parslet is essentially a regular expression that matches
a single character of input. Because we’ll be using ranges so much with
#match and because typing (‘[]’) is tiresome, here’s another way
to write the above #match atom:

  match['0-9a-f']

Character matches are instances of Parslet::Atoms::Re. Here are
some more examples of character ranges:

  match['[:alnum:]']      # letters and numbers
  match['\n']             # newlines
  match('\w')             # word characters
  match('.')              # any character

The wild wild #any

The last example above corresponds to the regular expression /./ that matches
any one character. There is a special atom for that:

  any

Composition of Atoms

These basic atoms can be composed to form complex grammars. The following
few sections will tell you about the various ways atoms can be composed.

Simple Sequences

Match ‘foo’ and then ‘bar’:

  str('foo') >> str('bar')    # same as str('foobar')

Sequences correspond to instances of the class
Parslet::Atoms::Sequence.

Repetition and its Special Cases

To model atoms that can be repeated, you should use #repeat:

  str('foo').repeat

This will allow foo to repeat any number of times, including zero. If you
look at the signature for #repeat in Parslet::Atoms::Base,
you’ll see that it has really two arguments: min and max. So the following
code all makes sense:

  str('foo').repeat(1)      # match 'foo' at least once
  str('foo').repeat(1,3)    # at least once and at most 3 times
  str('foo').repeat(0, nil) # the default: same as str('foo').repeat

Repetition has a special case that is used frequently: Matching something
once or not at all can be achieved by repeat(0,1), but also
through the prettier:

  str('foo').maybe          # same as str('foo').repeat(0,1)

These all map to Parslet::Atoms::Repetition. Please note this
little twist to #maybe:

  str('foo').maybe.as(:f).parse('')         # => {:f=>nil}
  str('foo').repeat(0,1).as(:f).parse('')   # => {:f=>[]}

The ‘nil’-value of #maybe is nil. This is catering to the
intuition that foo.maybe either gives me foo or
nothing at all, not an empty array. But have it your way!

Alternation

The most important composition method for grammars is alternation. Without
it, your grammars would only vary in the amount of things matched, but not
in content. Here’s how this looks:

  str('foo') | str('bar')   # matches 'foo' OR 'bar'

This reads naturally as “‘foo’ or ‘bar’”.

Operator precedence

The operators we have chosen for parslet atom combination have the operator
precedence that you would expect. No parenthesis are needed to express
alternation of sequences:

  str('s') >> str('equence') |
    str('se') >> str('quence')

And more

Parslet atoms are not as pretty as Treetop atoms. There you go, we said it.
However, there seems to be a different kind of aesthetic about them; they
are pure Ruby and integrate well with the rest of your environment. Have a
look at this:

  # Also consumes the space after important things like ';' or ':'. Call this
  # giving the character you want to match as argument:
  #
  #   arg >> (spaced(',') >> arg).repeat
  #
  def spaced(character)
    str(character) >> match['\s']
  end

or even this:

  # Turns any atom into an expression that matches a left parenthesis, the
  # atom and then a right parenthesis.
  #
  #   bracketed(sum)
  #
  def bracketed(atom)
    spaced('(') >> atom >> spaced(')')
  end

You might say that because parslet is just plain old Ruby objects itself (PORO
™), it allows for very tight code. Module inclusion, class inheritance, …
all your tools should work well with parslet.

Tree construction

By default, parslet will just echo back to you the strings you feed into it.
Parslet will not generate a parser for you and neither will it generate your
abstract syntax tree for you. The method #as(name) allows you
to specify exactly how you want your tree to look like:

  str('foo').parse('foo')             # => "foo"@0
  str('foo').as(:bar).parse('foo')    # => {:bar=>"foo"@0}

So you think: #as(name) allows me to create a hash, big deal.
That’s not all. You’ll notice that annotating everything that you want to keep
in your grammar with #as(name) autocreates a sensible tree
composed of hashes and arrays and strings. It’s really somewhat magic: Parslet
has a set of clever rules that merge the annotated output from your atoms into
a tree. Here are some more examples, with the atom on the left and the resulting
tree (assuming a successful parse) on the right:

  # Normal strings just map to strings
  str('a').repeat                         "aaa"@0

  # Arrays capture repetition of non-strings
  str('a').repeat.as(:b)                  {:b=>"aaa"@0}
  str('a').as(:b).repeat                  [{:b=>"a"@0}, {:b=>"a"@1}, {:b=>"a"@2}]

  # Subtrees get merged - unlabeled strings discarded
  str('a').as(:a) >> str('b').as(:b)      {:a=>"a"@0, :b=>"b"@1}
  str('a') >> str('b').as(:b) >> str('c') {:b=>"b"@1}

  # #maybe will return nil, not the empty array
  str('a').maybe.as(:a)                   {:a=>"a"@0}
  str('a').maybe.as(:a)                   {:a=>nil}

Capturing input

Advanced reading material – feel free to skip this.

Sometimes a parser needs to match against something that was already matched
against. Think about Ruby heredocs for example:

  str = <<-HERE
    This is part of the heredoc.
  HERE

The key to matching this kind of document is to capture part of the input
first and then construct the rest of the parser based on the captured part.
This is what it looks like in its simplest form:

  match['ab'].capture(:capt) >>               # create the capture
    dynamic { |s,c| str(c.captures[:capt]) }  # and match using the capture

This parser matches either ‘aa’ or ‘bb’, but not mixed forms ‘ab’ or ‘ba’. The
last sample introduced two new concepts for this kind of complex parser: the
#capture(name) method and the dynamic { ... } code
block.

Appending #capture(name) to any parser will capture that parsers
result in the captures hash in the parse context. If and only if the parser
match['ab'] succeeds, it stores either ‘a’ or ‘b’ in
context.captures[:capt].

The only way to get at that hash during the parse process is in a
dynamic { ... } code block. (for reasons that are out of the
scope of this document) In such a block, you can:

  dynamic { |source, context|
    # construct parsers by using randomness
    rand < 0.5 ? str('a') : str('b')

    # Or by using context information
    str( context.captures[:capt] )

    # Or by .. doing other kind of work (consumes 100 chars and then 'a')
    source.consume(100)
    str('a')
  }

Scopes

What if you want to parse heredocs contained within heredocs? It’s turtles all
the way down, after all. To be able to remember what string was used to
construct the outer heredoc, you would use the #scope { ... }
block that was introduced in parslet 1.5. Like opening a Ruby block, it allows
you to capture results (assign values to variables) to the same names you’ve
already used in outer scope – without destroying the outer scopes values for
these captures!.

Here’s an example for this:

  str('a').capture(:a) >> scope { str('b').capture(:a) } >>
    dynamic { |s,c| str(c.captures[:a]) }

This parses ‘aba’ – if you understand that, you understand scopes and
captures. Congrats.

And more

Now you know exactly how to create parsers using Parslet. Your parsers
will output intricate structures made of endless arrays, complex hashes and
a few string leftovers. But your programming skills fail you when you try
to put all this data to use. Selecting keys upon keys in hash after hash, you
feel like a cockroach that has just read Kafka’s works. This is no fun. This
is not what you signed up for.

Time to introduce you to Parslet::Transform and its workings.

MIT License, 2010-2018, © Kaspar Schiess


text:
layout: page
title: "Ordnungsamt & was danach geschah"
date: 9. August 17
author: findus
---
Hallo ihr Lieben,

nach einer Woche Funkstille wollten wir euch kurz neutral darüber informieren, was auf dem Utopival dieses Jahr passiert ist.

Auf die ersten zwei Tage voller Sonnenschein, guter Laune, schöner Begegnungen, spannender Workshops und Vorträge und unfassbar leckerem Essen folgte ein ziemlicher Schock: Das Ordnungsamt stand vor der Tür und hat uns ein Ultimatum bis 12 Uhr des nächsten Tages gesetzt, den Ort zu räumen. Die Vorwürfe: Offenes Feuer, nicht eingehaltene Hygienevorschriften usw.

Wir wollen hier auf die Berichte über die weiteren Ereignisse verzichten, aber ihr findet Presseberichte online. So könnt ihr euch selbst ein Bild machen.

Für alle Interessierte gibt es [hier](/2017/rueckblick/) einen kleinen Rückblick. Aus Rücksicht verzichten wir weitestgehend auf Fotos mit Gesichtern und wünschen uns stattdessen Berichte, Beschreibungen von Workshops, Gedichte und Lieder.

An dieser Stelle danken wir für alle stellvertretend nochmal für die Solidarität, den Mut und den Zusammenhalt trotz Trennung.

Wir sind der Utopie wieder einen Schritt näher gekommen und gehen weiter. Bis nächstes Jahr!


text:
package edu.uiowa.icts.criterion;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.TypedValue;

/**
 *
DateLike class.

 *
 * @author rrlorent
 * @date March 20, 2014
 * @version $Id: $
 */
public class DateLike implements Criterion {

	private static final long serialVersionUID = -6772056160232172164L;

	private final String SQL_SERVER = "org.hibernate.dialect.SQLServerDialect";
	private final String POSTGRES = "org.hibernate.dialect.PostgreSQLDialect";
	// private final String HSQL = "org.hibernate.dialect.HSQLDialect";
	// private final String MYSQL = "org.hibernate.dialect.MySQL5Dialect";

	private String propertyName;
	private String value;
	private Dialect dialect;

	/**
	 *
Constructor for DateLike.

	 *
	 * @param propertyName a {@link java.lang.String} object.
	 * @param value a {@link java.lang.String} object.
	 * @param dialect a {@link org.hibernate.dialect.Dialect} object.
	 */
	public DateLike( String propertyName, String value, Dialect dialect ) {
		super();
		this.propertyName = propertyName;
		this.value = value;
		this.dialect = dialect;
	}

	/**
	 * {@inheritDoc}
	 *
	 * (non-Javadoc)
	 * @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria, org.hibernate.criterion.CriteriaQuery)
	 */
	@Override
	public String toSqlString( Criteria criteria, CriteriaQuery criteriaQuery ) throws HibernateException {
		String[] columns = criteriaQuery.getColumnsUsingProjection( criteria, propertyName );
		if ( columns.length != 1 ) {
			throw new HibernateException( "like may only be used with single-column properties" );
		}
		if ( SQL_SERVER.equalsIgnoreCase( dialect.toString() ) ) {
			return " cast( convert( varchar( 10 ), " + columns[0] + ", 101 ) as varchar( 10 ) ) like lower( ? ) ";
		} else if ( POSTGRES.equalsIgnoreCase( dialect.toString() ) ) {
			return " cast( " + columns[0] + " as varchar ) like lower( ? ) ";
		} else {
			throw new HibernateException( "dialect not supported [" + dialect.toString() + "}" );
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * (non-Javadoc)
	 * @see org.hibernate.criterion.Criterion#getTypedValues(org.hibernate.Criteria, org.hibernate.criterion.CriteriaQuery)
	 */
	@Override
	public TypedValue[] getTypedValues( Criteria criteria, CriteriaQuery criteriaQuery ) throws HibernateException {
		return new TypedValue[] { new TypedValue( new org.hibernate.type.StringType(), MatchMode.START.toMatchString( value.toLowerCase() ) ) };
	}

}