text:
<ns0:eml xmlns:ns0="eml://ecoinformatics.org/eml-2.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packageId="sychen.25.3" system="knb" xsi:schemaLocation="eml://ecoinformatics.org/eml-2.1.0 eml.xsd"> <access authSystem="knb" order="allowFirst"> <allow> <principal>public</principal>
 <permission>read</permission>
 </allow>
 </access>
 <dataset> <title>Bigleaf mahogany (Swietenia macrophylla King) seeds in Taiwan
      exhibit orthodox storage behaviour</title>
 <creator id="1290147372606"> <individualName> <givenName>C.T.</givenName>
 <surName>Chien</surName>
 </individualName>
 <organizationName>Division of Silviculture, Taiwan Forestry
        Research Institute</organizationName>
 <positionName>Research Fellow</positionName>
 <address> <deliveryPoint>53 Nan-Hai Road, Taipei 10066, Taiwan</deliveryPoint>
 </address>
 <electronicMailAddress>chien@tfri.gov.tw</electronicMailAddress>
 </creator>
 <creator id="1290147660367"> <individualName> <givenName>B.S.P.</givenName>
 <surName>WANG</surName>
 </individualName>
 <organizationName>Emeritus Research Scientist, Petawawa Research
        Forest, Natural Resource Canada,</organizationName>
 <positionName>Professor</positionName>
 <address> <deliveryPoint>Chalk River, ON K0J 1P0, Canada</deliveryPoint>
 </address>
 </creator>
 <creator id="1290147784650"> <individualName> <givenName>S.Y.</givenName>
 <surName>CHEN</surName>
 </individualName>
 <organizationName>Division of Silviculture, Taiwan Forestry
        Research Institute</organizationName>
 <positionName>Assistant reseacher</positionName>
 <address> <deliveryPoint>53 Nan-Hai Road, Taipei 10066, Taiwan</deliveryPoint>
 </address>
 <electronicMailAddress>sychen@tfri.gov.tw</electronicMailAddress>
 </creator>
 <abstract> <para>The storage behaviour of Swietenia macrophylla King seeds
        (Meliaceae) was studied. Seeds that were dried to 3.7% moisture
        content and stored at 3°C for two years had a 82.7% germination.
        The two-year stored seeds were then transferred to -196°C and
        -20°C for continued storage for another one and two years,
        respectively. Result showed that seeds stored at either -20°C or
        -196°C retained their original germinability. Thus, seeds of S.
        macrophylla harvested in Taiwan exhibit orthodox storage behaviour.</para>
 </abstract>
 <keywordSet> <keyword>Bigleaf mahogany</keyword>
 <keyword>Swietenia macrophylla</keyword>
 <keyword>seed</keyword>
 <keyword>orthodox storage behaviour</keyword>
 </keywordSet>
 <intellectualRights> <para>If you want to use the information, please contact with me.</para>
 </intellectualRights>
 <coverage> <geographicCoverage> <geographicDescription>Kaohsiung county</geographicDescription>
 <boundingCoordinates> <westBoundingCoordinate>120.625</westBoundingCoordinate>
 <eastBoundingCoordinate>120.625</eastBoundingCoordinate>
 <northBoundingCoordinate>22.875</northBoundingCoordinate>
 <southBoundingCoordinate>22.875</southBoundingCoordinate>
 </boundingCoordinates>
 </geographicCoverage>
 <temporalCoverage> <rangeOfDates> <beginDate> <calendarDate>2004-03-10</calendarDate>
 </beginDate>
 <endDate> <calendarDate>2007-06-04</calendarDate>
 </endDate>
 </rangeOfDates>
 </temporalCoverage>
 <taxonomicCoverage> <taxonomicClassification> <taxonRankName>Kingdom</taxonRankName>
 <taxonRankValue>Plantae</taxonRankValue>
 <taxonomicClassification> <taxonRankName>Phylum</taxonRankName>
 <taxonRankValue>Magnoliophyta</taxonRankValue>
 <taxonomicClassification> <taxonRankName>Class</taxonRankName>
 <taxonRankValue>Magnoliopsida</taxonRankValue>
 <taxonomicClassification> <taxonRankName>Order</taxonRankName>
 <taxonRankValue>Sapindales</taxonRankValue>
 <taxonomicClassification> <taxonRankName>Family</taxonRankName>
 <taxonRankValue>MELIACEAE</taxonRankValue>
 <taxonomicClassification> <taxonRankName>Genus</taxonRankName>
 <taxonRankValue>Swietenia</taxonRankValue>
 <taxonomicClassification> <taxonRankName>Species</taxonRankName>
 <taxonRankValue>macrophylla</taxonRankValue>
 </taxonomicClassification>
 </taxonomicClassification>
 </taxonomicClassification>
 </taxonomicClassification>
 </taxonomicClassification>
 </taxonomicClassification>
 </taxonomicClassification>
 </taxonomicCoverage>
 </coverage>
 <contact> <references>1290147372606</references>
 </contact>
 <methods> <methodStep> <description> <section> <title>Seed harvesting and handling</title>
 <para>Bigleaf mahogany seeds used in this study were
              collected from Kaohsiung county,</para>
 <para>south-western Taiwan in March 2004. Annual rainfall
              and annual mean temperature in</para>
 <para>the collection site are about 1,952 mm and 25.3°C,
              respectively (statistical analysis from</para>
 <para>2000 to 2008). The brown fruits were air-dried in the
              sun for about 4 days until they had</para>
 <para>opened. Seeds were mechanically and manually
              extracted. The winged part of the seeds</para>
 <para>was removed by hand, followed by fanning to separate
              wings from seeds. De-winged</para>
 <para>seeds were dried in the sun for another 3 days to
              reduce the moisture content. Each fruit</para>
 <para>contained about 60 brown-winged seeds.</para>
 </section>
 </description>
 </methodStep>
 <methodStep> <description> <section> <title>Drying treatment and storage conditions</title>
 <para>The dried seeds were drawn from a bulk collection,
              which were stored at 3°C in the</para>
 <para>Tree Seed Bank of Dongshih Forest District Office,
              Taiwan Forest Bureau for 2 years.</para>
 <para>Moisture contents (fresh weight basis) of the
              two-year-old seeds were determined by an</para>
 <para>oven-dry method with four replications each of intact
              seeds, corky wings and embryos</para>
 <para>separately at 70°C and 80°C for 24 hours, and at 103°C
              for 17 hours (ISTA, 1999).</para>
 <para>Results of the moisture contents analysis are
              summarized in table 1. The order of seed</para>
 <para>moisture contents from high to low in the intact
              seeds, corky wings, and embryos as</para>
 <para>determined by the three different oven-drying
              temperatures was 103°C > 80°C > 70°C.</para>
 <para>Table 1 also shows that corky wings retained a higher
              moisture content than did embryos.</para>
 <para>Seeds typically have higher moisture in embryos than
              in the seed coat or pericarp. Thus,</para>
 <para>the corky wings possessing extensive air spaces may
              have caused the higher moisture</para>
 <para>content.</para>
 <para>Prior to transferring the two-year-stored seeds from
              3°C to -20°C and -196°C (in</para>
 <para>liquid nitrogen) for continued storage, a germination
              test was conducted with alternating</para>
 <para>temperatures of 30/20°C with 12 h of light at the
              higher temperature for 8 weeks.</para>
 <para>Following this reassessment of seed quality, the drawn
              seed samples were wrapped</para>
 <para>in sealed aluminum foil and stored at -20°C for two
              years and -196°C for one year.</para>
 <para>Germination of seeds was based on samples of 75 seeds
              in three replications of 25 each.</para>
 </section>
 </description>
 </methodStep>
 <methodStep> <description> <section> <title>Seed treatment methods and statstical analysis</title>
 <para>The germination test was carried out by mixing seeds
              with sphagnum medium (cut into</para>
 <para>small piece) at a 75%~80% moisture content in sealable
              polyethylene bags (0.04 mm</para>
 <para>thick) and then incubating them at the alternating
              temperature of 30/20°C with 12 h of</para>
 <para>light at the higher temperature for 8 weeks. The
              progress of germination was monitored</para>
 <para>weekly, and mean percentages of germination were
              calculated and compared by analysis</para>
 <para>of variance (ANOVA) and by the least significant
              difference (LSD) test at a 5% level</para>
 <para>of significance. The mean germination time (MGT) in
              days was calculated as: MGT =</para>
 <para>(Σniti)/N, where ni is the number of seeds germinated
              in ti days from the beginning of the</para>
 <para>test, and N is the total number of germinated seeds at
              the end of the test. The MGT is a</para>
 <para>measure of the rate of germination and of the
              sharpness of the germination peak.</para>
 </section>
 </description>
 </methodStep>
 </methods>
 <dataTable id="1290149970038"> <entityName>Table 1. Moisture contents of intact seeds, corky
        wings and embryos that were dried at different oven
        temperatures. Samples were stored at 3°C for two years.</entityName>
 <physical> <objectName>Unamed-table-9209350964377290475.tmp</objectName>
 <dataFormat> <textFormat> <attributeOrientation>column</attributeOrientation>
 <simpleDelimited> <fieldDelimiter>,</fieldDelimiter>
 </simpleDelimited>
 </textFormat>
 </dataFormat>
 <distribution> <online> <url>ecogrid://knb/sychen.23.4</url>
 </online>
 </distribution>
 </physical>
 <attributeList> <attribute id="1290149970054"> <attributeName>Oven temperature</attributeName>
 <attributeDefinition>Oven temperature (°C)</attributeDefinition>
 <measurementScale> <interval> <unit> <standardUnit>celsius</standardUnit>
 </unit>
 <numericDomain> <numberType>natural</numberType>
 </numericDomain>
 </interval>
 </measurementScale>
 </attribute>
  <attribute id="1290151132890"><attributeName>Dry time (h)</attributeName>
