text:
import React from 'react';
import _ from 'lodash';

import SectionHeader from '../components/section-header';
import token from 'otkit-shadows/token.common';

const Shadows = () => {
  var tokens = _.toPairsIn(token);

  tokens = tokens.map((token, index) => {
    return (

        {_.kebabCase(token[0])}: {token[1]}

    );
  });
  return (

      <SectionHeader text="Shadows" />
      {tokens}

  );
};

export default Shadows;


text:
package org.apache.maven.archiva.web.startup;

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

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.archiva.configuration.ArchivaConfiguration;

/**
 * ArchivaVersion
 *
 * @version $Id$
 */
public class ArchivaVersion
{
    private static String version = null;

    private ArchivaVersion()
    {
    }

    public static String determineVersion(  )
    {
        if ( version != null )
        {
            return version;
        }

        InputStream is = ArchivaConfiguration.class.getResourceAsStream( "/META-INF/maven/org.apache.archiva/archiva-configuration/pom.properties" );

        if ( is != null )
        {
            try
            {
                Properties props = new Properties();
                props.load( is );
                String version = props.getProperty( "version" );
                if ( StringUtils.isNotBlank( version ) )
                {
                    ArchivaVersion.version = version;
                    return version;
                }
            }
            catch ( IOException e )
            {
                /* do nothing */
            }
            finally
            {
                IOUtils.closeQuietly( is );
            }
        }

        ArchivaVersion.version = "";
        return version;
    }

    public static String getVersion()
    {
        return version;
    }
}

redpajama_set_name: RedPajamaGithub


text:
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.http import HttpResponse
import generator

def mainpage(request):

    text_list = ["just arbitrary text", "a lil something something", "wut", "...... ... ...", "hopefully this text will be displayed properly.", "hopefulz"] * 2
    tree_items = []

    for words in text_list:
        tree_items.append({'text':words,})

    #we put the ids of images yet to be chosen in the page.
    return render_to_response('main.html', {'images': [1, 2, 3, 4, 5, 6, 7, 8], 'treeitems':tree_items,}, context_instance=RequestContext(request))

def get_image(request):
    #generating a random genome
    genome = generator.generate_new_genome()

    return HttpResponse(generator.generate_image(genome), content_type='image/svg+xml')


text:
<?xml version="1.0" encoding="UTF-8" ?>
<pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel" version="12.1.3.10.8" id="tester_jspPageDef"
                Package="com.redheap.multiaction.pageDefs">
  <parameters/>
  <executables>
    <variableIterator id="variables"/>
    <iterator Binds="root" RangeSize="25" DataControl="MyDataControl" id="MyDataControlIterator"/>
    <accessorIterator MasterBinding="MyDataControlIterator" Binds="employees" RangeSize="25" DataControl="MyDataControl"
                      BeanClass="com.redheap.multiaction.Employee" id="employeesIterator"/>
  </executables>
  <bindings>
    <action IterBinding="employeesIterator" id="Delete" RequiresUpdateModel="false" Action="removeCurrentRow"/>
  </bindings>
</pageDefinition>


text:
#ifndef SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_SESSION_OBSERVER_H_
#define SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_SESSION_OBSERVER_H_

#include <gmock/gmock.h>
#include <list>
#include <string>
#include "protocol_handler/session_observer.h"
#include "transport_manager/common.h"

namespace test {
namespace components {
namespace protocol_handler_test {
/*
 * MOCK implementation of ::protocol_handler::SessionObserver interface
 */
class MockSessionObserver : public ::protocol_handler::SessionObserver {
 public:
  MOCK_METHOD5(OnSessionStartedCallback,
               void(const transport_manager::ConnectionUID connection_handle,
                    const uint8_t sessionId,
                    const protocol_handler::ServiceType& service_type,
                    const bool is_protected,
                    const BsonObject* params));
  MOCK_METHOD4(
      OnSessionEndedCallback,
      uint32_t(const transport_manager::ConnectionUID connection_handle,
               const uint8_t sessionId,
               const uint32_t& hashCode,
               const protocol_handler::ServiceType& service_type));
  MOCK_METHOD4(
      OnSessionEndedCallback,
      uint32_t(const transport_manager::ConnectionUID connection_handle,
               const uint8_t sessionId,
               uint32_t* hashCode,
               const protocol_handler::ServiceType& service_type));
  MOCK_METHOD5(
      OnSessionEndedCallback,
      uint32_t(const transport_manager::ConnectionUID connection_handle,
               const uint8_t sessionId,
               const uint32_t& hashCode,
               const protocol_handler::ServiceType& service_type,
               std::string* err_reason));
  MOCK_METHOD5(
      OnSessionEndedCallback,
      uint32_t(const transport_manager::ConnectionUID connection_handle,
               const uint8_t sessionId,
               uint32_t* hashCode,
               const protocol_handler::ServiceType& service_type,
               std::string* err_reason));
  MOCK_METHOD1(OnApplicationFloodCallBack,
               void(const uint32_t& connection_key));
  MOCK_METHOD1(OnMalformedMessageCallback,
               void(const uint32_t& connection_key));
  MOCK_METHOD1(OnFinalMessageCallback, void(const uint32_t& connection_key));
  MOCK_CONST_METHOD1(
      TransportTypeProfileStringFromConnHandle,
      const std::string(transport_manager::ConnectionUID connection_handle));
  MOCK_CONST_METHOD1(
      TransportTypeProfileStringFromDeviceHandle,
      const std::string(transport_manager::DeviceHandle device_handle));
  MOCK_CONST_METHOD2(
      KeyFromPair,
      uint32_t(transport_manager::ConnectionUID connection_handle,
               uint8_t session_id));
  MOCK_CONST_METHOD3(PairFromKey,
                     void(uint32_t key,
                          transport_manager::ConnectionUID* connection_handle,
                          uint8_t* sessionId));
  MOCK_CONST_METHOD4(GetDataOnSessionKey,
                     int32_t(uint32_t key,
                             uint32_t* app_id,
                             std::list<int32_t>* sessions_list,
                             transport_manager::DeviceHandle* device_id));

  MOCK_CONST_METHOD5(GetDataOnDeviceID,
                     int32_t(transport_manager::DeviceHandle device_handle,
                             std::string* device_name,
                             std::list<uint32_t>* applications_list,
                             std::string* mac_address,
                             std::string* connection_type));

  MOCK_CONST_METHOD2(IsHeartBeatSupported,
                     bool(transport_manager::ConnectionUID connection_handle,
                          uint8_t session_id));
  MOCK_CONST_METHOD3(ProtocolVersionUsed,
                     bool(uint32_t connection_id,
                          uint8_t session_id,
                          uint8_t& protocol_version));
  MOCK_CONST_METHOD3(ProtocolVersionUsed,
                     bool(uint32_t connection_id,
                          uint8_t session_id,
                          utils::SemanticVersion& full_protocol_version));
  MOCK_CONST_METHOD2(SessionServiceExists,
                     bool(const uint32_t connection_key,
                          const protocol_handler::ServiceType& service_type));

#ifdef ENABLE_SECURITY
  MOCK_METHOD2(SetSSLContext,
               int(const uint32_t& key, security_manager::SSLContext* context));
  MOCK_METHOD2(GetSSLContext,
               security_manager::SSLContext*(
                   const uint32_t& key,
                   const protocol_handler::ServiceType& service_type));
  MOCK_METHOD2(SetProtectionFlag,
               void(const uint32_t& key,
                    const protocol_handler::ServiceType& service_type));
  MOCK_CONST_METHOD1(
      GetHandshakeContext,
      security_manager::SSLContext::HandshakeContext(uint32_t key));
#endif  // ENABLE_SECURITY
};
}  // namespace protocol_handler_test
}  // namespace components
}  // namespace test
#endif  // SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_SESSION_OBSERVER_H_


text:
require "main/import"
require "berg/matcher"

module Main
  module Operations
    module Projects
      class CheckPublicationState
        include Main::Import["persistence.repositories.projects"]
        include Berg::Matcher

        def call(slug)
          project = projects.by_slug(slug)

          if project && project.status == "published"
            Dry::Monads::Right(project)
          else
            Dry::Monads::Left("This project has not yet been published.")
          end
        end
      end
    end
  end
end


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

#import "NNApriori.h"

@interface NNApriori (PrivateAPI)

+ (void)filterItemsets:(NSMutableDictionary*)itemsets minFreq:(NSUInteger)minFreq;
+ (NSMutableDictionary*)countOccurences:(NSSet*)itemsets tagsets:(NSArray*)tagsets;
+ (NSMutableSet*)generateCandidateSetFromFrequentItems:(NSSet*)frequentItems forLength:(NSUInteger)k;
+ (NSArray*)generateAssociationRulesForItemset:(NSArray*)itemset minConfidence:(CGFloat)minConfidence;
+ (BOOL)nextMask:(NSMutableArray*)mask;
+ (NSArray*)associationRules:(NSArray*)frequentItemsets minConfidence:(CGFloat)minConfidence;
+ (NSUInteger)support:(NSArray*)itemset;

@end

@implementation NNApriori

/**
 * Converts tag sets to sets of tag names, then calls the real method
 */
+ (NSArray*)frequentItemsetsForTagSets:(NSArray*)tagsets minFreq:(NSUInteger)minFreq
{
	NSMutableArray *tagnameSets = [NSMutableArray arrayWithCapacity:[tagsets count]];

	for (NSArray *tagset in tagsets)
	{
		NSArray *tagnameSet = [[NNTagging tagging] tagNamesForTags:tagset];
		[tagnameSets addObject:tagnameSet];
	}

	return [NNApriori frequentItemsetsForTagnameSets:tagnameSets minFreq:minFreq];
}

/**
 * Returns an array of itemsets that occur in the given transactions with at least the
 * specified frequency
 */
+ (NSArray*)frequentItemsetsForTagnameSets:(NSArray*)tagnameSets minFreq:(NSUInteger)minFreq
{
	NSMutableDictionary *itemsets = [NSMutableDictionary dictionary];
	for (NSSet *tagset in tagnameSets)
	{
		for (NSString *tag in tagset)
		{
			NSMutableArray *tagSingleton = [NSMutableArray arrayWithObject:tag];
			NSNumber *frequency = [itemsets objectForKey:tagSingleton];
			if (frequency == nil)
				[itemsets setObject:[NSNumber numberWithInteger:1] forKey:tagSingleton];
			else
				[itemsets setObject:[NSNumber numberWithInteger:[frequency integerValue]+1] forKey:tagSingleton];
		}
	}
	[NNApriori filterItemsets:itemsets minFreq:minFreq];

	NSMutableDictionary *frequentItemsets = [NSMutableDictionary dictionary];
	NSMutableDictionary *generatedItemsets = itemsets;

	NSUInteger k = 1;
	while ([generatedItemsets count] > 0)
	{
		NSSet *frequentItemset = [NSSet setWithArray:[generatedItemsets allKeys]];
		NSMutableSet *joinedItemsets = [NNApriori generateCandidateSetFromFrequentItems:frequentItemset forLength:++k];
		generatedItemsets = [NNApriori countOccurences:joinedItemsets tagsets:tagnameSets];
		[NNApriori filterItemsets:generatedItemsets minFreq:minFreq];
		[frequentItemsets addEntriesFromDictionary:generatedItemsets];
	}

	return [frequentItemsets allKeys];
}

