text:
require 'test/unit'
require 'beanstream'
require 'shoulda'

module Beanstream

  class ProfilesAPITest < Test::Unit::TestCase

    setup do
      Beanstream.merchant_id = "300200578"
      Beanstream.payments_api_key = "4BaD82D9197b4cc4b70a221911eE9f70"
      Beanstream.profiles_api_key = "D97D3BE1EE964A6193D17A571D9FBC80"
    end

    should "make profiles url be the same" do
      assert_equal("/api/v1/profiles", ProfilesAPI.new.profile_url())
    end

    should "make profiles/cards url be the same" do
      assert_equal("/api/v1/profiles/cards", ProfilesAPI.new.profile_cards_url())
    end
  end

  class ProfilesAPIIntegrationTest < Test::Unit::TestCase

    setup do
      Beanstream.merchant_id = "300200578"
      Beanstream.payments_api_key = "4BaD82D9197b4cc4b70a221911eE9f70"
      Beanstream.profiles_api_key = "D97D3BE1EE964A6193D17A571D9FBC80"
      @profile = Beanstream.ProfilesAPI.create_profile(
        {
        "billing" => {
        "name" => "Hilary Test",
        "address_line1" => "123 Fake St.",
        "city" => "Victoria",
        "province" => "BC",
        "country" => "CA",
        "postal_code" => "v1v2v2",
        "phone_number" => "12505551234",
        "email_address" => "fake@example.com"
      }
      })
      @card1 = {
        "card" => {
        "name" => "Hilary Test",
        "number" => "4030000010001234",
        "expiry_month" => "07",
        "expiry_year" => "22",
        "cvd" => "123"
      }}

      @card2 = {
        "card" => {
        "name":"John Doe",
        "number":"5100000010001004",
        "expiry_month":"02",
        "expiry_year":"14"
      } }

    end

    should "have successfully created a profile" do
      result = Beanstream.ProfilesAPI.create_profile(
        {
        "card" => {
        "name" => "Bob Test",
        "number" => "4030000010001234",
        "expiry_month" => "07",
        "expiry_year" => "22",
        "cvd" => "123"
      },
        "billing" => {
        "name" => "Bob Test",
        "address_line1" => "123 Fake St.",
        "city" => "Victoria",
        "province" => "BC",
        "country" => "CA",
        "postal_code" => "v1v2v2",
        "phone_number" => "12505551234",
        "email_address" => "fake@example.com"
      }
      }
      )
      assert(ProfilesAPI.profile_successfully_created(result))
      profile_id = result['customer_code']
      puts "Created profile with ID: #{profile_id}"
    end

    should "have successfully deleted a profile" do

      Beanstream.merchant_id = "300200578"
      Beanstream.profiles_api_key = "D97D3BE1EE964A6193D17A571D9FBC80"

      result = Beanstream.ProfilesAPI.create_profile(
        {
        "card" => {
        "name" => "Jill Test",
        "number" => "4030000010001234",
        "expiry_month" => "07",
        "expiry_year" => "22",
        "cvd" => "123"
      },
        "billing" => {
        "name" => "Jill Test",
        "address_line1" => "123 Fake St.",
        "city" => "Victoria",
        "province" => "BC",
        "country" => "CA",
        "postal_code" => "v1v2v2",
        "phone_number" => "12505551234",
        "email_address" => "fake@example.com"
      }
      }
      )
      assert(ProfilesAPI.profile_successfully_created(result))
      profile_id = result['customer_code']
      puts "Created profile with ID: #{profile_id}"

      # now delete the profile
      result = Beanstream.ProfilesAPI.delete_profile(profile_id)
      assert(ProfilesAPI.profile_successfully_deleted(result))
      puts "Deleted profile #{result['customer_code']}"
    end

    should "have successfully retrieved a profile" do

      Beanstream.merchant_id = "300200578"
      Beanstream.profiles_api_key = "D97D3BE1EE964A6193D17A571D9FBC80"

      result = Beanstream.ProfilesAPI.create_profile(
        {
        "card" => {
        "name" => "Jill Test",
        "number" => "4030000010001234",
        "expiry_month" => "07",
        "expiry_year" => "22",
        "cvd" => "123"
      },
        "billing" => {
        "name" => "Jill Test",
        "address_line1" => "123 Fake St.",
        "city" => "Victoria",
        "province" => "BC",
        "country" => "CA",
        "postal_code" => "v1v2v2",
        "phone_number" => "12505551234",
        "email_address" => "fake@example.com"
      }
      }
      )
      assert(ProfilesAPI.profile_successfully_created(result))
      profile_id = result['customer_code']
      puts "Created profile with ID: #{profile_id}"

      # now get that profile
      result = Beanstream.ProfilesAPI.get_profile(profile_id)
      assert(result != nil)
      assert(result['billing']['name'] == "Jill Test")

      Beanstream.ProfilesAPI.delete_profile(profile_id) #delete it to clean up
    end

    should "have successfully retrieved a profile" do

      Beanstream.merchant_id = "300200578"
      Beanstream.profiles_api_key = "D97D3BE1EE964A6193D17A571D9FBC80"

      result = Beanstream.ProfilesAPI.create_profile(
        {
        "card" => {
        "name" => "Hilary Test",
        "number" => "4030000010001234",
        "expiry_month" => "07",
        "expiry_year" => "22",
        "cvd" => "123"
      },
        "billing" => {
        "name" => "Hilary Test",
        "address_line1" => "123 Fake St.",
        "city" => "Victoria",
        "province" => "BC",
        "country" => "CA",
        "postal_code" => "v1v2v2",
        "phone_number" => "12505551234",
        "email_address" => "fake@example.com"
      }
      }
      )
      assert(ProfilesAPI.profile_successfully_created(result))
      profile_id = result['customer_code']
      puts "Created profile with ID: #{profile_id}"

      # now get that profile
      profile1 = Beanstream.ProfilesAPI.get_profile(profile_id)
      assert(profile1 != nil)
      assert(profile1['billing']['name'] == "Hilary Test")
      puts "\n\nRetrieved Profile 1:\n\n #{profile1}"

      #update profile
      profile1['billing']['name'] = "gizmo test"
      profile1['language'] = "en"
      profile1['comments'] = "test profile"
      profile1['custom']['ref1'] = "i wish"
      profile1['custom']['ref2'] = "i was"
      profile1['custom']['ref3'] = "an oscar"
      profile1['custom']['ref4'] = "mayer"
      profile1['custom']['ref5'] = "weiner"
      result = Beanstream.ProfilesAPI.update_profile(profile1)

      #get profile again and check the updates
      profile2 = Beanstream.ProfilesAPI.get_profile(profile_id)
      puts "\n\nRetrieved Profile 2:\n\n #{profile2}"
      assert(profile2 != nil)
      assert(profile2['billing']['name'] == "gizmo test")
      assert(profile2['language'] == "en")
      assert(profile2['custom']['ref1'] == "i wish")
      assert(profile2['custom']['ref2'] == "i was")
      assert(profile2['custom']['ref3'] == "an oscar")
      assert(profile2['custom']['ref4'] == "mayer")
      assert(profile2['custom']['ref5'] == "weiner")

      Beanstream.ProfilesAPI.delete_profile(profile_id) #delete it to clean up
    end

    should 'Successfully Add Card' do
      insert_card = Beanstream.ProfilesAPI.add_profile_card(@profile,@card1)
      #Retrieve Profile  again to check if card added
      profile2 = Beanstream.ProfilesAPI.get_profile(@profile['customer_code'])
      assert(profile2['card'])
      assert(insert_card['message']== 'Operation Successful')
    end

    should 'Successfully get Card' do
      add_card = Beanstream.ProfilesAPI.add_profile_card(@profile,@card1)
      card = Beanstream.ProfilesAPI.get_profile_card(@profile)
      assert(card)
      assert(card['message']== 'Operation Successful')
    end

    should 'successfully update card' do
      # Create profile with card 1
      insert_card = Beanstream.ProfilesAPI.add_profile_card(@profile,@card2)
      # Update profile with card 2
      update_card = Beanstream.ProfilesAPI.update_profile_card(@profile,1,@card1)
      profile2 = Beanstream.ProfilesAPI.get_profile(@profile['customer_code'])
      assert(update_card['message']== 'Operation Successful')
    end

    should 'successfully delete card' do
      # Create profile with card 1
      insert_card = Beanstream.ProfilesAPI.add_profile_card(@profile,@card2)
      # delete card from profile
      delete_card = Beanstream.ProfilesAPI.delete_profile_card(@profile,1)
      assert(delete_card['message']== 'Operation Successful')
    end
  end
end


text:
        <button ng-click="newMate = true; btnAddMate = true" ng-hide="btnAddMate" class="btn btn-success"></button>

    <form ng-show="newMate" novalidate name="newMateForm" class="form well">

            Mate name:
            <input type="text" class="form-control" id="text" ng-model="mate.user_name"/>

            E-mail:
            <input type="email" class="form-control" ng-model="mate.email" id="mail" />

            Image url:
            <input type="url" class="form-control" ng-model="mate.image" id="imageUrl" />

        <button type="button" ng-click="save()" class="btn btn-success">Save</button>
        <button type="button" ng-click="cancel()" class="btn btn-danger">Cancel</button>
    </form>

            <fieldset>