<attributeDefinition>(h)</attributeDefinition>
<measurementScale><nominal><nonNumericDomain><textDomain><definition>(h)</definition>
</textDomain>
</nonNumericDomain>
</nominal>
</measurementScale>
</attribute>
<attribute id="1290149970085"> <attributeName>Moisture content of seeds (% of fresh weight)</attributeName>
 <attributeLabel>Seeds</attributeLabel>
 <attributeDefinition>Moisture content (% of fresh weight)</attributeDefinition>
 <measurementScale> <nominal> <nonNumericDomain> <textDomain> <definition>%</definition>
 </textDomain>
 </nonNumericDomain>
 </nominal>
 </measurementScale>
 </attribute>
 <attribute id="1290149970101"> <attributeName>Moisture content of corky wings (% of fresh weight)</attributeName>
 <attributeLabel>Corky wings</attributeLabel>
 <attributeDefinition>Moisture content (% of fresh weight)</attributeDefinition>
 <measurementScale> <nominal> <nonNumericDomain> <textDomain> <definition>%</definition>
 </textDomain>
 </nonNumericDomain>
 </nominal>
 </measurementScale>
 </attribute>
 <attribute id="1290149970116"> <attributeName>Moisture content of embryos (% of fresh weight)</attributeName>
 <attributeLabel>Embryos</attributeLabel>
 <attributeDefinition>Moisture content (% of fresh weight)</attributeDefinition>
 <measurementScale> <nominal> <nonNumericDomain> <textDomain> <definition>%</definition>
 </textDomain>
 </nonNumericDomain>
 </nominal>
 </measurementScale>
 </attribute>
 </attributeList>
 </dataTable>
  <dataTable id="1290150874997"><entityName>Table 2. Germination percentages and mean germination time (days in bracket) of bigleaf mahogany seeds after stored at -20°C and -196°C (liquid nitrogen) for 24 and 12 months, respectively.</entityName>
<physical><objectName>Unamed-table-4505067938918049413.tmp</objectName>
<dataFormat> <textFormat><attributeOrientation>column</attributeOrientation>
<simpleDelimited><fieldDelimiter>,</fieldDelimiter>
</simpleDelimited>
</textFormat>
</dataFormat>
<distribution><online><url>ecogrid://knb/sychen.24.2</url>
</online>
</distribution>
</physical>
<attributeList><attribute id="1290150875012"><attributeName>Storage temperature (°C)</attributeName>
<attributeDefinition>Storage temperature</attributeDefinition>
<measurementScale><interval><unit><standardUnit>celsius</standardUnit>
</unit>
<numericDomain><numberType>integer</numberType>
</numericDomain>
</interval>
</measurementScale>
</attribute>
<attribute id="1290150875028"><attributeName>Germination (%) after a storage period (6 months)</attributeName>
<attributeDefinition>Germination (%) after a storage period (6 months)</attributeDefinition>
<measurementScale><nominal><nonNumericDomain><textDomain><definition>%</definition>
</textDomain>
</nonNumericDomain>
</nominal>
</measurementScale>
</attribute>
<attribute id="1290150875044"><attributeName>Germination (%) after a storage period (6 months)</attributeName>
<attributeDefinition>Germination (%) after a storage period (6 months)</attributeDefinition>
<measurementScale><nominal><nonNumericDomain><textDomain><definition>%</definition>
</textDomain>
</nonNumericDomain>
</nominal>
</measurementScale>
</attribute>
<attribute id="1290150875059"><attributeName>Germination (%) after a storage period (24 months)</attributeName>
<attributeDefinition>Germination (%) after a storage period (24 months)</attributeDefinition>
<measurementScale><nominal><nonNumericDomain><textDomain><definition>%</definition>
</textDomain>
</nonNumericDomain>
</nominal>
</measurementScale>
</attribute>
</attributeList>
</dataTable>
</dataset>
  </ns0:eml>


text:
using Tortuga.Anchor.Modeling;

namespace Grauenwolf.TravellerTools.Characters
{

    public class Feature : EditableObjectModelBase
    {
        public Feature(string text)
        {
            Text = text;
        }

        public string Text { get => Get<string>(); set => Set(value); }

    }

}

redpajama_set_name: RedPajamaGithub


text:
import { ReflectiveInjector } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { MockBackend } from '@angular/http/testing';
import { LocationService } from 'app/shared/location.service';
import { MockLocationService } from 'testing/location.service';
import { Logger } from 'app/shared/logger.service';
import { MockLogger } from 'testing/logger.service';
import { DocumentService, DocumentContents,
         FETCHING_ERROR_ID, FILE_NOT_FOUND_ID } from './document.service';

const CONTENT_URL_PREFIX = 'generated/docs/';

function createResponse(body: any) {
  return new Response(new ResponseOptions({ body: JSON.stringify(body) }));
}

function createInjector(initialUrl: string) {
  return ReflectiveInjector.resolveAndCreate([
      DocumentService,
      { provide: LocationService, useFactory: () => new MockLocationService(initialUrl) },
      { provide: ConnectionBackend, useClass: MockBackend },
      { provide: RequestOptions, useClass: BaseRequestOptions },
      { provide: Logger, useClass: MockLogger },
      Http,
  ]);
}

function getServices(initialUrl: string = '') {
  const injector = createInjector(initialUrl);
  return {
    backend: injector.get(ConnectionBackend) as MockBackend,
    locationService: injector.get(LocationService) as MockLocationService,
    docService: injector.get(DocumentService) as DocumentService,
    logger: injector.get(Logger) as MockLogger
  };
}

