text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Contr. Univ. Mich. Herb. 5: 21 (1941)

#### Original name
Psathyra silvatica Peck

### Remarks
null


text:
namespace Todo.MainProject.Authorization.Accounts.Dto
{
    public class RegisterOutput
    {
        public bool CanLogin { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace WordPlate\Tests\Acf\Fields;

use PHPUnit\Framework\TestCase;
use WordPlate\Acf\Fields\Email;

class EmailTest extends TestCase
{
    public function testType()
    {
        $field = Email::make('Email Address')->toArray();
        $this->assertSame('email', $field['type']);
    }
}


text:
/**
 * Check given value is prime or not.
 * @param target check target value.
 * @return true when a given number is prime.
 *         false otherwise.
 */
def isPrime (target:Int): Boolean = {
  // If target value is prime, the remainder should not be 0 for all primes less than square root of target.
  2 :: (3 to scala.Math.sqrt(target).toInt by 2).toList forall { target % _ != 0 }
}

/**
 * Pick up primes from given list.
 * @param targetRange integer range
 * @return prime value list
 */
def listPrimesinRange (targetRange:Range): List[Int] = targetRange.toList.filter(isPrime(_))

/*
scala> listPrimesinRange(7 to 31)
res0: List[Int] = List(7, 11, 13, 17, 19, 23, 29, 31)
*/


text:
export function assign(...args) {
  Object.assign(...args);
}

export function hiddenValue(object, property, value, writable = true) {
  Object.defineProperty(object, property, {
    enumberable: false,
    configurable: true,
    writable,
    value
  });
  return value;
}

export function proxy(objectTo, objectFrom) {
  Object.keys(objectFrom)
    .forEach(field => {
      const descriptor = Object.getOwnPropertyDescriptor(objectFrom, field);
      Object.defineProperty(objectTo, field, {
        enumerable: descriptor.enumerable,
        configurable: true,
        get: function() {
          return objectFrom[field];
        },
        set: function(value) {
          objectFrom[field] = value;
        }
      });
    });
}


text:
using System;
using Android.Content;
using Notes.Droid.Effects;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using AView = Android.Widget.AdapterView;
using LView = Android.Widget.ListView;
using ADragFlags = Android.Views.DragFlags;

[assembly: ResolutionGroupName("Notes")]
[assembly: ExportEffect(typeof(ItemDragAndDropEffect), "ItemDragAndDropEffect")]
namespace Notes.Droid.Effects
{
    public class ItemDragAndDropEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            // configure the ListView
            (Control as LView).OnItemLongClickListener = new ItemLongClickListen(this);
            (Control as LView).LongClickable = true;
            //Control.SetBackgroundColor(Android.Graphics.Color.LightGreen); // HACK: show it's bound
        }

        protected override void OnDetached()
        {
            if (Control != null && Control.Handle != IntPtr.Zero)
                (Control as AView).OnItemLongClickListener = null;
        }

        public class ItemLongClickListen : Java.Lang.Object, AView.IOnItemLongClickListener
        {
            ItemDragAndDropEffect _dragAndDropEffect;

            public ItemLongClickListen(ItemDragAndDropEffect dragAndDropEffect)
            {
                _dragAndDropEffect = dragAndDropEffect;
            }

            public bool OnItemLongClick(AView parent, Android.Views.View v, int position, long id)
            {
                if (v.Handle == IntPtr.Zero)
                    return false;

                // get the Note
                var noteString = (parent as LView).GetItemAtPosition(position).ToString();
                // clipData is the text from the note
                var data = ClipData.NewPlainText(
                    new Java.Lang.String("Note"),
                    new Java.Lang.String(noteString));
                // create a visual drag representation from the view
                var dragShadowBuilder = new AView.DragShadowBuilder(v);
                // start dragging
                v.StartDragAndDrop(data, dragShadowBuilder, v, (int)ADragFlags.Global);
                return true;
            }
        }
    }
}


text:
import * as vscode from 'vscode';
import { extensionName } from './appGlobals';
import { JestExt } from './JestExt';

export enum StatusType {
  active,
  summary,
}

export type Status = 'running' | 'failed' | 'success' | 'stopped' | 'initial';
export type Mode = 'watch' | 'coverage';

interface StatusUpdateRequest {
  source: string;
  status: Status;
  details?: string;
  modes?: Mode[];
}

interface SpinnableStatusBarItem
  extends Pick<vscode.StatusBarItem, 'command' | 'text' | 'tooltip'> {
  readonly type: StatusType;
  show(): void;
  hide(): void;
}

const createStatusBarItem = (type: StatusType, priority: number): SpinnableStatusBarItem => {
  const item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, priority);
  return {
    type,
    show: () => item.show(),
    hide: () => item.hide(),

    get command() {
      return item.command;
    },
    get text() {
      return item.text;
    },
    get tooltip() {
      return item.tooltip;
    },

    set command(_command) {
      item.command = _command;
    },
    set text(_text: string) {
      item.text = _text;
    },
    set tooltip(_tooltip: string) {
      item.tooltip = _tooltip;
    },
  };
};

// The bottom status bar
export class StatusBar {
  private activeStatusItem = createStatusBarItem(StatusType.active, 2);
  private summaryStatusItem = createStatusBarItem(StatusType.summary, 1);

  private priorities: Status[] = ['running', 'failed', 'success', 'stopped', 'initial'];
  private requests = new Map<string, StatusUpdateRequest>();
  private _activeFolder?: string;
  private summaryOutput?: vscode.OutputChannel;

  constructor() {
    this.summaryStatusItem.tooltip = 'Jest status summary of the workspace';
    this.activeStatusItem.tooltip = 'Jest status of the active folder';
  }

  register(getExtension: (name: string) => JestExt | undefined) {
    const showSummaryOutput = `${extensionName}.show-summary-output`;
    const showActiveOutput = `${extensionName}.show-active-output`;
    this.summaryStatusItem.command = showSummaryOutput;
    this.activeStatusItem.command = showActiveOutput;

    return [
      vscode.commands.registerCommand(showSummaryOutput, () => {
        if (this.summaryOutput) {
          this.summaryOutput.show();
        }
      }),
      vscode.commands.registerCommand(showActiveOutput, () => {
        if (this.activeFolder) {
          const ext = getExtension(this.activeFolder);
          if (ext) {
            ext.channel.show();
          }
        }
      }),
    ];
  }
  bind(source: string) {
    return {
      update: (status: Status, details?: string, modes?: Mode[]) => {
        this.request(source, status, details, modes);
      },
    };
  }

  onDidChangeActiveTextEditor(editor: vscode.TextEditor) {
    if (editor && editor.document) {
      const folder = vscode.workspace.getWorkspaceFolder(editor.document.uri);
      if (folder && folder.name !== this._activeFolder) {
        this._activeFolder = folder.name;
        this.updateActiveStatus();
      }
    }
  }

  private request(source: string, status: Status, details?: string, modes?: Mode[]) {
    const request: StatusUpdateRequest = {
      source,
      status,
      details,
      modes,
    };
    this.requests.set(source, request);
    this.updateStatus(request);
  }
  private updateStatus(request: StatusUpdateRequest) {
    this.updateActiveStatus(request);
    this.updateSummaryStatus();
  }

  private get activeFolder() {
    if (!this._activeFolder) {
      if (vscode.workspace.workspaceFolders.length === 1) {
        // there's only one workspaceFolder, so let's take it
        this._activeFolder = vscode.workspace.workspaceFolders[0].name;
      } else if (vscode.window.activeTextEditor) {
        // otherwise select correct workspaceFolder based on the currently open textEditor
        const folder = vscode.workspace.getWorkspaceFolder(
          vscode.window.activeTextEditor.document.uri
        );
        if (folder) {
          this._activeFolder = folder.name;
        }
      }
    }
    return this._activeFolder;
  }

  private updateActiveStatus(request?: StatusUpdateRequest) {
    if (request && this.activeFolder) {
      if (request.source === this.activeFolder) {
        this.render(request, this.activeStatusItem);
      }
      return;
    }

    // find the active item from requests
    let _request = null;
    if (this.activeFolder) {
      _request = this.requests.get(this.activeFolder);
    }
    if (!_request && this.requests.size === 1) {
      _request = this.requests.values().next().value;
    }

    if (_request) {
      this.render(_request, this.activeStatusItem);
    } else {
      this.activeStatusItem.hide();
    }
  }

  private updateSummaryStatus() {
    if (this.needsSummaryStatus()) {
      this.updateSummaryOutput();

      let summaryStatus: StatusUpdateRequest | undefined;
      let prev = 99;
      for (const r of this.requests.values()) {
        const idx = this.priorities.indexOf(r.status);
        if (idx >= 0 && idx < prev) {
          summaryStatus = r;
          prev = idx;
        }
      }

      if (summaryStatus) {
        this.render(summaryStatus, this.summaryStatusItem);
        return;
      }
    }
    this.summaryStatusItem.hide();
  }

  private render(request: StatusUpdateRequest, statusBarItem: SpinnableStatusBarItem) {
    const message = this.getMessageByStatus(request.status);

    switch (statusBarItem.type) {
      case StatusType.active: {
        const modes = this.getModes(request.modes);
        const details = !this.needsSummaryStatus() && request.details ? request.details : '';
        const displayString = [message, details, modes].filter((s) => s && s.length > 0).join(' ');
        statusBarItem.text = `Jest: ${displayString}`;
        statusBarItem.tooltip = `Jest status of '${this.activeFolder}'`;
        break;
      }
      case StatusType.summary:
        statusBarItem.text = `Jest-WS: ${message}`;
        break;
      default:
        throw new Error(`unexpected statusType: ${statusBarItem.type}`);
    }
    statusBarItem.show();
  }

  private updateSummaryOutput() {
    if (!this.summaryOutput) {
      this.summaryOutput = vscode.window.createOutputChannel('Jest (Workspace)');
    }
    this.summaryOutput.clear();

    const messages = [];
    this.requests.forEach((item) => {
      const details = item.details ? `: ${item.details}` : '';
      messages.push(`${item.source}: ${item.status} ${details}`);
    });
    this.summaryOutput.append(messages.join('\n'));
  }

  private needsSummaryStatus() {
    return this.requests.size > 1;
  }

  private getMessageByStatus(status: Status) {
    switch (status) {
      case 'running':
        return '$(sync~spin)';
      case 'failed':
        return '$(alert)';
      case 'success':
        return '$(check)';
      case 'initial':
        return '...';
      default:
        return status;
    }
  }
  private getModes(modes?: Mode[]) {
    if (!modes) {
      return '';
    }
    const modesStrings = modes.map((m) => {
      switch (m) {
        case 'coverage':
          return '$(color-mode)';
        case 'watch':
          return '$(eye)';
        default:
          throw new Error(`unrecognized mode: ${m}`);
      }
    });
    return modesStrings.join(' ');
  }
}

