text:
package org.wso2.das.integration.tests.analytics.execution;

import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.analytics.spark.admin.stub.AnalyticsProcessorAdminServiceStub;
import org.wso2.das.integration.common.utils.DASIntegrationTest;

import java.io.File;

public class CarbonJDBCTestCase extends DASIntegrationTest {

    private static final Log log = LogFactory.getLog(CarbonJDBCTestCase.class);
    private static final String ANALYTICS_SERVICE_NAME = "AnalyticsProcessorAdminService";
    private static final String SCRIPT_RESOURCE_DIR = "analytics" + File.separator + "scripts";
    private AnalyticsProcessorAdminServiceStub analyticsStub;

    @BeforeClass(alwaysRun = true)
    protected void init() throws Exception {
        super.init();
        String apiConf = new File(this.getClass().getClassLoader().getResource("dasconfig" + File.separator + "api"
                + File.separator + "analytics-data-config.xml").toURI()).getAbsolutePath();
        initializeStub();
    }

    @Test(groups = "wso2.bam", description = "Create table test")
    public void initTableTest() throws Exception {
        String query = getResourceContent(CarbonJDBCTestCase.class, getAnalyticsScriptResourcePath("CarbonJDBCScript.ql"));
        AnalyticsProcessorAdminServiceStub.AnalyticsQueryResultDto[] resultArr = this.analyticsStub.execute(query);
        AnalyticsProcessorAdminServiceStub.AnalyticsQueryResultDto result = resultArr[resultArr.length - 1];
        AnalyticsProcessorAdminServiceStub.AnalyticsRowResultDto[] rows = result.getRowsResults();
        Assert.assertEquals(rows.length, 10);
    }

    @Test(groups = "wso2.bam", description = "Testing INSERT INTO", dependsOnMethods = "initTableTest")
    public void insertIntoTest() throws Exception {
        String state = "Oregon";
        String polarity = "11";
        String value = "1683.08";
        String query1 = "insert into table test1 select \"" + state + "\", " + polarity + ", " + value;
        this.analyticsStub.execute(query1);
        String query2 = "select * from test1";
        AnalyticsProcessorAdminServiceStub.AnalyticsQueryResultDto[] resultArr = this.analyticsStub.execute(query2);
        AnalyticsProcessorAdminServiceStub.AnalyticsQueryResultDto result = resultArr[resultArr.length - 1];
        AnalyticsProcessorAdminServiceStub.AnalyticsRowResultDto[] rows = result.getRowsResults();
        for (AnalyticsProcessorAdminServiceStub.AnalyticsRowResultDto row : rows) {
            if (state.equals(row.getColumnValues()[0])) {
                Assert.assertEquals(row.getColumnValues()[1], polarity);
                Assert.assertEquals(row.getColumnValues()[2], value);
            }
        }
    }

    @Test(groups = "wso2.bam", description = "Testing INSERT OVERWRITE", dependsOnMethods = "initTableTest")
    public void insertOverwriteTest() throws Exception {
        String state = "New Orleans";
        String polarity = "7";
        String value = "211.67";
        String query1 = "insert overwrite table test1 select \"" + state + "\", " + polarity + ", " + value + ";";
        this.analyticsStub.execute(query1);
        String query2 = "select * from test1";
        AnalyticsProcessorAdminServiceStub.AnalyticsQueryResultDto[] resultArr = this.analyticsStub.execute(query2);
        AnalyticsProcessorAdminServiceStub.AnalyticsQueryResultDto result = resultArr[resultArr.length - 1];
        AnalyticsProcessorAdminServiceStub.AnalyticsRowResultDto[] rows = result.getRowsResults();
        Assert.assertEquals(rows.length, 1);
        Assert.assertEquals(rows[0].getColumnValues()[0], state);
        Assert.assertEquals(rows[0].getColumnValues()[1], polarity);
        Assert.assertEquals(rows[0].getColumnValues()[2], value);
    }

    private void initializeStub() throws Exception {
        ConfigurationContext cCtx = ConfigurationContextFactory.
                createConfigurationContextFromFileSystem(null);
        analyticsStub = new AnalyticsProcessorAdminServiceStub(cCtx,
                backendURL + "/services/" + ANALYTICS_SERVICE_NAME);
        ServiceClient client = analyticsStub._getServiceClient();
        Options option = client.getOptions();
        option.setManageSession(true);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, getSessionCookie());
    }

    private String getAnalyticsScriptResourcePath(String scriptName) {
        return SCRIPT_RESOURCE_DIR + File.separator + scriptName;
    }

}


text:
title: "UART DV Plan"
---

## Goals
* **DV**
  * Verify all UART IP features by running dynamic simulations with a SV/UVM based testbench
  * Develop and run all tests based on the [testplan](#testplan) below towards closing code and functional coverage on the IP and all of its sub-modules
* **FPV**
  * Verify TileLink device protocol compliance with an SVA based testbench

## Current status
* [Design & verification stage]({{< relref "doc/project/hw_dashboard" >}})
  * [HW development stages]({{< relref "doc/project/hw_stages.md" >}})
* DV regression results dashboard (link TBD)

## Design features
For detailed information on UART design features, please see the [UART design specification]({{< relref "hw/ip/uart/doc" >}}).

## Testbench architecture
UART testbench has been constructed based on the
[CIP testbench architecture]({{< relref "hw/dv/sv/cip_lib/doc" >}}).

### Block diagram
![Block diagram](tb.svg)

### Top level testbench
Top level testbench is located at `hw/ip/uart/dv/tb/tb.sv`. It instantiates the UART DUT module `hw/ip/uart/rtl/uart.sv`.
In addition, it instantiates the following interfaces, connects them to the DUT and sets their handle into `uvm_config_db`:
* [Clock and reset interface]({{< relref "hw/dv/sv/common_ifs" >}})
* [TileLink host interface]({{< relref "hw/dv/sv/tl_agent/README.md" >}})
* UART IOs
* Interrupts ([`pins_if`]({{< relref "hw/dv/sv/common_ifs" >}}))

### Common DV utility components
The following utilities provide generic helper tasks and functions to perform activities that are common across the project:
* [common_ifs]({{< relref "hw/dv/sv/common_ifs" >}})
* [dv_utils_pkg]({{< relref "hw/dv/sv/dv_utils/README.md" >}})
* [csr_utils_pkg]({{< relref "hw/dv/sv/csr_utils/README.md" >}})

### Global types & methods
All common types and methods defined at the package level can be found in
`uart_env_pkg`. Some of them in use are:
```systemverilog
parameter uint UART_ADDR_MAP_SIZE = 64;
parameter uint UART_FIFO_DEPTH    = 32;
```

### TL_agent
UART instantiates (already handled in CIP base env) [tl_agent]({{< relref "hw/dv/sv/tl_agent/README.md" >}})
which provides the ability to drive and independently monitor random traffic via
TL host interface into UART device.

### UART agent
[UART agent]({{< relref "hw/dv/sv/uart_agent/README.md" >}}) is used to drive and monitor UART items, which also provides basic coverage on
data, parity, baud rate etc.
These baud rates are supported: 9600, 115200, 230400, 1Mbps(1048576), 2Mbps(2097152)

### UVM RAL Model
The UART RAL model is created with the `hw/dv/tools/gen_ral_pkg.py` wrapper script at the start of the simulation automatically and is placed in the build area, along with a corresponding `fusesoc` core file.
The wrapper script invokes the [regtool.py]({{< relref "util/reggen/README.md" >}}) script from within to generate the RAL model.

It can be created manually by running `make ral` command from the `dv` area.

### Stimulus strategy
#### Test sequences
All test sequences reside in `hw/ip/uart/dv/env/seq_lib`.
The `uart_base_vseq` virtual sequence is extended from `cip_base_vseq` and serves as a starting point.
All test sequences are extended from `uart_base_vseq`.
It provides commonly used handles, variables, functions and tasks that the test sequences can simple use / call.
Some of the most commonly used tasks / functions are as follows:
* uart_init:    Configure uart control and fifo related csr with random values
* send_tx_byte: Program one TX byte to enable DUT to send a TX byte to UART interface
* send_rx_byte: Drive a RX byte to DUT through UART interface

#### Functional coverage
To ensure high quality constrained random stimulus, it is necessary to develop a functional coverage model.
The following covergroups have been developed to prove that the test intent has been adequately met:
* common covergroup for interrupts `hw/dv/sv/cip_lib/cip_base_env_cov.sv`: Cover interrupt value, interrupt enable, intr_test, interrup pin
* uart_cg in uart_agent_cov `hw/dv/sv/uart_agent/uart_agent_cov.sv`:       Cover direction, uart data, en_parity, odd_parity and baud rate
* fifo_level_cg `hw/ip/uart/dv/env/uart_env_cov.sv`:                       Cover all fifo level with fifo reset for both TX and RX

### Self-checking strategy
#### Scoreboard
The `uart_scoreboard` is primarily used for end to end checking.
It creates the following analysis fifos to retrieve the data monitored by corresponding interface agents:
* tl_a_chan_fifo, tl_d_chan_fifo: These 2 fifos provides transaction items at the end of address channel and
  data channel respectively
* uart_tx_fifo, uart_rx_fifo:     These 2 fifos provides UART TX and RX item when its transfer completes

#### Assertions
* TLUL assertions: The `tb/uart_bind.sv` binds the `tlul_assert` [assertions]({{< relref "hw/ip/tlul/doc/TlulProtocolChecker.md" >}}) to the IP to ensure TileLink interface protocol compliance.
* Unknown checks on DUT outputs: The RTL has assertions to ensure all outputs are initialized to known values after coming out of reset.

## Building and running tests
We are using our in-house developed [regression tool]({{< relref "hw/dv/tools/README.md" >}}) for building and running our tests and regressions.
Please take a look at the link for detailed information on the usage, capabilities, features and known issues.
Here's how to run a basic sanity test:
```console
$ cd hw/ip/uart/dv
$ make TEST_NAME=uart_sanity
```

## Testplan
{{< testplan "hw/ip/uart/data/uart_testplan.hjson" >}}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"net/http"
)

func main() {
	err := http.ListenAndServe(":8080", http.HandlerFunc(helloHandler))
	if err != nil {
		panic(err)
	}
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello, world!"))
}


text:
SoulGemNotifier
===============

A simple addon for ESO that I hope will add a chat message when a Soul Gem is filled


text:
package org.duracloud.account.db.util.notification;

import org.duracloud.notification.Emailer;