describe('DocumentService', () => {

  it('should be creatable', () => {
    const { docService } = getServices();
    expect(docService).toBeTruthy();
  });

  describe('currentDocument', () => {

    it('should fetch a document for the initial location', () => {
      const { docService, backend } = getServices('initial/doc');
      const connections = backend.connectionsArray;
      docService.currentDocument.subscribe();

      expect(connections.length).toEqual(1);
      expect(connections[0].request.url).toEqual(CONTENT_URL_PREFIX + 'initial/doc.json');
      expect(backend.connectionsArray[0].request.url).toEqual(CONTENT_URL_PREFIX + 'initial/doc.json');
    });

    it('should emit a document each time the location changes', () => {
      let latestDocument: DocumentContents;
      const doc0 = { contents: 'doc 0', id: 'initial/doc' };
      const doc1 = { contents: 'doc 1', id: 'new/doc'  };
      const { docService, backend, locationService } = getServices('initial/doc');
      const connections = backend.connectionsArray;

      docService.currentDocument.subscribe(doc => latestDocument = doc);
      expect(latestDocument).toBeUndefined();

      connections[0].mockRespond(createResponse(doc0));
      expect(latestDocument).toEqual(doc0);

      locationService.go('new/doc');
      connections[1].mockRespond(createResponse(doc1));
      expect(latestDocument).toEqual(doc1);
    });

    it('should emit the not-found document if the document is not found on the server', () => {
      const { docService, backend } = getServices('missing/doc');
      const connections = backend.connectionsArray;
      let currentDocument: DocumentContents;
      docService.currentDocument.subscribe(doc => currentDocument = doc);

      connections[0].mockError(new Response(new ResponseOptions({ status: 404, statusText: 'NOT FOUND'})) as any);
      expect(connections.length).toEqual(2);
      expect(connections[1].request.url).toEqual(CONTENT_URL_PREFIX + 'file-not-found.json');
      const fileNotFoundDoc = { id: FILE_NOT_FOUND_ID, contents: '
Page Not Found
' };
      connections[1].mockRespond(createResponse(fileNotFoundDoc));
      expect(currentDocument).toEqual(fileNotFoundDoc);
    });

    it('should emit a hard-coded not-found document if the not-found document is not found on the server', () => {
      let currentDocument: DocumentContents;
      const notFoundDoc: DocumentContents = { contents: 'Document not found', id: FILE_NOT_FOUND_ID };
      const nextDoc = { contents: 'Next Doc', id: 'new/doc' };
      const { docService, backend, locationService } = getServices(FILE_NOT_FOUND_ID);
      const connections = backend.connectionsArray;
      docService.currentDocument.subscribe(doc => currentDocument = doc);

      connections[0].mockError(new Response(new ResponseOptions({ status: 404, statusText: 'NOT FOUND'})) as any);
      expect(connections.length).toEqual(1);
      expect(currentDocument).toEqual(notFoundDoc);

      // now check that we haven't killed the currentDocument observable sequence
      locationService.go('new/doc');
      connections[1].mockRespond(createResponse(nextDoc));
      expect(currentDocument).toEqual(nextDoc);
    });

    it('should not crash the app if the response is invalid JSON', () => {
      let latestDocument: DocumentContents;
      const { docService, backend, locationService} = getServices('initial/doc');
      const connections = backend.connectionsArray;

      docService.currentDocument.subscribe(doc => latestDocument = doc);

      connections[0].mockRespond(new Response(new ResponseOptions({ body: 'this is invalid JSON' })));
      expect(latestDocument.id).toEqual(FETCHING_ERROR_ID);

      const doc1 = { contents: 'doc 1' };
      locationService.go('new/doc');
      connections[1].mockRespond(createResponse(doc1));
      expect(latestDocument).toEqual(jasmine.objectContaining(doc1));
    });

    it('should not make a request to the server if the doc is in the cache already', () => {
      let latestDocument: DocumentContents;
      let subscription: Subscription;

      const doc0 = { contents: 'doc 0' };
      const doc1 = { contents: 'doc 1' };
      const { docService, backend, locationService} = getServices('url/0');
      const connections = backend.connectionsArray;

      subscription = docService.currentDocument.subscribe(doc => latestDocument = doc);
      expect(connections.length).toEqual(1);
      connections[0].mockRespond(createResponse(doc0));
      expect(latestDocument).toEqual(jasmine.objectContaining(doc0));
      subscription.unsubscribe();

      // modify the response so we can check that future subscriptions do not trigger another request
      connections[0].response.next(createResponse({ contents: 'error 0' }));

      subscription = docService.currentDocument.subscribe(doc => latestDocument = doc);
      locationService.go('url/1');
      expect(connections.length).toEqual(2);
      connections[1].mockRespond(createResponse(doc1));
      expect(latestDocument).toEqual(jasmine.objectContaining(doc1));
      subscription.unsubscribe();

      // modify the response so we can check that future subscriptions do not trigger another request
      connections[1].response.next(createResponse({ contents: 'error 1' }));

      subscription = docService.currentDocument.subscribe(doc => latestDocument = doc);
      locationService.go('url/0');
      expect(connections.length).toEqual(2);
      expect(latestDocument).toEqual(jasmine.objectContaining(doc0));
      subscription.unsubscribe();

      subscription = docService.currentDocument.subscribe(doc => latestDocument = doc);
      locationService.go('url/1');
      expect(connections.length).toEqual(2);
      expect(latestDocument).toEqual(jasmine.objectContaining(doc1));
      subscription.unsubscribe();
    });
  });

  describe('computeMap', () => {
    it('should map the "empty" location to the correct document request', () => {
      let latestDocument: DocumentContents;
      const { docService, backend } = getServices();
      docService.currentDocument.subscribe(doc => latestDocument = doc);

      expect(backend.connectionsArray[0].request.url).toEqual(CONTENT_URL_PREFIX + 'index.json');
    });

    it('should map the "folder" locations to the correct document request', () => {
      const { docService, backend, locationService} = getServices('guide');
      docService.currentDocument.subscribe();

      expect(backend.connectionsArray[0].request.url).toEqual(CONTENT_URL_PREFIX + 'guide.json');
    });
  });
});


text:
cask 'betaflight-configurator' do
  version '10.3.1'
  sha256 '54c44d2d0ea22ad47e04341a8d85fbe49c13b7df9cf65355ec940928daa57403'

  url "https://github.com/betaflight/betaflight-configurator/releases/download/#{version}/betaflight-configurator_#{version}_macOS.dmg"
  appcast 'https://github.com/betaflight/betaflight-configurator/releases.atom'
  name 'Betaflight-Configurator'
  homepage 'https://github.com/betaflight/betaflight-configurator'

  app 'Betaflight Configurator.app'
end


text:
namespace media {

struct ScopedAudioQueueRefTraits {
  static AudioQueueRef Retain(AudioQueueRef queue) {
    NOTREACHED() << "Only compatible with ASSUME policy";
    return queue;
  }
  static void Release(AudioQueueRef queue) { AudioQueueDispose(queue, true); }
  static AudioQueueRef InvalidValue() { return nullptr; }
};

using ScopedAudioQueueRef =
    base::ScopedTypeRef<AudioQueueRef, ScopedAudioQueueRefTraits>;

}  // namespace media

#endif  // PLATFORM_MEDIA_RENDERER_DECODERS_MAC_SCOPED_AUDIO_QUEUE_REF_H_


text:
import {
  Component,
  OnInit,
  OnDestroy,
  AfterViewInit,
  ViewChild,
  HostListener,
  ViewEncapsulation,
  ElementRef,
  ChangeDetectorRef,
  TemplateRef,
  NgZone,
  Inject,
  PLATFORM_ID,
} from '@angular/core';

import { DOCUMENT, isPlatformBrowser } from '@angular/common';

import { detectIE, calculateAutoPositioning } from './helpers';

import { ColorFormats, Cmyk, Hsla, Hsva, Rgba } from './formats';
import { AlphaChannel, OutputFormat, SliderDimension, SliderPosition } from './helpers';

import { ColorPickerService } from './color-picker.service';

// Do not store that on the class instance since the condition will be run
// every time the class is created.
const SUPPORTS_TOUCH = typeof window !== 'undefined' && 'ontouchstart' in window;

@Component({
  selector: 'color-picker',
  templateUrl: './color-picker.component.html',
  styleUrls: [ './color-picker.component.css' ],
  encapsulation: ViewEncapsulation.None
})
export class ColorPickerComponent implements OnInit, OnDestroy, AfterViewInit {
  private isIE10: boolean = false;

  private cmyk: Cmyk;
  private hsva: Hsva;

  private width: number;
  private height: number;

  private cmykColor: string;
  private outputColor: string;
  private initialColor: string;
  private fallbackColor: string;

  private listenerResize: any;
  private listenerMouseDown: EventListener;

  private directiveInstance: any;

  private sliderH: number;
  private sliderDimMax: SliderDimension;
  private directiveElementRef: ElementRef;

  private dialogArrowSize: number = 10;
  private dialogArrowOffset: number = 15;

  private dialogInputFields: ColorFormats[] = [
    ColorFormats.HEX,
    ColorFormats.RGBA,
    ColorFormats.HSLA,
    ColorFormats.CMYK
  ];

  private useRootViewContainer: boolean = false;

  public show: boolean;
  public hidden: boolean;

  public top: number;
  public left: number;
  public position: string;

  public format: ColorFormats;
  public slider: SliderPosition;

  public hexText: string;
  public hexAlpha: number;

  public cmykText: Cmyk;
  public hslaText: Hsla;
  public rgbaText: Rgba;

  public arrowTop: number;

  public selectedColor: string;
  public hueSliderColor: string;
  public alphaSliderColor: string;

  public cpWidth: number;
  public cpHeight: number;

  public cpColorMode: number;

  public cpCmykEnabled: boolean;

  public cpAlphaChannel: AlphaChannel;
  public cpOutputFormat: OutputFormat;

  public cpDisableInput: boolean;
  public cpDialogDisplay: string;

  public cpIgnoredElements: any;

  public cpSaveClickOutside: boolean;
  public cpCloseClickOutside: boolean;

  public cpPosition: string;
  public cpUsePosition: string;
  public cpPositionOffset: number;

  public cpOKButton: boolean;
  public cpOKButtonText: string;
  public cpOKButtonClass: string;

  public cpCancelButton: boolean;
  public cpCancelButtonText: string;
  public cpCancelButtonClass: string;

  public eyeDropperSupported =
    isPlatformBrowser(this.platformId) && 'EyeDropper' in this.document.defaultView;
  public cpEyeDropper: boolean;

  public cpPresetLabel: string;
  public cpPresetColors: string[];
  public cpPresetColorsClass: string;
  public cpMaxPresetColorsLength: number;

  public cpPresetEmptyMessage: string;
  public cpPresetEmptyMessageClass: string;

  public cpAddColorButton: boolean;
  public cpAddColorButtonText: string;
  public cpAddColorButtonClass: string;
  public cpRemoveColorButtonClass: string;

  public cpTriggerElement: ElementRef;

  public cpExtraTemplate: TemplateRef<any>;

  @ViewChild('dialogPopup', { static: true }) dialogElement: ElementRef;

  @ViewChild('hueSlider', { static: true }) hueSlider: ElementRef;
  @ViewChild('alphaSlider', { static: true }) alphaSlider: ElementRef;

  @HostListener('document:keyup.esc', ['$event']) handleEsc(event: any): void {
    if (this.show && this.cpDialogDisplay === 'popup') {
      this.onCancelColor(event);
    }
  }

  @HostListener('document:keyup.enter', ['$event']) handleEnter(event: any): void {
    if (this.show && this.cpDialogDisplay === 'popup') {
      this.onAcceptColor(event);
    }
  }

  constructor(
    private ngZone: NgZone,
    private elRef: ElementRef,
    private cdRef: ChangeDetectorRef,
    @Inject(DOCUMENT) private document: Document,
    @Inject(PLATFORM_ID) private platformId: string,
    private service: ColorPickerService
  ) {}

  ngOnInit(): void {
    this.slider = new SliderPosition(0, 0, 0, 0);

    const hueWidth = this.hueSlider.nativeElement.offsetWidth || 140;
    const alphaWidth = this.alphaSlider.nativeElement.offsetWidth || 140;

    this.sliderDimMax = new SliderDimension(hueWidth, this.cpWidth, 130, alphaWidth);

    if (this.cpCmykEnabled) {
      this.format = ColorFormats.CMYK;
    } else if (this.cpOutputFormat === 'rgba') {
      this.format = ColorFormats.RGBA;
    } else if (this.cpOutputFormat === 'hsla') {
      this.format = ColorFormats.HSLA;
    } else {
      this.format = ColorFormats.HEX;
    }

    this.listenerMouseDown = (event: MouseEvent) => { this.onMouseDown(event); };
    this.listenerResize = () => { this.onResize(); };

    this.openDialog(this.initialColor, false);
  }

  ngOnDestroy(): void {
    this.closeDialog();
  }

  ngAfterViewInit(): void {
    if (this.cpWidth !== 230 || this.cpDialogDisplay === 'inline') {
      const hueWidth = this.hueSlider.nativeElement.offsetWidth || 140;
      const alphaWidth = this.alphaSlider.nativeElement.offsetWidth || 140;

      this.sliderDimMax = new SliderDimension(hueWidth, this.cpWidth, 130, alphaWidth);

      this.updateColorPicker(false);

      this.cdRef.detectChanges();
    }
  }

  public openDialog(color: any, emit: boolean = true): void {
    this.service.setActive(this);

    if (!this.width) {
      this.cpWidth = this.directiveElementRef.nativeElement.offsetWidth;
    }

    if (!this.height) {
      this.height = 320;
    }

    this.setInitialColor(color);

    this.setColorFromString(color, emit);

    this.openColorPicker();
  }

  public closeDialog(): void {
    this.closeColorPicker();
  }

  public setupDialog(instance: any, elementRef: ElementRef, color: any,
    cpWidth: string, cpHeight: string, cpDialogDisplay: string, cpFallbackColor: string,
    cpColorMode: string, cpCmykEnabled: boolean, cpAlphaChannel: AlphaChannel,
    cpOutputFormat: OutputFormat, cpDisableInput: boolean, cpIgnoredElements: any,
    cpSaveClickOutside: boolean, cpCloseClickOutside: boolean, cpUseRootViewContainer: boolean,
    cpPosition: string, cpPositionOffset: string, cpPositionRelativeToArrow: boolean,
    cpPresetLabel: string, cpPresetColors: string[], cpPresetColorsClass: string,
    cpMaxPresetColorsLength: number, cpPresetEmptyMessage: string,
    cpPresetEmptyMessageClass: string, cpOKButton: boolean, cpOKButtonClass: string,
    cpOKButtonText: string, cpCancelButton: boolean, cpCancelButtonClass: string,
    cpCancelButtonText: string, cpAddColorButton: boolean, cpAddColorButtonClass: string,
    cpAddColorButtonText: string, cpRemoveColorButtonClass: string, cpEyeDropper: boolean,
    cpTriggerElement: ElementRef, cpExtraTemplate: TemplateRef<any>): void
  {
    this.setInitialColor(color);

    this.setColorMode(cpColorMode);

    this.isIE10 = (detectIE() === 10);

    this.directiveInstance = instance;
    this.directiveElementRef = elementRef;

    this.cpDisableInput = cpDisableInput;

    this.cpCmykEnabled = cpCmykEnabled;
    this.cpAlphaChannel = cpAlphaChannel;
    this.cpOutputFormat = cpOutputFormat;

    this.cpDialogDisplay = cpDialogDisplay;

    this.cpIgnoredElements = cpIgnoredElements;

    this.cpSaveClickOutside = cpSaveClickOutside;
    this.cpCloseClickOutside = cpCloseClickOutside;

    this.useRootViewContainer = cpUseRootViewContainer;

    this.width = this.cpWidth = parseInt(cpWidth, 10);
    this.height = this.cpHeight = parseInt(cpHeight, 10);

    this.cpPosition = cpPosition;
    this.cpPositionOffset = parseInt(cpPositionOffset, 10);

    this.cpOKButton = cpOKButton;
    this.cpOKButtonText = cpOKButtonText;
    this.cpOKButtonClass = cpOKButtonClass;

    this.cpCancelButton = cpCancelButton;
    this.cpCancelButtonText = cpCancelButtonText;
    this.cpCancelButtonClass = cpCancelButtonClass;

    this.cpEyeDropper = cpEyeDropper;

    this.fallbackColor = cpFallbackColor || '#fff';

    this.setPresetConfig(cpPresetLabel, cpPresetColors);

    this.cpPresetColorsClass = cpPresetColorsClass;
    this.cpMaxPresetColorsLength = cpMaxPresetColorsLength;
    this.cpPresetEmptyMessage = cpPresetEmptyMessage;
    this.cpPresetEmptyMessageClass = cpPresetEmptyMessageClass;

    this.cpAddColorButton = cpAddColorButton;
    this.cpAddColorButtonText = cpAddColorButtonText;
    this.cpAddColorButtonClass = cpAddColorButtonClass;
    this.cpRemoveColorButtonClass = cpRemoveColorButtonClass;

    this.cpTriggerElement = cpTriggerElement;
    this.cpExtraTemplate = cpExtraTemplate;

    if (!cpPositionRelativeToArrow) {
      this.dialogArrowOffset = 0;
    }

    if (cpDialogDisplay === 'inline') {
      this.dialogArrowSize = 0;
      this.dialogArrowOffset = 0;
    }

    if (cpOutputFormat === 'hex' &&
        cpAlphaChannel !== 'always' && cpAlphaChannel !== 'forced')
    {
      this.cpAlphaChannel = 'disabled';
    }
  }

  public setColorMode(mode: string): void {
    switch (mode.toString().toUpperCase()) {
      case '1':
      case 'C':
      case 'COLOR':
        this.cpColorMode = 1;
        break;
      case '2':
      case 'G':
      case 'GRAYSCALE':
        this.cpColorMode = 2;
        break;
      case '3':
      case 'P':
      case 'PRESETS':
        this.cpColorMode = 3;
        break;
      default:
        this.cpColorMode = 1;
    }
  }

  public setInitialColor(color: any): void {
    this.initialColor = color;
  }

  public setPresetConfig(cpPresetLabel: string, cpPresetColors: string[]): void {
    this.cpPresetLabel = cpPresetLabel;
    this.cpPresetColors = cpPresetColors;
  }

  public setColorFromString(value: string, emit: boolean = true, update: boolean = true): void {
    let hsva: Hsva | null;

    if (this.cpAlphaChannel === 'always' || this.cpAlphaChannel === 'forced') {
      hsva = this.service.stringToHsva(value, true);

      if (!hsva && !this.hsva) {
        hsva = this.service.stringToHsva(value, false);
      }
    } else {
      hsva = this.service.stringToHsva(value, false);
    }

    if (!hsva && !this.hsva) {
      hsva = this.service.stringToHsva(this.fallbackColor, false);
    }

    if (hsva) {
      this.hsva = hsva;

      this.sliderH = this.hsva.h;

      if (this.cpOutputFormat === 'hex' && this.cpAlphaChannel === 'disabled') {
        this.hsva.a = 1;
      }

      this.updateColorPicker(emit, update);
    }
  }

  public onResize(): void {
    if (this.position === 'fixed') {
      this.setDialogPosition();
    } else if (this.cpDialogDisplay !== 'inline') {
      this.closeColorPicker();
    }
  }

  public onDragEnd(slider: string): void {
    this.directiveInstance.sliderDragEnd({ slider: slider, color: this.outputColor });
  }

  public onDragStart(slider: string): void {
    this.directiveInstance.sliderDragStart({ slider: slider, color: this.outputColor });
  }

  public onMouseDown(event: MouseEvent): void {
    if (
      this.show &&
      !this.isIE10 &&
      this.cpDialogDisplay === 'popup' &&
      event.target !== this.directiveElementRef.nativeElement &&
      !this.isDescendant(this.elRef.nativeElement, event.target) &&
      !this.isDescendant(this.directiveElementRef.nativeElement, event.target) &&
      this.cpIgnoredElements.filter((item: any) => item === event.target).length === 0
    ) {
      this.ngZone.run(() => {
        if (this.cpSaveClickOutside) {
          this.directiveInstance.colorSelected(this.outputColor);
        } else {
          this.hsva = null;

          this.setColorFromString(this.initialColor, false);

          if (this.cpCmykEnabled) {
            this.directiveInstance.cmykChanged(this.cmykColor);
          }

          this.directiveInstance.colorChanged(this.initialColor);

          this.directiveInstance.colorCanceled();
        }

        if (this.cpCloseClickOutside) {
          this.closeColorPicker();
        }
      });
    }
  }

  public onAcceptColor(event: Event): void {
    event.stopPropagation();

    if (this.outputColor) {
      this.directiveInstance.colorSelected(this.outputColor);
    }

    if (this.cpDialogDisplay === 'popup') {
      this.closeColorPicker();
    }
  }

  public onCancelColor(event: Event): void {
    this.hsva = null;

    event.stopPropagation();

    this.directiveInstance.colorCanceled();

    this.setColorFromString(this.initialColor, true);

    if (this.cpDialogDisplay === 'popup') {
      if (this.cpCmykEnabled) {
        this.directiveInstance.cmykChanged(this.cmykColor);
      }

      this.directiveInstance.colorChanged(this.initialColor, true);

      this.closeColorPicker();
    }
  }

  public onEyeDropper(): void {
    if (!this.eyeDropperSupported) return;
    const eyeDropper = new (window as any).EyeDropper();
    eyeDropper.open().then((eyeDropperResult: {
      sRGBHex: string;
    }) => {
      this.setColorFromString(eyeDropperResult.sRGBHex, true);
    });
  }

  public onFormatToggle(change: number): void {
    const availableFormats = this.dialogInputFields.length -
      (this.cpCmykEnabled ? 0 : 1);

    const nextFormat = (((this.dialogInputFields.indexOf(this.format) + change) %
      availableFormats) + availableFormats) % availableFormats;

    this.format = this.dialogInputFields[nextFormat];
  }

  public onColorChange(value: { s: number, v: number, rgX: number, rgY: number }): void {
    this.hsva.s = value.s / value.rgX;
    this.hsva.v = value.v / value.rgY;

    this.updateColorPicker();

    this.directiveInstance.sliderChanged({
      slider: 'lightness',
      value: this.hsva.v,
      color: this.outputColor
    });

    this.directiveInstance.sliderChanged({
      slider: 'saturation',
      value: this.hsva.s,
      color: this.outputColor
    });
  }

  public onHueChange(value: { v: number, rgX: number }): void {
    this.hsva.h = value.v / value.rgX;
    this.sliderH = this.hsva.h;

    this.updateColorPicker();

    this.directiveInstance.sliderChanged({
      slider: 'hue',
      value: this.hsva.h,
      color: this.outputColor
    });
  }

  public onValueChange(value: { v: number, rgX: number }): void {
    this.hsva.v = value.v / value.rgX;

    this.updateColorPicker();

    this.directiveInstance.sliderChanged({
      slider: 'value',
      value: this.hsva.v,
      color: this.outputColor
    });
  }

  public onAlphaChange(value: { v: number, rgX: number }): void {
    this.hsva.a = value.v / value.rgX;

    this.updateColorPicker();

    this.directiveInstance.sliderChanged({
      slider: 'alpha',
      value: this.hsva.a,
      color: this.outputColor
    });
  }

  public onHexInput(value: string | null): void {
    if (value === null) {
      this.updateColorPicker();
    } else {
      if (value && value[0] !== '#') {
        value = '#' + value;
      }

      let validHex = /^#([a-f0-9]{3}|[a-f0-9]{6})$/gi;

      if (this.cpAlphaChannel === 'always') {
        validHex = /^#([a-f0-9]{3}|[a-f0-9]{6}|[a-f0-9]{8})$/gi;
      }

      const valid = validHex.test(value);

      if (valid) {
        if (value.length < 5) {
          value = '#' + value.substring(1)
            .split('')
            .map(c => c + c)
            .join('');
        }

        if (this.cpAlphaChannel === 'forced') {
          value += Math.round(this.hsva.a * 255).toString(16);
        }

        this.setColorFromString(value, true, false);
      }

      this.directiveInstance.inputChanged({
        input: 'hex',
        valid: valid,
        value: value,
        color: this.outputColor
      });
    }
  }

  public onRedInput(value: { v: number, rg: number }): void {
    const rgba = this.service.hsvaToRgba(this.hsva);

    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      rgba.r = value.v / value.rg;

      this.hsva = this.service.rgbaToHsva(rgba);

      this.sliderH = this.hsva.h;

      this.updateColorPicker();
    }

    this.directiveInstance.inputChanged({
      input: 'red',
      valid: valid,
      value: rgba.r,
      color: this.outputColor
    });
  }

  public onBlueInput(value: { v: number, rg: number }): void {
    const rgba = this.service.hsvaToRgba(this.hsva);

    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      rgba.b = value.v / value.rg;

      this.hsva = this.service.rgbaToHsva(rgba);

      this.sliderH = this.hsva.h;

      this.updateColorPicker();
    }

    this.directiveInstance.inputChanged({
      input: 'blue',
      valid: valid,
      value: rgba.b,
      color: this.outputColor
    });
  }

  public onGreenInput(value: { v: number, rg: number }): void {
    const rgba = this.service.hsvaToRgba(this.hsva);

    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      rgba.g = value.v / value.rg;

      this.hsva = this.service.rgbaToHsva(rgba);

      this.sliderH = this.hsva.h;

      this.updateColorPicker();
    }

    this.directiveInstance.inputChanged({
      input: 'green',
      valid: valid,
      value: rgba.g,
      color: this.outputColor
    });
  }

  public onHueInput(value: { v: number, rg: number }) {
    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      this.hsva.h = value.v / value.rg;

      this.sliderH = this.hsva.h;

      this.updateColorPicker();
    }

    this.directiveInstance.inputChanged({
      input: 'hue',
      valid: valid,
      value: this.hsva.h,
      color: this.outputColor
    });
  }

  public onValueInput(value: { v: number, rg: number }): void {
    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      this.hsva.v = value.v / value.rg;

      this.updateColorPicker();
    }

    this.directiveInstance.inputChanged({
      input: 'value',
      valid: valid,
      value: this.hsva.v,
      color: this.outputColor
    });
  }

  public onAlphaInput(value: { v: number, rg: number }): void {
    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      this.hsva.a = value.v / value.rg;

      this.updateColorPicker();
    }

    this.directiveInstance.inputChanged({
      input: 'alpha',
      valid: valid,
      value: this.hsva.a,
      color: this.outputColor
    });
  }

  public onLightnessInput(value: { v: number, rg: number }): void {
    const hsla = this.service.hsva2hsla(this.hsva);

    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      hsla.l = value.v / value.rg;

      this.hsva = this.service.hsla2hsva(hsla);

      this.sliderH = this.hsva.h;

      this.updateColorPicker();
    }

    this.directiveInstance.inputChanged({
      input: 'lightness',
      valid: valid,
      value: hsla.l,
      color: this.outputColor
    });
  }

  public onSaturationInput(value: { v: number, rg: number }): void {
    const hsla = this.service.hsva2hsla(this.hsva);

    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      hsla.s = value.v / value.rg;

      this.hsva = this.service.hsla2hsva(hsla);

      this.sliderH = this.hsva.h;

      this.updateColorPicker();
    }

    this.directiveInstance.inputChanged({
      input: 'saturation',
      valid: valid,
      value: hsla.s,
      color: this.outputColor
    });
  }

  public onCyanInput(value: { v: number, rg: number }): void {
    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      this.cmyk.c = value.v;

      this.updateColorPicker(false, true, true);
    }

    this.directiveInstance.inputChanged({
      input: 'cyan',
      valid: true,
      value: this.cmyk.c,
      color: this.outputColor
    });
  }

  public onMagentaInput(value: { v: number, rg: number }): void {
    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      this.cmyk.m = value.v;

      this.updateColorPicker(false, true, true);
    }

    this.directiveInstance.inputChanged({
      input: 'magenta',
      valid: true,
      value: this.cmyk.m,
      color: this.outputColor
    });
  }

  public onYellowInput(value: { v: number, rg: number }): void {
    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      this.cmyk.y = value.v;

      this.updateColorPicker(false, true, true);
    }

     this.directiveInstance.inputChanged({
      input: 'yellow',
      valid: true,
      value: this.cmyk.y,
      color: this.outputColor
    });
  }

  public onBlackInput(value: { v: number, rg: number }): void {
    const valid = !isNaN(value.v) && value.v >= 0 && value.v <= value.rg;

    if (valid) {
      this.cmyk.k = value.v;

      this.updateColorPicker(false, true, true);
    }

    this.directiveInstance.inputChanged({
      input: 'black',
      valid: true,
      value: this.cmyk.k,
      color: this.outputColor
    });
  }

  public onAddPresetColor(event: any, value: string): void {
    event.stopPropagation();

    if (!this.cpPresetColors.filter((color) => (color === value)).length) {
      this.cpPresetColors = this.cpPresetColors.concat(value);

      this.directiveInstance.presetColorsChanged(this.cpPresetColors);
    }
  }

  public onRemovePresetColor(event: any, value: string): void {
    event.stopPropagation();

    this.cpPresetColors = this.cpPresetColors.filter((color) => (color !== value));

    this.directiveInstance.presetColorsChanged(this.cpPresetColors);
  }

  // Private helper functions for the color picker dialog status

  private openColorPicker(): void {
    if (!this.show) {
      this.show = true;
      this.hidden = true;

      setTimeout(() => {
        this.hidden = false;

        this.setDialogPosition();

        this.cdRef.detectChanges();
      }, 0);

      this.directiveInstance.stateChanged(true);

      if (!this.isIE10) {
        // The change detection should be run on `mousedown` event only when the condition
        // is met within the `onMouseDown` method.
        this.ngZone.runOutsideAngular(() => {
          // There's no sense to add both event listeners on touch devices since the `touchstart`
          // event is handled earlier than `mousedown`, so we'll get 2 change detections and the
          // second one will be unnecessary.
          if (SUPPORTS_TOUCH) {
            document.addEventListener('touchstart', this.listenerMouseDown);
          } else {
            document.addEventListener('mousedown', this.listenerMouseDown);
          }
        });
      }

      window.addEventListener('resize', this.listenerResize);
    }
  }

  private closeColorPicker(): void {
    if (this.show) {
      this.show = false;

      this.directiveInstance.stateChanged(false);

      if (!this.isIE10) {
        if (SUPPORTS_TOUCH) {
          document.removeEventListener('touchstart', this.listenerMouseDown);
        } else {
          document.removeEventListener('mousedown', this.listenerMouseDown);
        }
      }

      window.removeEventListener('resize', this.listenerResize);

      if (!this.cdRef['destroyed']) {
        this.cdRef.detectChanges();
      }
    }
  }

  private updateColorPicker(emit: boolean = true, update: boolean = true, cmykInput: boolean = false): void {
    if (this.sliderDimMax) {
      if (this.cpColorMode === 2) {
        this.hsva.s = 0;
      }

      let hue: Rgba, hsla: Hsla, rgba: Rgba;

      const lastOutput = this.outputColor;

      hsla = this.service.hsva2hsla(this.hsva);

      if (!this.cpCmykEnabled) {
        rgba = this.service.denormalizeRGBA(this.service.hsvaToRgba(this.hsva));
      } else {
        if (!cmykInput) {
          rgba = this.service.hsvaToRgba(this.hsva);

          this.cmyk = this.service.denormalizeCMYK(this.service.rgbaToCmyk(rgba));
        } else {
          rgba = this.service.cmykToRgb(this.service.normalizeCMYK(this.cmyk));

          this.hsva = this.service.rgbaToHsva(rgba);
        }

        rgba = this.service.denormalizeRGBA(rgba);

        this.sliderH = this.hsva.h;
      }

      hue = this.service.denormalizeRGBA(this.service.hsvaToRgba(new Hsva(this.sliderH || this.hsva.h, 1, 1, 1)));

      if (update) {
        this.hslaText = new Hsla(Math.round((hsla.h) * 360), Math.round(hsla.s * 100), Math.round(hsla.l * 100),
          Math.round(hsla.a * 100) / 100);

        this.rgbaText = new Rgba(rgba.r, rgba.g, rgba.b, Math.round(rgba.a * 100) / 100);

        if (this.cpCmykEnabled) {
          this.cmykText = new Cmyk(this.cmyk.c, this.cmyk.m, this.cmyk.y, this.cmyk.k,
            Math.round(this.cmyk.a * 100) / 100);
        }

        const allowHex8 = this.cpAlphaChannel === 'always';

        this.hexText = this.service.rgbaToHex(rgba, allowHex8);
        this.hexAlpha = this.rgbaText.a;
      }

      if (this.cpOutputFormat === 'auto') {
        if (this.format !== ColorFormats.RGBA && this.format !== ColorFormats.CMYK && this.format !== ColorFormats.HSLA) {
          if (this.hsva.a < 1) {
            this.format = this.hsva.a < 1 ? ColorFormats.RGBA : ColorFormats.HEX;
          }
        }
      }

      this.hueSliderColor = 'rgb(' + hue.r + ',' + hue.g + ',' + hue.b + ')';
      this.alphaSliderColor = 'rgb(' + rgba.r + ',' + rgba.g + ',' + rgba.b + ')';

      this.outputColor = this.service.outputFormat(this.hsva, this.cpOutputFormat, this.cpAlphaChannel);
      this.selectedColor = this.service.outputFormat(this.hsva, 'rgba', null);

      if (this.format !== ColorFormats.CMYK) {
        this.cmykColor = '';
      } else {
        if (this.cpAlphaChannel === 'always' || this.cpAlphaChannel === 'enabled' ||
          this.cpAlphaChannel === 'forced')
        {
          const alpha = Math.round(this.cmyk.a * 100) / 100;

          this.cmykColor = `cmyka(${this.cmyk.c},${this.cmyk.m},${this.cmyk.y},${this.cmyk.k},${alpha})`;
        } else {
          this.cmykColor = `cmyk(${this.cmyk.c},${this.cmyk.m},${this.cmyk.y},${this.cmyk.k})`;
        }
      }

      this.slider = new SliderPosition(
        (this.sliderH || this.hsva.h) * this.sliderDimMax.h - 8,
        this.hsva.s * this.sliderDimMax.s - 8,
        (1 - this.hsva.v) * this.sliderDimMax.v - 8,
        this.hsva.a * this.sliderDimMax.a - 8
      );

      if (emit && lastOutput !== this.outputColor) {
        if (this.cpCmykEnabled) {
          this.directiveInstance.cmykChanged(this.cmykColor);
        }

        this.directiveInstance.colorChanged(this.outputColor);
      }
    }
  }

  // Private helper functions for the color picker dialog positioning

  private setDialogPosition(): void {
    if (this.cpDialogDisplay === 'inline') {
      this.position = 'relative';
    } else {
      let position = 'static', transform = '', style;

      let parentNode: any = null, transformNode: any = null;

      let node = this.directiveElementRef.nativeElement.parentNode;

      const dialogHeight = this.dialogElement.nativeElement.offsetHeight;

      while (node !== null && node.tagName !== 'HTML') {
        style = window.getComputedStyle(node);
        position = style.getPropertyValue('position');
        transform = style.getPropertyValue('transform');

        if (position !== 'static' && parentNode === null) {
          parentNode = node;
        }

        if (transform && transform !== 'none' && transformNode === null) {
          transformNode = node;
        }

        if (position === 'fixed') {
          parentNode = transformNode;

          break;
        }

        node = node.parentNode;
      }

      const boxDirective = this.createDialogBox(this.directiveElementRef.nativeElement, (position !== 'fixed'));

      if (this.useRootViewContainer || (position === 'fixed' &&
         (!parentNode || parentNode instanceof HTMLUnknownElement)))
      {
        this.top = boxDirective.top;
        this.left = boxDirective.left;
      } else {
        if (parentNode === null) {
          parentNode = node;
        }

        const boxParent = this.createDialogBox(parentNode, (position !== 'fixed'));

        this.top = boxDirective.top - boxParent.top;
        this.left = boxDirective.left - boxParent.left;
      }

      if (position === 'fixed') {
        this.position = 'fixed';
      }

      let usePosition = this.cpPosition;

      if (this.cpPosition === 'auto') {
        const dialogBounds = this.dialogElement.nativeElement.getBoundingClientRect();
        const triggerBounds = this.cpTriggerElement.nativeElement.getBoundingClientRect();
        usePosition = calculateAutoPositioning(dialogBounds, triggerBounds);
      }

      if (usePosition === 'top') {
        this.arrowTop = dialogHeight - 1;

        this.top -= dialogHeight + this.dialogArrowSize;
        this.left += this.cpPositionOffset / 100 * boxDirective.width - this.dialogArrowOffset;
      } else if (usePosition === 'bottom') {
        this.top += boxDirective.height + this.dialogArrowSize;
        this.left += this.cpPositionOffset / 100 * boxDirective.width - this.dialogArrowOffset;
      } else if (usePosition === 'top-left' || usePosition === 'left-top') {
        this.top -= dialogHeight - boxDirective.height + boxDirective.height * this.cpPositionOffset / 100;
        this.left -= this.cpWidth + this.dialogArrowSize - 2 - this.dialogArrowOffset;
      } else if (usePosition === 'top-right' || usePosition === 'right-top') {
        this.top -= dialogHeight - boxDirective.height + boxDirective.height * this.cpPositionOffset / 100;
        this.left += boxDirective.width + this.dialogArrowSize - 2 - this.dialogArrowOffset;
      } else if (usePosition === 'left' || usePosition === 'bottom-left' || usePosition === 'left-bottom') {
        this.top += boxDirective.height * this.cpPositionOffset / 100 - this.dialogArrowOffset;
        this.left -= this.cpWidth + this.dialogArrowSize - 2;
      } else { // usePosition === 'right' || usePosition === 'bottom-right' || usePosition === 'right-bottom'
        this.top += boxDirective.height * this.cpPositionOffset / 100 - this.dialogArrowOffset;
        this.left += boxDirective.width + this.dialogArrowSize - 2;
      }

      this.cpUsePosition = usePosition;
    }
  }

  // Private helper functions for the color picker dialog positioning and opening

  private isDescendant(parent: any, child: any): boolean {
    let node: any = child.parentNode;

    while (node !== null) {
      if (node === parent) {
        return true;
      }

      node = node.parentNode;
    }

    return false;
  }

  private createDialogBox(element: any, offset: boolean): any {
    const { top, left } = element.getBoundingClientRect();
    return {
      top: top + (offset ? window.pageYOffset : 0),
      left: left + (offset ? window.pageXOffset : 0),
      width: element.offsetWidth,
      height: element.offsetHeight
    };
  }
}