export const statusBar = new StatusBar();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Online_Store_Tests.Commands.FeedbackCommands.EditCommentCommandTests
{
    class Execute_Should
    {
    }
}


text:
<?php

/**
 * TPriorityList class
 *
 * TPriorityList implements a priority ordered list collection class.  It allows you to specify
 * any numeric for priorities down to a specific precision.  The lower the numeric, the high the priority of the item in the
 * list.  Thus -10 has a higher priority than -5, 0, 10 (the default), 18, 10005, etc.  Per {@link round}, precision may be negative and
 * thus rounding can go by 10, 100, 1000, etc, instead of just .1, .01, .001, etc. The default precision allows for 8 decimal
 * places. There is also a default priority of 10, if no different default priority is specified or no item specific priority is indicated.
 * If you replace TList with this class it will  work exactly the same with items inserted set to the default priority, until you start
 * using different priorities than the default priority.
 *
 * As you access the PHP array features of this class, it flattens and caches the results.  If at all possible, this
 * will keep the cache fresh even when manipulated.  If this is not possible the cache is cleared.
 * When an array of items are needed and the cache is outdated, the cache is recreated from the items and their priorities
 *
 * You can access, append, insert, remove an item by using
 * {@link itemAt}, {@link add}, {@link insertAt}, and {@link remove}.
 * To get the number of the items in the list, use {@link getCount}.
 * TPriorityList can also be used like a regular array as follows,
 * <code>
 * $list[]=$item;  // append with the default priority.  It may not be the last item if other items in the list are prioritized after the default priority
 * $list[$index]=$item; // $index must be between 0 and $list->Count-1.  This sets the element regardless of priority.  Priority stays the same.
 * $list[$index]=$item; // $index is $list->Count.  This appends the item to the end of the list with the same priority as the last item in the list.
 * unset($list[$index]); // remove the item at $index
 * if(isset($list[$index])) // if the list has an item at $index
 * foreach($list as $index=>$item) // traverse each item in the list in proper priority order and add/insert order
 * $n=count($list); // returns the number of items in the list
 * </code>
 *
 * To extend TPriorityList for doing your own operations with each addition or removal,
 * override {@link insertAtIndexInPriority()} and {@link removeAtIndexInPriority()} and then call the parent.
 *
 * @author Brad Anderson <javalizard@gmail.com>
 * @version $Id: TPriorityList.php 2541 2008-10-21 15:05:13Z javalizard $
 * @package System.Collections
 * @since 3.2a
 */
class TPriorityList extends TList
{
	/**
	 * @var array internal data storage
	 */
	private $_d=array();
	/**
	 * @var boolean indicates if the _d is currently ordered.
	 */
	private $_o=false;
	/**
	 * @var array cached flattened internal data storage
	 */
	private $_fd=null;
	/**
	 * @var integer number of items contain within the list
	 */
	private $_c=0;
	/**
	 * @var numeric the default priority of items without specified priorities
	 */
	private $_dp=10;
	/**
	 * @var integer the precision of the numeric priorities within this priority list.
	 */
	private $_p=8;

	/**
	 * Constructor.
	 * Initializes the list with an array or an iterable object.
	 * @param array|Iterator the intial data. Default is null, meaning no initial data.
	 * @param boolean whether the list is read-only
	 * @param numeric the default priority of items without specified priorities.
	 * @param integer the precision of the numeric priorities
	 * @throws TInvalidDataTypeException If data is not null and is neither an array nor an iterator.
	 */
	public function __construct($data=null,$readOnly=false,$defaultPriority=10,$precision=8)
	{
		parent::__construct();
		if($data!==null)
			$this->copyFrom($data);
		$this->setReadOnly($readOnly);
		$this->setPrecision($precision);
		$this->setDefaultPriority($defaultPriority);
	}

	/**
	 * Returns the number of items in the list.
	 * This method is required by Countable interface.
	 * @return integer number of items in the list.
	 */
	public function count()
	{
		return $this->getCount();
	}

	/**
	 * Returns the total number of items in the list
	 * @return integer the number of items in the list
	 */
	public function getCount()
	{
		return $this->_c;
	}

	/**
	 * Gets the number of items at a priority within the list
	 * @param numeric optional priority at which to count items.  if no parameter, it will be set to the default {@link getDefaultPriority}
	 * @return integer the number of items in the list at the specified priority
	 */
	public function getPriorityCount($priority=null)
	{
		if($priority===null)
			$priority=$this->getDefaultPriority();
		$priority=(string)round(TPropertyValue::ensureFloat($priority),$this->_p);

		if(!isset($this->_d[$priority]) || !is_array($this->_d[$priority]))
			return false;
		return count($this->_d[$priority]);
	}

	/**
	 * @return numeric gets the default priority of inserted items without a specified priority
	 */
	public function getDefaultPriority()
	{
		return $this->_dp;
	}

	/**
	 * This must be called internally or when instantiated.
	 * @param numeric sets the default priority of inserted items without a specified priority
	 */
	protected function setDefaultPriority($value)
	{
		$this->_dp=(string)round(TPropertyValue::ensureFloat($value),$this->_p);
	}

	/**
	 * @return integer The precision of numeric priorities, defaults to 8
	 */
	public function getPrecision()
	{
		return $this->_p;
	}

	/**
	 * This must be called internally or when instantiated.
	 * @param integer The precision of numeric priorities.
	 */
	protected function setPrecision($value)
	{
		$this->_p=TPropertyValue::ensureInteger($value);
	}

	/**
	 * Returns an iterator for traversing the items in the list.
	 * This method is required by the interface IteratorAggregate.
	 * @return Iterator an iterator for traversing the items in the list.
	 */
	public function getIterator()
	{
		return new ArrayIterator($this->flattenPriorities());
	}

	/**
	 * This returns a list of the priorities within this list, ordered lowest to highest.
	 * @return array the array of priority numerics in decreasing priority order
	 */
	public function getPriorities()
	{
		$this->sortPriorities();
		return array_keys($this->_d);
	}

	/**
	 * This orders the priority list internally.
	 */
	protected function sortPriorities() {
		if(!$this->_o) {
			ksort($this->_d,SORT_NUMERIC);
			$this->_o=true;
		}
	}

	/**
	 * This flattens the priority list into a flat array [0,...,n-1]
	 * @return array array of items in the list in priority and index order
	 */
	protected function flattenPriorities() {
		if(is_array($this->_fd))
			return $this->_fd;

		$this->sortPriorities();
		$this->_fd=array();
		foreach($this->_d as $priority => $itemsatpriority)
			$this->_fd=array_merge($this->_fd,$itemsatpriority);
		return $this->_fd;
	}

	/**
	 * Returns the item at the index of a flattened priority list.
	 * {@link offsetGet} calls this method.
	 * @param integer the index of the item to get
	 * @return mixed the element at the offset
	 * @throws TInvalidDataValueException Issued when the index is invalid
	 */
	public function itemAt($index)
	{
		if($index>=0&&$index<$this->getCount()) {
			$arr=$this->flattenPriorities();
			return $arr[$index];
		} else
			throw new TInvalidDataValueException('list_index_invalid',$index);
	}

	/**
	 * Gets all the items at a specific priority.
	 * @param numeric priority of the items to get.  Defaults to null, filled in with the default priority, if left blank.
	 * @return array all items at priority in index order, null if there are no items at that priority
	 */
	public function itemsAtPriority($priority=null)
	{
		if($priority===null)
			$priority=$this->getDefaultPriority();
		$priority=(string)round(TPropertyValue::ensureFloat($priority),$this->_p);

		return isset($this->_d[$priority])?$this->_d[$priority]:null;
	}

	/**
	 * Returns the item at an index within a priority
	 * @param integer the index into the list of items at priority
	 * @param numeric the priority which to index.  no parameter or null will result in the default priority
	 * @return mixed the element at the offset, false if no element is found at the offset
	 */
	public function itemAtIndexInPriority($index,$priority=null)
	{
		if($priority===null)
			$priority=$this->getDefaultPriority();
		$priority=(string)round(TPropertyValue::ensureFloat($priority), $this->_p);

		return !isset($this->_d[$priority])?false:(
				isset($this->_d[$priority][$index])?$this->_d[$priority][$index]:false
			);
	}