/**
 * This interface defines the contract for retrieval of notification resources.
 *
 * @author Andrew Woods
 * Date: 3/17/11
 */
public interface NotificationMgr {

    /**
     * This method returns an emailer resource
     *
     * @return emailer
     */
    public Emailer getEmailer();

    /**
     * Retrieves the configuration of the NotificationMgr
     *
     * @return config
     */
    public NotificationMgrConfig getConfig();

}


text:
layout: page
show_meta: false
title: "Subcommittee Meeting Reports"
header:
   image_fullwidth: "wood_plank.jpg"
permalink: "/subcommittees/"
---

Minutes of the joint Data and Software Carpentry Subcommittees

### Bridge Subcommittee

- [05 August 2016](https://github.com/carpentries/bridge/blob/gh-pages/minutes/2016-08-05-minutes.md)
- [02 September 2016](https://github.com/carpentries/bridge/blob/master/minutes/2016-09-02-minutes.md)
- [21 September 2016](https://github.com/carpentries/bridge/blob/master/minutes/2016-09-21-minutes.md)
- [07 December 2016](https://github.com/carpentries/bridge/blob/master/minutes/2016-12-07-minutes.md)

### Mentoring Subcommittee

- [25 July 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-07-25.md)
- [11 July 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-07-11.md)
- [27 June 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-06-27.md)
- [14 June 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-06-14.md)
- [31 May 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-05-31.md)
- [02 May 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-05-02.md)
- [18 April 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-04-18.md)
- [04 April 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-04-04.md)
- [21 March 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-03-21.md)
- [07 March 2016](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2016-03-07.md)
- [21 December 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-12-21.md)
- [14 December 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-12-14.md)
- [30 November 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-11-30.md)
- [16 November 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-11-16.md)
- [02 November 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-11-02.md)
- [19 October 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-10-19.md)
- [05 October 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-10-05.md)
- [21 September 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-09-21.md)
- [04 September 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-09-04.md)
- [21 August 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-08-21.md)
- [07 August 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-08-07.md)
- [24 July 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-07-24.md)
- [10 July 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-07-10.md)
- [26 June 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-06-26.md)
- [12 June 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-06-12.md)
- [29 May 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-05-29.md)
- [15 May 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-05-15.md)
- [01 May 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-05-01.md)
- [17 April 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-04-17.md)
- [10 April 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-04-10.md)
- [17 March 2015](https://github.com/swcarpentry/board/blob/master/subcommittees/mentoring/minutes/minutes-2015-03-17.md)

### Trainer Subcommittee

- [17 February 2017](https://github.com/carpentries/trainers/blob/master/minutes/2017-02-17-minutes.md)
- [24 August 2016](https://github.com/carpentries/trainers/blob/master/minutes/2016-08-24.md)
- [10 August 2016](https://github.com/carpentries/trainers/blob/master/minutes/2016-08-10.md)


text:
package java.lang;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Simple iOS version of java.lang.ThreadLocal.
 *
 * @author Pankaj Kakkar
 */
public class ThreadLocal<T> {

  private static final String KEY_PREFIX = "jre_tls_key";

  private static final AtomicInteger nextId = new AtomicInteger(0);

  private final String key = KEY_PREFIX + nextId.getAndIncrement();

  public T get() {
    return getNative();
  }

  protected T initialValue() {
    return null;
  }

  public void remove() {
    removeNative();
  }

  public void set(T value) {
    setNative(value);
  }

  private native T getNative() /*-[
    NSMutableDictionary *dict = [[NSThread currentThread] threadDictionary];
    id value = [dict objectForKey:key_];
    if (value != nil) {
      // NSNull indicates that the value was explicitly set to null.
      return value == [NSNull null] ? nil : value;
    }

    id initialValue = [self initialValue];
    if (initialValue) {
      [dict setObject:initialValue forKey:key_];
    } // else return nil to show this key's value hasn't been set.
    return initialValue;
  ]-*/;

  private native void removeNative() /*-[
    [[[NSThread currentThread] threadDictionary] removeObjectForKey:key_];
  ]-*/;

  private native void setNative(T value) /*-[
    if (!value) {
      // Use NSNull singleton to show this value was explicitly set to null,
      // not just undefined.
      value = [NSNull null];
    }
    [[[NSThread currentThread] threadDictionary] setObject:value forKey:key_];
  ]-*/;
}


text:
typedef uint8_t byte;

using v8::internal::wasm::ErrorThrower;

namespace v8 {
namespace internal {

namespace {
i::MaybeHandle<i::FixedArray> CompileModule(
    i::Isolate* isolate, const byte* start, const byte* end,
    ErrorThrower* thrower,
    internal::wasm::ModuleOrigin origin = i::wasm::kWasmOrigin) {
  // Decode but avoid a redundant pass over function bodies for verification.
  // Verification will happen during compilation.
  i::Zone zone(isolate->allocator());
  internal::wasm::ModuleResult result = internal::wasm::DecodeWasmModule(
      isolate, &zone, start, end, false, origin);

  i::MaybeHandle<i::FixedArray> compiled_module;
  if (result.failed() && origin == internal::wasm::kAsmJsOrigin) {
    thrower->Error("Asm.js converted module failed to decode");
  } else if (result.failed()) {
    thrower->Failed("", result);
  } else {
    compiled_module = result.val->CompileFunctions(isolate);
  }

  if (result.val) delete result.val;
  return compiled_module;
}

}  // namespace

MaybeHandle<FixedArray> AsmJs::ConvertAsmToWasm(ParseInfo* info) {
  ErrorThrower thrower(info->isolate(), "Asm.js -> WebAssembly conversion");
  AsmTyper typer(info->isolate(), info->zone(), *(info->script()),
                 info->literal());
  typer.set_fixed_signature(true);
  if (i::FLAG_enable_simd_asmjs) {
    typer.set_allow_simd(true);
  }
  if (!typer.Validate()) {
    DCHECK(!info->isolate()->has_pending_exception());
    PrintF("Validation of asm.js module failed: %s", typer.error_message());
    return MaybeHandle<FixedArray>();
  }
  v8::internal::wasm::AsmWasmBuilder builder(info->isolate(), info->zone(),
                                             info->literal(), &typer);
  i::Handle<i::FixedArray> foreign_globals;
  auto module = builder.Run(&foreign_globals);
  size_t byte_length = module->end() - module->begin();
  Handle<JSArrayBuffer> buffer = info->isolate()->factory()->NewJSArrayBuffer();
  JSArrayBuffer::SetupAllocatingData(buffer, info->isolate(), byte_length,
                                     false, SharedFlag::kNotShared);
  uint8_t* module_bytes = reinterpret_cast<uint8_t*>(buffer->backing_store());
  memcpy(module_bytes, module->begin(), byte_length);
  Handle<FixedArray> result = info->isolate()->factory()->NewFixedArray(2);
  result->set(0, *buffer);
  result->set(1, *foreign_globals);
  return result;
}

MaybeHandle<Object> AsmJs::InstantiateAsmWasm(i::Isolate* isolate,
                                              Handle<FixedArray> wasm_data,
                                              Handle<JSArrayBuffer> memory,
                                              Handle<JSObject> foreign) {
  i::Handle<i::JSArrayBuffer> module_bytes(
      i::JSArrayBuffer::cast(wasm_data->get(0)));
  i::Handle<i::FixedArray> foreign_globals(
      i::FixedArray::cast(wasm_data->get(1)));

  ErrorThrower thrower(isolate, "Asm.js -> WebAssembly instantiation");

  const byte* module_start =
      reinterpret_cast<const byte*>(module_bytes->backing_store());
  size_t module_length =
      static_cast<size_t>(module_bytes->byte_length()->Number());
  const byte* module_end = module_start + module_length;
  i::MaybeHandle<i::FixedArray> compiled =
      CompileModule(isolate, module_start, module_end, &thrower,
                    internal::wasm::kAsmJsOrigin);
  if (compiled.is_null()) {
    return MaybeHandle<Object>();
  }
  i::MaybeHandle<i::JSObject> maybe_module_object =
      i::wasm::WasmModule::Instantiate(isolate, compiled.ToHandleChecked(),
                                       foreign, memory);
  if (maybe_module_object.is_null()) {
    return MaybeHandle<Object>();
  }

  i::Handle<i::Name> name(isolate->factory()->InternalizeOneByteString(
      STATIC_CHAR_VECTOR("__foreign_init__")));

  i::Handle<i::Object> module_object = maybe_module_object.ToHandleChecked();
  i::MaybeHandle<i::Object> maybe_init =
      i::Object::GetProperty(module_object, name);
  DCHECK(!maybe_init.is_null());

  i::Handle<i::Object> init = maybe_init.ToHandleChecked();
  i::Handle<i::Object> undefined(isolate->heap()->undefined_value(), isolate);
  i::Handle<i::Object>* foreign_args_array =
      new i::Handle<i::Object>[foreign_globals->length()];
  for (int j = 0; j < foreign_globals->length(); j++) {
    if (!foreign.is_null()) {
      i::MaybeHandle<i::Name> name = i::Object::ToName(
          isolate, i::Handle<i::Object>(foreign_globals->get(j), isolate));
      if (!name.is_null()) {
        i::MaybeHandle<i::Object> val =
            i::Object::GetProperty(foreign, name.ToHandleChecked());
        if (!val.is_null()) {
          foreign_args_array[j] = val.ToHandleChecked();
          continue;
        }
      }
    }
    foreign_args_array[j] = undefined;
  }
  i::MaybeHandle<i::Object> retval = i::Execution::Call(
      isolate, init, undefined, foreign_globals->length(), foreign_args_array);
  delete[] foreign_args_array;

  if (retval.is_null()) {
    thrower.Error(
        "WASM.instantiateModuleFromAsm(): foreign init function failed");
    return MaybeHandle<Object>();
  }
  return maybe_module_object;
}

}  // namespace internal
}  // namespace v8


text:
//
//  hospitalbill.hpp
//

#ifndef hospitalbill_hpp
#define hospitalbill_hpp

#include "person.hpp"
#include "doctor.hpp"
#include "date.hpp"
#include "patient.hpp"

class HospitalBill
{
private:

    Patient* mPtrPatient;
    int monthCheck;

public:
    HospitalBill();
    ~HospitalBill();
    string askFirst();
    string askLast();
    string askSpecial();
    int askYear();
    int askMonth();
    int askDay();

    int calculateAge(Date* current, Date* birth);
    void print();
};

#endif /* hospitalbill_hpp */


text:
'use strict';

var $ = require('jquery');
var branches = global.branches || [];
var allBranches = global.allBranches || [];

function BranchesController($scope) {
  $scope.branchName = '';
  $scope.branches = branches;
  $scope.allBranches = allBranches;

  $scope.remove = function (item) {
    var actuallyDelete = confirm(`Are you sure you want to remove ${item.name}?`);
    if (actuallyDelete) {
      item.loading = true;
      $scope.clearMessage();
      $.ajax({
        url: `/${$scope.project.name}/branches/`,
        type: 'DELETE',
        data: {name: item.name},
        success: function () {
          remove($scope.branches, item);
          $scope.success(`${item.name} is no longer a configured branch.`, true);
        },
        error: function (xhr, ts, e) {
          item.loading = false;
          if (xhr && xhr.responseText) {
            var data = $.parseJSON(xhr.responseText);
            $scope.error(`Error deleting branch: ${data.errors[0]}`, true);
          } else {
            $scope.error(`Error deleting branch: ${e}`, true);
          }
        }
      });
    }
  };

  $scope.add = function () {
    var data = {name: $scope.branchName};

    $.ajax({
      url: `/${$scope.project.name}/branches/`,
      type: 'POST',
      data: data,
      dataType: 'json',
      success: function (res) {
        $scope.branchName = '';
        if (res.created) {
          $scope.branches.push(res.branch);
        }
        $scope.success(res.message, true, !res.created);
      },
      error: function (xhr, ts, e) {
        if (xhr && xhr.responseText) {
          var data = $.parseJSON(xhr.responseText);
          $scope.error(`Error adding branch: ${data.errors[0]}`, true);
        } else {
          $scope.error(`Error adding branch: ${e}`, true);
        }
      }
    });
  };

  $scope.changeBranchOrder = function (list) {
    $scope.branches = list;
    $.ajax({
      url: `/${$scope.project.name}/branches/`,
      type: 'PUT',
      data: JSON.stringify({branches: list}),
      contentType: 'application/json',
      dataType: 'json',
      success: function (res) {
        $scope.success(res.message, true, false);
      },
      error: function (xhr, ts, e) {
        if (xhr && xhr.responseText) {
          var data = $.parseJSON(xhr.responseText);
          $scope.error(`Error changing order of branch: ${data.errors[0]}`, true);
        } else {
          $scope.error(`Error changing order of branch: ${e}`, true);
        }
      }
    });
  };

  $scope.clone = function (item) {
    var cloneName = prompt('Enter name of the clone', item.name);

    if (!cloneName) {
      return;
    }

    var data = {name: item.name, cloneName: cloneName};

    $.ajax({
      url: `/${$scope.project.name}/branches/`,
      type: 'POST',
      data: data,
      dataType: 'json',
      success: function (res) {
        $scope.branchName = '';
        if (res.created) {
          $scope.branches.push(res.branch);
        }
        $scope.success(res.message, true, !res.created);
      },
      error: function (xhr, ts, e) {
        if (xhr && xhr.responseText) {
          var data = $.parseJSON(xhr.responseText);
          $scope.error(`Error cloning branch: ${data.errors[0]}`, true);
        } else {
          $scope.error(`Error cloning branch: ${e}`, true);
        }
      }
    });
  };
}

function remove(ar, item) {
  ar.splice(ar.indexOf(item), 1);
}

module.exports = BranchesController;


text:
package org.ripple.bouncycastle.asn1.ocsp;

import org.ripple.bouncycastle.asn1.ASN1Choice;
import org.ripple.bouncycastle.asn1.ASN1Encodable;
import org.ripple.bouncycastle.asn1.ASN1Object;
import org.ripple.bouncycastle.asn1.ASN1OctetString;
import org.ripple.bouncycastle.asn1.ASN1Primitive;
import org.ripple.bouncycastle.asn1.ASN1TaggedObject;
import org.ripple.bouncycastle.asn1.DEROctetString;
import org.ripple.bouncycastle.asn1.DERTaggedObject;
import org.ripple.bouncycastle.asn1.x500.X500Name;

public class ResponderID
    extends ASN1Object
    implements ASN1Choice
{
    private ASN1Encodable    value;

    public ResponderID(
        ASN1OctetString    value)
    {
        this.value = value;
    }

    public ResponderID(
        X500Name value)
    {
        this.value = value;
    }

    public static ResponderID getInstance(
        Object  obj)
    {
        if (obj instanceof ResponderID)
        {
            return (ResponderID)obj;
        }
        else if (obj instanceof DEROctetString)
        {
            return new ResponderID((DEROctetString)obj);
        }
        else if (obj instanceof ASN1TaggedObject)
        {
            ASN1TaggedObject    o = (ASN1TaggedObject)obj;

            if (o.getTagNo() == 1)
            {
                return new ResponderID(X500Name.getInstance(o, true));
            }
            else
            {
                return new ResponderID(ASN1OctetString.getInstance(o, true));
            }
        }

        return new ResponderID(X500Name.getInstance(obj));
    }

    public static ResponderID getInstance(
        ASN1TaggedObject obj,
        boolean          explicit)
    {
        return getInstance(obj.getObject()); // must be explicitly tagged
    }

    public byte[] getKeyHash()
    {
        if (this.value instanceof ASN1OctetString)
        {
            ASN1OctetString octetString = (ASN1OctetString)this.value;
            return octetString.getOctets();
        }

        return null;
    }

    public X500Name getName()
    {
        if (this.value instanceof ASN1OctetString)
        {
            return null;
        }

        return X500Name.getInstance(value);
    }

    /**
     * Produce an object suitable for an ASN1OutputStream.
     * <pre>
     * ResponderID ::= CHOICE {
     *      byName          [1] Name,
     *      byKey           [2] KeyHash }
     * </pre>
     */
    public ASN1Primitive toASN1Primitive()
    {
        if (value instanceof ASN1OctetString)
        {
            return new DERTaggedObject(true, 2, value);
        }

        return new DERTaggedObject(true, 1, value);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using AutoRest.Core.Model;
using AutoRest.Core.Properties;
using AutoRest.Core.Utilities;
using AutoRest.Core.Utilities.Collections;
using AutoRest.Core.Validation;
using static AutoRest.Core.Utilities.DependencyInjection;

namespace AutoRest.Core
{
    public class CodeNamer
    {
        private static readonly IDictionary<char, string> basicLaticCharacters = new Dictionary<char, string>
        {
            [(char) 32] = "Space",
            [(char) 33] = "ExclamationMark",
            [(char) 34] = "QuotationMark",
            [(char) 35] = "NumberSign",
            [(char) 36] = "DollarSign",
            [(char) 37] = "PercentSign",
            [(char) 38] = "Ampersand",
            [(char) 39] = "Apostrophe",
            [(char) 40] = "LeftParenthesis",
            [(char) 41] = "RightParenthesis",
            [(char) 42] = "Asterisk",
            [(char) 43] = "PlusSign",
            [(char) 44] = "Comma",
            [(char) 45] = "HyphenMinus",
            [(char) 46] = "FullStop",
            [(char) 47] = "Slash",
            [(char) 48] = "Zero",
            [(char) 49] = "One",
            [(char) 50] = "Two",
            [(char) 51] = "Three",
            [(char) 52] = "Four",
            [(char) 53] = "Five",
            [(char) 54] = "Six",
            [(char) 55] = "Seven",
            [(char) 56] = "Eight",
            [(char) 57] = "Nine",
            [(char) 58] = "Colon",
            [(char) 59] = "Semicolon",
            [(char) 60] = "LessThanSign",
            [(char) 61] = "EqualSign",
            [(char) 62] = "GreaterThanSign",
            [(char) 63] = "QuestionMark",
            [(char) 64] = "AtSign",
            [(char) 91] = "LeftSquareBracket",
            [(char) 92] = "Backslash",
            [(char) 93] = "RightSquareBracket",
            [(char) 94] = "CircumflexAccent",
            [(char) 96] = "GraveAccent",
            [(char) 123] = "LeftCurlyBracket",
            [(char) 124] = "VerticalBar",
            [(char) 125] = "RightCurlyBracket",
            [(char) 126] = "Tilde"
        };

        public CodeNamer()
        {
        }

        /// <summary>
        ///     Gets the current code namer instance (using the active context).
        ///     A subclass should set the singleton on creation of their context.
        /// </summary>
        public static CodeNamer Instance
            =>
            Singleton<CodeNamer>.HasInstance
                ? Singleton<CodeNamer>.Instance
                : (Singleton<CodeNamer>.Instance = new CodeNamer());

        /// <summary>
        ///     Gets collection of reserved words.
        /// </summary>
        public HashSet<string> ReservedWords { get; } = new HashSet<string>();

        /// <summary>
        ///     Formats segments of a string split by underscores or hyphens into "Camel" case strings.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string CamelCase(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }

            if (name[0] == '_')
                // Preserve leading underscores.
            {
                return '_' + CamelCase(name.Substring(1));
            }

            return
                name.Split('_', '-', ' ')
                    .Where(s => !string.IsNullOrEmpty(s))
                    .Select((s, i) => FormatCase(s, i == 0)) // Pass true/toLower for just the first element.
                    .DefaultIfEmpty("")
                    .Aggregate(string.Concat);
        }

        /// <summary>
        ///     Formats segments of a string split by underscores or hyphens into "Pascal" case.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string PascalCase(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }

            if (name[0] == '_')
                // Preserve leading underscores and treat them like
                // uppercase characters by calling 'CamelCase()' on the rest.
            {
                return '_' + CamelCase(name.Substring(1));
            }

            return
                name.Split('_', '-', ' ')
                    .Where(s => !string.IsNullOrEmpty(s))
                    .Select(s => FormatCase(s, false))
                    .DefaultIfEmpty("")
                    .Aggregate(string.Concat);
        }

        /// <summary>
        ///     Wraps value in quotes and escapes quotes inside.
        /// </summary>
        /// <param name="value">String to quote</param>
        /// <param name="quoteChar">Quote character</param>
        /// <param name="escapeChar">Escape character</param>
        /// <exception cref="System.ArgumentNullException">Throw when either quoteChar or escapeChar are null.</exception>
        [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
        public virtual string QuoteValue(string value, string quoteChar = "\"", string escapeChar = "\\")
        {
            if (quoteChar == null)
            {
                throw new ArgumentNullException(nameof(quoteChar));
            }
            if (escapeChar == null)
            {
                throw new ArgumentNullException(nameof(escapeChar));
            }
            if (string.IsNullOrWhiteSpace(value))
            {
                value = string.Empty;
            }
            return quoteChar + value.Replace(quoteChar, escapeChar + quoteChar) + quoteChar;
        }

        /// <summary>
        ///     Returns a quoted string for the given language if applicable.
        /// </summary>
        /// <param name="defaultValue">Value to quote.</param>
        /// <param name="type">Data type.</param>
        public virtual string EscapeDefaultValue(string defaultValue, IModelType type)
        {
            return defaultValue;
        }

        /// <summary>
        ///     Formats a string for naming members of an enum using Pascal case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetEnumMemberName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return PascalCase(RemoveInvalidCharacters(name));
        }

        /// <summary>
        ///     Formats a string for naming fields using a prefix '_' and VariableName Camel case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetFieldName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return '_' + GetVariableName(name);
        }

        /// <summary>
        ///     Formats a string for naming interfaces using a prefix 'I' and Pascal case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetInterfaceName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return $"I{PascalCase(RemoveInvalidCharacters(name))}";
        }

        /// <summary>
        ///     Formats a string for naming a method using Pascal case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetMethodName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Operation")));
        }

        /// <summary>
        ///     Formats a string for identifying a namespace using Pascal case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetNamespaceName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return PascalCase(RemoveInvalidCharactersNamespace(name));
        }

        /// <summary>
        ///     Formats a string for naming method parameters using GetVariableName Camel case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetParameterName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return GetVariableName(GetEscapedReservedName(name, "Parameter"));
        }

        /// <summary>
        ///     Formats a string for naming properties using Pascal case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetPropertyName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Property")));
        }

        /// <summary>
        ///     Formats a string for naming a Type or Object using Pascal case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetTypeName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
        }

        /// <summary>
        ///     Formats a string for naming a Method Group using Pascal case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetMethodGroupName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
        }

        public virtual string GetClientName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
        }

        /// <summary>
        ///     Formats a string for naming a local variable using Camel case by default.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>The formatted string.</returns>
        public virtual string GetVariableName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return name;
            }
            return CamelCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Variable")));
        }

        /// <summary>
        ///     Returns language specific type reference name.
        /// </summary>
        /// <param name="typePair"></param>
        /// <returns></returns>
        public virtual Response NormalizeTypeReference(Response typePair)
        {
            return new Response(NormalizeTypeReference(typePair.Body),
                NormalizeTypeReference(typePair.Headers));
        }

        /// <summary>
        ///     Returns language specific type reference name.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public virtual IModelType NormalizeTypeReference(IModelType type)
        {
            return type;
        }

        /// <summary>
        ///     Returns language specific type declaration name.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public virtual IModelType NormalizeTypeDeclaration(IModelType type)
        {
            return type;
        }

        /// <summary>
        ///     Formats a string as upper or lower case. Two-letter inputs that are all upper case are both lowered.
        ///     Example: ID = > id,  Ex => ex
        /// </summary>
        /// <param name="name"></param>
        /// <param name="toLower"></param>
        /// <returns>The formatted string.</returns>
        private string FormatCase(string name, bool toLower)
        {
            if (!string.IsNullOrEmpty(name))
            {
                if ((name.Length < 2) || ((name.Length == 2) && char.IsUpper(name[0]) && char.IsUpper(name[1])))
                {
                    name = toLower ? name.ToLowerInvariant() : name.ToUpperInvariant();
                }
                else
                {
                    name =
                    (toLower
                        ? char.ToLowerInvariant(name[0])
                        : char.ToUpperInvariant(name[0])) + name.Substring(1, name.Length - 1);
                }
            }
            return name;
        }

        /// <summary>
        ///     Removes invalid characters from the name. Everything but alpha-numeral, underscore,
        ///     and dash.
        /// </summary>
        /// <param name="name">String to parse.</param>
        /// <returns>Name with invalid characters removed.</returns>
        public virtual string RemoveInvalidCharacters(string name)
        {
            return GetValidName(name, '_', '-');
        }

        /// <summary>
        ///     Removes invalid characters from the namespace. Everything but alpha-numeral, underscore,
        ///     period, and dash.
        /// </summary>
        /// <param name="name">String to parse.</param>
        /// <returns>Namespace with invalid characters removed.</returns>
        protected virtual string RemoveInvalidCharactersNamespace(string name)
        {
            return GetValidName(name, '_', '-', '.');
        }

        /// <summary>
        ///     Gets valid name for the identifier.
        /// </summary>
        /// <param name="name">String to parse.</param>
        /// <param name="allowedCharacters">Allowed characters.</param>
        /// <returns>Name with invalid characters removed.</returns>
        public virtual string GetValidName(string name, params char[] allowedCharacters)
        {
            var correctName = RemoveInvalidCharacters(name, allowedCharacters);

            // here we have only letters and digits or an empty string
            if (string.IsNullOrEmpty(correctName) ||
                basicLaticCharacters.ContainsKey(correctName[0]))
            {
                var sb = new StringBuilder();
                foreach (var symbol in name)
                {
                    if (basicLaticCharacters.ContainsKey(symbol))
                    {
                        sb.Append(basicLaticCharacters[symbol]);
                    }
                    else
                    {
                        sb.Append(symbol);
                    }
                }
                correctName = RemoveInvalidCharacters(sb.ToString(), allowedCharacters);
            }

            // if it is still empty string, throw
            if (correctName.IsNullOrEmpty())
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName,
                    name));
            }

            return correctName;
        }

        /// <summary>
        ///     Removes invalid characters from the name.
        /// </summary>
        /// <param name="name">String to parse.</param>
        /// <param name="allowerCharacters">Allowed characters.</param>
        /// <returns>Name with invalid characters removed.</returns>
        private string RemoveInvalidCharacters(string name, params char[] allowerCharacters)
        {
            return new string(name.Replace("[]", "Sequence")
                .Where(c => char.IsLetterOrDigit(c) || allowerCharacters.Contains(c))
                .ToArray());
        }

        /// <summary>
        ///     If the provided name is a reserved word in a programming language then the method converts the
        ///     name by appending the provided appendValue
        /// </summary>
        /// <param name="name">Name.</param>
        /// <param name="appendValue">String to append.</param>
        /// <returns>The transformed reserved name</returns>
        protected virtual string GetEscapedReservedName(string name, string appendValue)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (appendValue == null)
            {
                throw new ArgumentNullException("appendValue");
            }

            if (ReservedWords.Contains(name, StringComparer.OrdinalIgnoreCase))
            {
                name += appendValue;
            }

            return name;
        }

        public virtual string IsNameLegal(string desiredName, IIdentifier whoIsAsking)
        {
            if (string.IsNullOrWhiteSpace(desiredName))
            {
                // should have never got to this point with an blank name.
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName,
                    desiredName));
            }

            if (ReservedWords.Contains(desiredName))
            {
                return desiredName;
            }

            return null; // null == no conflict
        }

        public virtual IIdentifier IsNameAvailable(string desiredName, HashSet<IIdentifier> reservedNames)
        {
            // null == name is available
            return
                reservedNames.FirstOrDefault(
                    each => each.MyReservedNames.WhereNotNull().Any(name => name.Equals(desiredName)));
        }

        /// <summary>
        /// Returns true when the name comparison is a special case and should not
        /// be used to determine name conflicts.
        ///
        /// Override in subclasses so when the model is loaded into the language specific
        /// context, the behavior can be stricter than here.
        ///  </summary>
        /// <param name="whoIsAsking">the identifier that is checking to see if there is a conflict</param>
        /// <param name="reservedName">the identifier that would normally be reserved.</param>
        /// <returns></returns>
        public virtual bool IsSpecialCase(IIdentifier whoIsAsking, IIdentifier reservedName)
        {
            // special case: properties can actually have the same name as a composite type
            if (whoIsAsking is Property && reservedName is CompositeType)
            {
                return true;
            }

            // special case: parameters can actually have the same name as a method
            if (whoIsAsking is Parameter && reservedName is Method)
            {
                return true;
            }

            return false;
        }

        public virtual string GetUnique(string desiredName, IIdentifier whoIsAsking,
            IEnumerable<IIdentifier> reservedNames, IEnumerable<IIdentifier> siblingNames,
            HashSet<string> locallyReservedNames = null)
        {
            // can't disambiguate on an empty name.
            if (string.IsNullOrEmpty(desiredName))
            {
                return desiredName;
            }

#if refactoring_out
            // special case: properties can actually have the same name as a composite type
            // as long as that type is not the parent class of the property itself.
            if (whoIsAsking is Property)
            {
                reservedNames = reservedNames.Where(each => !(each is CompositeType));

                var parent = (whoIsAsking as IChild)?.Parent as IIdentifier;
                if (parent != null)
                {
                    reservedNames = reservedNames.ConcatSingleItem(parent);
                }
            }
#endif

            var names = new HashSet<IIdentifier>(reservedNames.Where(each => !IsSpecialCase(whoIsAsking, each)));

            // is this a legal name? -- add a Qualifier Suffix (ie, Method/Model/Property/etc)
            string conflict;
            while ((conflict = IsNameLegal(desiredName, whoIsAsking)) != null)
            {
                desiredName += whoIsAsking.Qualifier;
                // todo: gws: log the name change because it conflicted with a reserved word.
                // Singleton<Log>.Instance?.Add(new Message {Text = $"todo:{conflict}"});

            }

            // does it conflict with a type name locally? (add a Qualifier Suffix)

            IIdentifier confl;
            while (null != (confl = IsNameAvailable(desiredName, names)))
            {
                desiredName += whoIsAsking.Qualifier;
                // todo: gws: log the name change because there was something else named that.
                // Singleton<Log>.Instance?.Add(new Message {Text = $"todo:{confl}"});
                // reason = string.Format(CultureInfo.InvariantCulture, Resources.NamespaceConflictReasonMessage,desiredName, ...?
            }

            // special case (corolary): a compositeType  can actually have the same name as a property
            if (whoIsAsking is CompositeType)
            {
                siblingNames= siblingNames.Where(each => !(each is Property));
            }
            if (whoIsAsking is Property)
            {
                siblingNames = siblingNames.Where(each => !(each is CompositeType));
            }

            // does it have a sibling collision?
            names = new HashSet<IIdentifier>(siblingNames);
            var baseName = desiredName;
            var suffix = 0;
            while (IsNameAvailable(desiredName, names) != null)
            {
                desiredName = baseName + ++suffix;
            }

            // is there a collision with any local name we care about?
            while (true == locallyReservedNames?.Contains(desiredName))
            {
                desiredName = baseName + ++suffix;
            }

            return desiredName;
        }
    }
}