text:
import numpy

from chainer import cuda
from chainer import optimizer

_default_hyperparam = optimizer.Hyperparameter()
_default_hyperparam.rho = 0.95
_default_hyperparam.eps = 1e-6

class AdaDeltaRule(optimizer.UpdateRule):

    """Update rule of Zeiler's ADADELTA.

    See :class:`~chainer.optimizers.AdaDelta` for the default values of the
    hyperparameters.

    Args:
        parent_hyperparam (~chainer.optimizer.Hyperparameter): Hyperparameter
            that provides the default values.
        rho (float): Exponential decay rate of the first and second order
            moments.
        eps (float): Small value for the numerical stability.

    """

    def __init__(self, parent_hyperparam=None, rho=None, eps=None):
        super(AdaDeltaRule, self).__init__(
            parent_hyperparam or _default_hyperparam)
        if rho is not None:
            self.hyperparam.rho = rho
        if eps is not None:
            self.hyperparam.eps = eps

    def init_state(self, param):
        xp = cuda.get_array_module(param.data)
        with cuda.get_device_from_array(param.data):
            self.state['msg'] = xp.zeros_like(param.data)
            self.state['msdx'] = xp.zeros_like(param.data)

    def update_core_cpu(self, param):
        grad = param.grad
        if grad is None:
            return
        msg, msdx = self.state['msg'], self.state['msdx']
        rho = self.hyperparam.rho
        eps = self.hyperparam.eps

        msg *= rho
        msg += (1 - rho) * grad * grad
        dx = numpy.sqrt((msdx + eps) / (msg + eps)) * grad
        msdx *= rho
        msdx += (1 - rho) * dx * dx
        param.data -= dx

    def update_core_gpu(self, param):
        grad = param.grad
        if grad is None:
            return
        cuda.elementwise(
            'T grad, T one_minus_rho, T eps',
            'T param, T msg, T msdx',
            '''msg   = msg + one_minus_rho * (grad * grad - msg);
               T dx  = sqrt((msdx + eps) / (msg + eps)) * grad;
               msdx  += one_minus_rho * (dx * dx - msdx);
               param -= dx;''',
            'adadelta')(grad, 1 - self.hyperparam.rho,
                        self.hyperparam.eps, param.data,
                        self.state['msg'], self.state['msdx'])

