text:
Ext.namespace("GeoNode");

GeoNode.SearchTable = Ext.extend(Ext.util.Observable, {
    selectHeaderText: 'UT: Select',
    nameHeaderText: 'UT: Name',
    titleHeaderText: 'UT: Title',
    selectText: 'UT: Select:',
    selectAllText: 'UT: All',
    selectNoneText: 'UT: None',
    previousText: 'UT: Prev',
    nextText: 'UT: Next',
    ofText: 'UT: of',
    noResultsText: 'UT: Your search did not match any items.',
    searchLabelText: 'UT: Search Data',
    searchButtonText: 'UT: Search',
    showingText: 'UT: Showing',
    loadingText: 'UT: Loading',
    permalinkText: 'UT: permalink',
    unviewableTooltip: 'UT: Unviewable Data',
    remoteTooltip: 'UT: Remote Data',

    constructor: function(config) {
        this.addEvents('load');
        Ext.apply(this, config);
        this.initFromQuery();
        this.loadData();
    },

    loadData: function() {

        this.searchStore = new Ext.data.JsonStore({
            url: this.searchURL,
            root: 'rows',
            idProperty: 'uuid',
            remoteSort: true,
            totalProperty: 'total',
            fields: [
                {name: 'name', type: 'string'},
                {name: 'title', type: 'string'},
                {name: 'uuid', type: 'string'},
                {name: 'abstract', type: 'string'},
                {name: 'keywords'},
                {name: 'detail', type: 'string'},
                {name: 'attribution'},
                {name: 'download_links'},
                {name: 'metadata_links'},
                {name: 'bbox'},
                {name: '_local'},
                {name: '_permissions'}
            ]
        });
        this.searchStore.on('load', function() {
            this.updateControls();
            if (this.dataCart) {
                this.dataCart.reselect();
            }
            this.fireEvent('load', this);
        }, this);

        this.doLayout();
        this.doSearch();
    },

    initFromQuery: function() {
        if (!this.searchParams) {
            this.searchParams = {};
        }
        if (!this.searchParams.start) {
            this.searchParams.start = 0;
        }
        if (!this.searchParams.limit) {
            this.searchParams.limit = 25;
        }

        if (this.constraints) {
            for (var i = 0; i < this.constraints.length; i++) {
                this.constraints[i].initFromQuery(this, this.searchParams);
            }
        }
    },

    doSearch: function() {
        /* updates parameters from constraints and
           permforms a new search */
        this.searchParams.start = 0;
        if (this.constraints) {
            for (var i = 0; i < this.constraints.length; i++) {
                this.constraints[i].applyConstraint(this.searchParams);
            }
        }
        this._search(this.searchParams);
    },

    _search: function(params) {
       /* search with given parameters */
        this.disableControls();
        this.searchStore.load({params: params});
        this.updatePermalink(params);
    },

    loadNextBatch: function() {
        this.searchParams.start += this.searchParams.limit;
        this._search(this.searchParams);
    },

    loadPrevBatch: function() {
        this.searchParams.start -= this.searchParams.limit;
        if (this.searchParams.start < 0) {
            this.searchParams.start = 0;
        }
        this._search(this.searchParams);
    },

    disableControls: function() {
        this.nextButton.setDisabled(true);
        this.prevButton.setDisabled(true);
        this.pagerLabel.setText(this.loadingText);
    },

    updateControls: function() {
        var total = this.searchStore.getTotalCount();

        if (this.searchParams.start > 0) {
            this.prevButton.setDisabled(false);
        }
        else {
            this.prevButton.setDisabled(true);
        }

        if (this.searchParams.start + this.searchParams.limit < total) {
            this.nextButton.setDisabled(false);
        }
        else {
            this.nextButton.setDisabled(true);
        }

        var minItem = this.searchParams.start + 1;
        var maxItem = minItem + this.searchParams.limit - 1;
        if (minItem > total) {
            minItem = total;
        }
        if (maxItem > total) {
            maxItem = total;
        }
        this.pagerLabel.setText(this.showingText + ' ' + minItem  +
                                '-' + maxItem + ' ' + this.ofText + ' ' +
                                total);
    },

    updatePermalink: function() {
        if (this.permalink) {
            this.permalink.href = Ext.urlAppend(this.permalinkURL, Ext.urlEncode(this.searchParams));
        }
    },

    updateQuery: function() {
        /* called when main search query changes */
        this.searchParams.q = this.queryInput.getValue();
        this.doSearch();
    },

    hookupSearchButtons: function(el) {
        var root = Ext.get(el);
        var buttons = root.query('.search-button');
        for (var i = 0; i < buttons.length; i++) {
            var text = buttons[i].innerHTML || this.searchButtonText;
            Ext.get(buttons[i]).update('');
            var searchButton = new Ext.Button({
                text: text,
                renderTo: buttons[i]
            });
            searchButton.on('click', this.doSearch, this);
        }
    },

    doLayout: function() {

        var widgetHTML =
        '
' +
        '

' +
        '

' +
        '

' +
        '
';

        var el = Ext.get(this.renderTo);
        el.update(widgetHTML);
        var input_el = el.query('.search-input')[0];
        var table_el = el.query('.search-table')[0];
        var controls_el = el.query('.search-controls')[0];

        var expander = new GeoNode.SearchTableRowExpander({fetchURL: this.layerDetailURL});

        tableCfg = {
            store: this.searchStore,
            plugins: [expander],
            autoExpandColumn: 'title',
            viewConfig: {
                autoFill: true,
                forceFit: true,
                emptyText: this.noResultsText
            },
            autoHeight: true,
            renderTo: table_el
        };

        var unviewableTooltip = this.unviewableTooltip;
        var remoteTooltip = this.remoteTooltip;

        var columns = [
            expander,
            /*
            {header: this.nameHeaderText,
             dataIndex: 'name',
             hidden: true,
             id: 'name',
             width: 35
            },*/
            {
                header: this.titleHeaderText,
                dataIndex: 'title',
                id: 'title',
                renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                    var is_local = record.get('_local');
                    var detail = record.get('detail');

                    /* do not show detail link for layers without read permission */
                    if (is_local) {
                        var permissions = record.get('_permissions');
                        if (permissions.view != true) {
                            detail = '';
                        }
                    }
                    if (detail) {
                        detail = '' + value + '';
                    }
                    else {
                        detail = value;
                    }
                    return detail;
                }
            },
            {
                dataIndex: '_local',
                id: 'layer_info',
                width: 6,
                resizable: false,
                renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                    var is_local = record.get('_local');
                    var info_type = '';
                    var tooltip = '';

                    /* do not show detail link for layers without read permission */
                    if (is_local) {
                        var permissions = record.get('_permissions');
                        if (permissions.view != true) {
                            detail = '';
                            info_type = 'unviewable-layer';
                            tooltip = unviewableTooltip;
                        }
                        else {
                            info_type = 'info-layer';
                        }
                    }
                    else {
                        info_type = 'remote-layer';
                        tooltip = remoteTooltip;
                    }
                    info = '';
                    return info;
                }
            }
        ];

        if (this.trackSelection == true) {
            sm = new Ext.grid.CheckboxSelectionModel({
                checkOnly: true,
                renderer: function(v, p, record){
                    /*
                     *  A bit of a hack. CheckboxSelectionModel's
                     *  mousedown selection behavior
                     *  is tied to rendered div's class.
                     */
                    var permissions = record.get('_permissions');
                    if (permissions.view != true) {
                        return '

'
                    } else {
                        return '

';
                    }
                },
                listeners: {
                    'beforerowselect' : function(sm, rowIndex, keepExisting, record){
                        var permissions = record.get('_permissions');
                        if (permissions.view != true) {
                            return false;
                        }
                    }
                }
            });

            this.dataCart = new GeoNode.DataCartStore({selModel: sm});
            columns.push(sm);
            tableCfg.selModel = sm;
        }
        var colModel = new Ext.grid.ColumnModel({
            defaults: {sortable: false, menuDisabled: true},
            columns: columns
        });
        tableCfg.colModel = colModel;

        this.table = new Ext.grid.GridPanel(tableCfg);

        this.queryInput = new Ext.form.TextField({
                        fieldLabel: this.searchLabelText,
                        name: 'search',
                        allowBlank:true,
                        width: 350
                     });

        this.queryInput.on('specialkey', function(field, e) {
            if (e.getKey() == e.ENTER) {
                this.updateQuery();
            }
        }, this);
        var searchButton = new Ext.Button({
            text: this.searchButtonText
        });
        searchButton.on('click', this.updateQuery, this)

        var searchForm = new Ext.Panel({
             frame:false,
             border: false,
             layout: new Ext.layout.HBoxLayout({defaultMargins: {
                 top: 10,
                 bottom: 10,
                 left: 0,
                 right: 10
             }}),
             items: [this.queryInput,
                     searchButton
             ]
         });
         searchForm.render(input_el);

         this.prevButton =  new Ext.Button({text: this.previousText});
         this.prevButton.on('click', this.loadPrevBatch, this);

         this.nextButton =  new Ext.Button({text: this.nextText});
         this.nextButton.on('click', this.loadNextBatch, this);

         this.pagerLabel = new Ext.form.Label({text: ""});

         var controls = new Ext.Panel({
              frame:false,
              border: false,
              layout: new Ext.layout.HBoxLayout({defaultMargins: {
                  top: 10,
                  bottom: 10,
                  left: 0,
                  right: 10
              }}),
              items: [this.prevButton, this.nextButton, this.pagerLabel]
          });
          controls.render(controls_el);
          this.permalink = Ext.query('a.permalink')[0];

          this.disableControls();

          if (this.searchParams.q) {
              this.queryInput.setValue(this.searchParams.q);
          }
          this.updatePermalink();
}

});


text:
Query features on a map using an Arcade expression.

![QueryFeaturesWithArcadeExpression](QueryFeaturesWithArcadeExpression.jpg)

## Use case

Arcade is a portable, lightweight, and secure expression language used to create custom content in ArcGIS applications. Like other expression languages, it can perform mathematical calculations, manipulate text, and evaluate logical statements. It also supports multi-statement expressions, variables, and flow control statements. What makes Arcade particularly unique when compared to other expression and scripting languages is its inclusion of feature and geometry data types. This sample uses an arcade expression to query the number of crimes in a neighborhood in the last 60 days.

## How to use the sample

Tap on any neighborhood to see the number of crimes in the last 60 days in a callout.

## How it works

