text:
package com.consol.citrus.validation.matcher.core;

import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.testng.AbstractTestNGUnitTest;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * @author Christoph Deppisch
 */
public class WeekdayValidationMatcherTest extends AbstractTestNGUnitTest {

    private WeekdayValidationMatcher matcher = new WeekdayValidationMatcher();

    private SimpleDateFormat defaultDateFormat = new SimpleDateFormat("dd.MM.yyyy");

    @Test
    public void testValidationMatcher() {
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.MONDAY).getTime()), Arrays.asList("MONDAY"), context);
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.TUESDAY).getTime()), Arrays.asList("TUESDAY"), context);
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.WEDNESDAY).getTime()), Arrays.asList("WEDNESDAY"), context);
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.THURSDAY).getTime()), Arrays.asList("THURSDAY"), context);
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.FRIDAY).getTime()), Arrays.asList("FRIDAY"), context);
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.SATURDAY).getTime()), Arrays.asList("SATURDAY"), context);
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.SUNDAY).getTime()), Arrays.asList("SUNDAY"), context);

        try {
            matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.MONDAY).getTime()), Arrays.asList("SUNDAY"), context);
            Assert.fail("Missing validation matcher failed exception");
        } catch (CitrusRuntimeException e) {
            Assert.assertTrue(e.getMessage().endsWith("expected date to be a 'SUNDAY'"));
        }
    }

    @Test
    public void testCustomDateFormat() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        matcher.validate("fieldName", dateFormat.format(getNext(Calendar.MONDAY).getTime()), Arrays.asList("MONDAY", "yyyy-MM-dd"), context);
        matcher.validate("fieldName", dateFormat.format(getNext(Calendar.TUESDAY).getTime()), Arrays.asList("TUESDAY", "yyyy-MM-dd"), context);
        matcher.validate("fieldName", dateFormat.format(getNext(Calendar.WEDNESDAY).getTime()), Arrays.asList("WEDNESDAY", "yyyy-MM-dd"), context);
        matcher.validate("fieldName", dateFormat.format(getNext(Calendar.THURSDAY).getTime()), Arrays.asList("THURSDAY", "yyyy-MM-dd"), context);
        matcher.validate("fieldName", dateFormat.format(getNext(Calendar.FRIDAY).getTime()), Arrays.asList("FRIDAY", "yyyy-MM-dd"), context);
        matcher.validate("fieldName", dateFormat.format(getNext(Calendar.SATURDAY).getTime()), Arrays.asList("SATURDAY", "yyyy-MM-dd"), context);
        matcher.validate("fieldName", dateFormat.format(getNext(Calendar.SUNDAY).getTime()), Arrays.asList("SUNDAY", "yyyy-MM-dd"), context);

        try {
            matcher.validate("fieldName", dateFormat.format(getNext(Calendar.MONDAY).getTime()), Arrays.asList("SUNDAY", "yyyy-MM-dd"), context);
            Assert.fail("Missing validation matcher failed exception");
        } catch (CitrusRuntimeException e) {
            Assert.assertTrue(e.getMessage().endsWith("expected date to be a 'SUNDAY'"));
        }
    }

    @Test(expectedExceptions = {CitrusRuntimeException.class})
    public void testInvalidDefaultDateFormat() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        matcher.validate("fieldName", dateFormat.format(getNext(Calendar.MONDAY).getTime()), Arrays.asList("MONDAY"), context);
    }

    @Test(expectedExceptions = {CitrusRuntimeException.class})
    public void testInvalidCustomDateFormat() {
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.MONDAY).getTime()), Arrays.asList("MONDAY", "dd-MM-yyyy"), context);
    }

    @Test(expectedExceptions = {IllegalArgumentException.class})
    public void testInvalidDateFormatSyntax() {
        matcher.validate("fieldName", defaultDateFormat.format(getNext(Calendar.MONDAY).getTime()), Arrays.asList("MONDAY","ABC"), context);
    }

    @DataProvider
    public Object[][] validParameters() {
        return new Object[][]{
                {"MONDAY", Arrays.asList("MONDAY")},
                {"MONDAY('yyyy-MM-dd')", Arrays.asList("MONDAY", "yyyy-MM-dd")},
        };
    }
    @Test(dataProvider = "validParameters")
    public void shouldExtractParametersSuccessfully(String controlExpression, List<String> expectedParameters) {
        List<String> controlValues = matcher.extractControlValues(controlExpression, null);
        Assert.assertEquals(controlValues.size(), expectedParameters.size());

        for (int i = 0; i < controlValues.size(); i++) {
            Assert.assertEquals(controlValues.get(i), expectedParameters.get(i));
        }
    }

    /**
     * Get next desired day of week.
     * @param dayField
     * @return
     */
    private Calendar getNext(int dayField) {
        Calendar calendar = Calendar.getInstance();

        while (calendar.get(Calendar.DAY_OF_WEEK) != dayField) {
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }

        return calendar;
    }
}


text:
using Microsoft.AspNet.Identity;

namespace Swartz.Users
{
    public interface ISwartzRole<out TKey> : IRole<TKey>
    {
    }

    public interface ISwartzRole : ISwartzRole<decimal>
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
PrecisionModel::PrecisionModel() {
    _model = new geos::geom::PrecisionModel();
}

PrecisionModel::PrecisionModel(double newScale) {
    _model = new geos::geom::PrecisionModel(newScale);
}

PrecisionModel::PrecisionModel(geos::geom::PrecisionModel::Type nModelType) {
    _model = new geos::geom::PrecisionModel(nModelType);
}
PrecisionModel::PrecisionModel(const geos::geom::PrecisionModel *model) {
    _model = (geos::geom::PrecisionModel*) model; //hacky
}

PrecisionModel::~PrecisionModel() {}

Persistent<FunctionTemplate> PrecisionModel::constructor;

void PrecisionModel::Initialize(Handle<Object> target) {
    HandleScope scope;

    constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(PrecisionModel::New));
    constructor->InstanceTemplate()->SetInternalFieldCount(1);
    constructor->SetClassName(String::NewSymbol("PrecisionModel"));

    NODE_SET_PROTOTYPE_METHOD(constructor, "getType", GetType);
    NODE_SET_PROTOTYPE_METHOD(constructor, "getScale", GetScale);
    NODE_SET_PROTOTYPE_METHOD(constructor, "getOffsetX", GetOffsetX);
    NODE_SET_PROTOTYPE_METHOD(constructor, "getOffsetY", GetOffsetY);

    NODE_SET_PROTOTYPE_METHOD(constructor, "toString", ToString);

    NODE_SET_PROTOTYPE_METHOD(constructor, "isFloating", IsFloating);

    NODE_SET_PROTOTYPE_METHOD(constructor, "compareTo", CompareTo);

    target->Set(String::NewSymbol("PrecisionModel"), constructor->GetFunction());
}

Handle<Value> PrecisionModel::New(const Arguments& args) {
    HandleScope scope;
    PrecisionModel *model;
    if (args.Length() == 0) {
        model = new PrecisionModel();
    } else {
        if (args[0]->IsString()) {
            //type
            if(args[0]->ToString()->Equals(String::New("FIXED"))) {
                model = new PrecisionModel(geos::geom::PrecisionModel::FIXED);
            } else if (args[0]->ToString()->Equals(String::New("FLOATING"))) {
                model = new PrecisionModel(geos::geom::PrecisionModel::FLOATING);
            } else {
                model = new PrecisionModel(geos::geom::PrecisionModel::FLOATING_SINGLE);
            }
        } else {
            //double
            model = new PrecisionModel(args[0]->NumberValue());
        }
    }
    model->Wrap(args.This());
    return args.This();
}

Handle<Value> PrecisionModel::New(const geos::geom::PrecisionModel *m) {
    HandleScope scope;
    PrecisionModel *model = new PrecisionModel(m);
    Handle<Value> ext = External::New(model);
    Handle<Object> obj = constructor->GetFunction()->NewInstance(1, &ext);
    model->Wrap(obj);
    return scope.Close(obj);
}

Handle<Value> PrecisionModel::GetType(const Arguments& args) {
    HandleScope scope;
    PrecisionModel *model = ObjectWrap::Unwrap<PrecisionModel>(args.This());
    return scope.Close(Integer::New(model->_model->getType()));
}
//TODO add a macro for this?
Handle<Value> PrecisionModel::GetScale(const Arguments& args) {
    HandleScope scope;
    PrecisionModel *model = ObjectWrap::Unwrap<PrecisionModel>(args.This());
    return scope.Close(Number::New(model->_model->getScale()));
}

Handle<Value> PrecisionModel::GetOffsetX(const Arguments& args) {
    HandleScope scope;
    PrecisionModel *model = ObjectWrap::Unwrap<PrecisionModel>(args.This());
    return scope.Close(Number::New(model->_model->getOffsetX()));
}

Handle<Value> PrecisionModel::GetOffsetY(const Arguments& args) {
    HandleScope scope;
    PrecisionModel *model = ObjectWrap::Unwrap<PrecisionModel>(args.This());
    return scope.Close(Number::New(model->_model->getOffsetY()));
}

Handle<Value> PrecisionModel::ToString(const Arguments& args) {
    HandleScope scope;
    PrecisionModel *model = ObjectWrap::Unwrap<PrecisionModel>(args.This());
    return scope.Close(String::New(model->_model->toString().data()));
}

Handle<Value> PrecisionModel::IsFloating(const Arguments& args) {
    HandleScope scope;
    PrecisionModel *model = ObjectWrap::Unwrap<PrecisionModel>(args.This());
    return model->_model->isFloating() ? True() : False();
}

Handle<Value> PrecisionModel::CompareTo(const Arguments& args) {
    HandleScope scope;
    PrecisionModel *model = ObjectWrap::Unwrap<PrecisionModel>(args.This());
    PrecisionModel *model2 = ObjectWrap::Unwrap<PrecisionModel>(args[0]->ToObject());
    return scope.Close(Integer::New(model->_model->compareTo(model2->_model)));
}


text:
<?php
$libros = array();
$libros[0] = array('nombre'=>'campo1', 'tipo'=>PDO::PARAM_STR,'direccion'=>PDO::PARAM_INPUT_OUTPUT);
$libros[1] = array('nombre'=>'campo2', 'tipo'=>PDO::PARAM_INT,'direccion'=>PDO::PARAM_INPUT_OUTPUT);
echo $libros[1]['nombre'];
// esto devolver el valor CodeHero, ya que especificamos la fila numero 1 y la columna autor
?>


text:
* [Routing](docs/routing/README.md)
  * [Files](docs/routing/files.md)
  * [Bundles](docs/routing/bundles.md)
  * [Indexes](docs/routing/indexes.md)
* [Configuration](docs/configuration/README.md)
* [Tutorial](docs/tutorial/README.md)


text:
namespace cc {

// Interface for pixel comparators.
class PixelComparator {
 public:
  virtual ~PixelComparator() {}

