text:
using UnityEngine;

#if UNITY_EDITOR

using UnityEditor;

#endif

using System.Collections.Generic;

[System.Serializable]
public class SpSource
{
    public SpFlag Flag = SpFlag.JustCreated;

    public string Identifier; // Texture/Sprite GUID

    public bool Dirty = true;

    public bool Trim;

    public int PadSize;

    public SpPadStyle PadStyle;

    public bool UseCustomPivot;

    public Vector2 CustomPivot = new Vector2(0.5f, 0.5f);

    public bool UseCustomBorder;

    public Vector4 CustomBorder;

#if UNITY_EDITOR

    public string Path
    {
        get
        {
            return UnityEditor.AssetDatabase.GUIDToAssetPath(Identifier);
        }
    }

    public string Name
    {
        get
        {
            var texture = Texture;

            if (texture != null)
            {
                return texture.name;
            }

            return "(Missing)";
        }
    }

    public Texture2D Texture
    {
        get
        {
            var path = Path;

            if (string.IsNullOrEmpty(path) == false)
            {
                return UnityEditor.AssetDatabase.LoadMainAssetAtPath(path) as Texture2D;
            }

            return null;
        }
    }

    public List<Sprite> Sprites
    {
        get
        {
            var sprites = new List<Sprite>();
            var path = Path;

            if (string.IsNullOrEmpty(path) == false)
            {
                foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path))
                {
                    var sprite = asset as Sprite;

                    if (sprite != null)
                    {
                        sprites.Add(sprite);
                    }
                }
            }

            return sprites;
        }
    }

    public List<Sprite> FindSprites(List<Sprite> atlasSprites, List<Sprite> sourceSprites)
    {
        var foundSprites = new List<Sprite>();

        for (var i = 0; i < sourceSprites.Count; i++)
        {
            foundSprites.Add(atlasSprites.Find(s => s.name == sourceSprites[i].name));
        }

        return foundSprites;
    }

#endif
}


text:
**How to get current date and time?**
- DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  Calendar cal = Calendar.getInstance();
  System.out.println(dateFormat.format(cal.getTime()));

**Why can't I get variable value from edit control**
- view defined inner class should be defined as final, so the value would not change

**Why my BaseAdapter's data not changed?**
- notifyDataSetChanged() to notify adapter that the listView has changed.

**How to receive multiple value through Intent?**
- _Intent returnIntent = new Intent();_
_returnIntent.putExtra("title",titleField.getText().toString());_
_returnIntent.putExtra("year",yearField.getText().toString());_
_setResult(RESULT_OK,returnIntent);_
_finish();_

- _tempTitle = data.getStringExtra("title");
tempYear =  data.getStringExtra("year");_
- http://stackoverflow.com/questions/17996221/how-to-receive-multiple-values-using-an-intent

**How to Change remote github url?**
- git remote set-url origin git@github.com:JackZhongTJ/cosi153a-Expenselog.git

**How to Pass an Object through intent?**
- Two way: Serializable and Parcelable

****
Reference:
- http://www.pcsalt.com/android/listview-using-baseadapter-android/
- https://github.com/krrishnaaaa/CustomListViewDemo
- http://stackoverflow.com/questions/10407159/how-to-manage-startactivityforresult-on-android

redpajama_set_name: RedPajamaGithub


text:
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="description" content="{{ default .Site.Params.description .Description }}" />


text:
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace python { namespace converter {

template <class Source, class Target>
struct implicit
{
    static void* convertible(PyObject* obj)
    {
        // Find a converter which can produce a Source instance from
        // obj. The user has told us that Source can be converted to
        // Target, and instantiating construct() below, ensures that
        // at compile-time.
        return implicit_rvalue_convertible_from_python(obj, registered<Source>::converters)
            ? obj : 0;
    }

    static void construct(PyObject* obj, rvalue_from_python_stage1_data* data)
    {
        void* storage = ((rvalue_from_python_storage<Target>*)data)->storage.bytes;

        arg_from_python<Source> get_source(obj);
        bool convertible = get_source.convertible();
        BOOST_VERIFY(convertible);

        new (storage) Target(get_source());

        // record successful construction
        data->convertible = storage;
    }
};

}}} // namespace pdalboost::python::converter

#endif // IMPLICIT_DWA2002326_HPP


text:
package openanalytics

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// QueryEndPointList invokes the openanalytics.QueryEndPointList API synchronously
// api document: https://help.aliyun.com/api/openanalytics/queryendpointlist.html
func (client *Client) QueryEndPointList(request *QueryEndPointListRequest) (response *QueryEndPointListResponse, err error) {
	response = CreateQueryEndPointListResponse()
	err = client.DoAction(request, response)
	return
}

