text:
<?php

namespace Cs278\BankModulus;

/**
 * @covers \Cs278\BankModulus\BankAccountNormalized
 */
final class BankAccountNormalizedTest extends \PHPUnit\Framework\TestCase
{
    /** @dataProvider dataWithInvalidAccountNumber */
    public function testWithInvalidAccountNumber($accountNumber)
    {
        try {
            new BankAccountNormalized(
                new BankAccount('112233', '123456'),
                '112233',
                $accountNumber
            );
        } catch (\Exception $e) {
            $this->assertInstanceOf('InvalidArgumentException', $e);
            $this->assertInstanceOf('Cs278\BankModulus\Exception\InvalidArgumentException', $e);
            $this->assertInstanceOf('Cs278\BankModulus\Exception\Exception', $e);

            if (\is_string($accountNumber)) {
                $this->assertInstanceOf('Cs278\BankModulus\Exception\AccountNumberInvalidException', $e);
            } else {
                $this->assertNotInstanceOf('Cs278\BankModulus\Exception\AccountNumberInvalidException', $e);
            }

            return;
        }

        $this->fail('Failed to catch exception');
    }

    public function testGetOriginalBankAccount()
    {
        $account = BankAccountNormalized::createFromBankAccount(
            $original = new BankAccount('112233', '12345678')
        );

        $this->assertSame($original, $account->getOriginalBankAccount());
    }

    public function testGetSortCodeWithObject()
    {
        $sortCode = new SortCode('112233');
        $account = BankAccountNormalized::createFromBankAccount(
            new BankAccount($sortCode, '12345678')
        );

        $this->assertSame($sortCode, $account->getSortCode());
    }

    public function testGetSortCodeWithString()
    {
        $account = BankAccountNormalized::createFromBankAccount(
            new BankAccount('11-22 33', '12345678')
        );

        $this->assertSame('112233', $account->getSortCode()->format('%s%s%s'));
    }

    public function testGetAccountNumber()
    {
        $account = BankAccountNormalized::createFromBankAccount(
            new BankAccount('112233', 'AC1-2345678')
        );

        $this->assertSame('12345678', $account->getAccountNumber());
    }

    public function testToString()
    {
        $account = BankAccountNormalized::createFromBankAccount(
            new BankAccount('144441', '25555552')
        );

        $this->assertSame('14444125555552', $account->__toString());
    }

    public function dataWithInvalidAccountNumber()
    {
        return [
            [true],
            [12345678],
            [new \stdClass()],
            [[]],
            [''],
            ['X'],
            ['1234567A'],
            ['1234567'],
            ['123456789'],
            ['1234567890'],
        ];
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Date_Deceased__c</name>
    <label>Sterbedatum</label>
</CustomFieldTranslation>

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os
import time
import copy
import sys
import numpy as np
import importlib
import itertools
import argparse
import math
import json
import random
#from guuker import prt

SEED = 727

DATA_ROOT = '/raid5data/dplearn/carvn'

id2images = {}

image_size = (1280, 1918)
patch_size = 1000
move = (280, 306)  # 2*3 patches

train_image_dir = os.path.join(DATA_ROOT, 'train')
for image in os.listdir(train_image_dir):
  image = image.strip()
  if not image.endswith('.jpg'):
    continue
  basename = image.split('.')[0]
  image_id, pos = basename.split('_')
  if image_id not in id2images:
    id2images[image_id] = 1
  #id2images[image_id].append(os.path.join(train_image_dir, image))
  #id2images[image_id].append( (image_id, pos) )

id2images = sorted(id2images.items(), key = lambda x: x[0])
random.Random(SEED).shuffle(id2images)
train_f = open('train.lst', 'w')
val_f = open('val.lst', 'w')
val_count = len(id2images)//10
for i in xrange(len(id2images)):
  #f = val_f if i<val_count else train_f
  image_id = id2images[i][0]
  idxs = range(1, 17)
  random.Random(SEED).shuffle(idxs)
  for idx in idxs:
    data_image = os.path.join(DATA_ROOT, 'train', "%s_%02d.jpg" % (image_id, idx))
    mask_image = os.path.join(DATA_ROOT, 'train_masks', "%s_%02d_mask.gif" % (image_id, idx))
    for h in xrange(0,image_size[0]-patch_size+1,move[0]):
      for w in xrange(0, image_size[1]-patch_size+1, move[1]):
        oline = "%d\t%s\t%s\t%d\t%d\t%d\t%d\n" % (0, data_image, mask_image, h, h+patch_size, w, w+patch_size)
        train_f.write(oline)
        if i<val_count:
          val_f.write(oline)

train_f.close()
val_f.close()


text:
#ifndef QMITK_AUTOCROPACTION_H
#define QMITK_AUTOCROPACTION_H

#include "mitkIContextMenuAction.h"

#include "org_mitk_gui_qt_segmentation_Export.h"

#include "vector"
#include "mitkDataNode.h"
#include "mitkImage.h"

class MITK_QT_SEGMENTATION QmitkAutocropAction : public QObject, public mitk::IContextMenuAction
{
  Q_OBJECT
  Q_INTERFACES(mitk::IContextMenuAction)

public:

  QmitkAutocropAction();
  ~QmitkAutocropAction() override;

  //interface methods
  void Run( const QList<mitk::DataNode::Pointer>& selectedNodes ) override;
  void SetDataStorage(mitk::DataStorage* dataStorage) override;
  void SetSmoothed(bool smoothed) override;
  void SetDecimated(bool decimated) override;
  void SetFunctionality(berry::QtViewPart* view) override;

protected:

  mitk::Image::Pointer IncreaseCroppedImageSize( mitk::Image::Pointer image );

private:

  typedef QList<mitk::DataNode::Pointer> NodeList;

};

#endif // QMITK_AUTOCROPACTION_H


text:
var Vector = function () {
    function Vector(x, y) {
        this.x = x || 0;
        this.y = y || 0;
    }
    Vector.make = function (a, b) {
        return new Vector(b.x - a.x, b.y - a.y);
    };
    Vector.size = function (a) {
        return Math.sqrt(a.x * a.x + a.y * a.y);
    };
    Vector.normalize = function (a) {
        var l = Vector.size(a);
        a.x /= l;
        a.y /= l;
        return a;
    };
    Vector.incidence = function (a, b) {
        var angle = Math.atan2(b.y, b.x) - Math.atan2(a.y, a.x);
        // if (angle < 0) angle += 2 * Math.PI;
        // angle = Math.min(angle, (Math.PI * 2 - angle));
        return angle;
    };
    Vector.distance = function (a, b) {
        return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
    };
    Vector.cross = function (a, b) {
        return (a.x * b.y) - (a.y * b.x);
    };
    Vector.difference = function (a, b) {
        return new Vector(b.x - a.x, b.y - a.y);
    };
    Vector.prototype = {
        size: function () {
            return Vector.size(this);
        },
        normalize: function () {
            return Vector.normalize(this);
        },
        incidence: function (b) {
            return Vector.incidence(this, b);
        },
        cross: function (b) {
            return Vector.cross(this, b);
        },
        towards: function (b, friction) {
            friction = friction || 0.125;
            this.x += (b.x - this.x) * friction;
            this.y += (b.y - this.y) * friction;
            return this;
        },
        add: function (b) {
            this.x += b.x;
            this.y += b.y;
            return this;
        },
        friction: function (b) {
            this.x *= b;
            this.y *= b;
            return this;
        },
        copy: function (b) {
            return new Vector(this.x, this.y);
        },
        toString: function () {
            return '{' + this.x + ',' + this.y + '}';
        },
    };
    return Vector;
}();

var Utils = function () {

    (function () {
        var lastTime = 0;
        var vendors = ['ms', 'moz', 'webkit', 'o'];
        for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
            window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']
                                       || window[vendors[x] + 'CancelRequestAnimationFrame'];
        }
        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = function (callback, element) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };
        }
        if (!window.cancelAnimationFrame) {
            window.cancelAnimationFrame = function (id) {
                clearTimeout(id);
            };
        }
    }());

    var transformProperty = function detectTransformProperty() {
        var transformProperty = 'transform',
            safariPropertyHack = 'webkitTransform';
        var div = document.createElement("DIV");
        if (typeof div.style[transformProperty] !== 'undefined') {
            ['webkit', 'moz', 'o', 'ms'].every(function (prefix) {
                var e = '-' + prefix + '-transform';
                if (typeof div.style[e] !== 'undefined') {
                    transformProperty = e;
                    return false;
                }
                return true;
            });
        } else if (typeof div.style[safariPropertyHack] !== 'undefined') {
            transformProperty = '-webkit-transform';
        } else {
            transformProperty = undefined;
        }
        return transformProperty;
    }();

    function getTouch(e, previous) {
        var t = new Vector();
        if (e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel') {
            var touch = null;
            var event = e.originalEvent ? e.originalEvent : e;
            // event.stopImmediatePropagation();
            // event.currentTarget.removeEventListener('mousedown mousemove mouseup');
            var touches = event.touches.length ? event.touches : event.changedTouches;
            if (touches && touches.length) {
                touch = touches[0];
            }
            if (touch) {
                t.x = touch.pageX;
                t.y = touch.pageY;
            }
        } else if (e.type == 'click' || e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover' || e.type == 'mouseout' || e.type == 'mouseenter' || e.type == 'mouseleave') {
            t.x = e.pageX;
            t.y = e.pageY;
        }
        if (previous) {
            t.s = Vector.difference(previous, t);
        }
        t.type = e.type;
        return t;
    }

    function getRelativeTouch(element, point) {
        var st = window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0);
        var rect = element[0].getBoundingClientRect();
        var e = new Vector(rect.left, rect.top + st);
        return Vector.difference(e, point);
    }

    function getClosest(el, selector) {
        var matchesFn, parent;
        ['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'].some(function (fn) {
            if (typeof document.body[fn] == 'function') {
                matchesFn = fn;
                return true;
            }
            return false;
        });
        while (el !== null) {
            parent = el.parentElement;
            if (parent !== null && parent[matchesFn](selector)) {
                return parent;
            }
            el = parent;
        }
        return null;
    }

    function indexOf(array, object, key) {
        key = key || 'id';
        var index = -1;
        if (array) {
            var i = 0, t = array.length;
            while (i < t) {
                if (array[i] && array[i][key] === object[key]) {
                    index = i;
                    break;
                }
                i++;
            }
        }
        return index;
    }

    function removeValue(array, value) {
        var index = -1;
        if (array) {
            var i = 0, t = array.length;
            while (i < t) {
                if (array[i] === value) {
                    index = i;
                    break;
                }
                i++;
            }
        }
        if (index !== -1) {
            array.splice(index, 1);
            return value;
        } else {
            return null;
        }
    }

    function parseHour(duration, offset) {
        offset = offset || 0;
        duration = duration - offset * 60 * 1000;
        var milliseconds = parseInt((duration % 1000) / 100)
            , seconds = parseInt((duration / 1000) % 60)
            , minutes = parseInt((duration / (1000 * 60)) % 60)
            , hours = parseInt((duration / (1000 * 60 * 60)) % 24);

        var hours = (hours < 10) ? "0" + hours : hours;
        var minutes = (minutes < 10) ? "0" + minutes : minutes;
        var seconds = (seconds < 10) ? "0" + seconds : seconds;
        return hours + ':' + minutes + ':' + seconds; // + "." + milliseconds;
    }

    function parseTime(duration, offset) {
        offset = offset || 0;
        duration = duration - offset * 60 * 1000;
        var milliseconds = parseInt((duration % 1000) / 100)
            , seconds = parseInt((duration / 1000) % 60)
            , minutes = parseInt((duration / (1000 * 60)) % 60)
            , hours = parseInt((duration / (1000 * 60 * 60)) % 24);

        return (hours ? hours + 'h ' : '') + (minutes ? minutes + '\' ' : '') + (seconds ? seconds + '\'\' ' : ''); // + "." + milliseconds;
    }

    var getNow = Date.now || function () {
        return new Date().getTime();
    };

    function throttle(func, wait, options) {
        // Returns a function, that, when invoked, will only be triggered at most once
        // during a given window of time. Normally, the throttled function will run
        // as much as it can, without ever going more than once per `wait` duration;
        // but if you'd like to disable the execution on the leading edge, pass
        // `{leading: false}`. To disable execution on the trailing edge, ditto.
        var context, args, result;
        var timeout = null;
        var previous = 0;
        if (!options) options = {};
        var later = function () {
            previous = options.leading === false ? 0 : getNow();
            timeout = null;
            result = func.apply(context, args);
            if (!timeout) context = args = null;
        };
        return function () {
            var now = getNow();
            if (!previous && options.leading === false) previous = now;
            var remaining = wait - (now - previous);
            context = this;
            args = arguments;
            if (remaining <= 0 || remaining > wait) {
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = null;
                }
                previous = now;
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            } else if (!timeout && options.trailing !== false) {
                timeout = setTimeout(later, remaining);
            }
            return result;
        };
    }

    var Style = function () {
        function Style() {
            this.props = {
                scale: 1,
                hoverScale: 1,
                currentScale: 1,
            }
        }
        Style.prototype = {
            set: function (element) {
                var styles = [];
                for (var key in this) {
                    if (key !== 'props') {
                        styles.push(key + ':' + this[key]);
                    }
                }
                element.style.cssText = styles.join(';') + ';';
            },
            transform: function (transform) {
                this[Utils.transformProperty] = transform;
            },
            transformOrigin: function (x, y) {
                this[Utils.transformProperty + '-origin-x'] = (Math.round(x * 1000) / 1000) + '%';
                this[Utils.transformProperty + '-origin-y'] = (Math.round(y * 1000) / 1000) + '%';
            },
        };
        return Style;
    }();

    var Cookie = function () {
        function Cookie() {
        }

        Cookie._set = function (name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            } else {
                var expires = "";
            }
            window.document.cookie = name + "=" + value + expires + "; path=/";
        }

        Cookie.set = function (name, value, days) {
            try {
                var cache = [];
                var json = JSON.stringify(value, function (key, value) {
                    if (key === 'pool') {
                        return;
                    }
                    if (typeof value === 'object' && value !== null) {
                        if (cache.indexOf(value) !== -1) {
                            // Circular reference found, discard key
                            return;
                        }
                        cache.push(value);
                    }
                    return value;
                });
                cache = null;
                Cookie._set(name, json, days);
            } catch (e) {
                console.log('Cookie.set.error serializing', name, value, e);
            }
        };

        Cookie.get = function (name) {
            var cookieName = name + "=";
            var ca = window.document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(cookieName) == 0) {
                    var value = c.substring(cookieName.length, c.length);
                    var data = null;
                    try {
                        data = JSON.parse(value);
                    } catch (e) {
                        console.log('Cookie.get.error parsing', key, e);
                    };
                    return data;
                }
            }
            return null;
        };

        Cookie.delete = function (name) {
            Cookie._set(name, "", -1);
        };

        Cookie.on = function (name) {
            var deferred = $q.defer();
            var i, interval = 1000, elapsed = 0, timeout = 60 * 1000;
            function checkCookie() {
                if (elapsed > timeout) {
                    deferred.reject('timeout');
                } else {
                    var c = Cookie.get(name);
                    if (c) {
                        deferred.resolve(c);
                    } else {
                        elapsed += interval;
                        i = setTimeout(checkCookie, interval);
                    }
                }
            }
            checkCookie();
            return deferred.promise;
        };

        return Cookie;
    }();

    var LocalStorage = function () {
        function LocalStorage() {
        }

        function isLocalStorageSupported() {
            var supported = false;
            try {
                supported = 'localStorage' in window && window['localStorage'] !== null;
                if (supported) {
                    window.localStorage.setItem('test', '1');
                    window.localStorage.removeItem('test');
                } else {
                    supported = false;
                }
            } catch (e) {
                supported = false;
            }
            return supported;
        }
        LocalStorage.isSupported = isLocalStorageSupported();

        if (LocalStorage.isSupported) {
            LocalStorage.set = function (name, value) {
                try {
                    var cache = [];
                    var json = JSON.stringify(value, function (key, value) {
                        if (key === 'pool') {
                            return;
                        }
                        if (typeof value === 'object' && value !== null) {
                            if (cache.indexOf(value) !== -1) {
                                // Circular reference found, discard key
                                return;
                            }
                            cache.push(value);
                        }
                        return value;
                    });
                    cache = null;
                    window.localStorage.setItem(name, json);
                } catch (e) {
                    console.log('LocalStorage.set.error serializing', name, value, e);
                }
            };

            LocalStorage.get = function (name) {
                var value = null;
                if (window.localStorage[name] !== undefined) {
                    try {
                        value = JSON.parse(window.localStorage[name]);
                    } catch (e) {
                        console.log('LocalStorage.get.error parsing', name, e);
                    }
                }
                return value;
            };

            LocalStorage.delete = function (name) {
                window.localStorage.removeItem(name);
            };

            LocalStorage.on = function (name) {
                var deferred = $q.defer();
                var i, timeout = 60 * 1000;
                function storageEvent(e) {
                    // console.log('LocalStorage.on', name, e);
                    clearTimeout(i);
                    if (e.originalEvent.key == name) {
                        try {
                            var value = JSON.parse(e.originalEvent.newValue); // , e.originalEvent.oldValue
                            deferred.resolve(value);
                        } catch (e) {
                            console.log('LocalStorage.on.error parsing', name, e);
                            deferred.reject('error parsing ' + name);
                        }
                    }
                }
                if (window.addEventListener) {
                    window.addEventListener('storage', storageEvent, false);
                } else {
                    window.attachEvent('onstorage', storageEvent);
                }
                i = setTimeout(function () {
                    deferred.reject('timeout');
                }, timeout);
                return deferred.promise;
            };

        } else {
            console.log('LocalStorage.unsupported switching to cookies');
            LocalStorage.set = Cookie.set;
            LocalStorage.get = Cookie.get;
            LocalStorage.delete = Cookie.delete;
            LocalStorage.on = Cookie.on;

        }

        return LocalStorage;
    }();

    function Utils() {

    }

    Utils.transformProperty = transformProperty;
    Utils.getTouch = getTouch;
    Utils.getRelativeTouch = getRelativeTouch;
    Utils.getClosest = getClosest;
    Utils.indexOf = indexOf;
    Utils.removeValue = removeValue;
    Utils.parseHour = parseHour;
    Utils.parseTime = parseTime;
    Utils.throttle = throttle;
    Utils.Style = Style;
    Utils.LocalStorage = LocalStorage;
    Utils.Cookie = Cookie;

    return Utils;

}();