  virtual bool Compare(const SkBitmap& actual_bmp,
                       const SkBitmap& expected_bmp) const = 0;
};

// Exact pixel comparator. Counts the number of pixel with an error.
class ExactPixelComparator : public PixelComparator {
 public:
  explicit ExactPixelComparator(const bool discard_alpha);
  ~ExactPixelComparator() override {}

  // Returns true if the two bitmaps are identical. Otherwise, returns false
  // and report the number of pixels with an error on LOG(ERROR). Differences
  // in the alpha channel are ignored.
  bool Compare(const SkBitmap& actual_bmp,
               const SkBitmap& expected_bmp) const override;

 private:
  // Exclude alpha channel from comparison?
  bool discard_alpha_;
};

// Fuzzy pixel comparator. Counts small and arbitrary errors separately and
// computes average and maximum absolute errors per color channel.
class FuzzyPixelComparator : public PixelComparator {
 public:
  FuzzyPixelComparator(const bool discard_alpha,
                       const float error_pixels_percentage_limit,
                       const float small_error_pixels_percentage_limit,
                       const float avg_abs_error_limit,
                       const int max_abs_error_limit,
                       const int small_error_threshold);
  ~FuzzyPixelComparator() override {}

  // Computes error metrics and returns true if the errors don't exceed the
  // specified limits. Otherwise, returns false and reports the error metrics on
  // LOG(ERROR). Differences in the alpha channel are ignored.
  bool Compare(const SkBitmap& actual_bmp,
               const SkBitmap& expected_bmp) const override;

 private:
  // Exclude alpha channel from comparison?
  bool discard_alpha_;
  // Limit for percentage of pixels with an error.
  float error_pixels_percentage_limit_;
  // Limit for percentage of pixels with a small error.
  float small_error_pixels_percentage_limit_;
  // Limit for average absolute error (excluding identical pixels).
  float avg_abs_error_limit_;
  // Limit for largest absolute error.
  int max_abs_error_limit_;
  // Threshold for small errors.
  int small_error_threshold_;
};

// All pixels can be off by one, but any more than that is an error.
class FuzzyPixelOffByOneComparator : public FuzzyPixelComparator {
 public:
  explicit FuzzyPixelOffByOneComparator(bool discard_alpha)
      : FuzzyPixelComparator(discard_alpha, 100.f, 0.f, 1.f, 1, 0) {}
};

}  // namespace cc

#endif  // CC_TEST_PIXEL_COMPARATOR_H_


text:
<?php

function create($class, $attributes = [])
{
    return factory($class)->create($attributes);
}

function createFromState($class, $state, $attributes = [])
{
    return factory($class)->states($state)->create($attributes);
}

function make($class, $attributes = [])
{
    return factory($class)->make($attributes);
}

function makefromState($class, $state, $attributes = [])
{
    return factory($class)->states($state)->make($attributes);
}


text: `console-app` displays all the pages of the console app.


