text:
<?php
namespace yiiunit\framework\validators;

use yiiunit\data\validators\models\FakedValidationModel;
use yii\validators\BooleanValidator;
use yiiunit\TestCase;

/**
 * BooleanValidatorTest
 */
class BooleanValidatorTest extends TestCase
{
	protected function setUp()
	{
		parent::setUp();
		$this->mockApplication();
	}

	public function testValidateValue()
	{
		$val = new BooleanValidator;
		$this->assertTrue($val->validate(true));
		$this->assertTrue($val->validate(false));
		$this->assertTrue($val->validate('0'));
		$this->assertTrue($val->validate('1'));
		$this->assertFalse($val->validate(null));
		$this->assertFalse($val->validate([]));
		$val->strict = true;
		$this->assertTrue($val->validate('0'));
		$this->assertTrue($val->validate('1'));
		$this->assertFalse($val->validate(true));
		$this->assertFalse($val->validate(false));
		$val->trueValue = true;
		$val->falseValue = false;
		$this->assertFalse($val->validate('0'));
		$this->assertFalse($val->validate([]));
		$this->assertTrue($val->validate(true));
		$this->assertTrue($val->validate(false));
	}

	public function testValidateAttributeAndError()
	{
		$obj = new FakedValidationModel;
		$obj->attrA = true;
		$obj->attrB = '1';
		$obj->attrC = '0';
		$obj->attrD = [];
		$val = new BooleanValidator;
		$val->validateAttribute($obj, 'attrA');
		$this->assertFalse($obj->hasErrors('attrA'));
		$val->validateAttribute($obj, 'attrC');
		$this->assertFalse($obj->hasErrors('attrC'));
		$val->strict = true;
		$val->validateAttribute($obj, 'attrB');
		$this->assertFalse($obj->hasErrors('attrB'));
		$val->validateAttribute($obj, 'attrD');
		$this->assertTrue($obj->hasErrors('attrD'));
	}
}