/**
 * Removes all itemsets which don't satisfy the minimum required frequency
 */
+ (void)filterItemsets:(NSMutableDictionary*)itemsets minFreq:(NSUInteger)minFreq
{
	NSMutableArray *filteredItems = [NSMutableArray array];
	for (NSMutableArray *tagNames in itemsets)
	{
		NSNumber *frequency = [itemsets objectForKey:tagNames];
			if ([frequency unsignedIntegerValue] < minFreq)
				[filteredItems addObject:tagNames];
	}
	[itemsets removeObjectsForKeys:filteredItems];
}

/**
 * Takes the given frequentItems (of length k-1) and generates
 * a candidate set by joining them
 */
+ (NSMutableSet*)generateCandidateSetFromFrequentItems:(NSSet*)frequentItems forLength:(NSUInteger)k
{
	NSMutableSet *candidates = [NSMutableSet set];

	for (NSArray *item in frequentItems)
	{
		for (NSArray *innerItem in frequentItems)
		{
			// check for matching prefix
			BOOL matching = YES;

			for (NSUInteger i=0;i<k-2;i++)
			{
				if (![[item objectAtIndex:i] isEqualToString:[innerItem objectAtIndex:i]])
				{
					matching = NO;
					break;
				}
			}

			// if the prefix matches, create candidate if item[k-2] < innerItem[k-2]
			if (matching)
			{
				NSString *lastItemObject = [item objectAtIndex:k-2];
				NSString *lastInnerItemObject = [innerItem objectAtIndex:k-2];
				NSComparisonResult result = [lastItemObject compare:lastInnerItemObject];

				if (result == NSOrderedAscending)
				{
					NSMutableArray *candidate = [NSMutableArray array];

					for (NSUInteger i=0;i<k-2;i++)
						[candidate addObject:[item objectAtIndex:i]];

					// add differing items
					[candidate addObject:lastItemObject];
					[candidate addObject:lastInnerItemObject];

					// add to candidates
					[candidates addObject:candidate];
				}
			}
		}
	}

	return candidates;
}

/**
 * Counts the number of occurences of the specified itemsets in the tagsets and returns
 * a hashmap that maps each of the itemsets to its occurence count
 */
+ (NSMutableDictionary*)countOccurences:(NSSet*)itemsets tagsets:(NSArray*)tagsets
{
	NSMutableDictionary *itemsetCounts = [NSMutableDictionary dictionary];

	for (NSArray *tagset in tagsets)
	{
		for (NSArray *itemset in itemsets)
		{
			BOOL tagsetContainsItems = YES;
			for (NSString *tag in itemset)
			{
				if (![tagset containsObject:tag])
				{
					tagsetContainsItems = NO;
					break;
				}
			}

			if (tagsetContainsItems)
			{
				NSNumber *frequency = [itemsetCounts objectForKey:itemset];
				if (frequency == nil)
					[itemsetCounts setObject:[NSNumber numberWithInteger:1] forKey:itemset];
				else
					[itemsetCounts setObject:[NSNumber numberWithInteger:[frequency integerValue]+1] forKey:itemset];
			}
		}
	}

	return itemsetCounts;
}

/**
 * Generates the array of association rules that satisfy the given confidence level for the specified array of
 * transactions (tagsets) of tags, considering all itemsets with at least the given frequency
 */
+ (NSArray*)associationRulesForTagSets:(NSArray*)tagsets minFreq:(NSUInteger)minFreq minConfidence:(CGFloat)minConfidence
{
	return [NNApriori associationRules:[NNApriori frequentItemsetsForTagSets:tagsets minFreq:minFreq] minConfidence:minConfidence];
}

/**
 * Generates the array of association rules that satisfy the given confidence level for the specified array of
 * transactions (tagsets) of tag names, considering all itemsets with at least the given frequency
 */
+ (NSArray*)associationRulesForTagnameSets:(NSArray*)tagsets minFreq:(NSUInteger)minFreq minConfidence:(CGFloat)minConfidence
{
	return [NNApriori associationRules:[NNApriori frequentItemsetsForTagnameSets:tagsets minFreq:minFreq] minConfidence:minConfidence];
}

/**
 * Returns association rules with at least the specified confidence from the given array
 * of frequent itemsets
 */
+ (NSArray*)associationRules:(NSArray*)frequentItemsets minConfidence:(CGFloat)minConfidence
{
	NSMutableArray *rules = [NSMutableArray array];
	for (NSArray *itemset in frequentItemsets)
		[rules addObjectsFromArray:[NNApriori generateAssociationRulesForItemset:itemset minConfidence:minConfidence]];
	return rules;
}

/**
 * Generates association rules for the specified itemset that possess at least the given
 * confidence value
 */
+ (NSArray*)generateAssociationRulesForItemset:(NSArray*)itemset minConfidence:(CGFloat)minConfidence
{
	NSMutableArray *rules = [NSMutableArray array];

	NSUInteger length = [itemset count];
	NSMutableArray *mask = [NSMutableArray array];
	for (NSUInteger i=0; i<length; i++)
		[mask addObject:[NSNumber numberWithBool:NO]];

	NSMutableDictionary *supportCache = [NSMutableDictionary dictionary];

	while ([NNApriori nextMask:mask])
	{
		// generate head and body
		NSMutableArray *body = [NSMutableArray array];
		NSMutableArray *head = [NSMutableArray array];

		for (NSUInteger i=0; i<[mask count]; i++)
		{
			if ([[mask objectAtIndex:i] boolValue])
				[body addObject:[itemset objectAtIndex:i]];
			else
				[head addObject:[itemset objectAtIndex:i]];
		}

		// handle special cases, i.e. empty head or emtpy body
		if ([body count] == 0 || [head count] == 0)
			continue;

		// calculate confidence of this would-be rule - use cached support values
		NSNumber *itemsetSupport = [supportCache objectForKey:itemset];
		if (itemsetSupport == nil)
		{
			NSUInteger iss = [NNApriori support:itemset];
			itemsetSupport = [NSNumber numberWithInt:iss];
			[supportCache setObject:itemsetSupport forKey:itemset];
		}

		NSNumber *bodySupport = [supportCache objectForKey:body];
		if (bodySupport == nil)
		{
			NSUInteger bs = [NNApriori support:body];
			bodySupport = [NSNumber numberWithInt:bs];
			[supportCache setObject:bodySupport forKey:body];
		}

		CGFloat confidence = [itemsetSupport floatValue]  / [bodySupport floatValue];
		if (confidence >= minConfidence)
		{
			// generate rule
			NNAssociationRule *rule = [NNAssociationRule ruleWithContent:body head:head];
			[rule setConfidence:confidence];
			[rules addObject:rule];
		}
	}
	return rules;
}

/**
 * Returns the support of the specified itemset
 */
+ (NSUInteger)support:(NSArray*)itemset
{
	return [[[NNTagging tagging] taggedObjectsForTags:[[NNTags sharedTags] tagsForNames:itemset]] count];
}

/**
 * Creates the next ('bit'-)mask, that is an array of boolean values,
 * by modifying the specified array
 */
+ (BOOL)nextMask:(NSMutableArray*)mask
{
	NSUInteger i;
	for (i=0; (i<[mask count] && [[mask objectAtIndex:i] boolValue]); i++)
		[mask replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];

	if (i < [mask count])
	{
		[mask replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:YES]];
		return YES;
	}

	return NO;
}

@end


text:
package types

import "time"

type BaseEntity struct {
	CreatedAt  RFC3339Time `json:"created_at" datastore:"-" siren:"property"`
	ModifiedAt RFC3339Time `json:"modified_at" datastore:"-" siren:"property"`

	// appengine will not store RFC3339Time, we must store them as time.Time
	CreatedAtTime  time.Time `json:"-" datastore:"created_at"`
	ModifiedAtTime time.Time `json:"-" datastore:"modified_at"`
}

func (self *BaseEntity) SetCreatedAt(time time.Time) {
	self.CreatedAt = RFC3339Time(time)
	self.CreatedAtTime = time
}

func (self *BaseEntity) SetModifiedAt(time time.Time) {
	self.ModifiedAt = RFC3339Time(time)
	self.ModifiedAtTime = time
}

func (self *BaseEntity) SetTimes() {
	self.ModifiedAt = RFC3339Time(self.ModifiedAtTime)
	self.CreatedAt = RFC3339Time(self.CreatedAtTime)
}

type CreatedAt interface {
	SetCreatedAt(time time.Time)
}

type ModifiedAt interface {
	SetModifiedAt(time time.Time)
}