{{Mate.user_name}}

 {{Mate.email}}

                        <button
                          mwl-confirm
                          title="Confirm"
                          message="Are you sure you want delete this user?"
                          placement="bottom"
                          on-confirm="remove(Mate)"
                          type="button" class="btn btn-danger" ></button>

            </fieldset>

redpajama_set_name: RedPajamaGithub


text:
1.  Log in to the management console and click  **Virtual Private Network**.
2.  In the VPN list, locate the target VPN and click  **View Policy** in the **Operation**  column to view IKE and IPsec policy details about the VPN.
3.  Check the IKE and IPsec policies to see whether the negotiation modes and encryption algorithms between the local and remote sides of the VPN are the same.
    1.  If the IKE policy has been set up during phase one and the IPsec policy has not been enabled in phase two, the IPsec policies between the local and remote sides of the VPN may be inconsistent.
    2.  If the Cisco physical device is used at the customer side, it is recommended that you use MD5. Then, you need to set  **Authentication Mode** to **MD5**  in the IPsec policy for the VPN created on the cloud.

1.  Check whether the ACL configurations are correct.

    If the subnets of your data center are 192.168.3.0/24 and 192.168.4.0/24, and the VPC subnets are 192.168.1.0/24 and 192.168.2.0/24, configure the ACL rules for each data center subnet to permit the communication with the VPC subnets. The following provides an example of ACL configurations:

    ```
    rule 1 permit ip source 192.168.3.0 0.0.0.255 destination 192.168.1.0 0.0.0.255
    rule 2 permit ip source 192.168.3.0 0.0.0.255 destination 192.168.2.0 0.0.0.255
    rule 3 permit ip source 192.168.4.0 0.0.0.255 destination 192.168.1.0 0.0.0.255
    rule 4 permit ip source 192.168.4.0 0.0.0.255 destination 192.168.2.0 0.0.0.255
    ```

2.  After the configuration is complete, ping the local and the remote side from each other to check whether the VPN connection is normal.


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

package app.metatron.discovery.domain.context;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;

import org.apache.commons.lang3.StringUtils;

import app.metatron.discovery.common.entity.DomainType;

public class ContextPredicate {

  /**
   * Context 기본 검색 관련 조건 정의
   *
   * @param type type of domain
   * @param domainId domain id
   *
   * @return
   */
  public static Predicate searchList(DomainType type, String domainId) {

    BooleanBuilder builder = new BooleanBuilder();
    QContext context = QContext.context;

    if(type != null) {
      builder.and(context.domainType.eq(type));
    }

    if(StringUtils.isNotEmpty(domainId)) {
      builder.and(context.domainId.eq(domainId));
    }

    return builder;
  }

  /**
   * Context 기본 검색 관련 조건 정의
   *
   * @param type type of domain
   * @param key domain id
   * @param value domain id
   *
   * @return
   */
  public static Predicate searchByKeyValue(DomainType type, String key, String value) {

    BooleanBuilder builder = new BooleanBuilder();
    QContext context = QContext.context;

    //builder.and(context.domainId.isNotNull());

    if(type != null) {
      builder.and(context.domainType.eq(type));
    }

    if(StringUtils.isNotEmpty(key)) {
      builder.and(context.key.eq(key));
    }

    if(StringUtils.isNotEmpty(value)) {
      builder.and(context.value.eq(value));
    }

    return builder;
  }
}


text:
package uk.trainwatch.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 *
 * @author peter
 */
public interface ListBuilder<T>
{

    /**
     * Add an entry to the list
     *
     * @param v
     * @return
     */
    ListBuilder<T> add( T v );

    /**
     * Mark the list as readonly
     *
     * @return
     */
    ListBuilder<T> readonly();

    /**
     * Mark the list as synchronized
     *
     * @return
     */
    ListBuilder<T> _synchronized();

    /**
     * Mark the list as concurrent
     *
     * @return
     */
    ListBuilder<T> concurrent();

    /**
     * Create the final list
     *
     * @return
     */
    List<T> build();

    /**
     * Create a new builder
     *
     * @param <T>
     * @return
     */
    static <T> ListBuilder<T> builder()
    {
        return new ListBuilder<T>()
        {
            private boolean readonly;
            private boolean sync;
            private boolean concurrent;
            private List<T> list;
            private boolean built;

            private List<T> getList()
            {
                if( list == null ) {
                    if( concurrent ) {
                        list = new CopyOnWriteArrayList<>();
                    }
                    else {
                        list = new ArrayList<>();
                    }
                }
                else if( built ) {
                    if( concurrent ) {
                        list = new CopyOnWriteArrayList<>( list );
                    }
                    else {
                        list = new ArrayList<>( list );
                    }
                    built = false;
                }
                return list;
            }

            @Override
            public ListBuilder<T> add( T v )
            {
                getList().add( v );
                return this;
            }

            @Override
            public ListBuilder<T> readonly()
            {
                if( sync || concurrent ) {
                    throw new IllegalArgumentException( "Cannot make list read only" );
                }
                readonly = true;
                return this;
            }

            @Override
            public ListBuilder<T> _synchronized()
            {
                if( readonly || concurrent ) {
                    throw new IllegalArgumentException( "Cannot make list synchronized" );
                }
                sync = true;
                return this;
            }

            @Override
            public ListBuilder<T> concurrent()
            {
                if( readonly || sync ) {
                    throw new IllegalArgumentException( "Cannot make list concurrent" );
                }
                if( !concurrent && list != null ) {
                    throw new IllegalArgumentException( "Cannot convert list to concurrent" );
                }
                concurrent = true;
                return this;
            }

            @Override
            public List<T> build()
            {
                List<T> l = getList();
                if( readonly ) {
                    l = Collections.unmodifiableList( l );
                }
                else if( sync ) {
                    l = Collections.synchronizedList( l );
                }
                built = true;
                return l;
            }
        };
    }
}


text:
using System;
using System.Diagnostics;
using System.Dynamic;
using L4p.Common.DumpToLogs;
using L4p.Common.PubSub.contexts;

namespace L4p.Common.PubSub.client
{
    class NotInitializedSignals : ISignalsManager
    {
        private static readonly string NotInitializedMsg = "Signals are not initialized (or failed to initialize)";

        #region members
        #endregion

        #region construction

        public static ISignalsManager New()
        {
            return
                new NotInitializedSignals();
        }

        private NotInitializedSignals()
        {
        }

        #endregion

        #region private
        #endregion

        #region interface

        ExpandoObject IHaveDump.Dump(dynamic root)
        {
            if (root == null)
                root = new ExpandoObject();

            root.Error = NotInitializedMsg;

            return root;
        }

        ISignalSlot ISignalsManager.SubscribeTo<T>(Action<T> callback, Func<T, bool> filter, StackFrame filterAt)
        {
            throw
                new SignalsException(NotInitializedMsg);
        }

        void ISignalsManager.Publish<T>(T msg)
        {
            throw
                new SignalsException(NotInitializedMsg);
        }

        ISessionContext ISignalsManager.Context
        {
            get
            {
                throw new SignalsException(NotInitializedMsg);
            }
        }

        void ISignalsManager.StartAgent()
        {
            throw
                new SignalsException(NotInitializedMsg);
        }

        void ISignalsManager.StopAgent()
        {
            throw
                new SignalsException(NotInitializedMsg);
        }

        #endregion
    }
}


text:
package org.apache.sysml.test.integration.applications.dml;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.apache.sysml.api.DMLScript;
import org.apache.sysml.test.integration.applications.GNMFTest;

@RunWith(value = Parameterized.class)
public class GNMFDMLTest extends GNMFTest {

	public GNMFDMLTest(int m, int n, int k) {
		super(m, n, k);
		TEST_CLASS_DIR = TEST_DIR + GNMFDMLTest.class.getSimpleName() + "/";
	}

	@Test
	public void testGNMFDml() {
		testGNMF(ScriptType.DML);
	}

	@Test
	public void testGNMFDmlDisableSparseNCaching() {
		try {
			DMLScript.DISABLE_SPARSE = true;
			DMLScript.DISABLE_CACHING = true;
			testGNMF(ScriptType.DML);
		}
		finally {
			DMLScript.DISABLE_SPARSE = false;
			DMLScript.DISABLE_CACHING = false;
		}
	}
}


text:
var storage = chrome.storage.local;

storage.get({ "rowStyle":"", "titleStyle":"", "filter":"" } , function(items) {
    if (items.rowStyle) {
        $("#rowStyle").val(items.rowStyle);
    } else {
        $("#rowStyle").val("border-left: 5px solid #9933CC");
    }

    if (items.titleStyle) {
        $("#titleStyle").val(items.titleStyle);
    }

    if (items.filter) {
        $("#data").val(items.filter);
    }
});

function message(message) {
    $("#message").html(message);
    setTimeout(function() { $("#message").html('') }, 3000);
}

// Add event listeners once the DOM has fully loaded by listening for the
// `DOMContentLoaded` event on the document, and adding your listeners to
// specific elements when it triggers.
document.addEventListener('DOMContentLoaded', function () {
    $("#button").click(function() {
        // Get a value saved in a form.
        var rowStyle = $("#rowStyle").val();
        var titleStyle = $("#titleStyle").val();
        var filters = $("#data").val();
        // Check that there's some code there.
        if (!filters) {
            message('Error: Please, specify the filters');
            return;
        }
        var dataObj = {"rowStyle":rowStyle, "titleStyle":titleStyle, "filter":normalize(filters) };
        // Save it using the Chrome extension storage API.
        storage.set(dataObj, function() {
            // Notify that we saved.
            message('Settings saved');
        });
        $("#data").val(filters);
    });
});