class AdaDelta(optimizer.GradientMethod):

    """Zeiler's ADADELTA.

    See: http://www.matthewzeiler.com/pubs/googleTR2012/googleTR2012.pdf

    Args:
        rho (float): Exponential decay rate of the first and second order
            moments.
        eps (float): Small value for the numerical stability.

    """

    def __init__(self, rho=_default_hyperparam.rho,
                 eps=_default_hyperparam.eps):
        super(AdaDelta, self).__init__()
        self.hyperparam.rho = rho
        self.hyperparam.eps = eps

    rho = optimizer.HyperparameterProxy('rho')
    eps = optimizer.HyperparameterProxy('eps')

    def create_update_rule(self):
        return AdaDeltaRule(self.hyperparam)


text:
'''Module containing the Parser class for parsing expressions into ASTs.

The context-free grammar for the PyCalc language is as follows:

begin ::= (variable '=')* expr
expr ::= add_or_sub
add_or_sub ::= mul_or_div (('+'|'-') mul_or_div)*
mul_or_div ::= negative (('*'|'/') negative)*
negative ::= exponent | '-' negative
exponent ::= factorial | factorial '^' negative
factorial ::= atom ('!')*
atom ::= function | variable | int_number | float_number | enclosure
enclosure ::= parentheses | absolute_value
parentheses ::= '(' expr ')'
absolute_value ::= '|' expr '|'
function ::= <valid function name> enclosure
variable ::= <valid variable name>
int_number ::= <int>
float_number ::= <float>
'''
from lang import is_float, is_function, is_int, is_variable
from tokenizer import Tokenizer
from tree import BinaryOperation, UnaryFunction, Value, Variable