text:
'use strict';
const u2f = require('u2f-api');
var decryptWalletCtrl = function($scope, $sce, walletService) {
  $scope.walletType = '';
  $scope.supported = false;
  u2f.isSupported().then(res => {
    $scope.supported = res && window.browser.name === 'chrome';
    $scope.$apply();
  });

  $scope.requireFPass = $scope.requirePPass = $scope.showFDecrypt = $scope.showPDecrypt = $scope.showAOnly = $scope.showParityDecrypt = false;
  $scope.filePassword = '';
  $scope.fileContent = '';
  $scope.Validator = Validator;
  $scope.isSSL = window.location.protocol == 'https:';
  $scope.ajaxReq = ajaxReq;
  $scope.nodeType = $scope.ajaxReq.type;
  $scope.HDWallet = {
    numWallets: 0,
    walletsPerDialog: 5,
    wallets: [],
    id: 0,
    hdk: null,
    dPath: '',
    defaultDPath: 'm/44\'/60\'/0\'/0', // first address: m/44'/60'/0'/0/0
    alternativeDPath: 'm/44\'/60\'/0\'', // first address: m/44'/60'/0/0
    customDPath: 'm/44\'/60\'/1\'/0', // first address: m/44'/60'/1'/0/0
    ledgerPath: 'm/44\'/60\'/0\'', // first address: m/44'/60'/0/0
    ledgerClassicPath: 'm/44\'/60\'/160720\'/0\'', // first address: m/44'/60'/160720'/0/0
    trezorTestnetPath: 'm/44\'/1\'/0\'/0', // first address: m/44'/1'/0'/0/0
    trezorClassicPath: 'm/44\'/61\'/0\'/0', // first address: m/44'/61'/0'/0/0
    trezorPath: 'm/44\'/60\'/0\'/0', // first address: m/44'/60'/0'/0/0
    hwUbqPath: 'm/44\'/108\'/0\'/0', // first address: m/44'/40'/0'/0/0
    hwExpansePath: 'm/44\'/40\'/0\'/0', // first address: m/44'/40'/0'/0/0
    hwEllaismPath: 'm/44\'/163\'/0\'/0', // first address: m/44'/163'/0'/0/0
    hwPirlPath: 'm/44\'/164\'/0\'/0', // first address: m/44'/164'/0'/0/0
    hwEtherGemPath: 'm/44\'/1987\'/0\'/0', // first address: m/44'/1987'/0'/0/0
    hwCallistoPath: 'm/44\'/820\'/0\'/0', // first address: m/44'/820'/0'/0/0
    hwSocialPath: 'm/44\'/1128\'/0\'/0', // first address: m/44'/1128'/0'/0/0
    hwMusicoinPath: 'm/44\'/184\'/0\'/0', // first address: m/44'/184'/0'/0/0
    singularDTVPath: 'm/0\'/0\'/0\'', // first address: m/0'/0'/0'/0
    goPath: 'm/44\'/6060\'/0\'/0', // first address: m/44'/6060'/0'/0/0
    hwEOSClassicPath: 'm/44\'/2018\'/0\'/0', // first address: m/44'/2018'/0'/0/0
    hwAkromaPath: 'm/44\'/200625\'/0\'/0', // first address: m/44'/200625'/0'/0/0
    hwESNetworkPath: 'm/44\'/31102\'/0\'/0', // first address: m/44'/31102'/0'/0/0
    hwEther1Path: 'm/44\'/1313114\'/0\'/0', // first address: m/44'/1313114'/0'/0/0
    hwAtheiosPath: 'm/44\'/1620\'/0\'/0', // first address: m/44'/1620'/0'/0/0
    hwIolitePath: 'm/44\'/1171337\'/0\'/0', // first address: m/44'/1171337'/0'/0/0
    tomoPath: 'm/44\'/889\'/0\'/0', // first address: m/44'/889'/0'/0/0
    hwMixPath: 'm/44\'/76\'/0\'/0', // first address: m/44'/76'/0'/0/0
    hwReoscPath: 'm/44\'/2894\'/0\'/0', // first address: m/44'/2894'/0'/0/0
    thundercorePath: 'm/44\'/1001\'/0\'/0', // first address: m/44'/1001'/0'/0/0
  };
  $scope.canUseMewConnect = MewConnectEth.checkWebRTCAvailable();
  $scope.mewConnectMayFail = MewConnectEth.checkBrowser();
  $scope.HDWallet.dPath = $scope.HDWallet.defaultDPath;
  $scope.mnemonicModel = new Modal(document.getElementById('mnemonicModel'));
  $scope.$watch('ajaxReq.type', function() {
    $scope.nodeType = $scope.ajaxReq.type;
    $scope.setdPath();
  });
  $scope.$watch('walletType', function() {
    $scope.setdPath();
  });
  $scope.setdPath = function() {
    if ($scope.walletType == 'ledger') {
      switch ($scope.nodeType) {
        case nodes.nodeTypes.ETH:
          $scope.HDWallet.dPath = $scope.HDWallet.ledgerPath;
          break;
        case nodes.nodeTypes.ETC:
          $scope.HDWallet.dPath = $scope.HDWallet.ledgerClassicPath;
          break;
        case nodes.nodeTypes.CLO:
          $scope.HDWallet.dPath = $scope.HDWallet.hwCallistoPath;
          break;
        case nodes.nodeTypes.EXP:
          $scope.HDWallet.dPath = $scope.HDWallet.hwExpansePath;
          break;
        case nodes.nodeTypes.UBQ:
          $scope.HDWallet.dPath = $scope.HDWallet.hwUbqPath;
          break;
        case nodes.nodeTypes.POA:
          $scope.HDWallet.dPath = $scope.HDWallet.ledgerPath;
          break;
        case nodes.nodeTypes.AKA:
          $scope.HDWallet.dPath = $scope.HDWallet.hwAkromaPath;
          break;
        case nodes.nodeTypes.PIRL:
          $scope.HDWallet.dPath = $scope.HDWallet.hwPirlPath;
          break;
        case nodes.nodeTypes.ETHO:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEther1Path;
          break;
        case nodes.nodeTypes.ATH:
          $scope.HDWallet.dPath = $scope.HDWallet.hwAtheiosPath;
          break;
        case nodes.nodeTypes.ELLA:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEllaismPath;
          break;
        case nodes.nodeTypes.EGEM:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEtherGemPath;
          break;
        case nodes.nodeTypes.MUSIC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwMusicoinPath;
          break;
        case nodes.nodeTypes.EOSC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEOSClassicPath;
          break;
        case nodes.nodeTypes.GO:
          $scope.HDWallet.dPath = $scope.HDWallet.goPath;
          break;
        case nodes.nodeTypes.ILT:
          $scope.HDWallet.dPath = $scope.HDWallet.hwIolitePath;
          break;
        case nodes.nodeTypes.TOMO:
          $scope.HDWallet.dPath = $scope.HDWallet.tomoPath;
          break;
        case nodes.nodeTypes.MIX:
          $scope.HDWallet.dPath = $scope.HDWallet.hwMixPath;
          break;
        case nodes.nodeTypes.REOSC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwReoscPath;
          break;
        case nodes.nodeTypes.THUNDERCORE:
          $scope.HDWallet.dPath = $scope.HDWallet.thundercorePath;
          break;
        default:
          $scope.HDWallet.dPath = $scope.HDWallet.ledgerPath;
      }
    } else if ($scope.walletType == 'trezor') {
      switch ($scope.nodeType) {
        case nodes.nodeTypes.ETH:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorPath;
          break;
        case nodes.nodeTypes.ETC:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorClassicPath;
          break;
        case nodes.nodeTypes.Ropsten:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorTestnetPath;
          break;
        case nodes.nodeTypes.Rinkeby:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorTestnetPath;
          break;
        case nodes.nodeTypes.Kovan:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorTestnetPath;
          break;
        case nodes.nodeTypes.EXP:
          $scope.HDWallet.dPath = $scope.HDWallet.hwExpansePath;
          break;
        case nodes.nodeTypes.UBQ:
          $scope.HDWallet.dPath = $scope.HDWallet.hwUbqPath;
          break;
        case nodes.nodeTypes.ELLA:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEllaismPath;
          break;
        case nodes.nodeTypes.EGEM:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEtherGemPath;
          break;
        case nodes.nodeTypes.CLO:
          $scope.HDWallet.dPath = $scope.HDWallet.hwCallistoPath;
          break;
        case nodes.nodeTypes.ETSC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwSocialPath;
          break;
        case nodes.nodeTypes.MUSIC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwMusicoinPath;
          break;
        case nodes.nodeTypes.GO:
          $scope.HDWallet.dPath = $scope.HDWallet.goPath;
          break;
        case nodes.nodeTypes.EOSC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEOSClassicPath;
          break;
        case nodes.nodeTypes.AKA:
          $scope.HDWallet.dPath = $scope.HDWallet.hwAkromaPath;
          break;
        case nodes.nodeTypes.ESN:
          $scope.HDWallet.dPath = $scope.HDWallet.hwESNetworkPath;
          break;
        case nodes.nodeTypes.PIRL:
          $scope.HDWallet.dPath = $scope.HDWallet.hwPirlPath;
          break;
        case nodes.nodeTypes.ETHO:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEther1Path;
          break;
        case nodes.nodeTypes.ATH:
          $scope.HDWallet.dPath = $scope.HDWallet.hwAtheiosPath;
          break;
        case nodes.nodeTypes.ILT:
          $scope.HDWallet.dPath = $scope.HDWallet.hwIolitePath;
          break;
        case nodes.nodeTypes.TOMO:
          $scope.HDWallet.dPath = $scope.HDWallet.tomoPath;
          break;
        case nodes.nodeTypes.MIX:
          $scope.HDWallet.dPath = $scope.HDWallet.hwMixPath;
          break;
        case nodes.nodeTypes.REOSC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwReoscPath;
          break;
        default:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorPath;
      }
    } else {
      switch ($scope.nodeType) {
        case nodes.nodeTypes.ETH:
          $scope.HDWallet.dPath = $scope.HDWallet.defaultDPath;
          break;
        case nodes.nodeTypes.ETC:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorClassicPath;
          break;
        case nodes.nodeTypes.Ropsten:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorTestnetPath;
          break;
        case nodes.nodeTypes.Rinkeby:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorTestnetPath;
          break;
        case nodes.nodeTypes.Kovan:
          $scope.HDWallet.dPath = $scope.HDWallet.trezorTestnetPath;
          break;
        case nodes.nodeTypes.EXP:
          $scope.HDWallet.dPath = $scope.HDWallet.hwExpansePath;
          break;
        case nodes.nodeTypes.UBQ:
          $scope.HDWallet.dPath = $scope.HDWallet.hwUbqPath;
          break;
        case nodes.nodeTypes.CLO:
          $scope.HDWallet.dPath = $scope.HDWallet.hwCallistoPath;
          break;
        case nodes.nodeTypes.ETSC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwSocialPath;
          break;
        case nodes.nodeTypes.MUSIC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwMusicoinPath;
          break;
        case nodes.nodeTypes.GO:
          $scope.HDWallet.dPath = $scope.HDWallet.goPath;
          break;
        case nodes.nodeTypes.EOSC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEOSClassicPath;
          break;
        case nodes.nodeTypes.AKA:
          $scope.HDWallet.dPath = $scope.HDWallet.hwAkromaPath;
          break;
        case nodes.nodeTypes.ESN:
          $scope.HDWallet.dPath = $scope.HDWallet.hwESNetworkPath;
          break;
        case nodes.nodeTypes.PIRL:
          $scope.HDWallet.dPath = $scope.HDWallet.hwPirlPath;
          break;
        case nodes.nodeTypes.ETHO:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEther1Path;
          break;
        case nodes.nodeTypes.EGEM:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEtherGemPath;
          break;
        case nodes.nodeTypes.ELLA:
          $scope.HDWallet.dPath = $scope.HDWallet.hwEllaismPath;
          break;
        case nodes.nodeTypes.ATH:
          $scope.HDWallet.dPath = $scope.HDWallet.hwAtheiosPath;
          break;
        case nodes.nodeTypes.ILT:
          $scope.HDWallet.dPath = $scope.HDWallet.hwIolitePath;
          break;
        case nodes.nodeTypes.TOMO:
          $scope.HDWallet.dPath = $scope.HDWallet.tomoPath;
          break;
        case nodes.nodeTypes.MIX:
          $scope.HDWallet.dPath = $scope.HDWallet.hwMixPath;
          break;
        case nodes.nodeTypes.REOSC:
          $scope.HDWallet.dPath = $scope.HDWallet.hwReoscPath;
          break;
        case nodes.nodeTypes.THUNDERCORE:
          $scope.HDWallet.dPath = $scope.HDWallet.thundercorePath;
          break;
        default:
          $scope.HDWallet.dPath = $scope.HDWallet.defaultDPath;
      }
    }
  };
  $scope.onHDDPathChange = function(password = $scope.mnemonicPassword) {
    $scope.HDWallet.numWallets = 0;
    if ($scope.walletType == 'pastemnemonic') {
      $scope.HDWallet.hdk = hd.HDKey.fromMasterSeed(
        hd.bip39.mnemonicToSeed($scope.manualmnemonic.trim(), password)
      );
      $scope.setHDAddresses(
        $scope.HDWallet.numWallets,
        $scope.HDWallet.walletsPerDialog
      );
    } else if ($scope.walletType == 'ledger') {
      $scope.scanLedger();
    } else if ($scope.walletType == 'trezor') {
      $scope.scanTrezor();
    } else if ($scope.walletType == 'digitalBitbox') {
      $scope.scanDigitalBitbox();
    } else if ($scope.walletType == 'secalot') {
      $scope.scanSecalot();
    } else if ($scope.walletType == 'mewConnect') {
      $scope.scanMewConnect();
    }
  };
  $scope.onCustomHDDPathChange = function() {
    $scope.HDWallet.dPath = $scope.HDWallet.customDPath;
    $scope.onHDDPathChange();
  };
  $scope.showContent = function($fileContent) {
    $scope.notifier.info(
      globalFuncs.successMsgs[4] +
      document.getElementById('fselector').files[0].name
    );
    try {
      $scope.requireFPass = Wallet.walletRequirePass($fileContent);
      $scope.showFDecrypt = !$scope.requireFPass;
      $scope.fileContent = $fileContent;
    } catch (e) {
      $scope.notifier.danger(e);
    }
  };
  $scope.openFileDialog = function($fileContent) {
    $scope.showAOnly = false;
    document.getElementById('fselector').click();
  };
  $scope.onFilePassChange = function() {
    $scope.showAOnly = false;
    $scope.showFDecrypt = $scope.filePassword.length >= 0;
  };
  $scope.onPrivKeyChange = function() {
    $scope.showAOnly = false;
    const manualprivkey = fixPkey($scope.manualprivkey);

    $scope.requirePPass =
      manualprivkey.length == 128 || manualprivkey.length == 132;
    $scope.showPDecrypt = manualprivkey.length == 64;
  };
  $scope.onPrivKeyPassChange = function() {
    $scope.showAOnly = false;
    $scope.showPDecrypt = $scope.privPassword.length > 0;
  };
  $scope.onMnemonicChange = function() {
    $scope.showAOnly = false;
    $scope.showMDecrypt = hd.bip39.validateMnemonic($scope.manualmnemonic);
  };
  $scope.onParityPhraseChange = function() {
    if ($scope.parityPhrase) $scope.showParityDecrypt = true;
    else $scope.showParityDecrypt = false;
  };
  $scope.onAddressChange = function() {
    $scope.requireFPass = $scope.requirePPass = $scope.showFDecrypt = $scope.showPDecrypt = $scope.showParityDecrypt = false;
    $scope.showAOnly = $scope.Validator.isValidAddress($scope.addressOnly);
  };
  $scope.setHDAddresses = function(start, limit) {
    $scope.HDWallet.wallets = [];
    for (var i = start; i < start + limit; i++) {
      $scope.HDWallet.wallets.push(
        new Wallet(
          $scope.HDWallet.hdk.derive(
            $scope.HDWallet.dPath + '/' + i
          )._privateKey
        )
      );
      $scope.HDWallet.wallets[$scope.HDWallet.wallets.length - 1].setBalance(
        false
      );
    }
    $scope.HDWallet.id = 0;
    $scope.HDWallet.numWallets = start + limit;
  };
  $scope.setHDAddressesHWWallet = function(start, limit, ledger) {
    $scope.HDWallet.wallets = [];
    for (var i = start; i < start + limit; i++) {
      var derivedKey = $scope.HDWallet.hdk.derive('m/' + i);
      if ($scope.walletType == 'ledger') {
        $scope.HDWallet.wallets.push(
          new Wallet(
            undefined,
            derivedKey.publicKey,
            $scope.HDWallet.dPath + '/' + i,
            $scope.walletType,
            $scope.ledger
          )
        );
      } else if ($scope.walletType == 'digitalBitbox') {
        $scope.HDWallet.wallets.push(
          new Wallet(
            undefined,
            derivedKey.publicKey,
            $scope.HDWallet.dPath + '/' + i,
            $scope.walletType,
            $scope.digitalBitbox
          )
        );
      } else if ($scope.walletType == 'secalot') {
        $scope.HDWallet.wallets.push(
          new Wallet(
            undefined,
            derivedKey.publicKey,
            $scope.HDWallet.dPath + '/' + i,
            $scope.walletType,
            $scope.secalot
          )
        );
      } else if ($scope.walletType == 'mewConnect') {
        $scope.HDWallet.wallets.push(
          new Wallet(
            undefined,
            derivedKey.publicKey,
            $scope.HDWallet.dPath + '/' + i,
            $scope.walletType,
            $scope.mewConnect
          )
        );
      } else {
        $scope.HDWallet.wallets.push(
          new Wallet(
            undefined,
            derivedKey.publicKey,
            $scope.HDWallet.dPath + '/' + i,
            $scope.walletType
          )
        );
      }
      $scope.HDWallet.wallets[$scope.HDWallet.wallets.length - 1].type =
        'addressOnly';
      $scope.HDWallet.wallets[$scope.HDWallet.wallets.length - 1].setBalance(
        false
      );
    }
    $scope.HDWallet.id = 0;
    $scope.HDWallet.numWallets = start + limit;
  };
  $scope.AddRemoveHDAddresses = function(isAdd) {
    if (
      $scope.walletType == 'ledger' ||
      $scope.walletType == 'trezor' ||
      $scope.walletType == 'digitalBitbox' ||
      $scope.walletType == 'secalot' ||
      $scope.walletType == 'mewConnect'
    ) {
      if (isAdd)
        $scope.setHDAddressesHWWallet(
          $scope.HDWallet.numWallets,
          $scope.HDWallet.walletsPerDialog
        );
      else
        $scope.setHDAddressesHWWallet(
          $scope.HDWallet.numWallets - 2 * $scope.HDWallet.walletsPerDialog,
          $scope.HDWallet.walletsPerDialog
        );
    } else {
      if (isAdd)
        $scope.setHDAddresses(
          $scope.HDWallet.numWallets,
          $scope.HDWallet.walletsPerDialog
        );
      else
        $scope.setHDAddresses(
          $scope.HDWallet.numWallets - 2 * $scope.HDWallet.walletsPerDialog,
          $scope.HDWallet.walletsPerDialog
        );
    }
  };
  $scope.setHDWallet = function() {
    walletService.wallet = $scope.wallet =
      $scope.HDWallet.wallets[$scope.HDWallet.id];
    $scope.mnemonicModel.close();
    $scope.notifier.info(globalFuncs.successMsgs[1]);
    $scope.wallet.type = 'default';
  };
  $scope.decryptWallet = function() {
    $scope.wallet = null;
    try {
      if ($scope.showPDecrypt && $scope.requirePPass) {
        $scope.wallet = Wallet.fromMyEtherWalletKey(
          $scope.manualprivkey,
          $scope.privPassword
        );
        walletService.password = $scope.privPassword;
      } else if ($scope.showPDecrypt && !$scope.requirePPass) {
        let privKey =
          $scope.manualprivkey.indexOf('0x') === 0
            ? $scope.manualprivkey
            : '0x' + $scope.manualprivkey;

        if (!$scope.Validator.isValidHex($scope.manualprivkey)) {
          $scope.notifier.danger(globalFuncs.errorMsgs[37]);
          return;
        } else if (!ethUtil.isValidPrivate(ethUtil.toBuffer(privKey))) {
          $scope.wallet = null;
          $scope.notifier.danger(globalFuncs.errorMsgs[40]);
          return;
        } else {
          $scope.wallet = new Wallet(fixPkey($scope.manualprivkey));
          walletService.password = '';
        }
      } else if ($scope.showFDecrypt) {
        $scope.wallet = Wallet.getWalletFromPrivKeyFile(
          $scope.fileContent,
          $scope.filePassword
        );
        walletService.password = $scope.filePassword;
      } else if ($scope.showMDecrypt) {
        $scope.mnemonicModel = new Modal(
          document.getElementById('mnemonicModel')
        );
        $scope.mnemonicModel.open();
        $scope.onHDDPathChange($scope.mnemonicPassword);
      } else if ($scope.showParityDecrypt) {
        $scope.wallet = Wallet.fromParityPhrase($scope.parityPhrase);
      }
      walletService.wallet = $scope.wallet;
    } catch (e) {
      $scope.notifier.danger(globalFuncs.errorMsgs[6] + e);
    }

    if ($scope.wallet !== null) {
      $scope.notifier.info(globalFuncs.successMsgs[1]);
      $scope.wallet.type = 'default';
    }
  };
  $scope.decryptAddressOnly = function() {
    if ($scope.Validator.isValidAddress($scope.addressOnly)) {
      var tempWallet = new Wallet();
      $scope.wallet = {
        type: 'addressOnly',
        address: $scope.addressOnly,
        getAddressString: function() {
          return this.address;
        },
        getChecksumAddressString: function() {
          return ethUtil.toChecksumAddress(this.getAddressString());
        },
        setBalance: tempWallet.setBalance,
        setTokens: tempWallet.setTokens
      };
      $scope.notifier.info(globalFuncs.successMsgs[1]);
      walletService.wallet = $scope.wallet;
    }
  };
  $scope.HWWalletCreate = function(publicKey, chainCode, walletType, path) {
    $scope.mnemonicModel = new Modal(document.getElementById('mnemonicModel'));
    $scope.mnemonicModel.open();
    $scope.HDWallet.hdk = new hd.HDKey();
    $scope.HDWallet.hdk.publicKey = new Buffer(publicKey, 'hex');
    $scope.HDWallet.hdk.chainCode = new Buffer(chainCode, 'hex');
    $scope.HDWallet.numWallets = 0;
    $scope.HDWallet.dPath = path;
    $scope.setHDAddressesHWWallet(
      $scope.HDWallet.numWallets,
      $scope.HDWallet.walletsPerDialog,
      walletType
    );
    walletService.wallet = null;
  };
  $scope.ledgerCallback = function(result, error) {
    if (typeof result != 'undefined') {
      $scope.HWWalletCreate(
        result['publicKey'],
        result['chainCode'],
        'ledger',
        $scope.getLedgerPath()
      );
    } else {
      $scope.ledgerError = true;
      $scope.ledgerErrorString = error;
      $scope.$apply();
    }
  };
  $scope.digitalBitboxCallback = function(result, error) {
    $scope.HDWallet.digitalBitboxSecret = '';
    if (typeof result != 'undefined') {
      $scope.HWWalletCreate(
        result['publicKey'],
        result['chainCode'],
        'digitalBitbox',
        $scope.HDWallet.dPath
      );
    } else $scope.notifier.danger(error);
  };
  $scope.secalotCallback = function(result, error) {
    if (typeof result != 'undefined') {
      $scope.HWWalletCreate(
        result['publicKey'],
        result['chainCode'],
        'secalot',
        $scope.HDWallet.dPath
      );
    } else $scope.notifier.danger(error);
  };
  $scope.scanLedger = function() {
    $scope.ledgerError = false;
    $scope.ledger = new Ledger3('w0w');
    var app = new ledgerEth($scope.ledger);
    var path = $scope.getLedgerPath();
    app.getAddress(path, $scope.ledgerCallback, false, true);
  };
  $scope.scanDigitalBitbox = function() {
    $scope.digitalBitbox = new DigitalBitboxUsb();
    var app = new DigitalBitboxEth(
      $scope.digitalBitbox,
      $scope.HDWallet.digitalBitboxSecret
    );
    var path = $scope.HDWallet.dPath;
    app.getAddress(path, $scope.digitalBitboxCallback);
  };
  $scope.scanSecalot = function() {
    $scope.secalot = new SecalotUsb();
    if (typeof $scope.HDWallet.secalotSecret == 'undefined') {
      $scope.HDWallet.secalotSecret = '';
    }
    var app = new SecalotEth($scope.secalot, $scope.HDWallet.secalotSecret);
    var path = $scope.HDWallet.dPath;
    app.getAddress(path, $scope.secalotCallback);
  };
  $scope.scanTrezor = function() {
    // trezor is using the path without change level id
    var path = $scope.getTrezorPath();

    TrezorConnect.getPublicKey({path})
      .then(
        ({
          payload: {
            path,
            serializedPath,
            xpub,
            chainCode,
            childNum,
            publicKey,
            fingerprint,
            depth
          }
        }) => {
          $scope.HWWalletCreate(
            publicKey,
            chainCode,
            'trezor',
            $scope.getTrezorPath()
          );
        }
      )
      .catch(err => {
        $scope.trezorError = true;
        $scope.trezorErrorString = err;
        $scope.$apply();
      });
  };
  // ================= Mew Connect (start)==============================
  $scope.scanMewConnect = function() {
    globalFuncs.MEWconnectStatus.newTabOpenedTrigger(true);
    globalFuncs.MEWconnectStatus.update(0);
    var app = new MewConnectEth();

    globalFuncs.MEWconnectStatus.MEWconnect = MewConnect.init();

    $scope.$on('$destroy', function() {
      globalFuncs.MEWconnectStatus.newTabOpenedTrigger(false);
      globalFuncs.MEWconnectStatus.update(0);
      globalFuncs.MEWconnectStatus.MEWconnect.disconnectRTC();
      globalFuncs.MEWconnectStatus.MEWconnect = null;
    });

    globalFuncs.MEWconnectStatus.MEWconnect.on('codeDisplay', codeDisplay);
    globalFuncs.MEWconnectStatus.MEWconnect.on('RtcConnectedEvent', rtcConnected);
    globalFuncs.MEWconnectStatus.MEWconnect.on('RtcClosedEvent', rtcClosed);
    globalFuncs.MEWconnectStatus.MEWconnect.on('RtcDisconnectEvent', rtcDisconnected);
    globalFuncs.MEWconnectStatus.MEWconnect.on('address', makeWallet);

    app.setMewConnect(globalFuncs.MEWconnectStatus.MEWconnect);
    app.signalerConnect();

    $scope.connectionCodeTimeout = null;
    $scope.haveAddress = false;

    function rtcConnected(data) {
      if ($scope.connectionCodeTimeout) {
        clearTimeout($scope.connectionCodeTimeout);
      }
      globalFuncs.MEWconnectStatus.update(2);
      if ($scope.mewConnectionStatus !== 2) {
        $scope.connectionCodeTimeout = null;
        globalFuncs.MEWconnectStatus.MEWconnect.sendRtcMessage('address', '');
        uiFuncs.notifier.info('Connected Via MEWconnect');
        $scope.mewConnectionStatus = 2;
      } else if (!$scope.haveAddress) {
        $scope.connectionCodeTimeout = null;
        globalFuncs.MEWconnectStatus.MEWconnect.sendRtcMessage('address', '');
        uiFuncs.notifier.info('Connected Via MEWconnect');
      }
    }

    function rtcClosed(data) {
      globalFuncs.MEWconnectStatus.update(4);
      if ($scope.mewConnectionStatus !== 4) {
        $scope.mewConnectionStatus = 4;
        $scope.wallet = null;
        walletService.wallet = null;
        uiFuncs.notifier.danger('Disconnected', 10000);
        if (!$scope.$$phase) $scope.$apply();
      }
    }

    function rtcDisconnected(data) {
      globalFuncs.MEWconnectStatus.update(4);
      if ($scope.mewConnectionStatus !== 4) {
        $scope.mewConnectionStatus = 4;
        $scope.wallet = null;
        walletService.wallet = null;
        uiFuncs.notifier.danger('Disconnected', 10000);
        if (!$scope.$$phase) $scope.$apply();
      }
    }

    function codeDisplay(data) {
      $scope.mewConnectionStatus = 1;
      globalFuncs.MEWconnectStatus.update(1);
      $scope.mewConnectCode = data;
      $scope.connectionCodeTimeout = setTimeout(() => {
        $scope.mewConnectionStatus = 3;
        globalFuncs.MEWconnectStatus.update(3);
        if (!$scope.$$phase) $scope.$apply();
      }, 119800); // 200ms before the actual server timeout happens. (to account for transit time, ui lag, etc.)
      if (!$scope.$$phase) $scope.$apply();
    }

    function makeWallet(data) {
      var wallet = app.createWallet(data);
      $scope.wallet = wallet;
      walletService.wallet = wallet;
      $scope.haveAddress = true;
      if (!$scope.$$phase) $scope.$apply();
    }
  };

  $scope.mewConnectDisconnect = function() {
    globalFuncs.MEWconnectStatus.MEWconnect.disconnectRTC();
  };
  //= ================ Mew Connect (end)==============================
  $scope.getLedgerPath = function() {
    return $scope.HDWallet.dPath;
  };
  $scope.getTrezorPath = function() {
    return $scope.HDWallet.dPath;
  };

  function setWeb3Wallet() {
    window.web3.eth.getAccounts(function(err, accounts) {
      if (err)
        $scope.notifier.danger(
          err + '. Are you sure you are on a secure (SSL / HTTPS) connection?'
        );
      if (!accounts.length) {
        $scope.notifier.danger(
          'Could not read your accounts from MetaMask. Try unlocking it.'
        );
        return;
      }
      var address = accounts[0];
      var addressBuffer = Buffer.from(address.slice(2), 'hex');
      var wallet = new Web3Wallet(addressBuffer);
      wallet.setBalance(false);
      // set wallet
      $scope.wallet = wallet;
      walletService.wallet = wallet;
      $scope.notifier.info(globalFuncs.successMsgs[6]);
      $scope.wallet.type = 'default';
    });
  }

  $scope.scanMetamask = async function() {
    // if (window.web3 === undefined) {
    //   window.addEventListener('message', ({data}) => {
    //     if (data && data.type && data.type === 'ETHEREUM_PROVIDER_SUCCESS') {
    //       window.web3 = new Web3(ethereum);
    //     }
    //   });
    //   window.postMessage({ type: 'ETHEREUM_PROVIDER_REQUEST', web3: true }, '*');
    // }
    if (window.ethereum) {
      window.web3 = new Web3(ethereum);
      try {
        await ethereum.enable();
        setWeb3Wallet();
      } catch (e) {
        $scope.notifier.danger(
          'Could not read your accounts from MetaMask. Try unlocking it.'
        );
      }
    } else if (window.web3) {
      window.web3 = new Web3(web3.currentProvider);
      setWeb3Wallet();
    } else {
      $scope.notifier.danger(
        'Non-Ethereum browser detected. You should consider trying MetaMask!'
      );
    }
  };

  // helper function that removes 0x prefix from strings
  function fixPkey(key) {
    if (key.indexOf('0x') === 0) {
      return key.slice(2);
    }
    return key;
  }
};
module.exports = decryptWalletCtrl;