text:
// Originally from UpdatedComponentTests/StandardTesting/REST/Rest_Post_RequestTypes_Set_SimpleSet_XML_BlankEntry.xls;
package com.betfair.cougar.tests.updatedcomponenttests.standardtesting.rest;

import com.betfair.testing.utils.cougar.misc.XMLHelpers;
import com.betfair.testing.utils.JSONHelpers;
import com.betfair.testing.utils.cougar.assertions.AssertionUtils;
import com.betfair.testing.utils.cougar.beans.HttpCallBean;
import com.betfair.testing.utils.cougar.beans.HttpResponseBean;
import com.betfair.testing.utils.cougar.manager.CougarManager;
import com.betfair.testing.utils.cougar.manager.RequestLogRequirement;

import org.json.JSONObject;
import org.testng.annotations.Test;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.sql.Timestamp;

/**
 * Ensure that when a Rest (XML) Post operation is performed, Cougar can correctly handle a simple Set with a blank entry in the post body
 */
public class RestPostRequestTypesSetSimpleSetXMLBlankEntryTest {
    @Test
    public void doTest() throws Exception {
        // Set up the Http Call Bean to make the request
        CougarManager cougarManager1 = CougarManager.getInstance();
        HttpCallBean getNewHttpCallBean1 = cougarManager1.getNewHttpCallBean("87.248.113.14");
        cougarManager1 = cougarManager1;

        getNewHttpCallBean1.setOperationName("simpleSetOperation");

        getNewHttpCallBean1.setServiceName("baseline", "cougarBaseline");

        getNewHttpCallBean1.setVersion("v2");
        // Set the post body to contain a simple set with a blank entry
        getNewHttpCallBean1.setRestPostQueryObjects(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream("<message><simpleSet><String>bbb string</String><String/><String>ddd string</String><String>ccc string</String></simpleSet></message>".getBytes())));
        // Get current time for getting log entries later

        Timestamp getTimeAsTimeStamp7 = new Timestamp(System.currentTimeMillis());
        // Make XML call to the operation requesting an XML response
        cougarManager1.makeRestCougarHTTPCall(getNewHttpCallBean1, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTXML, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.XML);
        // Make XML call to the operation requesting a JSON response
        cougarManager1.makeRestCougarHTTPCall(getNewHttpCallBean1, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTXML, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.JSON);
        // Create the expected response as an XML document
        XMLHelpers xMLHelpers3 = new XMLHelpers();
        Document createAsDocument10 = xMLHelpers3.getXMLObjectFromString("<SimpleSetOperationResponse><SimpleSetOperationResponseObject><responseSet><String/><String>bbb string</String><String>ccc string</String><String>ddd string</String></responseSet></SimpleSetOperationResponseObject></SimpleSetOperationResponse>");
        // Create the expected response as a JSON object
        JSONHelpers jSONHelpers4 = new JSONHelpers();
        JSONObject createAsJSONObject11 = jSONHelpers4.createAsJSONObject(new JSONObject("{\"responseSet\": [\"\",\"bbb string\",\"ccc string\",\"ddd string\"]}"));
        // Check the 2 responses are as expected
        HttpResponseBean response5 = getNewHttpCallBean1.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTXMLXML);
        AssertionUtils.multiAssertEquals(createAsDocument10, response5.getResponseObject());
        AssertionUtils.multiAssertEquals((int) 200, response5.getHttpStatusCode());
        AssertionUtils.multiAssertEquals("OK", response5.getHttpStatusText());

        HttpResponseBean response6 = getNewHttpCallBean1.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTXMLJSON);
        AssertionUtils.multiAssertEquals(createAsJSONObject11, response6.getResponseObject());
        AssertionUtils.multiAssertEquals((int) 200, response6.getHttpStatusCode());
        AssertionUtils.multiAssertEquals("OK", response6.getHttpStatusText());

        // generalHelpers.pauseTest(500L);
        // Check the log entries are as expected

        cougarManager1.verifyRequestLogEntriesAfterDate(getTimeAsTimeStamp7, new RequestLogRequirement("2.8", "simpleSetOperation"),new RequestLogRequirement("2.8", "simpleSetOperation") );
    }

}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [1.0.0] - 2017-10-12
### Added
- changelog

## [1.0.1] - 2017-10-12 (Benjamin Wang)

- Added Tasks.php
- Changed autoload.php to load tasks.csv
- Updated changelog.md

## [1.0.2] - 2017-10-12 (Judy Zhu)

- Modified homepage page to display information about tasks
- Updated changelog.md

## [1.0.3] - 2017-10-12 (Benjamin Wang)

- Changed Work link to display tasks sorted by Priority and by Category
- Updated changelog.md

## [1.0.4] - 2017-10-12 (Judy Zhu)

- Changed Help Wanted link to display content
- Updated changelog.md

## [1.0.5] - 2017-10-19 (Benjamin Wang)

- Fixed bootstrap in template_secondary
- Implemented Maintainence
- Updated changelog.md

## [1.0.6] - 2017-10-19 (Judy Zhu)

- Implemented Pagination
- Updated changelog.md

## [1.0.7] - 2017-10-19 (Benjamin Wang)

- Added roles
- Updated changelog.md

## [1.0.8] - 2017-10-19 (Judy Zhu)

- Added form for work page
- Updated changelog.md

## [1.0.9] - 2017-10-19 (Benjamin Wang)

- Implemented role-specific maintenance
- Updated changelog.md

## [1.0.10] - 2017-10-19 (Judy Zhu)

- Edited Task Item maintenance final part
- Updated changelog.md

## [1.0.11] - 2017-10-19 (Benjamin Wang)

- Polished item maintenance
- Updated changelog.md

## [1.0.12] - 2017-11-04 (Judy Zhu)

- Added model: Entity.php, Task.php
- Added unit test: tests folder (TaskTest.php, TaskListTest.php, Bootstrap.php)
- Added phpunit.xml.dist
- Added .travis.yml
- Added composer
- Updated changelog.md

## [1.0.13] - 2017-11-04 (Judy Zhu)

- Updated .gitignore

## [1.0.14] - 2017-11-04 (Judy Zhu)

- Updated unit tests files for PHPUNIT 6.4.3

## [1.0.15] - 2017-11-16 (Benjamin Wang)

- Added data/tasks.xml

## [1.0.16] - 2017-11-16 (Judy Zhu)

- Added application/core/XML_Model.php
- Modified XML_Model.php load()

## [1.0.17] - 2017-11-16 (Benjamin Wang)

- Added store() function in XML_Model.php
- Fixed load() function XML_Model.php


text:
/**
 * CT Plugin Settings JavaScript
 *
 * This is loaded in WordPress admin when the CT Plugin Settings class is used.
 */

jQuery( document ).ready( function( $ ) {

	// Get section
	var section = location.hash.replace( '#', '' );

	// Activate section specified in URL hash
	// Or, first tab if no hash in URL or if hash is invalid
	// Or, first tab if just restored defaults
	if ( ! section || ! $( "#ctps-tabs .nav-tab[data-section^='" + section + "']" ).length || $( '#setting-error-restore_defaults' ).length ) { // use first if none specified or if section is wrong
		section = $( '#ctps-tabs .nav-tab:first-child' ).attr( 'data-section' );
	}

	// Switch the section
	ctps_switch_section( section );

	// Now show tabs + form after initial setup
	$( '#ctps-tabs, #ctps-form' ).fadeIn( 'fast' );

	// Change tab/section on click
	$( '#ctps-tabs .nav-tab' ).click( function() {

		var section;

		section = $( this ).attr( 'data-section' );

		ctps_switch_section( section );

		$( '.settings-error' ).remove(); // hide message

	} );

	// Move checkbox fields not having a name into same row/cell as one having name above them
	$( '.ctps-checkbox' ).each( function() {

		var row;

		row = $( this ).parents( 'tr' );

		// Does this field NOT have a name?
		if ( $( 'th', row ).html() == '' ) { // th holds name

			// Previous row
			var prev_row = row.prev( 'tr' );

			// Does immediately preceding row contain checkbox AND have name?
			if ( $( 'td .ctps-checkbox', prev_row ).length && $( 'th', prev_row ).html() != '' ) {

				// Move this checkbox field to bottom of that row
				$( 'td', prev_row ).append( '<div>' + $( 'td', row ).html() );

				// Remove old row
				row.remove();

			}

		}

	} )

} );

/**
 * Switch Tab/Section
 */