class ParseException(Exception):
    '''Exceptions raised during parsing'''
    def __init__(self, message, expression, token, start, end):
        self.message = message
        self.expression = expression
        self.token = token
        self.start = start
        self.end = end

    def __str__(self):
        return self.message

class Parser(object):
    '''Class for parsing expressions into ASTs.'''
    def __init__(self, illegal_vars, default_variable):
        self.illegal_vars = illegal_vars
        self.default_variable = default_variable

    def parse(self, line):
        '''Begin parsing the given line.'''
        # Start at the first grammar rule:
        # begin ::= (variable '=')* expression
        # Turn the line into variable names and an arithemtic expression.
        line = line.strip()
        *self.names, self.expression = line.split('=')
        self.expression = self.expression.strip()
        # remove whitespace, remove duplicates, and sort
        self.names = sorted(set((name.strip() for name in self.names)))
        # if no names are specified, use the default variable name
        self.names = [self.default_variable] if not self.names else self.names

        # Check that all variable names are valid
        for name in self.names:
            if not name:
                raise Exception('Illegal assignment: no variable or ' +
                                'expression specified.')
            if not is_variable(name) or name in self.illegal_vars:
                raise Exception('Illegal assignment: ' + name +
                                ' is not a valid variable name')

        # Parse expression according to grammar rules
        self.tokenizer = Tokenizer(self.expression)
        self.tree = self.expr()

        # the tokenizer should be out of tokens
        if self.tokenizer.has_next():
            token, start, end = next(self.tokenizer)
            message = 'Dangling tokens starting with ' + token
            raise ParseException(message, self.expression, token, start, end)

    # Everything below corresponds to the grammar rules described at the top.

    def expr(self):
        '''Rule:
        expr ::= add_or_sub'''
        return self.add_or_sub()

    def add_or_sub(self):
        '''Rule:
        add_or_sub ::= mul_or_div (("+"|"-") mul_or_div)*'''
        first_tree = self.mul_or_div()
        # Arrays for storing successive + or - operations and the tree args.
        ops = []
        trees = []
        # Run until no more + or -'s
        while True:
            if self.tokenizer.has_next():
                self.token, self.start, self.end = self.tokenizer.peek()
                if self.token in ('+', '-'):
                    # pop the token off the stack
                    next(self.tokenizer)
                    ops.append(self.token)
                    trees.append(self.mul_or_div())
                else:
                    break
            else:
                break
        if trees:
            # Combine the trees (left-associative)
            result_tree = first_tree
            for op, tree in zip(ops, trees):
                result_tree = BinaryOperation(op, result_tree, tree)
            return result_tree
        else:
            return first_tree

    def mul_or_div(self):
        '''Rule:
        mul_or_div ::= negative (("*"|"/") negative)*'''
        first_tree = self.negative()
        # Arrays for storing successive * or / operations and the tree args.
        ops = []
        trees = []
        # Run until no more * or /'s
        while True:
            if self.tokenizer.has_next():
                self.token, self.start, self.end = self.tokenizer.peek()
                if self.token in ('*', '/'):
                    # pop the token off the stack
                    next(self.tokenizer)
                    ops.append(self.token)
                    trees.append(self.negative())
                else:
                    break
            else:
                break
        if trees:
            # Combine the trees (left-associative)
            result_tree = first_tree
            for op, tree in zip(ops, trees):
                result_tree = BinaryOperation(op, result_tree, tree)
            return result_tree
        else:
            return first_tree

    def negative(self):
        '''Rule:
        negative ::= exponent | "-" negative'''
        if self.tokenizer.has_next():
            # Check for leading minus sign
            self.token, self.start, self.end = self.tokenizer.peek()
            if self.token == '-':
                next(self.tokenizer)
                tree = self.negative()
                return UnaryFunction('-', tree)
            else:
                return self.exponent()
            pass
        else:
            # There should still be tokens on the stack at this point.
            message = 'Expected token after ' + self.token
            expression = self.expression
            token = self.token
            start = self.start
            end = self.end
            raise ParseException(message, expression, token, start, end)

    def exponent(self):
        '''Rule:
        exponent ::= factorial | factorial "^" negative'''
        left_tree = self.factorial()
        if self.tokenizer.has_next():
            self.token, self.start, self.end = self.tokenizer.peek()
            if self.token == '^':
                next(self.tokenizer)
                right_tree = self.negative()
                return BinaryOperation('^', left_tree, right_tree)
        return left_tree

    def factorial(self):
        '''Rule:
        factorial ::= atom ("!")*'''
        first_tree = self.atom()
        num_factorial = 0
        # Run until no more !'s
        while True:
            if self.tokenizer.has_next():
                self.token, self.start, self.end = self.tokenizer.peek()
                if self.token == '!':
                    next(self.tokenizer)
                    num_factorial += 1
                else:
                    break
            else:
                break
        if num_factorial:
            result_tree = first_tree
            for _ in range(num_factorial):
                result_tree = UnaryFunction('!', result_tree)
            return result_tree
        else:
            return first_tree

    def atom(self):
        '''Rule:
        atom ::= function | variable | int_number | float_number | enclosure'''
        if self.tokenizer.has_next():
            self.token, self.start, self.end = self.tokenizer.peek()
            if is_function(self.token):
                return self.function()
            elif is_variable(self.token):
                return self.variable()
            elif is_int(self.token):
                return self.int_number()
            elif is_float(self.token):
                return self.float_number()
            else:
                return self.enclosure()
        else:
            # There should still be tokens on the stack at this point.
            message = 'Expected token after ' + self.token
            line = self.expression
            token = self.token
            start = self.start
            end = self.end
            raise ParseException(message, line, token, start, end)

    def enclosure(self):
        '''Rule:
        enclosure ::= parentheses | absolute_value'''
        if self.tokenizer.has_next():
            self.token, self.start, self.end = self.tokenizer.peek()
            if self.token == '(':
                # Pop the token off.
                next(self.tokenizer)
                return self.parentheses()
            elif self.token == '|':
                # Pop the token off.
                next(self.tokenizer)
                return self.absolute_value()
            else:
                message = 'Expected left delimiter, but found ' + self.token
                expression = self.expression
                token = self.token
                start = self.start
                end = self.end
                raise ParseException(message, expression, token, start, end)
        else:
            # There should still be tokens on the stack at this point.
            message = 'Expected delimited expression after ' + self.token
            expression = self.expression
            token = self.token
            start = self.start
            end = self.end
            raise ParseException(message, expression, token, start, end)

    def parentheses(self):
        '''Rule:
        parentheses ::= "(" expr ")"'''
        tree = self.expr()
        if self.tokenizer.has_next():
            token, start, end = self.tokenizer.peek()
            if token == ')':
                next(self.tokenizer)
                return tree
            else:
                error = 'Expected closing parenthesis, but found ' + token
                raise ParseException(error, self.expression, token, start, end)
        else:
            message = 'Expected closing parenthesis after ' + self.token
            expression = self.expression
            token = self.token
            start = self.start
            end = self.end
            raise ParseException(message, expression, token, start, end)

    def absolute_value(self):
        '''Rule:
        absolute_value ::= "|" expr "|"'''
        tree = self.expr()
        if self.tokenizer.has_next():
            token, start, end = self.tokenizer.peek()
            if token == '|':
                next(self.tokenizer)
                return UnaryFunction('abs', tree)
            else:
                error = 'Expected closing absolute value delimiter, '\
                    'but found ' + token
                raise ParseException(error, self.expression, token, start, end)
        else:
            message = 'Expected closing absolute value delimiter '\
                'after ' + self.token
            expression = self.expression
            token = self.token
            start = self.start
            end = self.end
            raise ParseException(message, expression, token, start, end)

    def function(self):
        '''Rule:
        function ::= <valid function name> enclosure'''
        token, _, _ = next(self.tokenizer)
        tree = self.enclosure()
        return UnaryFunction(token, tree)

    def variable(self):
        '''Rule:
        variable ::= <valid variable name>'''
        token, start, end = next(self.tokenizer)
        if token in self.illegal_vars:
            message = 'Illegal variable name: ' + token
            raise ParseException(message, self.expression, token, start, end)
        return Variable(token)

    def int_number(self):
        '''Rule:
        int_number ::= <int>'''
        token, _, _ = next(self.tokenizer)
        return Value(int(token))

    def float_number(self):
        '''Rule:
        float_number ::= <float>'''
        token, _, _ = next(self.tokenizer)
        return Value(float(token))