text:
<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/autoload.php';
require_once 'helper.php';

class Model_DivisionFieldTest extends Model_TestHelpers
{
    /**
     * Prepare to run test
     */
    protected function setUp()
    {
        $this->primeDatabase();
    }

    /**
     * Default Construction
     */
    public function testStaticMethods()
    {
        $divisionField = Model_Fields_DivisionField::Create($this->m_division->id, $this->m_facility->id, $this->m_field->id);
        $divisionFieldId = $divisionField->id;
        $this->assertEquals($divisionField->divisionId, $this->m_division->id);
        $this->assertEquals($divisionField->facilityId, $this->m_facility->id);
        $this->assertEquals($divisionField->fieldId, $this->m_field->id);

        $divisionField = Model_Fields_DivisionField::LookupByDivisionField($this->m_division->id, $this->m_facility->id, $this->m_field->id);
        $this->assertEquals($divisionField->divisionId, $this->m_division->id);
        $this->assertEquals($divisionField->facilityId, $this->m_facility->id);
        $this->assertEquals($divisionField->fieldId, $this->m_field->id);
        $this->assertEquals($divisionField->id, $divisionFieldId);

        $divisionField = Model_Fields_DivisionField::LookupById($divisionFieldId);
        $this->assertEquals($divisionField->divisionId, $this->m_division->id);
        $this->assertEquals($divisionField->facilityId, $this->m_facility->id);
        $this->assertEquals($divisionField->fieldId, $this->m_field->id);
        $this->assertEquals($divisionField->id, $divisionFieldId);

        $divisionFields = Model_Fields_DivisionField::GetFacilityFields($this->m_division->id, $this->m_facility->id);
        $this->assertEquals(count($divisionFields), 1);
        $this->assertEquals($this->m_field->name, $divisionFields[0]->name);

        $divisions = Model_Fields_DivisionField::GetFacilityFieldDivisions($this->m_facility->id, $this->m_field->id);
        $this->assertEquals(count($divisions), 1);
        $this->assertEquals($this->m_division->name, $divisions[0]->name);
    }
}