text:
[Demonstration](http://git.macropus.org/jquery-ajax-queue/demo/)

## Usage

### Make a request

    $.ajaxQueue(params, options);

`params`: parameters object, passed through to [jQuery.ajax](http://api.jquery.com/jquery.ajax/)

`options`: options object, for the queued item

* `queue: string`: queue name (default = 'default')
* `priority: boolean`: true = insert at the front of the queue (default = false)
* `tries: integer`: retry the request n times if it fails due to server error (default = 3)
* `limit: integer`: delay, in milliseconds, after this request (default = 0)

### Set the number of concurrent requests

    $.ajaxQueue.concurrent(n);

`n`: how many requests to run concurrently (will cause responses to return out of sequence)

redpajama_set_name: RedPajamaGithub


text:
package com.github.financing.adapter;

import android.database.DataSetObserver;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import com.github.financing.views.loopPage.HintView;
import com.github.financing.views.loopPage.RollPagerView;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * Created by Mr.Jude on 2016/1/9.
 */
public abstract class LoopPagerAdapter extends PagerAdapter{
    private RollPagerView mViewPager;

    private ArrayList<View> mViewList = new ArrayList<>();

    private class LoopHintViewDelegate implements RollPagerView.HintViewDelegate{
        @Override
        public void setCurrentPosition(int position, HintView hintView) {
            if (hintView!=null&&getRealCount()>0)
                hintView.setCurrent(position%getRealCount());
        }

        @Override
        public void initView(int length, int gravity, HintView hintView) {
            if (hintView!=null)
                hintView.initView(getRealCount(),gravity);
        }
    }

    @Override
    public void notifyDataSetChanged() {
        mViewList.clear();
        initPosition();
        super.notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) {
        super.registerDataSetObserver(observer);
        initPosition();
    }

    private void initPosition(){
        if (mViewPager.getViewPager().getCurrentItem() == 0&&getRealCount()>0){
            int half = Integer.MAX_VALUE/2;
            int start = half - half%getRealCount();
            setCurrent(start);
        }
    }

    private void setCurrent(int index){
        try {
            Field field = ViewPager.class.getDeclaredField("mCurItem");
            field.setAccessible(true);
            field.set(mViewPager.getViewPager(),index);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public LoopPagerAdapter(RollPagerView viewPager){
        this.mViewPager = viewPager;
        viewPager.setHintViewDelegate(new LoopHintViewDelegate());
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0==arg1;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        int realPosition = position%getRealCount();
        View itemView = findViewByPosition(container,realPosition);
        container.addView(itemView);
        return itemView;
    }

    private View findViewByPosition(ViewGroup container,int position){
        for (View view : mViewList) {
            if (((int)view.getTag()) == position&&view.getParent()==null){
                return view;
            }
        }
        View view = getView(container,position);
        view.setTag(position);
        mViewList.add(view);
        return view;
    }

    public abstract View getView(ViewGroup container, int position);

    @Deprecated
    @Override
    public final int getCount() {
        return getRealCount()<=0?getRealCount():Integer.MAX_VALUE;
    }

    public abstract int getRealCount();
}


text:
package org.jboss.weld.tests.beanManager.extension;

import jakarta.enterprise.inject.spi.Extension;

public class AlphaExtension implements Extension {

    private String state;

    public String getState() {
        return state;
    }

    void setState(String state) {
        this.state = state;
    }
}


text:
module Revily
  module Event
    # a sorted list of all available events matching a collection of patterns
    # ignores patterns that don't match any events
    class EventList
      attr_accessor :patterns, :events

      def initialize(*patterns)
        patterns = patterns.compact.any? ? patterns : %w[ * ]
        @patterns = clean_patterns(patterns)
        @events = expand(@patterns)
      end

      def events
        expand(patterns)
      end

      def patterns=(*patterns)
        @patterns = clean_patterns(patterns)
      end

      protected

        def clean_patterns(*patterns)
          patterns.flatten.map { |pattern| pattern == "*" ? ".*" : pattern }
        end

        def make_regexp(*patterns)
          /^(#{patterns.join("|")})$/
        end

        def expand(*patterns)
          Revily::Event.all.grep(make_regexp(patterns)).uniq.sort
        end

    end
  end
end


text:
import sys
import time

from elastictools import *

# Globals
EXIT_SUCCESS = 0
EXIT_FAILURE = 1

ES_NODE_HOST = "localhost"
ES_NODE_PORT = "9200"
ES_REQ_WAIT_SECS = 1

# Class: Elasticsearch Shard
class UETReassign(ESShard):
	# SECTION: Handler
	def tool_reassign_shards(self):
		for count, shard in enumerate(filter(lambda s: (s[3] == "UNASSIGNED"), self.shard_data_list)):
			sys.stdout.write("    * Re-assigning shard '%s' of type '%s' from index '%s' to node '%s' on host '%s' (%s of %s)... " % (shard[1], shard[2], shard[0], self.shard_node_list[count % len(self.shard_node_list)], self.es_host, count + 1, self.shard_status_unassigned_count()))

			post_data = {
			    "commands" : [ {
			        "allocate" : {
				    "index"         : "%s" % shard[0],
			            "shard"         : "%s" % shard[1],
			            "node"          : "%s" % self.shard_node_list[count % len(self.shard_node_list)],
			            "allow_primary" : True
			        }
			    } ]
			}

			# Request cluster reroute op for the current unassigned shard
			res = self.es_request_http("POST", "/_cluster/reroute", post_data)

			# TODO: 400 is obviously an error, but is there more stuff to be handled here?
			if res["status"] == 400:
				print(res["error"])
				print("Failed.")
				continue

			print("Reassigned.")

			self.shard_stat_reassigned += 1

			time.sleep(ES_REQ_WAIT_SECS)

	def do(self):
		print("Loading shard status...")
		self.shard_status_load()
		print("Parsing shard data...")
		self.shard_status_parse()

		print("  * Number of shards started:      %s" % self.shard_status_started_count())
		print("  * Number of shards initializing: %s" % self.shard_status_initializing_count())
		print("  * Number of shards unassigned:   %s" % self.shard_status_unassigned_count())
		print("  * Total number of shards:        %s" % self.shard_status_total_count())

		# Re-assign shards if unassigned shards are present
		if self.shard_status_unassigned_count():
			print("Enabling routing allocation...")
			self.cluster_settings_set("cluster.routing.allocation.enable", "all")
			print("Reassigning unassigned shards...")
			self.tool_reassign_shards()

		# Check if there are shards in initializing state
		if self.shard_status_initializing_count():
			print("There are shards in initialization state. If the problem persists, restart the node.")

		print("\nSummary:")
		print("  * Reassigned shards: %d" % self.shard_stat_reassigned)
		print("  * Failed Reassigns:  %d" % self.shard_stat_failed_reassign)
		print("  * Moved shards:      %d" % self.shard_stat_moved)
		print("  * Failed moves:      %d" % self.shard_stat_failed_move)
		print("  * Total warnings:    %d" % self.warnings)
		print("  * Total errors:      %d" % self.errors)

		print("\nResetting data...")
		self.shard_reset_data_status()
		print("Loading shard status...")
		self.shard_status_load()
		print("Parsing shard data...")
		self.shard_status_parse()

		print("\nCurrent status:")
		print("  * Number of shards started:      %s" % self.shard_status_started_count())
		print("  * Number of shards initializing: %s" % self.shard_status_initializing_count())
		print("  * Number of shards unassigned:   %s" % self.shard_status_unassigned_count())
		print("  * Total number of shards:        %s" % self.shard_status_total_count())

		print("\nDone.")

# Class: Usage
class Usage:
	args = {
		"target": None
	}

	def usage_show(self):
		print("Usage: %s <target filename OR url>" % (sys.argv[0]))

	def usage_check(self):
		if len(sys.argv) > 2:
			self.usage_show()
			sys.exit(EXIT_FAILURE)
		elif len(sys.argv) < 2:
			self.args["target"] = "http://%s:%s" % (ES_NODE_HOST, ES_NODE_PORT)

	def do(self):
		self.usage_check()

		if self.args["target"] == None:
			self.args["target"] = sys.argv[1]

class Main:
	def do(self):
		usage = Usage()
		usage.do()
		elastic = UETReassign(usage.args["target"])
		elastic.do()

## Entry Point
if __name__ == "__main__":
	Main().do()


text:
<# This module is part of the automated release process for SharePoint solutions.  It uses the Client Side Object Model.
#  Author: Tim Wheeler (http://blog.timwheeler.tech/)
#  Attribution: Some functions and approaches have been taken (and may have been updated) from other sources online.
#  Unfortunately I have not kept those links.  If you know of the source locations please let me know and I'll happilly attribute.
#>

$productName =" sp-clientapps automated release process"

Function Install-DisplayTemplates($context, $web, $location)
{
	$path = [System.IO.Path]::Combine($location, "DisplayTemplates")
	$xmlFilePath = [System.IO.Path]::Combine($path, "DisplayTemplates.xml")
    if((Test-Path $path) -eq $false -or (Test-Path $xmlFilePath) -eq $false)
    {
      write-host "No Display Templates to deploy"
      return
    }

	$list = $context.Site.GetCatalog([Microsoft.SharePoint.Client.ListTemplateType]::MasterPageCatalog)
	$context.Load($list)
    $context.Load($list.RootFolder)

	$context.ExecuteQuery();
	$publishingEnabled = $list.EnableModeration
	$versioningEnabled = $list.EnableVersioning

	[xml]$settingsFile = Get-Content $xmlFilePath
	$files = Get-ChildItem $path -Recurse | Where-Object { $_.PSIsContainer -eq $false}
	foreach($file in $files)
	{
		if($file.Name -eq "DisplayTemplates.xml" -or $file.Extension -eq ".js")
		{
			continue
		}
		Write-Host "Uploading Display Template $($file.Name)"
		$properties = $settingsFile.xml.DisplayTemplates.DisplayTemplate | where-object { $_.FileName -eq $file.Name}
        $folderUrl = "/Display Templates" + ($file.FullName -ireplace [regex]::escape($path),"") -ireplace "\\","/" -ireplace ("/" + [regex]::escape($file.Name)), ""
        $fileUrl = ($folderUrl + "/" + $file.Name)
        if([string]::IsNullOrEmpty($folderUrl) -eq $false)
        {
		    Ensure-Folder -Web $web -ParentFolder $list.RootFolder -FolderUrl $folderUrl | out-null
        }
        $fullFileUrl = Combine-Url $list.RootFolder.ServerRelativeUrl $fileUrl
        $properties.Attributes.RemoveNamedItem("FileName") | out-null
        UploadFile $context $web $file $fullFileUrl $properties $versioningEnabled $publishingEnabled | out-null
	}
}
Function Install-WebParts($context, $web, $location, $csomVersion)
{
	$path = [System.IO.Path]::Combine($location, "WebParts")
    if((Test-Path $path) -eq $false )
    {
        write-host "No Web Parts to deploy"
        return
    }

	$list = $context.Site.GetCatalog([Microsoft.SharePoint.Client.ListTemplateType]::WebPartCatalog)
	$context.Load($list)
    $context.Load($list.RootFolder)

	$context.ExecuteQuery();
	$publishingEnabled = $list.EnableModeration
	$versioningEnabled = $list.EnableVersioning

	$files = Get-ChildItem $path -Recurse | Where-Object { $_.PSIsContainer -eq $false}
	foreach($file in $files)
	{
		Write-Host "Uploading Web Part $($file.Name)"
        if($context.HasPendingRequest)
        {
            $context.ExecuteQuery()
        }
        $folderUrl =  ($file.FullName -ireplace [regex]::escape($path),"") -ireplace "\\","/" -ireplace ("/" + [regex]::escape($file.Name)), ""
        $fileUrl = ($folderUrl + "/" + $file.Name)
        $fullFileUrl = $list.RootFolder.ServerRelativeUrl + $fileUrl
        [xml]$properties = '<xml><WebPart Group="Client Apps"/></xml>'
		$replaceWith = $web.ServerRelativeUrl
        if($replaceWith -eq "/")
		{
			$replaceWith = "";
		}
        if($csomVersion -eq "15")
        {
            $tempFileName = New-TempFile $file.FullName
            Convert-FileTo2013 $tempFileName
            UploadFile $context $web (Get-ChildItem $tempFileName) $fullFileUrl $properties.xml.WebPart $versioningEnabled $publishingEnabled | out-null
            Remove-Item $tempFileName -Force
        }
        else
        {
            UploadFile $context $web $file $fullFileUrl $properties.xml.WebPart $versioningEnabled $publishingEnabled | out-null
        }
	}
}
Function Install-StyleLibrary($context, $web, $location)
{
	$path = [System.IO.Path]::Combine($location, "Style Library")
  if((Test-Path $path) -eq $false)
  {
      write-host "No Style Library assets to deploy"
      return
  }
	$list = $web.Lists.GetByTitle("Style Library");
	$context.Load($list)
  $context.Load($list.RootFolder)
	$context.ExecuteQuery();
	$publishingEnabled = $list.EnableModeration
	$versioningEnabled = $list.EnableVersioning
  $files = Get-ChildItem $path -Recurse | Where-Object { $_.PSIsContainer -eq $false}
  foreach($file in $files)
	{
		$folderUrl =  ($file.FullName -ireplace [regex]::escape($path),"") -ireplace "\\","/" -ireplace ("/" + [regex]::escape($file.Name)), ""
        $fileUrl = ($folderUrl + "/" + $file.Name)
		if([string]::IsNullOrEmpty($folderUrl) -eq $false)
		{
			Ensure-Folder -Web $web -ParentFolder $list.RootFolder -FolderUrl $folderUrl | out-null
		}
        $fullFileUrl = $list.RootFolder.ServerRelativeUrl + $fileUrl
        UploadFile $context $web $file $fullFileUrl $null $versioningEnabled $publishingEnabled | out-null
	}
}
Function Install-CommonFiles($context, $web, $location)
{
    throw "Obsolete - use the common client app"
    Write-Host "Deploying common files to Style Library"
	$path = $location
      if((Test-Path $path) -eq $false)
      {
          write-host "No Style Library\Client Apps\Common assets to deploy"
          return
      }

	$list = $web.Lists.GetByTitle("Style Library");
	$context.Load($list)
  $context.Load($list.RootFolder)
	$context.ExecuteQuery();
	$publishingEnabled = $list.EnableModeration
	$versioningEnabled = $list.EnableVersioning
  $files = Get-ChildItem $path -Recurse | Where-Object { $_.PSIsContainer -eq $false}
  $commonFolderUrl = "Client Apps/Common"
  Ensure-Folder -Web $web -ParentFolder $list.RootFolder -FolderUrl $commonFolderUrl | out-null
  foreach($file in $files)
	{
		$folderUrl =  ($file.FullName -ireplace [regex]::escape($path),"") -ireplace "\\","/" -ireplace ("/" + [regex]::escape($file.Name)), ""
        $fileUrl = ($folderUrl + "/" + $file.Name)
        $folderUrl = Combine-Url $commonFolderUrl $folderUrl
		if([string]::IsNullOrEmpty($folderUrl) -eq $false)
		{
			Ensure-Folder -Web $web -ParentFolder $list.RootFolder -FolderUrl $folderUrl | out-null
		}
        $fullFileUrl = Combine-Url $list.RootFolder.ServerRelativeUrl $commonFolderUrl $fileUrl
        UploadFile $context $web $file $fullFileUrl $null $versioningEnabled $publishingEnabled | out-null
	}
}
Function Install-PublishingImages($context, $web, $location)
{
	$path = [System.IO.Path]::Combine($location, "PublishingImages")
    if((Test-Path $path) -eq $false)
    {
        write-host "No Publishing to deploy"
        return
    }
	$list = $web.Lists.GetByTitle("Images");
	$context.Load($list)
	$context.Load($list.RootFolder)
	$context.ExecuteQuery();
	$publishingEnabled = $list.EnableModeration
	$versioningEnabled = $list.EnableVersioning

    $files = Get-ChildItem $path -Recurse | Where-Object { $_.PSIsContainer -eq $false}
    foreach($file in $files)
	{
		$folderUrl = $file.SubFolder #  ($file.FullName -ireplace [regex]::escape($path),"") -ireplace "\\","/" -ireplace ("/" + [regex]::escape($file.Name)), ""
        $fileUrl =  ($folderUrl + "/" + $file.Name)
		if([string]::IsNullOrEmpty($folderUrl) -eq $false)
		{
			Ensure-Folder -Web $web -ParentFolder $list.RootFolder -FolderUrl $folderUrl
		}
        $fullFileUrl = $list.RootFolder.ServerRelativeUrl + $fileUrl
        UploadFile $context $web $file $fullFileUrl $null $versioningEnabled $publishingEnabled | out-null
	}
}
#This creates the lists only.  not fields or cts
Function Install-Lists($context, $web, $location)
{
	$path = [System.IO.Path]::Combine($location, "Lists\Lists.xml")
    if((Test-Path $path) -eq $false)
    {
        Write-Host "No lists to deploy"
        return
    }
    $xmlFilePath = [System.IO.Path]::Combine($location, "Lists\Lists.xml")
    [xml] $listXml = Get-Content $xmlFilePath
    $lists = $listXml.xml.Lists.List
    $rootWeb = $context.Site.RootWeb
    $context.Load($web.Lists)
    $context.Load($rootWeb.Lists)
    $context.ExecuteQuery();
    foreach($listDef in $lists)
    {
        $targetWeb = $web
        if(Is-True $listDef.rootWeb)
        {
            $targetWeb = $rootWeb
        }
        else {
            $targetWeb = $web
        }

        $list = $targetWeb.Lists | Where-Object { $_.Title -eq $listDef.Title}

        if($list -eq $null -or $list.Count -eq 0)
        {
            $listInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
            $listInfo.Title = $listDef.Title
            $listInfo.TemplateType = $listDef.TemplateType
            $list = $targetWeb.Lists.Add($listInfo)
            $list.Description = $listDef.Description
            $list.Update()
            write-host "Creating List {$list.Title}"
            $Context.ExecuteQuery()
        }
    }
}

#Provision the list, add the list content types and reorder CT's.  Last CT added wins.
Function Install-ConfigureLists($context, $web, $location)
{
	$path = [System.IO.Path]::Combine($location, "Lists\Lists.xml")
    if((Test-Path $path) -eq $false)
    {
        Write-Host "No lists to deploy"
        return
    }
    $xmlFilePath = [System.IO.Path]::Combine($location, "Lists\Lists.xml")
    [xml] $listXml = Get-Content $xmlFilePath
    $lists = $listXml.xml.Lists.List
    $rootWeb = $context.Site.RootWeb
    $context.Load($web.Lists)
    $context.Load($rootWeb.Lists)
    $context.ExecuteQuery();
    foreach($listDef in $lists)
    {
        $targetWeb = $web
        if(Is-True $listDef.rootWeb)
        {
            $targetWeb = $rootWeb
        }
        else {
            $targetWeb = $web
        }

        $list = $targetWeb.Lists | Where-Object { $_.Title -eq $listDef.Title}

        if($list -eq $null -or $list.Count -eq 0)
        {
            $listInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
            $listInfo.Title = $listDef.Title
            $listInfo.TemplateType = $listDef.TemplateType
            $list = $targetWeb.Lists.Add($listInfo)
            $list.Description = $listDef.Description
            $list.Update()
            $Context.ExecuteQuery()
        }
        $contentTypes = $list.ContentTypes
        $context.Load($contentTypes)
        $context.Load($list.RootFolder)
        $context.Load($list.ContentTypes)
        $context.ExecuteQuery()
        $ctNames =  $contentTypes | Select -ExpandProperty Name
        foreach($contentTypeDef in $listDef.ContentTypes.ContentType)
        {
            if($contentTypeDef.Name -eq "Item" -or $contentTypeDef.Name -eq "Document" -or $contentTypeDef.Name -eq "Folder")
            {
                continue; #causes issues trying to re add them.
            }
            #Dev Note: The list ct id is not part of the web cts, so we need to look for the parent id only.
            $parentContentTypeId = Get-ParentContentTypeId $contentTypeDef.ID
            $contentType = $contentTypes | Where-Object {
                $_.ID.StringValue.Length -ge $parentContentTypeId.Length -and
                $parentContentTypeId -eq $_.ID.StringValue.SubString(0,$parentContentTypeId.Length)
            }
            if($contentType -eq $null -or $contentType.Count -eq 0)
            {
				Write-host "Looking for parent Content Type $parentContentTypeId ($($contentTypeDef.Name))"
                try {
                    $contentType = $context.Site.RootWeb.ContentTypes.GetById($parentContentTypeId)
                    $context.Load($contentType)
                    $Context.ExecuteQuery()
                }
                catch
                {
                    Write-Error "Could not load parent Content Type $parentContentTypeId ($($contentTypeDef.Name)), ensure it exists in the root web"
                    continue;
                }
                if($contentType -eq $null -or $contentType.Id -eq $null)
                {
                    throw "Could not find content type $($contentTypeDef.Name)"
                    continue;
                }
                #look for CT in list, if it exists ignore.
                if($ctNames.Contains($contentTypeDef.Name))
                {
                    write-host "Content Type $($contentType.Name) already exists in list $($list.Title)"
                    continue
                }
                write-host "Adding CT $($contentTypeDef.Name) to list $($listDef.Title)"

                $list.ContentTypesEnabled = $true
                $listContentType = $list.ContentTypes.AddExistingContentType($contentType)
                $list.Update()
                $context.Load($list)
                $context.Load($list.RootFolder)
                $context.Load($listContentType)
                $context.ExecuteQuery()
                #DevNote: You must commit these changes and reload before trying to reorder.
                $ctOrdered = New-Object System.Collections.Generic.List[Microsoft.SharePoint.Client.ContentTypeId]
                $ctOrdered.Add($listContentType.Id)
                foreach($ct in $list.ContentTypes)
                {
                    if($ct -eq $listContentType -or $ct.Name -eq "Folder")
                    {
                        continue;
                    }
                    $ctOrdered.Add($ct.Id)
                }
                $list.RootFolder.UniqueContentTypeOrder = $ctOrdered
                $list.Update()
                $context.Load($list)
                $context.ExecuteQuery()
            }
        }
    }
}

#if null or empty return the default.
function GetWithDefault($value, $default){
    if($value -eq $null)
    {
        return $default
    }
    if([string]::IsNullOrEmpty($value))
    {
        return $default
    }
    return $value
}
#Uses a SiteFields.xml file to deploy fields if they dont exist
Function Install-SiteFields($context, $web, $location)
{
    $path = [System.IO.Path]::Combine($location, "SiteFields")
	$xmlFilePath = [System.IO.Path]::Combine($path, "SiteFields.xml")
    if((Test-Path $path) -eq $false -or (Test-Path $xmlFilePath) -eq $false)
    {
        write-host "No Site Fields to deploy"
        return
    }

    # Handle Lookup fields
    $listManifestPath = [System.IO.Path]::Combine($location, "Lists")
	$listXmlFilePath = [System.IO.Path]::Combine($listManifestPath, "Lists.xml")
    $lists = @{}
    if((Test-Path $listManifestPath) -eq $false -or (Test-Path $listXmlFilePath) -eq $false)
    {
        write-warning "No List manifest could be found, Choice columns may not be accurate"
    }
    else {
        #load the list details
        [xml]$listsXML = Get-Content $listXmlFilePath
        foreach($listDef in $listsXML.xml.Lists.List)
        {
            $list = $web.Lists.GetByTitle($listDef.Title)
            $context.Load($list)
            if($listDef.Id -ne $null)
            {
                $lists.Add($listDef.Id, $list);
            }
        }
        if($lists.Count -gt 0) {
            $context.ExecuteQuery();
        }
    }

    [xml]$fieldsXML = Get-Content $xmlFilePath

    $context.Load($web.Fields)
    $context.ExecuteQuery()

    $fieldsXML.xml.Fields.Field | ForEach-Object {
    if($_ -eq $null)
    {
        return
    }
    #Configure core properties belonging to all column types
    $fieldXML = '<Field Type="' + $_.Type + '"
    Name="' + $_.Name + '"
    ID="' + $_.ID + '"
    Description="' + $_.Description + '"
    DisplayName="' + $_.DisplayName + '"
    StaticName="' + $_.StaticName + '"
    Group="' + $_.Group + '"
    Hidden="' + (GetWithDefault $_.Hidden "FALSE") + '"
    Required="' + $_.Required + '"
    Sealed="' + (GetWithDefault $_.Sealed, "FALSE") + '"'

    #Configure optional properties belonging to specific column types - you may need to add some extra properties here if present in your XML file
    if ($_.ShowInDisplayForm) { $fieldXML = $fieldXML + "`n" + 'ShowInDisplayForm="' + $_.ShowInDisplayForm + '"'}
    if ($_.ShowInEditForm) { $fieldXML = $fieldXML + "`n" + 'ShowInEditForm="' + $_.ShowInEditForm + '"'}
    if ($_.ShowInListSettings) { $fieldXML = $fieldXML + "`n" + 'ShowInListSettings="' + $_.ShowInListSettings + '"'}
    if ($_.ShowInNewForm) { $fieldXML = $fieldXML + "`n" + 'ShowInNewForm="' + $_.ShowInNewForm + '"'}

    if ($_.EnforceUniqueValues) { $fieldXML = $fieldXML + "`n" + 'EnforceUniqueValues="' + $_.EnforceUniqueValues + '"'}
    if ($_.Indexed) { $fieldXML = $fieldXML + "`n" + 'Indexed="' + $_.Indexed + '"'}
    if ($_.Format) { $fieldXML = $fieldXML + "`n" + 'Format="' + $_.Format + '"'}
    if ($_.MaxLength) { $fieldXML = $fieldXML + "`n" + 'MaxLength="' + $_.MaxLength + '"' }
    if ($_.FillInChoice) { $fieldXML = $fieldXML + "`n" + 'FillInChoice="' + $_.FillInChoice + '"' }
    if ($_.NumLines) { $fieldXML = $fieldXML + "`n" + 'NumLines="' + $_.NumLines + '"' }
    if ($_.RichText) { $fieldXML = $fieldXML + "`n" + 'RichText="' + $_.RichText + '"' }
    if ($_.RichTextMode) { $fieldXML = $fieldXML + "`n" + 'RichTextMode="' + $_.RichTextMode + '"' }
    if ($_.IsolateStyles) { $fieldXML = $fieldXML + "`n" + 'IsolateStyles="' + $_.IsolateStyles + '"' }
    if ($_.AppendOnly) { $fieldXML = $fieldXML + "`n" + 'AppendOnly="' + $_.AppendOnly + '"' }
    if ($_.Sortable) { $fieldXML = $fieldXML + "`n" + 'Sortable="' + $_.Sortable + '"' }
    if ($_.RestrictedMode) { $fieldXML = $fieldXML + "`n" + 'RestrictedMode="' + $_.RestrictedMode + '"' }
    if ($_.UnlimitedLengthInDocumentLibrary) { $fieldXML = $fieldXML + "`n" + 'UnlimitedLengthInDocumentLibrary="' + $_.UnlimitedLengthInDocumentLibrary + '"' }
    if ($_.CanToggleHidden) { $fieldXML = $fieldXML + "`n" + 'CanToggleHidden="' + $_.CanToggleHidden + '"' }
    if ($_.List) { $fieldXML = $fieldXML + "`n" + 'List="' + $_.List + '"' }
    if ($_.ShowField) { $fieldXML = $fieldXML + "`n" + 'ShowField="' + $_.ShowField + '"' }
    if ($_.UserSelectionMode) { $fieldXML = $fieldXML + "`n" + 'UserSelectionMode="' + $_.UserSelectionMode + '"' }
    if ($_.UserSelectionScope) { $fieldXML = $fieldXML + "`n" + 'UserSelectionScope="' + $_.UserSelectionScope + '"' }
    if ($_.BaseType) { $fieldXML = $fieldXML + "`n" + 'BaseType="' + $_.BaseType + '"' }
    if ($_.Mult) { $fieldXML = $fieldXML + "`n" + 'Mult="' + $_.Mult + '"' }
    if ($_.ReadOnly) { $fieldXML = $fieldXML + "`n" + 'ReadOnly="' + $_.ReadOnly + '"' }
    if ($_.FieldRef) { $fieldXML = $fieldXML + "`n" + 'FieldRef="' + $_.FieldRef + '"' }

    #Update Lookup Field Id's
    if ($_.Type -eq "Lookup") {
        #This will replace the List="[Guid]" with the current lists id as these change in new environments.
        foreach($mapping in $lists.Keys){
            $fieldXML = $fieldXML -ireplace $mapping, $lists[$mapping].Id
        }
        $fieldXML = $fieldXML + " WebId=`"" + $web.Id  + "`""
    }

    $fieldXML = $fieldXML + ">"
    #Create choices if choice column
    if ($_.Type -eq "Choice") {
        $fieldXML = $fieldXML + "`n<CHOICES>"
        $_.Choices.Choice | ForEach-Object {
           $fieldXML = $fieldXML + "`n<CHOICE>" + $_ + "</CHOICE>"
        }
        $fieldXML = $fieldXML + "`n</CHOICES>"
    }

    #Set Default value, if specified
    if ($_.Default) { $fieldXML = $fieldXML + "`n<Default>" + $_.Default + "</Default>" }

    #End XML tag specified for this field
    $fieldXML = $fieldXML + "</Field>"

    $iterator = $_
    $field = $web.Fields | Where-Object { $_.ID -icontains $iterator.ID }

    if($field -eq $null)
    {
        $web.Fields.AddFieldAsXml($fieldXML.Replace("&","&"), $false, [Microsoft.SharePoint.Client.AddFieldOptions]::AddToAllContentTypes) | out-null
        write-host "Creating site column" $_.DisplayName "on" $web.Url
    }
    else {
        $field.SchemaXml = $fieldXML.Replace("&","&")
        $field.Update()
        write-host "Updating site column" $_.DisplayName "on" $web.Url
    }
    $context.ExecuteQuery()
    }

}
# Creates content types and field links if they don't exist
#This method may generate errors if you haven't aquired all fields in the Build process.
Function Install-ContentTypes($context, $web, $location)
{

    $path = [System.IO.Path]::Combine($location, "ContentTypes")
	$xmlFilePath = [System.IO.Path]::Combine($path, "ContentTypes.xml")
    if((Test-Path $path) -eq $false -or (Test-Path $xmlFilePath) -eq $false)
    {
        write-host "No Site Fields to deploy"
        return
    }
    [xml]$ctsXML = Get-Content $xmlFilePath
    $context.Load($web.Fields)
    $context.Load($web.AvailableContentTypes)
    $context.ExecuteQuery()

    $ctsXML.xml.ContentTypes.ContentType | ForEach-Object {

    if($_ -eq $null)
    {
        return
    }
    $iterator = $_
    write-host ("Processing Content Type : " + $_.Name)
    $spContentType = $web.AvailableContentTypes | Where {$_.Name -eq $iterator.Name}
    $requiresUpdate = $false
    if($spContentType -eq $null)
    {
        #Create Content Type object inheriting from parent
        [Microsoft.SharePoint.Client.ContentTypeCreationInformation] $spContentTypeCI = new-object Microsoft.SharePoint.Client.ContentTypeCreationInformation
        $spContentTypeCI.Id = $_.ID
        $spContentTypeCI.Name = $_.Name
        #$spContentType.ParentContentType = $parentContentType
        $spContentTypeCI.Group = $_.Group
        $spContentType = $web.ContentTypes.Add($spContentTypeCI)
        $spContentType.Description = $_.Description
        $spContentType.Group = $_.Group
        $requiresUpdate = $true
    }

    #Set Content Type description and group

    $context.Load($spContentType.FieldLinks)
    $context.Load($spContentType.Fields)
    $context.ExecuteQuery()

    write-host "Adding field links"
    foreach($fieldDef in $_.Fields.Field) {
        if($fieldDef.DisplayName.contains(":"))
        {
            #these fields must be skipped (The choice additional fields automatically added).
            continue;
        }
        $doesFieldExist = $false
        foreach($fld in $spContentType.Fields)
        {
            if($fld.get_InternalName() -eq $fieldDef.Name){
               $doesFieldExist = $true
               break
            }
        }
        if($doesFieldExist -eq $false)
            {
                #Get all the columns associated with content type
                $fieldRefCollection = $spContentType.FieldLinks;

                #Add a new column to the content type
                $fieldName = $fieldDef.Name
                $field = $web.Fields | Where-Object { $_.InternalName -eq $fieldName }
                if($field -eq $null)
                {
                    Write-Error "The field $fieldName is not found in the Site Fields.  This means the field was not aquired through the build process. The group is $($fieldDef.Group)." -ErrorAction:Continue
                    continue;
                }

                Write-Host "Adding site column " $fieldDef.Name "to the content type" -ForegroundColor Cyan
                $fieldReferenceLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation
                $fieldReferenceLink.Field = $field;
                $fieldLink = $spContentType.FieldLinks.Add($fieldReferenceLink);
                $fieldLink.Required =  ($fieldDef.Required -ieq "TRUE")
                $fieldLink.Hidden =  ($fieldDef.Hidden -ieq "TRUE")

                $requiresUpdate = $true
                Write-Host "Field added successfully" -ForegroundColor Green
            }
       }

    #Create Content Type on the site and update Content Type object
    if($requiresUpdate)
    {
        $spContentType.Update($true)
        $context.ExecuteQuery()
        write-host "Content type" $fieldDef.Name "has been create/updated" -ForegroundColor Green
    }
    else {
        write-host "Content type" $fieldDef.Name "exists and has no updates"
    }
  }
}

#Creates page layouts.  Uses a PageLayouts.xml to get metadata.
#layout is uploaded and metadata set. $subFolderPath is the sub directory in the master page library and should the be project name.
Function Install-PageLayouts($context, $web, $location, $subFolderPath, $csomVersion)
{
  $path = [System.IO.Path]::Combine($location, "PageLayouts")
  $xmlFilePath = [System.IO.Path]::Combine($path, "PageLayouts.xml")
    if((Test-Path $path) -eq $false -or (Test-Path $xmlFilePath) -eq $false)
    {
        write-host "No Site Fields to deploy"
        return
    }

  $masterPageUrl = Combine-Url $web.ServerRelativeUrl "_catalogs" "masterpage"
  $list = $context.Site.GetCatalog([Microsoft.SharePoint.Client.ListTemplateType]::MasterPageCatalog)
  $context.Load($list)
  $context.Load($list.RootFolder)

  $context.ExecuteQuery();
  $publishingEnabled = $list.EnableModeration
  $versioningEnabled = $list.EnableVersioning

  [xml]$settingsFile = Get-Content $xmlFilePath
  $files = Get-ChildItem $path -Recurse | Where-Object { $_.PSIsContainer -eq $false} # -and $_.Name -eq "FileName.aspx"
  foreach($file in $files)
  {
    if($file.Name -eq "PageLayouts.xml")
    {
      continue
    }
    Write-Host "Uploading Page Layout $($file.Name)"
    $properties = $settingsFile.xml.Layouts.Layout | where-object { $_.FileName -eq $file.Name}
    #$folderUrl =   ($file.FullName -ireplace [regex]::escape($path),"") -ireplace "\\","/" -ireplace ("/" + [regex]::escape($file.Name)), ""
    $folderUrl =  $subFolderPath
    $fileUrl = Combine-Url $folderUrl $file.Name
    if([string]::IsNullOrEmpty($folderUrl) -eq $false)
    {
        Ensure-Folder -Web $web -ParentFolder $list.RootFolder $folderUrl | Out-Null
    }
    #$fullFileUrl = Combine-Url $folderUrl $fileUrl
    $properties.Attributes.RemoveNamedItem("FileName") #FileName is added in in the build process and is not part of the sharepoint schema.
    $properties.Attributes.RemoveNamedItem("_VirusStatus")
    $fullFileUrl = Combine-Url $masterPageUrl $fileUrl
    if($csomVersion -eq "15")
    {
        $tempFileName = New-TempFile $file.FullName
        Convert-FileTo2013 $tempFileName
        UploadFile $context $web (get-item $tempFileName) $fullFileUrl $properties $versioningEnabled $publishingEnabled | out-null
        Remove-Item $tempFileName -Force
    }
    else
    {
        UploadFile $context $web $file $fullFileUrl $properties $versioningEnabled $publishingEnabled | out-null
    }
  }
}

Function Install-ClientApp($context, $web, $rootWeb, $location, $manifest, $csomVersion)
{
    $xmlFilePath = [System.IO.Path]::Combine($location, "manifest.xml")
    if((Test-Path $xmlFilePath) -eq $false)
    {
        Write-Host "No manifest.xml file found at the location $location"
        return
    }
    write-host "Deploying Client App - $($manifest.xml.ClientApp.Name)"
    Install-WebParts $context $rootWeb $location $csomVersion
    Install-StyleLibrary $context $rootWeb $location
    Install-Lists $context $web $location
    Install-SiteFields $context $rootWeb $location
    Install-ContentTypes $context $rootWeb $location
    Install-ConfigureLists $context $web $location
    Install-ListItems $context $web $location
    Install-DisplayTemplates $context $rootWeb $location
}
Function Install-ClientApps($context, $web, $location, $csomVersion)
{
	$path = [System.IO.Path]::Combine($location, "Client Apps")
    if((Test-Path $path) -eq $false)
    {
        Write-Host "No Client Apps"
        return
    }

    $webPartFolders = Get-ChildItem $path -Directory
    $rootWeb = $context.Site.RootWeb
    $context.Load($rootWeb)
    $context.ExecuteQuery()
    foreach($webPartPath in $webPartFolders)
    {
        $xmlFilePath = [System.IO.Path]::Combine($webPartPath.FullName, "manifest.xml")
        if((Test-Path $xmlFilePath) -eq $false)
        {
            Write-warning "No manifest.xml file for client app found at the location $xmlFilePath"
            continue
        }
        [xml]$manifest = get-content $xmlFilePath
        Install-ClientApp $context $web $rootWeb $webPartPath.FullName $manifest $csomVersion
    }
}
Function Activate-WebFeature($context, $web, [guid]$featureId, $name)
{
    #note: This may only work in SP Online.  To verify.
    $features = $web.Features
    $context.Load($features)
    $context.ExecuteQuery()
    $feature = $features | Where-Object { $_.DefinitionId -eq $featureId}
    if($feature -eq $null -or $feature.Length -eq 0)
    {
        Write-Host "Adding feature $name"
        $features.Add($featureId, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None)
        try {
            $context.ExecuteQuery()
        }
        catch
        {
            Write-Warning "The feature $name with id $featureId could not be activated.  This may be an issue with the CSOM Version (Client or Server). "
            Write-Error $_
        }
    }
    else {
        Write-Host "The feature $name is already activated"
    }
}
Function Activate-SiteFeature($context, [guid]$featureId, $name)
{
    #note: This may only work in SP Online.  To verify.
    $features = $context.Site.Features
    $context.Load($features)
    $context.ExecuteQuery()
    $feature = $features | Where-Object { $_.DefinitionId -eq $featureId}
    if($feature -eq $null -or $feature.Length -eq 0)
    {
        Write-Host "Adding feature $name"
        $features.Add($featureId, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None)
        try {
            $context.ExecuteQuery()
        }
        catch
        {
            Write-Warning "The feature $name with id $featureId could not be activated.  This may be an issue with the CSOM Version (Client or Server). "
            Write-Error $_
        }
    }
    else {
        Write-Host "The feature $name is already activated"
    }
}
Function Install-Webs ($context, $web, $location)
{
  $websPath = [IO.Path]::Combine($location, "Webs")
  if(Test-Path $websPath)
  {
      #$rootWebPath = [IO.Path]::Combine($websPath, "Root")
      #Install-Web $context $web $rootWebPath
      $webPaths = Get-ChildItem $websPath  | Where-Object { $_.PSIsContainer -eq $true}
      foreach($webPath in $webPaths)
      {
         Install-Web $context $web $webPath.FullName
      }

  }
}

Function Install-Web ($context, $parentWeb, $location)
{
    $webManifestPath = [IO.Path]::Combine($location, "manifest.xml")
    [xml]$webManifest = Get-Content $webManifestPath
    #Build the structure of the web based on the manifest
    if($webManifest -eq $null)
    {
      write-host "No web manifest.  Skipping Web deploy"
      return
    }
    $web = $parentWeb
    $isRootWeb = $location.EndsWith("Root")
    if($isRootWeb -eq $false)
    {
        #Look to see if web exists
        $webs = $parentWeb.Webs
        $context.Load($webs)
        $context.ExecuteQuery()
        $existing = $webs | Where-Object {$_.Title -ieq $webManifest.xml.Web.Title}
        if($existing -ne $null -and $existing.Length -ge 1)
        {
            Write-Host "Web $($webManifest.xml.Web.Title) already exists"
            $web = $existing
        }
        else {
            $webProperties = $webManifest.xml.Web
            $title = $webProperties.Title
            $webUrl = $webProperties.ServerRelativeUrl.TrimStart("/")
            $template = $webProperties.WebTemplate
            $configuration = $webProperties.Configuration
            Write-Host "Creating Web $webUrl" #TODO
            $createWeb = New-Object Microsoft.SharePoint.Client.WebCreationInformation
            $createWeb.Url = $webUrl
            $createWeb.UseSamePermissionsAsParentSite = $true
            $createWeb.Title = $title
            $createWeb.WebTemplate = "$($template)#$($configuration)"
            $web = $parentWeb.Webs.Add($createWeb)
            $context.Load($web)
            Write-Host "Creating new web at $webUrl" -f Green -NoNewline
            $context.ExecuteQuery()
            Write-Host "...Created" -f Green
        }
    }
    Install-Lists $context $web $location
    Install-ListItems $context $web $location
}
Function Install-Masterpages($context, $web, $location)
{
	$path = [System.IO.Path]::Combine($location, "Masterpages")

    if((Test-Path $path) -eq $false)
    {
      write-host "No Master pages to deploy"
      return
    }

	$list = $context.Site.GetCatalog([Microsoft.SharePoint.Client.ListTemplateType]::MasterPageCatalog)
	$context.Load($list)
    $context.Load($list.RootFolder)

	$context.ExecuteQuery();
	$publishingEnabled = $list.EnableModeration
	$versioningEnabled = $list.EnableVersioning

	$files = Get-ChildItem $path -Recurse | Where-Object { $_.PSIsContainer -eq $false}
	foreach($file in $files)
	{
		Write-Host "Uploading Master page $($file.Name)"
		$folderUrl = ($file.FullName -ireplace [regex]::escape($path),"") -ireplace "\\","/" -ireplace ("/" + [regex]::escape($file.Name)), ""
        $fileUrl = ($folderUrl + "/" + $file.Name)
        if([string]::IsNullOrEmpty($folderUrl) -eq $false)
        {
		    Ensure-Folder -Web $web -ParentFolder $list.RootFolder -FolderUrl $folderUrl | out-null
        }
        $fullFileUrl = Combine-Url $list.RootFolder.ServerRelativeUrl $fileUrl
        UploadFile $context $web $file $fullFileUrl $null $versioningEnabled $publishingEnabled | out-null
        PublishFile $context $web $fullFileUrl $versioningEnabled $publishingEnabled
	}
}
function ApplyMetadataToListItem([Microsoft.SharePoint.Client.ClientContext]$context,[Microsoft.SharePoint.Client.List]$list, [Microsoft.SharePoint.Client.ListItem] $listItem, $properties)
{
    foreach($fieldValue in $properties)
        {
            $name = $fieldValue.name
            if($name -eq "Attachments" )
            {
                continue
            }
            [Array]$field = $list.Fields | Where-Object { $_.InternalName -eq $name }
            if($field.Length -eq 0)
            {
                Write-Warning "Field does not exist for : $($list.Name) - $name"
                continue
            }
            if($field.IsReadOnly) {
                Write-Warning "Skipping readonly field"
                continue
            }
            $value = $fieldValue.'#cdata-section' | ConvertFrom-Json
            if([string]::IsNullOrEmpty($value))
            {
                continue
            }
            switch ($field[0].TypeAsString)
            {
                "File" {}
                "DateTime" {
                    $value = Get-Date ($value.value) #.ToString()
                    $listItem[$name] = $value
                }
                "URL" {
                    $urlValue = New-Object Microsoft.SharePoint.Client.FieldUrlValue
                    $urlValue.Url = $value.Url
                    $urlValue.Description = $value.Description
                    $listItem[$name] =  [Microsoft.SharePoint.Client.FieldUrlValue]$urlValue
                }
                "Lookup" {
                    $lookupValue = New-Object Microsoft.SharePoint.Client.FieldLookupValue
                    $lookupValue = $value.Split(":")[0]
                    $listItem[$name] = $lookupValue
                }
                default {
                    $listItem[$name] = $value
                }
            }

        }
}
Function Install-ListItems($context, $web, $location)
{
    #Dev Notes: If the destination environment contains required fields like Title, and we aren't exporting that field value
    #then this will error.  Attempted to find required fields and set a default value, but for some reason
    #the fields from the list did not show as required even though it did in SP.

  $path = [System.IO.Path]::Combine($location, "Lists")
  $xmlFilePath = [System.IO.Path]::Combine($path, "ListItems.xml")
  if((Test-Path $path) -eq $false -or (Test-Path $xmlFilePath) -eq $false)
  {
    Write-Host "No list items to import"
    return
  }

  [xml]$manifest = Get-Content $xmlFilePath

  foreach($listDef in $manifest.xml.Lists.List)
  {
    $listName = $listDef.name
    $totalItems = $listDef.ListItem.Length
    Write-Host "Importing $totalItems list items to $listName"
    $targetWeb = $web
    if(Is-True $listDef.rootWeb)
    {
        $targetWeb = $rootWeb
    }

    $list = $targetWeb.Lists.GetByTitle($listName)
    #get the first item.  If there is data in the list we won't import.
    $query = New-Object Microsoft.SharePoint.Client.CamlQuery
    $query.ViewXml = "<View><Query></Query><RowLimit>1</RowLimit></View>"
    $listItems = $list.GetItems($query)
    $fields = $list.Fields
    $context.Load($list)
    $context.Load($list.RootFolder)
    $context.Load($listItems)
    $context.Load($fields)
    $context.ExecuteQuery()
    $isLibrary = $list.BaseType -eq "1"
    $publishingEnabled = $list.EnableModeration
	$versioningEnabled = $list.EnableVersioning
    $filePath = [System.IO.Path]::Combine($path, "Files\$listName")
    if($listItems.Count -ge 1)
    {
        Write-Warning "The list $listName already has content, items will not be imported"
        continue
    }
    foreach($listItemDef in $listDef.ListItem)
    {
        if($isLibrary)
        {
            $fileRef = ($listItemDef.FieldValue | Where-Object { $_.name -eq "FileLeafRef" }).'#cdata-section'
			$fileRef = $fileRef.Replace("`"","") #CData sections contain literal quotes if its a string value.
            $filename = [IO.Path]::Combine($filePath, $fileRef)
            $file = Get-ChildItem $filename
            if($file -eq $null -or $file.Exists -eq $false)
            {
                throw "Could not locate file for library at $filename"
            }

            $fullFileUrl = Combine-Url $list.RootFolder.ServerRelativeUrl $fileRef
            if($versioningEnabled -and (FileExists $context $web $fullFileUrl))
            {
                CheckOutFile $context $web $fullFileUrl
            }
            [Microsoft.SharePoint.Client.FileCreationInformation]$fileInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
            $fileInfo.Content = [IO.File]::ReadAllBytes($filename)
            $fileInfo.Overwrite = $true
            $fileInfo.Url = $fullFileUrl
            $uploadedFile = $list.RootFolder.Files.Add($fileInfo)
            $listItem = $uploadedFile.ListItemAllFields

            ApplyMetadataToListItem $context $list $listItem $listItemDef.FieldValue

            $listItem.Update()
            $context.ExecuteQuery()
            PublishFile $context $web $fullFileUrl $versioningEnabled $publishingEnabled
        }
        else {
            $itemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
            $listItem = $list.AddItem($itemInfo)
            ApplyMetadataToListItem $context $list $listItem $listItemDef.FieldValue
            $listItem.Update()
            $context.ExecuteQuery()
        }
    }
    $Context.ExecuteQuery()
  }
}
Export-ModuleMember -Function 'Install-*'
Export-ModuleMember -Function 'Activate-*'


text:
module.exports = function(grunt) {
  grunt.initConfig({
    browserify: {
      qs: {
        src: 'lib/qs.js',
        dest: 'vendor/qs.js'
      }
    },

    concat: {
      build: {
        src: [
          'vendor/qs.js',
          'bower_components/FakeXMLHttpRequest/fake_xml_http_request.js',
          'bower_components/route-recognizer/dist/route-recognizer.js',
          'bower_components/pretender/pretender.js',
          'lib/agent.js'
        ],
        dest: 'dist/agent.js'
      }
    },

    connect: {
      server: {
        options: {
          port: 3000
        }
      }
    },

    jshint: {
      options: {},
      all: ['lib/agent.js']
    },

    qunit: {
      all: {
        options: {
          urls: ['http://localhost:3000/test/index.html']
        }
      }
    },

    watch: {
      test: {
        files: ['test/**/*.js', 'lib/**/*.js'],
        tasks: ['build', 'jshint:all', 'qunit:all']
      },
      lint: {
        files: ['test/**/*.js', 'lib/**/*.js'],
        tasks: ['build', 'jshint:all']
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-browserify');

  grunt.registerTask('build', ['browserify:qs', 'concat:build']);
  grunt.registerTask('test', ['build', 'connect:server', 'jshint:all', 'qunit:all']);
  grunt.registerTask('autotest', ['build', 'connect:server', 'jshint:all', 'qunit:all', 'watch:test']);
  grunt.registerTask('server', ['build', 'connect:server', 'watch:lint']);
  grunt.registerTask('default', ['test']);
};


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

public final class GrapeConstants {

    public static final String GRAPE_COMMAND = "CamelGrapeCommand";

    private GrapeConstants() {
    }

}


text:
package com.microsoft.sqlserver.jdbc;

public interface SQLServerKeyVaultAuthenticationCallback {

    /**
     * The authentication callback delegate which is to be implemented by the client code
     *
     * @param authority
     *            - Identifier of the authority, a URL.
     * @param resource
     *            - Identifier of the target resource that is the recipient of the requested token, a URL.
     * @param scope
     *            - The scope of the authentication request.
     * @return access token
     */
    public String getAccessToken(String authority,
            String resource,
            String scope);
}


text:
Aquarium controller for raspberry pi and PCA9685
Developing on pi 3B

Written in python with a javascript frontend. Some templating done in handlebars and some quick UI prototyping using https://github.com/jdorn/json-editor
Using sockjs, tornado, websockets.

Features:
* Dimming - constant current led drivers that are dimmable via pwm signal. Originally developing using cheap chinese but switched to meanwell ldds and they are worth it.
* Relays or smart outlets with alexa/google home for pumps/powerheads co2 and heating.
* Support sounds for thunderstorms and other yet to be determined weather patterns.

![Hardware Prototype](whet-hardware-proto-1.jpg?raw=true "Hardware Prototype")

Acknowlegements:
* Adafruit - PCA9685 library
* Clach04 - python-tuya
* Jdorn - json-editor

My Nginx config for reverse proxy and https if you're into that sort of thing:

        location ^~ /web {
               auth_basic "Restricted";
               auth_basic_user_file /config/nginx/.htpasswd;
               include /config/nginx/proxy.conf;
               proxy_pass http://pi:7999;
       }
        location ^~ /chat {
               auth_basic "Restricted";
               auth_basic_user_file /config/nginx/.htpasswd;
               include /config/nginx/proxy.conf;
               proxy_pass http://pi:7999;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header Host $host;
       }

        #proxy.conf
        client_max_body_size 10m;
        client_body_buffer_size 128k;

        #Timeout if the real server is dead
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;

        # Advanced Proxy Config
        send_timeout 5m;
        proxy_read_timeout 240;
        proxy_send_timeout 240;
        proxy_connect_timeout 240;

        # Basic Proxy Config
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_redirect  http://  $scheme://;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_cache_bypass $cookie_session;
        proxy_no_cache $cookie_session;
        proxy_buffers 32 4k;


text:
<?php

namespace Google\Service\Contentwarehouse;

class AssistantApiAccessControlOutput extends \Google\Model
{
  /**
   * @var bool
   */
  public $allowNonUnicornUserAccessYoutubeKids;
  /**
   * @var string
   */
  public $guestAccessOnYoutube;

  /**
   * @param bool
   */
  public function setAllowNonUnicornUserAccessYoutubeKids($allowNonUnicornUserAccessYoutubeKids)
  {
    $this->allowNonUnicornUserAccessYoutubeKids = $allowNonUnicornUserAccessYoutubeKids;
  }
  /**
   * @return bool
   */
  public function getAllowNonUnicornUserAccessYoutubeKids()
  {
    return $this->allowNonUnicornUserAccessYoutubeKids;
  }
  /**
   * @param string
   */
  public function setGuestAccessOnYoutube($guestAccessOnYoutube)
  {
    $this->guestAccessOnYoutube = $guestAccessOnYoutube;
  }
  /**
   * @return string
   */
  public function getGuestAccessOnYoutube()
  {
    return $this->guestAccessOnYoutube;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AssistantApiAccessControlOutput::class, 'Google_Service_Contentwarehouse_AssistantApiAccessControlOutput');


text:
<?php

namespace App\Http\Requests\API;

class SyncRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     * Currently, only user with admin rights are allowed to do this.
     * When per-user media library will be available, this restriction will be removed.
     *
     * @return bool
     */
    public function authorize()
    {
        return auth()->user()->is_admin;
    }

    /**
     * Get the validation rules that apply to the request (currently none).
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}


text:
// -*- C++ -*-
//----------------------------------------------------------------------
//
//                   William S. Klug, Luigi Perotti
//                University of California Los Angeles
//                 (C) 2004-2007 All Rights Reserved
//
//----------------------------------------------------------------------
//
/*!
  \file SpringPotentialSQ.h
  \brief Interface for spring potential in 3D cartesian space
*/

#ifndef _SPRINGPOTENTIALSQ_H_
#define _SPRINGPOTENTIALSQ_H_

#include "Potential.h"
#include "VoomMath.h"
#include "Node.h"

#include<set>

using namespace std;

namespace voom {

  class SpringPotentialSQ : public Potential
  {

  public:

    // Constructors/destructors:
    //! Default constructor
    SpringPotentialSQ(): _springK(0.0), _restL(0.0) {};
    //! Construct potential from necessary constants
    SpringPotentialSQ(double springK, double restL): _springK(springK), _restL(restL) {};

    //! Destructor
    virtual ~SpringPotentialSQ() {}

    // Operators
    // General methods:
    //! Based on nodal postitions, calculates state of material (strain energy and nodal forces)
    void updateState(DeformationNode<3> *nodeA, DeformationNode<3> *nodeB, bool f0, bool f1, bool f2);

    double computeTension(DeformationNode<3> *nodeA, DeformationNode<3> *nodeB);

    void setScaling(double springK) { _springK = springK; };
    void setSpringK(double springK) { _springK = springK; };
    void setRestL(double restL) { _restL = restL; };
    double getSpringK() { return _springK; };
    double getRestL() { return _restL; };

  private:

    // Members:
    double _springK;
    double _restL;

  }; // SpringPotentialSQ class

}
#endif // _SPRINGPOTENTIALSQ_H_


text:
# UpdateGatherData Class

Parameters to change gather

## Inheritance Hierarchy
System.Object
  Bandwidth.Net.Api.UpdateGatherData

**Namespace:** Bandwidth.Net.Api
**Assembly:** Bandwidth.Net (in Bandwidth.Net.dll) Version: 3.0.3

## Syntax

**C#**

``` C#
public class UpdateGatherData
```

The UpdateGatherData type exposes the following members.

## Constructors

	Name	Description

![Public method](media/pubmethod.gif "Public method")	UpdateGatherData
Initializes a new instance of the UpdateGatherData class

Back to Top

## Properties

	Name	Description

![Public property](media/pubproperty.gif "Public property")	State
Gather state

Back to Top

## See Also

#### Reference
Bandwidth.Net.Api Namespace


text:
namespace subresource_filter {

// static
const char SubresourceFilterBrowserTest::kDocumentLoadActivationLevel[];
const char SubresourceFilterBrowserTest::kSubresourceLoadsTotalForPage[];
const char SubresourceFilterBrowserTest::kSubresourceLoadsEvaluatedForPage[];
const char SubresourceFilterBrowserTest::kSubresourceLoadsMatchedRulesForPage[];
const char SubresourceFilterBrowserTest::kSubresourceLoadsDisallowedForPage[];
const char SubresourceFilterBrowserTest::kEvaluationTotalWallDurationForPage[];
const char SubresourceFilterBrowserTest::kEvaluationTotalCPUDurationForPage[];
const char SubresourceFilterBrowserTest::kEvaluationWallDuration[];
const char SubresourceFilterBrowserTest::kEvaluationCPUDuration[];
const char SubresourceFilterBrowserTest::kActivationDecision[];
const char SubresourceFilterBrowserTest::kActivationListHistogram[];
const char SubresourceFilterBrowserTest::kPageLoadActivationStateHistogram[];
const char
    SubresourceFilterBrowserTest::kPageLoadActivationStateDidInheritHistogram[];
const char SubresourceFilterBrowserTest::kSubresourceFilterActionsHistogram[];

MockSubresourceFilterObserver::MockSubresourceFilterObserver(
    content::WebContents* web_contents) {
  scoped_observation_.Observe(
      SubresourceFilterObserverManager::FromWebContents(web_contents));
}

MockSubresourceFilterObserver::~MockSubresourceFilterObserver() = default;

SubresourceFilterBrowserTest::SubresourceFilterBrowserTest() {
  scoped_feature_list_.InitAndEnableFeature(kAdTagging);
}

SubresourceFilterBrowserTest::~SubresourceFilterBrowserTest() = default;

bool SubresourceFilterBrowserTest::AdsBlockedInContentSettings(
    content::RenderFrameHost* frame_host) {
  auto* content_settings =
      content_settings::PageSpecificContentSettings::GetForFrame(frame_host);

  return content_settings->IsContentBlocked(ContentSettingsType::ADS);
}

#if defined(OS_ANDROID)
bool SubresourceFilterBrowserTest::PresentingAdsBlockedInfobar(
    content::WebContents* web_contents) {
  auto* infobar_manager =
      infobars::ContentInfoBarManager::FromWebContents(web_contents);
  if (infobar_manager->infobar_count() == 0)
    return false;

  // No infobars other than the ads blocked infobar should be displayed in the
  // context of these tests.
  EXPECT_EQ(infobar_manager->infobar_count(), 1u);
  auto* infobar = infobar_manager->infobar_at(0);
  EXPECT_EQ(infobar->delegate()->GetIdentifier(),
            infobars::InfoBarDelegate::ADS_BLOCKED_INFOBAR_DELEGATE_ANDROID);

  return true;
}
#endif

void SubresourceFilterBrowserTest::SetUp() {
  database_helper_ = CreateTestDatabase();
  PlatformBrowserTest::SetUp();
}

void SubresourceFilterBrowserTest::TearDown() {
  PlatformBrowserTest::TearDown();
  // Unregister test factories after PlatformBrowserTest::TearDown
  // (which destructs SafeBrowsingService).
  database_helper_.reset();
}

void SubresourceFilterBrowserTest::SetUpOnMainThread() {
  embedded_test_server()->ServeFilesFromSourceDirectory("components/test/data");
  host_resolver()->AddSimulatedFailure("host-with-dns-lookup-failure");

  host_resolver()->AddRule("*", "127.0.0.1");
  content::SetupCrossSiteRedirector(embedded_test_server());

  // Add content/test/data for cross_site_iframe_factory.html
  base::FilePath test_data_dir;
  ASSERT_TRUE(base::PathService::Get(content::DIR_TEST_DATA, &test_data_dir));
  embedded_test_server()->ServeFilesFromDirectory(test_data_dir);

  ASSERT_TRUE(embedded_test_server()->Start());

  auto* web_contents = chrome_test_utils::GetActiveWebContents(this);
  profile_context_ = SubresourceFilterProfileContextFactory::GetForProfile(
      Profile::FromBrowserContext(web_contents->GetBrowserContext()));
}

std::unique_ptr<TestSafeBrowsingDatabaseHelper>
SubresourceFilterBrowserTest::CreateTestDatabase() {
  return std::make_unique<TestSafeBrowsingDatabaseHelper>();
}

GURL SubresourceFilterBrowserTest::GetTestUrl(
    const std::string& relative_url) const {
  return embedded_test_server()->base_url().Resolve(relative_url);
}

void SubresourceFilterBrowserTest::ConfigureAsPhishingURL(const GURL& url) {
  safe_browsing::ThreatMetadata metadata;
  database_helper_->AddFullHashToDbAndFullHashCache(
      url, safe_browsing::GetUrlSocEngId(), metadata);
}

void SubresourceFilterBrowserTest::ConfigureAsSubresourceFilterOnlyURL(
    const GURL& url) {
  safe_browsing::ThreatMetadata metadata;
  database_helper_->AddFullHashToDbAndFullHashCache(
      url, safe_browsing::GetUrlSubresourceFilterId(), metadata);
}

void SubresourceFilterBrowserTest::ConfigureURLWithWarning(
    const GURL& url,
    std::vector<safe_browsing::SubresourceFilterType> filter_types) {
  safe_browsing::ThreatMetadata metadata;

  for (auto type : filter_types) {
    metadata.subresource_filter_match[type] =
        safe_browsing::SubresourceFilterLevel::WARN;
  }
  database_helper_->AddFullHashToDbAndFullHashCache(
      url, safe_browsing::GetUrlSubresourceFilterId(), metadata);
}

content::WebContents* SubresourceFilterBrowserTest::web_contents() {
  return chrome_test_utils::GetActiveWebContents(this);
}

content::RenderFrameHost* SubresourceFilterBrowserTest::FindFrameByName(
    const std::string& name) {
  return content::FrameMatchingPredicate(
      web_contents()->GetPrimaryPage(),
      base::BindRepeating(&content::FrameMatchesName, name));
}

bool SubresourceFilterBrowserTest::WasParsedScriptElementLoaded(
    content::RenderFrameHost* rfh) {
  DCHECK(rfh);
  return content::EvalJs(rfh, "!!document.scriptExecuted").ExtractBool();
}

void SubresourceFilterBrowserTest::
    ExpectParsedScriptElementLoadedStatusInFrames(
        const std::vector<const char*>& frame_names,
        const std::vector<bool>& expect_loaded) {
  ASSERT_EQ(expect_loaded.size(), frame_names.size());
  for (size_t i = 0; i < frame_names.size(); ++i) {
    SCOPED_TRACE(frame_names[i]);
    content::RenderFrameHost* frame = FindFrameByName(frame_names[i]);
    ASSERT_TRUE(frame);
    ASSERT_EQ(expect_loaded[i], WasParsedScriptElementLoaded(frame));
  }
}

void SubresourceFilterBrowserTest::ExpectFramesIncludedInLayout(
    const std::vector<const char*>& frame_names,
    const std::vector<bool>& expect_displayed) {
  const char kScript[] = "document.getElementsByName(\"%s\")[0].clientWidth;";

  ASSERT_EQ(expect_displayed.size(), frame_names.size());
  for (size_t i = 0; i < frame_names.size(); ++i) {
    SCOPED_TRACE(frame_names[i]);
    int client_width =
        content::EvalJs(web_contents()->GetMainFrame(),
                        base::StringPrintf(kScript, frame_names[i]))
            .ExtractInt();
    EXPECT_EQ(expect_displayed[i], !!client_width) << client_width;
  }
}

bool SubresourceFilterBrowserTest::IsDynamicScriptElementLoaded(
    content::RenderFrameHost* rfh) {
  DCHECK(rfh);
  return content::EvalJs(rfh, "insertScriptElementAndReportSuccess()",
                         content::EXECUTE_SCRIPT_USE_MANUAL_REPLY)
      .ExtractBool();
}

void SubresourceFilterBrowserTest::InsertDynamicFrameWithScript() {
  EXPECT_EQ(true, content::EvalJs(web_contents()->GetMainFrame(),
                                  "insertFrameWithScriptAndNotify()",
                                  content::EXECUTE_SCRIPT_USE_MANUAL_REPLY));
}

void SubresourceFilterBrowserTest::NavigateFromRendererSide(const GURL& url) {
  content::TestNavigationObserver navigation_observer(web_contents(), 1);
  ASSERT_TRUE(content::ExecJs(
      web_contents()->GetMainFrame(),
      base::StringPrintf("window.location = \"%s\";", url.spec().c_str())));
  navigation_observer.Wait();
}

void SubresourceFilterBrowserTest::NavigateFrame(const char* frame_name,
                                                 const GURL& url) {
  content::TestNavigationObserver navigation_observer(web_contents(), 1);
  ASSERT_TRUE(content::ExecJs(
      web_contents()->GetMainFrame(),
      base::StringPrintf("document.getElementsByName(\"%s\")[0].src = \"%s\";",
                         frame_name, url.spec().c_str())));
  navigation_observer.Wait();
}

void SubresourceFilterBrowserTest::SetRulesetToDisallowURLsWithPathSuffix(
    const std::string& suffix) {
  TestRulesetPair test_ruleset_pair;
  ruleset_creator_.CreateRulesetToDisallowURLsWithPathSuffix(
      suffix, &test_ruleset_pair);

  TestRulesetPublisher test_ruleset_publisher(
      g_browser_process->subresource_filter_ruleset_service());
  ASSERT_NO_FATAL_FAILURE(
      test_ruleset_publisher.SetRuleset(test_ruleset_pair.unindexed));
}

void SubresourceFilterBrowserTest::SetRulesetToDisallowURLsWithSubstrings(
    std::vector<base::StringPiece> substrings) {
  TestRulesetPair test_ruleset_pair;
  ruleset_creator_.CreateRulesetToDisallowURLWithSubstrings(
      std::move(substrings), &test_ruleset_pair);

  TestRulesetPublisher test_ruleset_publisher(
      g_browser_process->subresource_filter_ruleset_service());
  ASSERT_NO_FATAL_FAILURE(
      test_ruleset_publisher.SetRuleset(test_ruleset_pair.unindexed));
}

void SubresourceFilterBrowserTest::SetRulesetWithRules(
    const std::vector<proto::UrlRule>& rules) {
  TestRulesetPair test_ruleset_pair;
  ruleset_creator_.CreateRulesetWithRules(rules, &test_ruleset_pair);

  TestRulesetPublisher test_ruleset_publisher(
      g_browser_process->subresource_filter_ruleset_service());
  ASSERT_NO_FATAL_FAILURE(
      test_ruleset_publisher.SetRuleset(test_ruleset_pair.unindexed));
}

void SubresourceFilterBrowserTest::OpenAndPublishRuleset(
    RulesetService* ruleset_service,
    const base::FilePath& indexed_ruleset_path) {
  RulesetFilePtr index_file(nullptr, base::OnTaskRunnerDeleter(nullptr));
  base::RunLoop open_loop;
  auto open_callback = base::BindLambdaForTesting(
      [&index_file, &open_loop](RulesetFilePtr result) {
        index_file = std::move(result);
        open_loop.Quit();
      });
  IndexedRulesetVersion version =
      ruleset_service->GetMostRecentlyIndexedVersion();
  ruleset_service->GetRulesetDealer()->TryOpenAndSetRulesetFile(
      indexed_ruleset_path, version.checksum, std::move(open_callback));
  open_loop.Run();
  ASSERT_TRUE(index_file->IsValid());
  ruleset_service->OnRulesetSet(std::move(index_file));
}

void SubresourceFilterBrowserTest::ResetConfiguration(Configuration config) {
  scoped_configuration_.ResetConfiguration(std::move(config));
}

void SubresourceFilterBrowserTest::ResetConfigurationToEnableOnPhishingSites(
    bool measure_performance) {
  Configuration config = Configuration::MakePresetForLiveRunOnPhishingSites();
  config.activation_options.performance_measurement_rate =
      measure_performance ? 1.0 : 0.0;
  ResetConfiguration(std::move(config));
}

std::unique_ptr<TestSafeBrowsingDatabaseHelper>
SubresourceFilterListInsertingBrowserTest::CreateTestDatabase() {
  std::vector<safe_browsing::ListIdentifier> list_ids = {
      safe_browsing::GetUrlSubresourceFilterId()};
  return std::make_unique<TestSafeBrowsingDatabaseHelper>(
      std::make_unique<safe_browsing::TestV4GetHashProtocolManagerFactory>(),
      std::move(list_ids));
}

SubresourceFilterPrerenderingBrowserTest::
    SubresourceFilterPrerenderingBrowserTest()
    : prerender_helper_(base::BindRepeating(
          &SubresourceFilterPrerenderingBrowserTest::web_contents,
          base::Unretained(this))) {}

SubresourceFilterPrerenderingBrowserTest::
    ~SubresourceFilterPrerenderingBrowserTest() = default;

void SubresourceFilterPrerenderingBrowserTest::SetUp() {
  prerender_helper_.SetUp(embedded_test_server());
  SubresourceFilterListInsertingBrowserTest::SetUp();
}

}  // namespace subresource_filter


text:
'use strict';

var gulp = require('gulp');

var $ = require('gulp-load-plugins')();
var saveLicense = require('uglify-save-license');

gulp.task('styles', function () {
  console.log('styles');
  return gulp.src('app/scss/main.scss')
    .pipe($.plumber())
    .pipe($.rubySass({style: 'expanded'})) // sourcemap: true, sourcemapPath: '../scss', not sure how this works
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('app/css'))
    .pipe($.size());
});

gulp.task('scripts', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.size());
});

gulp.task('partials', function () {
  return gulp.src('app/partials/**/*.html')
    .pipe($.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe($.ngHtml2js({
      moduleName: "seriesFinder",
      prefix: "partials/"
    }))
    .pipe(gulp.dest(".tmp/partials"))
    .pipe($.size());
});

gulp.task('html', ['styles', 'scripts', 'partials'], function () {
  var jsFilter = $.filter('app/**/*.js');
  var cssFilter = $.filter('app/**/*.css');

  return gulp.src('app/*.html')
    .pipe($.inject(gulp.src('.tmp/partials/**/*.js'), {
      read: false,
      starttag: '<!-- inject:partials -->',
      addRootSlash: false,
      addPrefix: '../'
    }))
    .pipe($.useref.assets())
    .pipe($.rev())
    .pipe(jsFilter)
    .pipe($.ngmin())
    .pipe($.uglify({preserveComments: saveLicense}))
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe($.replace('app/bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap','fonts'))
    .pipe($.csso())
    .pipe(cssFilter.restore())
    .pipe($.useref.restore())
    .pipe($.useref())
    .pipe($.revReplace())
    .pipe(gulp.dest('dist'))
    .pipe($.size());
});

gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size());
});

gulp.task('fonts', function () {
  return $.bowerFiles()
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size());
});

gulp.task('clean', function () {
  return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['html', 'partials', 'images', 'fonts']);


text:
package com.yelelen.sfish.helper;

import com.yelelen.sfish.parser.JsonParser;
import com.yelelen.sfish.contract.NetDataListener;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by yelelen on 17-9-15.
 */

public class ElasticHelper<T> implements Callback {

    private String mUrl;
    private static OkHttpClient mClient;
    private JsonParser<T> mParser;
    private NetDataListener<T> mDataListener;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public ElasticHelper(String url, NetDataListener<T> listener) {
        mDataListener = listener;
        mClient = new OkHttpClient();
        mUrl = url;
    }

    public void setParser(JsonParser<T> parser) {
        mParser = parser;
    }

    public void fetchByGet() {
        Request request = new Request.Builder().url(mUrl).build();
        mClient.newCall(request).enqueue(this);
    }

    public void fetchByPost(String json) {
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(mUrl).post(requestBody).build();
        mClient.newCall(request).enqueue(this);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        mDataListener.onNetFailed("网络异常");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.code() == 200) {
            String body = response.body().string();
            if (mParser != null) {
                List<T> ts = mParser.parse(body);
                mDataListener.onNetDone(ts);
            } else
                mDataListener.onNetDone(null);
        } else {
            mDataListener.onNetFailed("服务器内部异常");
        }
    }
}


text:
/**
 * Created by JetBrains RubyMine.
 * User: dougt
 * Date: 2/15/12
 * Time: 2:49 PM
 * To change this template use File | Settings | File Templates.
 */
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}

jQuery.fn.nextSlide = function (nextPrev) {
    var slide_number = Number($('.slideshow-foreground').data("slide_number"))
    var slideToShow = [];

    var slideAdd = 1;
    if (nextPrev == 'prev')
    {
        slideAdd = -1;
    }

    var next_slide = slide_number + slideAdd;

    var slide_id = 'slide' + next_slide;
    slideToShow = $('#' + slide_id)

    if (slideToShow.length > 0)
    {
        $('.slideshow-foreground').html('')
        $('.slideshow-foreground').append(slideToShow.clone())
        $('.slideshow-foreground').data("slide_number",next_slide)
        window.location.hash = '#'  + slide_id
//slideToShow.show();
    }
    else
    {
        $('.slideshow').hide();
        window.location.hash = ''
    }

}


text:
package com.shitao.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropsUtil {

	private PropsUtil() {

	}

	public static String getProperty(String propertyName) {
		Properties prop = new Properties();// 属性集合对象
		InputStream fis = null;
		try {
			fis = PropsUtil.class.getResourceAsStream("/shitao.properties");
			prop.load(fis);// 将属性文件流装载到Properties对象中
		} catch (Exception e) {
			e.printStackTrace();
		}finally
		{
			if(fis!=null)
			{
				try
				{
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		String result = prop.getProperty(propertyName);
		return ("".equals(result) || result == null) ? "" : result;
	}

}


text:
if [[ $1 == "-h" || $1 == "--help" ]] ; then
	echo "Usage:  ./makepot.sh"
	echo ""
	echo "Scans your plugin for strings that need translating and puts"
	echo "those strings in the .pot file.  Creates the .pot file if doesn't"
	echo "exist; updates the .pot file if it does."
	echo ""
	echo "THIS IS STEP 1:  This is the first step in translating a plugin."
	echo "The next step is './updatepos.sh.'"
	echo ""
	echo "Obtains the WordPress i18n / makepot package if needed."
	echo ""
	echo "For more information on translating yourplugin, see"
	echo "http://codex.wordpress.org/I18n_for_WordPress_Developers"
	echo ""
	echo "Author: Daniel Convissor <danielc@analysisandsolutions.com>"
	echo "License: http://www.gnu.org/licenses/gpl-2.0.html"
	echo "http://wordpress.org/extend/plugins/oop-plugin-template-solution/"
	exit 1
fi

cd "`dirname "$0"`/../.."

if [ ! -d makepot ] ; then
	svn checkout http://i18n.svn.wordpress.org/tools/trunk makepot
fi

cd makepot
svn up

php -d 'error_reporting=E_ALL^E_STRICT' \
	makepot.php wp-plugin \
	../typofr/trunk \
	../typofr/trunk/languages/typofr.pot


text:
package org.guvnor.ala.ui.client.provider.status;

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

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.guvnor.ala.ui.client.provider.status.runtime.RuntimePresenter;
import org.guvnor.ala.ui.model.PipelineExecutionTrace;
import org.guvnor.ala.ui.model.PipelineExecutionTraceKey;
import org.guvnor.ala.ui.model.Runtime;
import org.guvnor.ala.ui.model.RuntimeKey;
import org.guvnor.ala.ui.model.RuntimeListItem;
import org.jboss.errai.ioc.client.api.ManagedInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyObject;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class ProviderStatusPresenterTest {

    private static int ITEMS_COUNT = 5;

    @Mock
    private ProviderStatusPresenter.View view;

    @Mock
    private ManagedInstance<RuntimePresenter> runtimePresenterInstance;

    private ProviderStatusPresenter presenter;

    private List<RuntimePresenter> runtimePresenters;

    @Before
    public void setUp() {
        runtimePresenters = new ArrayList<>();
        presenter = new ProviderStatusPresenter(view,
                                                runtimePresenterInstance) {
            @Override
            protected RuntimePresenter newRuntimePresenter() {
                RuntimePresenter runtimePresenter = mock(RuntimePresenter.class);
                RuntimePresenter.View view = mock(RuntimePresenter.View.class);
                when(runtimePresenter.getView()).thenReturn(view);
                runtimePresenters.add(runtimePresenter);
                when(runtimePresenterInstance.get()).thenReturn(runtimePresenter);
                return super.newRuntimePresenter();
            }
        };
        presenter.init();
        verify(view,
               times(1)).init(presenter);
    }

    @Test
    public void testSetupItems() {
        List<RuntimeListItem> items = mockItems(ITEMS_COUNT);
        presenter.setupItems(items);

        verify(runtimePresenterInstance,
               times(ITEMS_COUNT)).get();
        verify(view,
               times(ITEMS_COUNT)).addListItem(any());

        for (int i = 0; i < ITEMS_COUNT; i++) {
            verify(runtimePresenters.get(i),
                   times(1)).setup(items.get(i));
            verify(view,
                   times(1)).addListItem(runtimePresenters.get(i).getView());
        }
    }

    @Test
    public void testRemoveExistingRuntime() {
        RuntimeKey keyToRemove = mock(RuntimeKey.class);
        List<RuntimeListItem> items = mockItems(ITEMS_COUNT);
        //pick an arbitrary element as the existing runtime.
        int index = 1;
        RuntimeListItem item = items.get(index);
        Runtime runtime = mock(Runtime.class);
        when(runtime.getKey()).thenReturn(keyToRemove);
        when(item.isRuntime()).thenReturn(true);
        when(item.getRuntime()).thenReturn(runtime);

        presenter.setupItems(items);
        for (int i = 0; i < ITEMS_COUNT; i++) {
            when(runtimePresenters.get(i).getItem()).thenReturn(items.get(i));
        }
        assertTrue(presenter.removeItem(keyToRemove));
        verify(runtimePresenterInstance,
               times(1)).destroy(runtimePresenters.get(index));
        verify(view,
               times(1)).removeListItem(runtimePresenters.get(index).getView());
    }

    @Test
    public void testRemoveNonExistingRuntime() {
        RuntimeKey keyToRemove = mock(RuntimeKey.class);
        List<RuntimeListItem> items = mockItems(ITEMS_COUNT);

        presenter.setupItems(items);
        for (int i = 0; i < ITEMS_COUNT; i++) {
            when(runtimePresenters.get(i).getItem()).thenReturn(items.get(i));
        }
        assertFalse(presenter.removeItem(keyToRemove));
        verify(runtimePresenterInstance,
               never()).destroy(anyObject());
        verify(view,
               never()).removeListItem(anyObject());
    }

    @Test
    public void testRemoveExistingPipelineExecution() {
        PipelineExecutionTraceKey keyToRemove = mock(PipelineExecutionTraceKey.class);
        List<RuntimeListItem> items = mockItems(ITEMS_COUNT);
        //pick an arbitrary element as the existing pipeline execution.
        int index = 2;
        RuntimeListItem item = items.get(index);
        PipelineExecutionTrace pipelineExecutionTrace = mock(PipelineExecutionTrace.class);
        when(pipelineExecutionTrace.getKey()).thenReturn(keyToRemove);
        when(item.isRuntime()).thenReturn(false);
        when(item.getPipelineTrace()).thenReturn(pipelineExecutionTrace);

        presenter.setupItems(items);
        for (int i = 0; i < ITEMS_COUNT; i++) {
            when(runtimePresenters.get(i).getItem()).thenReturn(items.get(i));
        }
        assertTrue(presenter.removeItem(keyToRemove));
        verify(runtimePresenterInstance,
               times(1)).destroy(runtimePresenters.get(index));
        verify(view,
               times(1)).removeListItem(runtimePresenters.get(index).getView());
    }

    @Test
    public void testRemoveNonExistingPipelineExecution() {
        PipelineExecutionTraceKey keyToRemove = mock(PipelineExecutionTraceKey.class);
        List<RuntimeListItem> items = mockItems(ITEMS_COUNT);

        presenter.setupItems(items);
        for (int i = 0; i < ITEMS_COUNT; i++) {
            when(runtimePresenters.get(i).getItem()).thenReturn(items.get(i));
        }
        assertFalse(presenter.removeItem(keyToRemove));
        verify(runtimePresenterInstance,
               never()).destroy(anyObject());
        verify(view,
               never()).removeListItem(anyObject());
    }

    @Test
    public void testIsEmptyWhenNoItems() {
        presenter.setupItems(new ArrayList<>());
        assertTrue(presenter.isEmpty());
    }

    @Test
    public void testIsEmptyWhenItems() {
        presenter.setupItems(mockItems(ITEMS_COUNT));
        assertFalse(presenter.isEmpty());
    }

    @Test
    public void testClear() {
        List<RuntimeListItem> items = mockItems(ITEMS_COUNT);
        presenter.setupItems(items);

        presenter.clear();
        verify(view,
               times(2)).clear();
        runtimePresenters.forEach(runtimePresenter -> verify(runtimePresenterInstance,
                                                             times(1)).destroy(runtimePresenter));
        verify(runtimePresenterInstance,
               times(ITEMS_COUNT)).destroy(any());
    }

    private List<RuntimeListItem> mockItems(int count) {
        List<RuntimeListItem> items = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            items.add(mock(RuntimeListItem.class));
        }
        return items;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.nr.events;

import edu.nr.machines.DriveMachine;
import edu.nr.main.HardwareDefines;
import edu.nr.states.DriveState;
import edu.nr.subsystems.Drive;
import edu.wpi.first.wpilibj.DriverStation;
/**
 *
 * @author alexbrinister
 */
public class AutonEvent {
    DriveMachine machine;
    DriverStation m_ds;
    public AutonEvent(String distUnits) {
        machine = DriveMachine.getInstance();
        m_ds = DriverStation.getInstance();
        machine.init(HardwareDefines.DRIVE_DISTANCE_UNIT);
    }

    public void runCm(double speed, double distanceCm, double reference) {
        if(m_ds.isAutonomous()) {
            if(m_ds.isEnabled() && !Drive.getInstance().isDroveDistance()) {
                machine.distanceCm = distanceCm;
                machine.speed = speed;
                machine.reference = reference;
                machine.setState(DriveState.DRIVE_DISTANCE);
            }
            else {
                machine.setState(DriveState.DRIVE_IDLE);
            }
        }
        machine.updateStateMachine();
    }

    public void runFt(double speed, double distanceFt, double reference) {
        if(m_ds.isAutonomous()) {
            if(m_ds.isEnabled() && !Drive.getInstance().isDroveDistance()) {
                machine.distanceFt = distanceFt;
                machine.speed = speed;
                machine.reference = reference;
                machine.setState(DriveState.DRIVE_DISTANCE);
            }
            else {
              machine.setState(DriveState.DRIVE_IDLE);
            }
        }
        machine.updateStateMachine();
    }

    public void runTime(double speed, double time, double reference) {
        if(m_ds.isAutonomous()) {
            if(m_ds.isEnabled()) {
                machine.speed = speed;
                machine.time = time;
                machine.reference = reference;
                machine.setState(DriveState.DRIVE_STRAIGHT_LINE);
            }
            else {
                machine.setState(DriveState.DRIVE_IDLE);
            }
        }
            machine.updateStateMachine();
    }

    public void runPIDFt(double speed, double distFt, double reference,
                                                            double i) {
        if(m_ds.isAutonomous()) {
            if(m_ds.isEnabled()) {
                machine.speed = speed;
                machine.distanceFt = distFt;
                machine.reference = reference;
                machine.i = i;
                machine.setState(DriveState.DRIVE_DISTANCE_PID);
            }
            else {
                machine.setState(DriveState.DRIVE_IDLE);
            }
        }
            machine.updateStateMachine();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>

<plugin>

  <extension point="org.eclipse.emf.ecore.generated_package">
    <package
       uri = "http://reo.project.cwi.nl/reo/Treo"
       class = "nl.cwi.reo.treo.TreoPackage"
       genModel = "model/generated/Treo.genmodel" />

  </extension>

</plugin>


text:
TPER2GTFS
=========

tper open data and web service 2 gtfs converter


text:
module Fog
  module Compute
    class Cloudstack

      class Real
        # Create site to site vpn connection
        #
        # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/createVpnConnection.html]
        def create_vpn_connection(s2scustomergatewayid, s2svpngatewayid, options={})
          options.merge!(
            'command' => 'createVpnConnection',
            's2scustomergatewayid' => s2scustomergatewayid,
            's2svpngatewayid' => s2svpngatewayid
          )
          request(options)
        end
      end

    end
  end
end


text:
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/2b97fe8319344d699a4bbba48827637b)](https://www.codacy.com/app/NYCRecords/NYCOpenRecords?utm_source=github.com&utm_medium=referral&utm_content=CityOfNewYork/NYCOpenRecords&utm_campaign=Badge_Grade)

# NYC OpenRecords
NYC OpenRecords is an application that assists individuals in the process of submitting Freedom of Information Law (FOIL) requests to a NYC Agency. The web application also allows government employees to manage, respond to, and fulfill incoming requests.

## Getting Started

### Technical Requirements
OpenRecords is currently being developed on RedHat Enterprise Linux v6 / v7 (in testing).

It relies on the following technologies:
- Python v3.5
- PostgreSQL v9.5
- ElasticSearch v5.2
- Redis v3.2

Authentication
- OpenRecords currently implements LDAP and OAuth for authentication. For development, you can bypass authentication by setting both `'USE_OAUTH'` and `'USE_LDAP'` to `False`.

We have optional integrations with [Sentry](https://sentry.io) for error tracing and are working on an integration with the ELK stack for log aggregation and analytics.

### Pre-Requisites
- Vagrant (v2.1.4) - Newer version may work but have not been tested.
- Virtualbox (v5.1.32) - Newer versions may work but have not been tested.
- [Vagrant-VBGuest](https://github.com/dotless-de/vagrant-vbguest)
- Redhat Developer Account (https://developers.redhat.com)
- FakeSMTP (Optional, for testing email functionality)

### Setting Up Development Environment (WIP)

#### On Mac OS X:
1. Install Virtualbox and Vagrant.
2. Install vagrant-vbguest:
    ```bash
    vagrant plugin install vagrant-vbguest
    ```
3. Create your `.env` file:
    ```bash
    cp .env.example .env
    ```
4. Edit your `.env` file. Look at the comments in `.env.example` and `config.py` for examples of valid values.
5. Create your `Vagrantfile`
    ```bash
    cp Vagrantfile.example Vagrantfile
    ```
5. Startup your Vagrant machine
    ```bash
    RH_USER=<YOUR REDHAT DEVELOPER USERNAME> RH_PASS=<YOUR REDHAT DEVELOPER PASSWORD> vagrant up default

    ```
6. Once Vagrant has finished setting up the VM, ssh in to the system (`vagrant ssh`). You'll need to have 2 different SSH Sessions open.
    Terminal 1 - Celery
    ```bash
    sh /vagrant/.startup/celery_startup.sh
    ```
    Terminal 2 - Flask
    ```bash
    sh /vagrant/.startup/flask_startup.sh
    ```

#### On Windows:
**TBD** (If you would like to help us setup a development environment on Windows, please try it out and submit issues as they come up.)

## Questions?
Please open an issue in this repository if you have any questions or any difficulty setting up and using OpenRecords.


text:
<?php
namespace Hangman\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version20141014140419 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE game ADD characters_guessed LONGTEXT NOT NULL COMMENT \'(DC2Type:json_array)\'');
    }

    public function down(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE game DROP characters_guessed');
    }
}


text:
/*

  ## query

  ### Parameters
  * query ::  A string or an array of querys. String if multi is off, array if it is on
              This should be fixed, it should always be an array even if its only
              one element
*/
define([
  'angular',
  'app',
  'underscore',

  'css!./query.css'
], function (angular, app, _) {
  'use strict';

  var module = angular.module('kibana.panels.query', []);
  app.useModule(module);

  module.controller('query', function($scope, querySrv, $rootScope) {
    $scope.panelMeta = {
      status  : "Stable",
      description : "Manage all of the queries on the dashboard. You almost certainly need one of "+
        "these somewhere. This panel allows you to add, remove, label, pin and color queries"
    };

    // Set and populate defaults
    var _d = {
      query   : "*",
      pinned  : true,
      history : [],
      remember: 10 // max: 100, angular strap can't take a variable for items param
    };
    _.defaults($scope.panel,_d);

    $scope.querySrv = querySrv;

    $scope.init = function() {
    };

    $scope.refresh = function() {
      update_history(_.pluck($scope.querySrv.list,'query'));
      $rootScope.$broadcast('refresh');
    };

    $scope.render = function() {
      $rootScope.$broadcast('render');
    };

    $scope.toggle_pin = function(id) {
      querySrv.list[id].pin = querySrv.list[id].pin ? false : true;
    };

    var update_history = function(query) {
      if($scope.panel.remember > 0) {
        $scope.panel.history = _.union(query.reverse(),$scope.panel.history);
        var _length = $scope.panel.history.length;
        if(_length > $scope.panel.remember) {
          $scope.panel.history = $scope.panel.history.slice(0,$scope.panel.remember);
        }
      }
    };

    $scope.init();

  });
});


text:
use rustfft::num_complex::Complex;
use rustfft::Length;

use crate::common::dct_error_inplace;
use crate::RequiredScratch;
use crate::{twiddles, DctNum};
use crate::{Dct2, Dct3, Dst2, Dst3, TransformType2And3};

/// Naive O(n^2 ) DCT Type 2, DST Type 2, DCT Type 3, and DST Type 3 implementation
///
/// ~~~
/// // Computes a naive DCT2, DST2, DCT3, and DST3 of size 23
/// use rustdct::{Dct2, Dst2, Dct3, Dst3};
/// use rustdct::algorithm::Type2And3Naive;
///
/// let len = 23;
/// let naive = Type2And3Naive::new(len);
///
/// let mut dct2_buffer = vec![0f32; len];
/// naive.process_dct2(&mut dct2_buffer);
///
/// let mut dst2_buffer = vec![0f32; len];
/// naive.process_dst2(&mut dst2_buffer);
///
/// let mut dct3_buffer = vec![0f32; len];
/// naive.process_dct3(&mut dct3_buffer);
///
/// let mut dst3_buffer = vec![0f32; len];
/// naive.process_dst3(&mut dst3_buffer);
/// ~~~
pub struct Type2And3Naive<T> {
    twiddles: Box<[Complex<T>]>,
}

impl<T: DctNum> Type2And3Naive<T> {
    /// Creates a new DCT2, DCT3, DST2, and DST3 context that will process signals of length `len`
    pub fn new(len: usize) -> Self {
        let twiddles: Vec<Complex<T>> = (0..len * 4)
            .map(|i| twiddles::single_twiddle(i, len * 4))
            .collect();

        Self {
            twiddles: twiddles.into_boxed_slice(),
        }
    }
}

impl<T: DctNum> Dct2<T> for Type2And3Naive<T> {
    fn process_dct2_with_scratch(&self, buffer: &mut [T], scratch: &mut [T]) {
        let scratch = validate_buffers!(buffer, scratch, self.len(), self.get_scratch_len());
        scratch.copy_from_slice(buffer);

        for k in 0..buffer.len() {
            let output_cell = buffer.get_mut(k).unwrap();
            *output_cell = T::zero();

            let twiddle_stride = k * 2;
            let mut twiddle_index = k;

            for i in 0..scratch.len() {
                let twiddle = self.twiddles[twiddle_index];

                *output_cell = *output_cell + scratch[i] * twiddle.re;

                twiddle_index += twiddle_stride;
                if twiddle_index >= self.twiddles.len() {
                    twiddle_index -= self.twiddles.len();
                }
            }
        }
    }
}
impl<T: DctNum> Dst2<T> for Type2And3Naive<T> {
    fn process_dst2_with_scratch(&self, buffer: &mut [T], scratch: &mut [T]) {
        let scratch = validate_buffers!(buffer, scratch, self.len(), self.get_scratch_len());
        scratch.copy_from_slice(buffer);

        for k in 0..buffer.len() {
            let output_cell = buffer.get_mut(k).unwrap();
            *output_cell = T::zero();

            let twiddle_stride = (k + 1) * 2;
            let mut twiddle_index = k + 1;

            for i in 0..scratch.len() {
                let twiddle = self.twiddles[twiddle_index];

                *output_cell = *output_cell - scratch[i] * twiddle.im;

                twiddle_index += twiddle_stride;
                if twiddle_index >= self.twiddles.len() {
                    twiddle_index -= self.twiddles.len();
                }
            }
        }
    }
}
impl<T: DctNum> Dct3<T> for Type2And3Naive<T> {
    fn process_dct3_with_scratch(&self, buffer: &mut [T], scratch: &mut [T]) {
        let scratch = validate_buffers!(buffer, scratch, self.len(), self.get_scratch_len());
        scratch.copy_from_slice(buffer);

        let half_first = T::half() * scratch[0];

        for k in 0..buffer.len() {
            let output_cell = buffer.get_mut(k).unwrap();
            *output_cell = half_first;

            let twiddle_stride = k * 2 + 1;
            let mut twiddle_index = twiddle_stride;

            for i in 1..scratch.len() {
                let twiddle = self.twiddles[twiddle_index];

                *output_cell = *output_cell + scratch[i] * twiddle.re;

                twiddle_index += twiddle_stride;
                if twiddle_index >= self.twiddles.len() {
                    twiddle_index -= self.twiddles.len();
                }
            }
        }
    }
}
impl<T: DctNum> Dst3<T> for Type2And3Naive<T> {
    fn process_dst3_with_scratch(&self, buffer: &mut [T], scratch: &mut [T]) {
        let scratch = validate_buffers!(buffer, scratch, self.len(), self.get_scratch_len());
        scratch.copy_from_slice(buffer);

        // scale the last scratch value by half before going into the loop
        scratch[scratch.len() - 1] = scratch[scratch.len() - 1] * T::half();

        for k in 0..buffer.len() {
            let output_cell = buffer.get_mut(k).unwrap();
            *output_cell = T::zero();

            let twiddle_stride = k * 2 + 1;
            let mut twiddle_index = twiddle_stride;

            for i in 0..scratch.len() {
                let twiddle = self.twiddles[twiddle_index];

                *output_cell = *output_cell - scratch[i] * twiddle.im;

                twiddle_index += twiddle_stride;
                if twiddle_index >= self.twiddles.len() {
                    twiddle_index -= self.twiddles.len();
                }
            }
        }
    }
}
impl<T: DctNum> TransformType2And3<T> for Type2And3Naive<T> {}
impl<T> Length for Type2And3Naive<T> {
    fn len(&self) -> usize {
        self.twiddles.len() / 4
    }
}
impl<T> RequiredScratch for Type2And3Naive<T> {
    fn get_scratch_len(&self) -> usize {
        self.len()
    }
}