text:
#ifndef CONFIG_H
#define CONFIG_H
/*
 * config.h (for ANTLR, DLG, and SORCERER)
 *
 * This is a simple configuration file that doesn't have config stuff
 * in it, but it's a start.
 *
 * SOFTWARE RIGHTS
 *
 * We reserve no LEGAL rights to the Purdue Compiler Construction Tool
 * Set (PCCTS) -- PCCTS is in the public domain.  An individual or
 * company may do whatever they wish with source code distributed with
 * PCCTS or the code generated by PCCTS, including the incorporation of
 * PCCTS, or its output, into commerical software.
 *
 * We encourage users to develop software with PCCTS.  However, we do ask
 * that credit is given to us for developing PCCTS.  By "credit",
 * we mean that if you incorporate our source code into one of your
 * programs (commercial product, research project, or otherwise) that you
 * acknowledge this fact somewhere in the documentation, research report,
 * etc...  If you like PCCTS and have developed a nice tool with the
 * output, please mention that you developed it using PCCTS.  In
 * addition, we ask that this header remain intact in our source code.
 * As long as these guidelines are kept, we expect to continue enhancing
 * this system and expect to make other tools available as they are
 * completed.
 *
 * Used by PCCTS 1.33 (SORCERER 1.00B11 and up)
 * Terence Parr
 * Parr Research Corporation
 * with Purdue University and AHPCRC, University of Minnesota
 * 1989-1998
 */

/* This file knows about the following ``environments''
	UNIX (default)
	DOS  (use #define PC)
	MAC  (use #define MPW; has a few things for THINK C, Metrowerks)
 */

/* should test __STDC__ for 1, but some compilers don't set value, just def */
#ifdef __STDC__
#define __USE_PROTOS
#endif
#ifdef __cplusplus
#ifndef __USE_PROTOS
#define __USE_PROTOS
#endif
#endif

#include <stdlib.h>

/* largest file name size */

#ifdef _MAX_PATH
#define MaxFileName		_MAX_PATH /* MR9 RJV: MAX_PATH defined in stdlib.h (MSVC++ 5.0) */
#else
#define MaxFileName		300
#endif

/*
*  Define PC32 if in a 32-bit PC environment (e.g. extended DOS or Win32).
*  The macros tested here are defined by Watcom, Microsoft, Borland,
*  and djgpp, respectively, when they are used as 32-bit compilers.
*  Users of these compilers *must* be sure to define PC in their
*  makefiles for this to work correctly.
*/
#ifdef PC
# if (defined(__WATCOM__) || defined(_WIN32) || defined(__WIN32__) || \
   defined(__GNUC__) || defined(__GNUG__))
#     ifndef PC32
#        define PC32
#     endif
#  endif
#endif

/* MR1  10-Apr-97  Default for PC is short file names			            */
/* MR1		   Default for non-PC is long file names                		*/
/* MR1		   Can override via command line option LONGFILENAMES           */

#ifndef LONGFILENAMES
#ifndef PC
#define LONGFILENAMES
#endif
#endif

#ifndef LONGFILENAMES
#define ATOKEN_H			"AToken.h"
#define ATOKPTR_H			"ATokPtr.h"
#define ATOKPTR_C			"ATokPtr.cpp"
#define ATOKENBUFFER_H		"ATokBuf.h"
#define ATOKENBUFFER_C      "ATokBuf.cpp"
#define ATOKENSTREAM_H		"ATokStr.h"
#define APARSER_H			"AParser.h"
#define APARSER_C           "AParser.cpp"
#define ASTBASE_H			"ASTBase.h"
#define ASTBASE_C           "ASTBase.cpp"
#define PCCTSAST_C          "PCCTSAST.cpp"
#define LIST_C              "List.cpp"
#define DLEXERBASE_H		"DLexBase.h"
#define DLEXERBASE_C        "DLexBase.cpp"
#define DLEXER_C            "DLexer.cpp"
#define STREESUPPORT_C		"STreeSup.C"
#else
#define ATOKEN_H			"AToken.h"
#define ATOKPTR_H			"ATokPtr.h"
#define ATOKPTR_C			"ATokPtr.cpp"
#define ATOKENBUFFER_H		"ATokenBuffer.h"
#define ATOKENBUFFER_C		"ATokenBuffer.cpp"
#define ATOKENSTREAM_H		"ATokenStream.h"
#define APARSER_H			"AParser.h"
#define APARSER_C			"AParser.cpp"
#define ASTBASE_H			"ASTBase.h"
#define ASTBASE_C		    "ASTBase.cpp"
#define PCCTSAST_C			"PCCTSAST.cpp"
#define LIST_C				"List.cpp"
#define DLEXERBASE_H		"DLexerBase.h"
#define DLEXERBASE_C		"DLexerBase.cpp"
#define DLEXER_C			"DLexer.cpp"
#define STREESUPPORT_C		"STreeSupport.cpp"
#endif