text:
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

var assert = require("chai").assert,
    assign = require("object-assign"),
    autoconfig = require("../../../lib/config/autoconfig"),
    sourceCodeUtil = require("../../../lib/util/source-code-util"),
    defaultOptions = require("../../../conf/cli-options");

defaultOptions = assign({}, defaultOptions, {cwd: process.cwd()});

//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------

var SOURCE_CODE_FIXTURE_FILENAME = "./tests/fixtures/autoconfig/source.js";
var SEVERITY = 2;

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

var rulesConfig = {
    semi: [ SEVERITY, [SEVERITY, "always"], [SEVERITY, "never"] ],
    "semi-spacing": [ SEVERITY,
        [ SEVERITY, { before: true, after: true } ],
        [ SEVERITY, { before: true, after: false } ],
        [ SEVERITY, { before: false, after: true } ],
        [ SEVERITY, { before: false, after: false } ]
    ],
    quotes: [ SEVERITY,
        [ SEVERITY, "single" ],
        [ SEVERITY, "double" ],
        [ SEVERITY, "backtick" ],
        [ SEVERITY, "single", "avoid-escape" ],
        [ SEVERITY, "double", "avoid-escape" ],
        [ SEVERITY, "backtick", "avoid-escape" ] ]
};

var errorRulesConfig = {
    "no-unused-vars": [ SEVERITY ],
    "semi-spacing": [ SEVERITY,
        [ SEVERITY, { before: true, after: true } ],
        [ SEVERITY, { before: true, after: false } ],
        [ SEVERITY, { before: false, after: true } ],
        [ SEVERITY, { before: false, after: false } ]
    ]
};