text:
""" @Imports """
from django.test.testcases import TestCase
from cuescience_cart.tests.support.support import TestSupport

class TestUpdateQuantityZero(TestCase):
    def setUp(self):
        self.test_support = TestSupport(self)

    def test(self):
        """
         The code in this method is generated from: /cuescience-shop/shop/tests/views/update_view/test_update_quantity_zero.natspec
         Never change this method or any contents of this file, all local changes will we overwritten.
        """


text:
package org.coinj.dash;

import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.wallet.Protos;
import org.bitcoinj.wallet.WalletTransaction;
import org.coinj.api.TransactionExtension;
import org.coinj.api.WalletProtobufSerializerExtension;

import javax.annotation.Nullable;

/**
* Date: 5/17/15
* Time: 1:36 PM
*
* @author Mikhail Kulikov
*/
public final class DashWalletProtobufSerializerExtension implements WalletProtobufSerializerExtension {

    static final DashWalletProtobufSerializerExtension INSTANCE = new DashWalletProtobufSerializerExtension();

    private DashWalletProtobufSerializerExtension() {}

    @Nullable
    @Override
    public Protos.Transaction.Pool getProtoExtendedPool(WalletTransaction.Pool pool) {
        if (pool == DashWalletCoinSpecifics.INSTANTX_PENDING) {
            return Protos.Transaction.Pool.INSTANTX_PENDING;
        } else if (pool == DashWalletCoinSpecifics.INSTANTX_LOCKED) {
            return Protos.Transaction.Pool.INSTANTX_LOCKED;
        } else {
            return null;
        }
    }

    @Nullable
    @Override
    public WalletTransaction.Pool getTxsExtendedPool(Protos.Transaction.Pool pool) {
        switch (pool) {
            case INSTANTX_LOCKED:
                return DashWalletCoinSpecifics.INSTANTX_LOCKED;
            case INSTANTX_PENDING:
                return DashWalletCoinSpecifics.INSTANTX_PENDING;
            default:
                return null;
        }
    }

    @Nullable
    @Override
    public TransactionConfidence.ConfidenceType getTxsExtendedConfidenceType(Protos.TransactionConfidence.Type type) {
        switch (type) {
            case INSTANTX_PENDING:
                return DashTransactionConfidenceExtension.INSTANTX_PENDING;
            case INSTANTX_LOCKED:
                return DashTransactionConfidenceExtension.INSTANTX_LOCKED;
            default:
                return null;
        }
    }