/* SORCERER Stuff */

/* MR8 6-Aug-97     Change from ifdef PC to ifndef LONGFILENAMES            */

#ifndef LONGFILENAMES
#define STPARSER_H			"STreePar.h"
#define STPARSER_C			"STreePar.C"
#else
#define STPARSER_H			"STreeParser.h"
#define STPARSER_C			"STreeParser.cpp"
#endif

#ifdef MPW
#define CPP_FILE_SUFFIX		".cp"
#define CPP_FILE_SUFFIX_NO_DOT	"cp"
#define OBJ_FILE_SUFFIX		".o"
#else
#ifdef PC
#define CPP_FILE_SUFFIX		".cpp"
#define CPP_FILE_SUFFIX_NO_DOT	"cpp"
#define OBJ_FILE_SUFFIX		".obj"
#else
#ifdef __VMS
#define CPP_FILE_SUFFIX		".cpp"
#define CPP_FILE_SUFFIX_NO_DOT	"cpp"
#define OBJ_FILE_SUFFIX		".obj"
#else
#define CPP_FILE_SUFFIX		".cpp"
#define CPP_FILE_SUFFIX_NO_DOT	"cpp"
#define OBJ_FILE_SUFFIX		".o"
#endif
#endif
#endif

/* User may redefine how line information looks */     /* make it #line MR7 */
#define LineInfoFormatStr "#line %d \"%s\"\n"

#ifdef MPW		/* Macintosh Programmer's Workshop */
#define ErrHdr "File \"%s\"; Line %d #"
#else
#define ErrHdr "%s, line %d:"
#endif

/* must assume old K&R cpp here, can't use #if defined(..)... */

#ifdef MPW
#define TopDirectory	":"
#define DirectorySymbol	":"
#define OutputDirectoryOption "Directory where all output files should go (default=\":\")"
#else
#ifdef PC
#define TopDirectory	"."
#define DirectorySymbol	"\\"
#define OutputDirectoryOption "Directory where all output files should go (default=\".\")"
#else
#define TopDirectory	"."
#define DirectorySymbol	"/"
#define OutputDirectoryOption "Directory where all output files should go (default=\".\")"
#endif
#endif

#ifdef MPW

/* Make sure we have prototypes for all functions under MPW */

#include <string.h>
#include <stdlib.h>
/* MR6 2-Jun-97	Fixes false dependency caused by VC++ #include scanner	*/
/* MR6		   Reported by Brad Schick (schick@interaccess.com)	*/
#define	MPW_CursorCtl_Header <CursorCtl.h>
#include MPW_CursorCtl_Header
#ifdef __cplusplus
extern "C" {
#endif
extern void fsetfileinfo (char *filename, unsigned long newcreator, unsigned long newtype);
#ifdef __cplusplus
}
#endif

/* File creators for various popular development environments */

#define MAC_FILE_CREATOR 'MPS '   /* MPW Text files */
#if 0
#define MAC_FILE_CREATOR 'KAHL'   /* THINK C/Symantec C++ Text files */
#endif
#if 0
#define MAC_FILE_CREATOR 'MMCC'   /* Metrowerks C/C++ Text files */
#endif

#endif

#ifdef MPW
#define DAWDLE	SpinCursor(1)
#else
#define DAWDLE
#endif

#ifdef MPW
#define SPECIAL_INITS
#define SPECIAL_FOPEN
#endif

#ifdef MPW
#ifdef __cplusplus
inline
#else
static
#endif
void special_inits()
{
  InitCursorCtl((acurHandle) 0);
}
#endif

#ifdef MPW
#ifdef __cplusplus
inline
#else
static
#endif
void special_fopen_actions(char * /* s */)
{
  fsetfileinfo (s, MAC_FILE_CREATOR, 'TEXT');
}
#endif

/* Define usable bits for set.c stuff */
#define BytesPerWord	sizeof(unsigned)
#define	WORDSIZE		(sizeof(unsigned)*8)
#define LogWordSize     (WORDSIZE==16?4:5)

#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

#if defined(VAXC) || defined(__VMS)
#include <ssdef.h>
#define PCCTS_EXIT_SUCCESS 1
#define PCCTS_EXIT_FAILURE SS$_ABORT
#define zzDIE		return SS$_ABORT;
#define zzDONE	return 1;

#else /* !VAXC and !__VMS */

#define PCCTS_EXIT_SUCCESS 0
#define PCCTS_EXIT_FAILURE 1
#define zzDIE		return 1;
#define zzDONE	return 0;

#endif

#ifdef USER_ZZMODE_STACK
# ifndef ZZSTACK_MAX_MODE
#  define  ZZSTACK_MAX_MODE 32
# endif
# define  ZZMAXSTK (ZZSTACK_MAX_MODE * 2)
#endif

#endif


text:
namespace ConFuoco
{
	namespace
	{
		const size_t kAudioBufferSize = 2048;
		const size_t kFallbackBufferSize = 22050;
		const int kFallbackChannels = 1;
		const int kFallbackSampleRate = kFallbackBufferSize >> 1;
	}

	size_t AudioFile::CreateBuffer(char **buffer, const unsigned int channels)
	{
		const size_t size = kAudioBufferSize * channels;
		*buffer = new char[size];
		return size;
	}

	int AudioFile::channels_impl() const
	{
		return kFallbackChannels;
	}

	int AudioFile::rate_impl() const
	{
		return kFallbackSampleRate;
	}

	size_t AudioFile::read_impl(char **dst)
	{
		R_DEBUG("[Rainbow::ConFuoco] Loading fallback\n");

		*dst = new char[kFallbackBufferSize];
		memset(*dst, 0, kFallbackBufferSize);
		return kFallbackBufferSize;
	}

	size_t AudioFile::read_impl(char *dst, const size_t size)
	{
		memset(dst, 0, size);
		return size;
	}

	void AudioFile::rewind_impl() { }
}

#endif


text:
svg .flute-pressed {
	fill: red !important;
}


text:
class ViewController < UIViewController
  extend IB

  outlet :label, UILabel

  def viewWillAppear animated
    @counter = 0
    label.text = "Click the button"
  end

  def touch
    @counter += 1
    label.text = "Touched #{@counter} times"
  end

end


text:
#include "WelsFrameWork.h"

///////////////////////////////////////////////////////////////////////

WELSVP_NAMESPACE_BEGIN

EResult Init (void* pCtx, int32_t iType, void* pCfg) {
  return pCtx ? WelsStaticCast (IWelsVP*, pCtx)->Init (iType, pCfg) : RET_INVALIDPARAM;
}
EResult Uninit (void* pCtx, int32_t iType) {
  return pCtx ? WelsStaticCast (IWelsVP*, pCtx)->Uninit (iType) : RET_INVALIDPARAM;
}
EResult Flush (void* pCtx, int32_t iType) {
  return pCtx ? WelsStaticCast (IWelsVP*, pCtx)->Flush (iType) : RET_INVALIDPARAM;
}
EResult Process (void* pCtx, int32_t iType, SPixMap* pSrc, SPixMap* dst) {
  return pCtx ? WelsStaticCast (IWelsVP*, pCtx)->Process (iType, pSrc, dst) : RET_INVALIDPARAM;
}
EResult Get (void* pCtx, int32_t iType, void* pParam) {
  return pCtx ? WelsStaticCast (IWelsVP*, pCtx)->Get (iType, pParam) : RET_INVALIDPARAM;
}
EResult Set (void* pCtx, int32_t iType, void* pParam) {
  return pCtx ? WelsStaticCast (IWelsVP*, pCtx)->Set (iType, pParam) : RET_INVALIDPARAM;
}
EResult SpecialFeature (void* pCtx, int32_t iType, void* pIn, void* pOut) {
  return pCtx ? WelsStaticCast (IWelsVP*, pCtx)->SpecialFeature (iType, pIn, pOut) : RET_INVALIDPARAM;
}

///////////////////////////////////////////////////////////////////////////////

EResult CreateSpecificVpInterface (IWelsVPc** pCtx) {
  EResult  ret     = RET_FAILED;
  IWelsVP* pWelsVP = NULL;

  ret = CreateSpecificVpInterface (&pWelsVP);
  if (ret == RET_SUCCESS) {
    IWelsVPc* pVPc = new IWelsVPc;
    if (pVPc) {
      pVPc->Init    = Init;
      pVPc->Uninit  = Uninit;
      pVPc->Flush   = Flush;
      pVPc->Process = Process;
      pVPc->Get     = Get;
      pVPc->Set     = Set;
      pVPc->SpecialFeature = SpecialFeature;
      pVPc->pCtx       = WelsStaticCast (void*, pWelsVP);
      *pCtx            = pVPc;
    } else
      ret = RET_OUTOFMEMORY;
  }

  return ret;
}

EResult DestroySpecificVpInterface (IWelsVPc* pCtx) {
  if (pCtx) {
    DestroySpecificVpInterface (WelsStaticCast (IWelsVP*, pCtx->pCtx));
    _SafeDelete (pCtx);
  }

  return RET_SUCCESS;
}

WELSVP_NAMESPACE_END


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Bugman Lvl. 2"</title>
		<link>http://bvs.wikidot.com/forum/t-626329/bugman-lvl-2</link>
		<description>Posts in the discussion thread "Bugman Lvl. 2"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:36:20 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-626329#post-1980314</guid>
				<title>Numbers</title>
				<link>http://bvs.wikidot.com/forum/t-626329/bugman-lvl-2#post-1980314</link>
				<description></description>
				<pubDate>Fri, 28 Feb 2014 09:49:44 +0000</pubDate>
				<wikidot:authorName>tn5421</wikidot:authorName>				<wikidot:authorUserId>378091</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

The numbers reflected in bugman lvl2's eyes are from the Steins;Gate series. Maybe this could be used for future trivia?

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>