function ctps_switch_section( section ) {

	// Add class to <body>
	// This is helpful for CSS based on section
	jQuery( '#ctps-tabs .nav-tab' ).each( function() { // remove all first
		jQuery( 'body' ).removeClass( 'ctps-active-section-' + jQuery( this ).attr( 'data-section' ) );
	} );
	jQuery( 'body' ).addClass( 'ctps-active-section-' + section );

	// Activate tab
	jQuery( '#ctps-tabs .nav-tab' ).removeClass( 'nav-tab-active' );
	jQuery( "#ctps-tabs .nav-tab[data-section^='" + section + "']" ).addClass( 'nav-tab-active' );

	// Show description
	jQuery( '.ctps-section-desc' ).hide(); // hide others
	jQuery( '#ctps-section-desc-' + section ).fadeIn( 'fast' );

	// Show settings
	jQuery( '#ctps-form tr' ).hide(); // hide others
	jQuery( '#ctps-form tr' ).each( function() {

		if ( jQuery( '.ctps-section-' + section, this ).length ) { // show row if it has setting belonging to section
			jQuery( this ).fadeIn( 'fast' );
		}

	} );

	// Show button only if section has fields
	// Add-on Licenses section will always begin empty
	if ( jQuery( '.ctps-section-' + section + ' .ctps-field' ).length ) {
		jQuery( '#ctps-form .submit' ).show();
	} else {
		jQuery( '#ctps-form .submit' ).hide();
	}

	// Add hash
	jQuery( '#ctps-form' ).attr( 'action', 'options.php#' + section ); // add to <form> post so tab stays same
	window.location.hash = section; // always show hash (such as first load w/none)

}


text:
"""Greedy distributions with respect to a set of preferences."""

import chex
from distrax._src.distributions import categorical
from distrax._src.distributions import distribution
import jax.numpy as jnp

Array = chex.Array

def _argmax_with_random_tie_breaking(preferences: Array) -> Array:
  """Compute probabilities greedily with respect to a set of preferences."""
  optimal_actions = (preferences == preferences.max(axis=-1, keepdims=True))
  return optimal_actions / optimal_actions.sum(axis=-1, keepdims=True)

class Greedy(categorical.Categorical):
  """A Categorical distribution that is greedy with respect to some preferences.

  Given a set of unnormalized preferences, the probability mass is distributed
  equally among all indices `i` such that `preferences[i] = max(preferences)`,
  all other indices will be assigned a probability of zero.
  """

  def __init__(self, preferences: Array, dtype: jnp.dtype = int):
    """Initializes a Greedy distribution.

    Args:
      preferences: Unnormalized preferences.
      dtype: The type of event samples.
    """
    self._preferences = jnp.asarray(preferences)
    probs = _argmax_with_random_tie_breaking(self._preferences)
    super().__init__(probs=probs, dtype=dtype)

  @property
  def preferences(self) -> Array:
    """Unnormalized preferences."""
    return self._preferences

  def __getitem__(self, index) -> 'Greedy':
    """See `Distribution.__getitem__`."""
    index = distribution.to_batch_shape_index(self.batch_shape, index)
    return Greedy(
        preferences=self.preferences[index], dtype=self.dtype)


text:
package ij.plugin;
import ij.IJ;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.applet.Applet;

public class BrowserLauncher implements PlugIn {
	/** The com.apple.mrj.MRJFileUtils class */
	private static Class mrjFileUtilsClass;
	/** The openURL method of com.apple.mrj.MRJFileUtils */
	private static Method openURL;
	private static boolean error;
	static {loadClasses();}

	/** Opens the specified URL (default is the ImageJ home page). */
	public void run(String theURL) {
		if (error) return;
		if (theURL==null || theURL.equals(""))
			theURL = IJ.URL;
		Applet applet = IJ.getApplet();
		if (applet!=null) {
			try {
				applet.getAppletContext().showDocument(new URL(theURL), "_blank" );
			} catch (Exception e) {}
			return;
		}
		try {openURL(theURL);}
		catch (IOException e) {}
	}

	/**
	 * Attempts to open the default web browser to the given URL.
	 * @param url The URL to open
	 * @throws IOException If the web browser could not be located or does not run
	 */
	public static void openURL(String url) throws IOException {
		String errorMessage = "";
		if (IJ.isMacOSX()) {
			if (IJ.isJava16())
				IJ.runMacro("exec('open', '"+url+"')");
			else {
				try {
					Method aMethod = mrjFileUtilsClass.getDeclaredMethod("sharedWorkspace", new Class[] {});
					Object aTarget = aMethod.invoke( mrjFileUtilsClass, new Object[] {});
					openURL.invoke(aTarget, new Object[] { new java.net.URL( url )});
				} catch (Exception e) {
					errorMessage = ""+e;
				}
			}
		} else if (IJ.isWindows()) {
			String cmd = "rundll32 url.dll,FileProtocolHandler " + url;
			if (System.getProperty("os.name").startsWith("Windows 2000"))
				cmd = "rundll32 shell32.dll,ShellExec_RunDLL " + url;
			Process process = Runtime.getRuntime().exec(cmd);
			// This avoids a memory leak on some versions of Java on Windows.
			// That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
			try {
				process.waitFor();
				process.exitValue();
			} catch (InterruptedException ie) {
				throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
			}
		} else {
				// Assume Linux or Unix
				// Based on BareBonesBrowserLaunch (http://www.centerkey.com/java/browser/)
				// The utility 'xdg-open' launches the URL in the user's preferred browser,
				// therefore we try to use it first, before trying to discover other browsers.
				String[] browsers = {"xdg-open", "netscape", "firefox", "konqueror", "mozilla", "opera", "epiphany", "lynx" };
				String browserName = null;
				try {
					for (int count=0; count<browsers.length && browserName==null; count++) {
						String[] c = new String[] {"which", browsers[count]};
						if (Runtime.getRuntime().exec(c).waitFor()==0)
							browserName = browsers[count];
					}
					if (browserName==null)
						ij.IJ.error("BrowserLauncher", "Could not find a browser");
					else
						Runtime.getRuntime().exec(new String[] {browserName, url});
				} catch (Exception e) {
					throw new IOException("Exception while launching browser: " + e.getMessage());
				}
		}
	}

	/**
	 * Called by a static initializer to load any classes, fields, and methods
	 * required at runtime to locate the user's web browser.
	 */
	private static void loadClasses() {
		if (IJ.isMacOSX() && !IJ.isJava16() && IJ.getApplet()==null) {
			try {
				if (new File("/System/Library/Java/com/apple/cocoa/application/NSWorkspace.class").exists()) {
					ClassLoader classLoader = new URLClassLoader(new URL[]{new File("/System/Library/Java").toURL()});
					mrjFileUtilsClass = Class.forName("com.apple.cocoa.application.NSWorkspace", true, classLoader);
				} else
					mrjFileUtilsClass = Class.forName("com.apple.cocoa.application.NSWorkspace");
				openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { java.net.URL.class });
			} catch (Exception e) {
				IJ.log("BrowserLauncher"+e);
				error = true;
			}
		}
	}

}


text:
DIR="$(pwd)/tls"

# Optional: Ensure the target directory exists and is empty.
rm -rf "${DIR}"
mkdir -p "${DIR}"

# Create the openssl configuration file. This is used for both generating
# the certificate as well as for specifying the extensions. It aims in favor
# of automation, so the DN is encoding and not prompted.
cat > "${DIR}/openssl.cnf" << EOF
[req]
default_bits = 2048
encrypt_key  = no # Change to encrypt the private key using des3 or similar
default_md   = sha256
prompt       = no
utf8         = yes

# Speify the DN here so we aren't prompted (along with prompt = no above).
distinguished_name = req_distinguished_name

# Extensions for SAN IP and SAN DNS
req_extensions = v3_req

# Be sure to update the subject to match your organization.
[req_distinguished_name]
C  = US
ST = California
L  = The Cloud
O  = Demo
CN = <EXTERNAL_IP>

# Allow client and server auth. You may want to only allow server auth.
# Link to SAN names.
[v3_req]
basicConstraints     = CA:FALSE
subjectKeyIdentifier = hash
keyUsage             = digitalSignature, keyEncipherment
extendedKeyUsage     = clientAuth, serverAuth
subjectAltName       = @alt_names

# Alternative names are specified as IP.# and DNS.# for IP addresses and
# DNS accordingly.
[alt_names]
IP.1  = <EXTERNAL_IP>
IP.2  = <INTERNAL_IP>
DNS.1 = <EXTERNAL_IP>
DNS.2 = <EXTERNAL_IP>:5000
DNS.3 = <EXTERNAL_IP>:9876
DNS.4 = <EXTERNAL_IP>:8780
DNS.5 = <INTERNAL_IP>
DNS.6 = <INTERNAL_IP>:5000
DNS.7 = <INTERNAL_IP>:9876
DNS.8 = <INTERNAL_IP>:8780
EOF

# Create the certificate authority (CA). This will be a self-signed CA, and this
# command generates both the private key and the certificate. You may want to
# adjust the number of bits (4096 is a bit more secure, but not supported in all
# places at the time of this publication).
#
# To put a password on the key, remove the -nodes option.
#
# Be sure to update the subject to match your organization.
openssl req \
  -new \
  -newkey rsa:2048 \
  -days 120 \
  -nodes \
  -x509 \
  -subj "/C=US/ST=California/L=The Cloud/O=My Company CA" \
  -keyout "${DIR}/ca.key" \
  -out "${DIR}/ca.crt"
#
# For each server/service you want to secure with your CA, repeat the
# following steps:
#

# Generate the private key for the service. Again, you may want to increase
# the bits to 4096.
openssl genrsa -out "${DIR}/my-service.key" 2048