text:
package org.apache.camel.component.kafka;

/**
 *
 */
public final class KafkaConstants {

    public static final String DEFAULT_GROUP = "group1";

    public static final String PARTITION_KEY = "kafka.PARTITION_KEY";
    public static final String PARTITION = "kafka.EXCHANGE_NAME";
    public static final String KEY = "kafka.CONTENT_TYPE";
    public static final String TOPIC = "kafka.TOPIC";

    private KafkaConstants() {
        // Utility class
    }
}


text:
'use strict';

var should = require('should');
var helper = require("../helper");
var POGarmentGeneralManager = require("../../src/managers/po/po-garment-general-manager");
var instanceManager = null;

function getData() {
    var POGarmentGeneral = require('dl-models').po.POGarmentGeneral;
    var UoM = require('dl-models').core.UoM;
    var PurchaseOrderItem = require('dl-models').po.PurchaseOrderItem;
    var Product = require('dl-models').core.Product;

    var now = new Date();
    var stamp = now / 1000 | 0;
    var code = stamp.toString(36);

    var poGarmentGeneral = new POGarmentGeneral();
    poGarmentGeneral.PRNo = '1' + code + stamp;
    poGarmentGeneral.RefPONo = '2' + code + stamp;
    poGarmentGeneral.PODLNo = '';
    poGarmentGeneral.buyerId = {};

    var _uom = new UoM({
        unit: `Meter`
    });

    var product = new Product("general-merchandiser", {
        code: '22',
        name: 'hotline',
        price: 0,
        description: 'hotline123',
        UoM: _uom,
        detail: {}
    });

    var productValue = new PurchaseOrderItem({
        quantity: 10,
        price: 10000,
        description : 'test desc',
        dealQuantity : 10,
        dealMeasurement : 'Meter',
        defaultQuantity : 1000,
        defaultMeasurementQuantity : 'Centimeter',
        product: product
    });

    var _products = [];
    _products.push(productValue);

    poGarmentGeneral.items = _products;

    return poGarmentGeneral;
}