type CreatedAtModifiedAt interface {
	CreatedAt
	ModifiedAt
	SetTimes()
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mém. Acad. malgache 6: 14 (1928)

#### Original name
Leucoporus tricholoma var. madagascariensis Pat.

### Remarks
null


text:
; Copyright (c) 2008-2009, diamond
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;       * Redistributions of source code must retain the above copyright
;       notice, this list of conditions and the following disclaimer.
;       * Redistributions in binary form must reproduce the above copyright
;       notice, this list of conditions and the following disclaimer in the
;       documentation and/or other materials provided with the distribution.
;       * Neither the name of the <organization> nor the
;       names of its contributors may be used to endorse or promote products
;       derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY Alexey Teplov aka <Lrz> ''AS IS'' AND ANY
; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;*****************************************************************************

        org     0x7E00
; the KordOS FAT32 bootsector loads first cluster of this file to 0:7E00 and transfers control to here
; ss:bp = 0:7C00
; ds = 0
virtual at bp
                rb      3       ; BS_jmpBoot
                rb      8       ; BS_OEMName, ignored
                dw      ?       ; BPB_BytsPerSec
BPB_SecsPerClus db      ?
BPB_RsvdSecCnt  dw      ?
BPB_NumFATs     db      ?
BPB_RootEntCnt  dw      ?
                dw      ?       ; BPB_TotSec16
                db      ?       ; BPB_Media
                dw      ?       ; BPB_FATSz16 = 0 for FAT32
BPB_SecPerTrk   dw      ?
BPB_NumHeads    dw      ?
BPB_HiddSec     dd      ?
                dd      ?       ; BPB_TotSec32
BPB_FATSz32     dd      ?
BPB_ExtFlags    dw      ?
                dw      ?       ; BPB_FSVer
BPB_RootClus    dd      ?
filesize:
                dw      ?       ; BPB_FSInfo
                dw      ?       ; BPB_BkBootSec
                rb      12      ; BPB_Reserved
BS_DrvNum       db      ?
                db      ?       ; BS_Reserved1
                db      ?       ; BS_BootSig
                dd      ?       ; BS_VolID
;               rb      11      ; BS_VolLab
;               rb      5       ; BS_FilSysType, first 5 bytes
read_sectors32  dw      ?
read_sectors2   dw      ?
err_             dw      ?
noloader        dw      ?
cachelimit      dw      ?
fatcachehead    rw      2
fatcacheend     dw      ?
                rb      3       ; BS_FilSysType, last 3 bytes
curseg          dw      ?
num_sectors     dd      ?
cur_cluster     dd      ?
next_cluster    dd      ?
flags           dw      ?
cur_delta       dd      ?
end virtual

; procedures from boot sector
; LBA version
lba_read_sectors2 = 7CD6h
lba_err = 7CAAh
lba_noloader = 7CA7h    ; = lba_err - 3
; CHS version
chs_read_sectors2 = 7CD2h
chs_err = 7CA6h
chs_noloader = 7CA3h    ; = chs_err - 3

        push    eax cx          ; save our position on disk
; determine version of bootsector (LBA vs CHS)
        mov     [read_sectors2], chs_read_sectors2
        mov     bx, chs_err
        mov     [err_], bx
;       mov     [noloader], chs_noloader
        cmp     byte [bx], 0xE8         ; [chs_err] = 0xE8 for CHS version, 0x14 for LBA version
        jz      @f
        add     [read_sectors2], lba_read_sectors2 - chs_read_sectors2
        add     [err_], lba_err - chs_err
;       mov     [noloader], lba_noloader
@@:
        xor     bx, bx
; determine size of cache for folders
        int     12h             ; ax = size of available base memory in Kb
        sub     ax, 92000h / 1024
        jae     @f
nomem:
        mov     si, nomem_str
        jmp     [err_]
@@:
        shr     ax, 3
        mov     [cachelimit], ax        ; size of cache - 1
        mov     es, bx
; no folders in cache yet
        mov     di, foldcache_clus
        mov     cx, 8*4/2 + 1
        xor     ax, ax
        rep stosw
; bootsector code caches one FAT sector, [bp-14], in 6000:0000
; initialize our (more advanced) FAT caching from this
        mov     di, 8400h
        mov     cx, di
        lea     si, [fatcachehead]
        mov     [si], si                ; no sectors in cache:
        mov     [si+2], si              ; 'prev' & 'next' links point to self
        mov     [fatcacheend], di       ; first free item = 8400h
        stosw                   ; 'next cached sector' link
        stosw                   ; 'prev cached sector' link
        mov     eax, [bp-14]
        stosd                           ; first sector number in cache
        test    eax, eax
        js      @f
        mov     [si], cx                ; 'first cached sector' link = 8400h
        mov     [si+2], cx              ; 'next cached sector' link = 8400h
        mov     [fatcacheend], di       ; first free item = 8406h
@@:
; if cluster = sector, we need to read second part of our file
; (bootsector loads only first cluster of kordldr.f32)
        pop     cx eax          ; restore our position on disk
        cmp     cx, 1
        ja      kordldr_full
        sub     eax, [bp-10]
        inc     eax
        inc     eax             ; eax = first cluster of kordldr.f32
        call    get_next_cluster
        jc      @f
;       jmp     [noloader]
        mov     ax, [err_]
        sub     ax, 3
        jmp     ax
@@:
        dec     eax
        dec     eax
        push    0x800
        pop     es
        call    [read_sectors2]
kordldr_full:
; bootsector code has read some data of root directory to 8000:0000
; initialize our folder caching from this
        mov     eax, [BPB_RootClus]
        mov     [foldcache_clus], eax
        mov     cx, [curseg]
        mov     ax, 8000h
        sub     cx, ax          ; cx = size of data read in paragraphs (0x10 bytes)
        shr     cx, 1           ; cx = size of folder data read in entries (0x20 bytes)
        mov     [foldcache_size], cx
        shl     cx, 4
        push    ds
        mov     ds, ax
        push    0x9000
        pop     es
        xor     si, si
        xor     di, di
        rep movsw
        pop     ds
; ...continue loading...
        mov     di, secondary_loader_info
        call    load_file
        test    bx, bx
        mov     bx, [err_]
        jz      @f
        mov     si, aKernelNotFound
        jmp     bx
@@:
; for subsequent calls to callback function, hook error handler
; push hooked_err / ret
        mov     dword [bx], 0x68 + (hooked_err shl 8) + (0xC3 shl 24)
; set registers for secondary loader
        mov     ah, [bp-2]              ; drive id
        mov     al, 'f'
        btr     ax, 15
        jnc     @f
        mov     al, 'h'
@@:
        mov     bx, '32'
        mov     si, callback
        jmp     far [si+secondary_loader_info-callback]

nomem_str       db      'No memory',0

cluster2sector:
        sub     eax, 2
clustersz2sectorsz:
        movzx   ecx, [BPB_SecsPerClus]
        mul     ecx
        ret

get_next_cluster:
; in: eax = cluster
; out: if there is next cluster: CF=1, eax = next cluster
; out: if there is no next cluster: CF=0
        push    di bx
        push    ds
        push    ss
        pop     ds
        push    ax
        shr     eax, 7
; eax = FAT sector number; look in cache
        mov     di, 8400h
.cache_lookup:
        cmp     di, [fatcacheend]
        jae     .not_in_cache
        scasd
        scasd
        jnz     .cache_lookup
.in_cache:
        sub     di, 8
; delete this sector from the list
        push    si
        mov     si, [di]
        mov     bx, [di+2]
        mov     [si+2], bx
        mov     [bx], si
        pop     si
        jmp     @f
.not_in_cache:
; cache miss
; cache is full?
        mov     di, [fatcacheend]
        cmp     di, 8C00h
        jnz     .cache_not_full
; yes, delete the oldest entry
        mov     di, [fatcachehead]
        mov     bx, [di]
        mov     [fatcachehead], bx
        push    word [di+2]
        pop     word [bx+2]
        jmp     .cache_append
.cache_not_full:
; no, allocate new sector
        add     [fatcacheend], 8
.cache_append:
; read FAT
        mov     [di+4], eax
        push    es
        pushad
        lea     cx, [di + 0x10000 - 0x8400 + (0x6000 shr (9-3))]        ; +0x10000 - for FASM
        shl     cx, 9-3
        mov     es, cx
        xor     bx, bx
        mov     cx, 1
        add     eax, [bp-6]     ; FAT start
        sub     eax, [bp-10]
        call    [read_sectors2]
        popad
        pop     es
@@:
; add new sector to the end of list
        mov     bx, di
        xchg    bx, [fatcachehead+2]
        push    word [bx]
        pop     word [di]
        mov     [bx], di
        mov     [di+2], bx
; get requested item
        lea     ax, [di + 0x10000 - 0x8400 + (0x6000 shr (9-3))]
        pop     di
        and     di, 0x7F
        shl     di, 2
        shl     ax, 9-3
        mov     ds, ax
        and     byte [di+3], 0x0F
        mov     eax, [di]
        pop     ds
        pop     bx di
        ;and    eax, 0x0FFFFFFF
        cmp     eax, 0x0FFFFFF7
        ret

if $ > 0x8000
error 'get_next_cluster must fit in first sector of kordldr.f32!'
end if

load_file:
; in: ss:bp = 0:7C00
; in: ds:di -> information structure
;       dw:dw   address
;       dw      limit in 4Kb blocks (0x1000 bytes) (must be non-zero and not greater than 0x100)
;       ASCIIZ  name
; out: bx = status: bx=0 - ok, bx=1 - file is too big, only part of file was loaded, bx=2 - file not found
; out: dx:ax = file size (0xFFFFFFFF if file not found)
        mov     eax, [BPB_RootClus]     ; start from root directory
        or      dword [filesize], -1    ; initialize file size with invalid value
        lea     si, [di+6]
parse_dir_loop:
; convert name to FAT name
        push    di
        push    ax
        push    ss
        pop     es
; convert ASCIIZ filename to FAT name
filename equ bp
        mov     di, filename
        push    di
        mov     cx, 8+3
        mov     al, ' '
        rep stosb
        pop     di
        mov     cl, 8   ; 8 symbols per name
        mov     bl, 1
nameloop:
        lodsb
        test    al, al
        jz      namedone
        cmp     al, '/'
        jz      namedone
        cmp     al, '.'
        jz      namedot
        dec     cx
        js      badname
        cmp     al, 'a'
        jb      @f
        cmp     al, 'z'
        ja      @f
        sub     al, 'a'-'A'
@@:
        stosb
        jmp     nameloop
namedot:
        inc     bx
        jp      badname
        add     di, cx
        mov     cl, 3
        jmp     nameloop
badname:        ; do not make direct js/jp to notfound_pop:
                ; this generates long forms of conditional jumps and results in longer code
        jmp     notfound_pop
namedone:
; scan directory
        pop     ax      ; eax = cluster of directory
                        ; high word of eax is preserved by operations above
        push    ds
        push    si
; read a folder sector-by-sector and scan
; first, try to use the cache
        push    ss
        pop     ds
        mov     di, foldcache_mark
        xor     bx, bx
        mov     cx, [cachelimit]
@@:
        lea     si, [di+bx]
        mov     edx, dword [foldcache_clus+si-foldcache_mark+bx]
        cmp     edx, eax
        jz      cacheok
        test    edx, edx
        jz      cacheadd        ; the cache has place for new entry
        inc     bx
        inc     bx
        dec     cx
        jns     @b
; the folder is not present in the cache, so add it
; the cache is full; find the oldest entry and replace it with the new one
        mov     bx, -2
        mov     dx, [cachelimit]
@@:
        inc     bx
        inc     bx
        cmp     word [di+bx], dx        ; marks have values 0 through [cachelimit]
        jnz     @b
        lea     si, [di+bx]
cacheadd:
        or      word [di+bx], 0xFFFF    ; very big value, it will be changed soon
        and     [foldcache_size+di-foldcache_mark+bx], 0        ; no folder items yet
        mov     dword [foldcache_clus+si-foldcache_mark+bx], eax
cacheok:
; update cache marks
        mov     dx, [di+bx]
        mov     cx, [foldcache_size+di-foldcache_mark+bx]
        mov     di, [cachelimit]
        add     di, di
cacheupdate:
        cmp     [foldcache_mark+di], dx
        adc     [foldcache_mark+di], 0
        dec     di
        dec     di
        jns     cacheupdate
        and     [foldcache_mark+bx], 0
; done, bx contains (position in cache)*2
        ;mov    dx, bx
        ;shl    dx, 8           ; dx = (position in cache)*0x2000/0x10
        ;add    dx, 0x9000
        lea     dx, [bx + 0x90]
        xchg    dl, dh
        mov     ds, dx
        mov     si, filename    ; ss:si -> filename in FAT style
        call    scan_for_filename
        jz      lookup_done
; cache miss, read folder data from disk
        mov     bx, cx
        shr     bx, 4
        shl     cx, 5
        mov     di, cx          ; es:di -> free space in cache entry
; external loop: scan clusters
folder_next_cluster:
; internal loop: scan sectors in cluster
        push    eax
        call    cluster2sector
folder_next_sector:
; skip first bx sectors
        dec     bx
        jns     folder_skip_sector
        push    cx
        push    es di
        push    0x8000
        pop     es
        xor     bx, bx
        mov     cx, 1
        push    es
        push    eax
        call    [read_sectors2]
        pop     eax
; copy data to the cache...
        pop     ds
        pop     di es
        cmp     di, 0x2000      ; ...if there is free space, of course
        jae     @f
        pusha
        mov     cx, 0x100
        xor     si, si
        rep movsw
        mov     di, es
        shr     di, 8
        add     [ss:foldcache_size+di-0x90], 0x10       ; 0x10 new entries in the cache
        popa
@@:
        push    es
        mov     cl, 0x10        ; ch=0 at this point
        call    scan_for_filename
        pop     es
        pop     cx
        jz      lookup_done_pop
folder_skip_sector:
        inc     eax
        loop    folder_next_sector
        pop     eax     ; eax = current cluster
        call    get_next_cluster
        jc      folder_next_cluster
        stc
        push    eax
lookup_done_pop:
        pop     eax
lookup_done:
        pop     si
; CF=1 <=> failed
        jnc     found
        pop     ds
notfound:
        pop     di
notfound2:
        mov     bx, 2   ; file not found
        mov     ax, 0xFFFF
        mov     dx, ax  ; invalid file size
        ret
notfound_pop:
        pop     ax
        jmp     notfound
found:
        mov     eax, [di+20-2]
        mov     edx, [di+28]
        mov     ax, [di+26]     ; get cluster
        test    byte [di+11], 10h       ; directory?
        pop     ds
        pop     di
        jz      regular_file
        cmp     byte [si-1], 0
        jz      notfound2       ; don't read directories as regular files
; ok, we have found a directory and the caller requested a file into it
        jmp     parse_dir_loop  ; restart with new cluster in ax
regular_file:
        cmp     byte [si-1], 0
        jnz     notfound2       ; file does not contain another files
; ok, we have found a regular file and the caller requested it
; save file size
        mov     [filesize], edx
        mov     si, [di+4]      ; [ds:di+4] = limit in 4K blocks
        shl     si, 3
        push    si
        les     bx, [di]        ; es:bx -> buffer
clusloop:
; eax = first cluster, top of stack contains limit in sectors
        mov     esi, eax        ; remember current cluster
        xor     ecx, ecx        ; ecx will contain number of consecutive clusters
        mov     [cur_delta], ecx
        mov     edi, eax
clusfind:
        inc     edi
        inc     ecx
        call    get_next_cluster
        jnc     clusread
        cmp     eax, edi
        jz      clusfind
        stc
clusread:
        pop     di      ; limit in sectors
        movzx   edi, di
        push    eax     ; save next cluster
        pushf           ; save flags
; read cx clusters, starting from si
; calculate number of sectors
        xchg    eax, ecx
        call    clustersz2sectorsz
        mov     [num_sectors], eax
        jmp     @f
continue_load_file:
        les     bx, [di]        ; es:bx -> buffer
        movzx   edi, word [di+4]        ; di = limit in 4K blocks
        shl     di, 3   ; now di = limit in sectors
        mov     eax, [num_sectors]
        mov     esi, [cur_cluster]
        push    [next_cluster]
        push    [flags]
        test    eax, eax
        jz      nextclus
@@:
; eax = number of sectors; compare with limit
        cmp     eax, edi
        seta    dl
        push    dx      ; limit was exceeded?
        jbe     @f
        mov     eax, edi
@@:
        sub     di, ax  ; calculate new limit
        sub     [num_sectors], eax
        mov     [cur_cluster], esi
; calculate starting sector
        push    ax
        xchg    eax, esi
        call    cluster2sector
        pop     cx
        add     eax, [cur_delta]
        add     [cur_delta], ecx
; read
        call    [read_sectors2]
        pop     dx
; next cluster?
nextclus:
        popf
        pop     eax
        mov     [next_cluster], eax
        pushf
        pop     [flags]
        jnc     @f      ; no next cluster => return
        mov     dl, 1   ; dh=0 in any case
        test    di, di
        jz      @f      ; if there is next cluster but current limit is 0 => return: limit exceeded
        push    di
        jmp     clusloop        ; all is ok, continue
hooked_err:
        mov     sp, 7C00h-14-2  ; restore stack
        mov     dx, 3           ; return: read error
@@:
        mov     bx, dx
        mov     ax, [filesize]
        mov     dx, [filesize+2]
        ret

scan_for_filename:
; in: ss:si -> 11-bytes FAT name
; in: ds:0 -> part of directory data
; in: cx = number of entries
; in: bh = 0
; out: if found: CF=0, ZF=1, es:di -> directory entry
; out: if not found, but continue required: CF=1 and ZF=0
; out: if not found and zero item reached: CF=1 and ZF=1
        push    ds
        pop     es
        xor     di, di
        push    cx
        jcxz    snoent
sloop:
        cmp     byte [di], bh
        jz      snotfound
        test    byte [di+11], 8         ; volume label?
        jnz     scont                   ; ignore volume labels
        pusha
        mov     cx, 11
        repz cmps byte [ss:si], byte [es:di]
        popa
        jz      sdone
scont:
        add     di, 0x20
        loop    sloop
snoent:
        inc     cx      ; clear ZF flag
snotfound:
        stc
sdone:
        pop     cx
lrdret:
        ret

; Callback function for secondary loader
callback:
; in: ax = function number; only functions 1 and 2 are defined for now
; save caller's stack
        mov     dx, ss
        mov     cx, sp
; set our stack (required because we need ss=0)
        xor     si, si
        mov     ss, si
        mov     sp, 7C00h-10
        mov     bp, 7C00h
        push    dx
        push    cx
; call our function
        stc     ; unsupported function
        dec     ax
        jz      callback_readfile
        dec     ax
        jnz     callback_ret
; function 2: continue loading file
; can be called only after function 1 returned value bx=1 (only part of file was loaded)
; in: ds:di -> information structure
;       dw:dw   address
;       dw      limit in 4Kb blocks (0x1000 bytes) (must be non-zero and not greater than 0x100)
; out: bx=0 - ok, bx=1 - still only part of file was loaded, bx=3 - read error
; out: dx:ax = file size
        call    continue_load_file
        jmp     callback_ret_succ
callback_readfile:
; function 1: read file
; in: ds:di -> information structure
;       dw:dw   address
;       dw      limit in 4Kb blocks (0x1000 bytes) (must be non-zero and not greater than 0x100)
;       ASCIIZ  name
; out: bx=0 - ok, bx=1 - file is too big, only part of file was loaded, bx=2 - file not found, bx=3 - read error
; out: dx:ax = file size (0xFFFFFFFF if file was not found)
        call    load_file
callback_ret_succ:
        clc     ; function is supported
callback_ret:
; restore caller's stack
        pop     cx
        pop     ss
        mov     sp, cx
; return to caller
        retf

secondary_loader_info:
        dw      0, 0x1000
        dw      0x30000 / 0x1000
        db      'kord/loader',0
aKernelNotFound db      'Fatal error: cannot load the secondary loader',0

;if $ > 0x8200
;error 'total size of kordldr.f32 must not exceed 1024 bytes!'
;end if

;foldcache_clus dd      0,0,0,0,0,0,0,0 ; start with no folders in cache
;foldcache_mark dw      0
;               rw      7
;foldcache_size rw      8
foldcache_clus  rd      8
foldcache_mark  rw      8
foldcache_size  rw      8


text:
{% extends "base2.html" %}
{% block title %}Reset Password{% endblock %}
{% block head %}
{{ super() }}

{% endblock %}

{% block content %}
{{ super() }}

Reset Password

                <form method="post" name="login">
                    {{form.hidden_tag()}}

                        Email
                        {{form.email (size=64)}}

                    {% for error in form.errors.email %}

{{error}}

                    {% endfor %}

                        Password
                        {{form.password (size=64)}}

                    {% for error in form.errors.password %}

{{error}}

                    {% endfor %}

                        Password confirmation
                        {{form.password2 (size=64)}}

                    {% for error in form.errors.password2 %}

{{error}}

                    {% endfor %}

                        <button type="submit" class="waves-effect waves-light btn">Reset password</button>

                </form>

{% endblock %}

{% block scripts %}
{{ super() }}
{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace Uheer.Services.Exceptions
{
    /// <summary>
    /// Thrown when a user already has an active channel and asks to open a second one.
    /// </summary>
    public class OwnerAlreadyHasAnActiveChannelException : ApplicationException
    {
        // Summary:
        //     Initializes a new instance of the System.OwnerAlreadyHasAnActiveChannelException class.
        public OwnerAlreadyHasAnActiveChannelException() { }
        //
        // Summary:
        //     Initializes a new instance of the System.OwnerAlreadyHasAnActiveChannelException class with
        //     a specified error message.
        //
        // Parameters:
        //   message:
        //     A message that describes the error.
        public OwnerAlreadyHasAnActiveChannelException(string message) : base(message) { }
        //
        // Summary:
        //     Initializes a new instance of the System.OwnerAlreadyHasAnActiveChannelException class with
        //     serialized data.
        //
        // Parameters:
        //   info:
        //     The object that holds the serialized object data.
        //
        //   context:
        //     The contextual information about the source or destination.
        protected OwnerAlreadyHasAnActiveChannelException(SerializationInfo info, StreamingContext context) : base(info, context) { }
        //
        // Summary:
        //     Initializes a new instance of the System.OwnerAlreadyHasAnActiveChannelException class with
        //     a specified error message and a reference to the inner exception that is
        //     the cause of this exception.
        //
        // Parameters:
        //   message:
        //     The error message that explains the reason for the exception.
        //
        //   innerException:
        //     The exception that is the cause of the current exception. If the innerException
        //     parameter is not a null reference, the current exception is raised in a catch
        //     block that handles the inner exception.
        public OwnerAlreadyHasAnActiveChannelException(string message, Exception innerException) : base(message, innerException) { }
    }
}


text:
package io.github.benas.jpopulator.randomizers;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Test class for {@link io.github.benas.jpopulator.randomizers.DateStringRandomizer}.
 *
 * @author Nikola Milivojevic (0dziga0@gmail.com)
 */
public class DateStringRandomizerTest {

    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String DEFAULT_DATE_FORMAT = "E M dd hh:mm:ss a zzz";

    private DateStringRandomizer dateStringRandomizer;

    private Date today, tomorrow;

    @Before
    public void setUp() throws Exception {
        today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        tomorrow = calendar.getTime();
    }

    @Test
    public void returnedStringShouldBeDate() {
        dateStringRandomizer = new DateStringRandomizer();
        String randomDate = dateStringRandomizer.getRandomValue();
        assertThat(randomDate).isNotNull();
        try {
            convertToDate(randomDate, DEFAULT_DATE_FORMAT);
        } catch (ParseException e) {
            Assert.fail("Returned date doesn't have a proper format " + randomDate);
        }
    }

    @Test
    public void returnedStringDateShouldBeInRange() throws ParseException {
        dateStringRandomizer = new DateStringRandomizer(today, tomorrow);
        Date actual = convertToDate(dateStringRandomizer.getRandomValue(), DEFAULT_DATE_FORMAT);
        assertThat(actual).isNotNull();
        assertThat(today.compareTo(actual) * tomorrow.compareTo(actual)).isGreaterThan(0);
    }

    @Test
    public void returnedStringDateShouldHaveSpecifiedFormat() throws Exception {
        dateStringRandomizer = new DateStringRandomizer(DATE_FORMAT, today, tomorrow);
        String randomDate = dateStringRandomizer.getRandomValue();
        assertThat(randomDate).isNotNull();
        assertThat(randomDate).matches("\\d{4}-\\d{2}-\\d{2}");
    }

    private Date convertToDate(String date, String format) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.parse(date);
    }

}


text:
package org.innovateuk.ifs.documentation;

import org.innovateuk.ifs.competition.publiccontent.resource.PublicContentSectionType;
import org.innovateuk.ifs.competition.publiccontent.resource.PublicContentStatus;
import org.innovateuk.ifs.publiccontent.builder.PublicContentResourceBuilder;

import java.time.ZonedDateTime;

import static java.util.Arrays.asList;
import static org.innovateuk.ifs.publiccontent.builder.ContentEventResourceBuilder.newContentEventResource;
import static org.innovateuk.ifs.publiccontent.builder.ContentGroupResourceBuilder.newContentGroupResource;
import static org.innovateuk.ifs.publiccontent.builder.PublicContentResourceBuilder.newPublicContentResource;
import static org.innovateuk.ifs.publiccontent.builder.PublicContentSectionResourceBuilder.newPublicContentSectionResource;

public class PublicContentResourceDocs {

    public static final PublicContentResourceBuilder publicContentResourceBuilder = newPublicContentResource()
            .withCompetitionId(1L)
            .withEligibilitySummary("summary")
            .withKeywords(asList("keyword1", "keyword2"))
            .withProjectFundingRange("range")
            .withProjectSize("size")
            .withPublishDate(ZonedDateTime.now())
            .withShortDescription("short")
            .withSummary("sum")
            .withInviteOnly(Boolean.FALSE)
            .withContentSections(
                    newPublicContentSectionResource()
                            .withStatus(PublicContentStatus.IN_PROGRESS)
                            .withType(PublicContentSectionType.DATES)
                            .withPublicContent(1L)
                            .withContentGroups(
                                newContentGroupResource()
                                    .withHeading("Heading")
                                    .withContent("Content")
                                    .withPriority(1)
                                .build(1)
                            ).build(1))
            .withContentEvents(newContentEventResource()
                    .withId(1L)
                    .withDate(ZonedDateTime.now())
                    .withPublicContent(2L)
                    .withContent("Content").build(1));
}


text:
      <form class="js-validation-login form-horizontal push-30-t form-login">

Login

                <input type="text" inputSelectText id="login-username" name="login-username" [(ngModel)]="email"
                       placeholder="Username"/>

                <input type="password" inputSelectText id="login-password" name="login-password" [(ngModel)]="password"
                       placeholder="Password"/>

            <button type="submit" (click)="login()" [ladda]="(accountState$ |async)?.isProcessing">Login</button>

            Register
            |
            Forgot password?

      </form>

    Contact Us


text:
(function () {
    'use strict';

    angular.module('main', []);

    /*
     * demo controller.
     */
    angular.module('main')
    .controller('demoController', ['$scope', function ($scope) {
        $scope.title = 'Demystifying AngularJS';
    }]);
})();


text:
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

using System;
using System.Linq;
using System.Net.Http;
using Microsoft.Rest;
using Pltkw3msApiUI2.ApiShipping;

namespace Pltkw3msApiUI2.ApiShipping
{
    public partial class Pltkw3msApiShipping : ServiceClient<Pltkw3msApiShipping>, IPltkw3msApiShipping
    {
        private Uri _baseUri;

        /// <summary>
        /// The base URI of the service.
        /// </summary>
        public Uri BaseUri
        {
            get { return this._baseUri; }
            set { this._baseUri = value; }
        }

        private ServiceClientCredentials _credentials;

        /// <summary>
        /// Credentials for authenticating with the service.
        /// </summary>
        public ServiceClientCredentials Credentials
        {
            get { return this._credentials; }
            set { this._credentials = value; }
        }

        private IShipping _shipping;

        public virtual IShipping Shipping
        {
            get { return this._shipping; }
        }

        private IValues _values;

        public virtual IValues Values
        {
            get { return this._values; }
        }

        /// <summary>
        /// Initializes a new instance of the Pltkw3msApiShipping class.
        /// </summary>
        public Pltkw3msApiShipping()
            : base()
        {
            this._shipping = new Shipping(this);
            this._values = new Values(this);
            this._baseUri = new Uri("https://microsoft-apiapp1068aac855d345fab80f472bc3ee8518.azurewebsites.net");
        }

        /// <summary>
        /// Initializes a new instance of the Pltkw3msApiShipping class.
        /// </summary>
        /// <param name='handlers'>
        /// Optional. The set of delegating handlers to insert in the http
        /// client pipeline.
        /// </param>
        public Pltkw3msApiShipping(params DelegatingHandler[] handlers)
            : base(handlers)
        {
            this._shipping = new Shipping(this);
            this._values = new Values(this);
            this._baseUri = new Uri("https://microsoft-apiapp1068aac855d345fab80f472bc3ee8518.azurewebsites.net");
        }

        /// <summary>
        /// Initializes a new instance of the Pltkw3msApiShipping class.
        /// </summary>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The set of delegating handlers to insert in the http
        /// client pipeline.
        /// </param>
        public Pltkw3msApiShipping(HttpClientHandler rootHandler, params DelegatingHandler[] handlers)
            : base(rootHandler, handlers)
        {
            this._shipping = new Shipping(this);
            this._values = new Values(this);
            this._baseUri = new Uri("https://microsoft-apiapp1068aac855d345fab80f472bc3ee8518.azurewebsites.net");
        }

        /// <summary>
        /// Initializes a new instance of the Pltkw3msApiShipping class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The set of delegating handlers to insert in the http
        /// client pipeline.
        /// </param>
        public Pltkw3msApiShipping(Uri baseUri, params DelegatingHandler[] handlers)
            : this(handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this._baseUri = baseUri;
        }

        /// <summary>
        /// Initializes a new instance of the Pltkw3msApiShipping class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Credentials for authenticating with the service.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The set of delegating handlers to insert in the http
        /// client pipeline.
        /// </param>
        public Pltkw3msApiShipping(ServiceClientCredentials credentials, params DelegatingHandler[] handlers)
            : this(handlers)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._credentials = credentials;

            if (this.Credentials != null)
            {
                this.Credentials.InitializeServiceClient(this);
            }
        }

        /// <summary>
        /// Initializes a new instance of the Pltkw3msApiShipping class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='credentials'>
        /// Required. Credentials for authenticating with the service.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The set of delegating handlers to insert in the http
        /// client pipeline.
        /// </param>
        public Pltkw3msApiShipping(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers)
            : this(handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._baseUri = baseUri;
            this._credentials = credentials;

            if (this.Credentials != null)
            {
                this.Credentials.InitializeServiceClient(this);
            }
        }
    }
}