# Generate a CSR using the configuration and the key just generated. We will
# give this CSR to our CA to sign.
openssl req \
  -new -key "${DIR}/my-service.key" \
  -out "${DIR}/my-service.csr" \
  -config "${DIR}/openssl.cnf"

# Sign the CSR with our CA. This will generate a new certificate that is signed
# by our CA.
openssl x509 \
  -req \
  -days 120 \
  -in "${DIR}/my-service.csr" \
  -CA "${DIR}/ca.crt" \
  -CAkey "${DIR}/ca.key" \
  -CAcreateserial \
  -extensions v3_req \
  -extfile "${DIR}/openssl.cnf" \
  -out "${DIR}/my-service.crt"

# (Optional) Verify the certificate.
openssl x509 -in "${DIR}/my-service.crt" -noout -text

# Here is a sample response (truncate):
#
# Certificate:
#     Signature Algorithm: sha256WithRSAEncryption
#         Issuer: C = US, ST = California, L = The Cloud, O = My Organization CA
#         Subject: C = US, ST = California, L = The Cloud, O = Demo, CN = My Certificate
#         # ...
#         X509v3 extensions:
#             X509v3 Basic Constraints:
#                 CA:FALSE
#             X509v3 Subject Key Identifier:
#                 36:7E:F0:3D:93:C6:ED:02:22:A9:3D:FF:18:B6:63:5F:20:52:6E:2E
#             X509v3 Key Usage:
#                 Digital Signature, Key Encipherment
#             X509v3 Extended Key Usage:
#                 TLS Web Client Authentication, TLS Web Server Authentication
#             X509v3 Subject Alternative Name:
#                 IP Address:1.2.3.4, DNS:my.dns.name
#

# [END anthosbaremetal_resources_create_certs]


text:
from oslo_config import cfg

from vitrage.evaluator.template_schemas import init_template_schemas

# Register options for the service
OPTS = [
    cfg.IntOpt('workers',
               default=1,
               min=1,
               max=32,
               help='Number of workers for template evaluator.'
               ),
]

init_template_schemas()


text:
import json

from django import template
from django.utils.safestring import mark_safe

from churchill import VERSION

register = template.Library()

@register.simple_tag
def app_version():
    return VERSION

@register.filter(is_safe=True)
def jsonify(data):
    return mark_safe(json.dumps(data))

@register.filter(is_safe=True)
def jsonify_messages(messages):
    return mark_safe(
        json.dumps([{"level": m.level_tag, "message": m.message} for m in messages])
    )


text:
apilevel = '2.0'
# Threads may not share the module because multi_client is not thread safe.
threadsafety = 0
paramstyle = 'named'

from vtdb.cursorv3 import *
from vtdb.dbexceptions import *
from vtdb.field_types import STRING, BINARY, NUMBER, DATETIME, ROWID
from vtdb.times import Date, Time, Timestamp, DateFromTicks, TimeFromTicks, TimestampFromTicks
from vtdb.vtgatev2 import *
from vtdb.vtgatev3 import *


text:
void TestDictOf(void);
void TestDictOf(void) {
    NSDictionary *d = $dict({@"seq", @1},
                            {@"id", @"foo"},
                            {@"changes", @[@"hi"]});
    CAssertEqual(d[@"seq"], @1);
}

#if DEBUG

TestCase(DictOf) {
    NSDictionary* z = @{@"hi": @"there"};
    NSLog(@"%@",z);
    //typedef struct { __unsafe_unretained id key; __unsafe_unretained id value; } Pair;
    typedef id Pair[2];
    typedef Pair Pairs[];
    Pairs pairs= {
        {@"changes", @[@"hi"]}
    };
    NSLog(@"it's %@", pairs[0][1]);
    //NSDictionary* d = _dictof(pairs,sizeof(pairs)/sizeof(struct _dictpair));
    //CAssertEqual(d[@"changes"], @[@"hi"]);
}

@interface CBLChangeTrackerTester : NSObject <CBLChangeTrackerClient>
{
    NSMutableArray* _changes;
    BOOL _running, _finished;
}
@property (readonly) NSArray* changes;
@property NSArray* anchorCerts;
@property BOOL onlyTrustAnchorCerts;
@property BOOL checkedAnSSLCert;
@property (readonly) BOOL caughtUp, finished;
@end

@implementation CBLChangeTrackerTester

@synthesize changes=_changes, checkedAnSSLCert=_checkedAnSSLCert, caughtUp=_caughtUp, finished=_finished, anchorCerts=_anchorCerts, onlyTrustAnchorCerts=_onlyTrustAnchorCerts;

- (void) run: (CBLChangeTracker*)tracker expectingChanges: (NSArray*)expectedChanges {
    [tracker start];
    _running = YES;
    NSDate* timeout = [NSDate dateWithTimeIntervalSinceNow: 10];
    while (_running && _changes.count < expectedChanges.count
           && [timeout timeIntervalSinceNow] > 0
           && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
                                       beforeDate: timeout])
    {
        AssertNil(tracker.error);
    }

    [tracker stop];
    if ([timeout timeIntervalSinceNow] <= 0) {
        Warn(@"Timeout contacting %@", tracker.databaseURL);
        Assert(NO, @"Failed to contact %@", tracker.databaseURL);
        return;
    }
    AssertNil(tracker.error);
    CAssertEqual(_changes, expectedChanges);
}

- (void) run: (CBLChangeTracker*)tracker expectingError: (NSError*)error {
    [tracker start];
    _running = YES;
    NSDate* timeout = [NSDate dateWithTimeIntervalSinceNow: 60];
    while (_running && [timeout timeIntervalSinceNow] > 0
           && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
                                       beforeDate: timeout])
        ;
    Assert(!_running, @"-changeTrackerStoped: wasn't called");
    CAssertEqual(tracker.error.domain, error.domain);
    CAssertEq(tracker.error.code, error.code);
}

- (void) changeTrackerReceivedSequence:(id)sequence
                                 docID:(NSString *)docID
                                revIDs:(NSArray *)revIDs
                               deleted:(BOOL)deleted
{
    if (!_changes)
        _changes = [[NSMutableArray alloc] init];
    [_changes addObject: $dict({@"seq", sequence},
                               {@"id", docID},
                               {@"revs", revIDs},
                               {@"deleted", (deleted ? $true : nil)})];
}

- (void) changeTrackerCaughtUp {
    _caughtUp = YES;
}

- (void) changeTrackerFinished {
    _finished = YES;
}

- (void) changeTrackerStopped:(CBLChangeTracker *)tracker {
    _running = NO;
}

- (BOOL) changeTrackerApproveSSLTrust: (SecTrustRef)trust
                              forHost: (NSString*)host port: (UInt16)port
{
    self.checkedAnSSLCert = YES;

    if (_anchorCerts.count > 0) {
        SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)_anchorCerts);
        SecTrustSetAnchorCertificatesOnly(trust, _onlyTrustAnchorCerts);
    }

    SecTrustResultType result;
    OSStatus err = SecTrustEvaluate(trust, &result);
    if (err) {
        Warn(@"SecTrustEvaluate failed with err %d for host %@:%d", (int)err, host, port);
        return NO;
    }
    if (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)
        return YES;
    CBLWarnUntrustedCert(@"", trust);
    return NO;
}

@end

TestCase(CBLChangeTracker_Simple) {
    for (CBLChangeTrackerMode mode = kOneShot; mode <= kLongPoll; ++mode) {
        Log(@"Mode = %d ...", mode);
        CBLChangeTrackerTester* tester = [[CBLChangeTrackerTester alloc] init];
        NSURL* url = RemoteTestDBURL(@"attach-test");
        CBLChangeTracker* tracker = [[CBLChangeTracker alloc] initWithDatabaseURL: url mode: mode conflicts: NO lastSequence: nil client: tester];
        NSArray* expected = $array($dict({@"seq", @3},
                                         {@"id", @"038c536dc29ff0f4127705879700062c"},
                                         {@"revs", $array(@"3-e715bcf1865f8283ab1f0ba76e7a92ba")}),
                                   $dict({@"seq", @5},
                                         {@"id", @"oneBigAttachment"},
                                         {@"revs", $array(@"2-7a9086d57651b86882d4806bad25903c")}),
                                   $dict({@"seq", @6},
                                         {@"id", @"propertytest"},
                                         {@"revs", $array(@"1-132f0b3efda2b9126aa0b7565d47acd3")}),
                                   $dict({@"seq", @8},
                                         {@"id", @"text_attachment"},
                                         {@"revs", $array(@"2-116dc4ccc934971ae14d8a8afb29b023")}),
                                   $dict({@"seq", @11},
                                         {@"id", @"weirdmeta"},
                                         {@"revs", $array(@"1-eef1e19e2aa822dc3f1c62196cbe6746")}),
                                   $dict({@"seq", @12},
                                         {@"id", @"extrameta"},
                                         {@"revs", $array(@"1-11d28a27038a6cce1f08674ab3d67653")})
                                   );
        [tester run: tracker expectingChanges: expected];
    }
}