    @Override
    public Protos.TransactionExtension protoFromTransactionExtension(TransactionExtension txExtension) {
        final DashTransactionExtension dashTxExt = CommonUtils.extractTransactionExtension(txExtension);
        final Protos.TransactionExtension.Builder builder = Protos.TransactionExtension.newBuilder();
        final DashTransactionWireStrategy wireStrategy = dashTxExt.getWireStrategy();

        final Protos.TransactionExtension.WireStrategy protoWireStrategy;
        if (wireStrategy != null) {
            switch (wireStrategy) {
                case INSTANT_X:
                    protoWireStrategy = Protos.TransactionExtension.WireStrategy.INSTANT_X; break;
                case INSTANT_X_LOCKED:
                    protoWireStrategy = Protos.TransactionExtension.WireStrategy.INSTANT_X_LOCKED; break;
                case STANDARD:
                    // fall down
                default:
                    protoWireStrategy = Protos.TransactionExtension.WireStrategy.STANDARD;
            }
        } else {
            protoWireStrategy = Protos.TransactionExtension.WireStrategy.STANDARD;
        }

        builder.setWireStrategy(protoWireStrategy);
        builder.setLockTime(dashTxExt.getLockingTime());
        return builder.build();
    }

    @Override
    public DashTransactionExtension transactionExtensionFromProto(Protos.TransactionExtension txExtension, Transaction tx) {
        final DashTransactionExtension dashTxExt = CommonUtils.extractDefinition(tx.getParams()).createTransactionExtension(tx);
        final Protos.TransactionExtension.WireStrategy wireStrategy = txExtension.getWireStrategy();
        final DashTransactionWireStrategy dashWireStrategy;
        switch (wireStrategy) {
            case INSTANT_X:
                dashWireStrategy = DashTransactionWireStrategy.INSTANT_X;
                break;
            case INSTANT_X_LOCKED:
                dashWireStrategy = DashTransactionWireStrategy.INSTANT_X_LOCKED;
                break;
            case STANDARD:
                // fall down
            default:
                dashWireStrategy = DashTransactionWireStrategy.STANDARD;
        }
        dashTxExt.setWireStrategy(dashWireStrategy);
        if (dashWireStrategy != DashTransactionWireStrategy.STANDARD)
            dashTxExt.setLockingTime(txExtension.getLockTime());
        return dashTxExt;
    }

}


text:
#ifndef __QLCNIC_HW_H
#define __QLCNIC_HW_H

/* Common registers in 83xx and 82xx */
enum qlcnic_regs {
	QLCNIC_PEG_HALT_STATUS1 = 0,
	QLCNIC_PEG_HALT_STATUS2,
	QLCNIC_PEG_ALIVE_COUNTER,
	QLCNIC_FLASH_LOCK_OWNER,
	QLCNIC_FW_CAPABILITIES,
	QLCNIC_CRB_DRV_ACTIVE,
	QLCNIC_CRB_DEV_STATE,
	QLCNIC_CRB_DRV_STATE,
	QLCNIC_CRB_DRV_SCRATCH,
	QLCNIC_CRB_DEV_PARTITION_INFO,
	QLCNIC_CRB_DRV_IDC_VER,
	QLCNIC_FW_VERSION_MAJOR,
	QLCNIC_FW_VERSION_MINOR,
	QLCNIC_FW_VERSION_SUB,
	QLCNIC_CRB_DEV_NPAR_STATE,
	QLCNIC_FW_IMG_VALID,
	QLCNIC_CMDPEG_STATE,
	QLCNIC_RCVPEG_STATE,
	QLCNIC_ASIC_TEMP,
	QLCNIC_FW_API,
	QLCNIC_DRV_OP_MODE,
	QLCNIC_FLASH_LOCK,
	QLCNIC_FLASH_UNLOCK,
};

/* Read from an address offset from BAR0, existing registers */
#define QLC_SHARED_REG_RD32(a, addr)			\
	readl(((a)->ahw->pci_base0) + ((a)->ahw->reg_tbl[addr]))

/* Write to an address offset from BAR0, existing registers */
#define QLC_SHARED_REG_WR32(a, addr, value)		\
	writel(value, ((a)->ahw->pci_base0) + ((a)->ahw->reg_tbl[addr]))

/* Read from a direct address offset from BAR0, additional registers */
#define QLCRDX(ahw, addr)	\
	readl(((ahw)->pci_base0) + ((ahw)->ext_reg_tbl[addr]))

/* Write to a direct address offset from BAR0, additional registers */
#define QLCWRX(ahw, addr, value)	\
	writel(value, (((ahw)->pci_base0) + ((ahw)->ext_reg_tbl[addr])))

#define QLCNIC_CMD_CONFIGURE_IP_ADDR		0x1
#define QLCNIC_CMD_CONFIG_INTRPT		0x2
#define QLCNIC_CMD_CREATE_RX_CTX		0x7
#define QLCNIC_CMD_DESTROY_RX_CTX		0x8
#define QLCNIC_CMD_CREATE_TX_CTX		0x9
#define QLCNIC_CMD_DESTROY_TX_CTX		0xa
#define QLCNIC_CMD_CONFIGURE_LRO		0xC
#define QLCNIC_CMD_CONFIGURE_MAC_LEARNING	0xD
#define QLCNIC_CMD_GET_STATISTICS		0xF
#define QLCNIC_CMD_INTRPT_TEST			0x11
#define QLCNIC_CMD_SET_MTU			0x12
#define QLCNIC_CMD_READ_PHY			0x13
#define QLCNIC_CMD_WRITE_PHY			0x14
#define QLCNIC_CMD_READ_HW_REG			0x15
#define QLCNIC_CMD_GET_FLOW_CTL			0x16
#define QLCNIC_CMD_SET_FLOW_CTL			0x17
#define QLCNIC_CMD_READ_MAX_MTU			0x18
#define QLCNIC_CMD_READ_MAX_LRO			0x19
#define QLCNIC_CMD_MAC_ADDRESS			0x1f
#define QLCNIC_CMD_GET_PCI_INFO			0x20
#define QLCNIC_CMD_GET_NIC_INFO			0x21
#define QLCNIC_CMD_SET_NIC_INFO			0x22
#define QLCNIC_CMD_GET_ESWITCH_CAPABILITY	0x24
#define QLCNIC_CMD_TOGGLE_ESWITCH		0x25
#define QLCNIC_CMD_GET_ESWITCH_STATUS		0x26
#define QLCNIC_CMD_SET_PORTMIRRORING		0x27
#define QLCNIC_CMD_CONFIGURE_ESWITCH		0x28
#define QLCNIC_CMD_GET_ESWITCH_PORT_CONFIG	0x29
#define QLCNIC_CMD_GET_ESWITCH_STATS		0x2a
#define QLCNIC_CMD_CONFIG_PORT			0x2e
#define QLCNIC_CMD_TEMP_SIZE			0x2f
#define QLCNIC_CMD_GET_TEMP_HDR			0x30
#define QLCNIC_CMD_BC_EVENT_SETUP		0x31
#define	QLCNIC_CMD_CONFIG_VPORT			0x32
#define	QLCNIC_CMD_DCB_QUERY_CAP		0x34
#define	QLCNIC_CMD_DCB_QUERY_PARAM		0x35
#define QLCNIC_CMD_GET_MAC_STATS		0x37
#define QLCNIC_CMD_82XX_SET_DRV_VER		0x38
#define QLCNIC_CMD_MQ_TX_CONFIG_INTR		0x39
#define QLCNIC_CMD_GET_LED_STATUS		0x3C
#define QLCNIC_CMD_CONFIGURE_RSS		0x41
#define QLCNIC_CMD_CONFIG_INTR_COAL		0x43
#define QLCNIC_CMD_CONFIGURE_LED		0x44
#define QLCNIC_CMD_CONFIG_MAC_VLAN		0x45
#define QLCNIC_CMD_GET_LINK_EVENT		0x48
#define QLCNIC_CMD_CONFIGURE_MAC_RX_MODE	0x49
#define QLCNIC_CMD_CONFIGURE_HW_LRO		0x4A
#define QLCNIC_CMD_SET_INGRESS_ENCAP		0x4E
#define QLCNIC_CMD_INIT_NIC_FUNC		0x60
#define QLCNIC_CMD_STOP_NIC_FUNC		0x61
#define QLCNIC_CMD_IDC_ACK			0x63
#define QLCNIC_CMD_SET_PORT_CONFIG		0x66
#define QLCNIC_CMD_GET_PORT_CONFIG		0x67
#define QLCNIC_CMD_GET_LINK_STATUS		0x68
#define QLCNIC_CMD_SET_LED_CONFIG		0x69
#define QLCNIC_CMD_GET_LED_CONFIG		0x6A
#define QLCNIC_CMD_83XX_SET_DRV_VER		0x6F
#define QLCNIC_CMD_ADD_RCV_RINGS		0x0B
#define QLCNIC_CMD_83XX_EXTEND_ISCSI_DUMP_CAP	0x37

#define QLCNIC_INTRPT_INTX			1
#define QLCNIC_INTRPT_MSIX			3
#define QLCNIC_INTRPT_ADD			1
#define QLCNIC_INTRPT_DEL			2

#define QLCNIC_GET_CURRENT_MAC			1
#define QLCNIC_SET_STATION_MAC			2
#define QLCNIC_GET_DEFAULT_MAC			3
#define QLCNIC_GET_FAC_DEF_MAC			4
#define QLCNIC_SET_FAC_DEF_MAC			5

#define QLCNIC_MBX_LINK_EVENT		0x8001
#define QLCNIC_MBX_BC_EVENT		0x8002
#define QLCNIC_MBX_COMP_EVENT		0x8100
#define QLCNIC_MBX_REQUEST_EVENT	0x8101
#define QLCNIC_MBX_TIME_EXTEND_EVENT	0x8102
#define QLCNIC_MBX_DCBX_CONFIG_CHANGE_EVENT	0x8110
#define QLCNIC_MBX_SFP_INSERT_EVENT	0x8130
#define QLCNIC_MBX_SFP_REMOVE_EVENT	0x8131

struct qlcnic_mailbox_metadata {
	u32 cmd;
	u32 in_args;
	u32 out_args;
};

/* Mailbox ownership */
#define QLCNIC_GET_OWNER(val)	((val) & (BIT_0 | BIT_1))

#define QLCNIC_SET_OWNER        1
#define QLCNIC_CLR_OWNER        0
#define QLCNIC_MBX_TIMEOUT      5000

#define QLCNIC_MBX_RSP_OK	1
#define QLCNIC_MBX_PORT_RSP_OK	0x1a
#define QLCNIC_MBX_ASYNC_EVENT	BIT_15