text:
namespace base {
namespace trace_event {
class TracedValue;
}  // namespace trace_event
}  // namespace base

namespace cc {

struct CC_EXPORT ClipNode {
  ClipNode();
  ClipNode(const ClipNode& other);

  ClipNode& operator=(const ClipNode& other);

  ~ClipNode();

  // The node index of this node in the clip tree node vector.
  int id;
  // The node index of the parent node in the clip tree node vector.
  int parent_id;

  enum class ClipType {
    // The node contributes a new clip (that is, |clip| needs to be applied).
    APPLIES_LOCAL_CLIP,

    // This node represents a space expansion. When computing visible rects,
    // the accumulated clip inherited by this node gets expanded. Similarly,
    // when mapping a rect in descendant space to the rect in ancestor space
    // that depends on the descendant rect's contents, this node expands the
    // descendant rect. This is used for effects like pixel-moving filters,
    // where clipped-out content can affect visible output.
    EXPANDS_CLIP
  };

  ClipType clip_type;

  // The clip rect that this node contributes, expressed in the space of its
  // transform node.
  gfx::RectF clip;

  // Each element of this cache stores the accumulated clip from this clip
  // node to a particular target.  The number of cached clip rects required
  // per node is roughly proportional to the number of render targets a
  // given clip rect participates in.  On many pages with only a root
  // render target, the number of cached clip rects per node is 1.
  // Any more than 3, and this will overflow rects onto the heap, so this
  // number is a tradeoff of ClipNode size on average and access speed.
  mutable base::StackVector<ClipRectData, 3> cached_clip_rects;