function getPODL(poGarmentGeneral) {

    var PurchaseOrderGroup = require('dl-models').po.PurchaseOrderGroup;
    var Supplier = require('dl-models').core.Supplier;

    var poGroupGarmentGeneral = new PurchaseOrderGroup();
    poGroupGarmentGeneral.usePPn = true;
    poGroupGarmentGeneral.usePPh = true;
    poGroupGarmentGeneral.deliveryDate = new Date();
    poGroupGarmentGeneral.termOfPayment = 'Cash';
    poGroupGarmentGeneral.deliveryFeeByBuyer = true;
    poGroupGarmentGeneral.description = 'SP1';
    poGroupGarmentGeneral.currency = 'dollar';
    poGroupGarmentGeneral.paymentDue = 2;
    poGroupGarmentGeneral.supplierId = {};

    var _supplier = new Supplier({
        code: '123',
        name: 'Supplier01',
        contact: '0812....',
        PIC:'Suppy',
        address: 'test',
        import: true
    });

    var _items = [];
    _items.push(poGarmentGeneral);

    poGroupGarmentGeneral.supplier = _supplier;
    poGroupGarmentGeneral.items = _items;

    return poGroupGarmentGeneral;
}

function updateForSplit(purchaseOrder) {

    var newPurchaseOrder = {};
    newPurchaseOrder.iso = purchaseOrder.iso;
    newPurchaseOrder.RONo = purchaseOrder.RONo;
    newPurchaseOrder.PRNo = purchaseOrder.PRNo;
    newPurchaseOrder.RefPONo = purchaseOrder.PRNo;
    newPurchaseOrder.linkedPONo = purchaseOrder.PONo;
    newPurchaseOrder.article = purchaseOrder.article;
    newPurchaseOrder.buyerId = purchaseOrder.buyerId;
    newPurchaseOrder.buyer = purchaseOrder.buyer;
    newPurchaseOrder.shipmentDate = purchaseOrder.shipmentDate;
    newPurchaseOrder.items = purchaseOrder.items;

    for(var item of newPurchaseOrder.items) {
        item.dealQuantity = 1;
        item.defaultQuantity = 10;
    }

    return newPurchaseOrder;
}

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            instanceManager = new POGarmentGeneralManager(db, {
                username: 'unit-test'
            });
            done();
        })
        .catch(e => {
            done(e);
        })
});

it('#01. should success when read data', function (done) {
    instanceManager.read()
        .then(documents => {
            //process documents
            documents.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        })
});

it('#02. should success when read all podl data', function (done) {
    instanceManager.readAllPurchaseOrderGroup()
        .then(documents => {
            //process documents
            documents.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        })
});

var createdId;
it('#03. should success when create new data', function (done) {
    var data = getData();
    instanceManager.create(data)
        .then(id => {
            id.should.be.Object();
            createdId = id;
            done();
        })
        .catch(e => {
            done(e);
        })
});

it('#04. should success when split po', function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(result => {
            var data = updateForSplit(result);
            instanceManager.split(data)
                .then(id => {
                    id.should.be.Object();
                    done();
                })
                .catch(e => {
                    done(e);
                })

        })
        .catch(e => {
            done(e);
        })
});

var createdPODLId;
it('#05. should success when create podl data', function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(result => {
            var data = getPODL(result)
            instanceManager.createGroup(data)
                .then(id => {
                    id.should.be.Object();
                    createdPODLId = id;
                    done();
                })
                .catch(e => {
                    done(e);
                })

        })
        .catch(e => {
            done(e);
        })
});

var createdData;
it(`#06. should success when get created data with id`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            data.should.instanceof(Object);
            createdData = data;
            done();
        })
        .catch(e => {
            done(e);
        })
});

it(`#07. should success when update created data`, function (done) {
    createdData.PRNo += '[updated]';

    instanceManager.update(createdData)
        .then(id => {
            createdId.toString().should.equal(id.toString());
            done();
        })
        .catch(e => {
            done(e);
        });
});

it(`#08. should success when get updated data with id`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            data.PRNo.should.equal(createdData.PRNo);
            data.PONo.should.equal(createdData.PONo);
            data.PODLNo.should.equal(createdData.PODLNo);

            done();
        })
        .catch(e => {
            done(e);
        })
});

// it(`#09. should success when delete data`, function (done) {
//     instanceManager.delete(createdData)
//         .then(id => {
//             createdId.toString().should.equal(id.toString());
//             done();
//         })
//         .catch(e => {
//             done(e);
//         });
// });

// it(`#10. should _deleted=true`, function (done) {
//     instanceManager.getSingleByQuery({ _id: createdId })
//         .then(data => {
//             // validate.product(data);
//             data._deleted.should.be.Boolean();
//             data._deleted.should.equal(true);
//             done();
//         })
//         .catch(e => {
//             done(e);
//         })
// });


text:
'use strict';

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _promise = require('babel-runtime/core-js/promise');

var _promise2 = _interopRequireDefault(_promise);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Realm = require('realm');
var uuidv4 = require('uuid/v4');

/*
let PostSchema = {
  name: 'Post',
  properties: {
    timestamp: 'date',
    title: 'string',
    content: 'string'
  }
}

let UsersSchema = {
  name: 'User',
  primaryKey: 'uuid',
  properties: {
    uuid: 'string',
    username: 'string',
    age: 'int',
    role: 'string',
    created_at: 'date'
  }
}

let schema = [PostSchema, UsersSchema]
*/

console.log('#### DATABSE ####');
// #### The 'new' should be placed to create Realm connection.
// https://realm.io/docs/javascript/latest/
//
// ===> Setting dbPath = 'database.realm' creates database file
//       at project directory while debug.
//       The location is not at the same location as this database.js src.
//
// ===> After making electronquickstart.app with npm run release,
//      the app halts with error.
//
//      terminating with uncaught exception of type
//    realm::util::File::PermissionDenied: make_dir() failed: Permission denied
//
// ===> Change current working directory of the launched app to userData.
//
/*
const electron = require('electron')
const app = electron.app
let userData = app.getPath('userData')
// #############################################
// https://github.com/realm/realm-js/issues/818
process.chdir(userData)
// #############################################
const path = require('path')
let dbPath = path.join(userData, 'database.realm')
console.log('Database Path', dbPath)
// /Users/codepropagator/Library/Application Support/electronquickstart/database.realm
*/

var dbPath = 'default.realm';
var dbSchema = [];

var registerPathAndSchema = function registerPathAndSchema(path, schema) {
  dbPath = path;
  dbSchema = schema;
  // Synchronously open the Realm at first.
  var realm = new Realm({
    path: dbPath,
    schema: dbSchema
  });
  return realm;
};

var listen = function listen(objects) {
  objects.addListener(function (arr, changes) {
    console.log('objects changed');

    // Update UI in response to inserted objects
    changes.insertions.forEach(function (index) {
      var inserted = arr[index];
      console.log('---> inserted', inserted);
    });
    // Update UI in response to modified objects
    changes.modifications.forEach(function (index) {
      var modified = arr[index];
      console.log('---> modified', modified);
    });
    // Update UI in response to deleted objects
    changes.deletions.forEach(function (index) {
      // Deleted objects cannot be accessed directly
      // Support for accessing deleted objects coming soon...
      console.log('---> deleted');
    });
  });
};

var putItem = function putItem(realm, name, item) {
  realm.write(function () {
    realm.create(name, item);
  });
};