/* Set HW Tx ring limit for 82xx adapter. */
#define QLCNIC_MAX_HW_TX_RINGS		8
#define QLCNIC_MAX_HW_VNIC_TX_RINGS	4
#define QLCNIC_MAX_TX_RINGS		8
#define QLCNIC_MAX_SDS_RINGS		8

struct qlcnic_pci_info;
struct qlcnic_info;
struct qlcnic_cmd_args;
struct ethtool_stats;
struct pci_device_id;
struct qlcnic_host_sds_ring;
struct qlcnic_host_tx_ring;
struct qlcnic_hardware_context;
struct qlcnic_adapter;
struct qlcnic_fw_dump;

int qlcnic_82xx_hw_read_wx_2M(struct qlcnic_adapter *adapter, ulong, int *);
int qlcnic_82xx_hw_write_wx_2M(struct qlcnic_adapter *, ulong, u32);
int qlcnic_82xx_config_hw_lro(struct qlcnic_adapter *adapter, int);
int qlcnic_82xx_nic_set_promisc(struct qlcnic_adapter *adapter, u32);
int qlcnic_82xx_napi_add(struct qlcnic_adapter *adapter,
			 struct net_device *netdev);
void qlcnic_82xx_get_beacon_state(struct qlcnic_adapter *);
void qlcnic_82xx_change_filter(struct qlcnic_adapter *adapter,
			       u64 *uaddr, u16 vlan_id);
int qlcnic_82xx_config_intr_coalesce(struct qlcnic_adapter *,
				     struct ethtool_coalesce *);
int qlcnic_82xx_set_rx_coalesce(struct qlcnic_adapter *);
int qlcnic_82xx_config_rss(struct qlcnic_adapter *adapter, int);
void qlcnic_82xx_config_ipaddr(struct qlcnic_adapter *adapter,
			       __be32, int);
int qlcnic_82xx_linkevent_request(struct qlcnic_adapter *adapter, int);
void qlcnic_82xx_process_rcv_ring_diag(struct qlcnic_host_sds_ring *sds_ring);
int qlcnic_82xx_clear_lb_mode(struct qlcnic_adapter *adapter, u8);
int qlcnic_82xx_set_lb_mode(struct qlcnic_adapter *, u8);
void qlcnic_82xx_write_crb(struct qlcnic_adapter *, char *, loff_t, size_t);
void qlcnic_82xx_read_crb(struct qlcnic_adapter *, char *, loff_t, size_t);
int qlcnic_82xx_issue_cmd(struct qlcnic_adapter *adapter,
			  struct qlcnic_cmd_args *);
int qlcnic_82xx_mq_intrpt(struct qlcnic_adapter *, int);
int qlcnic_82xx_config_intrpt(struct qlcnic_adapter *, u8);
int qlcnic_82xx_fw_cmd_create_rx_ctx(struct qlcnic_adapter *);
int qlcnic_82xx_fw_cmd_create_tx_ctx(struct qlcnic_adapter *,
				     struct qlcnic_host_tx_ring *tx_ring, int);
void qlcnic_82xx_fw_cmd_del_rx_ctx(struct qlcnic_adapter *);
void qlcnic_82xx_fw_cmd_del_tx_ctx(struct qlcnic_adapter *,
				   struct qlcnic_host_tx_ring *);
int qlcnic_82xx_sre_macaddr_change(struct qlcnic_adapter *, u8 *, u16, u8);
int qlcnic_82xx_get_mac_address(struct qlcnic_adapter *, u8*, u8);
int qlcnic_82xx_get_nic_info(struct qlcnic_adapter *, struct qlcnic_info *, u8);
int qlcnic_82xx_set_nic_info(struct qlcnic_adapter *, struct qlcnic_info *);
int qlcnic_82xx_get_pci_info(struct qlcnic_adapter *, struct qlcnic_pci_info*);
int qlcnic_82xx_alloc_mbx_args(struct qlcnic_cmd_args *,
			       struct qlcnic_adapter *, u32);
int qlcnic_82xx_hw_write_wx_2M(struct qlcnic_adapter *, ulong, u32);
int qlcnic_82xx_get_board_info(struct qlcnic_adapter *);
int qlcnic_82xx_config_led(struct qlcnic_adapter *, u32, u32);
void qlcnic_82xx_get_func_no(struct qlcnic_adapter *);
int qlcnic_82xx_api_lock(struct qlcnic_adapter *);
void qlcnic_82xx_api_unlock(struct qlcnic_adapter *);
void qlcnic_82xx_napi_enable(struct qlcnic_adapter *);
void qlcnic_82xx_napi_disable(struct qlcnic_adapter *);
void qlcnic_82xx_napi_del(struct qlcnic_adapter *);
int qlcnic_82xx_shutdown(struct pci_dev *);
int qlcnic_82xx_resume(struct qlcnic_adapter *);
void qlcnic_clr_all_drv_state(struct qlcnic_adapter *adapter, u8 failed);
void qlcnic_fw_poll_work(struct work_struct *work);

u32 qlcnic_82xx_get_saved_state(void *, u32);
void qlcnic_82xx_set_saved_state(void *, u32, u32);
void qlcnic_82xx_cache_tmpl_hdr_values(struct qlcnic_fw_dump *);
u32 qlcnic_82xx_get_cap_size(void *, int);
void qlcnic_82xx_set_sys_info(void *, int, u32);
void qlcnic_82xx_store_cap_mask(void *, u32);
#endif				/* __QLCNIC_HW_H_ */


text:
package org.zstack.test.network;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.header.cluster.ClusterVO;
import org.zstack.header.cluster.ClusterVO_;
import org.zstack.header.network.l2.*;
import org.zstack.header.search.APISearchMessage.NOLTriple;
import org.zstack.header.search.APISearchMessage.NOVTriple;
import org.zstack.header.search.SearchOp;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.deployer.Deployer;
import org.zstack.utils.Utils;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class TestSearchL2VlanNetwork {
    CLogger logger = Utils.getLogger(TestSearchL2VlanNetwork.class);
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        deployer = new Deployer("deployerXml/network/TestSearchL2VlanNetwork.xml");
        deployer.addSpringConfig("SearchManager.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
    }

    @Test
    public void test() throws InterruptedException, ApiSenderException {
        SimpleQuery<ClusterVO> cq = dbf.createQuery(ClusterVO.class);
        cq.add(ClusterVO_.name, Op.EQ, "TestCluster");
        ClusterVO cluster = cq.find();

        TimeUnit.SECONDS.sleep(1);
        APISearchL2VlanNetworkMsg msg = new APISearchL2VlanNetworkMsg();

        List<String> clusters = new ArrayList<String>();
        clusters.add(cluster.getUuid());

        NOLTriple tl = new NOLTriple();
        tl.setName("attachedClusterUuids");
        tl.setOp(SearchOp.AND_IN.toString());
        tl.setVals(clusters);
        msg.getNameOpListTriples().add(tl);

        NOVTriple t = new NOVTriple();
        t.setName("physicalInterface");
        t.setOp(SearchOp.AND_EQ.toString());
        t.setVal("eth2");
        msg.getNameOpValueTriples().add(t);

        t = new NOVTriple();
        t.setName("vlan");
        t.setOp(SearchOp.AND_EQ.toString());
        t.setVal("3");
        msg.getNameOpValueTriples().add(t);

        String content = api.search(msg);
        List<L2VlanNetworkInventory> invs = JSONObjectUtil.toCollection(content, ArrayList.class, L2VlanNetworkInventory.class);
        Assert.assertEquals(1, invs.size());

        SimpleQuery<L2VlanNetworkVO> q = dbf.createQuery(L2VlanNetworkVO.class);
        q.add(L2VlanNetworkVO_.vlan, Op.EQ, 1);
        L2VlanNetworkVO vlan1 = q.find();

        APIGetL2VlanNetworkMsg gmsg = new APIGetL2VlanNetworkMsg();
        gmsg.setUuid(vlan1.getUuid());
        String vlan1str = api.getInventory(gmsg);
        L2VlanNetworkInventory vlan1Inv = JSONObjectUtil.toObject(vlan1str, L2VlanNetworkInventory.class);
        Assert.assertEquals(vlan1.getName(), vlan1Inv.getName());
    }

}


text:
package gitlab

import (
	"net/http"
	"net/url"
	"strings"

	"github.com/openshift/oauth-server/pkg/oauth/external"

	"k8s.io/klog"
)

// The hosted version of GitLab is guaranteed to be using the latest stable version
// meaning that we can count on it having OIDC support (and no sub claim bug)
const gitlabHostedDomain = "gitlab.com"

func NewProvider(providerName, URL, clientID, clientSecret string, transport http.RoundTripper, legacy *bool) (external.Provider, error) {
	if isLegacy(legacy, URL) {
		klog.Infof("Using legacy OAuth2 for GitLab identity provider %s url=%s clientID=%s", providerName, URL, clientID)
		return NewOAuthProvider(providerName, URL, clientID, clientSecret, transport)
	}
	klog.Infof("Using OIDC for GitLab identity provider %s url=%s clientID=%s", providerName, URL, clientID)
	return NewOIDCProvider(providerName, URL, clientID, clientSecret, transport)
}

func isLegacy(legacy *bool, URL string) bool {
	// if a value is specified, honor it
	if legacy != nil {
		return *legacy
	}

	// use OIDC if we know it will work since the hosted version is being used
	// validation handles URL parsing errors so we can ignore them here
	if u, err := url.Parse(URL); err == nil && strings.EqualFold(u.Hostname(), gitlabHostedDomain) {
		return false
	}

	// otherwise use OAuth2 (to be safe for now)
	return true
}


text:
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.rmi.Naming;

public class BloodPump extends UnicastRemoteObject implements HeartBeatI {

    public BloodPump() throws RemoteException { super(); }