  // This rect accumulates all clips from this node to the root in screen space.
  // It is used in the computation of layer's visible rect.
  gfx::RectF cached_accumulated_rect_in_screen_space;

  // For nodes that expand, this represents the amount of expansion.
  base::Optional<ClipExpander> clip_expander;

  // The id of the transform node that defines the clip node's local space.
  int transform_id;

  bool operator==(const ClipNode& other) const;

  void AsValueInto(base::trace_event::TracedValue* value) const;
};

}  // namespace cc

#endif  // CC_TREES_CLIP_NODE_H_


text:
"""Provides a list of valid visual studio versions.
"""

import collections

MsvcVersion = collections.namedtuple(
    "MsvcVersion", ["product_name", "product_version"]
)

versions = [
    MsvcVersion("Visual Studio 2019", "16"),
    MsvcVersion("Visual Studio 2022", "17"),
    MsvcVersion("Visual Studio 2017", "15"),
    MsvcVersion("Visual Studio 2015", "14"),
    MsvcVersion("Visual Studio 2013", "12"),
]


text:
class AddSexToUser < ActiveRecord::Migration
  def change
    add_column :users, :sex, :boolean
  end
end


text:
<form id="searchform" role="search" method="get" class="navbar-form" action="<?php echo home_url('/'); ?>">

		<?php _e('', 'roots'); ?>
		<?php _e('Search for:', 'roots'); ?>
		<input type="search" value="<?php if (is_search()) { echo get_search_query(); } ?>" name="s" class="search-field form-control hide pull-right" placeholder="<?php _e('Search', 'roots'); ?> ..." >

</form>


text:
/* eslint-disable @typescript-eslint/no-floating-promises */

import {initializeApp, FirebaseApp, deleteApp} from 'firebase/app';
import {getFunctions, connectFunctionsEmulator, Functions} from 'firebase/functions';
import {httpsCallable} from '../dist/functions';
import {default as TEST_PROJECT, functionsEmulatorPort} from './config';

const rando = (): string => Math.random().toString(36).substring(5);

describe('RxFire Functions', () => {
  let app: FirebaseApp;
  let functions: Functions;

  /**
   * Each test runs inside it's own app instance and the app
   * is deleted after the test runs.
   *
   * Each test is responsible for seeding and removing data. Helper
   * functions are useful if the process becomes brittle or tedious.
   * Note that removing is less necessary since the tests are run
   * against the emulator.
   */
  beforeEach(() => {
    app = initializeApp(TEST_PROJECT, rando());
    functions = getFunctions(app);
    connectFunctionsEmulator(functions, 'localhost', functionsEmulatorPort);
  });

  afterEach(() => {
    deleteApp(app).catch(() => undefined);
  });

  describe('httpsCallable', () => {
    it('should work', (done: jest.DoneCallback) => {
      const string = rando();
      const reverseString = (it:String) => (it === '') ? '' : reverseString(it.substr(1)) + it.charAt(0);
      httpsCallable<{string: String}, {reversed: String}>(functions, 'reverseString')({string}).subscribe((it) => {
        expect(it).toEqual({reversed: reverseString(string)});
        done();
      });
    });
  });
});