var testDB = function testDB() {
  // Synchronously open the Realm at first.
  var realm = new Realm({
    path: dbPath,
    schema: dbSchema
  });

  // Observe Realm Notifications
  var myFunc = function myFunc() {
    console.log('### realm changed');
  };
  realm.addListener('change', myFunc);

  // ..later remove the listener
  // realm.removeListener('change', ...)

  // ..or unregister all listeners
  // realm.removeAllListeners()

  var posts = realm.objects('Post').sorted('timestamp', true);
  listen(posts);

  var users = realm.objects('User').sorted('created_at', true);
  listen(users);

  // Do someting with database.
  var getBlog = function getBlog() {
    return {
      Post: posts,
      User: users
    };
  };

  var putPost = function putPost(realm, title, content, timestamp) {
    putItem(realm, 'Post', {
      title: title,
      content: content,
      timestamp: timestamp
    });
  };

  var putUser = function putUser(realm, username, age, role, timestamp) {
    // Take care of primary key so that not to get error.
    // Error: Attempting to create an object of type 'User' with an existing primary key value.
    // https://www.npmjs.com/package/uuid
    putItem(realm, 'User', {
      uuid: uuidv4(),
      username: username,
      age: age,
      role: role,
      created_at: timestamp
    });
  };

  var myAsyncTask1 = function () {
    var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
      var res;
      return _regenerator2.default.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return function () {
                return new _promise2.default(function (resolve, reject) {
                  try {
                    var timestamp = new Date();
                    putPost(realm, 'Test', 'Hello. Electron can handle Realm for JavaScript!', timestamp);
                    putUser(realm, 'Me', 3, 'user', timestamp);
                    return console.log(resolve('Task1 OK'));
                  } catch (err) {
                    return reject(err);
                  }
                });
              }();

            case 3:
              res = _context.sent;
              return _context.abrupt('return', console.log('DONE myAsyncTask1', res));

            case 7:
              _context.prev = 7;
              _context.t0 = _context['catch'](0);
              return _context.abrupt('return', console.error('ERROR in myAsyncTask1', _context.t0));

            case 10:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, undefined, [[0, 7]]);
    }));

    return function myAsyncTask1() {
      return _ref.apply(this, arguments);
    };
  }();

  var myAsyncTask2 = function () {
    var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() {
      var res;
      return _regenerator2.default.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              _context2.next = 3;
              return function () {
                return new _promise2.default(function (resolve, reject) {
                  try {
                    var blog = getBlog();
                    console.log('blog.posts.length', blog.Post.length);
                    console.log('blog.users.length', blog.User.length);
                    return console.log(resolve('Task2 OK'));
                  } catch (err) {
                    return reject(err);
                  }
                });
              }();

            case 3:
              res = _context2.sent;
              return _context2.abrupt('return', console.log('DONE myAsyncTask2', res));

            case 7:
              _context2.prev = 7;
              _context2.t0 = _context2['catch'](0);
              return _context2.abrupt('return', console.error('ERROR in myAsyncTask2', _context2.t0));

            case 10:
            case 'end':
              return _context2.stop();
          }
        }
      }, _callee2, undefined, [[0, 7]]);
    }));

    return function myAsyncTask2() {
      return _ref2.apply(this, arguments);
    };
  }();

  myAsyncTask1().catch(function (err) {
    console.log('CAUGHT ERROR', err);
  });

  myAsyncTask2().catch(function (err) {
    console.log('CAUGHT ERROR', err);
  });

  realm.removeListener('change', myFunc);
};

var allData = function allData() {
  // Synchronously open the Realm at first.
  var realm = new Realm({
    path: dbPath,
    schema: dbSchema
  });

  var all = {};
  dbSchema.map(function (def) {
    var name = def.name;
    all[name] = realm.objects(name);
    // not sorted
  });

  // let posts = realm.objects('Post').sorted('timestamp', true)
  // let users = realm.objects('User').sorted('created_at', true)
  // return {Post: posts, User: users}

  return all;
};

var subscribeChange = function subscribeChange(monitor) {
  // Synchronously open the Realm at first.
  var realm = new Realm({
    path: dbPath,
    schema: dbSchema
  });

  realm.addListener('change', monitor);
};

var unsubscribeChange = function unsubscribeChange(monitor) {
  // Synchronously open the Realm at first.
  var realm = new Realm({
    path: dbPath,
    schema: dbSchema
  });

  realm.removeListener('change', monitor);
};

module.exports = {
  dbPath: dbPath,
  dbSchema: dbSchema,
  registerPathAndSchema: registerPathAndSchema,
  testDB: testDB,
  allData: allData,
  subscribeChange: subscribeChange,
  unsubscribeChange: unsubscribeChange
};


text:
<?php

namespace App;

interface ObservedDataParser {

	public function getLastUpdateTime();
	public function populateObservedData();

}


text:
#region Licence

#endregion

using System.Threading;
using System.Threading.Tasks;
using Paramore.Brighter.Policies.Attributes;
using Polly;

namespace Paramore.Brighter.Policies.Handlers
{
    ///
    /// Class ExceptionPolicyHandlerAsync.
    /// The <see cref="UsePolicyAttribute" /> supports the use of Polly to provide quality of service around exceptions
    /// thrown from subsequent steps in the handler pipeline. A Polly Policy can be used to support a Retry or Circuit Breaker approach to exception handling
    /// Policies used by the attribute are identified by a string based key, which is used as a lookup into an <see cref="IAmAPolicyRegistry" /> and it is
    /// assumed that you have registered required policies with a Policy Registry such as <see cref="PolicyRegistry" /> and configured that as a
    /// dependency of the <see cref="CommandProcessor" /> using the <see cref="CommandProcessorBuilder" />
    /// The ExceptionPolicyHandler is instantiated by the pipeline when the <see cref="UsePolicyAttribute" /> is added to the <see cref="IHandleRequests{T}.Handle" /> method
    /// of the target handler implemented by the client.
    ///
    /// <typeparam name="TRequest">The type of the t request.</typeparam>
    public class ExceptionPolicyHandlerAsync<TRequest> : RequestHandlerAsync<TRequest> where TRequest : class, IRequest
    {
        private AsyncPolicy _policy;

        ///
        /// Initializes from attribute parameters. This will get the <see cref="IAmAPolicyRegistry" /> from the <see cref="IRequestContext" /> and query it for the
        /// policy identified in <see cref="UsePolicyAttribute" />
        ///
        /// <param name="initializerList">The initializer list.</param>
        /// <exception cref="System.ArgumentException">Could not find the policy for this attribute, did you register it with the command processor's container;initializerList</exception>
        public override void InitializeFromAttributeParams(params object[] initializerList)
        {
            //we expect the first and only parameter to be a string
            var policyName = (string)initializerList[0];
            _policy = Context.Policies.Get<AsyncPolicy>(policyName);
        }