describe("autoconfig", function() {

    describe("Registry", function() {

        it("should set up a registry for rules in a provided rulesConfig", function() {
            var expectedRules = Object.keys(rulesConfig);
            var registry = new autoconfig.Registry(rulesConfig);
            assert.equal(Object.keys(registry.rules).length, 3);
            assert.sameMembers(Object.keys(registry.rules), expectedRules);
            assert.isArray(registry.rules.semi);
            assert.isArray(registry.rules["semi-spacing"]);
            assert.isArray(registry.rules.quotes);
            assert.lengthOf(registry.rules.semi, 3);
            assert.lengthOf(registry.rules["semi-spacing"], 5);
            assert.lengthOf(registry.rules.quotes, 7);
        });

        it("should not have any rules if constructed without a config argument", function() {
            var registry = new autoconfig.Registry();
            assert.isObject(registry.rules);
            assert.lengthOf(Object.keys(registry.rules), 0);
        });

        it("should create registryItems for each rule with the proper keys", function() {
            var registry = new autoconfig.Registry(rulesConfig);
            assert.isObject(registry.rules.semi[0]);
            assert.isObject(registry.rules["semi-spacing"][0]);
            assert.isObject(registry.rules.quotes[0]);
            assert.property(registry.rules.semi[0], "config");
            assert.property(registry.rules.semi[0], "specificity");
            assert.property(registry.rules.semi[0], "errorCount");
        });

        it("should populate the config property correctly", function() {
            var registry = new autoconfig.Registry(rulesConfig);
            assert.equal(registry.rules.quotes[0].config, SEVERITY);
            assert.deepEqual(registry.rules.quotes[1].config, [SEVERITY, "single"]);
            assert.deepEqual(registry.rules.quotes[2].config, [SEVERITY, "double"]);
            assert.deepEqual(registry.rules.quotes[3].config, [SEVERITY, "backtick"]);
            assert.deepEqual(registry.rules.quotes[4].config, [SEVERITY, "single", "avoid-escape"]);
            assert.deepEqual(registry.rules.quotes[5].config, [SEVERITY, "double", "avoid-escape"]);
            assert.deepEqual(registry.rules.quotes[6].config, [SEVERITY, "backtick", "avoid-escape"]);
        });

        it("should assign the correct specificity", function() {
            var registry = new autoconfig.Registry(rulesConfig);
            assert.equal(registry.rules.quotes[0].specificity, 1);
            assert.equal(registry.rules.quotes[1].specificity, 2);
            assert.equal(registry.rules.quotes[6].specificity, 3);
        });

        it("should initially leave the errorCount as undefined", function() {
            var registry = new autoconfig.Registry(rulesConfig);
            assert.isUndefined(registry.rules.quotes[0].errorCount);
            assert.isUndefined(registry.rules.quotes[1].errorCount);
            assert.isUndefined(registry.rules.quotes[6].errorCount);
        });

        describe("populateFromCoreRules()", function() {

            it("should add core rules to registry", function() {
                var registry = new autoconfig.Registry();
                registry.populateFromCoreRules();
                var finalRuleCount = Object.keys(registry.rules).length;
                assert(finalRuleCount > 0);
                assert.include(Object.keys(registry.rules), "eqeqeq");
            });

            it("should not add duplicate rules", function() {
                var registry = new autoconfig.Registry(rulesConfig);
                registry.populateFromCoreRules();
                var semiCount = Object.keys(registry.rules).filter(function(ruleId) {
                    return ruleId === "semi";
                }).length;
                assert.equal(semiCount, 1);
            });
        });

        describe("buildRuleSets()", function() {
            var ruleSets;

            beforeEach(function() {
                var registry = new autoconfig.Registry(rulesConfig);
                ruleSets = registry.buildRuleSets();
            });

            it("should create an array of rule configuration sets", function() {
                assert.isArray(ruleSets);
            });

            it("should include configs for each rule (at least for the first set)", function() {
                assert.sameMembers(Object.keys(ruleSets[0]), ["semi", "semi-spacing", "quotes"]);
            });

            it("should create the first set from default rule configs (severity only)", function() {
                assert.deepEqual(ruleSets[0], { semi: SEVERITY, "semi-spacing": SEVERITY, quotes: SEVERITY });
            });

            it("should create as many ruleSets as the highest number of configs in a rule", function() {
                // `quotes` has 7 possible configurations
                assert.lengthOf(ruleSets, 7);
            });
        });

        describe("lintSourceCode()", function() {
            var registry;

            beforeEach(function() {
                var config = {ignore: false};
                var sourceCode = sourceCodeUtil.getSourceCodeOfFiles(SOURCE_CODE_FIXTURE_FILENAME, config);
                registry = new autoconfig.Registry(rulesConfig);
                registry = registry.lintSourceCode(sourceCode, defaultOptions);
            });

            it("should populate the errorCount of all registryItems", function() {
                var expectedRules = ["semi", "semi-spacing", "quotes"];
                assert.sameMembers(Object.keys(registry.rules), expectedRules);
                expectedRules.forEach(function(ruleId) {
                    assert(registry.rules[ruleId].length > 0);
                    registry.rules[ruleId].forEach(function(conf) {
                        assert.isNumber(conf.errorCount);
                    });
                });
            });

            it("should correctly set the error count of configurations", function() {
                assert.equal(registry.rules.semi[0].config, SEVERITY);
                assert.equal(registry.rules.semi[0].errorCount, 0);
                assert.deepEqual(registry.rules.semi[2].config, [SEVERITY, "never"]);
                assert.equal(registry.rules.semi[2].errorCount, 3);
            });
        });

        describe("stripFailingConfigs()", function() {
            var registry;

            beforeEach(function() {
                var config = {ignore: false};
                var sourceCode = sourceCodeUtil.getSourceCodeOfFiles(SOURCE_CODE_FIXTURE_FILENAME, config);
                registry = new autoconfig.Registry(rulesConfig);
                registry = registry.lintSourceCode(sourceCode, defaultOptions);
                registry = registry.stripFailingConfigs();
            });

            it("should remove all registryItems with a non-zero errorCount", function() {
                assert.lengthOf(registry.rules.semi, 2);
                assert.lengthOf(registry.rules["semi-spacing"], 3);
                assert.lengthOf(registry.rules.quotes, 1);
                registry.rules.semi.forEach(function(registryItem) {
                    assert.equal(registryItem.errorCount, 0);
                });
                registry.rules["semi-spacing"].forEach(function(registryItem) {
                    assert.equal(registryItem.errorCount, 0);
                });
                registry.rules.quotes.forEach(function(registryItem) {
                    assert.equal(registryItem.errorCount, 0);
                });
            });
        });

        describe("getFailingRulesRegistry()", function() {
            var failingRegistry;

            beforeEach(function() {
                var config = {ignore: false};
                var sourceCode = sourceCodeUtil.getSourceCodeOfFiles(SOURCE_CODE_FIXTURE_FILENAME, config);
                var registry = new autoconfig.Registry(errorRulesConfig);
                registry = registry.lintSourceCode(sourceCode, defaultOptions);
                failingRegistry = registry.getFailingRulesRegistry();
            });

            it("should return a registry with no registryItems with an errorCount of zero", function() {
                var failingRules = Object.keys(failingRegistry.rules);
                assert.deepEqual(failingRules, ["no-unused-vars"]);
                assert.lengthOf(failingRegistry.rules["no-unused-vars"], 1);
                assert(failingRegistry.rules["no-unused-vars"][0].errorCount > 0);
            });
        });

        describe("createConfig()", function() {
            var createdConfig;

            beforeEach(function() {
                var config = {ignore: false};
                var sourceCode = sourceCodeUtil.getSourceCodeOfFiles(SOURCE_CODE_FIXTURE_FILENAME, config);
                var registry = new autoconfig.Registry(rulesConfig);
                registry = registry.lintSourceCode(sourceCode, defaultOptions);
                registry = registry.stripFailingConfigs();
                createdConfig = registry.createConfig();
            });

            it("should create a config with a rules property", function() {
                assert.property(createdConfig, "rules");
            });

            it("should add rules which have only one registryItem to the config", function() {
                var configuredRules = Object.keys(createdConfig.rules);
                assert.deepEqual(configuredRules, ["quotes"]);
            });

            it("should set the configuration of the rule to the registryItem's `config` value", function() {
                assert.deepEqual(createdConfig.rules.quotes, [ 2, "double", "avoid-escape" ]);
            });

            it("should not care how many errors the config has", function() {
                var config = {ignore: false};
                var sourceCode = sourceCodeUtil.getSourceCodeOfFiles(SOURCE_CODE_FIXTURE_FILENAME, config);
                var registry = new autoconfig.Registry(errorRulesConfig);
                registry = registry.lintSourceCode(sourceCode, defaultOptions);
                var failingRegistry = registry.getFailingRulesRegistry();
                createdConfig = failingRegistry.createConfig();
                var configuredRules = Object.keys(createdConfig.rules);
                assert.deepEqual(configuredRules, ["no-unused-vars"]);
            });
        });

        describe("filterBySpecificity()", function() {
            var registry;

            beforeEach(function() {
                registry = new autoconfig.Registry(rulesConfig);
            });

            it("should return a registry where all configs have a desired specificity", function() {
                var filteredRegistry1 = registry.filterBySpecificity(1);
                var filteredRegistry2 = registry.filterBySpecificity(2);
                var filteredRegistry3 = registry.filterBySpecificity(3);
                assert.lengthOf(filteredRegistry1.rules.semi, 1);
                assert.lengthOf(filteredRegistry1.rules["semi-spacing"], 1);
                assert.lengthOf(filteredRegistry1.rules.quotes, 1);
                assert.lengthOf(filteredRegistry2.rules.semi, 2);
                assert.lengthOf(filteredRegistry2.rules["semi-spacing"], 4);
                assert.lengthOf(filteredRegistry2.rules.quotes, 3);
                assert.lengthOf(filteredRegistry3.rules.quotes, 3);
            });
        });
    });
});