text:
@implementation GTPiwikAddOn

+ (void)trackEvent:(NSString *)event {
    [[PiwikTracker sharedTracker] trackPageview:event completionBlock:^(NSError *error) {
        if (error != nil) {
            ALog(@"Track event %@ failed with error message %@", event, [error description]);
        }
    }];
}

@end


text:
/* */
var baseUniq = require('./_baseUniq');
function uniqWith(array, comparator) {
  return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
}
module.exports = uniqWith;


text:
<?php

namespace NS\SentinelBundle\Entity\Types;

use NS\UtilBundle\Entity\Types\ArrayChoice;

/**
 * Description of TripleChoice
 *
 * @author gnat
 */
class Gender extends ArrayChoice
{
    /**
     * @var string
     */
    protected $convert_class = '\NS\SentinelBundle\Form\Types\Gender';

    /**
     * @return string
     */
    public function getName()
    {
        return 'Gender';
    }
}


text:
package request_test

import (
	"errors"
	"strings"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/awstesting/mock"
)

func TestRequestCancelRetry(t *testing.T) {
	c := make(chan struct{})

	reqNum := 0
	s := mock.NewMockClient(aws.NewConfig().WithMaxRetries(10))
	s.Handlers.Validate.Clear()
	s.Handlers.Unmarshal.Clear()
	s.Handlers.UnmarshalMeta.Clear()
	s.Handlers.UnmarshalError.Clear()
	s.Handlers.Send.PushFront(func(r *request.Request) {
		reqNum++
		r.Error = errors.New("net/http: request canceled")
	})
	out := &testData{}
	r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out)
	r.HTTPRequest.Cancel = c
	close(c)

	err := r.Send()
	if !strings.Contains(err.Error(), "canceled") {
		t.Errorf("expect canceled in error, %v", err)
	}
	if e, a := 1, reqNum; e != a {
		t.Errorf("expect %v, got %v", e, a)
	}
}


text:
zlsa.atc.ArrivalFactory = function(airport, options) {
  if (options.type) {
    if (options.type == 'random')
      return new zlsa.atc.ArrivalBase(airport, options);
    if (options.type == 'cyclic')
      return new zlsa.atc.ArrivalCyclic(airport, options);
    if (options.type == 'wave')
      return new zlsa.atc.ArrivalWave(airport, options);
    throw "Unsupported arrival type: " + options.type;
  }

  return new zlsa.atc.ArrivalDefault(airport, options);
};

zlsa.atc.ArrivalDefault = Fiber.extend(function(base) {
  return {
    init: function(airport, options) {
      this.airport = airport;

      this.airlines = [];
      this.altitude = 0;
      this.frequency = [0, 0];
      this.heading = 0;
      this.waypoints = [];
      this.radial = 0;
      this.speed = null;

      this.timeout = null;

      this.parse(options);
    },
    parse: function(options) {
      this.airlines = options.airlines;

      if(typeof options.altitude == typeof 0)
        this.altitude = [options.altitude, options.altitude];
      else
        this.altitude = options.altitude;

      this.frequency = vscale(options.frequency, 60);

      if(!options.heading)
        options.heading = (options.radial + 180) % 360;

      this.heading = radians(options.heading);

      if(options.fixes) {
        options.waypoints = [];
        for (var i=0; i<options.fixes.length; i++) {
          options.waypoints.push({
            fix: options.fixes[i],
          });
        }
      }

      if (options.waypoints)
        this.waypoints = options.waypoints;

      this.radial = radians(options.radial);
      this.speed = options.speed;
    },
    // Stop this arrival from running.  Generally called when
    // switching to another airport.
    stop: function() {
      if(this.timeout)
          game_clear_timeout(this.timeout);
    },
    // Start this arrival, spawning initial aircraft as appropriate
    start: function() {
      var delay = random(this.frequency[0], this.frequency[1]);

      if(Math.random() > 0.3) {
        delay = Math.random() * 0.1;
        game_timeout(this.spawnAircraft, delay, this, [false, false]);
      }
      this.timeout =
        game_timeout(this.spawnAircraft, delay, this, [true, true]);
    },

    // Create an aircraft and schedule next arrival if appropriate
    spawnAircraft: function(args) {
      var start_flag   = args[0];
      var timeout_flag = args[1] || false;

      // Set heading within 15 degrees of specified
      var wobble   = radians(15);
      var radial   = this.radial + random(-wobble, wobble);
      var distance;
      if(start_flag) // At start, spawn aircraft closer but outside ctr_radius
        distance = this.airport.ctr_radius + random(10, 20);
      else
        distance = 2*this.airport.ctr_radius - random(2, 18);
      var position = [sin(radial) * distance, cos(radial) * distance];

      var altitude = random(this.altitude[0] / 1000,
                            this.altitude[1] / 1000);
      altitude     = round(altitude * 2) * 500;

      var message = true;
      if(game_time() - this.airport.start < 2) message = false;

      var airline = choose_weight(this.airlines);
      var fleet = null;
      var idx = airline.indexOf('/');
      if (idx > 0) {
        var arr = airline.split('/', 2);
        airline = arr[0];
        fleet = arr[1];
      }

      aircraft_new({
        category:  "arrival",
        airline:   airline,
        fleet:     fleet,
        altitude:  altitude,
        heading:   this.heading,
        waypoints: this.waypoints,
        message:   message,
        position:  position,
        speed:     this.speed
      });

      if(timeout_flag) {
        this.timeout =
          game_timeout(this.spawnAircraft,
                       this.nextInterval(),
                       this,
                       [false, true]);
      }
    },
    nextInterval: function() {
      return random(this.frequency[0] / prop.game.frequency,
                    this.frequency[1] / prop.game.frequency);
    }
  };
});

zlsa.atc.ArrivalBase = Fiber.extend(function(base) {
  return {
    init: function(airport, options) {
      this.airport = airport;

      this.airlines = [];
      this.altitude = [1000, 1000];
      this.frequency = [0, 0];
      this.heading = null;
      this.waypoints = [];
      this.radial = [0, 0];
      this.speed = 200;

      this.timeout = null;

      this.parse(options);
    },
    // Supported Arrival options
    // airlines: {array of array} List of airlines with weight for each
    // altitude: {array or integer} Altitude in feet or range of altitudes
    // frequency: {array or integer} Frequency in aircraft/hour or range of frequencies
    // heading: {array or integer} Heading in degrees or range of headings
    // fixes: {array} Set of fixes to traverse (eg. for STARs)
    // radial: {array or integer} Radial in degrees or range of radials
    // speed: {integer} Speed in knots of spawned aircraft
    parse: function(options) {
      this.airlines = options.airlines;

      if(typeof options.altitude == typeof 0)
        this.altitude = [options.altitude, options.altitude];
      else
        this.altitude = options.altitude;

      if (typeof options.frequency == typeof 0)
        this.frequency = [options.frequency, options.frequency]
      else
        this.frequency = options.frequency;

      if (typeof options.heading == typeof 0)
        this.heading = [radians(options.heading), radians(options.heading)];
      else if (options.heading) {
        this.heading[0] = radians(options.heading[0]);
        this.heading[1] = radians(options.heading[1]);
      }

      if(options.fixes) {
        options.waypoints = [];
        for (var i=0; i<options.fixes.length; i++) {
          options.waypoints.push({
            fix: options.fixes[i],
          });
        }
      }

      if (options.waypoints)
        this.waypoints = options.waypoints;

      if (typeof options.radial == typeof 0)
        this.radial = [radians(options.radial), radians(options.radial)];
      else {
        this.radial[0] = radians(options.radial[0]);
        this.radial[1] = radians(options.radial[1]);
      }

      if (options.speed)
        this.speed = options.speed;
    },
    // Stop this arrival from running.  Generally called when
    // switching to another airport.
    stop: function() {
      if(this.timeout)
          game_clear_timeout(this.timeout);
    },
    // Start this arrival, spawning initial aircraft as appropriate
    start: function() {
      var delay = random(0, 3600 / this.frequency[0]);

      if(Math.random() > 0.3) {
        delay = Math.random() * 0.1;
        game_timeout(this.spawnAircraft, delay, this, [false, false]);
      }
      this.timeout =
        game_timeout(this.spawnAircraft, delay, this, [true, true]);
    },

    // Create an aircraft and schedule next arrival if appropriate
    spawnAircraft: function(args) {
      var start_flag   = args[0];
      var timeout_flag = args[1] || false;

      // Set heading within 15 degrees of specified
      var radial   = random(this.radial[0], this.radial[1])

      var heading = null;
      if (this.heading)
        heading = random(this.heading[0], this.heading[1]);
      else
        heading = radial + Math.PI;
      var distance;
      if(start_flag) // At start, spawn aircraft closer but outside ctr_radius
        distance = this.airport.ctr_radius + random(10, 20);
      else
        distance = 2*this.airport.ctr_radius - 2;
      var position = [sin(radial) * distance, cos(radial) * distance];

      var altitude = random(this.altitude[0] / 1000,
                            this.altitude[1] / 1000);
      altitude     = round(altitude * 2) * 500;

      var message = true;
      if(game_time() - this.airport.start < 2) message = false;

      var airline = choose_weight(this.airlines);
      var fleet = null;
      var idx = airline.indexOf('/');
      if (idx > 0) {
        var arr = airline.split('/', 2);
        airline = arr[0];
        fleet = arr[1];
      }

      aircraft_new({
        category:  "arrival",
        airline:   airline,
        fleet:     fleet,
        altitude:  altitude,
        heading:   heading,
        waypoints: this.waypoints,
        message:   message,
        position:  position,
        speed:     this.speed
      });

      if(timeout_flag) {
        this.timeout =
          game_timeout(this.spawnAircraft,
                       this.nextInterval(),
                       this,
                       [null, true]);
      }
    },
    nextInterval: function() {
      return random((3600 / this.frequency[1]) * prop.game.frequency,
                    (3600 / this.frequency[0]) * prop.game.frequency);
    }
  };
});

zlsa.atc.ArrivalCyclic = zlsa.atc.ArrivalBase.extend(function(base) {
  return {
    init: function(airport, options) {
      this.period = 60*60;
      this.offset = -15 * 60; // Start at the peak

      base.init.call(this, airport, options);

      this._amplitude = (3600 / this.frequency[0]) / 2;
      this._average = (3600/this.frequency[0] + 3600/this.frequency[1]) / 2;
    },
    // Additional supported options
    // period: {integer} Optionally specify the length of a cycle in minutes
    // offset: {integer} Optionally specify when the cycle peaks in minutes
    parse: function(options) {
      base.parse.call(this, options);
      if (options.period)
        this.period = options.period * 60;
      if (options.offset)
        this.offset = -this.period/4 + options.offset * 60;
    },
    nextInterval: function() {
      return (this._amplitude *
        Math.sin(Math.PI*2 * ((game_time() + this.offset)/this.period))
        + this._average) / prop.game.frequency;
    }
  };
});