        ///
        /// Handles the specified command asynchronously.
        ///
        /// <param name="command">The command.</param>
        /// <param name="cancellationToken">Allow the sender to cancel the reques (optional) </param>
        /// <returns>AA Task<TRequest> that wraps the asynchonous call to the policy, which itself wraps the handler chain</TRequest></returns>
        public override async Task<TRequest> HandleAsync(TRequest command, CancellationToken cancellationToken = default(CancellationToken))
        {
            return await _policy.ExecuteAsync(async () => await base.HandleAsync(command, cancellationToken)).ConfigureAwait(ContinueOnCapturedContext);
        }
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Microsoft.ApiDesignGuidelines.Analyzers
{
    /// <summary>
    /// CA1019: Define accessors for attribute arguments
    ///
    /// Cause:
    /// In its constructor, an attribute defines arguments that do not have corresponding properties.
    /// </summary>
    public abstract class DefineAccessorsForAttributeArgumentsAnalyzer : DiagnosticAnalyzer
    {
        internal const string RuleId = "CA1019";
        internal const string AddAccessorCase = "AddAccessor";
        internal const string MakePublicCase = "MakePublic";
        internal const string RemoveSetterCase = "RemoveSetter";

        private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DefineAccessorsForAttributeArgumentsTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
        private static readonly LocalizableString s_defaultRuleMessage = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DefineAccessorsForAttributeArgumentsMessageDefault), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
        private static readonly LocalizableString s_increaseVisibilityMessage = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DefineAccessorsForAttributeArgumentsMessageIncreaseVisibility), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
        private static readonly LocalizableString s_removeSetterMessage = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.DefineAccessorsForAttributeArgumentsMessageRemoveSetter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));

        internal static DiagnosticDescriptor DefaultRule = new DiagnosticDescriptor(RuleId,
                                                                                s_localizableTitle,
                                                                                s_defaultRuleMessage,
                                                                                DiagnosticCategory.Design,
                                                                                DiagnosticSeverity.Warning,
                                                                                isEnabledByDefault: false,
                                                                                helpLinkUri: "http://msdn.microsoft.com/library/ms182136.aspx",
                                                                                customTags: WellKnownDiagnosticTags.Telemetry);

        internal static DiagnosticDescriptor IncreaseVisibilityRule = new DiagnosticDescriptor(RuleId,
                                                                                s_localizableTitle,
                                                                                s_increaseVisibilityMessage,
                                                                                DiagnosticCategory.Design,
                                                                                DiagnosticSeverity.Warning,
                                                                                isEnabledByDefault: false,
                                                                                helpLinkUri: "http://msdn.microsoft.com/library/ms182136.aspx",
                                                                                customTags: WellKnownDiagnosticTags.Telemetry);

        internal static DiagnosticDescriptor RemoveSetterRule = new DiagnosticDescriptor(RuleId,
                                                                                s_localizableTitle,
                                                                                s_removeSetterMessage,
                                                                                DiagnosticCategory.Design,
                                                                                DiagnosticSeverity.Warning,
                                                                                isEnabledByDefault: false,
                                                                                helpLinkUri: "http://msdn.microsoft.com/library/ms182136.aspx",
                                                                                customTags: WellKnownDiagnosticTags.Telemetry);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get
            {
                return ImmutableArray.Create(DefaultRule, IncreaseVisibilityRule, RemoveSetterRule);
            }
        }

        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.RegisterCompilationStartAction(compilationContext =>
            {
                var attributeType = WellKnownTypes.IDisposable(compilationContext.Compilation);
                if (attributeType == null)
                {
                    return;
                }

                compilationContext.RegisterSymbolAction(context =>
                {
                    AnalyzeSymbol((INamedTypeSymbol)context.Symbol, attributeType, context.Compilation, context.ReportDiagnostic);
                },
                SymbolKind.NamedType);
            });
        }

        private void AnalyzeSymbol(INamedTypeSymbol symbol, INamedTypeSymbol attributeType, Compilation compilation, Action<Diagnostic> addDiagnostic)
        {
            if (symbol != null && symbol.GetBaseTypesAndThis().Contains(WellKnownTypes.Attribute(compilation)) && symbol.DeclaredAccessibility != Accessibility.Private)
            {
                IEnumerable<IParameterSymbol> parametersToCheck = GetAllPublicConstructorParameters(symbol);
                if (parametersToCheck.Any())
                {
                    IDictionary<string, IPropertySymbol> propertiesMap = GetAllPropertiesInTypeChain(symbol);
                    AnalyzeParameters(compilation, parametersToCheck, propertiesMap, symbol, addDiagnostic);
                }
            }
        }

        protected abstract bool IsAssignableTo(ITypeSymbol fromSymbol, ITypeSymbol toSymbol, Compilation compilation);

        private static IEnumerable<IParameterSymbol> GetAllPublicConstructorParameters(INamedTypeSymbol attributeType)
        {
            // FxCop compatibility:
            // Only examine parameters of public constructors. Can't use protected
            // constructors to define an attribute so this rule only applies to
            // public constructors.
            var instanceConstructorsToCheck = attributeType.InstanceConstructors.Where(c => c.DeclaredAccessibility == Accessibility.Public);

            if (instanceConstructorsToCheck.Any())
            {
                var uniqueParamNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                foreach (var constructor in instanceConstructorsToCheck)
                {
                    foreach (var parameter in constructor.Parameters)
                    {
                        if (uniqueParamNames.Add(parameter.Name))
                        {
                            yield return parameter;
                        }
                    }
                }
            }
        }

        private static IDictionary<string, IPropertySymbol> GetAllPropertiesInTypeChain(INamedTypeSymbol attributeType)
        {
            var propertiesMap = new Dictionary<string, IPropertySymbol>(StringComparer.OrdinalIgnoreCase);
            foreach (var currentType in attributeType.GetBaseTypesAndThis())
            {
                foreach (IPropertySymbol property in currentType.GetMembers().Where(m => m.Kind == SymbolKind.Property))
                {
                    if (!propertiesMap.ContainsKey(property.Name))
                    {
                        propertiesMap.Add(property.Name, property);
                    }
                }
            }

            return propertiesMap;
        }

        private void AnalyzeParameters(Compilation compilation, IEnumerable<IParameterSymbol> parameters, IDictionary<string, IPropertySymbol> propertiesMap, INamedTypeSymbol attributeType, Action<Diagnostic> addDiagnostic)
        {
            foreach (var parameter in parameters)
            {
                if (parameter.Type.Kind != SymbolKind.ErrorType)
                {
                    IPropertySymbol property;
                    if (!propertiesMap.TryGetValue(parameter.Name, out property) ||
                        !IsAssignableTo(parameter.Type, property.Type, compilation))
                    {
                        // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
                        addDiagnostic(GetDefaultDiagnostic(parameter, attributeType));
                    }
                    else
                    {
                        if (property.GetMethod == null)
                        {
                            // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
                            addDiagnostic(GetDefaultDiagnostic(parameter, attributeType));
                        }
                        else if (property.DeclaredAccessibility != Accessibility.Public ||
                            property.GetMethod.DeclaredAccessibility != Accessibility.Public)
                        {
                            if (!property.ContainingType.Equals(attributeType))
                            {
                                // A non-public getter exists in one of the base types.
                                // However, we cannot be sure if the user can modify the base type (it could be from a third party library).
                                // So generate the default diagnostic instead of increase visibility here.

                                // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
                                addDiagnostic(GetDefaultDiagnostic(parameter, attributeType));
                            }
                            else
                            {
                                // If '{0}' is the property accessor for positional argument '{1}', make it public.
                                addDiagnostic(GetIncreaseVisibilityDiagnostic(parameter, property));
                            }
                        }

                        if (property.SetMethod != null &&
                            property.SetMethod.DeclaredAccessibility == Accessibility.Public &&
                            property.ContainingType == attributeType)
                        {
                            // Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'.
                            addDiagnostic(GetRemoveSetterDiagnostic(parameter, property));
                        }
                    }
                }
            }
        }

        private static Diagnostic GetDefaultDiagnostic(IParameterSymbol parameter, INamedTypeSymbol attributeType)
        {
            // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
            return parameter.Locations.CreateDiagnostic(DefaultRule, new Dictionary<string, string> { { "case", AddAccessorCase } }.ToImmutableDictionary(), parameter.Name, attributeType.Name);
        }

        private static Diagnostic GetIncreaseVisibilityDiagnostic(IParameterSymbol parameter, IPropertySymbol property)
        {
            // If '{0}' is the property accessor for positional argument '{1}', make it public.
            return property.GetMethod.Locations.CreateDiagnostic(IncreaseVisibilityRule, new Dictionary<string, string> { { "case", MakePublicCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
        }

        private static Diagnostic GetRemoveSetterDiagnostic(IParameterSymbol parameter, IPropertySymbol property)
        {
            // Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'.
            return property.SetMethod.Locations.CreateDiagnostic(RemoveSetterRule, new Dictionary<string, string> { { "case", RemoveSetterCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
        }
    }
}


text:
import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;

/**
 * Android Browser Sauce Labs Test.
 */
public class AndroidBrowserSaucelabsTest{
	public static final String USERNAME = "YOUR_USERNAME";
	public static final String ACCESS_KEY = "YOUR_ACESS_KEY";
	public static final String URL = "https://"+USERNAME+":" + ACCESS_KEY + "@ondemand.saucelabs.com:443/wd/hub";
	public static AndroidDriver<?> mobiledriver;

	@BeforeTest
	public void beforeTest( ) throws MalformedURLException {
		DesiredCapabilities capabilities = new DesiredCapabilities();
		capabilities.setCapability(MobileCapabilityType.APPIUM_VERSION, "1.7.2");
		capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "4.4");
		capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");
		capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME,"Appium");
		capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Samsung Galaxy S4 Emulator");
		capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Browser");
		capabilities.setCapability("newCommandTimeout", 2000);
		mobiledriver = new AndroidDriver<>(new URL(URL), capabilities);
	}

	@AfterTest
	public void afterTest( ){
		mobiledriver.quit();
	}

	@Test
	public static void launchBrowser(){
		mobiledriver.get("http://appium.io/");
		Assert.assertEquals(mobiledriver.getCurrentUrl(), "http://appium.io/", "URL Mismatch");
		Assert.assertEquals(mobiledriver.getTitle(), "Appium: Mobile App Automation Made Awesome.", "Title Mismatch");
	}
}


text:
import pytest
import mailbox

class MockBox:
    status = -1
    def __init__(self, path, create):
        pass

    def lock(self):
        pass

    def add(self, message):
        MockBox.status += 1
        if MockBox.status == 0:
            pass
        elif MockBox.status == 1:
            raise mailbox.ExternalClashError
        else:
            raise Exception

    def unlock(self):
        pass

    def close(self):
        pass

from EEHlib.delivery import filesystem
filesystem.mailbox.MockBox = MockBox
Delivery = filesystem.Delivery

def test_delivery():
    d = Delivery({"Mailboxformat":"MockBox", "Path":""})
    assert d.deliver("","","","")
    assert not d.deliver("","","","")
    assert not d.deliver("","","","")

if __name__ == "__main__":
    import __main__
    for i in dir(__main__):
        if i.startswith("test_"):
            print("---", i)
            eval(i).__call__()


text:
package spatial.transform

import argon.core._
import argon.transform.ForwardTransformer
import spatial.aliases._
import spatial.metadata._
import spatial.nodes._
import spatial.utils._
import virtualized.SourceContext

trait UnrollingBase extends ForwardTransformer {
  /**
    * Valid bits - tracks all valid bits associated with the current scope to handle edge cases
    * e.g. cases where parallelization is not an even divider of counter max
    */
  var validBits: Seq[Exp[Bit]] = Nil
  def withValids[T](valids: Seq[Exp[Bit]])(blk: => T): T = {
    val prevValids = validBits
    validBits = valids
    val result = blk
    validBits = prevValids
    result
  }

  // Single global valid - should only be used in inner pipes - creates AND tree
  def globalValid: () => Exp[Bit] = () => {
    if (validBits.isEmpty) Bit.const(true)
    else spatial.lang.Math.reduceTree(validBits){(a,b) => Bit.and(a,b) }
  }

  // Sequence of valid bits associated with current unrolling scope
  def globalValids: Seq[Exp[Bit]] = if (validBits.nonEmpty) validBits else Seq(Bit.const(true))

  def cloneOp[A](lhs: Sym[A], rhs: Op[A]): Exp[A]

  /**
    * Unroll numbers - gives the unroll index of each pre-unrolled (prior to transformer) index
    * Used to determine which duplicate a particular memory access should be associated with
    */
  var unrollNum: Map[Exp[Index], Int] = Map.empty
  def withUnrollNums[A](ind: Seq[(Exp[Index], Int)])(blk: => A): A = {
    val prevUnroll = unrollNum
    unrollNum ++= ind
    val result = blk
    unrollNum = prevUnroll
    result
  }

  /**
    * Helper objects for unrolling
    * Tracks multiple substitution contexts in 'contexts' array
    **/
  trait Unroller {
    def inds: Seq[Bound[Index]]
    def Ps: Seq[Int]

    def P: Int = Ps.product
    def N: Int = Ps.length
    def size: Int = P
    def prods: List[Int] = List.tabulate(N){i => Ps.slice(i+1,N).product }
    def parAddr(p: Int): List[Int] = List.tabulate(N){d => (p / prods(d)) % Ps(d) }

    def contexts: Array[ Map[Exp[Any],Exp[Any]] ]

    private var __valids: Option[ Seq[Seq[Exp[Bit]]] ] = None
    protected def createLaneValids(): Seq[Seq[Exp[Bit]]]

    final def valids: Seq[Seq[Exp[Bit]]] = __valids.getOrElse{
      val vlds = createLaneValids()
      __valids = Some(vlds)
      vlds
    }

    def inLane[A](i: Int)(block: => A): A = {
      val save = subst
      val addr = parAddr(i)
      withUnrollNums(inds.zip(addr)) {
        withSubstRules(contexts(i)) {
          withValids(valids(i)) {
            val result = block
            // Retain only the substitutions added within this scope
            contexts(i) ++= subst.filterNot(save contains _._1)
            result
          }
        }
      }
    }

    def map[A](block: Int => A): List[A] = List.tabulate(P){p => inLane(p){ block(p) } }

    def foreach(block: Int => Unit) { map(block) }

    // --- Each unrolling rule should do at least one of three things:
    // 1. Split a given vector as the substitution for the single original symbol
    def duplicate[A](s: Sym[A], d: Op[A]): List[Exp[_]] = map{_ =>
      val s2 = cloneOp(s, d)
      register(s -> s2)
      s2
    }
    // 2. Make later stages depend on the given substitution across all lanes
    // NOTE: This assumes that the node has no meaningful return value (i.e. all are Pipeline or Unit)
    // Bad things can happen here if you're not careful!
    def split[T:Type](orig: Sym[T], vec: Exp[Vector[_]])(implicit ctx: SrcCtx): List[Exp[T]] = map{p =>
      val element = Vector.select[T](vec.asInstanceOf[Exp[Vector[T]]], p)
      register(orig -> element)
      element
    }
    // 3. Create an unrolled mapping of symbol (orig -> unrolled) for each lane
    def unify[T](orig: Exp[T], unrolled: Exp[T]): List[Exp[T]] = {
      foreach{p => register(orig -> unrolled) }
      List(unrolled)
    }

    def unifyUnsafe[A,B](orig: Exp[A], unrolled: Exp[B]): List[Exp[B]] = {
      foreach{p => registerUnsafe(orig, unrolled) }
      List(unrolled)
    }

    // Same symbol for all lanes
    def isCommon(e: Exp[_]): Boolean = contexts.map{p => f(e)}.forall{e2 => e2 == f(e)}
  }

  case class PartialUnroller(cchain: Exp[CounterChain], inds: Seq[Bound[Index]], isInnerLoop: Boolean) extends Unroller {
    // HACK: Don't unroll inner loops for CGRA generation
    val Ps: Seq[Int] = if (isInnerLoop && spatialConfig.enablePIR) inds.map{_ => 1}
                       else parFactorsOf(cchain).map{case Exact(c) => c.toInt }

    val fs: Seq[Boolean] = countersOf(cchain).map(isForever)

    val indices: Seq[Seq[Bound[Index]]]   = Ps.map{p => List.fill(p){ fresh[Index] }}
    val indexValids: Seq[Seq[Bound[Bit]]] = Ps.map{p => List.fill(p){ fresh[Bit] }}

    // Valid bits corresponding to each lane
    protected def createLaneValids(): Seq[Seq[Exp[Bit]]] = List.tabulate(P){p =>
      val laneIdxValids = indexValids.zip(parAddr(p)).map{case (vec,i) => vec(i)}
      laneIdxValids ++ validBits
    }

    // Substitution for each duplication "lane"
    val contexts = Array.tabulate(P){p =>
      val inds2 = indices.zip(parAddr(p)).map{case (vec, i) => vec(i) }
      Map.empty[Exp[Any],Exp[Any]] ++ inds.zip(inds2)
    }
  }

  case class FullUnroller(cchain: Exp[CounterChain], inds: Seq[Bound[Index]], isInnerLoop: Boolean) extends Unroller {
    val Ps: Seq[Int] = parFactorsOf(cchain).map{case Exact(c) => c.toInt }

    val indices: Seq[Seq[Const[Index]]] = countersOf(cchain).map{
      case Def(CounterNew(Exact(start),_,Exact(step),Exact(par))) =>
        List.tabulate(par.toInt){i => FixPt.int32s(BigDecimal(start + step*i)) }
    }
    val indexValids = indices.zip(countersOf(cchain)).map{
      case (is, Def(CounterNew(_,Exact(end),_,_))) =>
        is.map{case Exact(i) => Bit.const(i < end) }
    }

    protected def createLaneValids(): Seq[Seq[Exp[Bit]]] = List.tabulate(P){p =>
      val laneIdxValids = indexValids.zip(parAddr(p)).map{case (vec,i) => vec(i) }
      laneIdxValids ++ validBits
    }

    val contexts: Array[Map[Exp[Any], Exp[Any]]] = Array.tabulate(P){p =>
      val inds2 = indices.zip(parAddr(p)).map{case (vec, i) => vec(i) }
      Map.empty[Exp[Any],Exp[Any]] ++ inds.zip(inds2)
    }
  }

}


text:
#ifndef __TARGET_DARTUINOP0_MEMORY_LCD_H_
#define __TARGET_DARTUINOP0_MEMORY_LCD_H_

#include <stm32f7xx.h>

// Initialize the QSPI Flash device.
status_t memory_lcd_init(void);

#endif  // __TARGET_DARTUINOP0_MEMORY_LCD_H_


text:
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models

class Migration(DataMigration):

    def forwards(self, orm):
        orm.Station.objects.filter(type='similar_artists').update(type='similar')

    def backwards(self, orm):
        "Write your backwards methods here."

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'radio.favoritedstation': {
            'Meta': {'ordering': "('-date_added',)", 'object_name': 'FavoritedStation'},
            'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'station': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['radio.Station']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'radio.recentstation': {
            'Meta': {'ordering': "('-date_added',)", 'object_name': 'RecentStation'},
            'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'station': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['radio.Station']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'radio.station': {
            'Meta': {'ordering': "('type', 'name')", 'object_name': 'Station'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'plays_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
            'type': ('django.db.models.fields.CharField', [], {'max_length': '30', 'db_index': 'True'})
        },
        'radio.topartist': {
            'Meta': {'ordering': "('-popularity',)", 'object_name': 'TopArtist'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'popularity': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'})
        },
        'radio.toptag': {
            'Meta': {'ordering': "('name',)", 'object_name': 'TopTag'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'popularity': ('django.db.models.fields.IntegerField', [], {})
        }
    }

    complete_apps = ['radio']


text:
package org.cicatiello.interview_exercise.cart.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;

import org.cicatiello.interview_exercise.cart.CalculationService;
import org.cicatiello.interview_exercise.model.Cart;
import org.cicatiello.interview_exercise.model.CartEntry;
import org.cicatiello.interview_exercise.model.SalesTax;
import org.cicatiello.interview_exercise.session.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DefaultCalculationService implements CalculationService {

	private SessionService sessionService;

	@Override
	public void recalculate() {
		Cart sessionCart = sessionService.getSessionCart();
		resetCartValues(sessionCart);
		sessionCart.getEntries().forEach(entry -> recalculateEntry(entry));
		calculateTotals(sessionCart);
	}

	@Override
	public void recalculateEntry(CartEntry entry) {
		resetCartEntryValues(entry);
		BigDecimal subTotal = entry.getProduct().getBasePrice().multiply(BigDecimal.valueOf(entry.getQuantity()));
		entry.setSubTotal(subTotal);
		BigDecimal total = new BigDecimal(0).add(subTotal);
		entry.getProduct().getTaxRows().forEach(taxRow -> {
			BigDecimal calculateTaxValue = calculateTaxValue(subTotal, taxRow);
			entry.getTaxValues().add(calculateTaxValue);
		});
		for (BigDecimal taxValues : entry.getTaxValues()) {
			total = total.add(taxValues);
		}
		entry.setTotal(total);
	}

	@Override
	public void calculateTotals(Cart cart) {
		cart.getEntries().forEach(entry -> {
			cart.getSubTotal().add(entry.getSubTotal());
			entry.getTaxValues().forEach(taxValue -> {
				cart.setTotalTax(cart.getTotalTax().add(taxValue));
			});
			cart.setTotal(cart.getTotal().add(entry.getTotal()));
		});
		cart.getTotalTax().setScale(2, RoundingMode.HALF_EVEN);
		cart.getTotal().setScale(2, RoundingMode.HALF_EVEN);
	}

	private BigDecimal calculateTaxValue(BigDecimal subTotal, SalesTax tax) {
		BigDecimal taxValue = subTotal.multiply(tax.getTaxRate()).divide(new BigDecimal("100"));
		return roundTax(taxValue);
	}

	private BigDecimal roundTax(BigDecimal tax) {
		BigDecimal scale = new BigDecimal("0.05");
		return tax.divide(scale, 0, RoundingMode.UP).multiply(scale);
	}

	private void resetCartValues(Cart cart) {
		cart.setSubTotal(new BigDecimal(0));
		cart.setTotal(new BigDecimal(0));
		cart.setTotalTax(new BigDecimal(0));
	}

	private void resetCartEntryValues(CartEntry entry) {
		entry.setTotal(new BigDecimal(0));
		entry.setTaxValues(new ArrayList<>());
	}

	protected SessionService getSessionService() {
		return sessionService;
	}

	@Autowired
	public void setSessionService(SessionService sessionService) {
		this.sessionService = sessionService;
	}

}


text:
require 'test_helper'

module Gallery
  class Admin::AdminControllerTest < ActionController::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end


text:
#region License

// Copyright (c) 2013 Chandramouleswaran Ravichandran
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#endregion

using System.Collections.Generic;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Unity;
using Wide.Interfaces;
using Wide.Shell;
using Wide.Splash;

namespace WideMD
{
    internal class MDBootstrapper : WideBootstrapper
    {
        public MDBootstrapper(bool isMetro = true)
            : base(isMetro)
        {
        }

        protected override void InitializeModules()
        {
            //Register your splash view or else the default splash will load
            Container.RegisterType<ISplashView, AppSplash>();

            //Register your workspace here - if you have any
            Container.RegisterType<AbstractWorkspace, MDWorkspace>(new ContainerControlledLifetimeManager());

            // You can also override the logger service. Currently, NLog is used.
            // Since the config file is there in the output location, text files should be available in the Logs folder.

            //Initialize the original bootstrapper which will load modules from the probing path. Check app.config for probing path.
            base.InitializeModules();
        }

        protected override IModuleCatalog CreateModuleCatalog()
        {
            var catalog = new MultipleDirectoryModuleCatalog(new List<string>() {@".", @".\External", @".\Internal"});
            return catalog;
        }
    }
}


text:
<?php
    session_start();

    // Starta dokumentet.
    require ("../subrutiner/head.php");
    echo "

";

    // Släng in en logotyp på sidan.
    require ("../subrutiner/top_exlibris.php");

	// Kontrollera vilket steg som ska tas på sidan.
    $Steg = $_GET['Steg'];

	// Lista språk.
	if ($Steg == "Lista") {

		// Hämta språk från databasen sprak.
		$Listasprak = "SELECT * FROM sprak ORDER BY SPRAKLANG ASC";
		$result = mysqli_query($db,$Listasprak);

		if (!mysqli_num_rows($result)) $Output = "

Det finns inga registrerade språk.
";
		else {

			// Skapa en tabell över registrerade språk.
			echo "<button type='button' onClick='parent.location=\"administrera.php\"' class='Text'>Tillbaka</button>
";
			$Sprakrubrik = "Dessa språk är just nu registrerade:";
			echo "

$Sprakrubrik

";
			echo "
Titlar:	Språk:
";

			// Läs data om språk i databasen sprak.
			while ($row = mysqli_fetch_array($result)) {
                $SPRAKKORT = $row["SPRAKKORT"];
                $SPRAKLANG = $row["SPRAKLANG"];

				// Räkna efter hur många titlar som finns i aktuellt språk.
				$Raknatitlar    = "SELECT * FROM litteratur WHERE SPRAK = '$SPRAKKORT'";
				$Titlarresult	= mysqli_query($db,$Raknatitlar);
				$Antaltitlar	= mysqli_num_rows($Titlarresult);

                // Om det finns titlar i kategorin så skapa en länk.
                if ($Antaltitlar >= 1) $Antaltitlar = "$Antaltitlar";

				echo "
$Antaltitlar	$SPRAKLANG
";
			}
			echo "
";

			// Skriv ut Tillbaka-knappen.
			echo "
<button type='button' onClick='parent.location=\"administrera.php\"' class='Text'>Tillbaka</button>

";

            // Skriv ut en hjälpknapp.
            $HELPID = 14;
            require ("../subrutiner/help.php");

		}
	}
    // Avsluta dokumentet.
    echo "
";
?>