// QueryEndPointListWithChan invokes the openanalytics.QueryEndPointList API asynchronously
// api document: https://help.aliyun.com/api/openanalytics/queryendpointlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) QueryEndPointListWithChan(request *QueryEndPointListRequest) (<-chan *QueryEndPointListResponse, <-chan error) {
	responseChan := make(chan *QueryEndPointListResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.QueryEndPointList(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// QueryEndPointListWithCallback invokes the openanalytics.QueryEndPointList API asynchronously
// api document: https://help.aliyun.com/api/openanalytics/queryendpointlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) QueryEndPointListWithCallback(request *QueryEndPointListRequest, callback func(response *QueryEndPointListResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *QueryEndPointListResponse
		var err error
		defer close(result)
		response, err = client.QueryEndPointList(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// QueryEndPointListRequest is the request struct for api QueryEndPointList
type QueryEndPointListRequest struct {
	*requests.RpcRequest
	UserID requests.Integer `position:"Body" name:"UserID"`
}

// QueryEndPointListResponse is the response struct for api QueryEndPointList
type QueryEndPointListResponse struct {
	*responses.BaseResponse
	RequestId    string             `json:"RequestId" xml:"RequestId"`
	RegionId     string             `json:"RegionId" xml:"RegionId"`
	EndPointList []EndPointListItem `json:"EndPointList" xml:"EndPointList"`
}

// CreateQueryEndPointListRequest creates a request to invoke QueryEndPointList API
func CreateQueryEndPointListRequest() (request *QueryEndPointListRequest) {
	request = &QueryEndPointListRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("openanalytics", "2018-03-01", "QueryEndPointList", "openanalytics", "openAPI")
	return
}

// CreateQueryEndPointListResponse creates a response to parse from QueryEndPointList response
func CreateQueryEndPointListResponse() (response *QueryEndPointListResponse) {
	response = &QueryEndPointListResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
module Azure::CognitiveServices::FormRecognizer::V1_0_preview
  module Models
    #
    # Contract to initiate a train request.
    #
    class TrainRequest

      include MsRestAzure

      # @return [String] Get or set source path.
      attr_accessor :source

      # @return [TrainSourceFilter] Get or set filter to further search the
      # source path for content.
      attr_accessor :source_filter

      #
      # Mapper for TrainRequest class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'TrainRequest',
          type: {
            name: 'Composite',
            class_name: 'TrainRequest',
            model_properties: {
              source: {
                client_side_validation: true,
                required: true,
                serialized_name: 'source',
                constraints: {
                  MaxLength: 2048,
                  MinLength: 0
                },
                type: {
                  name: 'String'
                }
              },
              source_filter: {
                client_side_validation: true,
                required: false,
                serialized_name: 'sourceFilter',
                type: {
                  name: 'Composite',
                  class_name: 'TrainSourceFilter'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
require 'test_helper'
class MultiMeasureTestTest < ActiveJob::TestCase
  def setup
    @vendor = FactoryBot.create(:vendor)
    @bundle = FactoryBot.create(:static_bundle)
  end

  def setup_extra_measures
    cloned_cv = Measure.where(hqmf_id: 'BE65090C-EB1F-11E7-8C3F-9A214CF093AE').first.clone
    cloned_proportion = Measure.where(hqmf_id: '40280382-5FA6-FE85-0160-0918E74D2075').first.clone
    cloned_cv.hqmf_id = 'AE65090C-EB1F-11E7-8C3F-9A214CF093AE'
    cloned_cv.reporting_program_type = 'eh'
    cloned_cv.save
    cloned_proportion.hqmf_id = '50280382-5FA6-FE85-0160-0918E74D2075'
    cloned_proportion.reporting_program_type = 'eh'
    cloned_proportion.save
  end

  def test_multi_measure_test_creation_with_two_ep
    measure_ids = %w[BE65090C-EB1F-11E7-8C3F-9A214CF093AE 40280382-5FA6-FE85-0160-0918E74D2075]
    product = @vendor.products.create(name: "my product #{rand}", cvuplus: true, randomize_patients: true, duplicate_patients: true,
                                      bundle_id: @bundle.id)

    params = { measure_ids: measure_ids, 'cvuplus' => 'true' }
    product.update_with_tests(params)
    assert_equal true, product.save, 'should save with two measure ids'
    assert_equal 1, product.product_tests.multi_measure_tests.size, 'should have with one product test'
    assert_equal 'MultiMeasureTest', product.product_tests.first._type, 'should be a mutli measure test'
  end

  def test_multi_measure_test_creation_with_two_ep_two_eh
    setup_extra_measures
    measure_ids = %w[BE65090C-EB1F-11E7-8C3F-9A214CF093AE
                     40280382-5FA6-FE85-0160-0918E74D2075
                     AE65090C-EB1F-11E7-8C3F-9A214CF093AE
                     50280382-5FA6-FE85-0160-0918E74D2075]
    product = @vendor.products.create(name: "my product #{rand}", cvuplus: true, randomize_patients: true, duplicate_patients: true,
                                      bundle_id: @bundle.id)

    params = { measure_ids: measure_ids, 'cvuplus' => 'true' }
    product.update_with_tests(params)
    assert_equal 2, product.product_tests.multi_measure_tests.size, 'should have with two product test'
    ep_measure_test = product.product_tests.where(name: 'EC Measures').first
    eh_measure_test = product.product_tests.where(name: 'EH Measures').first
    assert_equal 'MultiMeasureCat3Task', ep_measure_test.tasks.first._type, 'an ep multi measure test should have a cat 3 task'
    assert_equal 'MultiMeasureCat1Task', eh_measure_test.tasks.first._type, 'an eh multi measure test should have a cat 1 task'
    assert_equal 2, ep_measure_test.measures.size, 'the ep multi measure test should be for 2 measures'
    assert_equal 1, ep_measure_test.tasks.size, 'a multi measure test (ep or eh) should only have a single task'
  end
end


text:
import { Component, HostListener, Input, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { ScrollService } from '../../../services/scroll-service';

const MIN_NAV_WIDTH = 1285;

@Component({
    selector: 'app-page-container',
    templateUrl: './page-container.component.html',
    styleUrls: ['./page-container.component.css']
})
export class PageContainerComponent implements OnInit {
    @Input() showTitle = true;
    @Input() showPrivacy = true;
    @Input() showBanner = false;
    title = 'SYDNEY GENOMICS COLLABORATIVE';
    smallTitle = 'SGC';
    showHamburger = false;

    @HostListener('window:resize') windowResized() {
        this.showHamburger = window.innerWidth <= MIN_NAV_WIDTH;
    }

    constructor(private router: Router,
                private scrollService: ScrollService) {
        this.windowResized();
        this.router.events
            .filter((x, idx) => x instanceof NavigationEnd)
            .subscribe(() => {
                window.scrollTo(0, 0);
            });
    }

    ngOnInit() {

    }

    updateScroll($event: any) {
        this.scrollService.scroll($event);
    }
}


text:
<template name="sysopSidebar">

        {{ i18n 'sidebar.saleOverview' }}

        {{ i18n 'sidebar.jobsMonitor' }}

</template>


text:
namespace PokerTell.Statistics.ViewModels.StatisticsSetSummary
{
    using PokerTell.Infrastructure.Enumerations.PokerHand;
    using PokerTell.Infrastructure.Interfaces.Statistics;

    using Tools.WPF.ViewModels;

    public class StatisticsSetSummaryRowViewModel : NotifyPropertyChanged, IStatisticsSetSummaryRowViewModel
    {
        readonly IBarGraphViewModel _barGraph;

        string _percentage;

        public StatisticsSetSummaryRowViewModel(ActionSequences actionSequence, IBarGraphViewModel barGraph)
        {
            _barGraph = barGraph;
            ActionLetter = ActionSequencesUtility.GetLastActionIn(actionSequence).ToString();
        }

        public string ActionLetter { get; private set; }

        public IBarGraphViewModel BarGraph
        {
            get { return _barGraph; }
        }

        public string Percentage
        {
            get { return _percentage; }
            private set
            {
                _percentage = value;
                RaisePropertyChanged(() => Percentage);
            }
        }

        public IStatisticsSetSummaryRowViewModel UpdateWith(int percentage, int[] percentagesByColumn)
        {
            Percentage = string.Format("{0:0#}", percentage);

            BarGraph.UpdateWith(percentagesByColumn);

            return this;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    package="com.mauriciotogneri.tensiontunnel"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="false"
        android:fullBackupContent="false"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">

        <activity
            android:name=".activities.MainActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:screenOrientation="landscape">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

        </activity>

    </application>

</manifest>


text:
/**
 * @class convert
 * @memberOf lapps.lappsServices
 * @description This service handles various conversions
 */
(function() {
  angular.module('lappsServices').service(
          'convert',
          function() {
            /**
             * @function
             * @type string
             * @memberOf lapps.lappsServices
             * @param {number}
             *          utc timestamp.
             * @description Converts timestamp in day time hh:mm.
             */
            this.time = function(utc) {
              var d = new Date(utc);

              var curr_hour = d.getHours();
              var curr_minute = d.getMinutes();

              return (('0' + curr_hour).slice(-2) + ":" + ('0' + curr_minute)
                      .slice(-2));
            };
            /**
             * @function
             * @type string
             * @memberOf lapps.lappsServices
             * @param {number}
             *          utc timestamp.
             * @description Converts timestamp in date string day-month-year.
             */
            this.date = function(utc) {
              var d = new Date(utc);
              var m_names = new Array("January", "February", "March", "April",
                      "May", "June", "July", "August", "September", "October",
                      "November", "December");

              var curr_date = d.getDate();
              var curr_month = d.getMonth();
              var curr_year = d.getFullYear();
              return (curr_date + "-" + m_names[curr_month] + "-" + curr_year);
            };
            /**
             * @function
             * @type string
             * @memberOf lapps.lappsServices
             * @param {number}
             *          utc timestamp.
             * @description Converts timestamp in date and time hh:mm
             *              day-month-year.
             */
            this.dateTime = function(utc) {
              return this.time(utc) + " " + this.date(utc);
            };
            /**
             * @function
             * @type string
             * @memberOf lapps.lappsServices
             * @param {number|string}
             *          size size in KB to convert to MB.
             * @description Converts size in KB to MB with 1 digit after the
             *              comma. If size is less than 1024 the value is not
             *              changed. The string MB or KB is appended to the
             *              result (12.5 MB).
             */
            this.size = function(size) {
              size = parseInt(size, 10);
              if (size < 1024) {
                return size + " KB";
              } else {
                var div = Math.floor(size / 1024);
                var rem = size % 1024;
                return div + "." + Math.round(rem / 100) + " MB";
              }
            };
            /**
             * @function
             * @type string
             * @memberOf lapps.lappsServices
             * @param {string}
             *          url
             * @description Shortens a given urlby only displaying the TLD.
             */
            this.url = function(url) {
              if (typeof url === 'undefined' || url === null) { return ''; }

              var urlCopy = url.substring(0);

              var wwwPos = urlCopy.indexOf('www.');
              if (wwwPos >= 0) {
                urlCopy = urlCopy.substring(wwwPos + 4);
                var slashPos = urlCopy.indexOf('/');
                if (slashPos >= 0) {
                  urlCopy = urlCopy.substring(0, slashPos);
                }
              }

              return urlCopy;
            }
          });
}).call(this);


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.storagecache.generated;

import com.azure.core.util.Context;

/** Samples for AscOperations Get. */
public final class AscOperationsGetSamples {
    /*
     * x-ms-original-file: specification/storagecache/resource-manager/Microsoft.StorageCache/stable/2022-05-01/examples/AscOperations_Get.json
     */
    /**
     * Sample code: AscOperations_Get.
     *
     * @param manager Entry point to StorageCacheManager.
     */
    public static void ascOperationsGet(com.azure.resourcemanager.storagecache.StorageCacheManager manager) {
        manager.ascOperations().getWithResponse("westus", "testoperationid", Context.NONE);
    }
}


text:
<?php
BLW_CORE_ClassLoader::import('app.lib.PSP.validator.BLW_PSP_Validator');
BLW_CORE_ClassLoader::import('app.lib.PSP.BLW_PSP_FacesContext');
BLW_CORE_ClassLoader::import('app.lib.PSP.BLW_PSP_FacesMessage');

class BLW_PSP_EmailValidator implements BLW_PSP_Validator {
	protected $max_length = null;

	public function setMaxLength($max) {
		if(is_numeric($max)) {
			$this->max_length = $max;
			return true;
		}
		throw new BLW_CORE_IllegalArgumentException('numeric', 'max', $max);
	}

	public function getMaxLength() {
		return $this->max_length;
	}

	public function validate(BLW_PSP_EditableValueHolder $valueHolder, $value = null) {
		if(is_string($value)) {
			$length = strlen($value);
			$regex = "=^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+[a-zA-Z]{2,4}+$=";

			if(!preg_match($regex, $value)) {
				$message = new BLW_PSP_FacesMessage();
				$message->setSummary("Not a valid email address!!!");
				BLW_PSP_FacesContext::instance()->addMessage($valueHolder->getId(), $message);
				$valueHolder->setValid(false);
				return false;
			}
			return true;
		} else {
			throw new BLW_CORE_IllegalArgumentException('string', 'value', $value);
		}

	}
}
?>


text:
package com.gml.myweather.gson;

import com.google.gson.annotations.SerializedName;

/**
 * Created by JayDragon on 2017/3/7 0007.
 */
public class Basic {
    @SerializedName("city")
    public String cityName;

    @SerializedName("id")
    public String weatherId;
    public Update update;
    public class Update{
        @SerializedName("loc")
        public String updateTime;
    }
}


text:
require 'test_helper'

class QueueTest < Test::Unit::TestCase
  def setup
    stub_netflix_for_user('nuid_one')
    stub_netflix_for_user('nuid_sub1')
    Netflix::Client.consumer_key = 'foo_consumer_key'
    Netflix::Client.consumer_secret = 'foo_consumer_secret'
  end

  def test_get_available_disc_queue
    user = Netflix::Client.new('nuid_access_key', 'nuid_access_secret').user('nuid_one')
    available_disc_queue = user.available_disc_queue
    assert available_disc_queue
  end

  def test_get_discs
    user = Netflix::Client.new('nuid_access_key', 'nuid_access_secret').user('nuid_one')
    available_disc_queue = user.available_disc_queue
    assert available_disc_queue
    discs = available_disc_queue.discs
    assert discs
    assert_equal 3, discs.size
    disc_one = discs[0]
    assert_equal "http://api-public.netflix.com/users/nuid_one/queues/disc/available/1/70167072", disc_one.id
    assert_equal "Arthur", disc_one.title
  end

  def test_add_item_to_queue_end_the_default
    user = Netflix::Client.new('nuid_access_key', 'nuid_access_secret').user('nuid_one')
    available_disc_queue = user.available_disc_queue
    assert available_disc_queue
    #pre tests
    assert_equal "http://api-public.netflix.com/users/nuid_one/queues/disc/available/1/70167072", available_disc_queue.discs[0].id
    assert_equal "http://api-public.netflix.com/users/nuid_one/queues/disc/available/2/70142826", available_disc_queue.discs[1].id
    assert_equal "http://api-public.netflix.com/users/nuid_one/queues/disc/available/3/70108988", available_disc_queue.discs[2].id
    assert_equal "115673854498", available_disc_queue.etag
    #operation and tests
    new_queue = available_disc_queue.add("http://api-public.netflix.com/catalog/titles/movies/70071613")
    assert_equal "http://api-public.netflix.com/users/nuid_one/queues/disc/available/1/70167072", new_queue.discs[0].id
    assert_equal "http://api-public.netflix.com/users/nuid_one/queues/disc/available/2/70142826", new_queue.discs[1].id
    assert_equal "http://api-public.netflix.com/users/nuid_one/queues/disc/available/3/70108988", new_queue.discs[2].id
    assert_equal "http://api-public.netflix.com/users/nuid_one/queues/disc/available/4/70071613", new_queue.discs[3].id
    assert_equal "1", new_queue.discs[0].instance_variable_get(:@map)["position"]
    assert_equal "2", new_queue.discs[1].instance_variable_get(:@map)["position"]
    assert_equal "3", new_queue.discs[2].instance_variable_get(:@map)["position"]
    assert_equal "4", new_queue.discs[3].instance_variable_get(:@map)["position"]
    assert_equal "82198468425", new_queue.etag
  end

  def test_add_item_to_queue_top
    user = Netflix::Client.new('nuid_access_key', 'nuid_access_secret').user('nuid_sub1')
    available_disc_queue = user.available_disc_queue
    assert available_disc_queue
    #pre tests
    assert_equal "http://api-public.netflix.com/users/nuid_sub1/queues/disc/available/1/70071613", available_disc_queue.discs[0].id
    assert_equal "http://api-public.netflix.com/users/nuid_sub1/queues/disc/available/2/70117306", available_disc_queue.discs[1].id
    assert_equal "http://api-public.netflix.com/users/nuid_sub1/queues/disc/available/3/70105135", available_disc_queue.discs[2].id
    assert_equal "115673854498", available_disc_queue.etag
    #operation and tests
    new_queue = available_disc_queue.add("http://api-public.netflix.com/catalog/titles/movies/70167072", 1)
    assert_equal "http://api-public.netflix.com/users/nuid_sub1/queues/disc/available/1/70167072", new_queue.discs[0].id
    assert_equal "http://api-public.netflix.com/users/nuid_sub1/queues/disc/available/2/70071613", new_queue.discs[1].id
    assert_equal "http://api-public.netflix.com/users/nuid_sub1/queues/disc/available/3/70117306", new_queue.discs[2].id
    assert_equal "http://api-public.netflix.com/users/nuid_sub1/queues/disc/available/4/70105135", new_queue.discs[3].id
    assert_equal "1", new_queue.discs[0].instance_variable_get(:@map)["position"]
    assert_equal "2", new_queue.discs[1].instance_variable_get(:@map)["position"]
    assert_equal "3", new_queue.discs[2].instance_variable_get(:@map)["position"]
    assert_equal "4", new_queue.discs[3].instance_variable_get(:@map)["position"]
    assert_equal "82198468425", new_queue.etag
  end

  def test_remove_item_from_queue_by_index
    user = Netflix::Client.new('nuid_access_key', 'nuid_access_secret').user('nuid_one')
    available_disc_queue = user.available_disc_queue
    assert available_disc_queue
    available_disc_queue.remove(2)
  end

  def test_empty_queue
    stub_netflix_for_user('empty_queue')
    user = Netflix::Client.new('nuid_access_key', 'nuid_access_secret').user('empty_queue')
    available_disc_queue = user.available_disc_queue
    assert available_disc_queue, "Expected a disc_queue"
    assert available_disc_queue.discs, "Expected the disc_queue to have a discs attribute"
    assert_equal 0, available_disc_queue.discs.size, "Expected discs to be empty array #{available_disc_queue.discs[0]}}"
    new_queue = available_disc_queue.add("http://api-public.netflix.com/catalog/titles/movies/70167072")
  end

end


text:
FROM jainishshah17/oracle-java7

MAINTAINER jainish shah <jainish.shah@getzephyr.com>

# Install ElasticSearch.
RUN \
  cd /tmp && \
  wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.4.4.tar.gz && \
  tar xvzf elasticsearch-1.4.4.tar.gz && \
  rm -f elasticsearch-1.4.4.tar.gz && \
  mv /tmp/elasticsearch-1.4.4 /elasticsearch
RUN sudo /elasticsearch/bin/plugin -install elasticsearch/elasticsearch-cloud-aws/2.4.1

RUN echo "America/Los_Angeles" > /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata

# Define mountable directories.
VOLUME ["/data"]
VOLUME ["/config"]

# Mount elasticsearch.yml config
ADD config/elasticsearch.yml /elasticsearch/config/elasticsearch.yml
ADD run.sh /config/run.sh

# Define working directory.
WORKDIR /data

# Define default command.
CMD ["sh /config/run.sh"]
CMD ["/elasticsearch/bin/elasticsearch"]

# Expose ports.
#   - 9200: HTTP
#   - 9300: transport
EXPOSE 9200
EXPOSE 9300
EXPOSE 6200


text:
'use strict';

module.exports = function () {
  this.add({ adapter: 'tmp' }, function (args, cb) {
    //do some kind of lookup for data relating to given
    //args.geojson to see if it intersects with any roading issues and calc
    //a value from 0-10 and return that
    cb(null, 7)
  })
}


text:
<?php

/*¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯*\
|   ____            _           _        Framework for whatever     |
|  / ___|  ___  ___| |_   _  __| | ___   you want to do with it!    |
|  \___ \ / _ \/ __| | | | |/ _` |/ _ \                             |
|   ___) |  __| (__| | |_| | (_| |  __/  Apache v2 Licence          |
|  |____/ \___|\___|_|\__,_|\__,_|\___|  © 2015 Xesau               |
\*_________________________________________________________________*/

namespace Seclude;

class TwigTemplateHandler implements TemplateHandler {

	protected $twigLoader, $twig;
	protected $options = array (
		'auto_reload' => false,
		'cache' => '{basedir}/cache'
	);

	public function __construct ($basedir, array $options = array ()) {
		## Register Twig's autoloader
		require_once __DIR__ .'/Twig/Autoloader.php';
		\Twig_Autoloader::register ();

		$this->options = $options + $this->options;

		## Create a Twig loader
		$this->twigLoader = new \Twig_Loader_Filesystem ($basedir);

		## Fix up the $options
		foreach ($this->options as $key => $value)
			if (is_string ($value))
				$this->options [$key] = str_replace ('{basedir}', $basedir, $value);

		if ($this->options ['cache'] !== false)
			$this->options['cache'] = str_replace (array ('\\', '/'), DIRECTORY_SEPARATOR, $this->options ['cache']);

		if (!is_dir ($this->options ['cache']))
			mkdir ($this->options ['cache'], 0777, true);

		## Setup the Twig Environment
		$this->twig = new \Twig_Environment ($this->twigLoader, $this->options);
	}

	public function getTwigEnvironment () {
		return $this->twig;
	}

	public function getOutput ($templateName, array $vars = array ()) {
		# Try to load the template and then return the rendered content
		try
		{
			$template = $this->twig->loadTemplate ($templateName .'.tpl');
			return $template->render ($vars);
		}

		# If Something doens't work, throw an error
		catch (\Twig_Error_Loader $ex)
		{
			trigger_error ('[Seclude] Something really bad happened which caused Twig to stop working: '. $ex->getMessage (), E_USER_ERROR);
		}
	}

	public function setOption ($option, $value) {
		$this->options [$option] = $value;
	}

	public function getOption ($option) {
		return $this->options [$option];
	}

	public function getOptions () {
		return $this->options;
	}
}


text:
Hi! 👋 I'm Leigh and I like designing, building community, and learning to code. My nephew Cory the corgi is more famous than you.

- Twitter: https://www.twitter.com/leighphan
- Website: http://leighphan.github.io/hello
- Languages: JavaScript, HTML, CSS


text:
package org.apache.shiro.aspectj;

import java.util.Arrays;

import org.apache.shiro.aop.MethodInvocation;
import org.apache.shiro.authz.aop.AnnotationsAuthorizingMethodInterceptor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

/**
 * Extends the annotations authorizing method interceptor class hierarchie to adapt
 * an aspectj {@link JoinPoint} into a {@link MethodInvocation} amd to perform the
 * authorization of method invocations.
 *
 * @author J-C Desrochers
 */
public class AspectjAnnotationsAuthorizingMethodInterceptor extends AnnotationsAuthorizingMethodInterceptor {

  public static boolean LOG_INTERCEPTED_INVOCATIONS = false;

  /**
   * Creates a new {@link AspectjAnnotationsAuthorizingMethodInterceptor} instance.
   */
  public AspectjAnnotationsAuthorizingMethodInterceptor() {
  }

  /**
   * Performs the method interception of the before advice at the specified joint point.
   *
   * @param aJoinPoint The joint point to intercept.
   * @throws Throwable If an error occurs berforming the method invocation.
   */
  protected void performBeforeInterception(JoinPoint aJoinPoint) throws Throwable {
    if (LOG_INTERCEPTED_INVOCATIONS) {
      logInterception(aJoinPoint);
    }

    // 1. Adapt the join point into a method invocation
    BeforeAdviceMethodInvocationAdapter mi = BeforeAdviceMethodInvocationAdapter.createFrom(aJoinPoint);

    // 2. Delegate the authorization of the method call to the super class
    super.invoke(mi);
  }

  /**
   * Internal utility method that logs the join point at which the method call is intercepted.
   *
   * @param aJoinPoint The aspectj join point.
   */
  private void logInterception(JoinPoint aJoinPoint) {
    System.out.println("#### Invoking a method decorated with a Shiro annotation" +
            "\n\tkind       : " + aJoinPoint.getKind() +
            "\n\tjoinPoint  : " + aJoinPoint +
            "\n\tannotations: " + Arrays.toString(((MethodSignature) aJoinPoint.getSignature()).getMethod().getAnnotations()) +
            "\n\ttarget     : " + aJoinPoint.getTarget()
            );
  }
}


text:
<?php

namespace Magento\Framework\Config\Data;

class Scoped extends \Magento\Framework\Config\Data
{
    /**
     * Configuration scope resolver
     *
     * @var \Magento\Framework\Config\ScopeInterface
     */
    protected $_configScope;

    /**
     * Configuration reader
     *
     * @var \Magento\Framework\Config\ReaderInterface
     */
    protected $_reader;

    /**
     * Configuration cache
     *
     * @var \Magento\Framework\Config\CacheInterface
     */
    protected $_cache;

    /**
     * Cache tag
     *
     * @var string
     */
    protected $_cacheId;

    /**
     * Scope priority loading scheme
     *
     * @var string[]
     */
    protected $_scopePriorityScheme = [];

    /**
     * Loaded scopes
     *
     * @var array
     */
    protected $_loadedScopes = [];

    /**
     * Constructor
     *
     * @param \Magento\Framework\Config\ReaderInterface $reader
     * @param \Magento\Framework\Config\ScopeInterface $configScope
     * @param \Magento\Framework\Config\CacheInterface $cache
     * @param string $cacheId
     */
    public function __construct(
        \Magento\Framework\Config\ReaderInterface $reader,
        \Magento\Framework\Config\ScopeInterface $configScope,
        \Magento\Framework\Config\CacheInterface $cache,
        $cacheId
    ) {
        $this->_reader = $reader;
        $this->_configScope = $configScope;
        $this->_cache = $cache;
        $this->_cacheId = $cacheId;
    }

    /**
     * Get config value by key
     *
     * @param string $path
     * @param mixed $default
     * @return array|mixed|null
     */
    public function get($path = null, $default = null)
    {
        $this->_loadScopedData();
        return parent::get($path, $default);
    }

    /**
     * Load data for current scope
     *
     * @return void
     */
    protected function _loadScopedData()
    {
        $scope = $this->_configScope->getCurrentScope();
        if (false == isset($this->_loadedScopes[$scope])) {
            if (false == in_array($scope, $this->_scopePriorityScheme)) {
                $this->_scopePriorityScheme[] = $scope;
            }
            foreach ($this->_scopePriorityScheme as $scopeCode) {
                if (false == isset($this->_loadedScopes[$scopeCode])) {
                    if ($scopeCode !== 'primary' && ($data = $this->_cache->load($scopeCode . '::' . $this->_cacheId))
                    ) {
                        $data = unserialize($data);
                    } else {
                        $data = $this->_reader->read($scopeCode);
                        if ($scopeCode !== 'primary') {
                            $this->_cache->save(serialize($data), $scopeCode . '::' . $this->_cacheId);
                        }
                    }
                    $this->merge($data);
                    $this->_loadedScopes[$scopeCode] = true;
                }
                if ($scopeCode == $scope) {
                    break;
                }
            }
        }
    }
}


text:
require 'spec_helper'

describe Circuit::Storage::Nodes do
  include SpecHelpers::StoresCleaner
  include SpecHelpers::BaseModels

  describe Circuit::Storage::Nodes::BaseStore do
    context "unimplemented store" do
      class Circuit::Storage::Nodes::UnimplementedStore < Circuit::Storage::Nodes::BaseStore
      end

      subject { Circuit::Storage::Nodes::UnimplementedStore.new }

      it do
        expect { subject.get("foo", "bar") }.
          to raise_error(Circuit::Storage::Nodes::UnimplementedError, "Circuit::Storage::Nodes::UnimplementedStore#get not implemented.")
      end

      it do
        expect { subject.get!("foo", "bar") }.
          to raise_error(Circuit::Storage::Nodes::UnimplementedError, "Circuit::Storage::Nodes::UnimplementedStore#get not implemented.")
      end
    end

    context "empty store" do
      class Circuit::Storage::Nodes::EmptyStore < Circuit::Storage::Nodes::BaseStore
        def get(site, path) nil; end
      end

      subject { Circuit::Storage::Nodes::EmptyStore.new }

      it { subject.get("foo", "bar").should be_nil }

      it do
        expect { subject.get!("foo", "bar").
          to raise_error(Circuit::Storage::Nodes::NotFoundError, "Host not found")
        }
      end
    end
  end

  describe Circuit::Storage::Nodes::MemoryStore do
    let(:site_class) { ::Site }
    let(:node_class) { ::RouteNode }
    use_storage :memory_store
    let!(:store) { :memory_store }
    include_examples "node store"

    describe Circuit::Storage::Nodes::MemoryStore::Node do
      subject { child }
      it { should have_attribute(:slug) }
      it { should have_attribute(:behavior_klass) }
      it { should have_attribute(:site) }
      it { should have_attribute(:parent) }
      it { should have_attribute(:children) }
    end
  end

  describe "Circuit::Storage::Nodes::MongoidStore", :if => $mongo_tests do
    use_storage :mongoid_store
    let!(:store) { :mongoid_store }
    include_examples "node store"
  end

  describe "subclasses in mongo", :if => $mongo_tests do
    use_storage :mongoid_store

    if $mongo_tests
      class SubclassA < MongoidRouteNode; end
      class SubclassB < MongoidRouteNode; end
      class SubclassC < SubclassA; end
      class SubclassD < SubclassC; end
    end

    before do
      root_ = ::MongoidRouteNode.create(:site => site, :behavior_klass => "RenderOk")
      SubclassA.create(:parent => root_, :slug => "foo", :behavior_klass => "RenderOk")
      SubclassB.create(:parent => root_, :slug => "bar", :behavior_klass => "RenderOk")
      SubclassC.create(:parent => root_, :slug => "baz", :behavior_klass => "RenderOk")
      SubclassD.create(:parent => root_, :slug => "wow", :behavior_klass => "RenderOk")
      SubclassA.create(:site => site_1, :behavior_klass => "RenderOk")
    end

    it { site.root.class.should include(Circuit::Storage::Nodes::MongoidStore::Node) }
    it { site.root.should be_instance_of(::MongoidRouteNode) }
    it { Circuit.node_store.get(site, "/").last.class.should include(Circuit::Storage::Nodes::MongoidStore::Node) }
    it { Circuit.node_store.get(site, "/").last.should be_instance_of(::MongoidRouteNode) }
    it { Circuit.node_store.get(site, "/foo").last.should be_instance_of(SubclassA) }
    it { Circuit.node_store.get(site, "/bar").last.should be_instance_of(SubclassB) }
    it { Circuit.node_store.get(site, "/baz").last.should be_instance_of(SubclassC) }
    it { Circuit.node_store.get(site, "/wow").last.should be_instance_of(SubclassD) }
    it { Circuit.node_store.get(site_1, "/").last.should be_instance_of(SubclassA) }
    it { SubclassA.where(:slug => "foo").first.should be_instance_of(SubclassA) }
    it { SubclassA.where(:slug => "baz").first.should be_instance_of(SubclassC) }
    it { SubclassC.where(:slug => "foo").first.should be_nil }
    it { SubclassC.where(:slug => "baz").first.should be_instance_of(SubclassC) }
  end
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: ben
 * Date: 16/10/17
 * Time: 10:22
 */
//Création simple du fichier BCAntispam
namespace BC\PlatformBundle\Antispam;

class BCAntispam
{
//    On passe des paramètres privés
    private $mailer;
    private $locale;
    private $minLength;

    public function __construct(\Swift_Mailer $mailer, $locale, $minLength)
    {
        $this->mailer    = $mailer;
        $this->locale    = $locale;
        $this->minLength = (int) $minLength;
    }

//    On crée juste un antispam cad si une annonce fait moins de 50 caractères = spam
    public function isSpam($text)
    {
        return strlen($text) < $this->minLength;
    }
}


text:
module Agents
  class ChangeDetectorAgent < Agent
    cannot_be_scheduled!

    description <<-MD
      The Change Detector Agent receives a stream of events and emits a new event when a property of the received event changes.

      `property` specifies a [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) template that expands to the property to be watched, where you can use a variable `last_property` for the last property value.  If you want to detect a new lowest price, try this: `{% assign drop = last_property | minus: price %}{% if last_property == blank or drop > 0 %}{{ price | default: last_property }}{% else %}{{ last_property }}{% endif %}`

      `expected_update_period_in_days` is used to determine if the Agent is working.

      The resulting event will be a copy of the received event.
    MD

    event_description <<-MD
    This will change based on the source event. If you were event from the ShellCommandAgent, your outbound event might look like:

      {
        'command' => 'pwd',
        'path' => '/home/Huginn',
        'exit_status' => '0',
        'errors' => '',
        'output' => '/home/Huginn'
      }
    MD

    def default_options
      {
          'property' => '{{output}}',
          'expected_update_period_in_days' => 1
      }
    end

    def validate_options
      unless options['property'].present? && options['expected_update_period_in_days'].present?
        errors.add(:base, "The property and expected_update_period_in_days fields are all required.")
      end
    end

    def working?
      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
    end

    def receive(incoming_events)
      incoming_events.each do |event|
        interpolation_context.stack do
          interpolation_context['last_property'] = last_property
          handle(interpolated(event), event)
        end
      end
    end

    private

    def handle(opts, event = nil)
      property = opts['property']
      if has_changed?(property)
        created_event = create_event :payload => event.payload

        log("Propagating new event as property has changed to #{property} from #{last_property}", :outbound_event => created_event, :inbound_event => event )
        update_memory(property)
      else
        log("Not propagating as incoming event has not changed from #{last_property}.", :inbound_event => event )
      end
    end

    def has_changed?(property)
      property != last_property
    end

    def last_property
      self.memory['last_property']
    end

    def update_memory(property)
      self.memory['last_property'] = property
    end
  end
end


text:
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Futhark.Representation.PrimitiveTests
       ( tests
       , arbitraryPrimValOfType
       )
       where

import Control.Applicative

import Test.QuickCheck
import Test.HUnit hiding (Test)
import Test.Framework
import Test.Framework.Providers.HUnit

import Prelude

import Futhark.Representation.Primitive

tests :: [Test]
tests = propPrimValuesHaveRightType

propPrimValuesHaveRightType :: [Test]
propPrimValuesHaveRightType = [ testCase (show t ++ " has blank of right type") $
                                primValueType (blankPrimValue t) @?= t
                              | t <- [minBound..maxBound]
                              ]

instance Arbitrary IntType where
  arbitrary = elements [minBound..maxBound]

instance Arbitrary FloatType where
  arbitrary = elements [minBound..maxBound]

instance Arbitrary PrimType where
  arbitrary = elements [minBound..maxBound]

instance Arbitrary IntValue where
  arbitrary = oneof [ Int8Value <$> arbitrary
                    , Int16Value <$> arbitrary
                    , Int32Value <$> arbitrary
                    , Int64Value <$> arbitrary ]

instance Arbitrary FloatValue where
  arbitrary = oneof [ Float32Value <$> arbitrary
                    , Float64Value <$> arbitrary ]

instance Arbitrary PrimValue where
  arbitrary = oneof [ IntValue <$> arbitrary
                    , FloatValue <$> arbitrary
                    , BoolValue <$> arbitrary
                    , pure Checked
                    ]

arbitraryPrimValOfType :: PrimType -> Gen PrimValue
arbitraryPrimValOfType (IntType Int8) = IntValue <$> Int8Value <$> arbitrary
arbitraryPrimValOfType (IntType Int16) = IntValue <$> Int16Value <$> arbitrary
arbitraryPrimValOfType (IntType Int32) = IntValue <$> Int32Value <$> arbitrary
arbitraryPrimValOfType (IntType Int64) = IntValue <$> Int64Value <$> arbitrary
arbitraryPrimValOfType (FloatType Float32) = FloatValue <$> Float32Value <$> arbitrary
arbitraryPrimValOfType (FloatType Float64) = FloatValue <$> Float32Value <$> arbitrary
arbitraryPrimValOfType Bool = BoolValue <$> arbitrary
arbitraryPrimValOfType Cert = return Checked


text:
package org.apache.geode.logging.internal;

import java.util.Optional;

import org.apache.geode.logging.internal.spi.LogFile;
import org.apache.geode.logging.internal.spi.LoggingSessionListener;
import org.apache.geode.logging.internal.spi.SessionContext;

public interface LoggingSessionNotifier {

  /**
   * Removes all currently registered {@code LoggingSessionListener}s.
   */
  void clear();

  /**
   * Provides {@code createSession} notification to all registered listeners.
   */
  void createSession(final SessionContext sessionContext);

  /**
   * Provides {@code startSession} notification to all registered listeners.
   */
  void startSession();

  /**
   * Provides {@code stopSession} notification to all registered listeners.
   */
  void stopSession();

  /**
   * Returns the system {@link LogFile} from any {@link LoggingSessionListener} that offers it.
   */
  Optional<LogFile> getLogFile();
}


text: openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 1000 -nodes


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Asciidoctor in JavaScript powered by Opal</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
    <link rel="stylesheet" href="../css/asciidoctor.css">


text:
require 'helper'
require 'bs/base/status_list'
require 'bs/base/status'

module BS::Base
  describe StatusList do
    let(:response) { [1, 2, 3] }

    describe '#new' do
      describe 'with arguments' do
        subject { StatusList.new([1, 2, 3, 4]) }
        specify { subject.valid?.must_equal true }
      end
      describe 'with no' do
        subject { StatusList.new }
        specify { subject.valid?.must_equal true }
      end
    end

    describe '#build_with_error' do
      let(:opts) do
        { error_message: 'error message' }
      end

      subject { StatusList.build_with_error(opts) }
      it 'has correct error message' do
        subject.invalid?.must_equal true
        subject.errors[:base].must_include 'error message'
      end
    end

    describe '#build_from_response' do
      before do
        Status.expects(:new).times(3)
      end
      subject { StatusList.build_from_response(response) }
      specify { subject.valid?.must_equal true }
      specify { subject.count.must_equal 3 }
    end
  end
end


text:
* Added `Lightness` property to the `ColorWheel` control, used
  to set the lightness of the generated color and to avoid
  resetting of lightness when using the `ColorEditorManager`
* Added `Alpha` property to the `ColorWheel` control, used to
  set the alpha channel of the generated color and to avoid
  resetting of alpha when using the `ColorEditorManager`
* Added `DisplayLightness` property to the `ColorWheel` control.
  When set, the wheel is drawn using the specified lightness,
  otherwise it draws the wheel at 50% (default)
* Added `ShowSaturationRing`, `ShowCenterLines`, `LineColor`,
  `ShowAngleArrow`, `SecondaryColors` and
  `SecondarySelectionSize` properties to the `ColorWheel`
  control
* Added `ScreenColorPicker.CaptureMouse` and `ReleaseMouse`
  methods. These allow you to initiate a screen picker operation
  without having to click and drag in the source control, for
  example via hotkey
* Added `ScreenColorPicker.Selecting` and `Selected` events,
  allowing you to know when a selection operation starts and
  ends
* Added `ColorSlider.NubOutlineColor`
* Added `PreserveAlphaChannel`, `ShowLoad`, `ShowSave` and
  `CustomColors` properties to the `ColorPickerDialog` component
* Added `CustomColorsLoading` and `CustomColorsSaving` events to
  the `ColorPickerDialog` component
* Added `ColorEditor.PreserveAlphaChannel`. By default, the
  `ColorEditor` will strip the alpha component from a colour if
  the `ShowAlphaChannel` property is not set. This new property
  allows the component to be preserved
* Added `ColorEditor.ShowHex`, `ShowHsl` and `ShowRgb`
  properties for showing or hiding groups of editors
* Added the `ColorEditor.NubSize`, `NubColor` and
  `NubOutlineColor` to allow at least some customisation of the
  sliders

#### Changed

* Added dedicated targets for .NET 3.5, .NET 4.0, .NET 4.5.2,
  .NET 4.6.2,.NET 4.7.2, .NET 4.8, .NET 5.0 and .NET Core 3.1
* Focus rectangles in slider controls now use an inverse
  painting operation
* Drag handles in the slider controls are no longer fully
  outside the bar, but are half inside and half out
* The `Up`, `Down`, `Home` and `End` keys are now used to
  manipulate the saturation value when a `ColorWheel` control
  has focus

#### Deprecated

* The `IPaletteSerializer` and `IColorEditor` interfaces have
  been marked as obsolete
* The `PaletteSerializer`, `AdobeColorTablePaletteSerializer`,
  `AdobePhotoShopColorSwatchSerializer`,
  `GimpPaletteSerializer`, `InterleavedBitmapPaletteSerializer`,
  `JascPaletteSerializer`, `PaintNetPaletteSerializer`, and
  `RawPaletteSerializer` classes have been marked as obsolete
* The `AdobePhotoshopColorSwatchColorSpace` and
  `AdobePhotoshopColorSwatchFileVersion` enums have been marked
  as obsolete

#### Removed

* The method `ColorEditor.ResizeComponents` is no longer
  accessible

#### Fixed

* The method `HslColor.ToRgbColor` didn't convert colours
  properly, most visible in the `LightnessColorSlider` which
  always showed a black and white scale no matter what the base
  color was
* Changing the `LightnessColorSlider.Value` property no longer
  updates the `Color` property
* The `ColorManagerEditor` does a better job of syncing values
  between attached controls
* The `SaturationColorSlider` and `LightnessColorSlider`
  controls now display a checker box background for non-solid
  colours
* The `ColorGrid` control wasn't binding events for the default
  `Colors` and `CustomColors` property values, causing
  programmatic changes not to be reflected in the control or
  crashes trying to access values not present
* Calling `ColorGrid.EndUpdate` didn't perform layout operations
  if the total number of colours had changed whiles updating was
  disabled

### 1.8.0

#### Changed

* The `ColorGrid` control now will now automatically scale color
  cells if the application is displayed with high DPI

#### Deprecated

* The protected `SelectionGlyph`, `Points`, `LockUpdates` and
  `Colors` properties of the `ColorWheel` control are deprecated
  and will be removed in a subsequent update

#### Fixed

* The `ColorWheel` no longer automatically snaps to the center
  of the wheel when the mouse is approaching the center

### 1.7.2

#### Added

* Added new `ShowColorSpaceLabels` property to the `ColorEditor`
  control. When `false`, the **RGB** and **HSL** labels will be
  hidden, allowing the control to take up less space. The
  default value is `true`
* Added new `CellContextMenuStrip` property to the `ColorGrid`
  control, allowing `ContextMenuStrip` controls to be
  automatically displayed when context clicking (including
  keyboard hotkeys) color cells
* Added new `GetCellBounds` method to the `ColorGrid` control,
  allowing consumers to get the `Rectangle` bounds of a color
  cell for purposes such as displaying context menus separately
  from the above support

#### Changed

* Reworked `ColorEditor` reszing handling so it doesn't look
  quite as awful if the control is small

### 1.7.1

#### Fixed

* `Palette` property of the `ColorGrid` control wasn't
  initialized correctly, making it pretty difficult to have a
  blank palette

### 1.7.0

#### Added

* Merged non-destructive changes from the version 2 branch,
  mainly around reworking events to require less overhead

### 1.6.0

#### Added

* Added `Minimum` and `Maximum` properties to
  `IPaletteSerializer` to provide hints to hosting applications
  about valid palettes
* Added support for reading and writing **Adobe Color Table**
  files (`*.act`) via the new `AdobeColorTablePaletteSerializer`
  class

#### Changed

* Code refactored using C# 6 syntax

#### Fixed

* Fixed rounding errors that could occur when using
  `HslColor.ToRgbColor`. Thanks to Jürgen from Iconshow for
  [this
  post](http://forums.cyotek.com/color-picker-controls/roundiing-difference/)
* Attempting to set the `Colors` property of the `ColorGrid` to
  `null` now throws an exception

### 1.5.0

* Added a new demonstration which shows how to host a
  `ColorGrid` control in a `ToolStrip`. More details on this can
  be found on
  [cyotek.com](http://www.cyotek.com/blog/hosting-a-colorgrid-control-in-a-toolstrip).
* Added new `PreviewColorChanged` event to the
  `ColorPickerDialog`
* Added new `PaintColor` protected methods to the `ColorWheel`
  control allowing additional hotspots to be painted
* Added new constructor to the `ColorCollection` to copy the
  contents of another `ColorCollection`
* The `ColorGrid` control now to defaults to creating 16 custom
  colours instead of 32
* Fixed an issue where the `ColorGrid` control wasn't rendering
  the custom colours group correctly (regression from previous
  version). Thanks to [Michael Schwarz](https://github.com/xwcg)
  for pointing out the offending line of code
* Fixed an issue where the `ColorPickerDialog` displayed
  non-opaque colours when the `ShowAlphaChannel` property was
  `false`
* Fixed an issue where the `ColorEditor` control would allow you
  to enter an 8 character hex color and thus set an alpha
  channel even if the `ShowAlphaChannel` property was `false`

### 1.4.1

#### Fixed

* Fixed an issue where `GimpPaletteSerializer.Deserialize` could
  get itself stuck in an infinite loop if a GPL file was
  formatted a certain way
* `GimpPaletteSerializer.Serialize` now uses `ASCII` encoding
  instead of `UTF-8`, fixing a problem where palette files
  couldn't be opened in Inkscape.

### 1.4.0

#### Changes and new features

* Added new `AdobePhotoShopColorSwatchSerializer` serializer for
  reading and writing Adobe PhotoShop colour swatches (both
  version 1 and version 2)
* You can now set the `Columns` property of a `ColorGrid`
  control to `0`, which will then internally calculate columns
  based on the size of the control, the cell size, and the
  spacing. A new read-only `ActualColumns` property has been
  added which will allow you to get the real number of columns
  if required. The `AutoSize` behaviour has been changed so that
  only the vertical height of the control is adjusted when
  `Columns` is zero
* **Save Palette** button in the `ColorPickerDialog` now obtains
  the serializer to use based on the selected filter index,
  allowing correct saving if multiple serializers use the same
  extension.
* Added `CanReadFrom` method to `IPaletteSerializer`.
* `PaletteSerializer.GetSerializer` now makes use of the above
  new method to access the relevant serializer rather than just
  matching extensions. This means if you have two serializers
  that support different .pal formatted files, these can now be
  loaded successfully, instead of one loading and one failing.
* Added new `RawPaletteSerializer` which reads and writes
  palettes that are simply RGB triplets in byte form
* Added new `ShowAlphaChannel` property to `ColorEditor` and
  `ColorPickerDialog`. This property allows the alpha channel
  editing controls to be hidden, for when working with 8-bit
  colours.
* The rendering of the selected cell in a `ColorGrid` control
  who's `SelectedCellStyle` is `Zoomed` now uses `Padding.Left`
  and `Padding.Top` to determine the size of the zoom box,
  avoiding massive boxes the larger the `CellSize` gets.
* Added a new standard 256 colour palette. You can use this in
  the `ColorGrid` by setting the `Palette` property to
  `ColorPalette.Standard256` or obtain the array of colours by
  calling `ColorPalettes.StandardPalette`
* `ColorGrid` and `RgbaColorSlider` controls now only create
  transparency brushes when required. A new virtual method
  `SupportsTransparentBackColor` allows inheritors to create
  their own brushes if required.
* Added `EditingColor` event to `ColorGrid`, allowing the edit
  colour action to be cancelled, or replaced with a custom
  editor
* Added `CurrentCell` property and `GetCellOffset` methods to
  the `ColorGrid`.
* `ColorCollection` now implements `IEquatable`
* Added more tests
* Added new `Navigate` method to `ColorGrid` for easier moving
  within the cells of the grid

#### Fixed

* The `ColorGrid` control now tries to be smarter with painting,
  and only paints cells that intersect with the clip rectangle.
  In addition, where possible only individual cells are
  invalidated rather than the entire control.
* Corrected invalid error messages from the **Save Palette**
  button in the `ColorPickerDialog`.
* **Load Palette** and **Save Palette** buttons in the
  `ColorPickerDialog` now check the `CanRead` and `CanWrite`
  properties of the serializer.
* Double clicking with any button other than the left in
  `ColorGrid` control no longer attempts to initiate colour
  editing
* Setting the `Color` property of the `ColorGrid` control to
  `Color.Empty` no longer treats the value as a valid colour
* The `ColorGrid` control no longer defines custom colour
  regions when the `ShowCustomColors` property was `false`. This
  manifested in hover and selection effects working if you moved
  your mouse over the bottom of a resized grid.
* Clicking "white space" areas of a `ColorWheel` control will no
  longer incorrectly set the colour to the closest matching
  point on the wheel itself. However, starting to select a
  colour within the wheel and then moving outside the bounds
  will continue to select the closest match as usual.
* Fixed a crash that occurred when creating controls that
  inherited from `ColorGrid` or `RgbaColorSlider`
* When the `AutoAddColors` and `ShowCustomColors` properties are
  `false`, unmatched colours will no longer be silently added to
  the `ColorGrid` custom palette unexpectedly. This also
  resolves various crashes after the colour regions fix above
  was applied.
* The `ColorWheel` control now makes use of
  `ButtonRenderer.DrawParentBackground` to draw itself, to avoid
  ugly blocks of solid colours when hosted in containers such as
  the `TabControl`
* The `ColorEditorManager` control's `ColorChanged` event has
  now been marked as the default event, so when you double click
  the component in the designer, a code window now correctly
  opens.
* If the underlying entry in a `ColorCollection` bound to a
  `ColorGrid` control was modified, and this particular entry
  was the selected colour, the `ColorGrid` would not keep its
  `Color` property in sync and would clear the selected index.
* Attempting to set the `Columns` property to less than zero now
  throws an `ArgumentOutOfRange` exception rather than setting
  it, then crashing later on
* Double clicking a colour in the grid of the
  `ColorPickerDialog` no longer opens another copy of the
  `ColorPickerDialog`
* Fixed problems in the `ColorGrid` with keyboard navigation and
  initial focus if no valid colour index was set.
* The `ColorCollection.Find` method now correctly works when
  adding named colours (e.g. `Color.CornflowerBlue`) to the
  collection, but searching by ARGB value (e.g.
  `Color.FromArgb(100, 149, 237)`)
* Fixed an issue where if the internal dictionary lookup in
  `ColorCollection` class had been created and the collection
  was then updated, in some cases the lookup wasn't correctly
  modified.

### 1.3.0

#### Changes and new features

* Added `Find` method to `ColorCollection`
* Replaced `ColorComparer.Brightness` with version derived from
  [here](http://stackoverflow.com/a/13558570/148962)
* Added new `InterleavedBitmapPaletteSerializer` class, that
  allows palettes to be loaded from  ILBM (IFF Interleaved
  Bitmap) format files (LBM images or BBM palettes). *Note:*
  Writing is not [yet
  supported](http://cyotek.com/blog/loading-the-color-palette-from-a-bbm-lbm-image-file-using-csharp).
* Added `CanRead` and `CanWrite` properties to
  `IPaletteSerializer` to indicate input/output support.
* The `PaletteSerializer.DefaultOpenFilter` and
  `PaletteSerializer.DefaultSaveFilter` make use of the above
  properties when building filters
* Added the ability for multiple extensions to be supplied.
* The colours displayed in the drop down list component of the
  `ColorEditor` now only load when the drop down is opened, or
  the **Up**, **Down**, **Page Up** or **Page Down** keys are
  pressed
* Reworked the `ColorEditor` control to work nicer with RGB
  colours. Previously, the `Color` property was a wrapper around
  the `HslColor` property, meaning if you set it to a named
  colour such as `Color.Red`, the name was lost, and the
  hex/name editor didn't show the name. Now it keeps track of
  both colours, so if you set it to a named value, you can see
  (and get) the named value back.
* Reworked the `ColorEditorManager` component to also store
  separate copies of the RGB/HSL colours instead of loosing
  named colour information
* Experimented with making the `hex/named colour` field in the
  `ColorEditor` control slightly wider than the other controls.
  Looks a touch odd now that all fields aren't a uniform width,
  but does make it much easier to read that the selected colour
  is `LightGoldenRodYellow`!

#### Fixed

* Setting the `SelectionSize` property of the `ColorWheel`
  didn't resize the wheel as it was supposed to
* When the orientation of a `ColorSlider` (or derived control)
  was `Vertical`, the colour bar was drawn in the reverse order
  of the scale.
* Changing the `Value` of the `LightnessColorSlider` control now
  correctly updates the `Color` property of that control, in
  turn making the `ColorEditorManager` change the luminosity of
  linked controls. Also setting the `Color` of the
  `LightnessColorSlider` now correctly updates the `Value`. This
  now means you can bind a `ColorWheel` to a
  `LightnessColorSlider` for full control over the brightness of
  a colour, which is not possible to do with the wheel alone.

### 1.2.3

#### Changes and new features

* Added static `LoadPalette` and instance `Load` methods to
  `ColorCollection`
* Added `Save` method to `ColorCollection`
* Added new constructor to `ColorCollection` that accepts a
  `System.Drawing.Imaging.ColorPalette` class.
* Added new `AutoFit` property to the `ColorGrid`. When set, the
  `CellSize` property is automatically calculated based on the
  size of the control, and its contents. You can't combine
  `AutoFit` with `AutoSize`.
* `ColorCollection` is now clone-able

#### Fixed

* Removed unnecessary `UpdateStyles` calls.
* Fixed a problem if a window was opened by pressing `Enter`,
  and a `ColorGrid` was the first focusable control on the new
  window, the pop-up colour editing dialog would be activated,
  regardless of the `ColorGrid`'s editing settings

### 1.2.2

#### Changes and new features

* Added `Name` and `DefaultExtension` properties to
  `IPaletteSerializer`
* Added new static properties `DefaultOpenFilter` and
  `DefaultSaveFilter`, and static method `GetSerializer` to
  `PaletteSerializer`. These allow the use of reflection for
  easily providing palette load and save functionality
  automatically based on loaded assemblies.
* Added the `SupportsTransparentBackColor` control style to
  `ColorGrid`
* Added system colours to the `ColorEditor` named colour drop
  down
* Added a new `DoubleSoft` cell border style to the `ColorGrid`

#### Fixed

* Setting the `Spacing` or `CellSize` properties of the
  `ColorGrid` control didn't recalculate the layout
* `ColorEditor` now uses `TextRenderer.DrawText` instead of
  `Graphics.DrawString` so all text is rendered consistently.

### 1.2.1

#### Changes and new features

* Added new constructor to the `ColorCollection` class that
  accepts an `IEnumerable<int>`
* `ColorCollection` now implements `IClonable`
* Added dotted outline to design time `ColorGrid` control

#### Fixed

* Fixed invalid default value for the `EditMode` property of a
  `ColorGrid`
* Fixed `AutoSize` property of `ColorGrid` control not being
  persisted

### 1.2.0

> *Note: Several of the updates in this version are breaking
> changes due to renaming of classes and enum values. Some more
> changes to your code will be required to use the new Color
> Picker API.*

#### Changes and new features

* `IPaletteReader` replaced with `IPaletteSerializer`
* `JascPaletteReader` replaced with `JascPaletteSerializer`
* `GimpPaletteReader` replaced with `GimpPaletteSerializer`
* `PaintNetPaletteReader` replaced with
  `PaintNetPaletteSerializer`
* The values of the `ColorEditingMode` enum have been renamed to
  make more sense.
* The `ColorEditor` now supports selecting of named colours as
  the hex editor is now a drop down list. As well as being able
  to select named colours from the list, you can now also type
  names directly into the hex editor and they will be processed
  accordingly.
* The `ColorPickerDialog` now can load and save palette files
* Palette support has been reworked to allow the saving of
  palettes as well as loading. Unfortunately due to the initial
  names of these classes this is a breaking change.
* Added a bit more documentation

#### Fixed

* Corrected some grammatical errors in existing documentation
  and headers

### 1.1.0

> *Note: Several of the updates in this version are breaking
> changes due to renaming of classes and enum values. Some more
> changes to your code will be required to use the new Color
> Picker API.*

#### Changes and new features

* Added `GimpPaletteReader` for reading palette files created by
  Gimp
* Added `ReadPalette(fileName)` overload to `IPaletteReader`
* Renamed `Jasc10PaletteReader` to `JascPaletteReader`
* Reworked Jasc palette import to match how Gimp is doing it
* Added a testing project. Currently this just tests the
  different palette readers are importing data correctly.

### 1.0.0

* Initial Release


text:
using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using NUnit.Framework;
using Orchard.Environment.Extensions.Models;
using Orchard.Mvc;
using Orchard.Tests.DisplayManagement;
using Orchard.Tests.Stubs;
using Autofac;

namespace Orchard.Tests.Mvc {
    [TestFixture]
    public class OrchardControllerFactoryTests {
        private OrchardControllerFactory _controllerFactory;
        private IWorkContextAccessor _workContextAccessor;
        private StubContainerProvider _containerProvider;

        [SetUp]
        public void Init() {
            var builder = new ContainerBuilder();
            builder.RegisterType<FooController>()
                .Keyed<IController>("/foo")
                .Keyed<IController>(typeof(FooController))
                .WithMetadata("ControllerType", typeof(FooController))
                .InstancePerDependency();

            builder.RegisterType<BarController>()
                .Keyed<IController>("/bar")
                .Keyed<IController>(typeof(BarController))
                .WithMetadata("ControllerType", typeof(BarController))
                .InstancePerDependency();

            builder.RegisterType<ReplacementFooController>()
                .Keyed<IController>("/foo")
                .Keyed<IController>(typeof(ReplacementFooController))
                .WithMetadata("ControllerType", typeof(ReplacementFooController))
                .InstancePerDependency();

            var container = builder.Build();
            _containerProvider = new StubContainerProvider(container, container.BeginLifetimeScope());

            var workContext = new DefaultDisplayManagerTests.TestWorkContext
            {
                CurrentTheme = new ExtensionDescriptor { Id = "Hello" },
                ContainerProvider = _containerProvider
            };
            _workContextAccessor = new DefaultDisplayManagerTests.TestWorkContextAccessor(workContext);

            _controllerFactory = new OrchardControllerFactory();
            InjectKnownControllerTypes(_controllerFactory, typeof(ReplacementFooController), typeof (FooController), typeof (BarController));
        }

        [Test]
        public void IContainerProvidersRequestContainerFromRouteDataShouldUseTokenWhenPresent() {
            var requestContext = GetRequestContext(_workContextAccessor);
            var controller = _controllerFactory.CreateController(requestContext, "foo");

            Assert.That(controller, Is.TypeOf<ReplacementFooController>());
        }

        [Test, Ignore("OrchardControllerFactory depends on metadata, calling base when no context is causing errors.")]
        public void WhenNullOrMissingContainerNormalControllerFactoryRulesShouldBeUsedAsFallback() {
            var requestContext = GetRequestContext(null);
            var controller = _controllerFactory.CreateController(requestContext, "foo");

            Assert.That(controller, Is.TypeOf<FooController>());
        }

        [Test]
        public void WhenContainerIsPresentButNamedControllerIsNotResolvedNormalControllerFactoryRulesShouldBeUsedAsFallback() {
            var requestContext = GetRequestContext(_workContextAccessor);
            var controller = _controllerFactory.CreateController(requestContext, "bar");

            Assert.That(controller, Is.TypeOf<BarController>());
        }

        [Test]
        public void DisposingControllerThatCameFromContainerShouldNotCauseProblemWhenContainerIsDisposed() {
            var requestContext = GetRequestContext(_workContextAccessor);
            var controller = _controllerFactory.CreateController(requestContext, "foo");

            Assert.That(controller, Is.TypeOf<ReplacementFooController>());

            _controllerFactory.ReleaseController(controller);
            _containerProvider.EndRequestLifetime();

            // explicitly dispose a few more, just to make sure it's getting hit from all different directions
            ((IDisposable) controller).Dispose();
            ((ReplacementFooController) controller).Dispose();

            Assert.That(((ReplacementFooController) controller).Disposals, Is.EqualTo(4));
        }

        [Test]
        public void NullServiceKeyReturnsDefault() {
            OrchardControllerFactoryAccessor orchardControllerFactory = new OrchardControllerFactoryAccessor();
            ReplacementFooController fooController;

            Assert.That(orchardControllerFactory.TryResolveAccessor(_workContextAccessor.GetContext(), null, out fooController), Is.False);
            Assert.That(fooController, Is.Null);
        }

        private static RequestContext GetRequestContext(IWorkContextAccessor workContextAccessor)
        {
            var handler = new MvcRouteHandler();
            var route = new Route("yadda", handler) {
                                                        DataTokens =
                                                            new RouteValueDictionary { { "IWorkContextAccessor", workContextAccessor } }
                                                    };

            var httpContext = new StubHttpContext();
            var routeData = route.GetRouteData(httpContext);
            return new RequestContext(httpContext, routeData);
        }

        public class FooController : Controller { }

        public class BarController : Controller { }

        public class ReplacementFooController : Controller {
            protected override void Dispose(bool disposing) {
                ++Disposals;

                base.Dispose(disposing);
            }

            public int Disposals { get; set; }
        }

        internal class OrchardControllerFactoryAccessor : OrchardControllerFactory {
            public bool TryResolveAccessor<T>(WorkContext workContext, object serviceKey, out T instance) {
                return TryResolve(workContext, serviceKey, out instance);
            }
        }

        private static void InjectKnownControllerTypes(DefaultControllerFactory controllerFactory,
                                                       params Type[] controllerTypes) {
            // D'oh!!! Hey MVC people, how is this testable? ;)

            // locate the appropriate reflection member info
            var controllerTypeCacheProperty = controllerFactory.GetType()
                .GetProperty("ControllerTypeCache", BindingFlags.Instance | BindingFlags.NonPublic);
            var cacheField = controllerTypeCacheProperty.PropertyType.GetField("_cache",
                                                                               BindingFlags.NonPublic |
                                                                               BindingFlags.Instance);

            // turn the array into the correct collection
            var cache = controllerTypes
                .GroupBy(t => t.Name.Substring(0, t.Name.Length - "Controller".Length), StringComparer.OrdinalIgnoreCase)
                .ToDictionary(g => g.Key,
                              g => g.ToLookup(t => t.Namespace ?? string.Empty, StringComparer.OrdinalIgnoreCase),
                              StringComparer.OrdinalIgnoreCase);

            // execute: controllerFactory.ControllerTypeCache._cache = cache;
            cacheField.SetValue(
                controllerTypeCacheProperty.GetValue(controllerFactory, null),
                cache);
        }
   }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Alfred-example</string>

</resources>


text:
cask 'netshade' do
  version :latest
  sha256 :no_check

  url 'http://raynersoftware.com/downloads/NetShade.app.zip'
  appcast 'https://secure.raynersw.com/appcast.php',
          :checkpoint => 'e25679e34ce737098f3c565e408bc6fb54d876ca10938a03099edc46e12229ab'
  name 'NetShade'
  homepage 'http://raynersoftware.com/netshade/'
  license :unknown # TODO: change license and remove this comment; ':unknown' is a machine-generated placeholder

  app 'NetShade.app'
end


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

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;

#endif

namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
    [TestFixture]
    public class ParseJsonArray : TestFixtureBase
    {
        [Test]
        public void Example()
        {
            #region Usage
            string json = @"[
              'Small',
              'Medium',
              'Large'
            ]";

            JArray a = JArray.Parse(json);

            Console.WriteLine(a.ToString());
            // [
            //   "Small",
            //   "Medium",
            //   "Large"
            // ]
            #endregion

            StringAssert.AreEqual(@"[
  ""Small"",
  ""Medium"",
  ""Large""
]", a.ToString());
        }
    }
}


text:
int main(int argc, char *argv[]) {
  using namespace kaldi;
  typedef kaldi::int32 int32;
  try {
    const char *usage =
        "Get feature-projection transform using stats obtained with acc-lda.\n"
        "See comments in the code of nnet2/get-feature-transform.h for more\n"
        "information.\n"
        "\n"
        "Usage:  nnet-get-feature-transform [options] <matrix-out> <lda-acc-1> <lda-acc-2> ...\n";

    bool binary = true;
    FeatureTransformEstimateOptions opts;
    std::string write_cholesky;
    std::string write_within_covar;
    ParseOptions po(usage);
    po.Register("binary", &binary, "Write outputs in binary mode.");
    po.Register("write-cholesky", &write_cholesky, "If supplied, write to this "
                "wxfilename the Cholesky factor of the within-class covariance. "
                "Can be used for perturbing features.  E.g. "
                "--write-cholesky=exp/nnet5/cholesky.tpmat");
    po.Register("write-within-covar", &write_within_covar, "If supplied, write "
                "to this wxfilename the within-class covariance (as a symmetric "
                "matrix). E.g. --write-within-covar=exp/nnet5/within_covar.mat");
    opts.Register(&po);
    po.Read(argc, argv);

    if (po.NumArgs() < 2) {
      po.PrintUsage();
      exit(1);
    }

    FeatureTransformEstimate fte;
    std::string projection_wxfilename = po.GetArg(1);

    for (int32 i = 2; i <= po.NumArgs(); i++) {
      bool binary_in, add = true;
      Input ki(po.GetArg(i), &binary_in);
      fte.Read(ki.Stream(), binary_in, add);
    }

    Matrix<BaseFloat> mat;
    TpMatrix<BaseFloat> cholesky;
    fte.Estimate(opts, &mat,
                 (write_cholesky != "" || write_within_covar != "" ?
                  &cholesky : NULL));
    WriteKaldiObject(mat, projection_wxfilename, binary);
    if (write_cholesky != "") {
      WriteKaldiObject(cholesky, write_cholesky, binary);
    }
    if (write_within_covar != "") {
      SpMatrix<BaseFloat> within_var(cholesky.NumRows());
      within_var.AddTp2(1.0, cholesky, kNoTrans, 0.0);
      WriteKaldiObject(within_var, write_within_covar, binary);
    }
    return 0;
  } catch(const std::exception &e) {
    std::cerr << e.what();
    return -1;
  }
}


text:
Ext.require( [ 'Ext.layout.container.*', 'ASPIREdb.view.filter.multicombo.MultiValueCombobox',
              'ASPIREdb.model.Operator', 'ASPIREdb.view.filter.TextImportWindow', 'ASPIREdb.ActiveProjectSettings' ] );

/**
 * Includes a property combo, operator combo and value text field.
 */
Ext.define( 'ASPIREdb.view.filter.PropertyFilter', {
   extend : 'Ext.Container',
   alias : 'widget.filter_property',
   width : 875,
   layout : {
      type : 'hbox',

      defaultMargins : {
         right : 5,
      }
   },
   config : {
      propertyStore : null, /* property suggestions */
      suggestValuesRemoteFunction : null,
   },
   constructor : function(cfg) {
      this.initConfig( cfg );
      this.callParent( arguments );
   },

   isMultiValue : true,
   selectedProperty : null,

   getRestrictionExpression : function() {

      var operatorComboBox = this.getComponent( "operatorComboBox" );
      var multicombo_container = this.getComponent( "multicombo_container" );
      var multicombo = multicombo_container.getComponent( "multicombo" );
      var singleValueField = multicombo_container.getComponent( "singleValueField" );

      if ( this.isMultiValue ) {
         var setRestriction = new SetRestriction();
         setRestriction.property = this.selectedProperty;
         setRestriction.operator = operatorComboBox.getValue();
         setRestriction.values = multicombo.getValues();
         return setRestriction;
      } else {
         var simpleRestriction = new SimpleRestriction();
         simpleRestriction.property = this.selectedProperty;
         simpleRestriction.operator = operatorComboBox.getValue();
         var value = new NumericValue();
         value.value = singleValueField.getValue();
         simpleRestriction.value = value;
         return simpleRestriction;
      }
   },

   // pass restriction to populate the gene list in variant filter
   setRestrictionExpression : function(restriction) {

      if ( restriction instanceof Conjunction || restriction instanceof Disjunction ) {

         for (var i = 0; i < restriction.restrictions.length; i++) {

            var rest1 = restriction.restrictions[i];

            this.populateMultiComboItem( rest1 );

         }

      } else if ( restriction instanceof VariantTypeRestriction ) {
         // VariantType is implied by the container

      } else if ( restriction instanceof SimpleRestriction ) {
         this.setSimpleRestrictionExpression( restriction );
      } else {
         this.populateMultiComboItem( restriction );
      }

   },

   setSimpleRestrictionExpression : function(restriction) {

      var operatorComboBox = this.getComponent( "operatorComboBox" );
      var multicombo_container = this.getComponent( "multicombo_container" );
      var multicombo = multicombo_container.getComponent( "multicombo" );
      var singleValueField = multicombo_container.getComponent( "singleValueField" );

      singleValueField.on( 'change', function() {

         ASPIREdb.EVENT_BUS.fireEvent( 'query_update' );

      } );

      var propertyComboBox = me.getComponent( "propertyComboBox" );

      this.selectedProperty = restriction.property;
      propertyComboBox.setValue( restriction.property.displayName );
      operatorComboBox.setValue( restriction.operator );

      singleValueField.setValue( restriction.value.value );

      this.isMultiValue = false;
      multicombo.hide();
      singleValueField.show();

   },

   // populate multi combo based on property combo selection
   populateMultiComboItem : function(restriction) {

      var r = restriction;

      var propertyComboBox = this.getComponent( "propertyComboBox" );
      var operatorComboBox = this.getComponent( "operatorComboBox" );
      var multicombo_container = this.getComponent( "multicombo_container" );
      var multicombo = multicombo_container.getComponent( "multicombo" );

      this.selectedProperty = r.property;
      propertyComboBox.setValue( r.property.displayName );
      operatorComboBox.setValue( r.operator );

      // set property in combo store for dwr calls
      multicombo.setProperty( r.property );

      for (var j = 0; j < r.values.length; j++) {

         var itemElement = Ext.create( 'ASPIREdb.view.filter.multicombo.Item', {
            text : r.values[j].label,
            value : r.values[j]
         } );

         multicombo.addMultiComboItem( itemElement );
         multicombo_container.add( multicombo );
      }

      this.enableEnterList( r.property );

   },
   // populate gene list from the text box in variant filter
   populateMultiComboItemFromImportList : function(vos) {

      var multicombo_container = this.getComponent( "multicombo_container" );
      var multicombo = multicombo_container.getComponent( "multicombo" );

      multicombo.reset();

      // set property in combo store for dwr calls
      // multicombo.setProperty(r.property);

      for (var j = 0; j < vos.length; j++) {

         var itemElement = Ext.create( 'ASPIREdb.view.filter.multicombo.Item', {
            text : vos[j].label,
            value : vos[j]
         } );

         multicombo.addMultiComboItem( itemElement );
         multicombo_container.add( multicombo );
      }

      this.enableEnterList( this.selectedProperty );

   },

   updateOperators : function(operators) {
      // update operators
      var operatorComboBox = this.getComponent( "operatorComboBox" );
      var operatorModels = Ext.Array.map( operators, function(x) {
         return {
            displayLabel : x,
            operator : x
         };
      } );
      var store = operatorComboBox.getStore();
      store.removeAll();
      store.add( operatorModels );
      operatorComboBox.select( store.getAt( 0 ) );
   },

   initComponent : function() {
      var me = this;

      this.items = [ {
         xtype : 'combo',
         itemId : 'propertyComboBox',
         emptyText : 'name',
         store : me.getPropertyStore(),
         displayField : 'displayName',
         listeners : {
            select : {
               fn : function(obj, records) {
                  // ASPIREdb.EVENT_BUS.fireEvent('query_update');
                  if ( records[0].name == "CNV Characteristics" )
                     this.setVisible( false );
               },
               scope : this,
            }
         },
      }, {
         xtype : 'combo',
         itemId : 'subPropertyComboBox',
         emptyText : 'Type characteristics',
         suggestValuesRemoteFunction : VariantService.suggestValues,
         store : {
            extend : Ext.data.Store,
            sorters : [ {
               property : 'displayName',
               direction : 'ASC'
            } ],
            proxy : {
               type : 'dwr',
               dwrFunction : VariantService.suggestPropertiesForVariantTypeInProject,
               dwrParams : [ 'CNV', ASPIREdb.ActiveProjectSettings.getActiveProjectIds()[0] ],
               model : 'ASPIREdb.model.Property',
               reader : {
                  type : 'json',
                  root : 'data',
                  totalProperty : 'count'
               }
            }
         },
         displayField : 'displayName',
         filterItemType : 'ASPIREdb.view.filter.PropertyFilter',
         hidden : true
      },

      {
         xtype : 'combo',
         itemId : 'operatorComboBox',
         emptyText : 'operator',
         displayField : 'displayLabel',
         queryMode : 'local',
         width : 100,
         store : {
            proxy : {
               type : 'memory'
            },
            model : 'ASPIREdb.model.Operator'
         }
      }, {
         /* multi value vs single value */
         xtype : 'container',
         itemId : 'multicombo_container',
         items : [ {
            xtype : 'multivalue_combo',
            itemId : 'multicombo',
            width : 400, // 450,
            enableKeyEvents : false,
            suggestValuesRemoteFunction : me.getSuggestValuesRemoteFunction(),
         }, {
            xtype : 'numberfield',
            itemId : 'singleValueField',
            width : 300,
            enableKeyEvents : true,
            hidden : true
         }, {
            xtype : 'label',
            itemId : 'example',
            text : '',
            style : {
               'top' : '25px',
               'font-size' : '10px',
               'color' : 'gray'
            }
         } ]
      }, {
         xtype : 'button',
         itemId : 'removeButton',
         text : 'X'
      }, {
         itemId : 'enterListButton',
         xtype : 'button',
         text : '',
         tooltip : 'Enter list...',
         icon : 'scripts/ASPIREdb/resources/images/icons/page_upload.png',
         disabled : true,
         hidden : true
      }, {
         xtype : 'label',
         itemId : 'operationLabel',
         text : ''
      }, ];

      this.callParent();
      var multicombo_container = me.getComponent( "multicombo_container" );
      var operatorComboBox = me.getComponent( "operatorComboBox" );
      var multicombo = multicombo_container.getComponent( "multicombo" );
      var singleValueField = multicombo_container.getComponent( "singleValueField" );
      var example = multicombo_container.getComponent( "example" );
      var propertyComboBox = me.getComponent( "propertyComboBox" );
      var subPropertyComboBox = me.getComponent( "subPropertyComboBox" );
      var andLabel = me.getComponent( "andLabel" );
      var orLabel = me.getComponent( "orLabel" );

      var firstTime = true;

      subPropertyComboBox.on( 'select', function(obj, records) {
         var record = records[0];

         var property = record.raw;
         if ( property.dataType instanceof NumericalDataType ) {
            me.isMultiValue = false;
            multicombo.hide();
            singleValueField.reset();
            singleValueField.show();
         } else {
            me.isMultiValue = true;
            // update multicombobox
            multicombo.setProperty( property );
            multicombo.reset();
            multicombo.show();
            singleValueField.hide();
         }

         me.selectedProperty = property;
         me.enableEnterList( property );

         me.updateOperators( record.data.operators );
      } );

      propertyComboBox.on( 'select', function(obj, records) {
         var record = records[0];
         var value = record.data.displayName;

         if ( value == "CNV Characteristics" ) {
            var subPropertyComboBox = me.getComponent( "subPropertyComboBox" );
            subPropertyComboBox.setVisible( true );
            subPropertyComboBox.store.proxy.dwrParams[0] = "CNV";
            subPropertyComboBox.emptyText = 'Type characteristics';

            var storeInstance = Ext.create( 'Ext.data.Store', {
               proxy : {
                  type : 'dwr',
                  dwrFunction : VariantService.suggestPropertiesForVariantTypeInProject,
                  dwrParams : [ 'CNV', ASPIREdb.ActiveProjectSettings.getActiveProjectIds()[0] ],
                  model : 'ASPIREdb.model.Property',
                  reader : {
                     type : 'json',
                     root : 'data',
                     totalProperty : 'count'
                  }
               },
               sortOnLoad : true,
               autoLoad : true
            } );

            subPropertyComboBox.store.reload( storeInstance );

            // context menu
            /**
             * VariantService.suggestPropertiesForVariantType( 'CNV', { callback : function(Properties) {
             *
             *
             * var menuItems = []; // TODO: context menu handlers for (var i = 0; i < Properties.length; i++) {
             * menuItems.push( { text : Properties[i].displayName, scope : me, listeners : { itemclick : function(item) {
             * alert( "selected item " + item.displayName ); me.selectedProperty = item; } }, handler :
             * me.contextMenuSelectionHandler, } ); }
             *
             * var contextMenu = new Ext.menu.Menu( { items : menuItems, } );
             *
             * contextMenu.showAt( 650, 410 ); } } );
             */

         } else if ( value == "SNV Characteristics" ) {

            var subPropertyComboBox = me.getComponent( "subPropertyComboBox" );
            subPropertyComboBox.setVisible( true );
            subPropertyComboBox.store.proxy.dwrParams[0] = "SNV";
            subPropertyComboBox.emptyText = 'Type characteristics';

            var storeInstance = Ext.create( 'Ext.data.Store', {
               proxy : {
                  type : 'dwr',
                  dwrFunction : VariantService.suggestPropertiesForVariantTypeInProject,
                  dwrParams : [ 'SNV', ASPIREdb.ActiveProjectSettings.getActiveProjectIds()[0] ],
                  model : 'ASPIREdb.model.Property',
                  reader : {
                     type : 'json',
                     root : 'data',
                     totalProperty : 'count'
                  }
               },
               sortOnLoad : true,
               autoLoad : true
            } );

            subPropertyComboBox.store.reload( storeInstance );

         } else if ( value == "Indel Characteristics" ) {

            var subPropertyComboBox = me.getComponent( "subPropertyComboBox" );
            subPropertyComboBox.setVisible( true );
            subPropertyComboBox.store.proxy.dwrParams[0] = "INDEL";
            subPropertyComboBox.emptyText = 'Type characteristics';

            var storeInstance = Ext.create( 'Ext.data.Store', {
               proxy : {
                  type : 'dwr',
                  dwrFunction : VariantService.suggestPropertiesForVariantTypeInProject,
                  dwrParams : [ 'INDEL', ASPIREdb.ActiveProjectSettings.getActiveProjectIds()[0] ],
                  model : 'ASPIREdb.model.Property',
                  reader : {
                     type : 'json',
                     root : 'data',
                     totalProperty : 'count'
                  }
               },
               sortOnLoad : true,
               autoLoad : true
            } );

            subPropertyComboBox.store.reload( storeInstance );

         } else {
            var subPropertyComboBox = me.getComponent( "subPropertyComboBox" );
            subPropertyComboBox.setVisible( false );
         }

         // update examples
         var queryExample = record.data.exampleValues;
         example.setText( queryExample, false );

         if ( !subPropertyComboBox.isVisible() ) {
            me.updateOperators( record.data.operators );
         } else {
            // clear operator combobox
            var operatorComboBox = me.getComponent( "operatorComboBox" );
            var store = operatorComboBox.getStore();
            store.removeAll();
            operatorComboBox.select( null );
         }

         var property = record.raw;
         if ( property.dataType instanceof NumericalDataType ) {
            me.isMultiValue = false;
            multicombo.hide();
            singleValueField.reset();
            singleValueField.show();
         } else {
            me.isMultiValue = true;
            // update multicombobox
            multicombo.setProperty( property );
            multicombo.reset();
            multicombo.show();
            singleValueField.hide();
         }

         me.selectedProperty = property;

         me.enableEnterList( property );

      } );

      me.getComponent( "removeButton" ).on( 'click', function(button, event) {

         var item = button.ownerCt;
         var filterContainer = item.ownerCt;
         filterContainer.remove( item );
         filterContainer.doLayout();

         if ( filterContainer.ownerCt.closeEmptyFilter )
            filterContainer.ownerCt.closeEmptyFilter();
      } );

      me.getComponent( "enterListButton" ).on( 'click', function(button, event) {
         example.destroy();
         ASPIREdb.view.filter.TextImportWindow.setPropertyFilterAndShow( me );
      } );

      propertyComboBox.getStore().on( 'load', function(store, records, successful) {

         var properties = [];
         for (var i = 0; i < records.length; i++) {
            properties.push( records[i].data.displayName );
         }
         // add Gene Set to the property list
         properties.push( 'GeneSet' );
         var geneSetProperty = new Property();
         geneSetProperty.displayName = 'GeneSet';
         geneSetProperty.name = 'GeneSet';
         store.data.add( geneSetProperty );

         propertyComboBox.select( store.getAt( 0 ) );
         propertyComboBox.fireEvent( 'select', propertyComboBox, [ store.getAt( 0 ) ] );
      } );

      propertyComboBox.getStore().on( 'datachanged', function(store, e0pts) {
         console.log( 'datachanged fired' );

      } );
   },

   contextMenuSelectionHandler : function(selProperty) {

      Ext.Msg.alert( 'Selected Sub-Property', selProperty.displayName + '  selected' );
      var propertyComboBox = this.getComponent( "propertyComboBox" );
      var existingStore = propertyComboBox.getStore();

      var newStore = Ext.create( 'Ext.data.Store', {
         model : 'ASPIREdb.model.Property',
         autoLoad : true,
         displayField : 'displayName',
         filterItemType : 'ASPIREdb.view.filter.PropertyFilter',
      } );

      existingStore.add( me.selectedProperty );
      propertyComboBox.select( store.getAt( 0 ) );
   },

   enableEnterList : function(property) {

      if ( property.displayName == 'Location' || property.displayName == 'Gene'
         || property.displayName == 'Neurocarta Phenotype' ) {

         this.getComponent( "enterListButton" ).enable();
         this.getComponent( "enterListButton" ).show();

      } else {
         this.getComponent( "enterListButton" ).disable();
         this.getComponent( "enterListButton" ).hide();
      }

   },

   setOperationLabel : function(operation) {
      this.down( '#operationLabel' ).setText( operation );
   }

} );