    public void sendHeartBeat() throws RemoteException{
        try {
            MonitorI monitor = (MonitorI) Naming.lookup("rmi://localhost:5000/monitor");
            while(true){
                monitor.receiveHeartBeat(monitor.BLOODPUMP_MAIN);
                Thread.sleep(1000);
                if(!ErrorGenerator.generateError()) {
					System.out.println("BloodPump is GOING DOWN");
                    System.exit(0);
                } else {
					System.out.println("BloodPump is RUNNING");
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String [] args){
        try {
            BloodPump bloodPump = new BloodPump();
            bloodPump.sendHeartBeat();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Sulu\Bundle\FormBundle\Entity\FormField" table="fo_form_fields">
        <unique-constraints>
            <unique-constraint columns="idForms,keyName"/>
        </unique-constraints>

        <id name="id" type="integer" column="id">
            <generator strategy="AUTO"/>
        </id>

        <field name="key" column="keyName" type="string" length="128"/>
        <field name="order" column="orderNumber" type="integer"/>
        <field name="type" column="type" type="string" length="255"/>
        <field name="width" column="width" type="string" length="16"/><!-- full / half / one-third / two-third / quarter -->
        <field name="required" column="required" type="boolean"/>
        <field name="defaultLocale" column="defaultLocale" type="string" length="5"/>

        <one-to-many field="translations"
                     target-entity="Sulu\Bundle\FormBundle\Entity\FormFieldTranslation"
                     mapped-by="field">
            <cascade>
                <cascade-persist/>
            </cascade>
        </one-to-many>

        <many-to-one field="form"
                     target-entity="Sulu\Bundle\FormBundle\Entity\Form"
                     inversed-by="fields">
            <join-columns>
                <join-column name="idForms" on-delete="CASCADE" referenced-column-name="id" nullable="false"/>
            </join-columns>
        </many-to-one>
    </entity>
</doctrine-mapping>


text:
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="zoom.css" />

    <title>Photo Zoom</title>
    <meta name="description" content="Photo zoom with 2d canvas." />

    <!-- Twitter Card data -->
    <meta name="twitter:card" value="Photo zoom with 2d canvas.">

    <!-- Open Graph data -->
    <meta property="og:title" content="Photo Zoom" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="https://nthitz.github.io/photozoom/" />
    <meta property="og:image" content="https://nthitz.github.io/photozoom/zoom.png" />
    <meta property="og:description" content="Photo zoom with 2D canvas." />

  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script>
    <script src="zoom.js"></script>

    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-62285627-1', 'auto');
      ga('send', 'pageview');

  </script>
  </body>
</html>


text:
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hash;

use crate::colour::Colour;
use crate::grid::Grid;

// Represent the state of the game as a graph.  One node for each cell.  There is an edge between
// two cells if and only if they are the same colour and have a distance of 1 according to the
// Manhattan metric.
//
// The game has only one real operation (i.e. not counting level generation): Switching the colour
// of the connected component containing the top left cell to whichever colour the clicked cell
// has.  This results in said component growing by every component it neighbours which has its new
// colour.  In essence, the aim of the gaim is to join connected components until only one is
// left.  Fewer clicks is better.
//
// So, we represent the game state as a collection of connected components, each of which has a
// colour, a list of coordinates of the constituent cells, and a list of it s neighbours.  As we
// do all our operations on connected components, we actually work not with the graph of
// neighbouring cells but with a graph of connected components.  The graph of connected components
// is made up of one node representing each connected component and an edge between any two
// connected components that have cells which share an edge, i.e. two cells which would have been
// connected by an edge in the original graph if they had had the same colour (which they did
// not).

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Position {
    pub row: usize,
    pub column: usize,
}

#[derive(Debug, Clone)]
pub struct ConnectedComponent {
    id: usize,
    pub colour: Colour,
    pub cells: HashSet<Position>,
}

impl PartialEq for ConnectedComponent {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Eq for ConnectedComponent {}

impl Hash for ConnectedComponent {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

#[derive(Debug)]
pub struct Graph {
    pub components: HashMap<usize, ConnectedComponent>,
    pub neighbours: HashMap<usize, HashSet<usize>>,
}

fn find_connected_components(grid: &Grid) -> Vec<(ConnectedComponent, HashSet<usize>)> {
    let rows = grid.number_of_rows;
    let columns = grid.number_of_columns;

    let mut remaining_cells: HashSet<usize> = (0..grid.cells.len()).into_iter().collect();

    let mut components = vec![];
    let mut counter = 0;

    // Take any element to land in any component.
    while let Some(&start_cell_index) = remaining_cells.iter().next() {
        let mut visited = HashSet::new();
        let mut neighbours = HashSet::new();
        let mut queue = VecDeque::new();

        queue.push_back(start_cell_index);

        // Gather all cells in the connected component of start_cell_index.
        while let Some(i) = queue.pop_front() {
            visited.insert(i);
            remaining_cells.remove(&i);

            let mut neighbouring_cells = vec![];
            if i % columns > 0 {
                neighbouring_cells.push(i - 1);
            }
            if i % columns < columns - 1 {
                neighbouring_cells.push(i + 1);
            }
            if i >= columns {
                neighbouring_cells.push(i - columns)
            }
            if i < (rows - 1) * columns {
                neighbouring_cells.push(i + columns)
            }

            for neighbour in neighbouring_cells {
                if visited.contains(&neighbour) {
                    continue;
                }

                if grid.cells[i] == grid.cells[neighbour] {
                    queue.push_back(neighbour);
                } else {
                    neighbours.insert(neighbour);
                }
            }
        }

        let cells = visited
            .iter()
            .map(|&i| Position {
                column: i % columns,
                row: i / columns,
            })
            .collect();

        let component = ConnectedComponent {
            id: counter,
            colour: grid.cells[*visited.iter().next().unwrap()],
            cells,
        };
        counter += 1;

        components.push((component, neighbours));
    }

    components
}

impl Graph {
    pub fn create(grid: &Grid) -> Self {
        let components_and_neighbours = find_connected_components(grid);

        let map_cell_to_component: HashMap<Position, ConnectedComponent> =
            components_and_neighbours
                .iter()
                .flat_map(|(component, _)| {
                    component
                        .cells
                        .iter()
                        .map(|cell| (cell.clone(), component.clone()))
                        .collect::<Vec<(Position, ConnectedComponent)>>()
                })
                .collect();

        let mut neighbours: HashMap<usize, HashSet<usize>> = HashMap::new();

        for (component, neighbour_cells) in &components_and_neighbours {
            let mut neighbour_components = HashSet::new();

            for cell in neighbour_cells {
                let position = Position {
                    column: cell % grid.number_of_columns,
                    row: cell / grid.number_of_columns,
                };
                neighbour_components.insert(map_cell_to_component[&position].id);
            }
            neighbours.insert(component.id, neighbour_components);
        }

        let mut components = HashMap::with_capacity(components_and_neighbours.len());

        for (c, _) in components_and_neighbours.into_iter() {
            components.insert(c.id, c);
        }

        Self {
            components,
            neighbours,
        }
    }

    fn to_grid(&self, rows: usize, columns: usize) -> Grid {
        let mut cells = vec![Colour::Red; rows * columns];

        for component in self.neighbours.keys() {
            for position in &self.components[component].cells {
                cells[position.column + position.row * columns] = self.components[component].colour;
            }
        }

        Grid {
            number_of_rows: rows,
            number_of_columns: columns,
            cells,
        }
    }

    pub fn find_component(&self, position: &Position) -> &ConnectedComponent {
        for component in self.neighbours.keys() {
            if self.components[component].cells.contains(position) {
                return &self.components[component];
            }
        }

        unreachable!()
    }

    pub fn change_colour_of_component_at(&mut self, position: &Position, colour: Colour) {
        let component_id = self.find_component(position).id;

        // Remove the component which is to change colour
        let mut component = self.components.remove(&component_id).unwrap();
        let mut neighbours = self.neighbours.remove(&component_id).unwrap();

        // Gather new cells for that component by combinging the cells of all
        // its neighbours which already have the new colour.
        let mut new_cells = HashSet::new();
        // Gather the set of its new neighbours which is just the union of the
        // sets of neighbours its neighbours with the new colour have.
        let mut new_neighbours = HashSet::new();
        let mut removed_neighbours = HashSet::new();

        for id in &neighbours {
            if *id != component_id && self.components[id].colour == colour {
                let neighbour_component = self.components.remove(id).unwrap();
                new_cells.extend(neighbour_component.cells.into_iter());
                let set_of_neighbour_ids = self.neighbours.remove(&neighbour_component.id).unwrap();
                new_neighbours.extend(set_of_neighbour_ids.into_iter());
                removed_neighbours.insert(*id);
            }
        }

        // Add new neighbours
        neighbours.extend(new_neighbours.clone().into_iter());
        // Remove the ID of the component itself
        neighbours.remove(&component_id);
        // and the IDs of the neighbours that were merged into the component
        neighbours = neighbours
            .difference(&removed_neighbours)
            .copied()
            .collect();

        // Add the cells from the neighbours which now have the new colour
        component.cells.extend(new_cells.into_iter());
        // and update the colour.  With this, the component itself is done.
        component.colour = colour;

        // Fix the neighbour sets for all the remaining components
        // All we have to do here is replace any of the indices in new_neighbours with component_id.
        for (_, n) in self.neighbours.iter_mut() {
            for incorporated_neighbour_id in &removed_neighbours {
                n.remove(incorporated_neighbour_id);
            }
            n.insert(component_id);
        }

        // Put the component and neighbours back into the Graph
        self.components.entry(component_id).or_insert(component);
        self.neighbours.entry(component_id).or_insert(neighbours);
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn should_return_same_grid_as_input() {
        let size = 4;
        let number_of_colours = 8;
        let grid = Grid::generate(size, number_of_colours);

        let graph = Graph::create(&grid);
        let reconstituted_grid = graph.to_grid(size, size);

        assert_eq!(reconstituted_grid, grid);
    }

    #[test]
    fn should_have_one_component() {
        let grid = Grid {
            number_of_columns: 2,
            number_of_rows: 2,
            cells: vec![Colour::Red; 4],
        };

        let graph = Graph::create(&grid);

        assert_eq!(graph.neighbours.len(), 1);
    }

    #[test]
    fn should_have_four_component() {
        let grid = Grid {
            number_of_columns: 2,
            number_of_rows: 2,
            cells: vec![Colour::Red, Colour::Yellow, Colour::Yellow, Colour::Red],
        };

        let graph = Graph::create(&grid);

        assert_eq!(graph.neighbours.len(), 4);
    }

    #[test]
    fn should_have_two_component() {
        let grid = Grid {
            number_of_columns: 2,
            number_of_rows: 2,
            cells: vec![Colour::Red, Colour::Red, Colour::Yellow, Colour::Yellow],
        };

        let graph = Graph::create(&grid);

        assert_eq!(graph.neighbours.len(), 2);
    }

    #[test]
    fn should_have_same_keys_for_components_and_neighbours_maps() {
        let size = 4;
        let number_of_colours = 8;
        let grid = Grid::generate(size, number_of_colours);

        let graph = Graph::create(&grid);

        let components_keys: HashSet<_> = graph.components.keys().collect();
        let neighbours_keys: HashSet<_> = graph.neighbours.keys().collect();
        assert_eq!(components_keys, neighbours_keys);
    }

    #[test]
    fn should_contain_exactly_the_component_ids_as_keys() {
        let size = 4;
        let number_of_colours = 8;
        let grid = Grid::generate(size, number_of_colours);

        let graph = Graph::create(&grid);

        let component_keys: HashSet<_> = graph.components.keys().collect();
        let component_ids: HashSet<_> = graph.components.values().map(|x| &x.id).collect();
        assert_eq!(component_keys, component_ids);

        for (id, component) in graph.components {
            assert_eq!(id, component.id);
        }
    }

    #[test]
    fn should_contain_only_component_ids_as_values_in_neighbours_map() {
        let size = 4;
        let number_of_colours = 8;
        let grid = Grid::generate(size, number_of_colours);

        let graph = Graph::create(&grid);

        let component_ids: HashSet<_> = graph.components.keys().copied().collect();

        for (_, neighbours) in graph.neighbours {
            assert_eq!(
                neighbours
                    .difference(&component_ids)
                    .collect::<HashSet<_>>()
                    .len(),
                0
            );
        }
    }
}


text:
'use strict';

(function() {
    $.fn.pageMe = function(opts) {
        var $this = this,
            defaults = {
                perPage: 7,
                showPrevNext: false,
                hidePageNumbers: false
            },
            settings = $.extend(defaults, opts);

        var listElement = $this;
        var perPage = settings.perPage;
        var children = listElement.children();
        var pager = $('.pager');

        if (typeof settings.childSelector != "undefined") {
            children = listElement.find(settings.childSelector);
        }

        if (typeof settings.pagerSelector != "undefined") {
            pager = $(settings.pagerSelector);
        }

        var numItems = children.size();
        var numPages = Math.ceil(numItems / perPage);

        pager.data("curr", 0);

        if (settings.showPrevNext) {
            $('
«
').appendTo(pager);
        }

        var curr = 0;
        while (numPages > curr && (settings.hidePageNumbers == false)) {
            $('
' + (curr + 1) + '
').appendTo(pager);
            curr++;
        }

        if (settings.showPrevNext) {
            $('
»
').appendTo(pager);
        }

        pager.find('.page_link:first').addClass('active');
        pager.find('.prev_link').hide();
        if (numPages <= 1) {
            pager.find('.next_link').hide();
        }
        pager.children().eq(1).addClass("active");

        children.hide();
        children.slice(0, perPage).show();

        pager.find('li .page_link').click(function() {
            var clickedPage = $(this).html().valueOf() - 1;
            goTo(clickedPage, perPage);
            return false;
        });
        pager.find('li .prev_link').click(function() {
            previous();
            return false;
        });
        pager.find('li .next_link').click(function() {
            next();
            return false;
        });

        function previous() {
            var goToPage = parseInt(pager.data("curr")) - 1;
            goToPage && goTo(goToPage);
        }

        function next() {
            var goToPage = parseInt(pager.data("curr")) + 1;
            goToPage && goTo(goToPage);
        }

        function goTo(page) {
            var startAt = page * perPage,
                endOn = startAt + perPage;

            children.css('display', 'none').slice(startAt, endOn).show();

            if (page >= 1) {
                pager.find('.prev_link').show();
            } else {
                pager.find('.prev_link').hide();
            }

            if (page < (numPages - 1)) {
                pager.find('.next_link').show();
            } else {
                pager.find('.next_link').hide();
            }

            pager.data("curr", page);
            pager.children().removeClass("active");
            pager.children().eq(page + 1).addClass("active");

        }
    };

    $(document).ready(function() {
        $("#registerDonor").click(function() {
            $("#registerDonorForm").modal();
        });

        $("#registerChild").click(function() {
            $("#registerChildForm").modal();
        });

        $("#Donation").click(function() {
            $("#DonationForm").modal();
        });

        // $(".editButton").click(function(event) {
        //     $("#registerDonorForm").modal();
        //     var donorInfo = event.target.parentElement.parentElement.childNodes;
        //     donorInfo.forEach(function(element, index) {
        //         element.className && $('#form_' + element.className) && $('#form_' + element.className).val(element.innerHTML);
        //     });
        // });

        $(".deleteButton").click(function(event) {
            $("#delete").modal();

            var Id = event.target.getAttribute('data-user-id') || event.target.parentElement.getAttribute('data-user-id') ;
            var userType = event.target.getAttribute('data-user-type') || event.target.parentElement.getAttribute('data-user-type');

            Id && $("#deleteMe").attr("data-user-id", Id);
            Id && $("#deleteMe").attr("data-user-type", userType);

        });

        $("#deleteMe").click(function(event) {
            var Id = event.target.getAttribute('data-user-id') || event.target.parentElement.getAttribute('data-user-id') ;
            var userType = event.target.getAttribute('data-user-type') || event.target.parentElement.getAttribute('data-user-type');

            var url = '/delete_' + userType;
            $.ajax({
                url: url,
                data: {
                    id: Id
                },
                type: "POST",
                dataType: "json",
                success: function(json) {
                  location.reload();
                },
                error: function() {
                  location.reload();
                }
            });
        });

        $('#donorList').pageMe({
            pagerSelector: '#myPager',
            showPrevNext: true,
            hidePageNumbers: false
        });

        $("#donorsList #checkall").click(function() {
            if ($("#donorsList #checkall").is(':checked')) {
                $("#donorsList input[type=checkbox]").each(function() {
                    $(this).prop("checked", true);
                });

            } else {
                $("#donorsList input[type=checkbox]").each(function() {
                    $(this).prop("checked", false);
                });
            }
        });

        // $('form#DonorMessageForm').on('submit', function(e) {
        //     // var donorsListCheckbox = document.querySelectorAll('.checkthis');
        //     // var donorIds = [];
        //     // donorsListCheckbox.forEach(function(element) {
        //     //     if (element.checked) {
        //     //         var findDonorId = element.parentElement.parentElement.childNodes;
        //     //         findDonorId.forEach(function(element) {
        //     //             if (element.className && element.className === 'donor_id' && element.innerHTML) {
        //     //                 donorIds.push(element.innerHTML);
        //     //             }
        //     //         });
        //     //     }
        //     // });
        //     //
        //     var data_ajax = $(this).serialize();
        //
        //     $.ajax({
        //         url: '/send_email',
        //         data: data_ajax,
        //         type: "POST",
        //         dataType: "json",
        //         success: function(json) {
        //           console.log('email_sent');
        //           location.reload();
        //         },
        //         error: function(err) {
        //           console.log('error while sending email');
        //           location.reload();
        //         }
        //     });
        // });
    });

})(this);


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using PatternSpider.Irc;
using PatternSpider.Plugins;

namespace Plugin_MTG
{
    [Export(typeof(IPlugin))]
    public class MTG : IPlugin
    {
        public string Name { get { return "MTG"; } }
        public string Description { get { return "Gives a link to a MTG card when invoked."; } }

        public List<string> Commands { get { return new List<string> { "mtg" }; } }

        public List<string> IrcCommand(IrcBot ircBot, string server, IrcMessage m)
        {
            var text = m.Text.Trim();
            var messageParts = text.Split(' ');
            var searchString = string.Join(" ", messageParts.Skip(1));

            var searchResult = SearchMagicCards(searchString);

            return new List<string> { searchResult };
        }

        public List<string> OnChannelMessage(IrcBot ircBot, string server, string channel, IrcMessage m)
        {
            return null;
        }

        public List<string> OnUserMessage(IrcBot ircBot, string server, IrcMessage m)
        {
            return null;
        }

        private string SearchMagicCards(string searchString)
        {
            HtmlDocument document;

            try
            {
                document = UrlRequest(string.Format("http://magiccards.info/query?q={0}&v=card&s=cname", searchString));
            }
            catch
            {
                return "Error Occured trying to search for card.";
            }

            string resultCount;

            try
            {
                resultCount = document.DocumentNode.SelectSingleNode("//body/table[3]/tr/td[3]").InnerHtml.Trim();

            }
            catch
            {
                return "No Results found for: " + searchString;
            }

            var matchString = @"([\d]+).cards";
            var regex = new Regex(matchString, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            if (regex.IsMatch(resultCount))
            {
                var count = regex.Match(resultCount).Groups[1];
                return String.Format("[http://magiccards.info/query?q={1}&v=card&s=cname] Found {0} cards.", count, searchString);
            }
            else
            {
                var cardLink = document.DocumentNode.SelectSingleNode("//body/table[4]/tr/td[2]/span/a").Attributes["href"].Value;
                return String.Format("[http://magiccards.info{0}]", cardLink);
            }

        }

        private HtmlDocument UrlRequest(string url)
        {
            var req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add("Accept-Language", "en;q=0.8");
            req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";

            var responseStream = req.GetResponse().GetResponseStream();
            var document = new HtmlDocument();

            if (responseStream == null)
            {
                throw new NoNullAllowedException();
            }

            using (var reader = new StreamReader(responseStream))
            {
                using (var memoryStream = new MemoryStream())
                {
                    using (var writer = new StreamWriter(memoryStream))
                    {
                        writer.Write(reader.ReadToEnd());
                        memoryStream.Position = 0;
                        document.Load(memoryStream, new UTF8Encoding());
                    }
                }
            }

            return document;
        }
    }
}


text:
#ifndef WS_PAE_CONTROLLER_H_
#define WS_PAE_CONTROLLER_H_

#ifdef HAVE_WS

typedef enum {
    AUTH_RESULT_OK = 0,                    // Successful
    AUTH_RESULT_ERR_NO_MEM = -1,           // No memory
    AUTH_RESULT_ERR_TX_NO_ACK = -2,        // No acknowledge was received
    AUTH_RESULT_ERR_UNSPEC = -3            // Other reason
} auth_result_e;

struct nvm_tlv_entry;

/**
 * ws_pae_controller_set_target sets EAPOL target for PAE supplicant
 *
 * \param interface_ptr interface
 * \param target_pan_id EAPOL target PAN ID
 * \param target_eui_64 EAPOL target
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_set_target(protocol_interface_info_entry_t *interface_ptr, uint16_t target_pan_id, uint8_t *target_eui_64);

/**
 * ws_pae_controller_authenticate start PAE supplicant authentication
 *
 * \param interface_ptr interface
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_authenticate(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_bootstrap_done indicates to PAE controller that bootstrap is ready
 *
 * \param interface_ptr interface
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_bootstrap_done(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_authenticator_start start PAE authenticator
 *
 * \param interface_ptr interface
 * \param local_port local port
 * \param remote_addr remote address
 * \param remote_port remote port
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_authenticator_start(protocol_interface_info_entry_t *interface_ptr, uint16_t local_port, const uint8_t *remote_addr, uint16_t remote_port);

/**
 * ws_pae_controller_init initializes PAE controller
 *
 * \param interface_ptr interface
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_init(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_init initializes PAE supplicant
 *
 * \param interface_ptr interface
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_supp_init(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_init initializes PAE authenticator
 *
 * \param interface_ptr interface
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_auth_init(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_stop stop PAE controller (e.g. on interface down)
 *
 * \param interface_ptr interface
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_stop(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_delete delete PAE controller (e.g. failure to create interface)
 *
 * \param interface_ptr interface
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_delete(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_timing_adjust Adjust retries and timings of the security protocols
 *
 * Timing value is a generic number between 0 to 32 that goes from fast and
 * reactive network to low bandwidth and long latency.
 *
 * example value definitions:
 * 0-8 very fast network
 * 9-16 medium network
 * 16-24 slow network
 * 25-32 extremely slow network
 *
 * There is no need to have lots variations in every layer if protocol is not very active in any case.
 *
 * \param timing Timing value.
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_timing_adjust(uint8_t timing);

/**
 * ws_pae_controller_certificate_chain_set set certificate chain
 *
 * \param chain certificate chain
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_certificate_chain_set(const arm_certificate_chain_entry_s *chain);

/**
 * ws_pae_controller_own_certificate_add add own certificate to certificate chain
 *
 * \param cert own certificate
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_own_certificate_add(const arm_certificate_entry_s *cert);

/**
 * ws_pae_controller_own_certificates_remove removes own certificates
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_own_certificates_remove(void);

/**
 * ws_pae_controller_trusted_certificate_add add trusted certificate
 *
 * \param cert trusted certificate
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_trusted_certificate_add(const arm_certificate_entry_s *cert);

/**
 * ws_pae_controller_trusted_certificate_remove remove trusted certificate
 *
 * \param cert trusted certificate
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_trusted_certificate_remove(const arm_certificate_entry_s *cert);

/**
 * ws_pae_controller_trusted_certificates_remove removes trusted certificates
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_trusted_certificates_remove(void);

/**
 * ws_pae_controller_certificate_revocation_list_add add certification revocation list
 *
 * \param crl certification revocation list
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_certificate_revocation_list_add(const arm_cert_revocation_list_entry_s *crl);

/**
 * ws_pae_controller_certificate_revocation_list_remove remove certification revocation list
 *
 * \param crl certification revocation list
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_certificate_revocation_list_remove(const arm_cert_revocation_list_entry_s *crl);

/**
 * ws_pae_controller_nw_info_set set network information
 *
 * \param interface_ptr interface
 * \param pan_id PAD ID
 * \param network_name network name
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_nw_info_set(protocol_interface_info_entry_t *interface_ptr, uint16_t pan_id, char *network_name);

/**
 * ws_pae_controller_nw_key_valid network key is valid i.e. used successfully on bootstrap
 *
 * \param interface_ptr interface
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_nw_key_valid(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_border_router_addr_write write border router address
 *
 * \param interface_ptr interface
 * \param eui_64 pointer to EUI-64
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_border_router_addr_write(protocol_interface_info_entry_t *interface_ptr, const uint8_t *eui_64);

/**
 * ws_pae_controller_border_router_addr_read read border router address
 *
 * \param interface_ptr interface
 * \param eui_64 pointer to EUI-64
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_border_router_addr_read(protocol_interface_info_entry_t *interface_ptr, uint8_t *eui_64);

/**
 * ws_pae_controller_gtk_update update GTKs (test interface)
 *
 * \param interface_id interface identifier
 * \param gtk GTK array, if GTK is not set, pointer for the index shall be NULL.
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_gtk_update(int8_t interface_id, uint8_t *gtk[4]);

/**
 * ws_pae_controller_next_gtk_update update next GTKs used during GTK lifecycle (test interface)
 *
 * \param interface_id interface identifier
 * \param gtk GTK array, if GTK is not set, pointer for the index shall be NULL.
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_next_gtk_update(int8_t interface_id, uint8_t *gtk[4]);

/**
 * ws_pae_controller_key_lifetime_update update key lifetime
 *
 * \param interface_id interface identifier
 * \param gtk_lifetime GTK lifetime
 * \param pmk_lifetime PMK lifetime
 * \param ptk_lifetime PTK lifetime
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_key_lifetime_update(int8_t interface_id, uint32_t gtk_lifetime, uint32_t pmk_lifetime, uint32_t ptk_lifetime);

/**
 * ws_pae_controller_gtk_time_settings_update update GTK time settings
 *
 * \param interface_id interface identifier
 * \param revocat_lifetime_reduct revocation lifetime reduction
 * \param new_activation_time new activation time
 * \param new_install_req new install required
 * \param max_mismatch max mismatch time
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_gtk_time_settings_update(int8_t interface_id, uint8_t revocat_lifetime_reduct, uint8_t new_activation_time, uint8_t new_install_req, uint32_t max_mismatch);

/**
 * ws_pae_controller_node_keys_remove remove node's keys
 *
 * \param interface_id interface identifier
 * \param eui-64 EUI-64
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_node_keys_remove(int8_t interface_id, uint8_t *eui_64);

/**
 * ws_pae_controller_node_access_revoke_start start node's access revoke
 *
 * \param interface_id interface identifier
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_node_access_revoke_start(int8_t interface_id);

/**
 * ws_pae_controller_node_limit_set set node limit
 *
 * \param interface_id interface identifier
 * \param limit limit for nodes
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_node_limit_set(int8_t interface_id, uint16_t limit);

/**
 * ws_pae_controller_ext_certificate_validation_set enable or disable extended certificate validation
 *
 * \param interface_ptr interface
 * \param enabled       true to enable extended validation, false to disable
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_ext_certificate_validation_set(int8_t interface_id, bool enabled);

/**
 * ws_pae_controller_active_key_update update active key (test interface)
 *
 * \param interface_id interface identifier
 * \param index GTK index
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_active_key_update(int8_t interface_id, uint8_t index);

/**
 * ws_pae_controller_gtk_hash_ptr_get get pointer to GTK hash storage
 *
 * \param interface_ptr interface
 *
 * \return pointer to GTK has storage or NULL
 *
 */
uint8_t *ws_pae_controller_gtk_hash_ptr_get(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_gtk_hash_update GTK hash has been updated (on PAN configuration)
 *
 * \param interface_ptr interface
 * \param gtkhash new GTK hash
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_gtk_hash_update(protocol_interface_info_entry_t *interface_ptr, uint8_t *gtkhash);

/**
 * ws_pae_controller_nw_key_index_update key index been updated (on PAN configuration)
 *
 * \param interface_ptr interface
 * \param index key index
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_nw_key_index_update(protocol_interface_info_entry_t *interface_ptr, uint8_t index);

/**
 * ws_pae_controller_nw_keys_remove remove network keys
 *
 * \param interface_ptr interface
 *
 */
void ws_pae_controller_nw_keys_remove(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_nw_key_insert network key insert callback
 *
 * \param interface_ptr interface
 * \param slot key slot (MAC key descriptor), from 0 to 4
 * \param index index of the new network key
 * \param key new key
 *
 */
typedef void ws_pae_controller_nw_key_set(protocol_interface_info_entry_t *interface_ptr, uint8_t slot, uint8_t index, uint8_t *key);

/**
 * ws_pae_controller_nw_key_clear network key clear callback
 *
 * \param interface_ptr interface
 * \param slot key slot (MAC key descriptor), from 0 to 4
 *
 */
typedef void ws_pae_controller_nw_key_clear(protocol_interface_info_entry_t *interface_ptr, uint8_t slot);

/**
 * ws_pae_controller_nw_send_key_index_set network send key index set callback
 *
 * \param interface_ptr interface
 * \param index index of the key to be used on sending
 *
 */
typedef void ws_pae_controller_nw_send_key_index_set(protocol_interface_info_entry_t *interface_ptr, uint8_t index);

/**
 * ws_pae_controller_nw_frame_counter_set network frame counter set callback
 *
 * \param interface_ptr interface
 * \param counter frame counter
 * \param slot key slot (MAC key descriptor), from 0 to 4
 *
 */
typedef void ws_pae_controller_nw_frame_counter_set(protocol_interface_info_entry_t *interface_ptr, uint32_t counter, uint8_t slot);

/**
 * ws_pae_controller_nw_frame_counter_read network frame counter read callback
 *
 * \param interface_ptr interface
 * \param counter frame counter
 *
 */
typedef void ws_pae_controller_nw_frame_counter_read(protocol_interface_info_entry_t *interface_ptr, uint32_t *counter, uint8_t slot);

/**
 * ws_pae_controller_auth_completed authentication completed callback
 *
 * \param interface_ptr interface
 * \param result result, either ok or failure reason
 * \param target_eui_64 EAPOL target in case of failure or NULL
 *
 */
typedef void ws_pae_controller_auth_completed(protocol_interface_info_entry_t *interface_ptr, auth_result_e result, uint8_t *target_eui_64);

/**
 * ws_pae_controller_pan_ver_increment PAN version increment callback
 *
 * \param interface_ptr interface
 *
 */
typedef void ws_pae_controller_pan_ver_increment(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_cb_register register PEA controller callbacks
 *
 * \param interface_ptr interface
 * \param completed authentication completed callback
 * \param nw_key_set network key set callback
 * \param nw_key_clear network key clear callback
 * \param nw_send_key_index_set network send key index set callback
 * \param nw_frame_counter_set network frame counter set callback
 * \param nw_frame_counter_read network frame counter read callback
 * \param pan_ver_increment PAN version increment callback
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
int8_t ws_pae_controller_cb_register(protocol_interface_info_entry_t *interface_ptr, ws_pae_controller_auth_completed *completed, ws_pae_controller_nw_key_set *nw_key_set, ws_pae_controller_nw_key_clear *nw_key_clear, ws_pae_controller_nw_send_key_index_set *nw_send_key_index_set, ws_pae_controller_nw_frame_counter_set *nw_frame_counter_set, ws_pae_controller_nw_frame_counter_read *nw_frame_counter_read, ws_pae_controller_pan_ver_increment *pan_ver_increment);

/**
 * ws_pae_controller_fast_timer PAE controller fast timer call
 *
 * \param ticks elapsed ticks
 *
 */
void ws_pae_controller_fast_timer(uint16_t ticks);

/**
 * ws_pae_controller_slow_timer PAE controller slow timer call
 *
 * \param seconds elapsed seconds
 *
 */
void ws_pae_controller_slow_timer(uint16_t seconds);

struct nvm_tlv_entry *ws_pae_controller_nvm_tlv_get(protocol_interface_info_entry_t *interface_ptr);

/**
 * ws_pae_controller_forced_gc PAE controller garbage cleanup callback
 *
 * \param full_gc Full cleanup (true for critical garbage cleanup)
 *
 */
void ws_pae_controller_forced_gc(bool full_gc);

#else

#define ws_pae_controller_set_target(interface_ptr, target_pan_id, target_dest_eui_64)
#define ws_pae_controller_authenticate(interface_ptr)

#define ws_pae_controller_authenticator_start(interface_ptr, local_port, remote_address, remote_port)

#define ws_pae_controller_border_router_addr_write(interface_ptr, eui_64) -1
#define ws_pae_controller_border_router_addr_read(interface_ptr, eui_64) -1

#define ws_pae_controller_gtk_set(interface_id, gtk) -1
#define ws_pae_controller_next_gtks_update(interface_id, gtk) -1

#define ws_pae_controller_init(interface_ptr) 1
#define ws_pae_controller_supp_init(interface_ptr) 1
#define ws_pae_controller_auth_init(interface_ptr) 1

#define ws_pae_controller_stop(interface_ptr)
#define ws_pae_controller_delete(interface_ptr)
#define ws_pae_controller_cb_register(interface_ptr, completed, nw_key_set, nw_key_clear, nw_send_key_index_set, pan_ver_increment) 1
#define ws_pae_controller_nvm_tlv_get(interface_ptr) NULL

#define ws_pae_controller_forced_gc NULL

#endif

#endif /* WS_PAE_CONTROLLER_H_ */


text:
<?php

namespace MobileCart\FedexBundle\Api\RateV10\SimpleType;

/**
 *
 *
 */
class NaftaImporterSpecificationType extends SimpleTypeAbstract
{
    const IMPORTER_OF_RECORD = 'IMPORTER_OF_RECORD';

    const RECIPIENT = 'RECIPIENT';

    const UNKNOWN = 'UNKNOWN';

    const VARIOUS = 'VARIOUS';

}


text:
package pl.panryba.mc.permissions;

import java.util.Collection;

/**
 * @author PanRyba.pl
 */
public class StringUtils {
    public static String join(Collection<String> items, String separator) {
        StringBuilder b = new StringBuilder();

        boolean first = true;
        for(String item : items) {
            if(first) {
                first = false;
            } else {
                b.append(separator);
            }
            b.append(item);
        }

        return b.toString();
    }
}


text:
package io.bootique.job;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class JobMetadataBuilderTest {

	@Test
	public void testBuild_static() {

		JobMetadata j = JobMetadata.build("nn");
		assertNotNull(j);
		assertEquals("nn", j.getName());
		assertTrue(j.getParameters().isEmpty());
	}

	@Test
	public void testBuild_Name() {

		JobMetadata j = JobMetadata.builder("nn").build();
		assertNotNull(j);
		assertEquals("nn", j.getName());
		assertTrue(j.getParameters().isEmpty());
	}

	@Test
	public void testBuild_Params() {

		JobMetadata j = JobMetadata.builder("nn").dateParam("dd", "2015-02-04").stringParam("ss", "ssv")
				.longParam("ll", "34556775").build();
		assertEquals(3, j.getParameters().size());

		List<JobParameterMetadata<?>> params = new ArrayList<>(j.getParameters());
		assertEquals("dd", params.get(0).getName());
		assertEquals(LocalDate.of(2015, 2, 4), params.get(0).fromString(null));

		assertEquals("ss", params.get(1).getName());
		assertEquals("ssv", params.get(1).fromString(null));

		assertEquals("ll", params.get(2).getName());
		assertEquals(34556775L, params.get(2).fromString(null));

	}
}


text:
description: Description of labels, which are used to manage metadata on Docker objects.
keywords: Usage, user guide, labels, metadata, docker, documentation, examples, annotating
title: Docker object labels
---

Labels are a mechanism for applying metadata to Docker objects, including:

- Images
- Containers
- Local daemons
- Volumes
- Networks
- Swarm nodes
- Swarm services

You can use labels to organize your images, record licensing information, annotate
relationships between containers, volumes, and networks, or in any way that makes
sense for your business or application.

## Label keys and values

A label is a key-value pair, stored as a string. You can specify multiple labels
for an object, but each key-value pair must be unique within an object. If the
same key is given multiple values, the most-recently-written value overwrites
all previous values.

### Key format recommendations

A label _key_ is the left-hand side of the key-value pair. Keys are alphanumeric
strings which may contain periods (`.`) and hyphens (`-`). Most Docker users use
images created by other organizations, and the following guidelines help to
prevent inadvertent duplication of labels across objects, especially if you plan
to use labels as a mechanism for automation.

- Authors of third-party tools should prefix each label key with the
  reverse DNS notation of a domain they own, such as `com.example.some-label`.

- Do not use a domain in your label key without the domain owner's permission.

- The `com.docker.*`, `io.docker.*`, and `org.dockerproject.*` namespaces are
  reserved by Docker for internal use.

- Label keys should begin and end with a lower-case letter and should only
  contain lower-case alphanumeric characters, the period character (`.`), and
  the hyphen character (`-`). Consecutive periods or hyphens are not allowed.

- The period character (`.`) separates namespace "fields". Label keys without
  namespaces are reserved for CLI use, allowing users of the CLI to interactively
  label Docker objects using shorter typing-friendly strings.

These guidelines are not currently enforced and additional guidelines may apply
to specific use cases.

### Value guidelines

Label values can contain any data type that can be represented as a string,
including (but not limited to) JSON, XML, CSV, or YAML. The only requirement is
that the value be serialized to a string first, using a mechanism specific to
the type of structure. For instance, to serialize JSON into a string, you might
use the `JSON.stringify()` JavaScript method.

Since Docker does not deserialize the value, you cannot treat a JSON or XML
document as a nested structure when querying or filtering by label value unless
you build this functionality into third-party tooling.

## Manage labels on objects

Each type of object with support for labels has mechanisms for adding and
managing them and using them as they relate to that type of object. These links
provide a good place to start learning about how you can use labels in your
Docker deployments.

Labels on images, containers, local daemons, volumes, and networks are static for
the lifetime of the object. To change these labels you must recreate the object.
Labels on swarm nodes and services can be updated dynamically.

- Images and containers
  - [Adding labels to images](../reference/builder.md#label)
  - [Overriding a container's labels at runtime](../reference/commandline/run.md#set-metadata-on-container--l---label---label-file)
  - [Inspecting labels on images or containers](../reference/commandline/inspect.md)
  - [Filtering images by label](../reference/commandline/inspect.md#filtering)
  - [Filtering containers by label](../reference/commandline/ps.md#filtering)

- Local Docker daemons
  - [Adding labels to a Docker daemon at runtime](../reference/commandline/dockerd.md)
  - [Inspecting a Docker daemon's labels](../reference/commandline/info.md)

- Volumes
  - [Adding labels to volumes](../reference/commandline/volume_create.md)
  - [Inspecting a volume's labels](../reference/commandline/volume_inspect.md)
  - [Filtering volumes by label](../reference/commandline/volume_ls.md#filtering)

- Networks
  - [Adding labels to a network](../reference/commandline/network_create.md)
  - [Inspecting a network's labels](../reference/commandline/network_inspect.md)
  - [Filtering networks by label](../reference/commandline/network_ls.md#filtering)

- Swarm nodes
  - [Adding or updating a swarm node's labels](../reference/commandline/node_update.md#add-label-metadata-to-a-node)
  - [Inspecting a swarm node's labels](../reference/commandline/node_inspect.md)
  - [Filtering swarm nodes by label](../reference/commandline/node_ls.md#filtering)

- Swarm services
  - [Adding labels when creating a swarm service](../reference/commandline/service_create.md#set-metadata-on-a-service-l-label)
  - [Updating a swarm service's labels](../reference/commandline/service_update.md)
  - [Inspecting a swarm service's labels](../reference/commandline/service_inspect.md)
  - [Filtering swarm services by label](../reference/commandline/service_ls.md#filtering)


text:
require 'spec_helper'
require 'conjur/rack'

describe Conjur::Rack do
  describe '.user' do
    include_context "with authorization"
    let(:stubuser) { double :stubuser }
    before do
      allow(Conjur::Rack::User).to receive(:new)
        .with(token, 'someacc', {:privilege => privilege, :remote_ip => remote_ip, :audit_roles => audit_roles, :audit_resources => audit_resources})
        .and_return(stubuser)
    end

    context 'when called in app context' do
      shared_examples_for :returns_user do
        it "returns user built from token" do
          expect(call).to eq stubuser
        end
      end

      include_examples :returns_user

      context 'with X-Conjur-Privilege' do
        let(:privilege) { "elevate" }
        include_examples :returns_user
      end

      context 'with X-Forwarded-For' do
        let(:remote_ip) { "66.0.0.1" }
        include_examples :returns_user
      end

      context 'with Conjur-Audit-Roles' do
        let (:audit_roles) { 'user%3Acook' }
        include_examples :returns_user
      end

      context 'with Conjur-Audit-Resources' do
        let (:audit_resources) { 'food%3Abacon' }
        include_examples :returns_user
      end

    end

    it "raises error if called out of app context" do
      expect { Conjur::Rack.user }.to raise_error('No Conjur identity for current request')
    end
  end
end


text:
<?php

namespace Bstoots\WOX\Serial;

abstract class XmlUtil {

  /**
   * Reformat XML string to a single line
   * Note: This is dependent on the underlying libxml implementation
   * and therefore may not work on certain platforms, such as Windows.
   *
   * @param  string $xml String of XML data
   * @return string      Formatted string of XML data
   */
  public static function linearize(string $xml) {
    $doc = new \DOMDocument();
    $doc->preserveWhiteSpace = false;
    $doc->formatOutput = false;
    $doc->loadXML($xml);
    return trim($doc->saveXML());
  }

  /**
   * Reformat XML string with one element per line
   * Note: This is dependent on the underlying libxml implementation
   * and therefore may not work on certain platforms, such as Windows.
   *
   * @param  string $xml String of XML data
   * @return string      Formatted string of XML data
   */
  public static function pretty(string $xml) {
    $doc = new \DOMDocument();
    $doc->preserveWhiteSpace = false;
    $doc->formatOutput = true;
    $doc->loadXML($xml);
    return trim($doc->saveXML());
  }

}