	/**
	 * Appends an item into the list at the end of the specified priority.  The position of the added item may
	 * not be at the end of the list.
	 * @param mixed item to add into the list at priority
	 * @param numeric priority blank or null for the default priority
	 * @return int the index within the flattened array
	 * @throws TInvalidOperationException if the map is read-only
	 */
	public function add($item,$priority=null)
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		return $this->insertAtIndexInPriority($item,false,$priority,true);
	}

	/**
	 * Inserts an item at an index.  It reads the priority of the item at index within the flattened list
	 * and then inserts the item at that priority-index.
	 * @param integer the specified position in the flattened list.
	 * @param mixed new item to add
	 * @throws TInvalidDataValueException If the index specified exceeds the bound
	 * @throws TInvalidOperationException if the list is read-only
	 */
	public function insertAt($index,$item)
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		if(($priority=$this->priorityAt($index,true))!==false)
			$this->insertAtIndexInPriority($item,$priority[1],$priority[0]);
		else
			throw new TInvalidDataValueException('list_index_invalid',$index);
	}

	/**
	 * Inserts an item at the specified index within a priority.  Override and call this method to
	 * insert your own functionality.
	 * @param mixed item to add within the list.
	 * @param integer index within the priority to add the item, defaults to false which appends the item at the priority
	 * @param numeric priority priority of the item.  defaults to null, which sets it to the default priority
	 * @param boolean preserveCache specifies if this is a special quick function or not. This defaults to false.
	 * @throws TInvalidDataValueException If the index specified exceeds the bound
	 * @throws TInvalidOperationException if the list is read-only
	 */
	public function insertAtIndexInPriority($item,$index=false,$priority=null,$preserveCache=false)
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		if($priority===null)
			$priority=$this->getDefaultPriority();
		$priority=(string)round(TPropertyValue::ensureFloat($priority), $this->_p);

		if($preserveCache) {
			$this->sortPriorities();
			$cc=0;
			foreach($this->_d as $prioritykey=>$items)
				if($prioritykey>=$priority)
					break;
				else
					$cc+=count($items);

			if($index===false&&isset($this->_d[$priority])) {
				$c=count($this->_d[$priority]);
				$c+=$cc;
				$this->_d[$priority][]=$item;
			} else if(isset($this->_d[$priority])) {
				$c=$index+$cc;
				array_splice($this->_d[$priority],$index,0,array($item));
			} else {
				$c = $cc;
				$this->_o = false;
				$this->_d[$priority]=array($item);
			}

			if($this->_fd&&is_array($this->_fd)) // if there is a flattened array cache
				array_splice($this->_fd,$c,0,array($item));
		} else {
			$c=null;
			if($index===false&&isset($this->_d[$priority])) {
				$cc=count($this->_d[$priority]);
				$this->_d[$priority][]=$item;
			} else if(isset($this->_d[$priority])) {
				$cc=$index;
				array_splice($this->_d[$priority],$index,0,array($item));
			} else {
				$cc=0;
				$this->_o=false;
				$this->_d[$priority]=array($item);
			}
			if($this->_fd&&is_array($this->_fd)&&count($this->_d)==1)
				array_splice($this->_fd,$cc,0,array($item));
			else
				$this->_fd=null;
		}

		$this->_c++;

		return $c;

	}

	/**
	 * Removes an item from the priority list.
	 * The list will search for the item.  The first matching item found will be removed from the list.
	 * @param mixed item the item to be removed.
	 * @param numeric priority of item to remove. without this parameter it defaults to false.
	 * A value of false means any priority. null will be filled in with the default priority.
	 * @return integer index within the flattened list at which the item is being removed
	 * @throws TInvalidDataValueException If the item does not exist
	 */
	public function remove($item,$priority=false)
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		if(($p=$this->priorityOf($item,true))!==false)
		{
			if($priority!==false) {
				if($priority===null)
					$priority=$this->getDefaultPriority();
				$priority=(string)round(TPropertyValue::ensureFloat($priority),$this->_p);

				if($p[0]!=$priority)
					throw new TInvalidDataValueException('list_item_inexistent');
			}
			$this->removeAtIndexInPriority($p[1],$p[0]);
			return $p[2];
		}
		else
			throw new TInvalidDataValueException('list_item_inexistent');
	}

	/**
	 * Removes an item at the specified index in the flattened list.
	 * @param integer index of the item to be removed.
	 * @return mixed the removed item.
	 * @throws TInvalidDataValueException If the index specified exceeds the bound
	 * @throws TInvalidOperationException if the list is read-only
	 */
	public function removeAt($index)
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		if(($priority=$this->priorityAt($index, true))!==false)
			return $this->removeAtIndexInPriority($priority[1],$priority[0]);
		throw new TInvalidDataValueException('list_index_invalid',$index);
	}

	/**
	 * Removes the item at a specific index within a priority.  Override
	 * and call this method to insert your own functionality.
	 * @param integer index of item to remove within the priority.
	 * @param numeric priority of the item to remove, defaults to null, or left blank, it is then set to the default priority
	 * @return mixed the removed item.
	 * @throws TInvalidDataValueException If the item does not exist
	 */
	public function removeAtIndexInPriority($index, $priority=null)
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		if($priority===null)
			$priority=$this->getDefaultPriority();
		$priority=(string)round(TPropertyValue::ensureFloat($priority),$this->_p);

		if(!isset($this->_d[$priority])||$index<0||$index>=count($this->_d[$priority]))
			throw new TInvalidDataValueException('list_item_inexistent');

		// $value is an array of elements removed, only one
		$value=array_splice($this->_d[$priority],$index,1);
		$value=$value[0];

		if(!count($this->_d[$priority]))
			unset($this->_d[$priority]);

		$this->_c--;
		$this->_fd=null;
		return $value;
	}

	/**
	 * Removes all items in the priority list by calling removeAtIndexInPriority from the last item to the first.
	 */
	public function clear()
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		$d=array_reverse($this->_d,true);
		foreach($this->_d as $priority=>$items) {
			for($index=count($items)-1;$index>=0;$index--)
				$this->removeAtIndexInPriority($index,$priority);
			unset($this->_d[$priority]);
		}
	}

	/**
	 * @param mixed item
	 * @return boolean whether the list contains the item
	 */
	public function contains($item)
	{
		return $this->indexOf($item)>=0;
	}

	/**
	 * @param mixed item
	 * @return integer the index of the item in the flattened list (0 based), -1 if not found.
	 */
	public function indexOf($item)
	{
		if(($index=array_search($item,$this->flattenPriorities(),true))===false)
			return -1;
		else
			return $index;
	}

	/**
	 * Returns the priority of a particular item
	 * @param mixed the item to look for within the list
	 * @param boolean withindex this specifies if the full positional data of the item within the list is returned.
	 * 		This defaults to false, if no parameter is provided, so only provides the priority number of the item by default.
	 * @return numeric|array the priority of the item in the list, false if not found.
	 *   if withindex is true, an array is returned of [0 => $priority, 1 => $priorityIndex, 2 => flattenedIndex,
	 * 'priority' => $priority, 'index' => $priorityIndex, 'absindex' => flattenedIndex]
	 */
	public function priorityOf($item,$withindex = false)
	{
		$this->sortPriorities();

		$absindex = 0;
		foreach($this->_d as $priority=>$items) {
			if(($index=array_search($item,$items,true))!==false) {
				$absindex+=$index;
				return $withindex?array($priority,$index,$absindex,
						'priority'=>$priority,'index'=>$index,'absindex'=>$absindex):$priority;
			} else
				$absindex+=count($items);
		}

		return false;
	}

	/**
	 * Retutrns the priority of an item at a particular flattened index.
	 * @param integer index of the item within the list
	 * @param boolean withindex this specifies if the full positional data of the item within the list is returned.
	 * 		This defaults to false, if no parameter is provided, so only provides the priority number of the item by default.
	 * @return numeric|array the priority of the item in the list, false if not found.
	 *   if withindex is true, an array is returned of [0 => $priority, 1 => $priorityIndex, 2 => flattenedIndex,
	 * 'priority' => $priority, 'index' => $priorityIndex, 'absindex' => flattenedIndex]
	 */
	public function priorityAt($index,$withindex = false)
	{
		if($index<0||$index>=$this->getCount())
			throw new TInvalidDataValueException('list_index_invalid',$index);

		$absindex=$index;
		$this->sortPriorities();
		foreach($this->_d as $priority=>$items) {
			if($index>=($c=count($items)))
				$index-=$c;
			else
				return $withindex?array($priority,$index,$absindex,
						'priority'=>$priority,'index'=>$index,'absindex'=>$absindex):$priority;
		}
		return false;
	}

	/**
	 * This inserts an item before another item within the list.  It uses the same priority as the
	 * found index item and places the new item before it.
	 * @param mixed indexitem the item to index
	 * @param mixed the item to add before indexitem
	 * @return integer where the item has been inserted in the flattened list
	 * @throws TInvalidDataValueException If the item does not exist
	 */
	public function insertBefore($indexitem, $item)
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		if(($priority=$this->priorityOf($indexitem,true))===false)
			throw new TInvalidDataValueException('list_item_inexistent');

		$this->insertAtIndexInPriority($item,$priority[1],$priority[0]);

		return $priority[2];
	}

	/**
	 * This inserts an item after another item within the list.  It uses the same priority as the
	 * found index item and places the new item after it.
	 * @param mixed indexitem the item to index
	 * @param mixed the item to add after indexitem
	 * @return integer where the item has been inserted in the flattened list
	 * @throws TInvalidDataValueException If the item does not exist
	 */
	public function insertAfter($indexitem, $item)
	{
		if($this->getReadOnly())
			throw new TInvalidOperationException('list_readonly',get_class($this));

		if(($priority=$this->priorityOf($indexitem,true))===false)
			throw new TInvalidDataValueException('list_item_inexistent');

		$this->insertAtIndexInPriority($item,$priority[1]+1,$priority[0]);

		return $priority[2]+1;
	}

	/**
	 * @return array the priority list of items in array
	 */
	public function toArray()
	{
		return $this->flattenPriorities();
	}

	/**
	 * @return array the array of priorities keys with values of arrays of items.  The priorities are sorted so important priorities, lower numerics, are first.
	 */
	public function toPriorityArray()
	{
		$this->sortPriorities();
		return $this->_d;
	}

	/**
	 * Combines the map elements which have a priority below the parameter value
	 * @param numeric the cut-off priority.  All items of priority less than this are returned.
	 * @param boolean whether or not the input cut-off priority is inclusive.  Default: false, not inclusive.
	 * @return array the array of priorities keys with values of arrays of items that are below a specified priority.
	 *  The priorities are sorted so important priorities, lower numerics, are first.
	 */
	public function toArrayBelowPriority($priority,$inclusive=false)
	{
		$this->sortPriorities();
		$items=array();
		foreach($this->_d as $itemspriority=>$itemsatpriority)
		{
			if((!$inclusive&&$itemspriority>=$priority)||$itemspriority>$priority)
				break;
			$items=array_merge($items,$itemsatpriority);
		}
		return $items;
	}

	/**
	 * Combines the map elements which have a priority above the parameter value
	 * @param numeric the cut-off priority.  All items of priority greater than this are returned.
	 * @param boolean whether or not the input cut-off priority is inclusive.  Default: true, inclusive.
	 * @return array the array of priorities keys with values of arrays of items that are above a specified priority.
	 *  The priorities are sorted so important priorities, lower numerics, are first.
	 */
	public function toArrayAbovePriority($priority,$inclusive=true)
	{
		$this->sortPriorities();
		$items=array();
		foreach($this->_d as $itemspriority=>$itemsatpriority)
		{
			if((!$inclusive&&$itemspriority<=$priority)||$itemspriority<$priority)
				continue;
			$items=array_merge($items,$itemsatpriority);
		}
		return $items;
	}

	/**
	 * Copies iterable data into the priority list.
	 * Note, existing data in the map will be cleared first.
	 * @param mixed the data to be copied from, must be an array or object implementing Traversable
	 * @throws TInvalidDataTypeException If data is neither an array nor an iterator.
	 */
	public function copyFrom($data)
	{
		if($data instanceof TPriorityList)
		{
			if($this->getCount()>0)
				$this->clear();
			foreach($data->getPriorities() as $priority)
			{
				foreach($data->itemsAtPriority($priority) as $index=>$item)
					$this->insertAtIndexInPriority($item,$index,$priority);
			}
		} else if(is_array($data)||$data instanceof Traversable) {
			if($this->getCount()>0)
				$this->clear();
			foreach($data as $key=>$item)
				$this->add($item);
		} else if($data!==null)
			throw new TInvalidDataTypeException('map_data_not_iterable');
	}

	/**
	 * Merges iterable data into the priority list.
	 * New data will be appended to the end of the existing data.  If another TPriorityList is merged,
	 * the incoming parameter items will be appended at the priorities they are present.  These items will be added
	 * to the end of the existing items with equal priorities, if there are any.
	 * @param mixed the data to be merged with, must be an array or object implementing Traversable
	 * @throws TInvalidDataTypeException If data is neither an array nor an iterator.
	 */
	public function mergeWith($data)
	{
		if($data instanceof TPriorityList)
		{
			foreach($data->getPriorities() as $priority)
			{
				foreach($data->itemsAtPriority($priority) as $index=>$item)
					$this->insertAtIndexInPriority($item,false,$priority);
			}
		}
		else if(is_array($data)||$data instanceof Traversable)
		{
			foreach($data as $priority=>$item)
				$this->add($item);

		}
		else if($data!==null)
			throw new TInvalidDataTypeException('map_data_not_iterable');
	}

	/**
	 * Returns whether there is an element at the specified offset.
	 * This method is required by the interface ArrayAccess.
	 * @param mixed the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
		return ($offset>=0&&$offset<$this->getCount());
	}

	/**
	 * Returns the element at the specified offset.
	 * This method is required by the interface ArrayAccess.
	 * @param integer the offset to retrieve element.
	 * @return mixed the element at the offset, null if no element is found at the offset
	 */
	public function offsetGet($offset)
	{
		return $this->itemAt($offset);
	}

	/**
	 * Sets the element at the specified offset. This method is required by the interface ArrayAccess.
	 * Setting elements in a priority list is not straight forword when appending and setting at the
	 * end boundary.  When appending without an offset (a null offset), the item will be added at
	 * the default priority.  The item may not be the last item in the list.  When appending with an
	 * offset equal to the count of the list, the item will get be appended with the last items priority.
	 *
	 * All together, when setting the location of an item, the item stays in that location, but appending
	 * an item into a priority list doesn't mean the item is at the end of the list.
	 * @param integer the offset to set element
	 * @param mixed the element value
	 */
	public function offsetSet($offset,$item)
	{
		if($offset===null)
			return $this->add($item);
		if($offset===$this->getCount()) {
			$priority=$this->priorityAt($offset-1,true);
			$priority[1]++;
		} else {
			$priority=$this->priorityAt($offset,true);
			$this->removeAtIndexInPriority($priority[1],$priority[0]);
		}
		$this->insertAtIndexInPriority($item,$priority[1],$priority[0]);
	}

	/**
	 * Unsets the element at the specified offset.
	 * This method is required by the interface ArrayAccess.
	 * @param mixed the offset to unset element
	 */
	public function offsetUnset($offset)
	{
		$this->removeAt($offset);
	}
}