1. Create a `PortalItem` using the URL and ID.
2. Create a `Map` using the portal item.
3. Set the visibility of all the layers to false, except for the layer named "RPD Beats  - City_Beats_Border_1128-4500".
4. Set up a lambda or a listener for clicks on the map.
5. Identify the visible layer where it is tapped or tapped on and get the feature.
6. Create an `ArcadeExpression` using the following string:

    ```cs
    "var crimes = FeatureSetByName($map, 'Crime in the last 60 days');\n" +
    "return Count(Intersects($feature, crimes));"
    ```

7. Create an `ArcadeEvaluator` using the Arcade expression and `ArcadeProfile.FormCalculation`.
8. Create a map of profile variables with the following key-value pairs. This will be passed to `ArcadeEvaluator.EvaluateAsync()` in the next step:

    ```cs
    {"$feature", identifiedFeature}
    {"$map", map}
    ```

9. Call `ArcadeEvaluator.EvaluateAsync()` on the Arcade evaluator object and pass the profile variables map.
10. Get the result from the `ArcadeEvaluationResult.Result` property.
11. Convert the result to a numerical value (integer) and populate the callout with the crime count.

## Relevant API

* ArcadeEvaluationResult
* ArcadeEvaluator
* ArcadeExpression
* ArcadeProfile
* Portal
* PortalItem

## About the data