zlsa.atc.ArrivalWave = zlsa.atc.ArrivalBase.extend(function(base) {
  return {
    init: function(airport, options) {
      this.period = 60*60;
      this.offset = 0;

      base.init.call(this, airport, options);

      // Average number of aircraft per hour
      this._average = (this.frequency[0] + this.frequency[1]) / 2;

      // Time in seconds for 7.5 nmi in-trail separation
      this._separation = Math.ceil(7.5/this.speed * 3600);

      // Aircraft per wave
      this._count = Math.floor(this._average/3600 * this.period);

      if ((this.period / this._separation) < this._count) {
        console.log("Reducing average arrival frequency from " +
                    this._average +
                    "/hour to maintain minimum in trail separation");
        this._count = Math.floor(3600 / this._separation);
      }

      // length of a wave in seconds
      this._waveLength = this._separation * this._count - 1;

      // Offset to have center of wave at 0 time and _offset always positive
      this._offset = this._waveLength/2;
      this._offset -= this.offset;
      while (this._offset < 0) this._offset += this.period;
    },
    // Additional supported options
    // period: {integer} Optionally specify the length of a cycle in minutes
    // offset: {integer} Optionally specify the center of the wave in minutes
    parse: function(options) {
      base.parse.call(this, options);
      if (options.period)
        this.period = options.period * 60;
      if (this.period <= 0)
        throw "Period must be greater than 0";
      if (options.offset)
        this.offset += options.offset * 60;
    },
    nextInterval: function() {
      var position = (game_time() + this._offset) % this.period;
      if (position >= this._waveLength)
        return this.period - position;
      return this._separation / prop.game.frequency;
    },
  };
});

zlsa.atc.DepartureFactory = function(airport, options) {
  if (options.type) {
    if (options.type == 'random')
      return new zlsa.atc.DepartureRandom(airport, options);
    if (options.type == 'cyclic')
      return new zlsa.atc.DepartureCyclic(airport, options);
    if (options.type == 'wave')
      return new zlsa.atc.DepartureWave(airport, options);
    throw "Unsupported departure type: " + options.type;
  }

  return new zlsa.atc.DepartureDefault(airport, options);
};

zlsa.atc.DepartureBase = Fiber.extend(function(base) {
  return {
    init: function(airport, options) {
      this.airport = airport;

      this.airlines = [];
      this.destinations = [0];
      this.sids = {};
      this.frequency = [0, 0];

      this.timeout = null;

      this.parse(options);
    },
    // Supported Departure options
    // airlines: {array of array} List of airlines with weight for each
    // frequency: {array or integer} Frequency in aircraft/hour or range of frequencies
    // destinations: {array of integer} List of headings for departures
    parse: function(options) {
      this.airlines = options.airlines;

      if (typeof options.frequency == typeof 0)
        this.frequency = [options.frequency, options.frequency]
      else
        this.frequency = options.frequency;

      if(options.sids) {
        this.sids = options.sids;
        for(var s in this.sids) {
          if(this.sids.hasOwnProperty(s)) {
            // Check each SID fix and log if not found in the airport fix list
            var fixList = this.sids[s];
            for(var i=0; i<fixList.length; i++) {
              var fixname = fixList[i];
              if(!this.airport.fixes[fixname])
                console.log("SID " + s + " fix not found: " + fixname);
            }
          }
        }
      }
      if (options.destinations) {
        this.destinations = [];
        for (var i=0;i<options.destinations.length;i++) {
            this.destinations.push(radians(options.destinations[i]));
        }
      }
    },
    // Stop this departure from running.  Generally called when
    // switching to another airport.
    stop: function() {
      if(this.timeout)
          game_clear_timeout(this.timeout);
    },
    // Start this departure, spawning initial aircraft as appropriate
    start: function() {
      var r = random(1, 2);
      if(Math.random() > 0.9)
        r = random(1, 6);
      for(var i=0;i<r;i++) {
        game_timeout(this.spawnAircraft, Math.random() * 0.1, this, false);
      }
      this.spawnAircraft(true);
    },

    // Create an aircraft and schedule next departure if appropriate
    spawnAircraft: function(timeout) {
      if(timeout == undefined) timeout=false;
      var message = true;
      if(game_time() - this.start < 2) message = false;

      var airline = choose_weight(this.airlines);
      var fleet = null;
      var idx = airline.indexOf('/');
      if (idx > 0) {
        var arr = airline.split('/', 2);
        airline = arr[0];
        fleet = arr[1];
      }

      aircraft_new({
        category:  "departure",
        destination: choose(this.destinations),
        airline:   airline,
        fleet:     fleet,
        message:   message
      });
      if(timeout)
        this.timeout = game_timeout(this.spawnAircraft,
                                    this.nextInterval(),
                                    this,
                                    true);
    },
    nextInterval: function() {
      // Frequency in minutes per aircraft
      return random((this.frequency[0] * 60) / prop.game.frequency,
                    (this.frequency[1] * 60) / prop.game.frequency);
    }
  };
});

zlsa.atc.DepartureDefault = zlsa.atc.DepartureBase;

zlsa.atc.DepartureRandom = zlsa.atc.DepartureBase.extend(function (base) {
  return {
    nextInterval: function () {
      return random((3600 / this.frequency[1]) / prop.game.frequency,
                    (3600 / this.frequency[0]) / prop.game.frequency);
    },
  };
});

zlsa.atc.DepartureCyclic = zlsa.atc.DepartureBase.extend(function (base) {
  return {
    init: function(airport, options) {
      this.period = 60*60;
      this.offset = -15 * 60; // Start at the peak

      base.init.call(this, airport, options);

      this._amplitude = (3600 / this.frequency[0]) / 2;
      this._average = (3600/this.frequency[0] + 3600/this.frequency[1]) / 2;
    },
    // Additional supported options
    // period: {integer} Optionally specify the length of a cycle in minutes
    // offset: {integer} Optionally specify when the cycle peaks in minutes
    parse: function(options) {
      base.parse.call(this, options);
      if (options.period)
        this.period = options.period * 60;
      if (options.offset)
        this.offset = -this.period/4 + options.offset * 60;
    },
    nextInterval: function() {
      return (this._amplitude *
        Math.sin(Math.PI*2 * ((game_time() + this.offset)/this.period))
        + this._average) / prop.game.frequency;
    },
  };
});

zlsa.atc.DepartureWave = zlsa.atc.DepartureCyclic.extend(function(base) {
  return {
    init: function(airport, options) {
      base.init.call(this, airport, options);

      // Time between aircraft in the wave
      this._separation = 10;

      // Aircraft per wave
      this._count = Math.floor(this._average/3600 * this.period);

      if ((this.period / this._separation) < this._count) {
        console.log("Reducing average departure frequency from " +
                    this._average +
                    "/hour to maintain minimum interval");
        this._count = Math.floor(3600 / this._separation);
      }

      // length of a wave in seconds
      this._waveLength = this._separation * this._count - 1;

      // Offset to have center of wave at 0 time
      this._offset = (this._waveLength - this._separation)/2 + this.offset;
    },
    nextInterval: function() {
      var position = (game_time() + this._offset) % this.period;
      if (position >= this._waveLength)
        return this.period - position;
      return this._separation / prop.game.frequency;
    },
  };
});

var Runway=Fiber.extend(function(base) {
  return {
    init: function(options) {
      if(!options) options={};

      this.position     = [0, 0];
      this.name         = [null, null];
      this.name_offset  = [[0, 0], [0, 0]];
      this.length       = 1;
      this.glideslope   = [radians(3), radians(3)];
      this.angle        = 0;
      this.ils          = [false, false];
      this.ils_distance = [null, null];
      this.delay        = [2, 2];
      this.lateral_separation = 4300 * 0.0003048;
      this.waiting      = [[], []];

      this.parse(options);

    },
    addQueue: function(aircraft, end) {
      end = this.getEnd(end);
      this.waiting[end].push(aircraft);
    },
    removeQueue: function(aircraft, end) {
      end = this.getEnd(end);
      if(this.waiting[end][0] == aircraft) {
        this.waiting[end].shift(aircraft);
        if(this.waiting[end].length >= 1) {
          this.waiting[end][0].moveForward();
        }
        return true;
      }
      return false;
    },
    isWaiting: function(aircraft, end) {
      end = this.getEnd(end);
      return this.waiting[end].indexOf(aircraft);
    },
    taxiDelay: function(aircraft, end) {
      end = this.getEnd(end);
      return this.delay[end] + Math.random() * 3;
    },
    getOffset: function(position, end, length) {
      end = this.getEnd(end);
      position = [position[0], position[1]];

      position = vsub(position, this.position);

      var offset = [0, 0];
      offset[0]  = (-cos(this.angle) * position[0]) + (sin(this.angle) * position[1]);
      offset[1]  = ( sin(this.angle) * position[0]) + (cos(this.angle) * position[1]);
//      offset[1] *= -1;

      if(end == 0) {
        offset = vscale(offset, -1);
      }

      if(length) {
        offset[1] -= this.length / 2;
      }
      return offset;

    },
    getAngle: function(end) {
      end = this.getEnd(end);
      return this.angle + (end == 1 ? Math.PI : 0);
    },
    getILS: function(end) {
      end = this.getEnd(end);
      return this.ils[end];
    },
    getILSDistance: function(end) {
      end = this.getEnd(end);
      return this.ils_distance[end];
    },
    getGlideslopeAltitude: function(distance, end, glideslope) {
      end = this.getEnd(end);
      if(!glideslope) glideslope = this.glideslope[end];
      glideslope = abs(glideslope);
      distance = Math.max(0, distance);
      var rise = tan(glideslope);
      return rise * distance * 3280;
    },
    getEnd: function(name) {
      if(typeof name == typeof 0) return name;
      if(typeof name == typeof "") {
        if(this.name[0].toLowerCase() == name.toLowerCase()) return 0;
        if(this.name[1].toLowerCase() == name.toLowerCase()) return 1;
      }
      return 0;
    },
    getPosition: function(end) {
      end = this.getEnd(end);

      return vsum(this.position,
          vscale(
            vturn(this.angle),
            (this.length / 2) * (end == 0 ? -1 : 1)
          )
        );
    },
    parse: function(data) {
      if(data.position) {
        var coord = new Position(data.position, data.reference_position, data.magnetic_north);
        this.position = coord.position;
      } else if(data.end) {
        var coord_start = new Position(data.end[0], data.reference_position, data.magnetic_north);
        var coord_end   = new Position(data.end[1], data.reference_position, data.magnetic_north);
        this.position   = vscale(vsum(coord_start.position, coord_end.position), 0.5);
        this.length     = vlen(vsub(coord_start, coord_end));
        this.angle      = vradial(vsub(coord_end.position, coord_start.position));
      }

      if(data.name) this.name = data.name;
      if(data.name_offset) this.name_offset = data.name_offset;

      if(data.length) this.length = data.length;
      if(data.angle) this.angle   = radians(data.angle);

      if(data.glideslope) this.glideslope = [radians(data.glideslope[0]), radians(data.glideslope[1])];

      if(data.ils) this.ils = data.ils;

      if(data.ils_distance) this.ils_distance = data.ils_distance;

      if(data.delay) this.delay = data.delay;

      if (data.lateral_separation)
        this.lateral_separation = data.lateral_separation * 0.0003048;
    },
  };
});