TestCase(CBLChangeTracker_SSL) {
    // First try without adding the custom root cert, which should fail:
    CBLChangeTrackerTester* tester = [[CBLChangeTrackerTester alloc] init];
    NSURL* url = [NSURL URLWithString: @"https://localhost:4994/public"];//FIX: Make portable
    CBLChangeTracker* tracker = [[CBLChangeTracker alloc] initWithDatabaseURL: url mode: kOneShot conflicts: NO lastSequence: 0 client:  tester];
    [tester run: tracker expectingError: [NSError errorWithDomain: NSURLErrorDomain
                                                             code:NSURLErrorServerCertificateUntrusted
                                                         userInfo: nil]];

    // Now get a copy of the server's certificate:
    NSData* certData = [NSData dataWithContentsOfFile: @"/Couchbase/sync_gateway/examples/ssl/cert.cer"];//FIX: Make portable
    Assert(certData, @"Couldn't load cert file");
    SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData);
    Assert(cert, @"Couldn't parse cert");

    // Retry, registering the server cert as a root:
    tester = [[CBLChangeTrackerTester alloc] init];
    tester.anchorCerts = @[(__bridge id)cert];
    tracker = [[CBLChangeTracker alloc] initWithDatabaseURL: url mode: kOneShot conflicts: NO lastSequence: 0 client:  tester];
    NSArray* expected = $array($dict({@"seq", @8},
                                     {@"id", @"foo"},
                                     {@"revs", $array(@"1-a154bf18a4d64ee6d93b6cc838b2b344")}),
                               $dict({@"seq", @9},
                                     {@"id", @"bar"},
                                     {@"revs", $array(@"1-a7a0e83c48d20397aed5703a06c01ea8")}),
                               $dict({@"seq", @11},
                                     {@"id", @"_user/GUEST"},
                                     {@"revs", $array()}),
                               );
    [tester run: tracker expectingChanges: expected];
    CAssert(tester.checkedAnSSLCert);
}

TestCase(CBLChangeTracker_Auth) {
    RequireTestCase(CBLChangeTracker_AuthFailure);
    // This database requires authentication to access at all.
    NSURL* url = RemoteTestDBURL(@"tdpuller_test2_auth");
    if (!url) {
        Warn(@"Skipping test; no remote DB URL configured");
        return;
    }
    CBLChangeTrackerTester* tester = [[CBLChangeTrackerTester alloc] init];
    AddTemporaryCredential(url, @"CouchDB", @"dummy", @"dummy");

    CBLChangeTracker* tracker = [[CBLChangeTracker alloc] initWithDatabaseURL: url mode: kOneShot conflicts: NO lastSequence: 0 client:  tester];
    NSArray* expected = $array($dict({@"seq", @1},
                                     {@"id", @"something"},
                                     {@"revs", $array(@"1-31e4c2faf5cfcd56f4518c29367f9124")}) );
    [tester run: tracker expectingChanges: expected];
}

TestCase(CBLChangeTracker_AuthFailure) {
    NSURL* url = RemoteTestDBURL(@"tdpuller_test2_auth");
    if (!url) {
        Warn(@"Skipping test; no remote DB URL configured");
        return;
    }
    // Add a bogus user to make auth fail:
    NSString* urlStr = url.absoluteString;
    urlStr = [urlStr stringByReplacingOccurrencesOfString: @"http://" withString: @"http://bogus@"];
    url = $url(urlStr);

    CBLChangeTrackerTester* tester = [[CBLChangeTrackerTester alloc] init];

    CBLChangeTracker* tracker = [[CBLChangeTracker alloc] initWithDatabaseURL: url mode: kOneShot conflicts: NO lastSequence: 0 client:  tester];
    [tester run: tracker expectingError: CBLStatusToNSError(kCBLStatusUnauthorized, url)];
}

TestCase(CBLWebSocketChangeTracker_Auth) {
    // This Sync Gateway database requires authentication to access at all.
    NSURL* url = $url(@"http://localhost:4984/cbl_auth_test"); //TEMP
    if (!url) {
        Warn(@"Skipping test; no remote DB URL configured");
        return;
    }
    CBLChangeTrackerTester* tester = [[CBLChangeTrackerTester alloc] init];
    CBLChangeTracker* tracker = [[CBLChangeTracker alloc] initWithDatabaseURL: url mode: kWebSocket conflicts: NO lastSequence: 0 client:  tester];

    NSURLCredential* c = [NSURLCredential credentialWithUser: @"test" password: @"abc123"
                                                 persistence: NSURLCredentialPersistenceForSession];
    tracker.authorizer = [[CBLBasicAuthorizer alloc] initWithCredential: c];

    NSArray* expected = $array($dict({@"seq", @1},
                                     {@"id", @"_user/test"},
                                     {@"revs", $array()}) ,
                               $dict({@"seq", @2},
                                     {@"id", @"something"},
                                     {@"revs", $array(@"1-53b059eb633a9d58042318e478cc73dc")}) );
    [tester run: tracker expectingChanges: expected];
}

TestCase(CBLChangeTracker_Retry) {
#if 0 // This test takes 31 seconds to run, so let's leave it turned off normally
    // Intentionally connect to a nonexistent server to see the retry logic.
    CBLChangeTrackerTester* tester = [[[CBLChangeTrackerTester alloc] init] autorelease];
    NSURL* url = [NSURL URLWithString: @"https://localhost:5999/db"];

    CBLChangeTracker* tracker = [[[CBLChangeTracker alloc] initWithDatabaseURL: url mode: kOneShot conflicts: NO lastSequence: 0 client:  tester] autorelease];
    [tester run: tracker expectingError: [NSError errorWithDomain: NSURLErrorDomain code: NSURLErrorCannotConnectToHost userInfo: nil]];
#endif
}

TestCase(CBLChangeTracker) {
    RequireTestCase(CBLChangeTracker_Simple);
    RequireTestCase(CBLChangeTracker_SSL);
    RequireTestCase(CBLChangeTracker_Auth);
    RequireTestCase(CBLChangeTracker_AuthFailure);
    RequireTestCase(CBLChangeTracker_Retry);
    RequireTestCase(CBLWebSocketChangeTracker_Auth);
}

#endif // DEBUG


text:
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}

