text:
layout: post
title: "Model View Channel ?! with Phoenix"
tags: phoenix
excerpt: "A ToDo test aplication in Elixir Phoenix without controllers ... well, almost without controllers."
tweet: "A ToDo test aplication in Elixir Phoenix using channels and no controllers."

---

A while ago, contributing to [the Formerer project](https://github.com/efexen/formerer){:target="_blank"}, I had my first contact with Phoenix Channels. I enjoyed it so much and thought why not to build an app that uses only Channels instead of Controllers?

This is how ChanDoThis experiment was born. Yes, just another todo list application... but a live updating one :) .The app is live on Heroku, and available [here.](https://chandothis.herokuapp.com/){:target="_blank"}

Just to clarify, this post is not a tutorial or step by step guide on how to build a controller-less application in Phoenix. I will focus more on the code organization and the relation between front-end and back-end of the app.

### Specifications

Before starting to code I defined the minimal structure and functionalities:

- a simple Todo list, with 2 models: List and Todo
- make use of Phoenix Channels instead of Controllers
- no front-end frameworks and no AJAX calls
- one-page app
- everything live updates for all users present on the app
- follow as close as possible the CRUD actions from a "normal" Controller

### Structure

#### Phoenix Controller and Template

Let's start with the only controller that exists in the app. It's the `PageController` with a single `index` action. This generates the default Phoenix welcome page.

The page template includes also the fixed structure of lists and todos. It also has some data attributes such as:

`data-list="new-list-container"`, `data-list="list-index-container"` or `data-todo="todos-container"`

Those containers will be soon used to render dynamic lists and todos.

#### JavaScript

The JS side will take the role of Views and Templates.

```
web/static/js/
  app.js
  sockets.js
  views/
    list.js
    todo.js
  actions/
    list_actions.js
    todo_actions.js
  templates/
    list/ (hbs templates)
    todo/ (hbs templates)
```

**app.js** imports List from the views and initialize it with the socket `List.init(socket)`

The view connects to the socket and creates the channel. Views have 2 roles:

- receive channel messages or user input

- send it to the action JS file

For example, this is how you create a list:

./web/static/js/views/list.js

```javascript

// user clicks the `create-list` button and calls createListPush
// from the actions file
$(document).on('click', '[data-behaviour="create-list"]',
  () => ListActions.createListPush(channel))

// the view receives the message from the channel with event "create"
// calls the createListReceive with the response argument
channel.on('create', resp => {
  ListActions.createListReceive(resp)
})

```

The JS actions files together with the Channels will stand in place of the classic Controller. To avoid writing HTML in the JS, I use handlebars templates (`.hbs`). The role of the JS actions files is:

- push the event to the channel
- render errors if any
- render handlebar template for the specific action

Coming back to the above example, this is how the action JS file handles the creation of a new list:

./web/static/js/actions/list_actions.js

```javascript
// get the name of the new list from the form
// push the event "create" to the channel
// render any errors

createListPush(channel){
  let name = $('[data-list="new-list-name"]').val()
  channel.push("create", {name: name}).receive("error", error => {
    $(`[data-error="error-${error.attr}"]`).remove()
    $('[data-list="new-list-container"]').append(errorTemplate(error))
  })
},

// on response clear the new list form
// renders the newListTemplate with response as argument

createListReceive(resp){
  $('[data-list="new-list-container"]').empty()
  $('[data-list="list-index-container"]').prepend(newListTemplate(resp))
},

```

The `newListTemplate` is actually imported hbs template:
`import newListTemplate from "../templates/list/new_list.hbs"`
The CRUD actions are organized in Push / Receive pairs.

### Channels

Channels use pattern matching to map the events sent by the front-end. This reflects the same CRUD actions as the JS above.

./web/channels/list_channel.ex

```elixir
def handle_in(topic = "create", params, socket) do
  # DRY the code with handle_action function
  # there is a separate ListActions module handling all DB interactions

  handle_action(topic, create_list(params), socket)
end

defp handle_action(topic, action, socket) do
  case action do
    {:ok, list} ->
      # if the list is persisted
      # broadcast the event "create" and list JSON
      broadcast!(socket, topic, list_to_json(list))
      {:reply, :ok, socket}
    {:error, changeset} ->
      # else reply with error
    {:reply, {:error, parse_changeset_errors(changeset)}, socket}
  end
end
```

A Phoenix view renders the list JSON:

./web/views/list_view.ex

```elixir
def render("list.json", %{list: list}) do
  %{
    id: list.id,
    name: list.name
  }
end
```

There are other components we did not review, such as models or lib modules, but those are not relevant in the context of this case study.

However, the full code is available on Github:
[https://github.com/iacobson/chan_do_this/blob/lists-todos-final](https://github.com/iacobson/chan_do_this/blob/lists-todos-final){:target="_blank"} if you want to take a closer look.

To finish with the structure, below is a diagram of the system components and the interactions between them:

```
+-------------+        +-------------+                  +-------------+
|             | input  |             |  action func     |             |
| USER        +--------> JS VIEWS    +------------------> JS ACTIONS  |
|             |        |             |   push / receive |             |
+-------------+        +-^-----------+                  +--^-------+--+
                         |                                 |       |
                         |                                 |       |
                         |             push action         |       |
                   action|       +-------------------------+       |
                 response|       |     receive error               |
                         |       |                           render|
                         |       |                                 |
                         |       |                                 |
+-------------+        +-+-------v---+                  +----------v--+
|             |persist |             |                  |             |
| DB          <--------+ CHANNELS    |                  | HBS TEMPLT  |
|             |        |             |                  |             |
+-------------+        +-------------+                  +-------------+
```

### Test-drive the app

As mentioned in the beginning of this post, the app is hosted on Heroku: [https://chandothis.herokuapp.com/](https://chandothis.herokuapp.com/){:target="_blank"}

You will need 2 browser windows opened in split screen. Or, even better, open the app at the same time on 2 different devices.

Create a new list. The list should instantly appear in the other browser/device.

Create new todos, edit their names, delete or complete them. Everything should reflect at the same time in all the instances of the app.

### Conclusion

This is a simple, straightforward project, but I think it achieved its goal. There are ways to (almost) avoid controllers in Phoenix. Channels can take their place while keeping a CRUD-like structure.

This is not something you would want to do for all your projects. But whenever you need many live updates on the page, it may be an option.

While it was so fun to work on this app, it wasn't entirely what I expected when I started it. I expected a cool Elixir / Channels learning project and ended up mostly with a JS / jQuery one.  Hunting Lists and Todos IDs around in the view proved  at times to be frustrating and repetitive.

### What's next?

With all the good and bad parts, this can be a very good learning project. There are many things that you can build and test on top of it such as:

- add more clarity to the JS side and remove duplications
- add some form of Router
- implement a controler-less user authentication system
- use Phoenix Presence to show online users
and so much more.

Just [clone the project](https://github.com/iacobson/chan_do_this){:target="_blank"} and have fun!


text:
var express = require('express');
var app = express();

var plantbox = require('plantbox')(module)
var pagebox = require('./../main')(module)

var indexPlant = plantbox('./js/indexplant')
var indexPage = pagebox(indexPlant, './css/index')//you could also just use pagebox('./js/indexplant', './css/index')

var StaticPrefix = '/static/'

indexPage.serve(app, '/index', StaticPrefix)

app.listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using System.Text;
using static TankLib.Helpers.ConsoleSwatch;
// ReSharper disable UnusedMember.Local

namespace TankLib.Helpers {
    public static class Logger {
        public static bool ShowTime = false;

    #if DEBUG
        public static bool ShowDebug = true;
    #else
        public static bool ShowDebug = false;
    #endif

        public static bool Enabled = true;
        public static bool UseColor = true;

        public static void Log4Bit(ConsoleColor color, bool newLine, TextWriter writer, string category, string message, params object[] arg) {
            if (!Enabled) return;
            if (UseColor) {
                Console.ForegroundColor = color;
            }

            string output = message;

            if (arg.Length > 0) {
                output = string.Format(message, arg);
            }

            if (!string.IsNullOrWhiteSpace(category)) {
                output = $"[{category}] {output}";
            }

            if (ShowTime) {
                output = $"{DateTime.Now.ToLocalTime().ToLongTimeString()} {output}";
            }

            writer.Write(output);

            if (UseColor) {
                Console.ForegroundColor = ConsoleColor.Gray; // erm, reset
            }

            if (newLine) {
                writer.WriteLine();
            }
        }

        private static void Log24Bit(ConsoleColor color, string category, string message, params object[] arg) {
            Log24Bit(color, true, Console.Out, category, message, arg);
        }

        public static void Log24Bit(ConsoleColor color, bool newline, TextWriter writer, string category, string message, params object[] arg) {
            if (!Enabled) return;
            if (!EnableVT()) {
                Log4Bit(color, newline, writer, category, message, arg);
                return;
            }

            Log24Bit(color.AsDOSColor().AsXTermColor().ToForeground(), null, newline, writer, category, message, arg);
        }

        private static void Log24Bit(DOSColor color, string category, string message, params object[] arg) {
            Log24Bit(color, true, Console.Out, category, message, arg);
        }

        public static void Log24Bit(DOSColor color, bool newline, TextWriter writer, string category, string message, params object[] arg) {
            if (!Enabled) return;
            if (!EnableVT()) {
                Log4Bit(color.AsConsoleColor(), newline, writer, category, message, arg);
                return;
            }

            Log24Bit(color.AsXTermColor().ToForeground(), null, newline, writer, category, message, arg);
        }

        private static void Log24Bit(XTermColor color, string category, string message, params object[] arg) {
            Log24Bit(color, true, Console.Out, category, message, arg);
        }

        public static void Log24Bit(XTermColor color, bool newline, TextWriter writer, string category, string message, params object[] arg) {
            if (!Enabled) return;
            if (!EnableVT()) {
                Log4Bit(ConsoleColor.Gray, newline, writer, category, message, arg);
                return;
            }

            Log24Bit(color.ToForeground(), null, newline, writer, category, message, arg);
        }

        private static void Log24Bit(string foreground, string background, bool newLine, string category, string message, params object[] arg) {
            Log24Bit(foreground, background, newLine, Console.Out, category, message, arg);
        }

        public static void Log24Bit(string foreground, string background, bool newLine, TextWriter writer, string category, string message, params object[] arg) {
            if (!Enabled) return;
            if (!EnableVT()) {
                Log4Bit(ConsoleColor.Gray, newLine, writer, category, message, arg);
                return;
            }

            if (UseColor && !string.IsNullOrWhiteSpace(foreground)) {
                writer.Write(foreground);
            }

            if (UseColor && !string.IsNullOrWhiteSpace(background)) {
                writer.Write(background);
            }

            string output = message;

            if (arg.Length > 0) {
                output = string.Format(message, arg);
            }

            if (!string.IsNullOrWhiteSpace(category)) {
                output = $"[{category}] {output}";
            }

            if (ShowTime) {
                output = $"{DateTime.Now.ToLocalTime().ToLongTimeString()} {output}";
            }

            writer.Write(output);

            if (UseColor && (!string.IsNullOrWhiteSpace(foreground) || !string.IsNullOrWhiteSpace(background))) {
                writer.Write(ColorReset);
            }

            if (newLine) {
                writer.WriteLine();
            }
        }

        public static void Log(ConsoleColor color, bool newline, bool stderr, string category, string message, params object[] arg) {
            Log24Bit(color, newline, stderr ? Console.Error : Console.Out, category, message, arg);
        }

        public static void Success(string category, string message, params object[] arg) {
            Log(ConsoleColor.Green, true, false, category, message, arg);
        }

        public static void Info(string category, string message, params object[] arg) {
            Log(ConsoleColor.White, true, false, category, message, arg);
        }

        public static void Debug(string category, string message, params object[] arg) {
            if (!ShowDebug) return;
            Log(ConsoleColor.DarkGray, true, false, category, message, arg);
        }

        public static void Warn(string category, string message, params object[] arg) {
            Log(ConsoleColor.DarkYellow, true, false, category, message, arg);
        }

        public static void Error(string category, string message, params object[] arg) {
            Log(ConsoleColor.Red, true, true, category, message, arg);
        }

        public static string ReadLine(TextWriter writer, bool @private) {
            StringBuilder builder = new StringBuilder();
            ConsoleKeyInfo ch;
            while ((ch = Console.ReadKey(true)).Key != ConsoleKey.Enter) {
                if (ch.Key == ConsoleKey.Backspace) {
                    if (builder.Length > 0) {
                        if (!@private) {
                            writer.Write(ch.KeyChar);
                            writer.Write(" ");
                            writer.Write(ch.KeyChar);
                        }

                        builder.Remove(builder.Length - 1, 1);
                    } else {
                        Console.Beep();
                    }
                } else {
                    builder.Append(ch.KeyChar);

                    if (!@private) writer.Write(ch.KeyChar);
                }
            }
            writer.WriteLine();
            return builder.ToString();
        }

        private static string LastMessage { get; set; }
        private static void Fill<T>(T[] array, T value)
        {
            Fill(array, value, 0, array.Length);
        }

        private static void Fill<T>(T[] array, T value, int start, int length)
        {
            for (int i = 0; i < length; ++i) array[i + start] = value;
        }

        public static void LogProgress(string message, string pre, string post, double value, XTermColor messageColor, XTermColor preColor, XTermColor postColor, XTermColor brickColor, XTermColor processColor, bool showProgressValue, XTermColor processValueColor) {
            if (Console.IsOutputRedirected) return;
            var width = Console.WindowWidth;
            var empty = new char[width];
            Fill(empty, ' ');
            if (message != LastMessage) {
                Console.Out.Write(empty);
                Console.CursorLeft = 0;
                LastMessage = message;
                Logger.Log24Bit(messageColor, true, Console.Out, null, message);
            }
            Console.Out.Write(empty);
            Console.CursorLeft = 0;
            var remaining = width - pre.Length - post.Length - 4;
            Logger.Log24Bit(preColor, false, Console.Out, null, pre);
            if (remaining > 0) {
                Logger.Log24Bit(brickColor, false, Console.Out, null, " [");
                empty = new char[remaining];
                Fill(empty, ' ');
                Fill(empty, '=', 0, (int)System.Math.Round(remaining * System.Math.Min(value, 1)));
                Logger.Log24Bit(processColor, false, Console.Out, null, string.Join("", empty));
                Logger.Log24Bit(brickColor, false, Console.Out, null, "] ");

                if(showProgressValue && remaining > 6) {
                    var valueText = (System.Math.Min(value, 1) * 100).ToString().Split('.')[0] + "%";
                    Console.CursorLeft = pre.Length + 2 + (int)System.Math.Floor(remaining / 2.0d - valueText.Length / 2.0d);
                    Logger.Log24Bit(processValueColor, false, Console.Out, null, valueText);
                    Console.CursorLeft = width - post.Length;
                }
            }
            Logger.Log24Bit(postColor, false, Console.Out, null, post);
            Console.CursorLeft = Console.WindowWidth - 1;
            Console.CursorTop -= 1;
        }

        public static void FlushProgress() {
            Console.CursorTop += 1;
            Console.WriteLine();
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.apache.lucene.search.grouping.TopGroups.ScoreMergeMode (Lucene 6.0.1 API)</title>
<meta name="date" content="2016-05-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.lucene.search.grouping.TopGroups.ScoreMergeMode

Packages that use TopGroups.ScoreMergeMode

Package
Description

org.apache.lucene.search.grouping

Grouping.

Uses of TopGroups.ScoreMergeMode in org.apache.lucene.search.grouping

Methods in org.apache.lucene.search.grouping that return TopGroups.ScoreMergeMode

Modifier and Type
Method and Description

static TopGroups.ScoreMergeMode
TopGroups.ScoreMergeMode.valueOf(String name)

Returns the enum constant of this type with the specified name.

static TopGroups.ScoreMergeMode[]
TopGroups.ScoreMergeMode.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods in org.apache.lucene.search.grouping with parameters of type TopGroups.ScoreMergeMode

Modifier and Type
Method and Description

static <T> TopGroups<T>
TopGroups.merge(TopGroups<T>[] shardGroups,
     Sort groupSort,
     Sort docSort,
     int docOffset,
     int docTopN,
     TopGroups.ScoreMergeMode scoreMergeMode)

Merges an array of TopGroups, for example obtained
  from the second-pass collector across multiple
  shards.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
<?php

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Isin;
use Symfony\Component\Validator\Constraints\IsinValidator;
use Symfony\Component\Validator\Constraints\Luhn;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class IsinValidatorTest extends ConstraintValidatorTestCase
{
    protected function createValidator()
    {
        return new IsinValidator();
    }

    public function testNullIsValid()
    {
        $this->validator->validate(null, new Isin());

        $this->assertNoViolation();
    }

    public function testEmptyStringIsValid()
    {
        $this->validator->validate('', new Isin());

        $this->assertNoViolation();
    }

    /**
     * @dataProvider getValidIsin
     */
    public function testValidIsin($isin)
    {
        $this->validator->validate($isin, new Isin());
        $this->expectViolationsAt(0, $isin, new Luhn());
        $this->assertNoViolation();
    }

    public function getValidIsin()
    {
        return [
            ['XS2125535901'], // Goldman Sachs International
            ['DE000HZ8VA77'], // UniCredit Bank AG
            ['CH0528261156'], // Leonteq Securities AG [Guernsey]
            ['US0378331005'], // Apple, Inc.
            ['AU0000XVGZA3'], // TREASURY CORP VICTORIA 5 3/4% 2005-2016
            ['GB0002634946'], // BAE Systems
            ['CH0528261099'], // Leonteq Securities AG [Guernsey]
            ['XS2155672814'], // OP Corporate Bank plc
            ['XS2155687259'], // Orbian Financial Services III, LLC
            ['XS2155696672'], // Sheffield Receivables Company LLC
        ];
    }

    /**
     * @dataProvider getIsinWithInvalidLenghFormat
     */
    public function testIsinWithInvalidFormat($isin)
    {
        $this->assertViolationRaised($isin, Isin::INVALID_LENGTH_ERROR);
    }

    public function getIsinWithInvalidLenghFormat()
    {
        return [
            ['X'],
            ['XS'],
            ['XS2'],
            ['XS21'],
            ['XS215'],
            ['XS2155'],
            ['XS21556'],
            ['XS215569'],
            ['XS2155696'],
            ['XS21556966'],
            ['XS215569667'],
        ];
    }

    /**
     * @dataProvider getIsinWithInvalidPattern
     */
    public function testIsinWithInvalidPattern($isin)
    {
        $this->assertViolationRaised($isin, Isin::INVALID_PATTERN_ERROR);
    }

    public function getIsinWithInvalidPattern()
    {
        return [
            ['X12155696679'],
            ['123456789101'],
            ['XS215569667E'],
            ['XS215E69667A'],
        ];
    }

    /**
     * @dataProvider getIsinWithValidFormatButIncorrectChecksum
     */
    public function testIsinWithValidFormatButIncorrectChecksum($isin)
    {
        $this->expectViolationsAt(0, $isin, new Luhn());
        $this->assertViolationRaised($isin, Isin::INVALID_CHECKSUM_ERROR);
    }

    public function getIsinWithValidFormatButIncorrectChecksum()
    {
        return [
            ['XS2112212144'],
            ['DE013228VA77'],
            ['CH0512361156'],
            ['XS2125660123'],
            ['XS2012587408'],
            ['XS2012380102'],
            ['XS2012239364'],
        ];
    }

    private function assertViolationRaised($isin, $code)
    {
        $constraint = new Isin([
            'message' => 'myMessage',
        ]);

        $this->validator->validate($isin, $constraint);

        $this->buildViolation('myMessage')
            ->setParameter('{{ value }}', '"'.$isin.'"')
            ->setCode($code)
            ->assertRaised();
    }
}


text:
var _ = require('underscore');
var ElasticSearchClient = require('elasticsearchclient');
var log = require('oae-logger').logger('elasticsearchclient');
var Telemetry = require('oae-telemetry').telemetry('search');

var index = null;
var client = null;

/**
 * Refresh the search configuration with the given options.
 *
 * @param  {String}    index       The index to use
 * @param  {Object}    serverOpts  The server opts with which to configure the client
 */
var refreshSearchConfiguration = module.exports.refreshSearchConfiguration = function(_index, serverOpts) {
    index = _index;
    client = new ElasticSearchClient(serverOpts);
    log().info({
        'config': {
            'index': _index,
            'serverOpts': serverOpts
        }
    }, 'Refreshed search configuration.');
};

/**
 * Create an index with the specified name.
 *
 * @param  {String}      indexName       The name of the index
 * @param  {Object}      settings        The settings of the ElasticSearch index
 * @param  {Function}    callback        Standard callback function
 * @param  {Object}      callback.err    An error that occurred, if any
 */
var createIndex = module.exports.createIndex = function(indexName, settings, callback) {
    indexExists(indexName, function(err, exists) {
        if (err) {
            return callback(err);
        }

        if (!exists) {
            log().info({
                'indexName': indexName,
                'indexSettings': settings
            }, 'Creating new search index.');

            _exec('createIndex', client.createIndex(indexName, settings, null), callback);
        } else {
            return callback();
        }
    });
};

/**
 * Delete the index with the given name.
 *
 * @param  {String}    indexName       The name of the index to delete
 * @param  {Function}  callback        Standard callback function
 * @param  {Object}    callback.err    An error that occurred, if any
 */
var deleteIndex = module.exports.deleteIndex = function(indexName, callback) {
    indexExists(indexName, function(err, exists) {
        if (err) {
            return callback(err);
        }

        if (exists) {
            log().info('Deleting index "%s"', indexName);
            _exec('deleteIndex', client.deleteIndex(indexName, null), callback);
        } else {
            return callback();
        }
    });
};

/**
 * Determine whether or not the specified index exists.
 *
 * @param  {String}      indexName       The name of the index to test
 * @param  {Function}    callback        Standard callback function
 * @param  {Object}      callback.err    An error that occurred, if any
 * @param  {Boolean}     callback.exists Whether or not the index exists
 */
var indexExists = module.exports.indexExists = function(indexName, callback) {
    _exec('indexStatus', client.status(indexName, null), function(err) {
        if (err && err.error === 'IndexMissingException[[' + indexName + '] missing]') {
            return callback(null, false);
        } else if (err) {
            return callback(err);
        } else {
            return callback(null, true);
        }
    });
};

/**
 * Refresh the current index so that all its documents are available for querying.
 *
 * @param  {Function}    callback        Standard callback function
 * @param  {Object}      callback.err    An error that occurred, if any
 */
var refresh = module.exports.refresh = function(callback) {
    _exec('refresh', client.refresh(index, null), callback);
};

/**
 * Create a type mapping that can be searched. The type mappings use the elastic search type mapping specification, as described
 * in the ElasticSearch documentation: http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping.html
 *
 * @param  {String}    typeName            The name of the type. Should be unique across the application.
 * @param  {Object}    fieldProperties     The field schema properties for the type, as per ElasticSearch mapping spec.
 * @param  {Object}    [opts]              Advanced mapping options
 * @param  {String}    [opts._parent]      The parent document type, if applicable
 * @param  {Boolean}   [opts._source]      Whether or not the `_source` document should be enabled for storage and inclusion in queries. Defaults to `false`.
 * @param  {Function}  callback            Standard callback function
 * @param  {Object}    callback.err        An error that occurred, if any
 */
var putMapping = module.exports.putMapping = function(typeName, fieldProperties, opts, callback) {
    opts = opts || {};
    opts._source = (opts._source !== true);

    mappingExists(typeName, function(err, exists) {
        if (err) {
            return callback(err);
        } else if (exists) {
            return callback();
        }

        var data = {};
        data[typeName] = {
            '_source': {
                'enabled': opts._source
            },
            'properties': fieldProperties
        };

        if (opts._parent) {
            data[typeName]._parent = {'type': opts._parent};
        }

        log().info({'typeData': data}, 'Creating new search type mapping');

        return _exec('putMapping', client.putMapping(index, typeName, data), callback);
    });
};

/**
 * Determine whether or not the mapping exists.
 *
 * @param  {String}    typeName        The name of the type to map.
 * @param  {Function}  callback        Standard callback function
 * @param  {Object}    callback.err    An error that occurred, if any
 */
var mappingExists = module.exports.mappingExists = function(typeName, callback) {
    _exec('getMapping', client.getMapping(index, typeName, null), function(err, data) {
        if (err) {
            return callback(err);
        }

        return callback(null, (!_.isEmpty(data)));
    });
};

/**
 * Search ElasticSearch using the given query.
 *
 * @param  {Object}    query           The query object
 * @param  {Object}    options         Options to send with the query
 * @param  {Function}  callback        Standard callback function
 * @param  {Object}    callback.err    An error that occurred, if any
 * @param  {Object}    callback.data   The response of the query
 */
var search = module.exports.search = function(query, options, callback) {
    log().trace({ 'query': query }, 'Querying elastic search');
    return _exec('search', client.search(index, query, options), callback);
};

/**
 * Index the given document in ElasticSearch.
 *
 * @param  {String}    typeName        The type of document to index
 * @param  {String}    id              The id of the document to index
 * @param  {Object}    doc             The document to index
 * @param  {Object}    options         The querystring options to send with the index call
 * @param  {Function}  callback        Standard callback function
 * @param  {Object}    callback.err    An error that occurred, if any
 */
var index = module.exports.index = function(typeName, id, doc, options, callback) {
    log().trace({ 'typeName': typeName, 'id': id, 'document': doc, 'options': options }, 'Indexing a document');
    return _exec('index', client.index(index, typeName, doc, id, options), callback);
};

/**
 * Index a bulk number of documents in ElasticSearch.
 *
 * @param  {Object[]}  operations      An array of ordered operations, as per the ElasticSearch Bulk API specification
 * @param  {Function}  callback        Standard callback function
 * @param  {Object}    callback.err    An error that occurred, if any
 */
var bulk = module.exports.bulk = function(operations, callback) {
    var numOps = 0;
    for (var i = 0; i < operations.length; i++) {
        var meta = operations[i];
        var keys = _.keys(meta);
        // Verify this is a metadata line, then apply the index
        if (keys.length === 1 && (meta['create'] || meta['index'] || meta['delete'])) {
            numOps++;
            var opName = keys[0];
            meta[opName]['_index'] = index;
        }
    }

    log().trace({'operations': operations}, 'Performing a bulk set of %s operations.', numOps);
    return _exec('bulk', client.bulk(operations, null), callback);
};

/**
 * Delete the document identified by the document id from the index.
 *
 * @param  {String}    typeName        The type of document to delete
 * @param  {Object}    id              The id of the document to delete
 * @param  {Function}  callback        Standard callback function
 * @param  {Object}    callback.err    An error that occurred, if any
 */
var del = module.exports.del = function(typeName, id, callback) {
    log().trace({ 'typeName': typeName, 'documentId': id }, 'Deleting an index document.');
    return _exec('delete', client.deleteDocument(index, typeName, id, null), callback);
};

/**
 * Delete all documents matched by the given query
 *
 * @param  {String}     typeName        The type of document to delete
 * @param  {Object}     query           The query to invoke to match the documents to delete
 * @param  {Object}     options         The querystring to send with the delete call
 * @param  {Function}   callback        Standard callback function
 * @param  {Object}     callback.err    An error that occurred, if any
 */
var deleteByQuery = module.exports.deleteByQuery = function(typeName, query, options, callback) {
    log().trace({'typeName': typeName, 'query': query, 'options': options}, 'Deleting search documents by query');
    return _exec('deleteByQuery', client.deleteByQuery(index, typeName, query, options), callback);
};

/**
 * Execute a call to the ElasticSearchClient API.
 *
 * @param  {String}              name            The name of the method
 * @param  {ElasticSearchCall}   call            The call object that will be executed
 * @param  {Function}            callback        Standard callback function
 * @param  {Object}              callback.err    An error that occurred, if any
 * @param  {Object}              callback.data   The search response data, if any
 * @api private
 */
var _exec = function(name, call, callback) {
    callback = callback || function() {};

    Telemetry.incr('exec.' + name + '.count');
    var start = Date.now();
    var data = null;
    var err = null;

    // Grab the data
    call.data(function(_data) {
        data = _data;
    });

    // When finished, call the callback with the data
    call.done(function() {
        // Data should always be JSON, I think.
        try {
            data = JSON.parse(data);
            log().trace({ 'call': name, 'data': data }, 'Search execution completed.');
        } catch (ex) {
            log().trace({ 'call': name, 'data': data }, 'Search execution completed.');
            _logError(name, ex);
            return callback(new Error('Non-JSON body returned in response.'));
        }

        // ElasticSearch returns an object with an error attribute if there is an error
        if (data.error) {
            // We don't implicitly log this because it could be intended
            return callback(data);
        }

        Telemetry.appendDuration('exec.' + name + '.time', start);
        return callback(null, data);
    });

    // When there is an error, call the callback with the error
    call.error(function(err) {
        _logError(name, err);
        return callback(err);
    });

    call.exec();
};

/**
 * Logs the given error and applies telemetry udpates.
 *
 * @param  {String} callName The name of the call that err'd
 * @param  {Object} err      The error to log.
 * @api private
 */
var _logError = function(callName, err) {
    Telemetry.incr('exec.' + callName + '.error.count');
    log().error({ 'err': err }, 'Error executing %s query.', callName);
};


text:
using System.Drawing;
using System.IO;
using System.Reflection;
using ImageTools.ImageStorageFileFormats;

namespace ImageTools.Utilities
{
	public static class Load
	{
		public static Bitmap FromFile(string filePath)
		{
            if (string.IsNullOrWhiteSpace(filePath)) return null;
            if (!File.Exists(filePath)) {
                var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                filePath = Path.Combine(basePath??"", filePath);
            }

            if (WaveletImageFormat.IsWaveletFile(filePath))
            {
	            return WaveletImageFormat.LoadFile(filePath);
            }

            using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            using var bmp = Image.FromStream(fs);

            return new Bitmap(bmp);
        }

        public static bool FileExists(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath)) return false;
            if (!File.Exists(filePath)) {
                var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                filePath = Path.Combine(basePath??"", filePath);
            }
            return File.Exists(filePath);
        }

        public static string FullPath(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath)) return filePath;
            if (!File.Exists(filePath)) {
                var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                filePath = Path.Combine(basePath??"", filePath);
            }
            return Path.GetFullPath(filePath).Replace("\\","/");
        }
    }
}


text:
<?php

namespace Elastica\Test\Filter;

use Elastica\Filter\Range;
use Elastica\Test\Base as BaseTest;

class RangeTest extends BaseTest
{
    public function testAddField()
    {
        $rangeFilter = new Range();
        $returnValue = $rangeFilter->addField('fieldName', array('to' => 'value'));
        $this->assertInstanceOf('Elastica\Filter\Range', $returnValue);
    }

    public function testToArray()
    {
        $field = 'field_name';
        $range = array('gte' => 10, 'lte' => 99);

        $filter = new Range();
        $filter->addField($field, $range);
        $expectedArray = array('range' => array($field => $range));
        $this->assertEquals($expectedArray, $filter->toArray());
    }

    public function testSetExecution()
    {
        $field = 'field_name';
        $range = array('gte' => 10, 'lte' => 99);
        $filter = new Range('field_name', $range);

        $filter->setExecution('fielddata');
        $this->assertEquals('fielddata', $filter->getParam('execution'));

        $returnValue = $filter->setExecution('index');
        $this->assertInstanceOf('Elastica\Filter\Range', $returnValue);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ui.MainActivity">
    <item
        android:id="@+id/action_popular"
        android:orderInCategory="1"
        android:title="@string/action_popular" />
    <item
        android:id="@+id/action_top_rated"
        android:orderInCategory="2"
        android:title="@string/action_top_rated" />
    <item
        android:id="@+id/action_favorite"
        android:orderInCategory="3"
        android:title="@string/action_favorite" />
</menu>


text:
var _displayMessage = function(data) {
  var text = data.text;
  var suggestions = data.classifications;
  var grant_id = data.grant_id;

  $("#messageText").text(text);
  // TODO: Make message ID a hidden field
  $("#grantId").text(grant_id);

  // Display machine suggestion(s)
  var suggestedClassificationHtml = "";
  suggestedClassificationHtml += "
";
  for (var i=0; i < suggestions.length; i++) {
    suggestedClassificationHtml += '
';
    suggestedClassificationHtml += suggestions[i].category;
    suggestedClassificationHtml += " (Confidence: " + suggestions[i].confidence + ")";
    suggestedClassificationHtml += '
';
  }
  suggestedClassificationHtml += "
";
  $("#suggestedClassification").html(suggestedClassificationHtml);

  // Update pre-selected item in the dropdown menu to match most-likely machine suggestion
  var machine_suggestion = suggestions[0].category;
  // First letter corresponds to a top_level category suggestion
  $( "#categorySelect" ).val(machine_suggestion.substr(0,1))
  $( "#categorySelect" ).change() // Trigger change() event to prompt update to subcategory options
  $( "#subcategorySelect" ).val(machine_suggestion)

  // Display human annotated category, if any
  var human_label = "";
  if (data['human_labelled_category'] !== undefined && data['human_labelled_category'] !== null) {
    human_label = " (Manual label: " + data['human_labelled_category'] + ")";
    // Overwrite machine suggestion with human label
    $( "#categorySelect" ).val(data['human_labelled_category']);
  }
  $("#humanClassification").text(human_label);
}

// Fetch message from api/message endpoint
var getMessage = function() {
  console.log( "GET api/message: fetching (new) text..." );
  $.get("api/message", function( data ) {
    console.log("got message:", data);
    _displayMessage(data);
  });
}

// `data` should include:
//  - id
//  - (text)
//  - classification
//  - (confidence = 1)
//  - (user who classified it)

var _readMessageValuesFromUI = function() {
  // TODO: read message ID in hidden field
  // TODO: read message text (optional if ID exists)
  return {
    "text" : $("#messageText").text(),
    "grant_id" : $("#grantId").text(),
    "category" : $( "#subcategorySelect" ).val(),
  };
}

var postMessage = function() {
  var data = _readMessageValuesFromUI();
  $.post("api/message", data, function() {
    console.log( "POST api/message: saving a text classification..." );
  }, "json");
}

// displaySubcategories - takes a category_id (a letter) and updates subcategory dropdown
// to only show appropriate choices for that category
var displaySubcategories = function(category_id) {
  $('#subcategorySelect option').hide()
  // Show ones whose category starts with category_id
  $('#subcategorySelect option[value^="' + category_id + '"]').show()
}

// On page ready...
$(function() {
  // update subcategories when main category is change
  $('#categorySelect').change(function() {
    displaySubcategories(this.value);
  });

  // Load first message
  getMessage();
  $('#container').show();

  // Setup listeners - when user clicks next task
  // save current Message and get the next Message
  $('input.nextTask').click(function() {
    console.log("clicked save");
    postMessage();
    getMessage();
  });

});


text:
"use strict";

var test = require('tape');
var mapnik = require('../');

function cleanXml(xml) {
  return xml.replace('\n','').split(' ').join('');
}

test('should be accessible from map', (assert) => {
  var map = new mapnik.Map(1, 1);
  map.loadSync('./test/support/extra_arbitary_map_parameters.xml');
  var params = map.parameters;
  assert.equal(params.decimal, 0.999);
  assert.equal(params.integer, 10);
  assert.equal(params.key, 'value2');
  assert.equal(params.integer_one, 1);
  assert.equal(params.integer_zero, 0);
  assert.equal(params.boolean_yes, true);
  assert.equal(params.boolean_no, false);
  assert.equal(params.boolean_on, true);
  assert.equal(params.boolean_off, false);
  assert.equal(params.boolean_true, true);
  assert.equal(params.boolean_false, false);
  assert.end();
});

test('should be settable on map', (assert) => {
  var map = new mapnik.Map(1, 1);
  var actual = cleanXml(map.toXML());
  var expected = cleanXml('<?xml version="1.0" encoding="utf-8"?>\n<Map srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"/>\n');
  assert.equal(actual, expected);
  map.parameters = {'a': 'b','bool':false, 'num': 12.2, 'num2': 1};
  actual = cleanXml(map.toXML());
  if (mapnik.versions.mapnik_number >= 300000) {
    expected = cleanXml('<?xml version="1.0" encoding="utf-8"?>\n<Map srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">\n    <Parameters>\n        <Parameter name="a">b</Parameter>\n    <Parameter name="bool">false</Parameter>\n    <Parameter name="num">12.2</Parameter>\n    <Parameter name="num2">1</Parameter>\n</Parameters>\n</Map>\n');
  } else {
    expected = cleanXml('<?xml version="1.0" encoding="utf-8"?>\n<Map srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">\n    <Parameters>\n        <Parameter name="a" type="string">b</Parameter>\n    </Parameters>\n</Map>\n');
  }
  assert.equal(actual, expected);
  assert.end();
});


text:
<import resource="classpath:alfresco/templates/webscripts/org/alfresco/cmis/lib/read.lib.js">

script:
{
    // locate node
    var object = getObjectFromUrl();
    if (object.node == null)
    {
        break script;
    }
    model.node = object.node;

    if (model.node.isDocument)
    {
        status.code = 404;
        status.message = "Object " + object.ref + " is not a folder";
        status.redirect = true;
        break script;
    }

    // property filter
    model.filter = args[cmisserver.ARG_FILTER];
    if (model.filter === null)
    {
        model.filter = "*";
    }

    // rendition filter
    model.renditionFilter = args[cmisserver.ARG_RENDITION_FILTER];
    if (model.renditionFilter === null || model.renditionFilter.length == 0)
    {
        model.renditionFilter = "cmis:none";
    }

    // depth
    var depth = args[cmisserver.ARG_DEPTH];
    model.depth = (depth === null) ? 1 : parseInt(depth);

    // include allowable actions
    var includeAllowableActions = args[cmisserver.ARG_INCLUDE_ALLOWABLE_ACTIONS];
    model.includeAllowableActions = (includeAllowableActions == "true" ? true : false);

    // include relationships
    model.includeRelationships = args[cmisserver.ARG_INCLUDE_RELATIONSHIPS];
    if (model.includeRelationships == null || model.includeRelationships.length == 0)
    {
        model.includeRelationships = "none";
    }
}


text:
require 'strscan'
require_relative 'comment_parser'

# @see Parser::Parser
# @see Parser::CommentParser
module Parser

  NO_BR = /((?!\n)\s)/
  ALL = /./m

  # Multiline Comments
  M_START = /\/\*+/

  # End of multiline comment with all leading whitespaces (no breaks)
  M_END = /#{NO_BR}*\*+\//

  # Singleline Comments
  S_START = /\/\//
  S_END = /\n/

  LINE_START = /(#{NO_BR})*\*+#{NO_BR}?/
  LINE_END = /\n/
  EMPTY_LINE = /^\s*$/

  # CAUTION: \s can contain breaks "\n"
  TOKENLINE_START = /\s*@/
  TOKENLINE = /
    #{TOKENLINE_START}
      (?<name>\w+)
      (?:#{NO_BR}?(?<content>#{ALL}+)|$)
    /x

  # String delimiter
  S_STRING = /'/
  D_STRING = /"/

  REGEXP_START = /\/[^\/]/
  REGEXP_END = /\//

  NON_COMMENT_PATTERNS = {
    S_STRING     => S_STRING,
    D_STRING     => D_STRING,
    REGEXP_START => REGEXP_END
  }

  NON_CODE_PATTERNS = {
    M_START      => M_END,
    S_START      => S_END,
    S_STRING     => S_STRING,
    D_STRING     => D_STRING,
    REGEXP_START => REGEXP_END
  }

  # ![Parser Overview](../img/md_parse_js.png)
  #
  # Turns the incoming javascript-source into a stream of {Parser::Comment comments}. Those comments
  # contain the parsed doclines, which are simply all lines found in the comment and all tokenlines.
  #
  # A tokenline starts with a token like `@token` and can span over multiple lines, if it is intended
  # by two spaces.
  #
  # The comment-scope (i.e. the javascript-language-scope beginning in the next line) will be preserved
  # as `source` of the comment as well.
  #
  # For example it extracts to Comments from the following source
  #
  #     /**
  #      * @object Person
  #      */
  #     var Person = {}
  #
  #     /**
  #      * Some documentation here, and there
  #      *
  #      * @object Person.config
  #      */
  #     Person.config = {};
  #
  #     #=> [#<Parser::Comment tokenlines=1 doclines=0>, #<Parser::Comment tokenlines=1 doclines=2>]
  #
  # @see Parser::CommentParser
  class Parser

    attr_reader :filepath, :offset

    # A new StringScanner instance will be used to {#parse parse} the given `input`.
    #
    # @param [String] input
    def initialize(input, args = {})

      raise Exception, "Expected input to be a String, got #{input.class}" unless input.is_a? String

      # Default Values
      @filepath = args[:filepath]  || "No File specified"
      @offset   = args[:offset]    || -1 # we are adding 1 later

      # clean input and convert windows linebreaks to normal ones
      @to_parse = input.force_encoding("UTF-8").gsub(/\r\n/, "\n")
      @scanner = StringScanner.new @to_parse

      @comments = []
    end

    # Recursivly parses the {#initialize given input} and thereby ignores strings and regular-
    # expressions.
    #
    # @todo Rewrite to use {StringScanner#intelligent_skip_until}
    # @return [Array<Parser::Comment>] the parsed comment-stream
    def parse()
      @scanner.skip /\s/
      @scanner.skip_until /#{M_START}|#{S_START}|#{NON_COMMENT_PATTERNS.keys.join('|')}|$/

      found = @scanner.matched

      if found.match M_START
        parse_comment_until(M_END)

      elsif found.match S_START
        parse_comment_until(S_END)

      else
        matched_pattern = NON_COMMENT_PATTERNS.detect do |start_pattern, end_pattern|
          found.match start_pattern
        end
        @scanner.skip_escaping_until matched_pattern.last unless matched_pattern.nil?
      end

      if @scanner.eos?
        return @comments
      else
        parse
      end
    end

    # Reads the contents of `path`, creates a new `Parser` and starts parsing all at once
    def self.parse_file(path)
      stream = File.read path
      Parser.new(stream, :filepath => path).parse
    end

    protected

    def parse_comment_until(ending)
      content = @scanner.scan_until_ahead ending     # this consumes ending, but don't includes it
      comment = CommentParser.new(content).parse unless content.nil?

      # only proceed, if it is a tokenized comment
      return parse unless comment and comment.has_tokens?

      # First skip some white spaces, that may occure after comment
      @scanner.skip /#{NO_BR}+/

      # search scope for that comment
      @scanner.skip /\n/

      scope = @scanner.save_scanned { find_scope }

      # FIX: UTF-8 characters destroyed the string-slicing, because scanner is working with
      # byte-positions only
      @to_parse.force_encoding "ISO-8859-1"

      code_line = @to_parse.line_of(scope.min) + @offset + 1
      source = @to_parse[scope]

      # Switch back to UTF-8
      @to_parse.force_encoding "UTF-8"

      # Add Metadata
      comment.add_meta_data @filepath, source, code_line

      # Save Comment
      @comments << comment

      comment.add_children Parser.new(source, :filepath => @filepath, :offset => code_line-1).parse
    end

    def find_scope(scope_stack = [], ignore_line_end = false)

      if ignore_line_end
        return if scope_stack.empty?
        @scanner.skip /\s/
      end

      # adding |$ only if we don't ignore line_ends (which is most of the time)
      @scanner.intelligent_skip_until /\{|\(|\}|\)#{"|$" unless ignore_line_end}/

      match = @scanner.matched

      case match
      when '{'
        find_scope(scope_stack << '}', ignore_line_end)

      when '('
        find_scope(scope_stack << ')', ignore_line_end)

      when '}', ')'
        if(scope_stack.last == match)
          scope_stack.pop
          find_scope(scope_stack, ignore_line_end)
        else
          # currently just ignore non matching closing pairs
          puts "I'm ignoring #{match} at #{@scanner.pos} of #{@filepath}"
        end
      else

        if ignore_line_end
          if not @scanner.eos?
            find_scope(scope_stack, ignore_line_end)

          elsif not scope_stack.empty?
            raise "Unmatched Scope-Stack: #{scope_stack}"
          end

        else
          find_scope(scope_stack, true)  unless scope_stack.empty?
        end
      end
    end

  end

end

# We have to extend StringScanner a little bit to fit our needs.
#
# @see Parser::Parser
# @see Parser::CommentParser
class StringScanner

  # returns the string until `pattern` matches, then consums `pattern`
  #
  # @example
  #   scanner = StringScanner.new("hello     world")
  #   scanner.scan_until_ahead(/\s+/) #=> "hello"
  #   scanner.pos #=> 5
  #
  # @param [Regexp] pattern the pattern to scan until
  # @return [String] the String before `pattern`
  def scan_until_ahead(pattern)
    content = self.scan_until /(?=(#{pattern}))/
    self.skip pattern
    return content
  end

  # will stop to scan at the specified pattern or at eos and returns the consumed string.
  #
  # @param [Regexp] pattern the pattern to scan for
  # @return [String] the String before `pattern`
  def scan_until_or_end(pattern)
    self.scan_until(pattern) or self.scan_until(/$/)
  end

  # skips content within comments, strings and regularexpressions
  def intelligent_skip_until(pattern)

    self.skip_escaping_until(/#{pattern}|#{Parser::NON_CODE_PATTERNS.keys.join('|')}/)

    found = self.matched

    raise end_of_string_error(pattern) if self.matched.nil?

    Parser::NON_CODE_PATTERNS.each do |start_pattern, end_pattern|
      if found.match start_pattern
        self.skip_escaping_until end_pattern
        return self.intelligent_skip_until pattern
      end
    end
  end

  def save_scanned
    pos_start = self.pos
    yield
    pos_end = self.pos
    Range.new(pos_start, pos_end)
  end

  def skip_escaping_until(pattern)

    self.skip_until(/\\|#{pattern}/)

    raise end_of_string_error(pattern) if self.matched.nil?

    if self.matched.match /\\/
      self.getch
      skip_escaping_until(pattern)
    end
  end

  protected

  def end_of_string_error(pattern)
    Error.new "Unexpected end of String, expected: #{pattern.inspect} in \"#{self.string}\" at pos:#{self.pos}"
  end

end

class String
  def line_of(pos)
    self[0..pos].count "\n"
  end
end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using ApprovalTests;
using ApprovalTests.Reporters;
using Mono.Cecil;
using NUnit.Framework;

[TestFixture]
[UseReporter(typeof(VisualStudioReporter))]
public class InMemoryTests
{
    Assembly assembly;
    string beforeAssemblyPath;
    string afterAssemblyPath;
    ModuleDefinition moduleDefinition;
    string isolatedPath;

    public InMemoryTests()
    {
        beforeAssemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll");
        var directoryName = Path.GetDirectoryName(@"..\..\..\Debug\");
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
        directoryName = directoryName.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "InMemory.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);
        File.Copy(beforeAssemblyPath.Replace(".dll", ".pdb"), afterAssemblyPath.Replace(".dll", ".pdb"), true);

        var readerParams = new ReaderParameters() { ReadSymbols = true };

        moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath, readerParams);

        var references = new List<string>
            {
                beforeAssemblyPath.Replace("AssemblyToProcess", "AssemblyToReference"),
                beforeAssemblyPath.Replace("AssemblyToProcess", "AssemblyToReferencePreEmbed"),
                Path.ChangeExtension(beforeAssemblyPath.Replace("AssemblyToProcess", "ExeToReference"), "exe"),
                Path.Combine(directoryName, "AssemblyToReferenceMixed.dll"),
            };

        var assemblyToReferenceDirectory = Path.GetDirectoryName(beforeAssemblyPath.Replace("AssemblyToProcess", "AssemblyToReference"));
        var assemblyToReferenceResources = Directory.GetFiles(assemblyToReferenceDirectory, "*.resources.dll", SearchOption.AllDirectories);
        references.AddRange(assemblyToReferenceResources);

        using (var weavingTask = new ModuleWeaver
            {
                ModuleDefinition = moduleDefinition,
                AssemblyResolver = new MockAssemblyResolver(),
                Config = XElement.Parse("<Costura Unmanaged32Assemblies='AssemblyToReferenceMixed' PreloadOrder='AssemblyToReferenceNative' />"),
                ReferenceCopyLocalPaths = references,
                AssemblyFilePath = beforeAssemblyPath
            })
        {
            weavingTask.Execute();
            var writerParams = new WriterParameters() { WriteSymbols = true };
            moduleDefinition.Write(afterAssemblyPath, writerParams);
        }

        isolatedPath = Path.Combine(Path.GetTempPath(), "CosturaIsolatedMemory.dll");
        File.Copy(afterAssemblyPath, isolatedPath, true);
        File.Copy(afterAssemblyPath.Replace(".dll", ".pdb"), isolatedPath.Replace(".dll", ".pdb"), true);
        assembly = Assembly.LoadFile(isolatedPath);
    }

    [Test]
    public void Simple()
    {
        var instance2 = assembly.GetInstance("ClassToTest");
        Assert.AreEqual("Hello", instance2.Foo());
    }

    [Test]
    public void SimplePreEmbed()
    {
        var instance2 = assembly.GetInstance("ClassToTest");
        Assert.AreEqual("Hello", instance2.Foo2());
    }

    [Test]
    public void Exe()
    {
        var instance2 = assembly.GetInstance("ClassToTest");
        Assert.AreEqual("Hello", instance2.ExeFoo());
    }

    [Test]
    public void ThrowException()
    {
        try
        {
            var instance = assembly.GetInstance("ClassToTest");
            instance.ThrowException();
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.StackTrace);
            Assert.IsTrue(exception.StackTrace.Contains("ClassToReference.cs:line"));
        }
    }

    [Test]
    public void Native()
    {
        var instance1 = assembly.GetInstance("ClassToTest");
        Assert.AreEqual("Hello", instance1.NativeFoo());
    }

    [Test]
    public void Mixed()
    {
        var instance1 = assembly.GetInstance("ClassToTest");
        Assert.AreEqual("Hello", instance1.MixedFoo());
    }

    [Test]
    public void MixedPInvoke()
    {
        var instance1 = assembly.GetInstance("ClassToTest");
        Assert.AreEqual("Hello", instance1.MixedFooPInvoke());
    }

    [Test]
    public void EnsureOnly1RefToMscorLib()
    {
        Assert.AreEqual(1, moduleDefinition.AssemblyReferences.Count(x => x.Name == "mscorlib"));
    }

    [Test]
    public void EnsureCompilerGeneratedAttribute()
    {
        Assert.IsTrue(moduleDefinition.GetType("Costura.AssemblyLoader").Resolve().CustomAttributes.Any(attr => attr.AttributeType.Name == "CompilerGeneratedAttribute"));
    }

#if DEBUG
    [Test]
    public void TemplateHasCorrectSymbols()
    {
        Approvals.Verify(Decompiler.Decompile(afterAssemblyPath, "Costura.AssemblyLoader"));
        //Approvals.Verify(Decompiler.Decompile(Path.GetFullPath(@"..\..\..\Template\bin\Debug\Template.dll"), "Common"));
    }
#endif

    [Test]
    public void PeVerify()
    {
        Verifier.Verify(beforeAssemblyPath, afterAssemblyPath);
    }

    [Test]
    public void TypeReferencedWithPartialAssemblyNameIsLoadedFromExistingAssemblyInstance()
    {
        var instance = assembly.GetInstance("ClassToTest");
        var assemblyLoadedByCompileTimeReference = instance.GetReferencedAssembly();
        var typeLoadedWithPartialAssemblyName = Type.GetType("ClassToReference, AssemblyToReference");
        Assume.That(typeLoadedWithPartialAssemblyName, Is.Not.Null);

        Assert.AreSame(assemblyLoadedByCompileTimeReference, typeLoadedWithPartialAssemblyName.Assembly);
    }
}


text:
package patterncommand.simple;

import patterncommand.GarageDoor;
import patterncommand.GarageDoorOpenCommand;
import patterncommand.Light;
import patterncommand.LightOnCommand;

/**
 * Project: PatternsBook
 * Date: 06.09.13
 * Time: 0:21
 *
 * @author Skurishin Vladislav
 *
 * Паттерн Команда:
 * инкапсулирует запрос в виде объекта, делая
 * возможным параметризацию клиентских объектов
 * с другими запросами, организацию очереди или
 * регистрацию запросов, а так же поддержку отмены операций.
 *
 */
public class RemoteControlTest {
    public static void main(String args[]){
        SimpleRemoteControl remoteControl = new SimpleRemoteControl();
        Light light = new Light();
        GarageDoor garageDoor = new GarageDoor();
        GarageDoorOpenCommand garageOpen = new GarageDoorOpenCommand(garageDoor);
        LightOnCommand lightOn = new LightOnCommand(light);

        remoteControl.setCommand(lightOn);
        remoteControl.buttonWasPressed();
        remoteControl.setCommand(garageOpen);
        remoteControl.buttonWasPressed();
    }
}


text:
package com.google.cloud.healthcare.imaging.dicomadapter.monitoring;

public enum Event implements IMonitoringEvent {
  STARTED(Constants.prefix + "started"),

  CSTORE_REQUEST(Constants.prefix + "cstore_requests"),
  CSTORE_ERROR(Constants.prefix + "cstore_errors"),
  CSTORE_BACKUP_ERROR(Constants.prefix + "cstore_backup_errors"),
  CSTORE_BYTES(Constants.prefix + "cstore_bytes"),

  CFIND_REQUEST(Constants.prefix + "cfind_requests"),
  CFIND_ERROR(Constants.prefix + "cfind_errors"),
  CFIND_CANCEL(Constants.prefix + "cfind_cancels"),
  CFIND_QIDORS_REQUEST(Constants.prefix + "cfind_qidors_requests"),
  CFIND_QIDORS_ERROR(Constants.prefix + "cfind_qidors_errors"),

  CMOVE_REQUEST(Constants.prefix + "cmove_requests"),
  CMOVE_ERROR(Constants.prefix + "cmove_errors"),
  CMOVE_WARNING(Constants.prefix + "cmove_warnings"),
  CMOVE_CANCEL(Constants.prefix + "cmove_cancels"),
  CMOVE_QIDORS_REQUEST(Constants.prefix + "cmove_qidors_requests"),
  CMOVE_QIDORS_ERROR(Constants.prefix + "cmove_qidors_errors"),
  CMOVE_CSTORE_REQUEST(Constants.prefix + "cmove_cstore_requests"),
  CMOVE_CSTORE_ERROR(Constants.prefix + "cmove_cstore_errors"),
  CMOVE_CSTORE_BYTES(Constants.prefix + "cmove_cstore_bytes"),

  COMMITMENT_REQUEST(Constants.prefix + "commitment_requests"),
  COMMITMENT_ERROR(Constants.prefix + "commitment_errors"),
  COMMITMENT_QIDORS_ERROR(Constants.prefix + "commitment_qidors_errors");

  private final String metricName;

  Event(String metricName) {
    this.metricName = metricName;
  }

  public String getMetricName() {
    return metricName;
  }

  private static class Constants {

    private static final String prefix = "custom.googleapis.com/dicomadapter/import/";
  }
}


text:
package org.robolectric.shadows;

import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.TestRunners;

import static org.assertj.core.api.Assertions.assertThat;
import static org.robolectric.Shadows.shadowOf;

@RunWith(TestRunners.WithDefaults.class)
public class ShadowAccessibilityWindowInfoTest {
  private AccessibilityWindowInfo window;
  private ShadowAccessibilityWindowInfo shadow;

  @Before
  public void setUp() {
    window = ShadowAccessibilityWindowInfo.obtain();
    assertThat(window == null).isEqualTo(false);
    shadow = shadowOf(window);
  }

  @Test
  public void shouldNotHaveRootNode() {
    assertThat(shadow.getRoot() == null).isEqualTo(true);
  }

  @Test
  public void shouldHaveAssignedRoot() {
    AccessibilityNodeInfo node = AccessibilityNodeInfo.obtain();
    shadow.setRoot(node);
    assertThat(shadow.getRoot()).isEqualTo(node);
  }
}


text:
var assert = require('assert');

/**
 * Test strict equality of all elements in two arrays.
 * @param {Array} a
 * @param {Array} b
 */
module.exports = function strictEqualArray(a, b) {
  assert.strictEqual(a.length, b.length);

  for (var i = 0; i < a.length; a++) {
    assert.strictEqual(a[i], b[i]);
  }
};


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Hedysarum glomeratum F.Dietr.

### Remarks
null


text:
using System;
using System.IO;
using Cassette.Utilities;

namespace Cassette.HtmlTemplates
{
    public class RegisterTemplateWithJQueryTmpl : IAssetTransformer
    {
        public delegate RegisterTemplateWithJQueryTmpl Factory(HtmlTemplateBundle bundle);

        readonly HtmlTemplateBundle bundle;
        readonly IHtmlTemplateIdStrategy idStrategy;

        public RegisterTemplateWithJQueryTmpl(HtmlTemplateBundle bundle, IHtmlTemplateIdStrategy idStrategy)
        {
            this.bundle = bundle;
            this.idStrategy = idStrategy;
        }

        public Func<Stream> Transform(Func<Stream> openSourceStream, IAsset asset)
        {
            return delegate
            {
                var id = idStrategy.HtmlTemplateId(bundle, asset);
                var template = openSourceStream().ReadToEnd();
                return string.Format("jQuery.template('{0}', {1});{2}", id, template, Environment.NewLine).AsStream();
            };
        }
    }
}