text:
/**
 * @file
 * Declares ignite::cache::query::SqlFieldsQuery class.
 */

#ifndef _IGNITE_CACHE_QUERY_QUERY_SQL_FIELDS
#define _IGNITE_CACHE_QUERY_QUERY_SQL_FIELDS

#include <stdint.h>
#include <string>
#include <vector>

#include "ignite/cache/query/query_argument.h"
#include "ignite/binary/binary_raw_writer.h"

namespace ignite
{
    namespace cache
    {
        namespace query
        {
            /**
             * Sql fields query.
             */
            class SqlFieldsQuery
            {
            public:
                /**
                 * Constructor.
                 *
                 * @param sql SQL string.
                 */
                SqlFieldsQuery(const std::string& sql) :
                    sql(sql),
                    pageSize(1024),
                    loc(false),
                    distributedJoins(false),
                    enforceJoinOrder(false),
                    args()
                {
                    // No-op.
                }

                /**
                 * Constructor.
                 *
                 * @param sql SQL string.
                 * @param loc Whether query should be executed locally.
                 */
                SqlFieldsQuery(const std::string& sql, bool loc) :
                    sql(sql),
                    pageSize(1024),
                    loc(false),
                    distributedJoins(false),
                    enforceJoinOrder(false),
                    args()
                {
                    // No-op.
                }

                /**
                 * Copy constructor.
                 *
                 * @param other Other instance.
                 */
                SqlFieldsQuery(const SqlFieldsQuery& other) :
                    sql(other.sql),
                    pageSize(other.pageSize),
                    loc(other.loc),
                    distributedJoins(other.distributedJoins),
                    enforceJoinOrder(other.enforceJoinOrder),
                    args()
                {
                    args.reserve(other.args.size());

                    typedef std::vector<QueryArgumentBase*>::const_iterator Iter;

                    for (Iter i = other.args.begin(); i != other.args.end(); ++i)
                        args.push_back((*i)->Copy());
                }

                /**
                 * Assignment operator.
                 *
                 * @param other Other instance.
                 */
                SqlFieldsQuery& operator=(const SqlFieldsQuery& other)
                {
                    if (this != &other)
                    {
                        SqlFieldsQuery tmp(other);

                        Swap(tmp);
                    }

                    return *this;
                }

                /**
                 * Destructor.
                 */
                ~SqlFieldsQuery()
                {
                    typedef std::vector<QueryArgumentBase*>::const_iterator Iter;

                    for (Iter it = args.begin(); it != args.end(); ++it)
                        delete *it;
                }

                /**
                 * Efficiently swaps contents with another SqlQuery instance.
                 *
                 * @param other Other instance.
                 */
                void Swap(SqlFieldsQuery& other)
                {
                    if (this != &other)
                    {
                        std::swap(sql, other.sql);
                        std::swap(pageSize, other.pageSize);
                        std::swap(loc, other.loc);
                        std::swap(distributedJoins, other.distributedJoins);
                        std::swap(enforceJoinOrder, other.enforceJoinOrder);
                        std::swap(args, other.args);
                    }
                }

                /**
                 * Get SQL string.
                 *
                 * @return SQL string.
                 */
                const std::string& GetSql() const
                {
                    return sql;
                }

                /**
                 * Set SQL string.
                 *
                 * @param sql SQL string.
                 */
                void SetSql(const std::string& sql)
                {
                    this->sql = sql;
                }

                /**
                 * Get page size.
                 *
                 * @return Page size.
                 */
                int32_t GetPageSize() const
                {
                    return pageSize;
                }

                /**
                 * Set page size.
                 *
                 * @param pageSize Page size.
                 */
                void SetPageSize(int32_t pageSize)
                {
                    this->pageSize = pageSize;
                }

                /**
                 * Get local flag.
                 *
                 * @return Local flag.
                 */
                bool IsLocal() const
                {
                    return loc;
                }

                /**
                 * Set local flag.
                 *
                 * @param loc Local flag.
                 */
                void SetLocal(bool loc)
                {
                    this->loc = loc;
                }

                /**
                 * Checks if join order of tables if enforced.
                 *
                 * @return Flag value.
                 */
                bool IsEnforceJoinOrder() const
                {
                    return enforceJoinOrder;
                }

                /**
                 * Sets flag to enforce join order of tables in the query.
                 * If set to true query optimizer will not reorder tables in
                 * join. By default is false.
                 *
                 * It is not recommended to enable this property unless you are
                 * sure that your indexes and the query itself are correct and
                 * tuned as much as possible but query optimizer still produces
                 * wrong join order.
                 *
                 * @param enforce Flag value.
                 */
                void SetEnforceJoinOrder(bool enforce)
                {
                    enforceJoinOrder = enforce;
                }

                /**
                 * Check if distributed joins are enabled for this query.
                 *
                 * @return True If distributed joind enabled.
                 */
                bool IsDistributedJoins() const
                {
                    return distributedJoins;
                }

                /**
                 * Specify if distributed joins are enabled for this query.
                 *
                 * When disabled, join results will only contain colocated data (joins work locally).
                 * When enabled, joins work as expected, no matter how the data is distributed.
                 *
                 * @param enabled Distributed joins enabled.
                 */
                void SetDistributedJoins(bool enabled)
                {
                    distributedJoins = enabled;
                }

                /**
                 * Add argument.
                 *
                 * Template argument type should be copy-constructable and
                 * assignable. Also BinaryType class template should be specialized
                 * for this type.
                 *
                 * @param arg Argument.
                 */
                template<typename T>
                void AddArgument(const T& arg)
                {
                    args.push_back(new QueryArgument<T>(arg));
                }

                /**
                 * Write query info to the stream.
                 *
                 * @param writer Writer.
                 */
                void Write(binary::BinaryRawWriter& writer) const
                {
                    writer.WriteBool(loc);
                    writer.WriteString(sql);
                    writer.WriteInt32(pageSize);

                    writer.WriteInt32(static_cast<int32_t>(args.size()));

                    for (std::vector<QueryArgumentBase*>::const_iterator it = args.begin(); it != args.end(); ++it)
                        (*it)->Write(writer);

                    writer.WriteBool(distributedJoins);
                    writer.WriteBool(enforceJoinOrder);
                }

            private:
                /** SQL string. */
                std::string sql;

                /** Page size. */
                int32_t pageSize;

                /** Local flag. */
                bool loc;

                /** Distributed joins flag. */
                bool distributedJoins;

                /** Enforce join order flag. */
                bool enforceJoinOrder;

                /** Arguments. */
                std::vector<QueryArgumentBase*> args;
            };
        }
    }
}

#endif //_IGNITE_CACHE_QUERY_QUERY_SQL_FIELDS


text:
'use strict';

Connector.playerSelector = '.ui.controls';

Connector.currentTimeSelector = '.item.start.time';

Connector.trackArtSelector = '.ui.item.active img';