text:
ulx.motdmenu_exists = true

local isUrl
local url

function ulx.showMotdMenu( steamid )
	local window = vgui.Create( "DFrame" )
	if ScrW() > 640 then -- Make it larger if we can.
		window:SetSize( ScrW()*0.9, ScrH()*0.9 )
	else
		window:SetSize( 640, 480 )
	end
	window:Center()
	window:SetTitle( "ULX MOTD" )
	window:SetVisible( true )
	window:MakePopup()

	local html = vgui.Create( "HTML", window )

	local button = vgui.Create( "DButton", window )
	button:SetText( "Close" )
	button.DoClick = function() window:Close() end
	button:SetSize( 100, 40 )
	button:SetPos( (window:GetWide() - button:GetWide()) / 2, window:GetTall() - button:GetTall() - 10 )

	html:SetSize( window:GetWide() - 20, window:GetTall() - button:GetTall() - 50 )
	html:SetPos( 10, 30 )
	if not isUrl then
		html:SetHTML( ULib.fileRead( "data/ulx_motd.txt" ) )
	else
		url = string.gsub( url, "%%curmap%%", game.GetMap() )
		url = string.gsub( url, "%%steamid%%", steamid )
		html:OpenURL( url )
	end
end

function ulx.rcvMotd( isUrl_, text )
	isUrl = isUrl_
	if not isUrl then
		ULib.fileWrite( "data/ulx_motd.txt", text )
	else
		if text:find( "://", 1, true ) then
			url = text
		else
			url = "http://" .. text
		end
	end
end


text:
require "rspec-puppet"

fixture_path = File.expand_path File.join(__FILE__, "..", "fixtures")

$: << File.join(fixture_path, 'modules/module-data/lib')

RSpec.configure do |c|
  c.manifest_dir = File.join(fixture_path, "manifests")
  c.module_path  = File.join(fixture_path, "modules")
  c.hiera_config = File.join(fixture_path, 'hiera/hiera.yaml')
end

def default_test_facts
  {
    :boxen_home                  => '/test/boxen',
    :boxen_user                  => 'testuser',
    :boxen_srcdir                => '/test/boxen/src',
    :macosx_productversion_major => '10.8',
    :osfamily                    => 'Darwin',
  }
end


text:
package ui // import "miniflux.app/ui"

import (
	"net/http"

	"miniflux.app/http/request"
	"miniflux.app/http/response/html"
	"miniflux.app/http/route"
	"miniflux.app/model"
	"miniflux.app/ui/session"
	"miniflux.app/ui/view"
)

func (h *handler) showSearchEntriesPage(w http.ResponseWriter, r *http.Request) {
	user, err := h.store.UserByID(request.UserID(r))
	if err != nil {
		html.ServerError(w, r, err)
		return
	}

	searchQuery := request.QueryStringParam(r, "q", "")
	offset := request.QueryIntParam(r, "offset", 0)
	builder := h.store.NewEntryQueryBuilder(user.ID)
	builder.WithSearchQuery(searchQuery)
	builder.WithoutStatus(model.EntryStatusRemoved)
	builder.WithOffset(offset)
	builder.WithLimit(user.EntriesPerPage)

	entries, err := builder.GetEntries()
	if err != nil {
		html.ServerError(w, r, err)
		return
	}

	count, err := builder.CountEntries()
	if err != nil {
		html.ServerError(w, r, err)
		return
	}

	sess := session.New(h.store, request.SessionID(r))
	view := view.New(h.tpl, r, sess)
	pagination := getPagination(route.Path(h.router, "searchEntries"), count, offset, user.EntriesPerPage)
	pagination.SearchQuery = searchQuery

	view.Set("searchQuery", searchQuery)
	view.Set("entries", entries)
	view.Set("total", count)
	view.Set("pagination", pagination)
	view.Set("menu", "search")
	view.Set("user", user)
	view.Set("countUnread", h.store.CountUnreadEntries(user.ID))
	view.Set("countErrorFeeds", h.store.CountUserFeedsWithErrors(user.ID))
	view.Set("hasSaveEntry", h.store.HasSaveEntry(user.ID))

	html.OK(w, r, view.Render("search_entries"))
}


text:
class BalanceUpdater
  def initialize(credit_agreement)
    @credit_agreement = credit_agreement
  end

  def run
    create_missing_balances
    delete_unnecessary_balances
    update_balances
  end

  private
    def create_missing_balances
      (obligatory_balances_dates - existing_balances_dates).each do |balance_date|
        @credit_agreement.auto_balances.create!(date: balance_date)
      end
    end

    def delete_unnecessary_balances
      @credit_agreement.balances.before(date_of_first_payment).destroy_all
    end

    def update_balances
      @credit_agreement.auto_balances.each(&:update_end_amount!)
    end

    def obligatory_balances_dates
      (date_of_first_payment.year...last_obligatory_year).map{ |y| Date.new(y, 12, 31) }
    end

    def last_obligatory_year
      return this_year unless @credit_agreement.terminated_at
      @credit_agreement.terminated_at.year
    end

    def existing_balances_dates
      @credit_agreement.balances.pluck(:date)
    end

    def date_of_first_payment
      (@credit_agreement.payments.first || NullPayment.new).date
    end

    def this_year
      Date.today.year
    end
end


text:
namespace Apache.Ignite.Core.Discovery.Tcp
{
    using Apache.Ignite.Core.Binary;
    using Apache.Ignite.Core.Discovery.Tcp.Multicast;
    using Apache.Ignite.Core.Discovery.Tcp.Static;

    /// <summary>
    /// Base IpFinder class.
    /// </summary>
    public abstract class TcpDiscoveryIpFinderBase : ITcpDiscoveryIpFinder
    {
        /** */
        protected const byte TypeCodeVmIpFinder = 1;

        /** */
        protected const byte TypeCodeMulticastIpFinder = 2;

        /// <summary>
        /// Initializes a new instance of the <see cref="TcpDiscoveryIpFinderBase"/> class.
        /// Prevents user-defined implementations.
        /// </summary>
        protected internal TcpDiscoveryIpFinderBase()
        {
            // No-op.
        }

        /// <summary>
        /// Writes this instance to the specified writer.
        /// </summary>
        /// <param name="writer">The writer.</param>
        internal virtual void Write(IBinaryRawWriter writer)
        {
            writer.WriteByte(TypeCode);
        }

        /// <summary>
        /// Gets the type code to be used in Java to determine ip finder type.
        /// </summary>
        protected abstract byte TypeCode { get; }

        /// <summary>
        /// Reads the instance.
        /// </summary>
        internal static TcpDiscoveryIpFinderBase ReadInstance(IBinaryRawReader reader)
        {
            var code = reader.ReadByte();

            switch (code)
            {
                case TypeCodeVmIpFinder:
                    return new TcpDiscoveryStaticIpFinder(reader);

                case TypeCodeMulticastIpFinder:
                    return new TcpDiscoveryMulticastIpFinder(reader);

                default:
                    return null;
            }
        }
    }
}