This sample uses the [Crimes in Police Beats Sample](https://www.arcgis.com/home/item.html?id=14562fced3474190b52d315bc19127f6) ArcGIS Online Web Map which contains 3 layers for police stations, city beats borders, and crimes in the last 60 days as recorded by the Rochester, NY police department.

## Additional information

Visit [Getting Started](https://developers.arcgis.com/arcade/) on the *ArcGIS Developer* website to learn more about Arcade expressions.

## Tags

Arcade evaluator, Arcade expression, identify layers, portal, portal item, query

redpajama_set_name: RedPajamaGithub


text:
require "language/node"
require "json"

class Babel < Formula
  desc "Compiler for writing next generation JavaScript"
  homepage "https://babeljs.io/"
  url "https://registry.npmjs.org/@babel/core/-/core-7.15.8.tgz"
  sha256 "33091e6edf24ee719166645ba6807c1d179d28d88965977fe04da9c5ffadf397"
  license "MIT"

  bottle do
    sha256 cellar: :any_skip_relocation, all: "21de12960426e5e3f5350d6fdddfac2fd93fd2eb21bb5afc1d501241097911ad"
  end

  depends_on "node"

  resource "babel-cli" do
    url "https://registry.npmjs.org/@babel/cli/-/cli-7.15.7.tgz"
    sha256 "027d695a5ad68347b6f4fc7aac8ce66fe000576952a9ce38769cf12988f1a34a"
  end

  def install
    (buildpath/"node_modules/@babel/core").install Dir["*"]
    buildpath.install resource("babel-cli")

    cd buildpath/"node_modules/@babel/core" do
      system "npm", "install", *Language::Node.local_npm_install_args, "--production"
    end

    # declare babel-core as a bundledDependency of babel-cli
    pkg_json = JSON.parse(File.read("package.json"))
    pkg_json["dependencies"]["@babel/core"] = version
    pkg_json["bundleDependencies"] = ["@babel/core"]
    File.write("package.json", JSON.pretty_generate(pkg_json))

    system "npm", "install", *Language::Node.std_npm_install_args(libexec)
    bin.install_symlink Dir["#{libexec}/bin/*"]
  end

  test do
    (testpath/"script.js").write <<~EOS
      [1,2,3].map(n => n + 1);
    EOS

    system bin/"babel", "script.js", "--out-file", "script-compiled.js"
    assert_predicate testpath/"script-compiled.js", :exist?, "script-compiled.js was not generated"
  end
end


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model common\models\ActionFields */

$this->title = Yii::t('actionFields', 'Create Action Fields');
$this->params['breadcrumbs'][] = ['label' => Yii::t('actionFields', 'Action Fields'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
package org.elasticsearch.cluster;

/**
 * Interface for a class used to gather information about a cluster at
 * regular intervals
 */
public interface ClusterInfoService {

    public static ClusterInfoService EMPTY = EmptyClusterInfoService.getInstance();

    /** The latest cluster information */
    public ClusterInfo getClusterInfo();

    /** Add a listener that will be called every time new information is gathered */
    public void addListener(Listener listener);

    /**
     * Interface for listeners to implement in order to perform actions when
     * new information about the cluster has been gathered
     */
    public interface Listener {
        public void onNewInfo(ClusterInfo info);
    }
}


text:
package com.hazelcast.cache;

import javax.cache.event.EventType;

/**
 * Hazelcast JCache implementation's internal event types. This enum
 * type is an extension to {@link EventType} to define more event types.
 */
public enum CacheEventType {

    /**
     * An event type indicating that the cache entry was created.
     */
    CREATED(1),

    /**
     * An event type indicating that the cache entry was updated, i.e. a previous
     * mapping existed.
     */
    UPDATED(2),

    /**
     * An event type indicating that the cache entry was removed.
     */
    REMOVED(3),

    /**
     * An event type indicating that the cache entry has expired.
     */
    EXPIRED(4),

    /**
     * An event type indicating that the cache entry has evicted.
     */
    EVICTED(5),

    /**
     * An event type indicating that the cache entry has invalidated for Near Cache invalidation.
     */
    INVALIDATED(6),

    /**
     * An event type indicating that the cache operation has completed.
     */
    COMPLETED(7),

    /**
     * An event type indicating that the expiration time of cache record has been updated
     */
    EXPIRATION_TIME_UPDATED(8),

    /**
     * An event type indicating that partition loss is detected in given cache with name
     */
    PARTITION_LOST(9);

    private static final int MIN_TYPE_ID = CREATED.type;
    private static final int MAX_TYPE_ID = PARTITION_LOST.type;
    private static final CacheEventType[] CACHED_VALUES = values();

    private int type;

    CacheEventType(final int type) {
        this.type = type;
    }

    /**
     * @return unique ID of the event type.
     */
    public int getType() {
        return type;
    }

    public static CacheEventType getByType(final int eventType) {
        if (MIN_TYPE_ID <= eventType && eventType <= MAX_TYPE_ID) {
            return CACHED_VALUES[eventType - 1];
        }

        return null;
    }

    /**
     * Converts a {@link CacheEventType} into {@link EventType}.
     * Just an Enum type conversion takes place.
     *
     * @param cacheEventType a {@link CacheEventType}.
     * @return same event of {@link EventType} enum.
     */
    public static EventType convertToEventType(CacheEventType cacheEventType) {
        return EventType.valueOf(cacheEventType.name());
    }

}


text:
namespace Loon.Action.Map
{

    using System.IO;
    using System.Collections.Generic;
    using Loon.Core.Resource;
    using Loon.Utils;
    using Loon.Core;
    using System;

    public class TileMapConfig
    {

        private int[][] backMap;

        public int[][] GetBackMap()
        {
            return backMap;
        }

        public void SetBackMap(int[][] backMap_0)
        {
            this.backMap = backMap_0;
        }

        public static Field2D LoadCharsField(string resName, int tileWidth,
                int tileHeight)
        {
            Field2D field = new Field2D(LoadCharsMap(resName), tileWidth,
                    tileHeight);
            return field;
        }

        public static int[][] LoadCharsMap(string resName)
        {
            int[][] map = null;
            try
            {
                TextReader br = new StreamReader(Resources.OpenStream(resName), System.Text.Encoding.GetEncoding(LSystem.encoding));
                string line = br.ReadLine();
                int width = Int32.Parse(line);
                line = br.ReadLine();
                int height = Int32.Parse(line);
                map = (int[][])CollectionUtils.XNA_CreateJaggedArray(typeof(int), width, height);
                for (int i = 0; i < width; i++)
                {
                    line = br.ReadLine();
                    for (int j = 0; j < height; j++)
                    {
                        map[i][j] = line[j];
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.StackTrace);
            }
            return map;
        }

        public static IList<int[]> LoadList(string fileName)
        {
            Stream ins0 = Resources.OpenStream(fileName);
            TextReader reader = new StreamReader(ins0);
            IList<int[]> records = new List<int[]>(
                    CollectionUtils.INITIAL_CAPACITY);
            string result = null;
            try
            {
                while ((result = reader.ReadLine()) != null)
                {
                    if (!"".Equals(result))
                    {
                        string[] stringArray = StringUtils.Split(result, ",");
                        int size = stringArray.Length;
                        int[] intArray = new int[size];
                        for (int i = 0; i < size; i++)
                        {
                            intArray[i] = Int32.Parse(stringArray[i]);
                        }
                        records.Add(intArray);
                    }
                }
            }
            finally
            {
                if (reader != null)
                {
                    try
                    {
                        reader.Close();
                        reader = null;
                    }
                    catch (IOException ex)
                    {
                        Loon.Utils.Debug.Log.Exception(ex);
                    }
                }
            }
            return records;
        }

        public static int[][] ReversalXandY(int[][] array)
        {
            int col = array[0].Length;
            int row = array.Length;
            int[][] result = (int[][])CollectionUtils.XNA_CreateJaggedArray(typeof(int), col, row);
            for (int y = 0; y < col; y++)
            {
                for (int x = 0; x < row; x++)
                {
                    result[x][y] = array[y][x];
                }
            }
            return result;
        }

        public static int[][] LoadAthwartArray(string fileName)
        {
            IList<int[]> list = LoadList(fileName);
            int col = list.Count;
            int[][] result = new int[col][];
            for (int i = 0; i < col; i++)
            {
                result[i] = (int[])list[i];
            }
            return result;
        }
        public static int[][] LoadJustArray(string fileName)
        {
            IList<int[]> list = LoadList(fileName);
            int col = list.Count;
            int[][] mapArray = new int[col][];
            for (int i = 0; i < col; i++)
            {
                mapArray[i] = (int[])list[i];
            }
            int row = (((int[])mapArray[(col > 0) ? col - 1 : 0]).Length);
            int[][] result = (int[][])CollectionUtils.XNA_CreateJaggedArray(typeof(int), row, col);
            for (int y = 0; y < col; y++)
            {
                for (int x = 0; x < row; x++)
                {
                    result[x][y] = mapArray[y][x];
                }
            }
            return result;
        }

    }
}


text:
<?xml version="1.0"?>
<package>
  <name>carl_bringup</name>
  <version>0.0.34</version>
  <description>CARL Bringup Launch Scripts</description>

  <maintainer email="dekent@gatech.edu">David Kent</maintainer>
  <author email="spkordell@wpi.edu">Steven Kordell</author>
  <author email="russell.toris@gmail.com">Russell Toris</author>
  <author email="dekent@gatech.edu">David Kent</author>

  <license>BSD</license>

  <url type="website">http://ros.org/wiki/carl_bringup</url>
  <url type="bugtracker">https://github.com/GT-RAIL/carl_bot/issues</url>
  <url type="repository">https://github.com/GT-RAIL/carl_bot</url>

  <buildtool_depend>catkin</buildtool_depend>

  <!-- ROBOT MODEL -->
  <run_depend>carl_description</run_depend>

  <!-- SENSORS -->
  <run_depend>carl_dynamixel</run_depend>
  <run_depend>m4atx_battery_monitor</run_depend>
  <run_depend>openni2_launch</run_depend>
  <run_depend>urg_node</run_depend>

  <!-- SEGWAY -->
  <run_depend>ros_ethernet_rmp</run_depend>

  <!-- JACO -->
  <run_depend>wpi_jaco_wrapper</run_depend>

  <!-- CARL -->
  <run_depend>carl_teleop</run_depend>
  <run_depend>carl_interactive_manipulation</run_depend>
  <run_depend>carl_safety</run_depend>
  <run_depend>carl_moveit</run_depend>

  <!-- VISION -->
  <run_depend>rail_segmentation</run_depend>
  <run_depend>rail_recognition</run_depend>

  <!-- MISC -->
  <run_depend>world_item_observer</run_depend>
</package>


text:
import argparse
import pydoc
import pager

from texttable import Texttable

from .ntripbrowser import NtripBrowser
from .ntripbrowser import ExceededTimeoutError, UnableToConnect, NoDataReceivedFromCaster
from .ntripbrowser import CAS_HEADERS, STR_HEADERS, NET_HEADERS

SCREEN_WIDTH = pager.getwidth()

def argparser():
    parser = argparse.ArgumentParser(description='Parse NTRIP sourcetable')
    parser.add_argument('url', help='NTRIP sourcetable address')
    parser.add_argument('-p', '--port', type=int,
                        help='Set url port. Standard port is 2101', default=2101)
    parser.add_argument('-t', '--timeout', type=int,
                        help='add timeout', default=4)
    parser.add_argument('-c', '--coordinates',
                        help='Add NTRIP station distance to this coordinate', nargs=2)
    parser.add_argument('-M', '--maxdist',
                        help='Only report stations less than this number of km away from given coordinate',
                        type=float)

    return parser.parse_args()

def display_ntrip_table(ntrip_table):
    table_cas = compile_ntrip_table(ntrip_table['cas'], CAS_HEADERS)
    table_net = compile_ntrip_table(ntrip_table['net'], NET_HEADERS)
    table_str = compile_ntrip_table(ntrip_table['str'], STR_HEADERS)

    pydoc.pager((
        'CAS TABLE'.center(SCREEN_WIDTH, '=') + '\n' + table_cas + 4 * '\n' +
        'NET TABLE'.center(SCREEN_WIDTH, '=') + '\n' + table_net + 4 * '\n' +
        'STR TABLE'.center(SCREEN_WIDTH, '=') + '\n' + table_str
    ))

def compile_ntrip_table(table, headers):
    table_to_draw = Texttable(max_width=SCREEN_WIDTH)
    for row in table:
        row_to_draw = []
        for header in headers:
            try:
                row_to_draw.append(row[header])
            except KeyError:
                row_to_draw.append(None)
        table_to_draw.add_rows((headers, row_to_draw))

    return table_to_string(table_to_draw)

def table_to_string(table):
    try:
        return str(table.draw()).center(SCREEN_WIDTH, ' ')  # python3
    except UnicodeEncodeError:
        return table.draw().center(SCREEN_WIDTH, ' ')       # python2
    except TypeError:
        return ''

def main():
    args = argparser()
    browser = NtripBrowser(
        args.url,
        port=args.port,
        timeout=args.timeout,
        coordinates=args.coordinates,
        maxdist=args.maxdist
    )
    try:
        ntrip_table = browser.get_mountpoints()
    except ExceededTimeoutError:
        print('Connection timed out')
    except UnableToConnect:
        print('Unable to connect to NTRIP caster')
    except NoDataReceivedFromCaster:
        print('No data received from NTRIP caster')
    else:
        display_ntrip_table(ntrip_table)


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.engine.evaluation.expression;

import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.openapi.util.text.StringUtil;
import com.sun.jdi.Value;

import java.util.ArrayList;
import java.util.List;

/**
 * @author egor
 */
public class ExpressionListEvaluator implements Evaluator {
  private final List<Evaluator> myEvaluators;

  public ExpressionListEvaluator(List<Evaluator> evaluators) {
    myEvaluators = evaluators;
  }

  @Override
  public Object evaluate(EvaluationContextImpl context) throws EvaluateException {
    List<String> strings = new ArrayList<>(myEvaluators.size());
    for (Evaluator evaluator : myEvaluators) {
      strings.add(DebuggerUtils.getValueAsString(context, (Value)evaluator.evaluate(context)));
    }
    return DebuggerUtilsEx.mirrorOfString(StringUtil.join(strings, ", "),
                                          context.getDebugProcess().getVirtualMachineProxy(), context);
  }
}


text:
/* autogenerated by generator-region.js */

#include "../../debug.h"
#include "../../gi.h"
#include "../../util.h"
#include "region.h"
#include "rectangle.h"
#include "rectangle-int.h"

using namespace v8;

namespace GNodeJS {

namespace Cairo {

Nan::Persistent<FunctionTemplate> Region::constructorTemplate;
Nan::Persistent<Function>         Region::constructor;

/*
 * Initialize
 */

Region::Region(cairo_region_t* data) : ObjectWrap() {
  _data = data;
}

/*
 * Destroy
 */

Region::~Region() {
  if (_data != NULL) {
    cairo_region_destroy (_data);
  }
}

/*
 * Template methods
 */

Local<FunctionTemplate> Region::GetTemplate() {
  if (constructorTemplate.IsEmpty())
    Region::SetupTemplate();
  return Nan::New<FunctionTemplate> (constructorTemplate);
}

Local<Function> Region::GetConstructor() {
  if (constructor.IsEmpty())
    Region::SetupTemplate();
  return Nan::New<Function> (constructor);
}

void Region::SetupTemplate() {

  // Constructor
  auto tpl = Nan::New<FunctionTemplate>(Region::New);
  tpl->InstanceTemplate()->SetInternalFieldCount(1);
  tpl->SetClassName(Nan::New("CairoRegion").ToLocalChecked());

  SET_PROTOTYPE_METHOD(tpl, status);
  SET_PROTOTYPE_METHOD(tpl, getExtents);
  SET_PROTOTYPE_METHOD(tpl, numRectangles);
  SET_PROTOTYPE_METHOD(tpl, getRectangle);
  SET_PROTOTYPE_METHOD(tpl, isEmpty);
  SET_PROTOTYPE_METHOD(tpl, containsPoint);
  SET_PROTOTYPE_METHOD(tpl, containsRectangle);
  SET_PROTOTYPE_METHOD(tpl, equal);
  SET_PROTOTYPE_METHOD(tpl, translate);
  SET_PROTOTYPE_METHOD(tpl, intersect);
  SET_PROTOTYPE_METHOD(tpl, intersectRectangle);
  SET_PROTOTYPE_METHOD(tpl, subtract);
  SET_PROTOTYPE_METHOD(tpl, subtractRectangle);
  Nan::SetPrototypeMethod(tpl, "union", union_);
  SET_PROTOTYPE_METHOD(tpl, unionRectangle);
  Nan::SetPrototypeMethod(tpl, "xor", xor_);
  SET_PROTOTYPE_METHOD(tpl, xorRectangle);

  auto ctor = Nan::GetFunction (tpl).ToLocalChecked();

  SET_METHOD(ctor, copy);

  constructorTemplate.Reset(tpl);
  constructor.Reset(ctor);

}

/*
 * Initialize method
 */

void Region::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
  Nan::Set (target, Nan::New ("Region").ToLocalChecked(), Region::GetConstructor());
}

/*
 * Instance constructors
 */

NAN_METHOD(Region::New) {
  if (!info.IsConstructCall()) {
    return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
  }

  cairo_region_t* data = NULL;

  if (info[0]->IsExternal()) {
    data = (cairo_region_t*) External::Cast (*info[0])->Value ();
  }
  else if (info.Length() == 1) {
    auto rectangle = Nan::ObjectWrap::Unwrap<RectangleInt>(info[0].As<Object>())->_data;

    data = cairo_region_create_rectangle (rectangle);
  }
  else {
    data = cairo_region_create ();
  }

  Region* instance = new Region(data);
  instance->Wrap(info.This());

  info.GetReturnValue().Set(info.This());
}

/*
 * Methods
 */

NAN_METHOD(Region::copy) {
  // in-arguments
  auto original = Nan::ObjectWrap::Unwrap<Region>(info[0].As<Object>())->_data;

  // function call
  cairo_region_t * result = cairo_region_copy (original);

  // return
  Local<Value> args[] = { Nan::New<External> (result) };
  Local<Function> constructor = Nan::New<Function> (Region::constructor);
  Local<Value> returnValue = Nan::NewInstance(constructor, 1, args).ToLocalChecked();
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::status) {
  auto self = info.This();
  auto region = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // function call
  cairo_status_t result = cairo_region_status (region);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::getExtents) {
  auto self = info.This();
  auto region = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // out-arguments
  auto extents = Nan::NewInstance(
            Nan::New<Function>(RectangleInt::constructor),
            0,
            NULL).ToLocalChecked();

  // function call
  cairo_region_get_extents (region, Nan::ObjectWrap::Unwrap<RectangleInt>(extents)->_data);

  // return
  Local<Value> returnValue = extents;
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::numRectangles) {
  auto self = info.This();
  auto region = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // function call
  int result = cairo_region_num_rectangles (region);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::getRectangle) {
  auto self = info.This();
  auto region = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto nth = Nan::To<int64_t>(info[0].As<Number>()).ToChecked();

  // out-arguments
  auto rectangle = Nan::NewInstance(
            Nan::New<Function>(RectangleInt::constructor),
            0,
            NULL).ToLocalChecked();

  // function call
  cairo_region_get_rectangle (region, nth, Nan::ObjectWrap::Unwrap<RectangleInt>(rectangle)->_data);

  // return
  Local<Value> returnValue = rectangle;
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::isEmpty) {
  auto self = info.This();
  auto region = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // function call
  cairo_bool_t result = cairo_region_is_empty (region);

  // return
  Local<Value> returnValue = Nan::New ((bool) result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::containsPoint) {
  auto self = info.This();
  auto region = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto x = Nan::To<int64_t>(info[0].As<Number>()).ToChecked();
  auto y = Nan::To<int64_t>(info[1].As<Number>()).ToChecked();

  // function call
  cairo_bool_t result = cairo_region_contains_point (region, x, y);

  // return
  Local<Value> returnValue = Nan::New ((bool) result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::containsRectangle) {
  auto self = info.This();
  auto region = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto rectangle = Nan::ObjectWrap::Unwrap<RectangleInt>(info[0].As<Object>())->_data;

  // function call
  cairo_region_overlap_t result = cairo_region_contains_rectangle (region, rectangle);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::equal) {
  auto self = info.This();
  auto a = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto b = Nan::ObjectWrap::Unwrap<Region>(info[0].As<Object>())->_data;

  // function call
  cairo_bool_t result = cairo_region_equal (a, b);

  // return
  Local<Value> returnValue = Nan::New ((bool) result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::translate) {
  auto self = info.This();
  auto region = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto dx = Nan::To<int64_t>(info[0].As<Number>()).ToChecked();
  auto dy = Nan::To<int64_t>(info[1].As<Number>()).ToChecked();

  // function call
  cairo_region_translate (region, dx, dy);
}

NAN_METHOD(Region::intersect) {
  auto self = info.This();
  auto dst = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto other = Nan::ObjectWrap::Unwrap<Region>(info[0].As<Object>())->_data;

  // function call
  cairo_status_t result = cairo_region_intersect (dst, other);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::intersectRectangle) {
  auto self = info.This();
  auto dst = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto rectangle = Nan::ObjectWrap::Unwrap<RectangleInt>(info[0].As<Object>())->_data;

  // function call
  cairo_status_t result = cairo_region_intersect_rectangle (dst, rectangle);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::subtract) {
  auto self = info.This();
  auto dst = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto other = Nan::ObjectWrap::Unwrap<Region>(info[0].As<Object>())->_data;

  // function call
  cairo_status_t result = cairo_region_subtract (dst, other);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::subtractRectangle) {
  auto self = info.This();
  auto dst = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto rectangle = Nan::ObjectWrap::Unwrap<RectangleInt>(info[0].As<Object>())->_data;

  // function call
  cairo_status_t result = cairo_region_subtract_rectangle (dst, rectangle);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::union_) {
  auto self = info.This();
  auto dst = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto other = Nan::ObjectWrap::Unwrap<Region>(info[0].As<Object>())->_data;

  // function call
  cairo_status_t result = cairo_region_union (dst, other);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::unionRectangle) {
  auto self = info.This();
  auto dst = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto rectangle = Nan::ObjectWrap::Unwrap<RectangleInt>(info[0].As<Object>())->_data;

  // function call
  cairo_status_t result = cairo_region_union_rectangle (dst, rectangle);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::xor_) {
  auto self = info.This();
  auto dst = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto other = Nan::ObjectWrap::Unwrap<Region>(info[0].As<Object>())->_data;

  // function call
  cairo_status_t result = cairo_region_xor (dst, other);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

NAN_METHOD(Region::xorRectangle) {
  auto self = info.This();
  auto dst = Nan::ObjectWrap::Unwrap<Region>(self)->_data;

  // in-arguments
  auto rectangle = Nan::ObjectWrap::Unwrap<RectangleInt>(info[0].As<Object>())->_data;

  // function call
  cairo_status_t result = cairo_region_xor_rectangle (dst, rectangle);

  // return
  Local<Value> returnValue = Nan::New (result);
  info.GetReturnValue().Set(returnValue);
}

}; // Cairo

}; // GNodeJS


text:
/* eslint-disable react/jsx-filename-extension */
import React from 'react';
import ReactDOM from 'react-dom';
import 'normalize.css';
import 'flexboxgrid2/flexboxgrid2.css';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();


text:
// <copyright file="StringExtensionsMain.cs" company="company">
// Copyright (c) company. All rights reserved.
// </copyright>
using System;

namespace StringConvertions
{
    /// <summary>
    /// Startup point of the program.
    /// </summary>
    public class StringExtensionsMain
    {
        /// <summary>
        /// Main method executes all string extensions
        /// </summary>
        public static void Main()
        {
            string inputString = "minions2015филм.docx";
            Console.WriteLine(StringExtensions.CapitalizeFirstLetter(inputString));
            Console.WriteLine(StringExtensions.ConvertCyrillicToLatinLetters(inputString));
            Console.WriteLine(StringExtensions.GetFileExtension(inputString));
            Console.WriteLine(StringExtensions.GetFirstCharacters(inputString, 2));
            Console.WriteLine(StringExtensions.ToContentType(inputString));
        }
    }
}


text:
@class SRRecorderControl;

@interface Core (HotkeyDelegateCategory)

- (void)registerHotkeyForTagger;

- (PTHotKey *)taggerHotkey;
- (void)setTaggerHotkey:(PTHotKey *)newHotkey;

@end


text:
export interface PlumLightpadConfig {
    username: string;
    password: string;
}


text:
This is a nkf (Network Kanji Filter) package for Alpine Linux.

## How to build a package
You can build a package by using [ttanjo/alpine-pkg-nkf](https://hub.docker.com/r/ttanjo/alpine-pkg-nkf/).
It generates APK packages for `nkf` and `nkf-doc` in `$PWD/packages`.
```
$ docker run -v $PWD/packages:/packages -v ~/.abuild:/home/builder/.abuild:ro --rm ttanjo/alpine-pkg-nkf
```

I assume that `~/.abuild` contains a private key file and `abuild.conf` (for environment variables).

Here is an example:
```
PACKAGER_PRIVKEY="/home/builder/.abuild/private-key.rsa"
PACKAGER='Tomoya Tanjo <ttanjo@gmail.com>'
```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>TFarListInsert</title>
<meta http-equiv="Content-Type" Content="text/html; charset=Windows-1251">
<link rel="stylesheet" type="text/css" href="../../styles/styles.css">

TFarListInsert

main |
structures |
FarListInsert

The <dfn>FarListInsert</dfn> stucture for Delphi:

TFarListInsert = packed record
  Index: integer;
  Item: TFarListItem;
end;
PFarListInsert = ^TFarListInsert;


text:
namespace LinuxPackages.Data.Models
{
    using System.ComponentModel.DataAnnotations;

    using Common.Constants;

    public class Rating
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [Range(PackageConstants.MinRating, PackageConstants.MaxRating)]
        public int Value { get; set; }

        public int PackageId { get; set; }

        public virtual Package Package { get; set; }

        public string RatedById { get; set; }

        public virtual User RatedBy { get; set; }
    }
}


text:
import logging
from flask import render_template, make_response, url_for
from flask_restful import Resource

from blog_management import hearts

LOGGER = logging.getLogger("running-log")

class HeartsGroup(Resource):

    def __init__(self):
        self.header = {'Content-Type': 'text/html'}

    def get(self, group_name):
        try:
            group = hearts.Group(group_name)
        except Exception as e:
            LOGGER.error(e)
            template = render_template('404.html', error="Group {} not found".format(group_name))
            return make_response(template, 404, self.header)
        group.calculate_scoreboard()
        group.calculate_point_breakdown_day()

        template = render_template('hearts_group.html', group_name=group.name,
                                   scoreboard=group.get_scoreboard(),
                                   player_1=group.get_players()[0],
                                   player_2=group.get_players()[1],
                                   player_3=group.get_players()[2],
                                   player_4=group.get_players()[3],
                                   results=group.point_breakdown_day,
                                   addurl=url_for('heartsgame', group_name=group_name)
                                   )
        return make_response(template, 200, self.header)


text:
PEAR_Error: expected errors
--SKIPIF--
<?php
if (!getenv('PHP_PEAR_RUNTESTS')) {
    echo 'skip';
}
?>
--FILE--
<?php // -*- PHP -*-

// Test for: PEAR.php
// Parts tested: - PEAR_Error class
//               - PEAR::expectError
//               - PEAR::popExpect

include_once "PEAR.php";

function errorhandler($eobj)
{
    if (PEAR::isError($eobj)) {
        print "error: ".$eobj->getMessage()."\n";
    } else {
        print "errorhandler called without error object\n";
    }
}

$obj = new PEAR;
$obj->setErrorHandling(PEAR_ERROR_CALLBACK, "errorhandler");

print "subtest 1\n";
$obj->expectError(1);
$obj->raiseError("1", 1);
$obj->popExpect();
$obj->raiseError("2", 2);

print "subtest 2\n";
$obj->expectError(3);
$obj->expectError(2);
$obj->raiseError("3", 3);

print "subtest 3\n";
$obj->popExpect();
$obj->raiseError("3", 3);
$obj->popExpect();

print "subtest 4\n";
$obj->expectError(array(1,2,3,4,5));
$obj->raiseError("0", 0);
$obj->raiseError("1", 1);
$obj->raiseError("2", 2);
$obj->raiseError("3", 3);
$obj->raiseError("4", 4);
$obj->raiseError("5", 5);
$obj->raiseError("6", 6);
$obj->raiseError("error");
$obj->popExpect();

print "subtest 5\n";
$obj->expectError("*");
$obj->raiseError("42", 42);
$obj->raiseError("75", 75);
$obj->raiseError("13", 13);
$obj->popExpect();

print "subtest 6\n";
$obj->expectError();
$obj->raiseError("123", 123);
$obj->raiseError("456", 456);
$obj->raiseError("789", 789);
$obj->popExpect();

print "subtest 7\n";
$obj->expectError("syntax error");
$obj->raiseError("type mismatch");
$obj->raiseError("syntax error");
$obj->popExpect();

print "subtest 8\n";
$obj->expectError(array(1, 2, 3));
$obj->expectError(array(3, 4, 5));
$obj->raiseError(4);
$obj->delExpect(2);
$obj->raiseError(3);
$obj->delExpect(1, 3, 4, 5);
$err = $obj->delExpect(2);

?>
--EXPECT--
subtest 1
error: 2
subtest 2
error: 3
subtest 3
subtest 4
error: 0
error: 6
error: error
subtest 5
subtest 6
subtest 7
error: type mismatch
subtest 8
error: 4
error: 3
error: The expected error you submitted does not exist


text:
An overview of the included protection and analytic capabilities of Dotfuscator CE included with VS2015.

The presentation itself is instrumented using the PreEmptive Analytics JavaScript API.

The instrumentation of the presentation is included as a separate commit from the presentation data.

Instrumented with [PreEmptive Analytics](https://github.com/preemptive/ri-js-api)

Presented in [reveal.js](https://github.com/hakimel/reveal.js)


text:
import logging

import coreapi
from rest_framework import mixins, filters
from rest_framework.filters import BaseFilterBackend
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from rest_framework.viewsets import GenericViewSet

from books.models import Book
from books.serializers import BookSerializer
from search.models import SearchWord
from search.serializers import SearchWordSerializer

logger = logging.getLogger(__name__)

class SearchWordViewSet(mixins.ListModelMixin, GenericViewSet):
    queryset = SearchWord.objects.filter(is_hot=True).all()
    serializer_class = SearchWordSerializer
    pagination_class = None

class WordFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        content = request.query_params.get('word', None)
        if content is not None:
            return SearchWord.objects.filter(word__contains=content)
        return queryset

    def get_schema_fields(self, view):
        return coreapi.Field(name='word', required=False, location='query')

class SearchSuggestViewSet(mixins.ListModelMixin, GenericViewSet):
    queryset = SearchWord.objects.all()
    serializer_class = SearchWordSerializer
    pagination_class = None

    filter_backends = [filters.DjangoFilterBackend]
    filter_fields = ['word']

    def get_queryset(self):
        content = self.request.query_params.get('word', None)
        if content is not None:
            return SearchWord.objects.filter(word__contains=content)
        return self.queryset

    def list(self, request, *args, **kwargs):
        serializer = self.get_serializer(self.get_queryset(), many=True)
        return Response(serializer.data)

class SearchTopViewSet(mixins.ListModelMixin, GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    pagination_class = None

    def get_queryset(self):
        count = self.kwargs.get('count', 5)
        if count is not None:
            return Book.objects.order_by('-click_amount')[:count]
        return self.queryset

    def list(self, request, *args, **kwargs):
        serializer = self.get_serializer(self.get_queryset(), many=True)
        return Response(serializer.data)

class SearchBookViewSet(mixins.ListModelMixin, GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    filter_backends = (filters.SearchFilter, filters.DjangoFilterBackend)
    search_fields = ('name',)

    def list(self, request, *args, **kwargs):
        content = request.query_params[filters.SearchFilter.search_param]
        if content is None:
            return Response(status=HTTP_400_BAD_REQUEST)

        if SearchWord.objects.filter(word=content).count() == 0:
            sw = SearchWord(word=content, is_hot=False)
            sw.save()
        else:
            sw = SearchWord.objects.filter(word=content).get()
            sw.count += 1
            sw.save()

        return super(SearchBookViewSet, self).list(self, request, *args, **kwargs)


text:
/******************************************************************************/
/* General utility functions.                                                 */
/*                                                                            */
/* Copyright 2015 Jim Buller                                                  */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License");            */
/* you may not use this file except in compliance with the License.           */
/* You may obtain a copy of the License at                                    */
/*                                                                            */
/*     http://www.apache.org/licenses/LICENSE-2.0                             */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/******************************************************************************/

/***************************************************************************//**
 * @file utils.h
 * @brief General utility functions.
 *
 * General utility functions used throughout, largely output related.
 ******************************************************************************/
#ifndef __ES_UTILS__
#define __ES_UTILS__

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>
#include <string.h>
#include <openssl/bn.h>
#include <openssl/ec.h>

#include "log.h"

/***************************************************************************//**
 * Returns current software version.
 ******************************************************************************/
char *softwareVersion(void);

/*******************************************************************************
 * Outputs a hash value to the specified log-type.
 ******************************************************************************/
void utils_displayHash(
    const uint8_t   log_type,
    const char     *section,
    const char     *text,
    const uint8_t   pad,
    const char     *hash,
    const uint16_t  len);

/*******************************************************************************
 * Outputs an OpenSSL BN value to the specified log-type.
 ******************************************************************************/
void utils_BNdump(
    const uint8_t  log_type,
    const char    *section,
    const char    *text,
    const uint8_t  pad,
    const BIGNUM  *val);

/*******************************************************************************
 * Outputs the coordinates of the specified point on the specified curve to the
 * specified log-type.
 ******************************************************************************/
void utils_displayAffineCoordinates(
    const uint8_t   log_type,
    const char     *section,
    const char     *text,
    const uint8_t   pad,
    const EC_GROUP *group,
    const EC_POINT *point);

/*******************************************************************************
 * Outputs an octet string to the specified log-type. The octet string is output
 * in a 'pretty' fashion i.e. 4 byte space and 16 byte line separators.
 ******************************************************************************/
void utils_printFormattedOctetString(
    const uint8_t  log_type,
    const char    *section,
    const char    *text,
    const uint8_t  pad,
    const uint8_t *oStr,
    const size_t   oStr_len);

/*******************************************************************************
 * Convert a hex string e.g. where F0 would be two bytes 0x46, 0x30 to an octet
 * string 0xF0.
 ******************************************************************************/
short utils_convertHexStringToOctetString(
    const char    *hexString,
    const size_t   requiredLength,
    uint8_t      **octetString,
    size_t        *octetStringLength);

/*******************************************************************************
 * Outputs an MS identifier that conforms to date|NULL|id|NULL as date.id
 ******************************************************************************/
void utils_printUserId(
    const uint8_t  log_type,
    const char    *section,
    const char    *text,
    const uint8_t  pad,
    const uint8_t *id,
    const size_t   id_len);

#ifdef __cplusplus
}
#endif
#endif /* __ES_UTILS__ */

/******************************************************************************/
/*                                End of file                                 */
/******************************************************************************/


text:
var webpack = require("webpack"),
    port = require('node_erlastic').port,
    server = require('node_erlastic').server

var client_config = require("./client.webpack.config.js")
if(process.argv[2] === "hot"){
    // add hotmodule plugin to client
    client_config.plugins = (client_config.plugins || []).concat([new webpack.HotModuleReplacementPlugin()])
    // add reloading code to entries
    client_config.add_to_entries(client_config,"webpack/hot/dev-server")
    // remove external which cause conflicts in hot loading
    client_config.externals = {}
}
var client_compiler = webpack(client_config)

var client_stats,client_err
function maybe_done() {
  if(client_err) port.write({event: "client_done", error: JSON.stringify(client_err)})
  else if(client_stats.hasErrors()) port.write({event: "client_done", error: "soft fail"})
  else    port.write({event: "client_done"})
}

client_compiler.plugin("invalid", function() {
  port.write({event: "client_invalid"})
})
client_compiler.plugin("compile", function() {
  port.write({event: "client_compile"})
})
client_compiler.plugin("failed", function(error) {
  client_err = error
  maybe_done()
})
client_compiler.plugin("done", function(stats) {
  client_stats = stats
  port.write({event: "client_hash",hash: stats.hash})
  require("fs").writeFile(process.cwd()+"/../priv/webpack.stats.json", JSON.stringify(stats.toJson()), maybe_done)
})
//port.write({event: "invalid"})
client_compiler.watch(100, function(){})
server(function(req,reply_to,state,done){
  //maybe_done() // receive message indicating server compilation end
  done("noreply")
})


text:
module RedmineGitHosting
  module Plugins
    extend self

    def execute(step, repository, **opts)
      Plugins::GitolitePlugin.all_plugins.each do |plugin|
        plugin.new(repository, **opts).send(step) if plugin.method_defined? step
      end
    rescue StandardError => e
      RedmineGitHosting.logger.error e.message
    end
  end
end


text:
"""
Console Exec

Plugin for Sublime Text 2 to execute a command and redirect its output
into a console window. This is based on the default exec command.
"""

import sublime
import sublime_plugin
import os
import sys
import subprocess
import time

class Process(object):
    def __init__(self, arg_list, env, listener,
            # "path" is an option in build systems
            path='',
            # "shell" is an options in build systems
            shell=False):

        self.listener = listener
        self.killed = False

        self.start_time = time.time()

        # Set temporary PATH to locate executable in arg_list
        if path:
            old_path = os.environ["PATH"]
            # The user decides in the build system whether he wants to append $PATH
            # or tuck it at the front: "$PATH;C:\\new\\path", "C:\\new\\path;$PATH"
            os.environ["PATH"] = os.path.expandvars(path).encode(sys.getfilesystemencoding())

        proc_env = os.environ.copy()
        proc_env.update(env)
        for k, v in proc_env.iteritems():
            proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())

        self.proc = subprocess.Popen(arg_list, env=proc_env, shell=shell)

        if path:
            os.environ["PATH"] = old_path

    def kill(self):
        if not self.killed:
            self.killed = True
            self.proc.terminate()
            self.listener = None

    def poll(self):
        return self.proc.poll() == None

class ConsoleExecCommand(sublime_plugin.WindowCommand):
    def run(self, cmd=[], file_regex='', line_regex='', working_dir='', encoding='utf-8', env={}, quiet=False, kill=False, **kwargs):
        launcher = os.path.join(sublime.packages_path(), 'ConsoleExec', 'launch.exe')
        if not os.path.exists(launcher):
            if not quiet:
                print 'Error: Could not find the ConsoleExec package.'
            return
        cmd = [launcher] + map(lambda s: '"%s"' % s if ' ' in s else s, cmd)

        if kill:
            if self.proc:
                self.proc.kill()
                self.proc = None
            return

        # Default the to the current files directory if no working directory was given
        if (working_dir == '' and self.window.active_view()
                        and self.window.active_view().file_name()):
            working_dir = os.path.dirname(self.window.active_view().file_name())

        # Call get_output_panel a second time after assigning the above
        # settings, so that it'll be picked up as a result buffer
        self.window.get_output_panel("exec")

        self.encoding = encoding
        self.quiet = quiet

        self.proc = None
        if not self.quiet:
            print "Running " + " ".join(cmd)
            sublime.status_message("Building")

        merged_env = env.copy()
        if self.window.active_view():
            user_env = self.window.active_view().settings().get('build_env')
            if user_env:
                merged_env.update(user_env)

        # Change to the working dir, rather than spawning the process with it,
        # so that emitted working dir relative path names make sense
        if working_dir != '':
            os.chdir(working_dir)

        # Forward kwargs to Process
        self.proc = Process(cmd, merged_env, self, **kwargs)

    def is_enabled(self, kill=False):
        if kill:
            return hasattr(self, 'proc') and self.proc and self.proc.poll()
        else:
            return True


text:
/*global describe, it, beforeEach, afterEach, sinon, _*/
require('../initialize-globals').load();
//Require the module to test.
var MetadataBuilder = require('../../app/lib/metadata_builder');
//Require the basic model and extend it.
var Mdl = require('../../app/models/model');
var Model = Mdl.extend({
	metadatas: {
		id: {
			metadata: {
				"domain": "DO_ID",
				"required": true
			}
		},
		name: {
			metadata: {
				"domain": "DO_ID",
				"required": false
			}
		},
		age: {
			metadata: {
				domain: "DO_ENTIER",
				required: false
			},
			required: true,
			isValidationOff: false
			//domain: ''
		},
		attrNoVal: {
			metadata: "DO_ID",
			isValidationOff: true
		}
	}
});

describe('# MetadataBuilder', function() {
	describe('## getDomainsValidationAttrs', function() {
		//Initialisation
		var model = new Model();
		var validators = MetadataBuilder.getDomainsValidationAttrs(model);
		it('Should have validators for each property', function() {
			validators.should.have.property('id');
			validators.should.have.property('name');
			validators.should.have.property('age');
		});
		it('Should have a required override on the validators.', function() {
			validators.should.have.property('age').be.an("Array").of.length(2);
			validators.age[0].should.have.a.property('type', "required");
			validators.age[0].should.have.a.property('value', true);
		});
		it('should override the domain validators with others.');
		it('should return no validation when isValidationOff:true is pass', function() {
			validators.should.not.have.a.property('attrNoVal');
		});
		it('should behave normally when isValidationOff:false', function() {
			validators.should.have.property('age').be.an("Array").of.length(2);
		});
	});
	describe.skip('## domainAttributes', function() {
		var ModelWithName = Model.extend({
			modelName: "fatherModel"
		});
		var mb = _.clone(MetadataBuilder);
		var spy;
		//Register the spy before each test.
		beforeEach(function() {

			spy = sinon.spy(mb, "getDomainsValidationAttrs");
		});

		//Unregister the spy after each test.
		afterEach(function() {
			mb.getDomainsValidationAttrs.restore();
		});
		it("should call the getDomainsValidationAttr each time without name.", function() {
			mb.domainAttributes(new Model());
			//console.log("val", val);
			spy.should.have.callCount(1);
			mb.domainAttributes(new Model());
			spy.should.have.callCount(2);
		});
		it("should call the getDomainsValidationAttr once with a name.", function() {
			mb.domainAttributes(new ModelWithName());
			spy.should.have.callCount(1);
			mb.domainAttributes(new ModelWithName());
			spy.should.have.callCount(1);
		});

	});
});


text:
<?php

declare(strict_types=1);

namespace Sonata\PageBundle\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\Cache\CacheManagerInterface;
use Sonata\Form\Type\DateTimePickerType;

/**
 * Admin definition for the Snapshot class.
 *
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class SnapshotAdmin extends AbstractAdmin
{
    protected $classnameLabel = 'Snapshot';

    /**
     * @var CacheManagerInterface
     */
    protected $cacheManager;

    protected $accessMapping = [
        'batchToggleEnabled' => 'EDIT',
    ];

    public function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('url')
            ->add('enabled')
            ->add('publicationDateStart')
            ->add('publicationDateEnd')
        ;
    }

    public function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('routeName');
    }

    public function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('enabled', null, ['required' => false])
            ->add('publicationDateStart', DateTimePickerType::class, ['dp_side_by_side' => true])
            ->add('publicationDateEnd', DateTimePickerType::class, ['required' => false, 'dp_side_by_side' => true])
        ;
    }

    public function getBatchActions()
    {
        $actions = parent::getBatchActions();

        $actions['toggle_enabled'] = [
            'label' => $this->trans('toggle_enabled'),
            'ask_confirmation' => true,
        ];

        return $actions;
    }

    public function postUpdate($object)
    {
        $this->cacheManager->invalidate([
            'page_id' => $object->getPage()->getId(),
        ]);
    }

    public function postPersist($object)
    {
        $this->cacheManager->invalidate([
            'page_id' => $object->getPage()->getId(),
        ]);
    }

    public function setCacheManager(CacheManagerInterface $cacheManager)
    {
        $this->cacheManager = $cacheManager;
    }
}


text:
<?php

namespace Tolerance\Tracer\Zipkin;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use Tolerance\Tracer\Span\Annotation;
use Tolerance\Tracer\Span\BinaryAnnotation;
use Tolerance\Tracer\Span\Endpoint;
use Tolerance\Tracer\Span\Span;
use Tolerance\Tracer\Tracer;
use Tolerance\Tracer\TracerException;

class ZipkinHttpTracer implements Tracer
{
    /**
     * @var string
     */
    private $baseUrl;

    /**
     * @var ClientInterface
     */
    private $client;

    /**
     * @param ClientInterface $client
     * @param string          $baseUrl
     */
    public function __construct(ClientInterface $client, $baseUrl)
    {
        $this->baseUrl = $baseUrl;
        $this->client = $client;
    }

    /**
     * {@inheritdoc}
     */
    public function trace(array $spans)
    {
        try {
            $options = [
                'json' => array_map([$this, 'normalizeSpan'], $spans),
            ];

            if (version_compare(ClientInterface::VERSION, '6.0') >= 0) {
                $this->client->request('POST', $this->baseUrl . '/api/v1/spans', $options);
            } else {
                $this->client->post($this->baseUrl . '/api/v1/spans', $options);
            }
        } catch (RequestException $e) {
            throw new TracerException('Unable to publish the traces', $e->getCode(), $e);
        }
    }

    /**
     * @param Span $span
     *
     * @return array
     */
    private function normalizeSpan(Span $span)
    {
        return [
            'id' => (string) $span->getIdentifier(),
            'name' => $span->getName(),
            'traceId' => (string) $span->getTraceIdentifier(),
            'parentId' => null !== $span->getParentIdentifier() ? (string) $span->getParentIdentifier() : null,
            'timestamp' => $span->getTimestamp(),
            'duration' => $span->getDuration(),
            'debug' => $span->getDebug(),
            'annotations' => array_map([$this, 'normalizeAnnotation'], $span->getAnnotations()),
            'binaryAnnotations' => array_map([$this, 'normalizeBinaryAnnotation'], $span->getBinaryAnnotations()),
        ];
    }

    /**
     * @param Annotation $annotation
     *
     * @return array
     */
    private function normalizeAnnotation(Annotation $annotation)
    {
        return [
            'value' => $annotation->getValue(),
            'timestamp' => $annotation->getTimestamp(),
            'endpoint' => null !== $annotation->getHost() ? $this->normalizeEndpoint($annotation->getHost()) : null,
        ];
    }

    /**
     * @param BinaryAnnotation $binaryAnnotation
     *
     * @return array
     */
    private function normalizeBinaryAnnotation(BinaryAnnotation $binaryAnnotation)
    {
        $normalizedAnnotation = [
            'key' => $binaryAnnotation->getKey(),
            'value' => (string) $binaryAnnotation->getValue(),
        ];

        if (null !== ($host = $binaryAnnotation->getHost())) {
            $normalizedAnnotation['endpoint'] = $this->normalizeEndpoint($host);
        }

        return $normalizedAnnotation;
    }

    /**
     * @param Endpoint $endpoint
     *
     * @return array
     */
    private function normalizeEndpoint(Endpoint $endpoint)
    {
        $normalizedEndpoint = [
            'serviceName' => $endpoint->getServiceName(),
        ];

        if (null !== ($ipv4 = $endpoint->getIpv4())) {
            $normalizedEndpoint['ipv4'] = $ipv4;
        }

        if (null !== ($ipv6 = $endpoint->getIpv6())) {
            $normalizedEndpoint['ipv6'] = $ipv6;
        }

        if (null !== ($port = $endpoint->getPort())) {
            $normalizedEndpoint['port'] = $port;
        }

        return $normalizedEndpoint;
    }
}


text:
package com.vumobile.celeb.model;

/**
 * Created by toukirul on 16/5/2017.
 */

public class ChatClass {

    private String imageUrl;
    private String text;
    private String isCeleb;

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getIsCeleb() {
        return isCeleb;
    }

    public void setIsCeleb(String isCeleb) {
        this.isCeleb = isCeleb;
    }
}


text:
#ifndef DFINSTANCE_OSX_H
#define DFINSTANCE_OSX_H
#include <mach/vm_region.h>
#include <mach/vm_map.h>

#include "dfinstance.h"
#include "dfinstancenix.h"

class DFInstanceOSX : public DFInstanceNix {
    Q_OBJECT
public:
    DFInstanceOSX(QObject *parent=0);
    virtual ~DFInstanceOSX();
    void find_running_copy();

    USIZE read_raw(const VIRTADDR &addr, const USIZE &bytes, void *buffer);
    USIZE write_raw(const VIRTADDR &addr, const USIZE &bytes, const void *buffer);

    bool attach();
    bool detach();
    int VM_TYPE_OFFSET();

    static bool authorize();
    static bool isAuthorized();
    static bool checkPermissions();

protected:
    vm_map_t m_task;
    bool set_pid();

private:
    VIRTADDR alloc_chunk(USIZE size);
    VIRTADDR m_alloc_start, m_alloc_end;
    int m_alloc_remaining, m_size_allocated;
};

#endif // DFINSTANCE_H


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Peruse Bg Process</title>


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;
using System.Collections.Generic;
using Windows.Networking.Connectivity;

namespace NetworkInformationApi
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class LanId : Page
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;

        public LanId()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// This is the click handler for the 'Default' button.  You would replace this with your own handler
        /// if you have a button or buttons on this page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LanId_Click(object sender, RoutedEventArgs e)
        {
            //
            //Display Lan Identifiers - Infrastructure ID, Port ID, Network Adapter ID
            //
            string lanIdentifierData = string.Empty;
            try
            {
                var lanIdentifiers = NetworkInformation.GetLanIdentifiers();
                if (lanIdentifiers.Count != 0)
                {
                    lanIdentifierData = "Number of Lan Identifiers retrieved: " + lanIdentifiers.Count + "\n";
                    lanIdentifierData += "=============================================\n";
                    for (var i = 0; i < lanIdentifiers.Count; i++)
                    {
                        //Display Lan Identifier data for each identifier
                        lanIdentifierData += GetLanIdentifierData(lanIdentifiers[i]);
                        lanIdentifierData += "------------------------------------------------\n";
                    }

                    OutputText.Text = lanIdentifierData;
                    rootPage.NotifyUser("Success", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("No Lan Identifier Data found", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Unexpected exception occurred: " + ex.ToString(), NotifyType.ErrorMessage);
            }
        }

        //
        //Get Lan Identifier Data
        //
        string GetLanIdentifierData(LanIdentifier lanIdentifier)
        {
            string lanIdentifierData = string.Empty;
            if (lanIdentifier == null)
            {
                return lanIdentifierData;
            }

            if (lanIdentifier.InfrastructureId != null)
            {
                lanIdentifierData += "Infrastructure Type: " + lanIdentifier.InfrastructureId.Type + "\n";
                lanIdentifierData += "Infrastructure Value: ";
                var infrastructureIdValue = lanIdentifier.InfrastructureId.Value;
                foreach (var value in infrastructureIdValue)
                {
                    lanIdentifierData += value + " ";
                }
            }

            if (lanIdentifier.PortId != null)
            {
                lanIdentifierData += "\nPort Type : " + lanIdentifier.PortId.Type + "\n";
                lanIdentifierData += "Port Value: ";
                var portIdValue = lanIdentifier.PortId.Value;
                foreach (var value in portIdValue)
                {
                    lanIdentifierData += value + " ";
                }
            }

            if (lanIdentifier.NetworkAdapterId != null)
            {
                lanIdentifierData += "\nNetwork Adapter Id : " + lanIdentifier.NetworkAdapterId + "\n";
            }
            return lanIdentifierData;
        }
    }
}


text:
from mock import patch
import pytest

from mycroft.models.abstract_records import PrimaryKeyError
from mycroft.views.clusters import clusters
from mycroft.views.clusters import cluster_by_name
from tests.views.conftest import dummy_request

@pytest.mark.parametrize("err_instance, expected_return_code", [
    (ValueError(), 404),
    (Exception(), 500)
])
def test_cluster_by_name_errors(err_instance, expected_return_code):
    dr = dummy_request()
    dr.matchdict["log_name"] = "dummy_log_name"

    with patch('mycroft.models.aws_connections.TableConnection.get_connection'):
        with patch('mycroft.views.clusters.list_cluster_by_name') as list_action:
            list_action.side_effect = err_instance
            actual_return_code, _ = cluster_by_name(dr)
        assert actual_return_code == expected_return_code

@pytest.mark.parametrize("err_instance, expected_return_code", [
    (PrimaryKeyError(), 400),
    (ValueError(), 404),
    (ValueError("ConditionalCheckFailedException"), 404),
    (Exception, 500),
])
def test_clusters_errors(err_instance, expected_return_code):
    dr = dummy_request()
    with patch('mycroft.models.aws_connections.TableConnection.get_connection'):
        with patch('mycroft.views.clusters.list_all_clusters') as list_all_clusters:
            list_all_clusters.side_effect = err_instance
            actual_return_code, _ = clusters(dr)
        assert actual_return_code == expected_return_code

@pytest.mark.parametrize("request_method, parm", [
    ("POST", "mycroft.views.clusters.post_cluster"),
    ("GET", "mycroft.views.clusters.list_all_clusters")])
def test_clusters(request_method, parm):
    dr = dummy_request()
    dr.method = request_method
    expected_return_code = 200
    with patch('mycroft.models.aws_connections.TableConnection.get_connection'):
        with patch(parm) as request_method_action:
            request_method_action.return_value = {}
            actual_return_code, _ = clusters(dr)
        assert actual_return_code == expected_return_code

@pytest.mark.parametrize("cluster_name, parm", [
    ("dummy_clustername", "mycroft.views.clusters.list_cluster_by_name"),
    (None, "mycroft.views.clusters.list_cluster_by_name")])
def test_cluster_by_name(cluster_name, parm):
    dr = dummy_request()
    dr.matchdict["cluster_name"] = cluster_name
    expected_return_code = 200
    with patch('mycroft.models.aws_connections.TableConnection.get_connection'):
        with patch(parm) as list_action:
            list_action.return_value = {}
            actual_return_code, _ = cluster_by_name(dr)
        assert actual_return_code == expected_return_code


text:
Docker is een hulpmiddel voor systeembeheerders (ookwel 'devops' genoemd, beheerders van 'development' en 'operations') om de softwarecomponenten (delen van de infrastructuur) van een applicatie op een gestructureerde manier op te zetten en te beheren.

Het werk van een systeembeheerder is niet altijd makkelijk. Zo ontstaan er eenvoudig verschillen in de ontwikkelomgevingen van de ontwikkelaars - alleen al een verschillend besturingssysteem zorgt veelal voor problemen. Ook schaalt een applicatie niet altijd goed, omdat de infrastructuur handmatig is opgezet, waarbij de samenhang als het ware 'opnieuw is uitgevonden'. Denk hierbij aan bijvoorbeeld het handmatig uitvoeren van de installatiestappen voor de software onderdelen.

Docker is een stap in de goede richting voor de volgende problemen of moeilijkheden:

- __Verschillen in ontwikkelomgeving:__ Alle containers gebruiken dezelfde 'base image' en installatiestappen, hierdoor zullen deze - uitgezonderd van de gekoppelde data - niet verschillen.

- __Verschillen in aanpak:__ Docker biedt een gestandaardiseerde en herhaalbare aanpak. Hierdoor kunnen images van andere worden hergebruikt, wat veel tijd scheelt. Doordat het wiel niet telkens opnieuw wordt uitgevonden, kan er ook meer tijd worden besteed aan het oplossen van beveiligingsproblemen en dergelijke.

- __Uitrollen van applicaties:__ Het starten en stoppen van containers kan worden geautomatiseerd. Hierdoor hoeven er niet handmatig servers worden herstart en wordt er inzicht geboden in uitgeschakelde of falende componenten van de applicatie. Wat het mede mogelijk maakt om bij het falen van een component, automatisch een container te herstarten - eventueel op een backup server.

- __Het schalen van de applicatie:__ Docker kan worden ingezet als een dienst, waarbij er met een druk op de knop meer containers worden gestart of gestopt. Zoals bijvoorbeeld de [Kubernetes](http://kubernetes.io/) dienst van Google.

## Alternatieven
Uiteraard is Docker niet de eerste die dit probleem probeert te tackelen. Zo zijn er veel andere softwarepakketten die de problemen elk op hun eigen manier aanpakken. Een veel gebruikte aanpak is het geautomatiseerd configureren van de volledige server. Bijvoorbeeld door gebruikers en services te persisteren (zorgen dat ze respectievelijk aanwezig zijn/goed geconfigureerd zijn of draaien). Chef is hier een voorbeeld van.

Gelukkig sluit Docker weinig van deze configuratiemiddelen uit. Docker zal eerder eenvoudiger te gebruiken zijn in combinatie met een zogeheten 'provision tool' (bijvoorbeeld Chef, Puppet of Ansible). In de onderstaande afbeelding is te zien welke tools Docker, op het moment van schrijven, al ondersteunen.

![](../../assets/docker_devops.png)

In plaats van dat Docker een 'one size fits all' oplossing aanbiedt, stelt het de gebruiker enkel in staat om software in een geïsoleerde omgeving te draaien. Hierdoor kan de stabiliteit van het opzetten of uitrollen van een applicatie juist worden vergroot. Zo kunnen 'provision tools' het bouwen van images (met behulp van de 'Dockerfile' bestanden) en het (her)starten en stoppen van containers verzorgen.

Ook zijn er inmiddels hulpmiddelen beschikbaar om Docker in te zetten bij een infrastructuur met gedistribueerde componenten.

## Gedistribueerde componenten

Omdat Docker geen bewustzijn heeft van andere servers en enkel de containers op de eigen server beheert, is er uiteraard behoefte aan een middel die de distributie van containers verzorgt. Denk hierbij aan het verdelen van de serverlast over meerdere servers. Bij bijvoorbeeld duizenden page requests naar een webserver is het wenselijk dat de werklast wordt verdeeld, om ervoor te zorgen dat de server niet overbelast raakt.

Ondanks de recente lancering zijn er al meerdere partijen die dit probleem oplossen:

1. [Weave](https://github.com/zettio/weave)
2. [Kubernetes](http://kubernetes.io/)
3. [Core OS/Flannen](https://github.com/coreos/flannel)
4. [Pipework](https://github.com/jpetazzo/pipework)
5. [SocketPlane](http://socketplane.io/)
6. [Mezos](http://mesos.apache.org/)

Deze softwarepakketten hebben ieder hun verschillen in aanpak. De keuze hangt hierin af van de eisen die aan de infrastructuur zijn gesteld.

```
- Veel voorkomende problemen bij deployment.
- Hoe kan Docker helpen bij de problemen die zich voordoen?

Bronnen:
- http://thenewstack.io/how-docker-fits-into-the-devops-ecosystem/
- http://www.informationweek.com/cloud/infrastructure-as-a-service/chef-finds-docker-a-close-fit/d/d-id/1297282
- http://recursivity.com/blog/2014/09/08/how-ansible-docker-fit-using-ansible-to-bootstrap-coordinate-docker-containers/
- http://www.wired.com/2014/06/eric-brewer-google-docker/
- http://computerworld.nl/beveiliging/84279-5-projecten-die-docker-completeren

Notes:
- Infrastructuur
- Systeembeheerders
- Oplossing
	- Gelijke ontwikkelomgeving (aligned environments, door zelfde base image, die gegarandeerd overal hetzelfde is)
	- Gestandaardiseerde/uniforme aanpak
	- Deployments
- Schalen van applicatie
- In productie:
	- Grote deployments
	- Geautomatiseerde deployment op (nieuwe) server
	- Het inzetten van een backup bij uitval
- Kan ook samen werken met Chef, Puppet, Ansible etc.
	- Om elkaar te versterken
	- Process/application container
```


text:
package org.apache.jackrabbit.oak.plugins.commit;

import static com.google.common.collect.Lists.newArrayList;
import static org.apache.jackrabbit.JcrConstants.JCR_MIXINTYPES;
import static org.apache.jackrabbit.JcrConstants.JCR_PRIMARYTYPE;
import static org.apache.jackrabbit.oak.api.Type.NAMES;
import static org.apache.jackrabbit.oak.spi.nodetype.NodeTypeConstants.MIX_REP_MERGE_CONFLICT;
import static org.apache.jackrabbit.oak.spi.nodetype.NodeTypeConstants.REP_OURS;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.ADD_EXISTING_NODE;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.ADD_EXISTING_PROPERTY;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.CHANGE_CHANGED_PROPERTY;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.CHANGE_DELETED_NODE;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.CHANGE_DELETED_PROPERTY;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.DELETE_CHANGED_NODE;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.DELETE_CHANGED_PROPERTY;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.DELETE_DELETED_NODE;
import static org.apache.jackrabbit.oak.spi.state.ConflictType.DELETE_DELETED_PROPERTY;

import java.util.List;

import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.spi.nodetype.NodeTypeConstants;
import org.apache.jackrabbit.oak.spi.commit.ThreeWayConflictHandler;
import org.apache.jackrabbit.oak.spi.state.ConflictType;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.jetbrains.annotations.NotNull;

/**
 * This {@link ThreeWayConflictHandler} implementation resolves conflicts to
 * {@link org.apache.jackrabbit.oak.spi.commit.ThreeWayConflictHandler.Resolution#THEIRS} and in addition marks nodes where a
 * conflict occurred with the mixin {@code rep:MergeConflict}:
 *
 * <pre>
 * [rep:MergeConflict]
 *   mixin
 *   primaryitem rep:ours
 *   + rep:ours (rep:Unstructured) protected IGNORE
 * </pre>
 *
 * The {@code rep:ours} sub node contains our version of the node prior to
 * the conflict.
 *
 * @see ConflictValidator
 */
public class AnnotatingConflictHandler implements ThreeWayConflictHandler {

    @NotNull
    @Override
    public Resolution addExistingProperty(@NotNull NodeBuilder parent, @NotNull PropertyState ours, @NotNull PropertyState theirs) {
        NodeBuilder marker = addConflictMarker(parent);
        createChild(marker, ADD_EXISTING_PROPERTY).setProperty(ours);
        return Resolution.THEIRS;
    }

    @NotNull
    @Override
    public Resolution changeDeletedProperty(@NotNull NodeBuilder parent, @NotNull PropertyState ours, @NotNull PropertyState base) {
        NodeBuilder marker = addConflictMarker(parent);
        createChild(marker, CHANGE_DELETED_PROPERTY).setProperty(ours);
        return Resolution.THEIRS;
    }

    @NotNull
    @Override
    public Resolution changeChangedProperty(@NotNull NodeBuilder parent, @NotNull PropertyState ours, @NotNull PropertyState theirs,
                                            @NotNull PropertyState base) {
        NodeBuilder marker = addConflictMarker(parent);
        createChild(marker, CHANGE_CHANGED_PROPERTY).setProperty(ours);
        return Resolution.THEIRS;
    }

    @NotNull
    @Override
    public Resolution deleteChangedProperty(@NotNull NodeBuilder parent, @NotNull PropertyState theirs, @NotNull PropertyState base) {
        NodeBuilder marker = addConflictMarker(parent);
        createChild(marker, DELETE_CHANGED_PROPERTY).setProperty(theirs);
        return Resolution.THEIRS;
    }

    @NotNull
    @Override
    public Resolution deleteDeletedProperty(@NotNull NodeBuilder parent, @NotNull PropertyState base) {
        NodeBuilder marker = addConflictMarker(parent);
        createChild(marker, DELETE_DELETED_PROPERTY).setProperty(base);
        return Resolution.THEIRS;
    }

    @NotNull
    @Override
    public Resolution addExistingNode(@NotNull NodeBuilder parent, @NotNull String name, @NotNull NodeState ours, @NotNull NodeState theirs) {
        NodeBuilder marker = addConflictMarker(parent);
        createChild(marker, ADD_EXISTING_NODE).setChildNode(name, ours);
        return Resolution.THEIRS;
    }

    @NotNull
    @Override
    public Resolution changeDeletedNode(@NotNull NodeBuilder parent, @NotNull String name, @NotNull NodeState ours, @NotNull NodeState base) {
        NodeBuilder marker = addConflictMarker(parent);
        createChild(marker, CHANGE_DELETED_NODE).setChildNode(name, ours);
        return Resolution.THEIRS;
    }

    @NotNull
    @Override
    public Resolution deleteChangedNode(@NotNull NodeBuilder parent, @NotNull String name, @NotNull NodeState theirs, @NotNull NodeState base) {
        NodeBuilder marker = addConflictMarker(parent);
        markChild(createChild(marker, DELETE_CHANGED_NODE), name);
        return Resolution.THEIRS;
    }

    @NotNull
    @Override
    public Resolution deleteDeletedNode(@NotNull NodeBuilder parent, @NotNull String name, @NotNull NodeState base) {
        NodeBuilder marker = addConflictMarker(parent);
        markChild(createChild(marker, DELETE_DELETED_NODE), name);
        return Resolution.THEIRS;
    }

    private static NodeBuilder addConflictMarker(@NotNull NodeBuilder parent) {
        List<String> mixins = newArrayList(parent.getNames(JCR_MIXINTYPES));
        if (mixins.add(MIX_REP_MERGE_CONFLICT)) {
            parent.setProperty(JCR_MIXINTYPES, mixins, NAMES);
        }
        NodeBuilder repOurs = parent.child(REP_OURS);
        repOurs.setProperty(JCR_PRIMARYTYPE, NodeTypeConstants.NT_REP_UNSTRUCTURED, Type.NAME);
        return repOurs;
    }

    @NotNull
    private static NodeBuilder createChild(@NotNull NodeBuilder parent, @NotNull ConflictType ct) {
        return parent.child(ct.getName());
    }

    private static void markChild(@NotNull NodeBuilder parent, @NotNull String name) {
        parent.child(name);
    }

}


text:
This build step invokes `singularity` commands in [Google Cloud Build](cloud.google.com/cloud-build/).

Arguments passed to this builder will be passed to `singularity` directly,
allowing callers to run [any singularity
command](https://www.sylabs.io/guides/3.0/user-guide/cli.html).


text:
<?php

use Tester\Assert;
use WebinoImageThumb\Service\ImageThumb;
use Zend\Mvc\Application;
use Zend\ServiceManager\ServiceManager;

require __DIR__ . '/../bootstrap.php';

$app = createApp();
$services = $app->getServiceManager();
$imageThumb = $services->get('WebinoImageThumb');

Assert::type(Application::class, $app);
Assert::type(ServiceManager::class, $services);
Assert::type(ImageThumb::class, $imageThumb);


text:
package org.scalaide.debug.internal.preferences

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer
import org.eclipse.jface.preference.BooleanFieldEditor
import org.eclipse.jface.preference.FieldEditorPreferencePage
import org.eclipse.jface.preference.IntegerFieldEditor
import org.eclipse.swt.widgets.Composite
import org.eclipse.ui.IWorkbench
import org.eclipse.ui.IWorkbenchPreferencePage
import org.scalaide.debug.internal.ui.ExpressionEvaluatorViewLayoutType
import org.scalaide.debug.internal.expression.ScalaExpressionEvaluatorPlugin
import org.eclipse.swt.layout.GridLayout

class ExprEvalPreferencePage extends FieldEditorPreferencePage(FieldEditorPreferencePage.GRID) with IWorkbenchPreferencePage {
  import ExprEvalPreferencePage._

  setPreferenceStore(ScalaExpressionEvaluatorPlugin().getPreferenceStore)

  override def createFieldEditors(): Unit = {
    val c = getFieldEditorParent
    c.setLayout(new GridLayout(1, false))
    addBooleanField(EnableCodeCompletion, "Enable simple, experimental, temporary code completion", c)

    val collectionAndArrayValuesGroupSize = new IntegerFieldEditor(CollectionAndArrayValuesGroupSize,
      "Number of collection elements shown in logical structure:", c)
    collectionAndArrayValuesGroupSize.setValidRange(1, Integer.MAX_VALUE)
    addField(collectionAndArrayValuesGroupSize)

    addBooleanField(ShowStaticFieldsInTreeView, "Show static fields in tree view", c)
    addBooleanField(ShowSyntheticFieldsInTreeView, "Show synthetic fields in tree view", c)
    addBooleanField(RefreshVariablesViewAfterEvaluation, "Refresh variables view after evaluation", c)
    addBooleanField(AddImportsFromCurrentFile, "Add imports from current file", c)
  }

  override def init(workbench: IWorkbench): Unit = {}

  override def dispose: Unit = {
    super.dispose()
  }

  private def addBooleanField(name: String, label: String, parent: Composite): Unit =
    addField(new BooleanFieldEditor(name, label, parent))
}

object ExprEvalPreferencePage {
  val EnableCodeCompletion = "org.scala-ide.sdt.debug.expression.expEval.codeCompletion"
  val ShowLineNumbers = "org.scala-ide.sdt.debug.expression.expEval.enableLineNumbersByDefault"
  val CollectionAndArrayValuesGroupSize = "org.scala-ide.sdt.debug.expression.expEval.arrayValuesGroupSize"
  val LayoutType = "org.scala-ide.sdt.debug.expression.expEval.layoutType"
  val ShowStaticFieldsInTreeView = "org.scala-ide.sdt.debug.expression.expEval.showStaticFieldsInTreeView"
  val ShowSyntheticFieldsInTreeView = "org.scala-ide.sdt.debug.expression.expEval.showSyntheticFieldsInTreeView"
  val ShowCollectionsLogicalStructure = "org.scala-ide.sdt.debug.expression.expEval.showCollectionsLogicalStructureInTreeView"
  val RefreshVariablesViewAfterEvaluation = "org.scala-ide.sdt.debug.expEval.refreshVariablesViewAfterEvaluation"
  val AddImportsFromCurrentFile = "org.scala-ide.sdt.debug.expression.expEval.addImportsFromCurrentFile"
}

class ExprEvalPreferencesInitializer extends AbstractPreferenceInitializer {
  import ExprEvalPreferencePage._

  override def initializeDefaultPreferences(): Unit = {
    val store = ScalaExpressionEvaluatorPlugin().getPreferenceStore

    store.setDefault(EnableCodeCompletion, false)
    store.setDefault(ShowLineNumbers, false)
    store.setDefault(ShowStaticFieldsInTreeView, true)
    store.setDefault(ShowSyntheticFieldsInTreeView, true)
    store.setDefault(CollectionAndArrayValuesGroupSize, 100)
    store.setDefault(LayoutType, ExpressionEvaluatorViewLayoutType.ConsoleAndTreeHorizontally.id.toString())
    store.setDefault(ShowCollectionsLogicalStructure, true)
    store.setDefault(RefreshVariablesViewAfterEvaluation, true)
    store.setDefault(AddImportsFromCurrentFile, false)
  }
}