{-# OPTIONS -Wall #-}
module Statistics.Iteratee.Sample (
  minMaxNBy
, range
, mean
, harmonicMean
, variance
, stdDev
) where

import Statistics.Iteratee.Compat
import Control.Arrow
import Control.Monad
import Data.Iteratee as I

import Data.Heap as Heap

--  | /O(n)/ minMaxNBy. Calculate the 'n' highest and lowest elements of the
--  stream, according to the given priority function.
--  Returns /([minimum],[maximum]/ with the /(minimum,maximum)/
--  elements listed first.
minMaxNBy
  :: forall m prio s el. (Monad m, Ord prio, ListLikey s el)
  => Int
  -> (el -> prio)
  -> Iteratee s m ([(prio,el)],[(prio,el)])
minMaxNBy ns prio = finalize `liftM` I.foldl' step (Heap.empty,Heap.empty)
  where
    finalize :: (MaxPrioHeap prio el, MinPrioHeap prio el)
             -> ([(prio,el)],[(prio,el)])
    finalize = Heap.toDescList *** Heap.toDescList
    addHeap val = Heap.insert (prio val, val)
    step :: (MaxPrioHeap prio el, MinPrioHeap prio el) -> el
            -> (MaxPrioHeap prio el, MinPrioHeap prio el)
    step (!mins,!maxes) val = let sz = Heap.size mins
                                  adj hp = if sz >= ns
                                             then Heap.drop 1 hp
                                             else hp
                              in (adj $ addHeap val mins
                                 ,adj $ addHeap val maxes)
{-# INLINE minMaxNBy #-}

-- | /O(n)/ Range. The difference between the largest and smallest elements of
-- a stream.
range :: (Monad m, ListLikey s el, Num el, Ord el)
      => Iteratee s m el
range = finalize `liftM` minMaxNBy 1 id
  where
    finalize ([mins],[maxes]) = snd maxes - snd mins
    finalize _ = 0
{-# INLINE range #-}

-- | /O(n)/ Arithmetic mean.  Uses Welford's algorithm.
mean :: forall s m el. (Fractional el, Monad m, ListLikey s el)
     => Iteratee s m el
mean = fst `liftM` I.foldl' step (0,0)
  where
    step :: (el,Integer) -> el -> (el,Integer)
    step (!m,!n) x = let m' = m + (x-m) / fromIntegral n'
                         n' = n + 1
                     in  (m',n')
{-# INLINE mean #-}

-- | /O(n)/ Harmonic mean.
harmonicMean :: (Fractional el, Monad m, ListLikey s el) => Iteratee s m el
harmonicMean = finalize `liftM` I.foldl' step (0,0 :: Integer)
  where
    finalize (m,n) = fromIntegral n / m
    step (!m,!n) val = (m+(1/val),n+1)
{-# INLINE harmonicMean #-}

-- | /O(n)/ variance, using Knuth's algorithm.
var :: (Fractional el, Integral t, Monad m, ListLikey s el)
    => Iteratee s m (t, el, el)
var = I.foldl' step (0,0,0)
  where
    step (!n,!m,!s) x = let n' = n+1
                            m' = m+d/fromIntegral n'
                            s' = s+d* (x-m')
                            d  = x-m
                        in (n',m',s')
{-# INLINE var #-}

-- | /O(n)/ Maximum likelihood estimate of a sample's variance, using Knuth's
--   algorithm.
variance :: (Fractional b, Monad m, ListLikey s b) => Iteratee s m b
variance = finalize `liftM` var
  where
    finalize (n,_,s)
      | n > 1 = s / fromInteger n
      | otherwise = 0
{-# INLINE variance #-}

-- | /O(n) Standard deviation, using Knuth's algorithm.
stdDev :: (Floating b, Monad m, Functor m, ListLikey s b) => Iteratee s m b
stdDev = sqrt `liftM` variance
{-# INLINE stdDev #-}


text:
<?php

namespace MemcachedManager\Exceptions;

class SocketConnectionException extends \Exception
{

}


text:
"""Mrs Worker

The worker process executes the user's map function and reduce function.
That's it.  It just does what the main slave process tells it to.  The worker
process is terminated when the main process quits.
"""

import os
import traceback

from . import datasets
from . import tasks
from . import util

from logging import getLogger
logger = getLogger('mrs')

class WorkerSetupRequest(object):
    """Request the worker to run the setup function."""

    def __init__(self, opts, args, default_dir):
        self.id = 'worker_setup'
        self.opts = opts
        self.args = args
        self.default_dir = default_dir

    def id(self):
        return self.__class__.__name__

class WorkerRemoveRequest(object):
    def __init__(self, *args):
        (self.directory,) = args

    def id(self):
        return self.__class__.__name__

class WorkerTaskRequest(object):
    """Request the to worker to run a task."""

    def __init__(self, *args):
        _, _, self.dataset_id, self.task_index, _, _, _, _, _ = args
        self.args = args

    def id(self):
        return '%s_%s_%s' % (self.__class__.__name__, self.dataset_id,
                self.task_index)

class WorkerQuitRequest(object):
    """Request the worker to quit."""

class WorkerFailure(object):
    """Failure response from worker."""
    def __init__(self, dataset_id, task_index, exception, traceback,
            request_id):
        self.dataset_id = dataset_id
        self.task_index = task_index
        self.exception = exception
        self.traceback = traceback
        self.request_id = request_id

class WorkerSetupSuccess(object):
    """Successful worker setup."""

class WorkerSuccess(object):
    """Successful response from worker."""
    def __init__(self, dataset_id, task_index, outdir, outurls, request_id):
        self.dataset_id = dataset_id
        self.task_index = task_index
        self.outdir = outdir
        self.outurls = outurls
        self.request_id = request_id

class Worker(object):
    """Execute map tasks and reduce tasks.

    The worker waits for other threads to make assignments by calling
    start_map and start_reduce.

    This needs to run in a daemon thread rather than in the main thread so
    that it can be killed by other threads.
    """
    def __init__(self, program_class, request_pipe):
        self.program_class = program_class
        self.request_pipe = request_pipe
        self.default_dir = None
        self.program = None
        self.opts = None
        self.args = None

    def run(self):
        while self.run_once():
            pass

    def run_once(self):
        """Runs one iteration of the event loop.

        Returns True if it should keep running.
        """
        request = None
        response = None

        try:
            request = self.request_pipe.recv()

            if isinstance(request, WorkerSetupRequest):
                assert self.program is None
                self.opts = request.opts
                self.args = request.args
                logger.debug('Starting to run the user setup function.')
                util.log_ram_usage()
                self.program = self.program_class(self.opts, self.args)
                self.default_dir = request.default_dir
                response = WorkerSetupSuccess()

            elif isinstance(request, WorkerQuitRequest):
                return False

            elif isinstance(request, WorkerRemoveRequest):
                util.remove_recursive(request.directory)

            else:
                assert self.program is not None
                logger.info('Running task: %s, %s' %
                        (request.dataset_id, request.task_index))
                util.log_ram_usage()
                max_sort_size = getattr(self.opts, 'mrs__max_sort_size', None)
                t = tasks.Task.from_args(*request.args, program=self.program)
                t.run(self.program, self.default_dir,
                        max_sort_size=max_sort_size)
                response = WorkerSuccess(request.dataset_id,
                        request.task_index, t.outdir, t.outurls(),
                        request.id())
                logger.info('Completed task: %s, %s' %
                        (request.dataset_id, request.task_index))
                util.log_ram_usage()
        except KeyboardInterrupt:
            return
        except Exception as e:
            logger.info('Failed task: %s, %s' %
                    (request.dataset_id, request.task_index))
            request_id = request.id() if request else None
            tb = traceback.format_exc()
            response = WorkerFailure(request.dataset_id, request.task_index,
                    e, tb, request_id)

        if response:
            self.request_pipe.send(response)

        return True

    def profiled_run(self):
        #TODO: detect the node number for other systems (e.g., pbs)
        nodenum = os.getenv('PSSH_NODENUM')
        if nodenum:
            filename = 'mrs-worker-%s.prof' % nodenum
        else:
            filename = 'mrs-worker.prof'
        util.profile_loop(self.run_once, (), {}, filename)

class WorkerManager(object):
    """Mixin class that provides methods for dealing with Workers.

    Assumes that a worker_pipe attribute is defined and that read_worker_pipe
    is called when data is available.  Also assumes that a current_task
    attribute is available.
    """
    def worker_setup(self, opts, args, default_dir):
        request = WorkerSetupRequest(opts, args, default_dir)
        self.worker_pipe.send(request)
        response = self.worker_pipe.recv()
        if isinstance(response, WorkerSetupSuccess):
            return True
        if isinstance(response, WorkerFailure):
            msg = 'Exception in Worker Setup: %s' % response.exception
            logger.critical(msg)
            msg = 'Traceback: %s' % response.traceback
            logger.error(msg)
            return False
        else:
            raise RuntimeError('Invalid message type.')

    def read_worker_pipe(self):
        """Reads a single response from the worker pipe."""

        r = self.worker_pipe.recv()
        if not (isinstance(r, WorkerSuccess) or isinstance(r, WorkerFailure)):
            assert False, 'Unexpected response type'

        assert self.current_task == (r.dataset_id, r.task_index)
        self.current_task = None

        if isinstance(r, WorkerSuccess):
            self.worker_success(r)
        elif isinstance(r, WorkerFailure):
            msg = 'Exception in Worker: %s' % r.exception
            logger.critical(msg)
            msg = 'Traceback: %s' % r.traceback
            logger.error(msg)

            self.worker_failure(r)

    def submit_request(self, request):
        """Submit the given request to the worker.

        If one_at_a_time is specified, then no other one_at_time requests can
        be accepted until the current task finishes.  Returns a boolean
        indicating whether the request was accepted.

        Called from the RPC thread.
        """
        if isinstance(request, WorkerTaskRequest):
            if self.current_task is not None:
                return False
            self.current_task = (request.dataset_id, request.task_index)

        self.worker_pipe.send(request)
        return True

    def worker_success(self, response):
        """Called when a worker sends a WorkerSuccess for the given task."""
        raise NotImplementedError

    def worker_failure(self, response):
        """Called when a worker sends a WorkerFailure for the given task."""
        raise NotImplementedError

# vim: et sw=4 sts=4


text:
module RaygunClient
  module HTTP
    class Post
      include Log::Dependency

      setting :api_key

      attr_reader :data

      dependency :telemetry, ::Telemetry

      def self.build
        new.tap do |instance|
          RaygunClient::Settings.set(instance)

          ::Telemetry.configure instance
        end
      end

      def self.configure(receiver, attr_name=nil)
        attr_name ||= :raygun_post
        build.tap do |instance|
          receiver.send "#{attr_name}=", instance
        end
      end

      def self.call(data)
        instance = build
        instance.(data)
      end

      def call(data)
        logger.trace "Posting to Raygun"
        json_text = Transform::Write.(data, :json)

        response = post json_text

        record_posted data, response

        logger.info "Posted to Raygun (#{LogText::Posted.(data, response)})"

        response
      end

      def self.host
        'api.raygun.io'
      end

      def self.path
        '/entries'
      end

      def self.uri
        @uri ||= URI::HTTPS.build :host => host, :path => path
      end

      def record_posted(data, response)
        telemetry_data = Telemetry::Data.new data, response

        telemetry.record :posted, telemetry_data

        telemetry_data
      end

      def post(request_body)
        uri = self.class.uri

        Net::HTTP.start uri.host, uri.port, :use_ssl => uri.scheme == 'https' do |http|
          http.request_post uri.path, request_body, 'X-ApiKey' => api_key
        end
      end

      def self.register_telemetry_sink(post)
        sink = Telemetry.sink
        post.telemetry.register sink
        sink
      end

      def self.logger
        @logger ||= Log.get self
      end

      module Telemetry
        class Sink
          include ::Telemetry::Sink

          record :posted

          module Assertions
            def posts(&blk)
              if blk.nil?
                return posted_records
              end

              posted_records.select do |record|
                blk.call(record.data.data, record.data.response)
              end
            end

            def posted?(&blk)
              if blk.nil?
                return recorded_posted?
              end

              recorded_posted? do |record|
                blk.call(record.data.data, record.data.response)
              end
            end
          end
        end

        Data = Struct.new :data, :response

        def self.sink
          Sink.new
        end
      end

      module Substitute
        def self.build
          Substitute::Post.build.tap do |substitute|
            sink = RaygunClient::HTTP::Post.register_telemetry_sink(substitute)
            substitute.sink = sink
          end
        end

        class Post < Post
          attr_accessor :status_code
          attr_accessor :reason_phrase
          attr_accessor :sink

          def call(post_data)
            response = OpenStruct.new(
              :code => status_code,
              :message => reason_phrase
            )

            record_posted post_data, response
          end

          def set_response(status_code, reason_phrase: nil)
            self.reason_phrase = reason_phrase if reason_phrase
            self.status_code = status_code.to_s
          end

          def self.build
            new.tap do |instance|
              ::Telemetry.configure instance
            end
          end
        end
      end

      module LogText
        module Posted
          def self.call(data, response)
            "StatusCode: #{response.code}, ReasonPhrase: #{response.message}, ErrorMessage: #{data.error.message}, CustomData: #{data.custom_data || '(none)'})"
          end
        end
      end
    end
  end
end


text:
package com.github.s4ke.moar.regex;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

import com.github.s4ke.moar.moa.Moa;
import com.github.s4ke.moar.moa.edgegraph.EdgeGraph;
import com.github.s4ke.moar.moa.states.State;
import com.github.s4ke.moar.moa.states.Variable;

/**
 * @author Martin Braun
 */
final class Concat implements Regex {

	private final Regex fst;
	private final Regex snd;

	Concat(Regex fst, Regex snd) {
		this.fst = fst;
		this.snd = snd;
	}

	@Override
	public String toString() {
		return this.fst.toString() + this.snd.toString();
	}

	@Override
	public Regex copy() {
		return new Concat( this.fst.copy(), this.snd.copy() );
	}

	@Override
	public void contributeStates(
			Map<String, Variable> variables,
			Set<State> states,
			Map<Regex, Map<String, State>> selfRelevant,
			Supplier<Integer> idxSupplier) {
		this.fst.contributeStates( variables, states, selfRelevant, idxSupplier );
		this.snd.contributeStates( variables, states, selfRelevant, idxSupplier );
	}

	@Override
	public void contributeEdges(
			EdgeGraph edgeGraph,
			Map<String, Variable> variables,
			Set<State> states,
			Map<Regex, Map<String, State>> selfRelevant) {
		EdgeGraph eg1 = new EdgeGraph();
		for ( State state : states ) {
			eg1.addState( state );
		}
		this.fst.contributeEdges( eg1, variables, states, selfRelevant );

		EdgeGraph eg2 = new EdgeGraph();
		for ( State state : states ) {
			eg2.addState( state );
		}
		this.snd.contributeEdges( eg2, variables, states, selfRelevant );

		Map<State, Set<EdgeGraph.Edge>> snkEdges = new HashMap<>();
		Set<EdgeGraph.Edge> srcEdges = new HashSet<>();

		for ( State state : states ) {
			Collection<EdgeGraph.Edge> edges = eg1.getEdges( state );
			for ( EdgeGraph.Edge edge : edges ) {
				if ( !edge.destination.equals( Moa.SNK.getIdx() ) ) {
					edgeGraph.addEdgeWithDeterminismCheck( state, edge, this );
				}
				else {
					snkEdges.computeIfAbsent( state, (key) -> new HashSet<>() ).add( edge );
				}
			}
		}

		for ( State state : states ) {
			Collection<EdgeGraph.Edge> edges = eg2.getEdges( state );
			for ( EdgeGraph.Edge edge : edges ) {
				if ( state.getIdx() != (Moa.SRC.getIdx()) ) {
					edgeGraph.addEdgeWithDeterminismCheck( state, edge, this );
				}
				else {
					srcEdges.add( edge );
				}
			}
		}

		for ( Map.Entry<State, Set<EdgeGraph.Edge>> snkEdgeEntry : snkEdges.entrySet() ) {
			State toSnkState = snkEdgeEntry.getKey();
			for ( EdgeGraph.Edge snkEdge : snkEdgeEntry.getValue() ) {
				for ( EdgeGraph.Edge srcEdge : srcEdges ) {
					Integer fromSrcState = srcEdge.destination;
					edgeGraph.addEdgeWithDeterminismCheck(
							toSnkState, new EdgeGraph.Edge(
									Moa.f(
											snkEdge.memoryAction,
											srcEdge.memoryAction
									), fromSrcState
							),
							this
					);
				}
			}
		}
	}

	@Override
	public void calculateVariableOccurences(Map<String, Variable> variables, Supplier<Integer> varIdxSupplier) {
		this.fst.calculateVariableOccurences( variables, varIdxSupplier );
		this.snd.calculateVariableOccurences( variables, varIdxSupplier );
	}
}


text:
class CamCompress
{
public:
    CamCompress()
    {
        experiment_init_pub_ = nh_.advertise<std_msgs::Bool>("/experiment_started", 1);
        secondaryTask_init_pub_ = nh_.advertise<std_msgs::Bool>("/secondary_task/started", 1);
        secondaryTask_end_pub_ = nh_.advertise<std_msgs::Bool>("/secondary_task/ended", 1);
        noiseReset_pub_ = nh_.advertise<std_msgs::Bool>("/noise_reset", 1);

        joy_sub_ = nh_.subscribe<sensor_msgs::Joy>("/joy", 2 , &CamCompress::joyPublishedCallBack,this);
        joy2_sub_ = nh_.subscribe<sensor_msgs::Joy>("/joy2", 2 , &CamCompress::joy2PublishedCallBack,this);
        clearCostmapSrv_ = nh_.serviceClient<std_srvs::Empty>("move_base/clear_costmaps") ;
    }

private:
    ros::NodeHandle nh_;
    ros::Publisher experiment_init_pub_ , secondaryTask_init_pub_, secondaryTask_end_pub_, noiseReset_pub_;
    ros::Subscriber joy_sub_ , joy2_sub_;
    ros::ServiceClient clearCostmapSrv_ ;

    void joyPublishedCallBack(const sensor_msgs::Joy::ConstPtr& msg);
    void joy2PublishedCallBack(const sensor_msgs::Joy::ConstPtr& msg);
};

void CamCompress::joyPublishedCallBack(const sensor_msgs::Joy::ConstPtr& msg)
{

}

void CamCompress::joy2PublishedCallBack(const sensor_msgs::Joy::ConstPtr& msg)
{
    if (msg->buttons[7] == true) // denotes when the trials starts and when it finishes (START<!-- change this /jsX depending on your joystick port --> button)
    {
        std_msgs::Bool started;
        started.data = true;
        experiment_init_pub_.publish(started);
    }

    if (msg->buttons[2] == true) // denotes when the secondary task starts (X)
    {
        std_msgs::Bool started;
        started.data = true;
        secondaryTask_init_pub_.publish(started);
    }

    if (msg->buttons[1] == true)  // denotes when the secondary task finishes (B)
    {
        std_msgs::Bool ended;
        ended.data = true;
        secondaryTask_end_pub_.publish(ended);
    }

    if (msg->buttons[0] == true)  // resets sensor noise node so it can start again on the way back (A)
    {
        std_msgs::Bool reset;
        reset.data = true;
        noiseReset_pub_.publish(reset);
    }

    if (msg->buttons[3] == true)  // Clears cost maps (Y)
    {
        std_srvs::Empty srv ;
        clearCostmapSrv_.call(srv);
    }

}

int main(int argc, char** argv)
{
    ros::init(argc, argv, "experiment_logger");
    CamCompress experimentLogger;

    ros::spin();

}


text:
#region License Header

#endregion License Header

using FluentAssertions;
using Quantler.Data;
using Quantler.Data.Market;
using Quantler.Securities;
using System;
using Xunit;
using Xunit.Abstractions;

namespace Quantler.Tests.Core.Data.Market
{
    public class TradingStatusTests
    {
        #region Private Fields

        /// <summary>
        /// The output
        /// </summary>
        private readonly ITestOutputHelper _output;

        #endregion Private Fields

        #region Public Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="TickTests"/> class.
        /// </summary>
        /// <param name="output">The output.</param>
        public TradingStatusTests(ITestOutputHelper output) =>
            _output = output;

        #endregion Public Constructors

        #region Private Properties

        /// <summary>
        /// System under test
        /// </summary>
        private TradingStatus Sut => new TradingStatus
        {
            DataType = DataType.TradingStatus,
            IsBackfilling = false,
            Occured = DateTime.UtcNow,
            Reason = "Testing",
            Status = "H",
            Ticker = TickerSymbol.NIL("TST"),
            TimeZone = TimeZone.Auckland
        };

        #endregion Private Properties

        #region Public Methods

        [Fact]
        [Trait("Quantler.Core.Data.Market", "TradingStatus")]
        public void Tick_SerializeDeserialize()
        {
            //Act
            var serialized = Sut.Serialize();
            var deserialized = DataPointImpl.Deserialize(serialized, true) as TradingStatus;

            //Assert
            serialized.Length.Should().BePositive();
            deserialized.Should().NotBeNull();
            deserialized.OccuredUtc.Should().NotBe(Sut.Occured);
            deserialized.Reason.Should().Be(Sut.Reason);
            deserialized.Status.Should().Be(Sut.Status);
        }

        [Fact]
        [Trait("Quantler.Core.Data.Market", "TradingStatus")]
        public void Tick_SerializeJson()
        {
            //Act
            var result = Sut.SerializeJson();
            _output.WriteLine(result);

            //Assert
            result.Should().NotBeNullOrWhiteSpace();
        }

        #endregion Public Methods
    }
}