text:
HexColors
=========================
![Badge w/ Version](https://cocoapod-badges.herokuapp.com/v/HexColors/badge.png)

![Badge w/ Version](https://cocoapod-badges.herokuapp.com/p/HexColors/badge.png)

HexColors is drop in category for HexColor Support for NSColor and UIColor. Support for HexColors with prefixed # and without.

#Example iOS
``` objective-c
// with hash
UIColor *colorWithHex = [UIColor colorWithHexString:@"#ff8942" alpha:1];

// without hash
UIColor *secondColorWithHex = [UIColor colorWithHexString:@"ff8942" alpha:1];

// short handling
UIColor *shortColorWithHex = [UIColor colorWithHexString:@"fff" alpha:1];
```

#Example Mac OS X
``` objective-c
// with hash
NSColor *colorWithHex = [NSColor colorWithHexString:@"#ff8942" alpha:1];

// wihtout hash
NSColor *secondColorWithHex = [NSColor colorWithHexString:@"ff8942" alpha:1];

// short handling
NSColor *shortColorWithHex = [NSColor colorWithHexString:@"fff" alpha:1];
```

#Installation
* `#import "HexColor.h"` where you want to use easy as pie HexColors
* `pod install HexColors`
* or just drag the source files in your project

##Requirements
HexColors requires [iOS 5.0](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html) and above, and Mac OS X 10.6

#ToDos
* Implementing Hex Alpha values

##Credits
HexColors was created by [Marius Landwehr](https://github.com/mRs-) because of the pain recalculating Hex values to RGB.

HexColors was ported to Mac OS X by [holgersindbaek](https://github.com/holgersindbaek).

##Creator
[Marius Landwehr](https://github.com/mRs-) [@mariusLAN](https://twitter.com/mariusLAN)

##License
HexColors is available underthe MIT license. See the LICENSE file for more info.


text:
////////////////////////////////////////////////////////////////////////////////
//
// Package:   RoadNarrows Robotics ROS Chess Engine Package
//
// Link:      https://github.com/roadnarrows-robotics/chess_engine
//
// Library:   libchessengine
//
// File:      ceGame.h
//

/*
 * @EulaBegin@
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and its documentation for any purpose, provided that
 * (1) The above copyright notice and the following two paragraphs
 * appear in all copies of the source code and (2) redistributions
 * including binaries reproduces these notices in the supporting
 * documentation.   Substantial modifications to this software may be
 * copyrighted by their authors and need not follow the licensing terms
 * described here, provided that the new terms are clearly indicated in
 * all files where they apply.
 *
 * IN NO EVENT SHALL THE AUTHOR, ROADNARROWS LLC, OR ANY MEMBERS/EMPLOYEES
 * OF ROADNARROW LLC OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY
 * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
 * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
 * EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 *
 * THE AUTHOR AND ROADNARROWS LLC SPECIFICALLY DISCLAIM ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN
 * "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 * @EulaEnd@
 */
////////////////////////////////////////////////////////////////////////////////

#ifndef _CE_GAME_H
#define _CE_GAME_H

#include <iostream>
#include <string>
#include <vector>
#include <map>

#include "chess_engine/ceTypes.h"
#include "chess_engine/ceSquare.h"
#include "chess_engine/ceBoard.h"
#include "chess_engine/cePlayer.h"
#include "chess_engine/ceMove.h"
#include "chess_engine/ceError.h"
#include "chess_engine/ceUtils.h"

/*!
 * \brief Package top-level namespace.
 */
namespace chess_engine
{
  // ---------------------------------------------------------------------------
  // Class ChessGame
  // ---------------------------------------------------------------------------

  /*!
   * \brief Chess game class.
   */
  class ChessGame
  {
  public:
    //
    // Types
    //
    typedef std::vector<ChessFqPiece> ChessBoneYard;    ///< captured pieces
    typedef std::vector<ChessMove>    ChessHistory;     ///< game history
    typedef std::map<ChessColor, int> ChessPromotion;   ///< promotions/player

    /*!
     * \brief Default constructor.
     */
    ChessGame();

    /*!
     * \brief Destructor.
     */
    virtual ~ChessGame();

    /*!
     * \brief Start a new game.
     *
     * The caller provides the two antagonists. If NULL, an anonymous player is
     * provided.
     *
     * White moves first.
     *
     * \param pWhite    Pointer to player playing white.
     * \param pBlack    Pointer to player playing black.
     *
     * \return Returns CE_OK on success, negative error code on failure.
     */
    int startNewGame(ChessPlayer *pWhite = NULL, ChessPlayer *pBlack = NULL);

    /*!
     * \brief End current game.
     *
     * \param eReason   Reason game ended.
     * \param eWinner   Declared winner, if any.
     *
     * \return Returns CE_OK on success, negative error code on failure.
     */
    int endCurrentGame(ChessResult eReason, ChessColor eWinner = NoColor);

    /*!
     * \brief Fully qualify the chess move.
     *
     * The move is reasonably verified and additional move fields are set
     * by examining the game and board state.
     *
     * \param [in,out] move   Chess move.
     *
     * \return Returns CE_OK on success, negative error code on failure.
     */
    int qualifyMove(ChessMove &move);

    /*!
     * \brief Qualify the chess move source and destination positions.
     *
     * \param [in,out] move   Chess move.
     *
     * \return Returns CE_OK on success, negative error code on failure.
     */
    int qualifyMovePositions(ChessMove &move);

    /*!
     * \brief Qualify the moved chess piece.
     *
     * \param [in,out] move   Chess move.
     *
     * \return Returns CE_OK on success, negative error code on failure.
     */
    int qualifyMovePiece(ChessMove &move);

    /*!
     * \brief Qualify any capture.
     *
     * \param [in,out] move   Chess move.
     *
     * \return Returns CE_OK on success, negative error code on failure.
     */
    int qualifyMoveCapture(ChessMove &move);

    /*!
     * \brief Execute move.
     *
     * \param [in] move   Chess move.
     *
     * \return Returns CE_OK on success, negative error code on failure.
     */
    int execMove(ChessMove &move);

    /*!
     * \brief Set up the game.
     */
    void setupGame();

    /*!
     * \brief Test if a game is being played.
     *
     * \return Returns true or false.
     */
    bool isPlayingAGame() const
    {
      return m_bIsPlaying;
    }

    /*!
     * \brief Get current or most recent players' names.
     *
     * \param [out] strWhite  White player's name.
     * \param [out] strBlack  Black player's name.
     */
    void getPlayerNames(std::string &strWhite, std::string &strBlack) const;

    /*!
     * \brief Get the game's winner, if any.
     *
     * \return Returns White, Black, or NoColor.
     */
    ChessColor getWinner() const
    {
      return m_eWinner;
    }

    /*!
     * Get the current play state code.
     *
     * \return Returns reason code.
     */
    ChessResult getPlayState() const
    {
      return m_ePlayState;
    }

    /*!
     * \brief Get the number of plies (half-moves) played.
     *
     * \return Number of plies.
     */
    int getNumOfPliesPlayed() const;

    /*!
     * \brief Get the number of completed moves played.
     *
     * One completed move is White then Black, with White always starting.
     *
     * \return Number of moves.
     */
    int getNumOfMovesPlayed() const;

    /*!
     * \brief Get the current move number in play.
     *
     * \return If a game is in play, returns move number \> 0. Else returns 0.
     */
    int getMoveNumInPlay() const;

    /*!
     * \brief Get a reference to the board square.
     *
     * \param file  Chess board file.
     * \param rank  Chess board rank.
     *
     * \return If in range, returns the reference to the board's square.\n
     * If out-of-range, returns "no square" square
     * (check with ChessSquare.isOnChessBoard).
     */
    ChessSquare &getBoardSquare(const int file, const int rank);

    /*!
     * \brief Get a reference to the board square.
     *
     * \param pos   Chess board position.
     *
     * \return If in range, returns the reference to the board's square.\n
     * If out-of-range, returns "no square" square
     * (check with ChessSquare.isOnChessBoard).
     */
    ChessSquare &getBoardSquare(const ChessPos &pos);

    /*!
     * \brief Get the chess board state.
     *
     * \return Reference to board.
     */
    ChessBoard &getBoard()
    {
      return m_board;
    }

    /*!
     * \brief Get the player's bone yard (captured pieces).
     *
     * \param ePlayer   Player and color of captured piece.
     *
     * \return Reference to bone yard.
     */
    const ChessBoneYard &getBoneYard(const ChessColor ePlayer) const
    {
      return ePlayer == White? m_boneyardWhite: m_boneyardBlack;
    }

    /*!
     * \brief Get the game history.
     *
     * \return Reference to history.
     */
    const ChessHistory &getGameHistory() const
    {
      return m_history;
    }

    /*!
     * \brief Get game history at the give ply.
     *
     * \param nPlyNum   Ply number (1/2 moves)
     *
     * \return Reference to history move.
     */
    const ChessMove &getHistoryAt(int nPlyNum) const;

    /*!
     * \brief Set unicode graphic state.
     *
     * \param on_off    State.
     */
    void setGuiState(bool on_off)
    {
      m_bGraphic = on_off;
      m_board.setGraphicState(on_off);
    }

    // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    // Static Member Functions
    // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

  protected:
    //
    // Layout
    //
    ChessBoard    m_board;          ///< the standard chess board
    ChessBoneYard m_boneyardWhite;  ///< captured white pieces
    ChessBoneYard m_boneyardBlack;  ///< captured black pieces
    ChessHistory  m_history;        ///< game history

    //
    // Game state
    //
    bool          m_bIsPlaying;     ///< is [not] playing a game
    ChessResult   m_ePlayState;     ///< current play state
    ChessColor    m_eWinner;        ///< end of game winner, if any

    //
    // Player state
    //
    ChessColor      m_eTurnToMove;    ///< current player's turn to move
    ChessPromotion  m_numPromotions;  ///< number of promotions/player
    ChessPlayer     m_anonWhite;      ///< anonymous white player
    ChessPlayer     m_anonBlack;      ///< anonymous black player
    ChessPlayer    *m_pPlayerWhite;   ///< pointer to current white player
    ChessPlayer    *m_pPlayerBlack;   ///< pointer to current black player

    //
    // Other
    //
    bool      m_bGraphic;             ///< [not] a graphic stream output

    /*!
     * \brief Record game history.
     *
     * \param move    Move to record.
     */
    void recordHistory(ChessMove &move);

    /*!
     * \brief Drop piece into the player's bone yard.
     *
     * The piece is removed from the board.
     *
     * \param ePlayer   Player and color of captured piece.
     * \param pos       Board position of piece.
     */
    void dropInBoneYard(const ChessColor ePlayer, const ChessPos &pos);

    //
    // Friends
    //
    friend std::ostream &operator<<(std::ostream &os, const ChessGame &game);
  };

  // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  // Friends
  // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

  /*!
   * \brief ChessGame output stream operator.
   *
   * \param os    Output stream.
   * \param board Chess game.
   *
   * \return Output stream.
   */
  extern std::ostream &operator<<(std::ostream &os, const ChessGame &game);

} // chess_engine

#endif // _CE_GAME_H


text:
export class History {
    activate() {
        throw new Error('History must implement activate().');
    }
    deactivate() {
        throw new Error('History must implement deactivate().');
    }
    navigate() {
        throw new Error('History must implement navigate().');
    }
    navigateBack() {
        throw new Error('History must implement navigateBack().');
    }
}


text:
#pragma once
#include <dfk/http/response.h>
#include <dfk/wrapper.hpp>
#include <dfk/core.hpp>
#include <dfk/buffer.hpp>
#include <dfk/string_map.hpp>
#include <dfk/http/method.hpp>
#include <dfk/http/status.hpp>

namespace dfk {
namespace http {

class Server;

class Response : public Wrapper<dfk_http_response_t, dfk_http_response_sizeof>
{
public:
  Response(dfk_http_response_t* response);

  const Server* server() const;
  Server* server();

  StringMap headers() const;
  Response& majorVersion(unsigned short majorVersion);
  Response& minorVersion(unsigned short minorVersion);
  Response& status(Status status);
  Response& contentLength(std::size_t contentLength);
  Response& chunked();
  Response& keepalive();
  ssize_t write(char* buf, std::size_t nbytes);
  ssize_t writev(IoVec* iov, std::size_t niov);
  Response& set(const char* name, std::size_t namelen, const char* value, std::size_t valuelen);
};

}} // namespace dfk::http


text:
<?php

namespace Pum\Bundle\CoreBundle\Command;

use Pum\Bundle\CoreBundle\Console\OutputLogger;
use Pum\Core\Definition\Project;
use Pum\Core\Extension\EmFactory\EmFactoryExtension;
use Pum\Core\Event\ProjectEvent;
use Pum\Core\Events;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\ArrayInput;

class UpdateSchemaCommand extends ContainerAwareCommand
{
    public function configure()
    {
        $this
            ->setName('pum:schema:update')
            ->setDescription('Updates dynamic schema')
        ;
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->executeCommand('doctrine:schema:update', array('--force' => true), $output);

        foreach ($this->getContainer()->get('pum')->getAllProjects() as $project) {
            $this->doUpdate($project, $output);
        }
    }

    public function doUpdate(Project $project, OutputInterface $output)
    {
        $project->raise(Events::PROJECT_SCHEMA_UPDATE, new ProjectEvent($project));
        $this->getContainer()->get('pum')->saveProject($project);
        $output->writeln('Updated project <info>'.$project->getName().'</info>');
    }

    private function executeCommand($command, $arguments, OutputInterface $output)
    {
        $command              = $this->getApplication()->find($command);
        $arguments['command'] = $command;
        $input                = new ArrayInput($arguments);

        $returnCode = $command->run($input, $output);

        if($returnCode == 0) {
            return true;
        }

        return false;
    }
}


text:
package tk.mybatis.mapper.model;

import javax.persistence.Column;

/**
 * @author liuzh_3nofxnp
 * @since 2016-08-29 22:36
 */
public class UserParent {

    @Column(updatable = false)
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


text:
package com.atomgraph.processor.model;

import javax.ws.rs.core.MultivaluedMap;
import org.apache.jena.query.QuerySolutionMap;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;

/**
 *
 * @author Martynas Jusevičius {@literal <martynas@atomgraph.com>}
 */
public interface TemplateCall
{

    Template getTemplate();

    TemplateCall applyArguments(MultivaluedMap<String, String> queryParams);

    TemplateCall applyDefaults();

    StmtIterator listArguments();

    boolean hasArgument(Property predicate);

    Resource getArgument(Property predicate);

    boolean hasArgument(String varName, RDFNode object);

    Resource getArgument(String varName, RDFNode object);

    Statement getArgumentProperty(Property predicate);

    TemplateCall arg(Parameter param, RDFNode value);

    TemplateCall arg(Resource arg);

    TemplateCall validateOptionals();

    QuerySolutionMap getQuerySolutionMap();

    Resource build();

}


text:
using System;

namespace MongoDB.Bson
{
    /// <summary>
    /// Represents the BSON Null value.
    /// </summary>
    [Serializable]
    public class BsonNull : BsonValue, IComparable<BsonNull>, IEquatable<BsonNull>
    {
        // private static fields
        private static BsonNull __value = new BsonNull();

        // constructors
        // private so only the singleton instance can be created
        private BsonNull()
            : base(BsonType.Null)
        {
        }

        // public operators
        /// <summary>
        /// Compares two BsonNull values.
        /// </summary>
        /// <param name="lhs">The first BsonNull.</param>
        /// <param name="rhs">The other BsonNull.</param>
        /// <returns>True if the two BsonNull values are not equal according to ==.</returns>
        public static bool operator !=(BsonNull lhs, BsonNull rhs)
        {
            return !(lhs == rhs);
        }

        /// <summary>
        /// Compares two BsonNull values.
        /// </summary>
        /// <param name="lhs">The first BsonNull.</param>
        /// <param name="rhs">The other BsonNull.</param>
        /// <returns>True if the two BsonNull values are equal according to ==.</returns>
        public static bool operator ==(BsonNull lhs, BsonNull rhs)
        {
            if (object.ReferenceEquals(lhs, null)) { return object.ReferenceEquals(rhs, null); }
            return lhs.Equals(rhs);
        }

        // public static properties
        /// <summary>
        /// Gets the singleton instance of BsonNull.
        /// </summary>
        public static BsonNull Value { get { return __value; } }

        // public methods
        /// <summary>
        /// Compares this BsonNull to another BsonNull.
        /// </summary>
        /// <param name="other">The other BsonNull.</param>
        /// <returns>A 32-bit signed integer that indicates whether this BsonNull is less than, equal to, or greather than the other.</returns>
        public int CompareTo(BsonNull other)
        {
            if (other == null) { return 1; }
            return 0; // it's a singleton
        }

        /// <summary>
        /// Compares the BsonNull to another BsonValue.
        /// </summary>
        /// <param name="other">The other BsonValue.</param>
        /// <returns>A 32-bit signed integer that indicates whether this BsonNull is less than, equal to, or greather than the other BsonValue.</returns>
        public override int CompareTo(BsonValue other)
        {
            if (other == null) { return 1; }
            if (other is BsonMinKey) { return 1; }
            if (other is BsonUndefined) { return 1; }
            if (other is BsonNull) { return 0; }
            return -1;
        }

        /// <summary>
        /// Compares this BsonNull to another BsonNull.
        /// </summary>
        /// <param name="rhs">The other BsonNull.</param>
        /// <returns>True if the two BsonNull values are equal.</returns>
        public bool Equals(BsonNull rhs)
        {
            if (object.ReferenceEquals(rhs, null) || GetType() != rhs.GetType()) { return false; }
            return true; // it's a singleton
        }

        /// <summary>
        /// Compares this BsonNull to another object.
        /// </summary>
        /// <param name="obj">The other object.</param>
        /// <returns>True if the other object is a BsonNull and equal to this one.</returns>
        public override bool Equals(object obj)
        {
            return Equals(obj as BsonNull); // works even if obj is null or of a different type
        }

        /// <summary>
        /// Gets the hash code.
        /// </summary>
        /// <returns>The hash code.</returns>
        public override int GetHashCode()
        {
            return BsonType.GetHashCode();
        }

        /// <summary>
        /// Converts this BsonValue to a Boolean (using the JavaScript definition of truthiness).
        /// </summary>
        /// <returns>A Boolean.</returns>
        public override bool ToBoolean()
        {
            return false;
        }

        /// <summary>
        /// Converts this BsonValue to a DateTime? in local time.
        /// </summary>
        /// <returns>A DateTime?.</returns>
        public override DateTime? ToNullableLocalTime()
        {
            return null;
        }

        /// <summary>
        /// Converts this BsonValue to a DateTime? in UTC.
        /// </summary>
        /// <returns>A DateTime?.</returns>
        public override DateTime? ToNullableUniversalTime()
        {
            return null;
        }

        /// <summary>
        /// Returns a string representation of the value.
        /// </summary>
        /// <returns>A string representation of the value.</returns>
        public override string ToString()
        {
            return "BsonNull";
        }
    }
}


text:
package org.apache.solr.cloud.api.collections;

import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;
import static org.apache.solr.common.cloud.ZkStateReader.CORE_NAME_PROP;
import static org.apache.solr.common.params.CollectionAdminParams.FOLLOW_ALIASES;
import static org.apache.solr.common.params.CommonAdminParams.ASYNC;
import static org.apache.solr.common.params.CommonParams.NAME;

import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.solr.cloud.api.collections.CollectionHandlingUtils.ShardRequestTracker;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Replica.State;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.params.CoreAdminParams;
import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.snapshots.CollectionSnapshotMetaData;
import org.apache.solr.core.snapshots.CollectionSnapshotMetaData.CoreSnapshotMetaData;
import org.apache.solr.core.snapshots.CollectionSnapshotMetaData.SnapshotStatus;
import org.apache.solr.core.snapshots.SolrSnapshotManager;
import org.apache.solr.handler.component.ShardHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** This class implements the functionality of creating a collection level snapshot. */
public class CreateSnapshotCmd implements CollApiCmds.CollectionApiCommand {
  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
  private final CollectionCommandContext ccc;

  public CreateSnapshotCmd(CollectionCommandContext ccc) {
    this.ccc = ccc;
  }

  @Override
  public void call(ClusterState state, ZkNodeProps message, NamedList<Object> results)
      throws Exception {
    String extCollectionName = message.getStr(COLLECTION_PROP);
    boolean followAliases = message.getBool(FOLLOW_ALIASES, false);

    String collectionName;
    if (followAliases) {
      collectionName = ccc.getZkStateReader().getAliases().resolveSimpleAlias(extCollectionName);
    } else {
      collectionName = extCollectionName;
    }

    String commitName = message.getStr(CoreAdminParams.COMMIT_NAME);
    String asyncId = message.getStr(ASYNC);
    SolrZkClient zkClient = ccc.getZkStateReader().getZkClient();
    Date creationDate = new Date();

    if (SolrSnapshotManager.snapshotExists(zkClient, collectionName, commitName)) {
      throw new SolrException(
          ErrorCode.BAD_REQUEST,
          "Snapshot with name " + commitName + " already exists for collection " + collectionName);
    }

    log.info(
        "Creating a snapshot for collection={} with commitName={}", collectionName, commitName);

    // Create a node in ZK to store the collection level snapshot meta-data.
    SolrSnapshotManager.createCollectionLevelSnapshot(
        zkClient, collectionName, new CollectionSnapshotMetaData(commitName));
    log.info(
        "Created a ZK path to store snapshot information for collection={} with commitName={}",
        collectionName,
        commitName);

    NamedList<Object> shardRequestResults = new NamedList<>();
    Map<String, Slice> shardByCoreName = new HashMap<>();
    ShardHandler shardHandler = ccc.newShardHandler();

    final ShardRequestTracker shardRequestTracker =
        CollectionHandlingUtils.asyncRequestTracker(asyncId, ccc);
    for (Slice slice :
        ccc.getZkStateReader().getClusterState().getCollection(collectionName).getSlices()) {
      for (Replica replica : slice.getReplicas()) {
        if (replica.getState() != State.ACTIVE) {
          if (log.isInfoEnabled()) {
            log.info(
                "Replica {} is not active. Hence not sending the createsnapshot request",
                replica.getCoreName());
          }
          continue; // Since replica is not active - no point sending a request.
        }

        String coreName = replica.getStr(CORE_NAME_PROP);

        ModifiableSolrParams params = new ModifiableSolrParams();
        params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATESNAPSHOT.toString());
        params.set(NAME, slice.getName());
        params.set(CORE_NAME_PROP, coreName);
        params.set(CoreAdminParams.COMMIT_NAME, commitName);

        shardRequestTracker.sendShardRequest(replica.getNodeName(), params, shardHandler);
        log.debug(
            "Sent createsnapshot request to core={} with commitName={}", coreName, commitName);

        shardByCoreName.put(coreName, slice);
      }
    }

    // At this point we want to make sure that at-least one replica for every shard
    // is able to create the snapshot. If that is not the case, then we fail the request.
    // This is to take care of the situation where e.g. entire shard is unavailable.
    Set<String> failedShards = new HashSet<>();

    shardRequestTracker.processResponses(shardRequestResults, shardHandler, false, null);
    NamedList<?> success = (NamedList<?>) shardRequestResults.get("success");
    List<CoreSnapshotMetaData> replicas = new ArrayList<>();
    if (success != null) {
      for (int i = 0; i < success.size(); i++) {
        @SuppressWarnings("unchecked")
        NamedList<Object> resp = (NamedList<Object>) success.getVal(i);

        // Check if this core is the leader for the shard. The idea here is that during the backup
        // operation we preferably use the snapshot of the "leader" replica since it is most likely
        // to have latest state.
        String coreName = (String) resp.get(CoreAdminParams.CORE);
        Slice slice = shardByCoreName.remove(coreName);
        boolean leader =
            (slice.getLeader() != null && slice.getLeader().getCoreName().equals(coreName));
        resp.add(SolrSnapshotManager.SHARD_ID, slice.getName());
        resp.add(SolrSnapshotManager.LEADER, leader);

        CoreSnapshotMetaData c = new CoreSnapshotMetaData(resp);
        replicas.add(c);
        if (log.isInfoEnabled()) {
          log.info(
              "Snapshot with commitName {} is created successfully for core {}",
              commitName,
              c.getCoreName());
        }
      }
    }

    if (!shardByCoreName.isEmpty()) { // One or more failures.
      log.warn(
          "Unable to create a snapshot with name {} for following cores {}",
          commitName,
          shardByCoreName.keySet());

      // Count number of failures per shard.
      Map<String, Integer> failuresByShardId = new HashMap<>();
      for (Map.Entry<String, Slice> entry : shardByCoreName.entrySet()) {
        int f = 0;
        if (failuresByShardId.get(entry.getValue().getName()) != null) {
          f = failuresByShardId.get(entry.getValue().getName());
        }
        failuresByShardId.put(entry.getValue().getName(), f + 1);
      }

      // Now that we know number of failures per shard, we can figure out
      // if at-least one replica per shard was able to create a snapshot or not.
      DocCollection collectionStatus =
          ccc.getZkStateReader().getClusterState().getCollection(collectionName);
      for (Map.Entry<String, Integer> entry : failuresByShardId.entrySet()) {
        int replicaCount = collectionStatus.getSlice(entry.getKey()).getReplicas().size();
        if (replicaCount <= entry.getValue()) {
          failedShards.add(entry.getKey());
        }
      }
    }

    if (failedShards.isEmpty()) { // No failures.
      CollectionSnapshotMetaData meta =
          new CollectionSnapshotMetaData(
              commitName, SnapshotStatus.Successful, creationDate, replicas);
      SolrSnapshotManager.updateCollectionLevelSnapshot(zkClient, collectionName, meta);
      if (log.isInfoEnabled()) {
        log.info(
            "Saved following snapshot information for collection={} with commitName={} in Zookeeper : {}",
            collectionName,
            commitName,
            meta.toNamedList());
      }
    } else {
      log.warn(
          "Failed to create a snapshot for collection {} with commitName = {}. Snapshot could not be captured for following shards {}",
          collectionName,
          commitName,
          failedShards);
      // Update the ZK meta-data to include only cores with the snapshot. This will enable users to
      // figure out which cores have the named snapshot.
      CollectionSnapshotMetaData meta =
          new CollectionSnapshotMetaData(commitName, SnapshotStatus.Failed, creationDate, replicas);
      SolrSnapshotManager.updateCollectionLevelSnapshot(zkClient, collectionName, meta);
      if (log.isInfoEnabled()) {
        log.info(
            "Saved following snapshot information for collection={} with commitName={} in Zookeeper : {}",
            collectionName,
            commitName,
            meta.toNamedList());
      }
      throw new SolrException(
          ErrorCode.SERVER_ERROR, "Failed to create snapshot on shards " + failedShards);
    }
  }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include <cstdint>
#include <functional>

namespace document { class GlobalId; }

namespace search {

/*
 * Interface for gid to lid mapper visitor.
 */
class IGidToLidMapperVisitor
{
public:
    virtual ~IGidToLidMapperVisitor() { }
    virtual void visit(const document::GlobalId &gid, uint32_t lid) const = 0;
};

/*
 * Interface class for mapping from gid to lid. Instances should be short
 * lived due to implementations containing read guards preventing resource
 * reuse.
 */
class IGidToLidMapper
{
public:
    virtual ~IGidToLidMapper() { }
    virtual void foreach(const IGidToLidMapperVisitor &visitor) const = 0;
};

} // namespace search


text:
<?php

namespace haqqi\metronic\assets\plugins;

use haqqi\metronic\base\assets\GlobalPluginAssetBundle;

class JsCookieAsset extends GlobalPluginAssetBundle
{
    public $js = [
        'js.cookie.min.js'
    ];
}


text:
package app.util;

import spark.*;
import static app.util.RequestUtil.*;

public class Filters {

    // If a user manually manipulates paths and forgets to add
    // a trailing slash, redirect the user to the correct path
    public static Filter addTrailingSlashes = (Request request, Response response) -> {
        if (!request.pathInfo().endsWith("/")) {
            response.redirect(request.pathInfo() + "/");
        }
    };

    // Locale change can be initiated from any page
    // The locale is extracted from the request and saved to the user's session
    public static Filter handleLocaleChange = (Request request, Response response) -> {
        if (getQueryLocale(request) != null) {
            request.session().attribute("locale", getQueryLocale(request));
            response.redirect(request.pathInfo());
        }
    };

    // Enable GZIP for all responses
    public static Filter addGzipHeader = (Request request, Response response) -> {
        response.header("Content-Encoding", "gzip");
    };

}


text:
import os
import numpy as np
import sys
import cPickle as pickle
import random
import cv2
import theano
import theano.tensor as T
import lasagne

from tqdm import tqdm
from constants import *
from models.model_salgan import ModelSALGAN
from models.model_bce import ModelBCE
from utils import *

flag = str(sys.argv[1])

def bce_batch_iterator(model, train_data, validation_sample):
    num_epochs = 301
    n_updates = 1
    nr_batches_train = int(len(train_data) / model.batch_size)
    for current_epoch in tqdm(range(num_epochs), ncols=20):
        e_cost = 0.

        random.shuffle(train_data)

        for currChunk in chunks(train_data, model.batch_size):

            if len(currChunk) != model.batch_size:
                continue

            batch_input = np.asarray([x.image.data.astype(theano.config.floatX).transpose(2, 0, 1) for x in currChunk],
                                     dtype=theano.config.floatX)

            batch_output = np.asarray([y.saliency.data.astype(theano.config.floatX) / 255. for y in currChunk],
                                      dtype=theano.config.floatX)
            batch_output = np.expand_dims(batch_output, axis=1)

            # train generator with one batch and discriminator with next batch
            G_cost = model.G_trainFunction(batch_input, batch_output)
            e_cost += G_cost
            n_updates += 1

        e_cost /= nr_batches_train

        print 'Epoch:', current_epoch, ' train_loss->', e_cost

        if current_epoch % 5 == 0:
            np.savez('./' + DIR_TO_SAVE + '/gen_modelWeights{:04d}.npz'.format(current_epoch),
                     *lasagne.layers.get_all_param_values(model.net['output']))
            predict(model=model, image_stimuli=validation_sample, num_epoch=current_epoch, path_output_maps=DIR_TO_SAVE)

def salgan_batch_iterator(model, train_data, validation_sample):
    num_epochs = 301
    nr_batches_train = int(len(train_data) / model.batch_size)
    n_updates = 1
    for current_epoch in tqdm(range(num_epochs), ncols=20):

        g_cost = 0.
        d_cost = 0.
        e_cost = 0.

        random.shuffle(train_data)

        for currChunk in chunks(train_data, model.batch_size):

            if len(currChunk) != model.batch_size:
                continue

            batch_input = np.asarray([x.image.data.astype(theano.config.floatX).transpose(2, 0, 1) for x in currChunk],
                                     dtype=theano.config.floatX)
            batch_output = np.asarray([y.saliency.data.astype(theano.config.floatX) / 255. for y in currChunk],
                                      dtype=theano.config.floatX)
            batch_output = np.expand_dims(batch_output, axis=1)

            # train generator with one batch and discriminator with next batch
            if n_updates % 2 == 0:
                G_obj, D_obj, G_cost = model.G_trainFunction(batch_input, batch_output)
                d_cost += D_obj
                g_cost += G_obj
                e_cost += G_cost
            else:
                G_obj, D_obj, G_cost = model.D_trainFunction(batch_input, batch_output)
                d_cost += D_obj
                g_cost += G_obj
                e_cost += G_cost

            n_updates += 1

        g_cost /= nr_batches_train
        d_cost /= nr_batches_train
        e_cost /= nr_batches_train

        # Save weights every 3 epoch
        if current_epoch % 3 == 0:
            np.savez('./' + DIR_TO_SAVE + '/gen_modelWeights{:04d}.npz'.format(current_epoch),
                     *lasagne.layers.get_all_param_values(model.net['output']))
            np.savez('./' + DIR_TO_SAVE + '/disrim_modelWeights{:04d}.npz'.format(current_epoch),
                     *lasagne.layers.get_all_param_values(model.discriminator['prob']))
            predict(model=model, image_stimuli=validation_sample, numEpoch=current_epoch, pathOutputMaps=DIR_TO_SAVE)
        print 'Epoch:', current_epoch, ' train_loss->', (g_cost, d_cost, e_cost)

def train():
    """
    Train both generator and discriminator
    :return:
    """
    # Load data
    print 'Loading training data...'
    with open('../saliency-2016-lsun/validationSample240x320.pkl', 'rb') as f:
    # with open(TRAIN_DATA_DIR, 'rb') as f:
        train_data = pickle.load(f)
    print '-->done!'

    print 'Loading validation data...'
    with open('../saliency-2016-lsun/validationSample240x320.pkl', 'rb') as f:
    # with open(VALIDATION_DATA_DIR, 'rb') as f:
        validation_data = pickle.load(f)
    print '-->done!'

    # Choose a random sample to monitor the training
    num_random = random.choice(range(len(validation_data)))
    validation_sample = validation_data[num_random]
    cv2.imwrite('./' + DIR_TO_SAVE + '/validationRandomSaliencyGT.png', validation_sample.saliency.data)
    cv2.imwrite('./' + DIR_TO_SAVE + '/validationRandomImage.png', cv2.cvtColor(validation_sample.image.data,
                                                                                cv2.COLOR_RGB2BGR))

    # Create network

    if flag == 'salgan':
        model = ModelSALGAN(INPUT_SIZE[0], INPUT_SIZE[1])
        # Load a pre-trained model
        # load_weights(net=model.net['output'], path="nss/gen_", epochtoload=15)
        # load_weights(net=model.discriminator['prob'], path="test_dialted/disrim_", epochtoload=54)
        salgan_batch_iterator(model, train_data, validation_sample.image.data)

    elif flag == 'bce':
        model = ModelBCE(INPUT_SIZE[0], INPUT_SIZE[1])
        # Load a pre-trained model
        # load_weights(net=model.net['output'], path='test/gen_', epochtoload=15)
        bce_batch_iterator(model, train_data, validation_sample.image.data)
    else:
        print "Invalid input argument."
if __name__ == "__main__":
    train()


text:
jQuery(document).ready(function($) {
 	// hides as soon as the DOM is ready
	$('div.v-option-body').hide();
 	// shows on clicking the noted link
	$('h3').click(function() {
		$(this).toggleClass("open");
		$(this).next("div").slideToggle('1000');
		return false;
	});
});

function toggleColorpicker (link, id, toggledir, opentext, closetext) {
	jQuery('.colorpicker_container').hide();

	if (toggledir == "open") {
		jQuery('#'+id+'_colorpicker').show();
		jQuery(link).replaceWith(''+closetext+'');
	} else {
		jQuery(link).replaceWith(''+opentext+'');
	}
}


text:
// This is ExFat, an exFAT accessor written in pure C#
// Released under MIT license
// https://github.com/picrap/ExFat

namespace ExFat.DiscUtils.Environment
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Security.Principal;
    using global::DiscUtils.Vhdx;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    internal class TestEnvironment : IDisposable
    {
        protected string VhdxPath;
        protected Disk Disk;

        protected TestEnvironment()
        {
        }

        private static bool IsElevated
        {
            get
            {
                var id = WindowsIdentity.GetCurrent();
                return id.Owner != id.User;
            }
        }

        public virtual void Dispose()
        {
            Disk?.Dispose();
            // a check when required
            if (VhdxPath != null && File.Exists(VhdxPath))
            {
                try
                {
                    if (IsElevated)
                    {
                        var t = CheckDisk();
                        if (!t.Item1)
                            Assert.Fail("VHDX filesystem is found corrupted by CHKDSK: " + t.Item2);
                    }
                    else
                        Assert.Inconclusive("Not elevated");
                }
                finally
                {
                    File.Delete(VhdxPath);
                }
            }
        }

        private Tuple<bool, string> CheckDisk()
        {
            var previousDrives = DriveInfo.GetDrives();
            RunDiskPart("attach", VhdxPath);
            var newDrives = DriveInfo.GetDrives();
            var mountedDrive = newDrives.FirstOrDefault(d => previousDrives.All(p => p.Name != d.Name));
            bool success = true;
            string checkResult = null;
            if (mountedDrive != null)
            {
                var result = ProcessUtility.Run("chkdsk", mountedDrive.Name.TrimEnd('\\'));
                success = result.Item1 == 0;
                checkResult = result.Item2;
            }
            RunDiskPart("detach", VhdxPath);
            return Tuple.Create(success, checkResult);
        }

        private static void RunDiskPart(string action, string vdiskPath)
        {
            var scriptPath = Path.GetTempFileName();
            using (var scriptStream = File.CreateText(scriptPath))
            {
                scriptStream.WriteLine($"select vdisk file=\"{vdiskPath}\"");
                scriptStream.WriteLine($"{action} vdisk");
            }
            ProcessUtility.Run("diskpart", $"/s {scriptPath}");
            File.Delete(scriptPath);
        }
    }
}


text:
MultisigAddressEntry::MultisigAddressEntry(QWidget *parent) : QFrame(parent), ui(new Ui::MultisigAddressEntry), model(0)
{
    ui->setupUi(this);
    GUIUtil::setupAddressWidget(ui->address, this);
}

MultisigAddressEntry::~MultisigAddressEntry()
{
    delete ui;
}

void MultisigAddressEntry::setModel(WalletModel *model)
{
    this->model = model;
    clear();
}

void MultisigAddressEntry::clear()
{
    ui->pubkey->clear();
    ui->address->clear();
    ui->label->clear();
    ui->pubkey->setFocus();
}

bool MultisigAddressEntry::validate()
{
    return !ui->pubkey->text().isEmpty();
}

QString MultisigAddressEntry::getPubkey()
{
    return ui->pubkey->text();
}

void MultisigAddressEntry::setRemoveEnabled(bool enabled)
{
    ui->deleteButton->setEnabled(enabled);
}

void MultisigAddressEntry::on_pasteButton_clicked()
{
    ui->address->setText(QApplication::clipboard()->text());
}

void MultisigAddressEntry::on_deleteButton_clicked()
{
    Q_EMIT removeEntry(this);
}

void MultisigAddressEntry::on_addressBookButton_clicked()
{
    if(!model)
        return;

    AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
    dlg.setModel(model->getAddressTableModel());
    if(dlg.exec())
    {
        ui->address->setText(dlg.getReturnValue());
    }
}

void MultisigAddressEntry::on_pubkey_textChanged(const QString &pubkey)
{
    // Compute address from public key
    std::vector<unsigned char> vchPubKey(ParseHex(pubkey.toStdString()));
    CPubKey pkey(vchPubKey);
    std::string address = EncodeDestination(pkey.GetID());
    ui->address->setText(address.c_str());

    if(!model)
        return;

    // Get label of address
    QString associatedLabel = model->getAddressTableModel()->labelForAddress(address.c_str());
    if(!associatedLabel.isEmpty())
        ui->label->setText(associatedLabel);
}

void MultisigAddressEntry::on_address_textChanged(const QString &address)
{
    if(!model)
        return;

    // Get public key of address
    CTxDestination dest = DecodeDestination(address.toStdString());
    const CKeyID *keyID = boost::get<CKeyID>(&dest);
    if(!keyID)
    {
        CPubKey vchPubKey;
        model->getPubKey(*keyID, vchPubKey);
        std::string pubkey = HexStr(vchPubKey);
        if(!pubkey.empty())
            ui->pubkey->setText(pubkey.c_str());
    }

    // Get label of address
    QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
    if(!associatedLabel.isEmpty())
        ui->label->setText(associatedLabel);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
<?asciidoc-toc?>
<?asciidoc-numbered?>
<refentry lang="en">
<refmeta>
<refentrytitle>unicharambigs</refentrytitle>
<manvolnum>5</manvolnum>
<refmiscinfo class="source"> </refmiscinfo>
<refmiscinfo class="manual"> </refmiscinfo>
</refmeta>
<refnamediv>
    <refname>unicharambigs</refname>
    <refpurpose>Tesseract unicharset ambiguities</refpurpose>
</refnamediv>
<refsect1 id="_description">
<title>DESCRIPTION</title>
<simpara>The unicharset file is used by Tesseract to represent possible
ambiguities between characters, or groups of characters.</simpara>
<simpara>The file contains a number of lines, laid out as follow:</simpara>
<literallayout class="monospaced">[num] <TAB> [char(s)] <TAB> [num] <TAB> [char(s)] <TAB> [num]</literallayout>
<informaltable tabstyle="horizontal" frame="none" colsep="0" rowsep="0"><tgroup cols="2"><colspec colwidth="15*"/><colspec colwidth="85*"/><tbody valign="top">
<row>
<entry>
<simpara>
Field one
</simpara>
</entry>
<entry>
<simpara>
the number of characters contained in field two
</simpara>
</entry>
</row>
<row>
<entry>
<simpara>
Field two
</simpara>
</entry>
<entry>
<simpara>
the character sequence to be replaced
</simpara>
</entry>
</row>
<row>
<entry>
<simpara>
Field three
</simpara>
</entry>
<entry>
<simpara>
the number of characters contained in field four
</simpara>
</entry>
</row>
<row>
<entry>
<simpara>
Field four
</simpara>
</entry>
<entry>
<simpara>
the character sequence used to replace field two
</simpara>
</entry>
</row>
<row>
<entry>
<simpara>
Field five
</simpara>
</entry>
<entry>
<simpara>
contains either 1 or 0. 1 denotes a mandatory
replacement, 0 denotes an optional replacement.
</simpara>
</entry>
</row>
</tbody></tgroup></informaltable>
<simpara>Characters appearing in fields two and four should appear in
unicharset. The numbers in fields one and three refer to the
number of unichars (not bytes).</simpara>
</refsect1>
<refsect1 id="_example">
<title>EXAMPLE</title>
<literallayout class="monospaced">2       ' '     1       "     1
1       m       2       r n   0
3       i i i   1       m     0</literallayout>
<simpara>In this example, all instances of the <emphasis>2</emphasis> character sequence <emphasis>'</emphasis>' will
<emphasis role="strong">always</emphasis> be replaced by the <emphasis>1</emphasis> character sequence <emphasis>"</emphasis>; a <emphasis>1</emphasis> character
sequence <emphasis>m</emphasis> <emphasis role="strong">may</emphasis> be replaced by the <emphasis>2</emphasis> character sequence <emphasis>rn</emphasis>, and
the <emphasis>3</emphasis> character sequence <emphasis role="strong">may</emphasis> be replaced by the <emphasis>1</emphasis> character
sequence <emphasis>m</emphasis>.</simpara>
</refsect1>
<refsect1 id="_history">
<title>HISTORY</title>
<simpara>The unicharambigs file first appeared in Tesseract 3.00; prior to that, a
similar format, called DangAmbigs (<emphasis>dangerous ambiguities</emphasis>) was used: the
format was almost identical, except only mandatory replacements could be
specified, and field 5 was absent.</simpara>
</refsect1>
<refsect1 id="_bugs">
<title>BUGS</title>
<simpara>This is a documentation "bug": it’s not currently clear what should be done
in the case of ligatures (such as <emphasis>fi</emphasis>) which may also appear as regular
letters in the unicharset.</simpara>
</refsect1>
<refsect1 id="_see_also">
<title>SEE ALSO</title>
<simpara>tesseract(1), unicharset(5)</simpara>
</refsect1>
</refentry>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software
	Foundation (ASF) under one or more contributor license agreements. See the
	NOTICE file distributed with this work for additional information regarding
	copyright ownership. The ASF licenses this file to You under the Apache License,
	Version 2.0 (the "License"); you may not use this file except in compliance
	with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software distributed
	under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
	OR CONDITIONS OF ANY KIND, either express or implied. See the License for
  the specific language governing permissions and limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.metron</groupId>
        <artifactId>metron-indexing</artifactId>
        <version>0.7.2</version>
    </parent>
    <artifactId>metron-indexing-storm</artifactId>
    <name>metron-indexing-storm</name>
    <description>Components common to Storm</description>
    <url>https://metron.apache.org/</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <commons.config.version>1.10</commons.config.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.metron</groupId>
            <artifactId>metron-indexing-common</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.metron</groupId>
            <artifactId>metron-writer-storm</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.metron</groupId>
            <artifactId>metron-storm-kafka</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.metron</groupId>
            <artifactId>metron-integration-test</artifactId>
            <version>${project.parent.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>servlet-api</artifactId>
                    <groupId>javax.servlet</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>log4j-over-slf4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.netty</groupId>
                    <artifactId>netty</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.netty</groupId>
                    <artifactId>netty-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.metron</groupId>
            <artifactId>metron-common</artifactId>
            <version>${project.parent.version}</version>
            <type>test-jar</type>
            <exclusions>
                <exclusion>
                    <groupId>io.netty</groupId>
                    <artifactId>netty</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>${global_kafka_version}</version>
            <classifier>test</classifier>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>${global_jar_version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptor>src/main/assembly/assembly.xml</descriptor>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id> <!-- this is used for inheritance merges -->
                        <phase>package</phase> <!-- bind to the packaging phase -->
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>