var Airport=Fiber.extend(function() {
  return {
    init: function(options) {
      if(!options) options={};

      this.name     = null;
      this.icao     = null;
      this.radio    = null;

      this.level    = null;

      this.runways  = [];

      this.runway   = null;

      this.fixes    = {};
      this.real_fixes = {};
      this.restricted_areas = [];

      this.timeout  = {
        runway: null,
        departure: null
      };

      this.departures = null;

      this.arrivals   = [];

      this.wind     = {
        speed: 10,
        angle: 0
      };

      this.ctr_radius  = 80;
      this.ctr_ceiling = 10000;

      this.parse(options);
      if(options.url) {
        this.load(options.url);
      }

    },
    getWind: function() {
      var wind = clone(this.wind);
      var s = 1;
      var angle_factor = Math.sin((s + game_time()) * 0.5) + Math.sin((s + game_time()) * 2);
      var s = 100;
      var speed_factor = Math.sin((s + game_time()) * 0.5) + Math.sin((s + game_time()) * 2);
      wind.angle += crange(-1, angle_factor, 1, radians(-4), radians(4));
      wind.speed *= crange(-1, speed_factor, 1, 0.9, 1.05);
      return wind;
    },
    parse: function(data) {
      if(data.position) this.position = new Position(data.position);
      if(data.magnetic_north) this.magnetic_north = radians(data.magnetic_north);
      if(!this.magnetic_north) this.magnetic_north = 0;
      if(data.name) this.name   = data.name;
      if(data.icao) this.icao   = data.icao;
      if(data.radio) this.radio = data.radio;
      if(data.ctr_radius) this.ctr_radius = data.ctr_radius;
      if(data.ctr_ceiling) this.ctr_ceiling = data.ctr_ceiling;
      if(data.rr_radius_nm) this.rr_radius_nm = data.rr_radius_nm;
      if(data.rr_center) this.rr_center = data.rr_center;
      if(data.level) this.level = data.level;
      this.has_terrain = false || data.has_terrain;

      if (this.has_terrain) {
        this.loadTerrain();
      }

      if(data.runways) {
        for(var i in data.runways) {
          data.runways[i].reference_position = this.position;
          data.runways[i].magnetic_north = this.magnetic_north;
          this.runways.push(new Runway(data.runways[i]));
        }
      }

      if(data.fixes) {
        for(var i in data.fixes) {
          var name = i.toUpperCase(),
              coord = new Position(data.fixes[i],
                                   this.position,
                                   this.magnetic_north);
          this.fixes[name] = coord.position;
          if (i.indexOf('_') != 0) {
            this.real_fixes[name] = coord.position;
          }
        }

      }

      if(data.restricted) {
        var r = data.restricted,
          self = this;
        for(var i in r) {
          var obj = {};
          if (r[i].name) obj.name = r[i].name;
          obj.height = parseElevation(r[i].height);
          obj.coordinates = $.map(r[i].coordinates, function(v) {
            return [(new Position(v, self.position, self.magnetic_north)).position];
          });

          var coords = obj.coordinates,
              coords_max = coords[0],
              coords_min = coords[0];

          for (var i in coords) {
            var v = coords[i]; //.position;
            coords_max = [Math.max(v[0], coords_max[0]), Math.max(v[1], coords_max[1])];
            coords_min = [Math.min(v[0], coords_min[0]), Math.min(v[1], coords_min[1])];
          };

          obj.center = vscale(vsum(coords_max, coords_min), 0.5);
          self.restricted_areas.push(obj);
        }
      }

      if(data.wind) {
        this.wind = data.wind;
        this.wind.angle = radians(this.wind.angle);
      }

      if(data.departures) {
        this.departures = zlsa.atc.DepartureFactory(this, data.departures);
      }

      if(data.arrivals) {
        for(var i=0;i<data.arrivals.length;i++) {
          this.arrivals.push(zlsa.atc.ArrivalFactory(this, data.arrivals[i]));
        }
      }

    },
    set: function() {
      this.start = game_time();
      this.updateRunway();
      this.addAircraft();
    },
    unset: function() {
      for(var i=0;i<this.arrivals.length;i++) {
        this.arrivals[i].stop();
      }
      this.departures.stop();
      if(this.timeout.runway) game_clear_timeout(this.timeout.runway);
    },
    addAircraft: function() {
      if(this.departures) {
        this.departures.start();
      }

      if(this.arrivals) {
        for(var i=0;i<this.arrivals.length;i++) {
          this.arrivals[i].start();
        }
      }

    },
    updateRunway: function(length) {
      if(!length) length = 0;
      var wind = this.getWind();
      var headwind = {};
      function ra(n) {
        var deviation = radians(10);
        return n + crange(0, Math.random(), 1, -deviation, deviation);
      }
      for(var i=0;i<this.runways.length;i++) {
        var runway = this.runways[i];
        headwind[runway.name[0]] =  Math.cos(runway.angle - ra(wind.angle)) * wind.speed;
        headwind[runway.name[1]] = -Math.cos(runway.angle - ra(wind.angle)) * wind.speed;
      }
      var best_runway = "";
      var best_runway_headwind = -Infinity;
      for(var i in headwind) {
        if(headwind[i] > best_runway_headwind && this.getRunway(i).length > length) {
          best_runway = i;
          best_runway_headwind = headwind[i];
        }
      }
      this.runway = best_runway;
      this.timeout.runway = game_timeout(this.updateRunway, Math.random() * 30, this);
    },
    selectRunway: function(length) {
      return this.runway;
    },
    parseTerrain: function(data) {
      // terrain must be in geojson format
      var apt = this;
      apt.terrain = {};
      for (var i in data.features) {
        var f = data.features[i],
            ele = round(f.properties.elevation / .3048, 1000); // m => ft, rounded to 1K (but not divided)

        if (!apt.terrain[ele]) {
          apt.terrain[ele] = [];
        }

        var multipoly = f.geometry.coordinates;
        if (f.geometry.type == 'LineString') {
          multipoly = [[multipoly]];
        }
        if (f.geometry.type == 'Polygon') {
          multipoly = [multipoly];
        }

        $.each(multipoly, function(i, poly) {
          // multipoly contains several polys
          // each poly has 1st outer ring and other rings are holes
          apt.terrain[ele].push($.map(poly, function(line_string) {
            return [
              $.map(line_string,
                function(pt) {
                  var pos = new Position(pt, apt.position, apt.magnetic_north);
                  pos.parse4326();
                  return [pos.position];
                }
              )
            ];
          }));
        });
      }
    },
    loadTerrain: function() {
      var terrain = new Content({
        type: "json",
        url:  'assets/airports/terrain/' + this.icao.toLowerCase() + '.geojson',
        that: this,
        callback: function(status, data) {
          if(status == "ok") {
            try {
              log('Parsing terrain');
              this.parseTerrain(data);
            }
            catch (e) {
              log(e.message);
            }
          }
        }
      });
    },
    load: function(url) {
      this.content = new Content({
        type: "json",
        url: url,
        that: this,
        callback: function(status, data) {
          if(status == "ok") {
            try {
              log('Parsing data');
              this.parse(data);
            }
            catch (e) {
              log(e.message);
            }
          }
        }
      });
    },
    getRestrictedAreas: function() {
      return this.restricted_areas || null;
    },
    getFix: function(name) {
      if(!name) return null;
      return this.fixes[name.toUpperCase()] || null;
    },
    getSID: function(name) {
      if(!name) return null;
      return this.departures.sids[name.toUpperCase()] || null;
    },
    getRunway: function(name) {
      if(!name) return null;
      name = name.toLowerCase();
      for(var i=0;i<this.runways.length;i++) {
        if(this.runways[i].name[0].toLowerCase() == name) return this.runways[i];
        if(this.runways[i].name[1].toLowerCase() == name) return this.runways[i];
      }
      return null;
    }
  };
});

function airport_init_pre() {
  prop.airport = {};
  prop.airport.airports = {};
  prop.airport.current  = null;
}

function airport_init() {
  // Add your airports here

  // DEBUG AIRPORTS
  airport_load("kdbg");

  // K*
  airport_load("ksfo");
  airport_load("kmsp");
  airport_load("kjfk");
  airport_load("klax");
  airport_load("ksan");
  //  airport_load("ksna");

  airport_load("ebbr");
  airport_load("eddh");
  airport_load("eham");
  airport_load("engm");
  airport_load("eddm");
  airport_load("eidw");
  airport_load("eglc");
  airport_load("loww");
  airport_load("egll");

  //  SOUTH AMERICA AIRPORTS
  airport_load("sbgr");
  airport_load("sbgl");
  airport_load("saez");

  //  RUSSIA AIRPORTS
  airport_load("uudd");

  airport_load("ltba");
  airport_load("vhhh");

}

function airport_ready() {
  if(!('atc-last-airport' in localStorage) || !(localStorage['atc-last-airport'] in prop.airport.airports)) airport_set('ksfo');
  else airport_set();
}

function airport_load(icao) {
  icao = icao.toLowerCase();
  if(icao in prop.airport.airports) {
    console.log(icao + ": already loaded");
    return;
  }
  var airport=new Airport({icao: icao, url: "assets/airports/"+icao+".json"});
  airport_add(airport);
  return airport;
}

function airport_add(airport) {
  prop.airport.airports[airport.icao.toLowerCase()] = airport;
}

function airport_set(icao) {
  if(!icao) {
    if(!('atc-last-airport' in localStorage)) return;
    else icao = localStorage['atc-last-airport'];
  }
  icao = icao.toLowerCase();

  localStorage['atc-last-airport'] = icao;
  if(!(icao in prop.airport.airports)) {
    console.log(icao + ": no such airport");
    return;
  }
  if(prop.airport.current) {
    prop.airport.current.unset();
    aircraft_remove_all();
  }
  prop.airport.current = prop.airport.airports[icao];
  prop.airport.current.set();

  var airport = prop.airport.current;

  $('#airport')
    .text(prop.airport.current.icao.toUpperCase())
    .attr("title", airport.name);

  $('.toggle-restricted-areas').toggle(
    (prop.airport.current.restricted_areas || []).length > 0);

  $('.toggle-sids').toggle(
    !$.isEmptyObject(prop.airport.current.departures.sids));

  prop.canvas.dirty = true;

  $('.toggle-terrain').toggle(
    !$.isEmptyObject(prop.airport.current.terrain));
}

function airport_get(icao) {
  if(!icao) return prop.airport.current;
  return prop.airport.airports[icao.toLowerCase()];
}