Connector.getArtistTrack = () => {
	let text = $('.current .title').text().replace(/ \[.*/, '');
	return Util.splitArtistTrack(text);
};

Connector.isPlaying = () => $('.item.play.button').hasClass('active');

Connector.getUniqueID = () => {
	let videoUrl = $('#player').attr('src');
	return Util.getYoutubeVideoIdFromUrl(videoUrl);
};

Connector.filter = MetadataFilter.getYoutubeFilter();


text:
<?php

namespace Cascade\Tests\Config\Loader\ClassLoader\Resolver;

use Cascade\Util;
use Cascade\Config\Loader\ClassLoader\Resolver\ConstructorResolver;

use PHPUnit\Framework\TestCase;
use Symfony;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException;

/**
 * Class ConstructorResolverTest
 *
 * @author Raphael Antonmattei <rantonmattei@theorchard.com>
 */
class ConstructorResolverTest extends TestCase
{
    /**
     * Reflection class for which you want to resolve extra options
     * @var \ReflectionClass
     */
    protected $reflected = null;

    /**
     * Constructor Resolver
     * @var ConstructorResolver
     */
    protected $resolver = null;

    /**
     * Set up function
     */
    public function setUp(): void
    {
        $this->class = 'Cascade\Tests\Fixtures\SampleClass';
        $this->resolver = new ConstructorResolver(new \ReflectionClass($this->class));
        parent::setUp();
    }

    /**
     * Tear down function
     */
    public function tearDown(): void
    {
        $this->resolver = null;
        $this->class = null;
        parent::tearDown();
    }

    /**
     * Return the contructor args of the reflected class
     *
     * @return \ReflectionParameter[] array of params
     */
    protected function getConstructorArgs()
    {
        return $this->resolver->getReflected()->getConstructor()->getParameters();
    }

    /**
     * Test the resolver contructor
     */
    public function testConstructor()
    {
        $this->assertEquals($this->class, $this->resolver->getReflected()->getName());
    }

    /**
     * Test that constructor args were pulled properly
     *
     * Note that we need to deuplicate the CamelCase conversion here for old
     * fashioned classes
     */
    public function testInitConstructorArgs()
    {
        $expectedConstructorArgs = array();

        foreach ($this->getConstructorArgs() as $param) {
            $expectedConstructorArgs[Util::snakeToCamelCase($param->getName())] = $param;
        }
        $this->assertEquals($expectedConstructorArgs, $this->resolver->getConstructorArgs());
    }

    /**
     * Test the hashToArgsArray function
     */
    public function testHashToArgsArray()
    {
        $this->assertEquals(
            array('someValue', 'hello', 'there', 'slither'),
            $this->resolver->hashToArgsArray(
                array( // Not properly ordered on purpose
                    'optionalB'     => 'there',
                    'optionalA'     => 'hello',
                    'optionalSnake' => 'slither',
                    'mandatory'     => 'someValue',
                )
            )
        );
    }

    /**
     * Data provider for testResolve
     *
     * The order of the input options does not matter and is somewhat random. The resolution
     * should reconcile those options and match them up with the contructor param position
     *
     * @return array of arrays with expected resolved values and options used as input
     */
    public function optionsProvider()
    {
        return array(
            array(
                array('someValue', 'hello', 'there', 'slither'), // Expected resolved options
                array( // Options (order should not matter, part of resolution)
                    'optionalB'      => 'there',
                    'optionalA'      => 'hello',
                    'mandatory'      => 'someValue',
                    'optionalSnake'  => 'slither',
                )
            ),
            array(
                array('someValue', 'hello', 'BBB', 'snake'),
                array(
                    'mandatory' => 'someValue',
                    'optionalA' => 'hello',
                )
            ),
            array(
                array('someValue', 'AAA', 'BBB', 'snake'),
                array('mandatory' => 'someValue')
            )
        );
    }

    /**
     * Test resolving with valid options
     *
     * @param array $expectedResolvedOptions Array of expected resolved options
     * (i.e. parsed and validated)
     * @param  array $options Array of raw options
     * @dataProvider optionsProvider
     */
    public function testResolve(array $expectedResolvedOptions, array $options)
    {
        $this->assertEquals($expectedResolvedOptions, $this->resolver->resolve($options));
    }

    /**
     * Data provider for testResolveWithInvalidOptions.
     *
     * The order of the input options does not matter and is somewhat random. The resolution
     * should reconcile those options and match them up with the contructor param position
     *
     * @return array of arrays with expected resolved values and options used as input
     */
    public function missingOptionsProvider()
    {
        return array(
            array(
                array( // No values
                ),
                array( // Missing a mandatory value
                    'optionalB' => 'BBB'
                ),
                array( // Still missing a mandatory value
                    'optionalB' => 'there',
                    'optionalA' => 'hello'
                )
            )
        );
    }

    /**
     * Test resolving with missing/incomplete options. It should throw an exception.
     *
     * @param  array $incompleteOptions Array of invalid options
     * @dataProvider missingOptionsProvider
     */
    public function testResolveWithMissingOptions(array $incompleteOptions)
    {
        $this->expectException(MissingOptionsException::class);

        $this->resolver->resolve($incompleteOptions);
    }

    /**
     * Data provider for testResolveWithInvalidOptions
     *
     * The order of the input options does not matter and is somewhat random. The resolution
     * should reconcile those options and match them up with the contructor param position
     *
     * @return array of arrays with expected resolved values and options used as input
     */
    public function invalidOptionsProvider()
    {
        return array(
            array(
                array('ABC'),
                array( // All invalid
                    'someInvalidOptionA' => 'abc',
                    'someInvalidOptionB' => 'def'
                ),
                array( // Some invalid
                    'optionalB' => 'there',
                    'optionalA' => 'hello',
                    'mandatory' => 'dsadsa',
                    'additionalInvalid' => 'some unknow param'
                )
            )
        );
    }

    /**
     * Test resolving with invalid options. It should throw an exception.
     *
     * @param  array $invalidOptions Array of invalid options
     * @dataProvider invalidOptionsProvider
     */
    public function testResolveWithInvalidOptions($invalidOptions)
    {
        $this->expectException(UndefinedOptionsException::class);

        $this->resolver->resolve($invalidOptions);
    }
}


text:
package com.miloshpetrov.sol2.ui;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.miloshpetrov.sol2.*;
import com.miloshpetrov.sol2.common.SolColor;
import com.miloshpetrov.sol2.common.SolMath;
import com.miloshpetrov.sol2.files.FileManager;
import com.miloshpetrov.sol2.game.DebugOptions;
import com.miloshpetrov.sol2.game.SolGame;
import com.miloshpetrov.sol2.GameOptions;

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

public class SolInputManager {

  private static final int POINTER_COUNT = 4;
  private static final float CURSOR_SHOW_TIME = 3;
  public static final float CURSOR_SZ = .07f;
  public static final float WARN_PERC_GROWTH_TIME = 1f;
  private static final float initialRatio = ((float) Gdx.graphics.getWidth()) / ((float) Gdx.graphics.getHeight());

  private final List<SolUiScreen> myScreens;
  private final List<SolUiScreen> myToRemove;
  private final List<SolUiScreen> myToAdd;
  private final Ptr[] myPtrs;
  private final Ptr myFlashPtr;
  private final Vector2 myMousePos;
  private final Vector2 myMousePrevPos;
  private final Sound myHoverSound;
  private float myMouseIdleTime;
  private final TextureAtlas.AtlasRegion myUiCursor;
  private final Color myWarnCol;

  private TextureAtlas.AtlasRegion myCurrCursor;
  private boolean myMouseOnUi;
  private float myWarnPerc;
  private boolean myWarnPercGrows;
  private Boolean myScrolledUp;

  public SolInputManager(TextureManager textureManager, float r) {
    myPtrs = new Ptr[POINTER_COUNT];
    for (int i = 0; i < POINTER_COUNT; i++) {
      myPtrs[i] = new Ptr();
    }
    SolInputProcessor sip = new SolInputProcessor(this);
    Gdx.input.setInputProcessor(sip);
    myFlashPtr = new Ptr();
    myMousePos = new Vector2();
    myMousePrevPos = new Vector2();

    // We want the original mouse cursor to be hidden as we draw our own mouse cursor.
    Gdx.input.setCursorCatched(false);
    setMouseCursorHidden();
    myUiCursor = textureManager.getTex("ui/cursor", null);
    myScreens = new ArrayList<SolUiScreen>();
    myToRemove = new ArrayList<SolUiScreen>();
    myToAdd = new ArrayList<SolUiScreen>();
    myWarnCol = new Color(SolColor.UI_WARN);

    FileHandle hoverSoundFile = FileManager.getInstance().getSoundsDirectory().child("ui").child("uiHover.ogg");
    myHoverSound = Gdx.audio.newSound(hoverSoundFile);
  }

  /**
   * Hides the mouse cursor by setting it to a transparent image.
   */
  private void setMouseCursorHidden() {
    // When debugging the path has a "main" directory prepended
    String debugPath = (DebugOptions.DEV_ROOT_PATH == null) ? "" : DebugOptions.DEV_ROOT_PATH;

    // Load the cursor image - the hotspot is where the click point is which is in the middle in this image.
    Pixmap pm = new Pixmap(Gdx.files.internal(debugPath + "res/imgs/cursorHidden.png"));
    Gdx.input.setCursorImage(pm, 0, 0);
    pm.dispose();
  }

  public void maybeFlashPressed(int keyCode) {
    for (int i = 0, myScreensSize = myScreens.size(); i < myScreensSize; i++) {
      SolUiScreen screen = myScreens.get(i);
      boolean consumed = false;
      List<SolUiControl> controls = screen.getControls();
      for (int i1 = 0, controlsSize = controls.size(); i1 < controlsSize; i1++) {
        SolUiControl c = controls.get(i1);
        if (c.maybeFlashPressed(keyCode)) consumed = true;
      }
      if (consumed) return;
    }

  }

  public void maybeFlashPressed(int x, int y) {
    setPtrPos(myFlashPtr, x, y);
    for (int i = 0, myScreensSize = myScreens.size(); i < myScreensSize; i++) {
      SolUiScreen screen = myScreens.get(i);
      List<SolUiControl> controls = screen.getControls();
      for (int i1 = 0, controlsSize = controls.size(); i1 < controlsSize; i1++) {
        SolUiControl c = controls.get(i1);
        if (c.maybeFlashPressed(myFlashPtr)) return;
      }
      if (screen.isCursorOnBg(myFlashPtr)) return;
    }

  }

  public void setScreen(SolApplication cmp, SolUiScreen screen) {
    for (int i = 0, myScreensSize = myScreens.size(); i < myScreensSize; i++) {
      SolUiScreen oldScreen = myScreens.get(i);
      removeScreen(oldScreen, cmp);
    }
    addScreen(cmp, screen);
  }

  public void addScreen(SolApplication cmp, SolUiScreen screen) {
    myToAdd.add(screen);
    screen.onAdd(cmp);
  }

  private void removeScreen(SolUiScreen screen, SolApplication cmp) {
    myToRemove.add(screen);
    List<SolUiControl> controls = screen.getControls();
    for (int i = 0, controlsSize = controls.size(); i < controlsSize; i++) {
      SolUiControl c = controls.get(i);
      c.blur();
    }
    screen.blurCustom(cmp);
  }

  public boolean isScreenOn(SolUiScreen screen) {
    return myScreens.contains(screen);
  }

  private static void setPtrPos(Ptr ptr, int screenX, int screenY) {
    int h = Gdx.graphics.getHeight();
    float currentRatio = ((float) Gdx.graphics.getWidth()) / ((float) Gdx.graphics.getHeight());

    ptr.x = 1f * screenX / h * (initialRatio / currentRatio);
    ptr.y = 1f * screenY / h;
  }

  public void update(SolApplication cmp) {
    boolean mobile = cmp.isMobile();
    SolGame game = cmp.getGame();

    // This keeps the mouse within the window, but only when playing the game with the mouse.
    // All other times the mouse can freely leave and return.
    if (!mobile && (cmp.getOptions().controlType == GameOptions.CONTROL_MIXED || cmp.getOptions().controlType == GameOptions.CONTROL_MOUSE) &&
            game != null && getTopScreen() != game.getScreens().menuScreen) {
      if(!Gdx.input.isCursorCatched()) Gdx.input.setCursorCatched(true);
      maybeFixMousePos();
    } else {
      if(Gdx.input.isCursorCatched()) Gdx.input.setCursorCatched(false);
    }

    updatePtrs();

    boolean consumed = false;
    myMouseOnUi = false;
    boolean clickOutsideReacted = false;
    for (int i = 0, myScreensSize = myScreens.size(); i < myScreensSize; i++) {
      SolUiScreen screen = myScreens.get(i);
      boolean consumedNow = false;
      List<SolUiControl> controls = screen.getControls();
      for (int i1 = 0, controlsSize = controls.size(); i1 < controlsSize; i1++) {
        SolUiControl c = controls.get(i1);
        c.update(myPtrs, myCurrCursor != null, !consumed, this, cmp);
        if (c.isOn() || c.isJustOff()) {
          consumedNow = true;
        }
        Rectangle area = c.getScreenArea();
        if (area != null && area.contains(myMousePos)) {
          myMouseOnUi = true;
        }
      }
      if (consumedNow) consumed = true;
      boolean clickedOutside = false;
      if (!consumed) {
        for (int i1 = 0, myPtrsLength = myPtrs.length; i1 < myPtrsLength; i1++) {
          Ptr ptr = myPtrs[i1];
          boolean onBg = screen.isCursorOnBg(ptr);
          if (ptr.pressed && onBg) {
            clickedOutside = false;
            consumed = true;
            break;
          }
          if (!onBg && ptr.isJustUnPressed() && !clickOutsideReacted) {
            clickedOutside = true;
          }
        }
      }
      if (clickedOutside && screen.reactsToClickOutside()) clickOutsideReacted = true;
      if (screen.isCursorOnBg(myPtrs[0])) myMouseOnUi = true;
      screen.updateCustom(cmp, myPtrs, clickedOutside);
    }

    TutorialManager tutorialManager = game == null ? null : game.getTutMan();
    if (tutorialManager != null && tutorialManager.isFinished()) {
      cmp.finishGame();
    }

    updateCursor(cmp);
    addRemoveScreens();
    updateWarnPerc();
    myScrolledUp = null;
  }

  private void updateWarnPerc() {
    float dif = SolMath.toInt(myWarnPercGrows) * Const.REAL_TIME_STEP / WARN_PERC_GROWTH_TIME;
    myWarnPerc += dif;
    if (myWarnPerc < 0 || 1 < myWarnPerc) {
      myWarnPerc = SolMath.clamp(myWarnPerc);
      myWarnPercGrows = !myWarnPercGrows;
    }
    myWarnCol.a = myWarnPerc * .5f;
  }

  private void addRemoveScreens() {
    for (int i = 0, myToRemoveSize = myToRemove.size(); i < myToRemoveSize; i++) {
      SolUiScreen screen = myToRemove.get(i);
      myScreens.remove(screen);
    }
    myToRemove.clear();

    for (int i = 0, myToAddSize = myToAdd.size(); i < myToAddSize; i++) {
      SolUiScreen screen = myToAdd.get(i);
      if (isScreenOn(screen)) continue;
      myScreens.add(0, screen);
    }
    myToAdd.clear();
  }

  private void updateCursor(SolApplication cmp) {
    if (cmp.isMobile()) return;
    SolGame game = cmp.getGame();

    myMousePos.set(myPtrs[0].x, myPtrs[0].y);
    if (cmp.getOptions().controlType == GameOptions.CONTROL_MIXED || cmp.getOptions().controlType == GameOptions.CONTROL_MOUSE) {
      if (game == null || myMouseOnUi) {
        myCurrCursor = myUiCursor;
      } else {
        myCurrCursor = game.getScreens().mainScreen.shipControl.getInGameTex();
        if (myCurrCursor == null) myCurrCursor = myUiCursor;
      }
      return;
    }
    if (myMousePrevPos.epsilonEquals(myMousePos, 0) && game != null && getTopScreen() != game.getScreens().menuScreen) {
      myMouseIdleTime += Const.REAL_TIME_STEP;
      myCurrCursor = myMouseIdleTime < CURSOR_SHOW_TIME ? myUiCursor : null;
    } else {
      myCurrCursor = myUiCursor;
      myMouseIdleTime = 0;
      myMousePrevPos.set(myMousePos);
    }
  }

  private void maybeFixMousePos() {
    int mouseX = Gdx.input.getX();
    int mouseY = Gdx.input.getY();
    int w = Gdx.graphics.getWidth();
    int h = Gdx.graphics.getHeight();
    mouseX = (int)SolMath.clamp(mouseX, 0, w);
    mouseY = (int)SolMath.clamp(mouseY, 0, h);
    Gdx.input.setCursorPosition(mouseX, mouseY);
  }

  private void updatePtrs() {
    for (int i = 0; i < POINTER_COUNT; i++) {
      Ptr ptr = myPtrs[i];
      int screenX = Gdx.input.getX(i);
      int screenY = Gdx.input.getY(i);
      setPtrPos(ptr, screenX, screenY);
      ptr.prevPressed = ptr.pressed;
      ptr.pressed = Gdx.input.isTouched(i);
    }
  }

  public void draw(UiDrawer uiDrawer, SolApplication cmp) {
    for (int i = myScreens.size() - 1; i >= 0; i--) {
      SolUiScreen screen = myScreens.get(i);

      uiDrawer.setTextMode(false);
      screen.drawBg(uiDrawer, cmp);
      List<SolUiControl> ctrls = screen.getControls();
      for (int i1 = 0, ctrlsSize = ctrls.size(); i1 < ctrlsSize; i1++) {
        SolUiControl ctrl = ctrls.get(i1);
        ctrl.drawButton(uiDrawer, cmp, myWarnCol);
      }
      screen.drawImgs(uiDrawer, cmp);

      uiDrawer.setTextMode(true);
      screen.drawText(uiDrawer, cmp);
      for (int i1 = 0, ctrlsSize = ctrls.size(); i1 < ctrlsSize; i1++) {
        SolUiControl ctrl = ctrls.get(i1);
        ctrl.drawDisplayName(uiDrawer);
      }
    }
    uiDrawer.setTextMode(null);

    SolGame game = cmp.getGame();
    TutorialManager tutorialManager = game == null ? null : game.getTutMan();
    if (tutorialManager != null && getTopScreen() != game.getScreens().menuScreen) tutorialManager.draw(uiDrawer);

    if (myCurrCursor != null) {
      uiDrawer.draw(myCurrCursor, CURSOR_SZ, CURSOR_SZ, CURSOR_SZ/2, CURSOR_SZ/2, myMousePos.x, myMousePos.y, 0, SolColor.W);
    }
  }

  public Vector2 getMousePos() {
    return myMousePos;
  }

  public Ptr[] getPtrs() {
    return myPtrs;
  }

  public boolean isMouseOnUi() {
    return myMouseOnUi;
  }

  public void playHover(SolApplication cmp) {
    myHoverSound.play(.7f * cmp.getOptions().volMul, .7f, 0);
  }

  public void playClick(SolApplication cmp) {
    myHoverSound.play(.7f * cmp.getOptions().volMul, .9f, 0);
  }

  public SolUiScreen getTopScreen() {
    return myScreens.isEmpty() ? null : myScreens.get(0);
  }

  public void scrolled(boolean up) {
    myScrolledUp = up;
  }

  public Boolean getScrolledUp() {
    return myScrolledUp;
  }

  public void dispose() {
    myHoverSound.dispose();
  }

  public static class Ptr {
    public float x;
    public float y;
    public boolean pressed;
    public boolean prevPressed;

    public boolean isJustPressed() {
      return pressed && !prevPressed;
    }

    public boolean isJustUnPressed() {
      return !pressed && prevPressed;
    }
  }

}


text:
from unittest import mock
import unittest

import responses

from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.salesforce import RetrieveReportsAndDashboards
from cumulusci.utils import temporary_dir
from .util import create_task

class TestRetrievePackaged(unittest.TestCase):
    @responses.activate
    def test_get_api(self):
        with temporary_dir() as path:
            task = create_task(
                RetrieveReportsAndDashboards,
                {
                    "path": path,
                    "report_folders": ["Default"],
                    "dashboard_folders": ["Default"],
                    "api_version": "43.0",
                },
            )
            api = mock.Mock(
                return_value={
                    "Report": [{"fullName": "Report1"}],
                    "Dashboard": [{"fullName": "Dashboard1"}],
                }
            )
            task.list_metadata_api_class = mock.Mock(return_value=api)
            task.api_class = mock.Mock()
            task._get_api()
            package_xml = task.api_class.call_args[0][1]
            self.assertEqual(
                """<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>Dashboard1</members>
        <members>Default</members>
        <name>Dashboard</name>
    </types>
    <types>
        <members>Default</members>
        <members>Report1</members>
        <name>Report</name>
    </types>
    <version>43.0</version>
</Package>""",
                package_xml,
            )

    def test_init__missing_options(self):
        with self.assertRaises(TaskOptionsError):
            create_task(RetrieveReportsAndDashboards, {"path": None})