text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Component, Input, Optional, Injector, ViewChild } from '@angular/core';
import { Content, NavController } from 'ionic-angular';
import { CoreGroupInfo, CoreGroupsProvider } from '@providers/groups';
import { CoreTimeUtilsProvider } from '@providers/utils/time';
import { CoreCourseModuleMainActivityComponent } from '@core/course/classes/main-activity-component';
import { AddonModFeedbackProvider } from '../../providers/feedback';
import { AddonModFeedbackHelperProvider } from '../../providers/helper';
import { AddonModFeedbackOfflineProvider } from '../../providers/offline';
import { AddonModFeedbackSyncProvider } from '../../providers/sync';
import { CoreTabsComponent } from '@components/tabs/tabs';

/**
 * Component that displays a feedback index page.
 */
@Component({
    selector: 'addon-mod-feedback-index',
    templateUrl: 'addon-mod-feedback-index.html',
})
export class AddonModFeedbackIndexComponent extends CoreCourseModuleMainActivityComponent {
    @ViewChild(CoreTabsComponent) tabsComponent: CoreTabsComponent;

    @Input() tab = 'overview';
    @Input() group = 0;

    component = AddonModFeedbackProvider.COMPONENT;
    moduleName = 'feedback';

    access = {
        canviewreports: false,
        canviewanalysis: false,
        isempty: true
    };
    feedback: any;
    goPage: number;
    groupInfo: CoreGroupInfo = {
        groups: [],
        separateGroups: false,
        visibleGroups: false
    };
    items: any[];
    overview = {
        timeopen: 0,
        openTimeReadable: '',
        timeclose: 0,
        closeTimeReadable: ''
    };
    warning = '';
    tabsLoaded = {
        overview: false,
        analysis: false
    };
    showTabs = false;
    tabsReady = false;
    firstSelectedTab: number;

    protected submitObserver: any;
    protected syncEventName = AddonModFeedbackSyncProvider.AUTO_SYNCED;

    constructor(injector: Injector, private feedbackProvider: AddonModFeedbackProvider, @Optional() content: Content,
            private feedbackOffline: AddonModFeedbackOfflineProvider, private groupsProvider: CoreGroupsProvider,
            private feedbackSync: AddonModFeedbackSyncProvider, protected navCtrl: NavController,
            private feedbackHelper: AddonModFeedbackHelperProvider, private timeUtils: CoreTimeUtilsProvider) {
        super(injector, content);

        // Listen for form submit events.
        this.submitObserver = this.eventsProvider.on(AddonModFeedbackProvider.FORM_SUBMITTED, (data) => {
            if (this.feedback && data.feedbackId == this.feedback.id) {
                this.tabsLoaded['analysis'] = false;
                this.tabsLoaded['overview'] = false;
                this.loaded = false;

                let promise;

                // Prefetch data if needed.
                if (!data.offline && this.isPrefetched()) {
                    promise = this.feedbackSync.prefetchAfterUpdate(this.module, this.courseId).catch(() => {
                        // Ignore errors.
                    });
                } else {
                    promise = Promise.resolve();
                }

                promise.then(() => {
                    // Load the right tab.
                    if (data.tab != this.tab) {
                        this.tabChanged(data.tab);
                    } else {
                        this.loadContent(true);
                    }
                });
            }
        }, this.siteId);
    }

    /**
     * Component being initialized.
     */
    ngOnInit(): void {
        super.ngOnInit();

        this.loadContent(false, true).then(() => {
            this.feedbackProvider.logView(this.feedback.id, this.feedback.name).catch(() => {
                // Ignore errors.
            });
        }).finally(() => {
            this.tabsReady = true;
        });
    }

    /**
     * Perform the invalidate content function.
     *
     * @return {Promise<any>} Resolved when done.
     */
    protected invalidateContent(): Promise<any> {
        const promises = [];

        promises.push(this.feedbackProvider.invalidateFeedbackData(this.courseId));
        if (this.feedback) {
            promises.push(this.feedbackProvider.invalidateFeedbackAccessInformationData(this.feedback.id));
            promises.push(this.feedbackProvider.invalidateAnalysisData(this.feedback.id));
            promises.push(this.groupsProvider.invalidateActivityAllowedGroups(this.feedback.coursemodule));
            promises.push(this.groupsProvider.invalidateActivityGroupMode(this.feedback.coursemodule));
            promises.push(this.feedbackProvider.invalidateResumePageData(this.feedback.id));
        }

        this.tabsLoaded['analysis'] = false;
        this.tabsLoaded['overview'] = false;

        return Promise.all(promises);
    }

    /**
     * Compares sync event data with current data to check if refresh content is needed.
     *
     * @param {any} syncEventData Data receiven on sync observer.
     * @return {boolean}          True if refresh is needed, false otherwise.
     */
    protected isRefreshSyncNeeded(syncEventData: any): boolean {
        if (this.feedback && syncEventData.feedbackId == this.feedback.id) {
            // Refresh the data.
            this.domUtils.scrollToTop(this.content);

            return true;
        }

        return false;
    }

    /**
     * Download feedback contents.
     *
     * @param  {boolean}      [refresh=false]    If it's refreshing content.
     * @param  {boolean}      [sync=false]       If it should try to sync.
     * @param  {boolean}      [showErrors=false] If show errors to the user of hide them.
     * @return {Promise<any>} Promise resolved when done.
     */
    protected fetchContent(refresh: boolean = false, sync: boolean = false, showErrors: boolean = false): Promise<any> {
        return this.feedbackProvider.getFeedback(this.courseId, this.module.id).then((feedback) => {
            this.feedback = feedback;

            this.description = feedback.intro || feedback.description;
            this.dataRetrieved.emit(feedback);

            if (sync) {
                // Try to synchronize the feedback.
                return this.syncActivity(showErrors);
            }
        }).then(() => {
            // Check if there are answers stored in offline.
            return this.feedbackProvider.getFeedbackAccessInformation(this.feedback.id);
        }).then((accessData) => {
            this.access = accessData;
            this.showTabs = (accessData.canviewreports || accessData.canviewanalysis) && !accessData.isempty;

            this.firstSelectedTab = 0;
            if (this.tab == 'analysis') {
                this.firstSelectedTab = 1;

                return this.fetchFeedbackAnalysisData(this.access);
            }

            return this.fetchFeedbackOverviewData(this.access);
        }).finally(() => {
            // Now fill the context menu.
            this.fillContextMenu(refresh);

            // Check if there are responses stored in offline.
            return this.feedbackOffline.hasFeedbackOfflineData(this.feedback.id).then((hasOffline) => {
                this.hasOffline = hasOffline;
            });
        });
    }

    /**
     * Convenience function to get feedback overview data.
     *
     * @param {any} accessData Retrieved access data.
     * @return {Promise<any>}  Resolved when done.
     */
    protected fetchFeedbackOverviewData(accessData: any): Promise<any> {
        const promises = [];

        if (accessData.cancomplete && accessData.cansubmit && accessData.isopen) {
            promises.push(this.feedbackProvider.getResumePage(this.feedback.id).then((goPage) => {
                this.goPage = goPage > 0 ? goPage : false;
            }));
        }

        if (accessData.canedititems) {
            this.overview.timeopen = parseInt(this.feedback.timeopen) * 1000 || 0;
            this.overview.openTimeReadable = this.overview.timeopen ? this.timeUtils.userDate(this.overview.timeopen) : '';
            this.overview.timeclose = parseInt(this.feedback.timeclose) * 1000 || 0;
            this.overview.closeTimeReadable = this.overview.timeclose ? this.timeUtils.userDate(this.overview.timeclose) : '';
        }
        if (accessData.canviewanalysis) {
            // Get groups (only for teachers).
            promises.push(this.fetchGroupInfo(this.feedback.coursemodule));
        }

        return Promise.all(promises).finally(() => {
            this.tabsLoaded['overview'] = true;
        });
    }

    /**
     * Convenience function to get feedback analysis data.
     *
     * @param {any} accessData Retrieved access data.
     * @return {Promise<any>}  Resolved when done.
     */
    protected fetchFeedbackAnalysisData(accessData: any): Promise<any> {
        let promise;

        if (accessData.canviewanalysis) {
            // Get groups (only for teachers).
            promise = this.fetchGroupInfo(this.feedback.coursemodule);
        } else {
            this.tabChanged('overview');
            promise = Promise.resolve();
        }

        return promise.finally(() => {
            this.tabsLoaded['analysis'] = true;
        });
    }

    /**
     * Fetch Group info data.
     *
     * @param  {number}       cmId Course module ID.
     * @return {Promise<any>}      Resolved when done.
     */
    protected fetchGroupInfo(cmId: number): Promise<any> {
        return this.groupsProvider.getActivityGroupInfo(cmId).then((groupInfo) => {
            this.groupInfo = groupInfo;

            return this.setGroup(this.groupsProvider.validateGroupId(this.group, groupInfo));
        });
    }

    /**
     * Parse the analysis info to show the info correctly formatted.
     *
     * @param  {any} item Item to parse.
     * @return {any}      Parsed item.
     */
    protected parseAnalysisInfo(item: any): any {
        switch (item.typ) {
            case 'numeric':
                item.average = item.data.reduce((prev, current) => {
                    return prev + parseInt(current, 10);
                }, 0) / item.data.length;
                item.template = 'numeric';
                break;

            case 'info':
                item.data = item.data.map((dataItem) => {
                    dataItem = this.textUtils.parseJSON(dataItem);

                    return typeof dataItem.show != 'undefined' ? dataItem.show : false;
                }).filter((dataItem) => {
                    // Filter false entries.
                    return dataItem;
                });

            case 'textfield':
            case 'textarea':
                item.template = 'list';
                break;

            case 'multichoicerated':
            case 'multichoice':
                item.data = item.data.map((dataItem) => {
                    dataItem = this.textUtils.parseJSON(dataItem);

                    return typeof dataItem.answertext != 'undefined' ? dataItem : false;
                }).filter((dataItem) => {
                    // Filter false entries.
                    return dataItem;
                });

                // Format labels.
                item.labels = item.data.map((dataItem) => {
                    dataItem.quotient = (dataItem.quotient * 100).toFixed(2);
                    let label = '';

                    if (typeof dataItem.value != 'undefined') {
                        label = '(' + dataItem.value + ') ';
                    }
                    label += dataItem.answertext;
                    label += dataItem.quotient > 0 ? ' (' + dataItem.quotient + '%)' : '';

                    return label;
                });

                item.chartData = item.data.map((dataItem) => {
                    return dataItem.answercount;
                });

                if (item.typ == 'multichoicerated') {
                    item.average = item.data.reduce((prev, current) => {
                        return prev + parseFloat(current.avg);
                    }, 0.0);
                }

                const subtype = item.presentation.charAt(0);

                const single = subtype != 'c';
                item.chartType = single ? 'doughnut' : 'bar';

                item.template = 'chart';
                break;

            default:
               break;
        }

        return item;
    }

    /**
     * Function to go to the questions form.
     *
     * @param {boolean} preview Preview or edit the form.
     */
    gotoAnswerQuestions(preview: boolean = false): void {
        const stateParams = {
            module: this.module,
            moduleId: this.module.id,
            courseId: this.courseId,
            preview: preview
        };
        this.navCtrl.push('AddonModFeedbackFormPage', stateParams);
    }

    /**
     * User entered the page that contains the component.
     */
    ionViewDidEnter(): void {
        super.ionViewDidEnter();

        this.tabsComponent && this.tabsComponent.ionViewDidEnter();
    }

    /**
     * User left the page that contains the component.
     */
    ionViewDidLeave(): void {
        super.ionViewDidLeave();

        this.tabsComponent && this.tabsComponent.ionViewDidLeave();
    }

    /**
     * Function to link implemented features.
     *
     * @param {string} feature Feature to navigate.
     */
    openFeature(feature: string): void {
        this.feedbackHelper.openFeature(feature, this.navCtrl, this.module, this.courseId, this.group);
    }

    /**
     * Tab changed, fetch content again.
     *
     * @param {string} tabName New tab name.
     */
    tabChanged(tabName: string): void {
        this.tab = tabName;

        if (!this.tabsLoaded[this.tab]) {
            this.loadContent(false, false, true);
        }
    }

    /**
     * Set group to see the analysis.
     *
     * @param  {number}       groupId Group ID.
     * @return {Promise<any>}         Resolved when done.
     */
    setGroup(groupId: number): Promise<any> {
        this.group = groupId;

        return this.feedbackProvider.getAnalysis(this.feedback.id, groupId).then((analysis) => {
            this.feedback.completedCount = analysis.completedcount;
            this.feedback.itemsCount = analysis.itemscount;

            if (this.tab == 'analysis') {
                let num = 1;

                this.items = analysis.itemsdata.map((item) => {
                    // Move data inside item.
                    item.item.data = item.data;
                    item = item.item;
                    item.number = num++;
                    if (item.data && item.data.length) {
                        return this.parseAnalysisInfo(item);
                    }

                    return false;
                }).filter((item) => {
                    return item;
                });

                this.warning = '';
                if (analysis.warnings.length) {
                    const warning = analysis.warnings.find((warning) => {
                        return warning.warningcode == 'insufficientresponsesforthisgroup';
                    });
                    this.warning = warning && warning.message;
                }
            }
        });
    }

    /**
     * Performs the sync of the activity.
     *
     * @return {Promise<any>} Promise resolved when done.
     */
    protected sync(): Promise<any> {
        return this.feedbackSync.syncFeedback(this.feedback.id);
    }

    /**
     * Checks if sync has succeed from result sync data.
     *
     * @param  {any}     result Data returned on the sync function.
     * @return {boolean}        If suceed or not.
     */
    protected hasSyncSucceed(result: any): boolean {
        return result.updated;
    }

    /**
     * Component being destroyed.
     */
    ngOnDestroy(): void {
        super.ngOnDestroy();
        this.submitObserver && this.submitObserver.off();
    }
}


text:
/** @namespace decorators */
/** @flow */

import { GQLBase, META_KEY } from '../GQLBase'
import { dedent } from 'ne-tag-fns'

/**
 * Since the bulk functionality of @subscriptor, @mutator and
 * @resolver are almost identical, a single function can serve
 * the bulk of the functionality needed since they are so similar
 * in nature.
 *
 * @method decorators~decorate
 * @param {string} metaProperty the name of the meta sub key under which to
 * store the modified decorated function.
 * @param {Object|Function} target either the Class itself, if defined
 * on a static method, or the prototype if defined on an instance method
 * @param {string} key the property name of the function being decorated
 * @param {Object} descriptor a decorator descriptor; see
 * `Object.defineProperty` for more information on descriptors
 */
function decorate(
  metaProperty: string,
  target: Object | Function,
  key: string,
  descriptor: Object
): Object {
  const Class = typeof target === 'function' ? target : target.constructor;
  const proto = typeof target === 'function' ? target.prototype : target;
  const isClass = Class === target;
  let fn: Function = descriptor.value;

  if (!Class instanceof GQLBase) {
    console.warn(dedent`
      Ignoring the transformation of @resolver for ${fn && fn.name || key}.
      The reason for this is that ${Class.name} is not an instance of GQLBase.
    `)

    return descriptor
  }

  if (
    !descriptor.value
    || (descriptor.get || descriptor.set || descriptor.initializer)
  ) {
    console.warn(dedent`
      Ignoring the transformation of @resolver for ${fn && fn.name || key}. The
      reason for this is that it should only be applied to a static or instance
      method of a class. It is not valid to apply this to a getter, setter,
      or property.
    `)

    return descriptor
  }

  // Remove the function from wherever it happens to be defined.
  delete target[key];
  delete descriptor.value;

  if (isClass) {
    delete proto[key]
  }
  else {
    delete Class[key]
  }

  // Obtain a reference to the metadata storage area and create the resolver
  // portion if it does not yet exist.
  Class[META_KEY][metaProperty] = Class[META_KEY][metaProperty] || []

  // Ensure that the function name matches the key, if not, wrap it
  // such that future uses of the .name property match the key of the
  // decorated function
  if (fn.name !== key) {
    Object.defineProperty(fn, 'name', { get: function() { return key } })
  }

  // Store the key by name, overwritting if necessary, and assign the function
  Class[META_KEY][metaProperty].push(fn)

  // Pass the decorated function along for others to consume
  descriptor[Symbol.for(metaProperty)] = fn

  // Return a new decorator descriptor without the value function
  return descriptor;
}

/**
 * The resolver function should perform the necessary insertion to place
 * the decorated function in question into a place that it can be merged
 * with the final list of query resolvers. Typically a resolver function,
 * as defined in `RESOLVERS()` receives a `requestData` object. Functions
 * decorated with `@resolver` receive this as their first parameter. Code
 * accordingly.
 *
 * @method 🏷⠀decorators~resolver
 * @param {Object|Function} target either the Class itself, if defined
 * on a static method, or the prototype if defined on an instance method
 * @param {string} key the property name of the function being decorated
 * @param {Object} descriptor a decorator descriptor; see
 * `Object.defineProperty` for more information on descriptors
 */
export function resolver(
  target: Object | Function,
  key: string,
  descriptor: Object
): Object {
  return decorate('resolvers', target, key, descriptor)
}

/**
 * The mutator function should perform the necessary insertion to place
 * the decorated function in question into a place that it can be merged
 * with the final list of query resolvers. Typically a mutator function,
 * as defined in `RESOLVERS()` receives a `requestData` object. Functions
 * decorated with `@mutator` receive this as their first parameter. Code
 * accordingly.
 *
 * @method 🏷⠀decorators~mutator
 * @param {Object|Function} target either the Class itself, if defined
 * on a static method, or the prototype if defined on an instance method
 * @param {string} key the property name of the function being decorated
 * @param {Object} descriptor a decorator descriptor; see
 * `Object.defineProperty` for more information on descriptors
 */
export function mutator(
  target: Object | Function,
  key: string,
  descriptor: Object
): Object {
  return decorate('mutators', target, key, descriptor)
}

/**
 * The subscriptor function should perform the necessary insertion to place
 * the decorated function in question into a place that it can be merged
 * with the final list of query resolvers. Typically a subscriptor function,
 * as defined in `RESOLVERS()` receives a `requestData` object. Functions
 * decorated with `@subscriptor` receive this as their first parameter.
 * Code accordingly.
 *
 * @method 🏷⠀decorators~subscriptor
 * @param {Object|Function} target either the Class itself, if defined
 * on a static method, or the prototype if defined on an instance method
 * @param {string} key the property name of the function being decorated
 * @param {Object} descriptor a decorator descriptor; see
 * `Object.defineProperty` for more information on descriptors
 */
export function subscriptor(
  target: Object | Function,
  key: string,
  descriptor: Object
): Object {
  return decorate('subscriptors', target, key, descriptor)
}

redpajama_set_name: RedPajamaGithub


text:
import { span, i, div } from 'utils/selection';
import { Dropdown } from 'components/dropdown';

function tooltip({ icon, label, text } = {}) {
  if (!text) {
    throw new Error('tooltip: No text provided for the tooltip');
  }

  if (icon && label) {
    throw new Error('tooltip: You can only use an icon or a label when creating a tooltip');
  }

  const tooltipParent = span(label ? 'hx-tooltip-label' : 'hx-tooltip-icon');
  const iconElement = icon ? i(icon) : undefined;

  tooltipParent.text(label);
  tooltipParent.add(iconElement);

  const ddText = div().text(text);

  const ddClass = icon
    ? 'hx-tooltip hx-tooltip-from-icon'
    : 'hx-tooltip hx-tooltip-from-label';

  new Dropdown(tooltipParent, ddText,
    {
      ddClass,
      align: 'up',
      mode: 'hover',
      matchWidth: false,
    });

  return tooltipParent;
}

export { tooltip };


text: Chrome Extension: Look up words in OALD


text:
/* $Revision: 840 $                           */
/* $Date: 2005-01-10 01:30:06 -0300 (Mon, 10 Jan 2005) $               */

/* Update jiveVersion to JM 2.4 */
UPDATE jiveVersion SET majorVersion=2, minorVersion=4;

/* jiveGroupUser: Alter length of username column */
ALTER TABLE jiveGroupUser ALTER COLUMN username NVARCHAR(100) NOT NULL;


text:
/* TODO: update notes in header above */

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "tiffio.h"
#include "tif_ovrcache.h"

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

#ifndef MAX
#  define MIN(a,b)      ((a<b) ? a : b)
#  define MAX(a,b)      ((a>b) ? a : b)
#endif

void TIFFBuildOverviews( TIFF *, int, int *, int, const char *,
                         int (*)(double,void*), void * );

/************************************************************************/
/*                         TIFF_WriteOverview()                         */
/*                                                                      */
/*      Create a new directory, without any image data for an overview. */
/*      Returns offset of newly created overview directory, but the     */
/*      current directory is reset to be the one in used when this      */
/*      function is called.                                             */
/************************************************************************/

uint32 TIFF_WriteOverview( TIFF *hTIFF, uint32 nXSize, uint32 nYSize,
                           int nBitsPerPixel, int nPlanarConfig, int nSamples,
                           int nBlockXSize, int nBlockYSize,
                           int bTiled, int nCompressFlag, int nPhotometric,
                           int nSampleFormat,
                           unsigned short *panRed,
                           unsigned short *panGreen,
                           unsigned short *panBlue,
                           int bUseSubIFDs,
                           int nHorSubsampling, int nVerSubsampling )

{
    toff_t	nBaseDirOffset;
    toff_t	nOffset;

    (void) bUseSubIFDs;

    nBaseDirOffset = TIFFCurrentDirOffset( hTIFF );

    TIFFCreateDirectory( hTIFF );

/* -------------------------------------------------------------------- */
/*      Setup TIFF fields.                                              */
/* -------------------------------------------------------------------- */
    TIFFSetField( hTIFF, TIFFTAG_IMAGEWIDTH, nXSize );
    TIFFSetField( hTIFF, TIFFTAG_IMAGELENGTH, nYSize );
    if( nSamples == 1 )
        TIFFSetField( hTIFF, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG );
    else
        TIFFSetField( hTIFF, TIFFTAG_PLANARCONFIG, nPlanarConfig );

    TIFFSetField( hTIFF, TIFFTAG_BITSPERSAMPLE, nBitsPerPixel );
    TIFFSetField( hTIFF, TIFFTAG_SAMPLESPERPIXEL, nSamples );
    TIFFSetField( hTIFF, TIFFTAG_COMPRESSION, nCompressFlag );
    TIFFSetField( hTIFF, TIFFTAG_PHOTOMETRIC, nPhotometric );
    TIFFSetField( hTIFF, TIFFTAG_SAMPLEFORMAT, nSampleFormat );

    if( bTiled )
    {
        TIFFSetField( hTIFF, TIFFTAG_TILEWIDTH, nBlockXSize );
        TIFFSetField( hTIFF, TIFFTAG_TILELENGTH, nBlockYSize );
    }
    else
        TIFFSetField( hTIFF, TIFFTAG_ROWSPERSTRIP, nBlockYSize );

    TIFFSetField( hTIFF, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE );

    if( nPhotometric == PHOTOMETRIC_YCBCR || nPhotometric == PHOTOMETRIC_ITULAB )
    {
        TIFFSetField( hTIFF, TIFFTAG_YCBCRSUBSAMPLING, nHorSubsampling, nVerSubsampling);
        /* TODO: also write YCbCrPositioning and YCbCrCoefficients tag identical to source IFD */
    }
    /* TODO: add command-line parameter for selecting jpeg compression quality
     * that gets ignored when compression isn't jpeg */

/* -------------------------------------------------------------------- */
/*	Write color table if one is present.				*/
/* -------------------------------------------------------------------- */
    if( panRed != NULL )
    {
        TIFFSetField( hTIFF, TIFFTAG_COLORMAP, panRed, panGreen, panBlue );
    }

/* -------------------------------------------------------------------- */
/*      Write directory, and return byte offset.                        */
/* -------------------------------------------------------------------- */
    if( TIFFWriteCheck( hTIFF, bTiled, "TIFFBuildOverviews" ) == 0 )
        return 0;

    TIFFWriteDirectory( hTIFF );
    TIFFSetDirectory( hTIFF, (tdir_t) (TIFFNumberOfDirectories(hTIFF)-1) );

    nOffset = TIFFCurrentDirOffset( hTIFF );

    TIFFSetSubDirectory( hTIFF, nBaseDirOffset );

    return nOffset;
}

/************************************************************************/
/*                       TIFF_GetSourceSamples()                        */
/************************************************************************/

static void
TIFF_GetSourceSamples( double * padfSamples, unsigned char *pabySrc,
                       int nPixelBytes, int nSampleFormat,
                       uint32 nXSize, uint32 nYSize,
                       int nPixelOffset, int nLineOffset )
{
    uint32  iXOff, iYOff;
    int     iSample;

    iSample = 0;

    for( iYOff = 0; iYOff < nYSize; iYOff++ )
    {
        for( iXOff = 0; iXOff < nXSize; iXOff++ )
        {
            unsigned char *pabyData;

            pabyData = pabySrc + iYOff * nLineOffset + iXOff * nPixelOffset;

            if( nSampleFormat == SAMPLEFORMAT_UINT && nPixelBytes == 1 )
            {
                padfSamples[iSample++] = *pabyData;
            }
            else if( nSampleFormat == SAMPLEFORMAT_UINT && nPixelBytes == 2 )
            {
                padfSamples[iSample++] = ((uint16 *) pabyData)[0];
            }
            else if( nSampleFormat == SAMPLEFORMAT_UINT && nPixelBytes == 4 )
            {
                padfSamples[iSample++] = ((uint32 *) pabyData)[0];
            }
            else if( nSampleFormat == SAMPLEFORMAT_INT && nPixelBytes == 2 )
            {
                padfSamples[iSample++] = ((int16 *) pabyData)[0];
            }
            else if( nSampleFormat == SAMPLEFORMAT_INT && nPixelBytes == 32 )
            {
                padfSamples[iSample++] = ((int32 *) pabyData)[0];
            }
            else if( nSampleFormat == SAMPLEFORMAT_IEEEFP && nPixelBytes == 4 )
            {
                padfSamples[iSample++] = ((float *) pabyData)[0];
            }
            else if( nSampleFormat == SAMPLEFORMAT_IEEEFP && nPixelBytes == 8 )
            {
                padfSamples[iSample++] = ((double *) pabyData)[0];
            }
        }
    }
}

/************************************************************************/
/*                           TIFF_SetSample()                           */
/************************************************************************/

static void
TIFF_SetSample( unsigned char * pabyData, int nPixelBytes, int nSampleFormat,
                double dfValue )

{
    if( nSampleFormat == SAMPLEFORMAT_UINT && nPixelBytes == 1 )
    {
        *pabyData = (unsigned char) MAX(0,MIN(255,dfValue));
    }
    else if( nSampleFormat == SAMPLEFORMAT_UINT && nPixelBytes == 2 )
    {
        *((uint16 *)pabyData) = (uint16) MAX(0,MIN(65535,dfValue));
    }
    else if( nSampleFormat == SAMPLEFORMAT_UINT && nPixelBytes == 4 )
    {
        *((uint32 *)pabyData) = (uint32) dfValue;
    }
    else if( nSampleFormat == SAMPLEFORMAT_INT && nPixelBytes == 2 )
    {
        *((int16 *)pabyData) = (int16) MAX(-32768,MIN(32767,dfValue));
    }
    else if( nSampleFormat == SAMPLEFORMAT_INT && nPixelBytes == 32 )
    {
        *((int32 *)pabyData) = (int32) dfValue;
    }
    else if( nSampleFormat == SAMPLEFORMAT_IEEEFP && nPixelBytes == 4 )
    {
        *((float *)pabyData) = (float) dfValue;
    }
    else if( nSampleFormat == SAMPLEFORMAT_IEEEFP && nPixelBytes == 8 )
    {
        *((double *)pabyData) = dfValue;
    }
}

/************************************************************************/
/*                          TIFF_DownSample()                           */
/*                                                                      */
/*      Down sample a tile of full res data into a window of a tile     */
/*      of downsampled data.                                            */
/************************************************************************/

static
void TIFF_DownSample( unsigned char *pabySrcTile,
                      uint32 nBlockXSize, uint32 nBlockYSize,
                      int nPixelSkewBits, int nBitsPerPixel,
                      unsigned char * pabyOTile,
                      uint32 nOBlockXSize, uint32 nOBlockYSize,
                      uint32 nTXOff, uint32 nTYOff, int nOMult,
                      int nSampleFormat, const char * pszResampling )

{
    uint32	i, j;
    int         k, nPixelBytes = (nBitsPerPixel) / 8;
    int		nPixelGroupBytes = (nBitsPerPixel+nPixelSkewBits)/8;
    unsigned char *pabySrc, *pabyDst;
    double      *padfSamples;

    assert( nBitsPerPixel >= 8 );

    padfSamples = (double *) malloc(sizeof(double) * nOMult * nOMult);

/* ==================================================================== */
/*      Loop over scanline chunks to process, establishing where the    */
/*      data is going.                                                  */
/* ==================================================================== */
    for( j = 0; j*nOMult < nBlockYSize; j++ )
    {
        if( j + nTYOff >= nOBlockYSize )
            break;

        pabyDst = pabyOTile + ((j+nTYOff)*nOBlockXSize + nTXOff)
            * nPixelBytes * nPixelGroupBytes;

/* -------------------------------------------------------------------- */
/*      Handler nearest resampling ... we don't even care about the     */
/*      data type, we just do a bytewise copy.                          */
/* -------------------------------------------------------------------- */
        if( strncmp(pszResampling,"nearest",4) == 0
            || strncmp(pszResampling,"NEAR",4) == 0 )
        {
            pabySrc = pabySrcTile + j*nOMult*nBlockXSize * nPixelGroupBytes;

            for( i = 0; i*nOMult < nBlockXSize; i++ )
            {
                if( i + nTXOff >= nOBlockXSize )
                    break;

                /*
                 * For now use simple subsampling, from the top left corner
                 * of the source block of pixels.
                 */

                for( k = 0; k < nPixelBytes; k++ )
                    pabyDst[k] = pabySrc[k];

                pabyDst += nPixelBytes * nPixelGroupBytes;
                pabySrc += nOMult * nPixelGroupBytes;
            }
        }

/* -------------------------------------------------------------------- */
/*      Handle the case of averaging.  For this we also have to         */
/*      handle each sample format we are concerned with.                */
/* -------------------------------------------------------------------- */
        else if( strncmp(pszResampling,"averag",6) == 0
                 || strncmp(pszResampling,"AVERAG",6) == 0 )
        {
            pabySrc = pabySrcTile + j*nOMult*nBlockXSize * nPixelGroupBytes;

            for( i = 0; i*nOMult < nBlockXSize; i++ )
            {
                double   dfTotal;
                uint32   nXSize, nYSize, iSample;

                if( i + nTXOff >= nOBlockXSize )
                    break;

                nXSize = MIN((uint32)nOMult,nBlockXSize-i);
                nYSize = MIN((uint32)nOMult,nBlockYSize-j);

                TIFF_GetSourceSamples( padfSamples, pabySrc,
                                       nPixelBytes, nSampleFormat,
                                       nXSize, nYSize,
                                       nPixelGroupBytes,
                                       nPixelGroupBytes * nBlockXSize );

                dfTotal = 0;
                for( iSample = 0; iSample < nXSize*nYSize; iSample++ )
                {
                    dfTotal += padfSamples[iSample];
                }

                TIFF_SetSample( pabyDst, nPixelBytes, nSampleFormat,
                                dfTotal / (nXSize*nYSize) );

                pabySrc += nOMult * nPixelGroupBytes;
                pabyDst += nPixelBytes;
            }
        }
    }

    free( padfSamples );
}

/************************************************************************/
/*                     TIFF_DownSample_Subsampled()                     */
/************************************************************************/
static
void TIFF_DownSample_Subsampled( unsigned char *pabySrcTile, int nSample,
                                 uint32 nBlockXSize, uint32 nBlockYSize,
                                 unsigned char * pabyOTile,
                                 uint32 nOBlockXSize, uint32 nOBlockYSize,
                                 uint32 nTXOff, uint32 nTYOff, int nOMult,
                                 const char *pszResampling,
                                 int nHorSubsampling, int nVerSubsampling )
{
    /* TODO: test with variety of subsampling values, and incovinient tile/strip sizes */
    int nSampleBlockSize;
    int nSourceSampleRowSize;
    int nDestSampleRowSize;
    uint32  nSourceX, nSourceY;
    uint32  nSourceXSec, nSourceYSec;
    uint32  nSourceXSecEnd, nSourceYSecEnd;
    uint32  nDestX, nDestY;
    int nSampleOffsetInSampleBlock;
    unsigned int nCummulator;
    unsigned int nCummulatorCount;

    nSampleBlockSize = nHorSubsampling * nVerSubsampling + 2;
    nSourceSampleRowSize =
        ( ( nBlockXSize + nHorSubsampling - 1 ) / nHorSubsampling ) * nSampleBlockSize;
    nDestSampleRowSize =
        ( ( nOBlockXSize + nHorSubsampling - 1 ) / nHorSubsampling ) * nSampleBlockSize;

    if( strncmp(pszResampling,"nearest",4) == 0
        || strncmp(pszResampling,"NEAR",4) == 0 )
    {
    	if( nSample == 0 )
        {
            for( nSourceY = 0, nDestY = nTYOff;
                 nSourceY < nBlockYSize;
                 nSourceY += nOMult, nDestY ++)
            {
                if( nDestY >= nOBlockYSize )
                    break;

                for( nSourceX = 0, nDestX = nTXOff;
                     nSourceX < nBlockXSize;
                     nSourceX += nOMult, nDestX ++)
                {
                    if( nDestX >= nOBlockXSize )
                        break;

                    * ( pabyOTile + ( nDestY / nVerSubsampling ) * nDestSampleRowSize
                        + ( nDestY % nVerSubsampling ) * nHorSubsampling
                        + ( nDestX / nHorSubsampling ) * nSampleBlockSize
                        + ( nDestX % nHorSubsampling ) ) =
                        * ( pabySrcTile + ( nSourceY / nVerSubsampling ) * nSourceSampleRowSize
                            + ( nSourceY % nVerSubsampling ) * nHorSubsampling
                            + ( nSourceX / nHorSubsampling ) * nSampleBlockSize
                            + ( nSourceX % nHorSubsampling ) );
                }
            }
        }
        else
        {
            nSampleOffsetInSampleBlock = nHorSubsampling * nVerSubsampling + nSample - 1;
            for( nSourceY = 0, nDestY = ( nTYOff / nVerSubsampling );
                 nSourceY < ( nBlockYSize / nVerSubsampling );
                 nSourceY += nOMult, nDestY ++)
            {
                if( nDestY*nVerSubsampling >= nOBlockYSize )
                    break;

            	for( nSourceX = 0, nDestX = ( nTXOff / nHorSubsampling );
                     nSourceX < ( nBlockXSize / nHorSubsampling );
                     nSourceX += nOMult, nDestX ++)
                {
                    if( nDestX*nHorSubsampling >= nOBlockXSize )
                        break;

                    * ( pabyOTile + nDestY * nDestSampleRowSize
                        + nDestX * nSampleBlockSize
                        + nSampleOffsetInSampleBlock ) =
                    	* ( pabySrcTile + nSourceY * nSourceSampleRowSize
                            + nSourceX * nSampleBlockSize
                            + nSampleOffsetInSampleBlock );
                }
            }
        }
    }
    else if( strncmp(pszResampling,"averag",6) == 0
             || strncmp(pszResampling,"AVERAG",6) == 0 )
    {
    	if( nSample == 0 )
        {
            for( nSourceY = 0, nDestY = nTYOff; nSourceY < nBlockYSize; nSourceY += nOMult, nDestY ++)
            {
                if( nDestY >= nOBlockYSize )
                    break;

                for( nSourceX = 0, nDestX = nTXOff; nSourceX < nBlockXSize; nSourceX += nOMult, nDestX ++)
                {
                    if( nDestX >= nOBlockXSize )
                        break;

                    nSourceXSecEnd = nSourceX + nOMult;
                    if( nSourceXSecEnd > nBlockXSize )
                        nSourceXSecEnd = nBlockXSize;
                    nSourceYSecEnd = nSourceY + nOMult;
                    if( nSourceYSecEnd > nBlockYSize )
                        nSourceYSecEnd = nBlockYSize;
                    nCummulator = 0;
                    for( nSourceYSec = nSourceY; nSourceYSec < nSourceYSecEnd; nSourceYSec ++)
                    {
                        for( nSourceXSec = nSourceX; nSourceXSec < nSourceXSecEnd; nSourceXSec ++)
                        {
                            nCummulator += * ( pabySrcTile + ( nSourceYSec / nVerSubsampling ) * nSourceSampleRowSize
                                               + ( nSourceYSec % nVerSubsampling ) * nHorSubsampling
                                               + ( nSourceXSec / nHorSubsampling ) * nSampleBlockSize
                                               + ( nSourceXSec % nHorSubsampling ) );
                        }
                    }
                    nCummulatorCount = ( nSourceXSecEnd - nSourceX ) * ( nSourceYSecEnd - nSourceY );
                    * ( pabyOTile + ( nDestY / nVerSubsampling ) * nDestSampleRowSize
                        + ( nDestY % nVerSubsampling ) * nHorSubsampling
                        + ( nDestX / nHorSubsampling ) * nSampleBlockSize
                        + ( nDestX % nHorSubsampling ) ) =
                        ( ( nCummulator + ( nCummulatorCount >> 1 ) ) / nCummulatorCount );
                }
            }
        }
        else
        {
            nSampleOffsetInSampleBlock = nHorSubsampling * nVerSubsampling + nSample - 1;
            for( nSourceY = 0, nDestY = ( nTYOff / nVerSubsampling ); nSourceY < ( nBlockYSize / nVerSubsampling );
                 nSourceY += nOMult, nDestY ++)
            {
                if( nDestY*nVerSubsampling >= nOBlockYSize )
                    break;

                for( nSourceX = 0, nDestX = ( nTXOff / nHorSubsampling ); nSourceX < ( nBlockXSize / nHorSubsampling );
                     nSourceX += nOMult, nDestX ++)
                {
                    if( nDestX*nHorSubsampling >= nOBlockXSize )
                        break;

                    nSourceXSecEnd = nSourceX + nOMult;
                    if( nSourceXSecEnd > ( nBlockXSize / nHorSubsampling ) )
                        nSourceXSecEnd = ( nBlockXSize / nHorSubsampling );
                    nSourceYSecEnd = nSourceY + nOMult;
                    if( nSourceYSecEnd > ( nBlockYSize / nVerSubsampling ) )
                        nSourceYSecEnd = ( nBlockYSize / nVerSubsampling );
                    nCummulator = 0;
                    for( nSourceYSec = nSourceY; nSourceYSec < nSourceYSecEnd; nSourceYSec ++)
                    {
                        for( nSourceXSec = nSourceX; nSourceXSec < nSourceXSecEnd; nSourceXSec ++)
                        {
                            nCummulator += * ( pabySrcTile + nSourceYSec * nSourceSampleRowSize
                                               + nSourceXSec * nSampleBlockSize
                                               + nSampleOffsetInSampleBlock );
                        }
                    }
                    nCummulatorCount = ( nSourceXSecEnd - nSourceX ) * ( nSourceYSecEnd - nSourceY );
                    * ( pabyOTile + nDestY * nDestSampleRowSize
                        + nDestX * nSampleBlockSize
                        + nSampleOffsetInSampleBlock ) =
                        ( ( nCummulator + ( nCummulatorCount >> 1 ) ) / nCummulatorCount );
                }
            }
        }
    }
}

/************************************************************************/
/*                      TIFF_ProcessFullResBlock()                      */
/*                                                                      */
/*      Process one block of full res data, downsampling into each      */
/*      of the overviews.                                               */
/************************************************************************/

void TIFF_ProcessFullResBlock( TIFF *hTIFF, int nPlanarConfig,
                               int bSubsampled,
                               int nHorSubsampling, int nVerSubsampling,
                               int nOverviews, int * panOvList,
                               int nBitsPerPixel,
                               int nSamples, TIFFOvrCache ** papoRawBIs,
                               uint32 nSXOff, uint32 nSYOff,
                               unsigned char *pabySrcTile,
                               uint32 nBlockXSize, uint32 nBlockYSize,
                               int nSampleFormat, const char * pszResampling )

{
    int		iOverview, iSample;

    for( iSample = 0; iSample < nSamples; iSample++ )
    {
        /*
         * We have to read a tile/strip for each sample for
         * PLANARCONFIG_SEPARATE.  Otherwise, we just read all the samples
         * at once when handling the first sample.
         */
        if( nPlanarConfig == PLANARCONFIG_SEPARATE || iSample == 0 )
        {
            if( TIFFIsTiled(hTIFF) )
            {
                TIFFReadEncodedTile( hTIFF,
                                     TIFFComputeTile(hTIFF, nSXOff, nSYOff,
                                                     0, (tsample_t)iSample ),
                                     pabySrcTile,
                                     TIFFTileSize(hTIFF));
            }
            else
            {
                TIFFReadEncodedStrip( hTIFF,
                                      TIFFComputeStrip(hTIFF, nSYOff,
                                                       (tsample_t) iSample),
                                      pabySrcTile,
                                      TIFFStripSize(hTIFF) );
            }
        }

        /*
         * Loop over destination overview layers
         */
        for( iOverview = 0; iOverview < nOverviews; iOverview++ )
        {
            TIFFOvrCache *poRBI = papoRawBIs[iOverview];
            unsigned char *pabyOTile;
            uint32  nTXOff, nTYOff, nOXOff, nOYOff, nOMult;
            uint32  nOBlockXSize = poRBI->nBlockXSize;
            uint32  nOBlockYSize = poRBI->nBlockYSize;
            int     nSkewBits, nSampleByteOffset;

            /*
             * Fetch the destination overview tile
             */
            nOMult = panOvList[iOverview];
            nOXOff = (nSXOff/nOMult) / nOBlockXSize;
            nOYOff = (nSYOff/nOMult) / nOBlockYSize;

            if( bSubsampled )
            {
                pabyOTile = TIFFGetOvrBlock_Subsampled( poRBI, nOXOff, nOYOff );

                /*
                 * Establish the offset into this tile at which we should
                 * start placing data.
                 */
                nTXOff = (nSXOff - nOXOff*nOMult*nOBlockXSize) / nOMult;
                nTYOff = (nSYOff - nOYOff*nOMult*nOBlockYSize) / nOMult;

#ifdef DBMALLOC
                malloc_chain_check( 1 );
#endif
                TIFF_DownSample_Subsampled( pabySrcTile, iSample,
                                            nBlockXSize, nBlockYSize,
                                            pabyOTile,
                                            poRBI->nBlockXSize, poRBI->nBlockYSize,
                                            nTXOff, nTYOff,
                                            nOMult, pszResampling,
                                            nHorSubsampling, nVerSubsampling );
#ifdef DBMALLOC
                malloc_chain_check( 1 );
#endif

            }
            else
            {

                pabyOTile = TIFFGetOvrBlock( poRBI, nOXOff, nOYOff, iSample );

                /*
                 * Establish the offset into this tile at which we should
                 * start placing data.
                 */
                nTXOff = (nSXOff - nOXOff*nOMult*nOBlockXSize) / nOMult;
                nTYOff = (nSYOff - nOYOff*nOMult*nOBlockYSize) / nOMult;

                /*
                 * Figure out the skew (extra space between ``our samples'') and
                 * the byte offset to the first sample.
                 */
                assert( (nBitsPerPixel % 8) == 0 );
                if( nPlanarConfig == PLANARCONFIG_SEPARATE )
                {
                    nSkewBits = 0;
                    nSampleByteOffset = 0;
                }
                else
                {
                    nSkewBits = nBitsPerPixel * (nSamples-1);
                    nSampleByteOffset = (nBitsPerPixel/8) * iSample;
                }

                /*
                 * Perform the downsampling.
                 */
#ifdef DBMALLOC
                malloc_chain_check( 1 );
#endif
                TIFF_DownSample( pabySrcTile + nSampleByteOffset,
                               nBlockXSize, nBlockYSize,
                               nSkewBits, nBitsPerPixel, pabyOTile,
                               poRBI->nBlockXSize, poRBI->nBlockYSize,
                               nTXOff, nTYOff,
                               nOMult, nSampleFormat, pszResampling );
#ifdef DBMALLOC
                malloc_chain_check( 1 );
#endif
            }
        }
    }
}

/************************************************************************/
/*                        TIFF_BuildOverviews()                         */
/*                                                                      */
/*      Build the requested list of overviews.  Overviews are           */
/*      maintained in a bunch of temporary files and then these are     */
/*      written back to the TIFF file.  Only one pass through the       */
/*      source TIFF file is made for any number of output               */
/*      overviews.                                                      */
/************************************************************************/

void TIFFBuildOverviews( TIFF *hTIFF, int nOverviews, int * panOvList,
                         int bUseSubIFDs, const char *pszResampleMethod,
                         int (*pfnProgress)( double, void * ),
                         void * pProgressData )

{
    TIFFOvrCache	**papoRawBIs;
    uint32		nXSize, nYSize, nBlockXSize, nBlockYSize;
    uint16		nBitsPerPixel, nPhotometric, nCompressFlag, nSamples,
        nPlanarConfig, nSampleFormat;
    int         bSubsampled;
    uint16      nHorSubsampling, nVerSubsampling;
    int			bTiled, nSXOff, nSYOff, i;
    unsigned char	*pabySrcTile;
    uint16		*panRedMap, *panGreenMap, *panBlueMap;
    TIFFErrorHandler    pfnWarning;

    (void) pfnProgress;
    (void) pProgressData;

/* -------------------------------------------------------------------- */
/*      Get the base raster size.                                       */
/* -------------------------------------------------------------------- */
    TIFFGetField( hTIFF, TIFFTAG_IMAGEWIDTH, &nXSize );
    TIFFGetField( hTIFF, TIFFTAG_IMAGELENGTH, &nYSize );

    TIFFGetField( hTIFF, TIFFTAG_BITSPERSAMPLE, &nBitsPerPixel );
    /* TODO: nBitsPerPixel seems misnomer and may need renaming to nBitsPerSample */
    TIFFGetField( hTIFF, TIFFTAG_SAMPLESPERPIXEL, &nSamples );
    TIFFGetFieldDefaulted( hTIFF, TIFFTAG_PLANARCONFIG, &nPlanarConfig );

    TIFFGetFieldDefaulted( hTIFF, TIFFTAG_PHOTOMETRIC, &nPhotometric );
    TIFFGetFieldDefaulted( hTIFF, TIFFTAG_COMPRESSION, &nCompressFlag );
    TIFFGetFieldDefaulted( hTIFF, TIFFTAG_SAMPLEFORMAT, &nSampleFormat );

    if( nPhotometric == PHOTOMETRIC_YCBCR || nPhotometric == PHOTOMETRIC_ITULAB )
    {
        if( nBitsPerPixel != 8 || nSamples != 3 || nPlanarConfig != PLANARCONFIG_CONTIG ||
            nSampleFormat != SAMPLEFORMAT_UINT)
        {
            /* TODO: use of TIFFError is inconsistent with use of fprintf in addtiffo.c, sort out */
            TIFFErrorExt( TIFFClientdata(hTIFF), "TIFFBuildOverviews",
                          "File `%s' has an unsupported subsampling configuration.\n",
                          TIFFFileName(hTIFF) );
            /* If you need support for this particular flavor, please contact either
             * Frank Warmerdam warmerdam@pobox.com
             * Joris Van Damme info@awaresystems.be
             */
            return;
        }
        bSubsampled = 1;
        TIFFGetField( hTIFF, TIFFTAG_YCBCRSUBSAMPLING, &nHorSubsampling, &nVerSubsampling );
        /* TODO: find out if maybe TIFFGetFieldDefaulted is better choice for YCbCrSubsampling tag */
    }
    else
    {
        if( nBitsPerPixel < 8 )
        {
            /* TODO: use of TIFFError is inconsistent with use of fprintf in addtiffo.c, sort out */
            TIFFErrorExt( TIFFClientdata(hTIFF), "TIFFBuildOverviews",
                          "File `%s' has samples of %d bits per sample.  Sample\n"
                          "sizes of less than 8 bits per sample are not supported.\n",
                          TIFFFileName(hTIFF), nBitsPerPixel );
            return;
        }
        bSubsampled = 0;
        nHorSubsampling = 1;
        nVerSubsampling = 1;
    }

/* -------------------------------------------------------------------- */
/*      Turn off warnings to avoid alot of repeated warnings while      */
/*      rereading directories.                                          */
/* -------------------------------------------------------------------- */
    pfnWarning = TIFFSetWarningHandler( NULL );

/* -------------------------------------------------------------------- */
/*      Get the base raster block size.                                 */
/* -------------------------------------------------------------------- */
    if( TIFFGetField( hTIFF, TIFFTAG_ROWSPERSTRIP, &(nBlockYSize) ) )
    {
        nBlockXSize = nXSize;
        bTiled = FALSE;
    }
    else
    {
        TIFFGetField( hTIFF, TIFFTAG_TILEWIDTH, &nBlockXSize );
        TIFFGetField( hTIFF, TIFFTAG_TILELENGTH, &nBlockYSize );
        bTiled = TRUE;
    }

/* -------------------------------------------------------------------- */
/*	Capture the pallette if there is one.				*/
/* -------------------------------------------------------------------- */
    if( TIFFGetField( hTIFF, TIFFTAG_COLORMAP,
                      &panRedMap, &panGreenMap, &panBlueMap ) )
    {
        uint16		*panRed2, *panGreen2, *panBlue2;
        int             nColorCount = 1 << nBitsPerPixel;

        panRed2 = (uint16 *) _TIFFmalloc(2*nColorCount);
        panGreen2 = (uint16 *) _TIFFmalloc(2*nColorCount);
        panBlue2 = (uint16 *) _TIFFmalloc(2*nColorCount);

        memcpy( panRed2, panRedMap, 2 * nColorCount );
        memcpy( panGreen2, panGreenMap, 2 * nColorCount );
        memcpy( panBlue2, panBlueMap, 2 * nColorCount );

        panRedMap = panRed2;
        panGreenMap = panGreen2;
        panBlueMap = panBlue2;
    }
    else
    {
        panRedMap = panGreenMap = panBlueMap = NULL;
    }

/* -------------------------------------------------------------------- */
/*      Initialize overviews.                                           */
/* -------------------------------------------------------------------- */
    papoRawBIs = (TIFFOvrCache **) _TIFFmalloc(nOverviews*sizeof(void*));

    for( i = 0; i < nOverviews; i++ )
    {
        uint32  nOXSize, nOYSize, nOBlockXSize, nOBlockYSize;
        toff_t  nDirOffset;

        nOXSize = (nXSize + panOvList[i] - 1) / panOvList[i];
        nOYSize = (nYSize + panOvList[i] - 1) / panOvList[i];

        nOBlockXSize = MIN(nBlockXSize,nOXSize);
        nOBlockYSize = MIN(nBlockYSize,nOYSize);

        if( bTiled )
        {
            if( (nOBlockXSize % 16) != 0 )
                nOBlockXSize = nOBlockXSize + 16 - (nOBlockXSize % 16);

            if( (nOBlockYSize % 16) != 0 )
                nOBlockYSize = nOBlockYSize + 16 - (nOBlockYSize % 16);
        }

        nDirOffset = TIFF_WriteOverview( hTIFF, nOXSize, nOYSize,
                                         nBitsPerPixel, nPlanarConfig,
                                         nSamples, nOBlockXSize, nOBlockYSize,
                                         bTiled, nCompressFlag, nPhotometric,
                                         nSampleFormat,
                                         panRedMap, panGreenMap, panBlueMap,
                                         bUseSubIFDs,
                                         nHorSubsampling, nVerSubsampling );

        papoRawBIs[i] = TIFFCreateOvrCache( hTIFF, nDirOffset );
    }

    if( panRedMap != NULL )
    {
        _TIFFfree( panRedMap );
        _TIFFfree( panGreenMap );
        _TIFFfree( panBlueMap );
    }

/* -------------------------------------------------------------------- */
/*      Allocate a buffer to hold a source block.                       */
/* -------------------------------------------------------------------- */
    if( bTiled )
        pabySrcTile = (unsigned char *) _TIFFmalloc(TIFFTileSize(hTIFF));
    else
        pabySrcTile = (unsigned char *) _TIFFmalloc(TIFFStripSize(hTIFF));

/* -------------------------------------------------------------------- */
/*      Loop over the source raster, applying data to the               */
/*      destination raster.                                             */
/* -------------------------------------------------------------------- */
    for( nSYOff = 0; nSYOff < (int) nYSize; nSYOff += nBlockYSize )
    {
        for( nSXOff = 0; nSXOff < (int) nXSize; nSXOff += nBlockXSize )
        {
            /*
             * Read and resample into the various overview images.
             */

            TIFF_ProcessFullResBlock( hTIFF, nPlanarConfig,
                                      bSubsampled,nHorSubsampling,nVerSubsampling,
                                      nOverviews, panOvList,
                                      nBitsPerPixel, nSamples, papoRawBIs,
                                      nSXOff, nSYOff, pabySrcTile,
                                      nBlockXSize, nBlockYSize,
                                      nSampleFormat, pszResampleMethod );
        }
    }

    _TIFFfree( pabySrcTile );

/* -------------------------------------------------------------------- */
/*      Cleanup the rawblockedimage files.                              */
/* -------------------------------------------------------------------- */
    for( i = 0; i < nOverviews; i++ )
    {
        TIFFDestroyOvrCache( papoRawBIs[i] );
    }

    if( papoRawBIs != NULL )
        _TIFFfree( papoRawBIs );

    TIFFSetWarningHandler( pfnWarning );
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 8
 * fill-column: 78
 * End:
 */


text:
package mount

import (
	"sort"
	"strconv"
	"strings"

	"github.com/containers/storage/pkg/fileutils"
)

// mountError holds an error from a mount or unmount operation
type mountError struct {
	op             string
	source, target string
	flags          uintptr
	data           string
	err            error
}

// Error returns a string representation of mountError
func (e *mountError) Error() string {
	out := e.op + " "

	if e.source != "" {
		out += e.source + ":" + e.target
	} else {
		out += e.target
	}

	if e.flags != uintptr(0) {
		out += ", flags: 0x" + strconv.FormatUint(uint64(e.flags), 16)
	}
	if e.data != "" {
		out += ", data: " + e.data
	}

	out += ": " + e.err.Error()
	return out
}

// Cause returns the underlying cause of the error
func (e *mountError) Cause() error {
	return e.err
}

// GetMounts retrieves a list of mounts for the current running process.
func GetMounts() ([]*Info, error) {
	return parseMountTable()
}

// Mounted determines if a specified mountpoint has been mounted.
// On Linux it looks at /proc/self/mountinfo and on Solaris at mnttab.
func Mounted(mountpoint string) (bool, error) {
	entries, err := parseMountTable()
	if err != nil {
		return false, err
	}

	mountpoint, err = fileutils.ReadSymlinkedPath(mountpoint)
	if err != nil {
		return false, err
	}

	// Search the table for the mountpoint
	for _, e := range entries {
		if e.Mountpoint == mountpoint {
			return true, nil
		}
	}
	return false, nil
}

// Mount will mount filesystem according to the specified configuration, on the
// condition that the target path is *not* already mounted. Options must be
// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See
// flags.go for supported option flags.
func Mount(device, target, mType, options string) error {
	flag, data := ParseOptions(options)
	if flag&REMOUNT != REMOUNT {
		if mounted, err := Mounted(target); err != nil || mounted {
			return err
		}
	}
	return mount(device, target, mType, uintptr(flag), data)
}

// ForceMount will mount a filesystem according to the specified configuration,
// *regardless* if the target path is not already mounted. Options must be
// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See
// flags.go for supported option flags.
func ForceMount(device, target, mType, options string) error {
	flag, data := ParseOptions(options)
	return mount(device, target, mType, uintptr(flag), data)
}

// Unmount lazily unmounts a filesystem on supported platforms, otherwise
// does a normal unmount.
func Unmount(target string) error {
	return unmount(target, mntDetach)
}

// RecursiveUnmount unmounts the target and all mounts underneath, starting with
// the deepest mount first.
func RecursiveUnmount(target string) error {
	mounts, err := GetMounts()
	if err != nil {
		return err
	}

	// Make the deepest mount be first
	sort.Slice(mounts, func(i, j int) bool {
		return len(mounts[i].Mountpoint) > len(mounts[j].Mountpoint)
	})

	for i, m := range mounts {
		if !strings.HasPrefix(m.Mountpoint, target) {
			continue
		}
		if err := Unmount(m.Mountpoint); err != nil && i == len(mounts)-1 {
			return err
			// Ignore errors for submounts and continue trying to unmount others
			// The final unmount should fail if there ane any submounts remaining
		}
	}
	return nil
}

// ForceUnmount lazily unmounts a filesystem on supported platforms,
// otherwise does a normal unmount.
//
// Deprecated: please use Unmount instead, it is identical.
func ForceUnmount(target string) error {
	return unmount(target, mntDetach)
}


text:
package com.github.yaterz.ctci.ci;

/**
 * Assume you have a method {@code isSubstring} which checks if one word is a substring of another.
 * Given two strings, s1 and s2, write code to check if s3 is a rotations of s1 using only one call to {@code isSubstring}
 * E.g., "waterbottle" is a rotation of "erbottlewat"
 *
 * @author mattyaterz
 * @since 11/7/14
 */
public class C1E8Solution {
    public static boolean isRotation( String s1, String s2 ) {
        return s1 != null &&
                s2 != null &&
                s1.length() == s2.length() &&
                ( s1 + s1 ).contains( s2 ); // Using contains( CharSequence ) as 'isSubstring'
    }
}


text:
@echo off

REM
REM  To run this at startup, use this as your shortcut target:
REM  %windir%\system32\cmd.exe /k w:\Pixel_RE\misc\shell.bat
REM

call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x64

set LIB=%LIB%;C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x64


text:
<template name="help">

Help if you need help, then it"s our fault.

</template>


text:
namespace webrtc {
class DesktopFrame;
}  // namespace webrtc

namespace remoting {

class Canvas;

// This class draws the desktop on the canvas.
class GlDesktop : public Drawable {
 public:
  GlDesktop();
  ~GlDesktop() override;

  // |frame| can be either a full frame or updated regions only frame.
  void SetVideoFrame(const webrtc::DesktopFrame& frame);

  // Drawable implementation.
  void SetCanvas(base::WeakPtr<Canvas> canvas) override;
  bool Draw() override;
  int GetZIndex() override;
  base::WeakPtr<Drawable> GetWeakPtr() override;

 private:
  struct GlDesktopTextureContainer;

  void ReallocateTextures(const webrtc::DesktopSize& size);

  std::vector<std::unique_ptr<GlDesktopTextureContainer>> textures_;

  webrtc::DesktopSize last_desktop_size_;
  int max_texture_size_ = 0;
  base::WeakPtr<Canvas> canvas_ = nullptr;
  base::ThreadChecker thread_checker_;
  base::WeakPtrFactory<Drawable> weak_factory_{this};

  DISALLOW_COPY_AND_ASSIGN(GlDesktop);
};

}  // namespace remoting

#endif  // REMOTING_CLIENT_DISPLAY_GL_DESKTOP_H_


text:
/* menu_tree of cms_content */
#menu_tree {
    padding: 5px;
    margin: 0px;
}

#menu_tree ul {
    margin:0px;
    padding:0px;
    list-style-type:none;
    border-top: 1px solid #ccc;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
    width: 140px;
}

#menu_tree li {
    background:#f7f7f7;
    height: 24px;
    line-height: 24px;
    width: 140px;
    border-bottom: 1px solid #ccc;
    text-align: center;
    position: relative;
}

#menu_tree li.title {
    background: #ccc;
    color: #333333;
}

#menu_tree li.selected {
    background: #aaa;
    color: #111;
}

#menu_tree li.hover{
    background: #c0c0c0 url(http://img.ifeng.com/tres/phoenix/icon2.gif) no-repeat 186px -303px;
}
#menu_tree li a {
    display: block;
}
#menu_tree li ul{
    display:none;
    position:absolute;
    top:0;
    left:0;
    margin-left:140px;
}
#menu_tree li ul li{
    background:#ffffe1;
    width:140px;
}
#menu_tree li ul li.hover{
    background:#ffffe1;
}

/* cms_content category table */
.cms_category {
    border:1px solid #E3E3E3;
    border-spacing:0px 0px;
    border-collapse:separate;
}

.cms_category tr.title {
    background: #F5F5F5 url(/media/cms_content/img/table_title_bg.jpg) repeat-x scroll center bottom;
}

.cms_category tr.row1 {

}

.cms_category tr.row2 {
    background: #E5ECF9;
}

.cms_article_table_list {
    border: 1px solid #E3E3E3;
    border-spacing: 0px 0px;
    border-collapse: separate;
}

.cms_article_table_list tr.title {
    background: #F5F5F5 url(/media/cms_content/img/table_title_bg.jpg) repeat-x scroll center bottom;
}

.cms_article_table_list tr.row1 {
    background: #FFFFFF;
}

.cms_article_table_list tr.row2 {
    background: #E5ECF9;
}


text:
/*! @file
    @brief Static page directory allocator.

    Pre-allocates a static array of PDs, and provides interface to allocate and reuse them as
    needed. This is done to avoid fragmentation as kernel PD objects are quite big. Also manages
    root CNodes objects associated with the PDs address spaces, as they are quite big and also cause
    fragmentation.

    This module has ownership of the underlying PDs and CNodes, and will manage their creation /
    deletion. Uses a free-list internally to bookkeep re-assignment of previously deleted PDs.
*/

#ifndef _REFOS_PROCESS_SERVER_SYSTEM_ADDRSPACE_PAGE_DIRECTORY_H_
#define _REFOS_PROCESS_SERVER_SYSTEM_ADDRSPACE_PAGE_DIRECTORY_H_

#include <stdio.h>
#include <stdlib.h>
#include <data_struct/cpool.h>
#include <autoconf.h>
#include <allocman/allocman.h>
#include <allocman/vka.h>
#include <sel4utils/util.h>
#include <sel4utils/vspace.h>
#include "../../common.h"

/*! @file
    @brief VSpace Page Directory module. */

#define PD_MAX CONFIG_PROCSERV_MAX_VSPACES

/*! @brief Page directory list structure. */
struct pd_list {
    cpool_t PDpool;
    vka_object_t pd[PD_MAX]; /* Has ownership. */
    vka_object_t cnode[PD_MAX]; /* Has ownership. */
};

/*! @brief Page directory output structure. */
struct pd_info {
    seL4_CPtr kpdObject;
    seL4_CPtr kcnodeObject;
};

/*! @brief Initialises a PD list.
    @param pdlist The allocated struct pd_list structure to initialise.
 */
void pd_init(struct pd_list *pdlist);

/*! @brief Assigns a free PD to use.
    @param pdlist The PD list to assign from. (No ownership)
    @return pd_info struct containing: cptr to an empty PD (No ownership),
            cptr to empty Root CNode associated with the PD (No ownership), if success.
            Returns NULL if no more PDs left.
 */
struct pd_info pd_assign(struct pd_list *pdlist);

/*! @brief Frees a previously assigned PD from use.
    @param pdlist The PD list to delete from. (No ownership)
    @param pdPtr Reference to PD. Assumes the PD came from a pd_assign from the same list.
           (Keeps previous ownership)
 */
void pd_free(struct pd_list *pdlist, seL4_CPtr pdPtr);

#endif /* _REFOS_PROCESS_SERVER_SYSTEM_ADDRSPACE_PAGE_DIRECTORY_H_ */


text:
[#ftl]
#
#  Copyright 2014 by Cloudsoft Corporation Limited
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
# sshd
#
# VERSION 0.0.4

FROM ${repository}/${imageName}
MAINTAINER Cloudsoft "brooklyn@cloudsoftcorp.com"

# setup locale
RUN type locale-gen ; if [ "$?" -eq "0" ] ; then locale-gen en_US.UTF-8 ; fi

# setup root account
RUN echo 'root:${entity.password}' | chpasswd

# install sshd
RUN type apt-get ; \
  if [ "$?" -eq "0" ] ; then \
    apt-get update ; \
    apt-get install -y openssh-server ; \
  else \
    yum -y install openssh-server ; \
  fi ; \
  mkdir /var/run/sshd ; \
  chmod 600 /var/run/sshd ; \
  /usr/sbin/sshd ;

EXPOSE 22

CMD [ "/usr/sbin/sshd", "-D" ]


text: select c_boolean, COUNT(DISTINCT c_integer) from alltypes group by c_boolean order by c_boolean;


text:
using System;

namespace Deezer.Api
{
    public class DeezerRuntimeException : Exception
    {
        private string HttpReasonPhrase;

        public DeezerRuntimeException(string httpReasonPhrase)
        {
            this.HttpReasonPhrase = httpReasonPhrase;
        }

    }
}


text:
// Copyright © 2015-2016 Pierre Neidhardt <ambrevar@gmail.com>
// Use of this file is governed by the license that can be found in LICENSE.

/*
A filesystem hierarchy synchronizer

Rename files in TARGET so that identical files found in SOURCE and TARGET have
the same relative path.

The main goal of the program is to make folders synchronization faster by
sparing big file transfers when a simple rename suffices. It complements other
synchronization programs that lack this capability.

See http://ambrevar.bitbucket.io/hsync and 'hsync -h' for more details.

Usage:

	hsync [OPTIONS] SOURCE TARGET

For usage options, see:

	hsync -h

Implementation details

We store the file entries in the following structure:

	entries := map[partialHash struct{size int64, pos int64, hash string}]fileMatch struct{
		sourceID *fileID{path string, h hash.Hash},
		targetID *fileID{path string, h hash.Hash}
	}

This 'entries' map indexes the possible file matches by content ('partialHash').
A file match references the paths that will be used to rename the file in TARGET
from 'oldpath' to 'newpath'. Note that 'newpath' is given by 'sourceID.path',
and 'oldpath' by 'targetID.path'.

The algorithm is centered around one main optimization: rolling-checksums. We
assume that two files match if they have the same partial hash.

The initial partial hash is just the size with an empty hash. This speeds up the
process since this saves an open/close of the file. We just need a 'stat'. Files
will not be read unless a rolling-checksum is required. As a consequence,
unreadable files with a unique size will be stored in 'entries', while
unreadable conflicting files will be discarded. Note that the system allows to
rename files that cannot be read.

One checksum roll increments 'pos' and updates the hash by hashing the next
BLOCKSIZE bytes of the file. BLOCKSIZE is set to a value that is commonly
believed to be optimal in most cases. The optimal value would be the device
blocksize where the file resides. It would be more complex and memory consuming
to query this value for each file.

We choose md5 (128 bits) as the checksum algorithm. Adler32, CRC-32 and CRC-64
are only a tiny little faster while suffering from more clashes. This choice
should be backed up with a proper benchmark.

A conflict arises when two files in either SOURCE or TARGET have the same
partial hash. We solve the conflict by updating the partial hashes until they
differ. If the partial hashes cannot be updated any further (i.e. we reached
end-of-file), it means that the files are duplicates.

Notes:

- Partial hashes of conflicting files will be complete at the same roll since
they have the same size.

- When a partial hash is complete, we have the following relation:

	(pos-1)*BLOCKSIZE < filesize <= pos*BLOCKSIZE

- There is only one possible conflicting file at a time.

A file match may be erroneous if the partial hash is not complete. The most
obvious case is when two different files are the only ones of size N in SOURCE
and TARGET. This down-side is a consequence of the design choice, i.e. focus on
speed. Erroneous matches can be corrected in the preview file. If we wanted no
ambiguity, we would have to compute the full hashes and this would take
approximately as much time as copying files from SOURCE to TARGET, like a
regular synchronization tool would do.

We store the digest 'hash.Hash' together with the file path for when we update a
partial hash.

Process:

1. We walk SOURCE completely. Only regular files are processed. The 'sourceID'
are stored. If two entries conflict (they have the same partial hash), we
compute update the partial hashes until they do not conflict anymore. If the
conflict is not resolvable, i.e. the partial hash is complete and files are
identical, we drop both files from 'entries'.

Future files can have the same partial hash that led to a former conflict. To
distinguish the content from former conflicts when adding a new file, we must
compute the partial hash up to the 'pos' of the last conflict (the number of
checksum rolls). To keep track of this 'pos' when there is a conflict, we mark
all computed partial hash as dummy values. When the next entry will be added, we
will have to compute the partial hash until it does not match a dummy value in
'entries'.

Duplicates are not processed but display a warning. Usually the user does not
want duplicates, so she is better off fixing them before processing with the
renames. It would add a lot of complexity to handle duplicates properly.

2. We walk TARGET completely. We skip all dummies as source the SOURCE walk.
We need to analyze SOURCE completely before we can check for matches.

- If there are only dummy entries, there was an unsolvable conflict in SOURCE.
We drop the file.

- If we end on a non-empty entry with an 'unsolvable' targetID, it means that an
unsolvable conflict with target files happened with this partial hash. This is
only possible at end-of-file. We drop the file.

- If we end on an empty entry, there is no match with SOURCE and we drop the
file.

- If we end on a non-empty entry without previous matches, we store the
match.

- Else we end on a non-empty entry with one match already present. This is a
conflict. We solve the conflict as for the SOURCE walk except that we need to
update the partial hashes of three files: the SOURCE file, the first TARGET
match and the new TARGET match.

3. We generate the 'renameOps' and 'reverseOps' maps. They map 'oldpath' to
'newpath' and 'newpath' to 'oldpath' respectively. We drop entries where
'oldpath==newpath' to spare a lot of noise.

Note that file names are not used to compute a match since they could be
identical while the content would be different.

4. We proceed with the renames. Chains and cycles may occur.

- Example of a chain of renames: a->b, b->c, c->d.

- Example of a cycle of renames: a->b, b->c, c->a.

TARGET must be fully analyzed before proceeding with the renames so that we can
detect chains.

We always traverse chains until we reach the end, then rename the elements while
going backward till the beginning. The beginning can be before the entry point.
'reverseOps' is used for going backward.

When a cycle is detected, we break it down to a chain. We rename one file to a
temporary name. Then we add this new file to the other end of the chain so that
it gets renamed to its original new name once all files have been processed.
*/
package main


text:
import time

from ._timer import Timer

class AsyncTimer(Timer):
    """A timer instance, which awaits the wrapped function."""

    def _wrapped_factory(self, func):
        """Report an execution time for each function run.

        :param func (function): A function to wrap for measurement.
        :returns function: A measured function, which will be awaited.
        """
        async def wrapped(*args, **kwargs):
            self.time_start = time.time()
            ret = await func(*args, **kwargs)
            self.__exit__(None, None, None)
            return ret

        return wrapped


text:
package me.knox.zmz.entity;

import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;

/**
 * Created by KNOX.
 */

public class ScheduleUpdate implements Parcelable {

  @SerializedName("id") private int id;
  @SerializedName("cnname") private String cnname;
  @SerializedName("enname") private String enname;
  @SerializedName("poster") private String poster;
  @SerializedName("poster_b") private String posterB;  // posterB, poster_a, poster_b, poster_m,poster_s
  @SerializedName("season") private String season;
  @SerializedName("episode") private String episode;

  public int getId() {
    return id;
  }

  public String getCnname() {
    return cnname;
  }

  public String getEnname() {
    return enname;
  }

  public String getPoster() {
    return poster;
  }

  public String getPosterB() {
    return posterB;
  }

  public String getSeason() {
    if (Math.log10(Double.valueOf(season)) + 1 < 2) {
      return "0" + season;
    }
    return season;
  }

  public String getEpisode() {
    if (Math.log10(Double.valueOf(episode)) + 1 < 2) {
      return "0" + episode;
    }
    return episode;
  }

  @Override public int describeContents() {
    return 0;
  }

  @Override public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(this.id);
    dest.writeString(this.cnname);
    dest.writeString(this.enname);
    dest.writeString(this.poster);
    dest.writeString(this.posterB);
    dest.writeString(this.season);
    dest.writeString(this.episode);
  }

  public ScheduleUpdate() {
  }

  protected ScheduleUpdate(Parcel in) {
    this.id = in.readInt();
    this.cnname = in.readString();
    this.enname = in.readString();
    this.poster = in.readString();
    this.posterB = in.readString();
    this.season = in.readString();
    this.episode = in.readString();
  }

  public static final Parcelable.Creator<ScheduleUpdate> CREATOR =
      new Parcelable.Creator<ScheduleUpdate>() {
        @Override public ScheduleUpdate createFromParcel(Parcel source) {
          return new ScheduleUpdate(source);
        }

        @Override public ScheduleUpdate[] newArray(int size) {
          return new ScheduleUpdate[size];
        }
      };
}


text: export { WatsonHealthCdArchive16 as default } from "../../../";


text:
class VoteManager:
    def __init__(self):
        self.currentVote = None

    def start(self, user, name):
        if self.currentVote:
            raise OngoingVoteException()
        self.currentVote = Vote(name)

    def vote(self, user, vote):
        if not self.currentVote:
            raise NoVoteException()
        self.currentVote.vote(user["id"], vote)

    def state(self):
        if not self.currentVote:
            raise NoVoteException()
        return VoteResult(self.currentVote, False)

    def close(self, user):
        if not self.currentVote:
            raise NoVoteException()
        vote = self.currentVote
        self.currentVote = None
        return VoteResult(vote, True)

class VoteResult:
    def __init__(self, vote, end):
        if not isinstance(vote, Vote):
            raise ValueError("Vote is not a vote")
        self.name = vote.name
        self.votesFor = vote.votesFor
        self.votesAgainst = vote.votesAgainst
        self.voteCount = len(vote.votes)
        self.rate = 0 if self.voteCount == 0 else self.votesFor / self.voteCount
        self.end = bool(end)

class Vote:
    def __init__(self, name):
        self.name = name
        self.votesFor = 0
        self.votesAgainst = 0
        self.votes = []

    def has_voted(self, user_id):
        return user_id in self.votes

    def vote(self, user_id, vote):
        if self.has_voted(user_id):
            raise AlreadyVoteException()
        self.votes.append(user_id)
        if vote:
            self.votesFor += 1
        else:
            self.votesAgainst += 1

class VoteException(Exception):
    pass

class OngoingVoteException(VoteException):
    pass

class NoVoteException(VoteException):
    pass

class AlreadyVoteException(VoteException):
    pass


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Detalle_tarea_ctrl extends CI_Controller {
	public function traerTarea($idTarea){
		checkSession();

		$this->load->model('Tarea');
		$data['cTarea'] = $this->Tarea->traer($idTarea);

		$data['menu'] = $this->load->view('Menu_principal',null,true);
		$this->load->view('Detalle_tarea_vw',$data);
	}

	public function traerRetrabajo($idRetrabajo){
		checkSession();

		$this->load->model('Retrabajo');
		$data['cRetrabajo'] = $this->Retrabajo->traer($idRetrabajo);

		$data['menu'] = $this->load->view('Menu_principal',null,true);
		$this->load->view('Detalle_tarea_vw',$data);
	}

}
?>


text:
using System;
using System.Globalization;

namespace Anycmd.Xacml.Runtime.DataTypes
{
    using Functions;
    using Interfaces;

    /// <summary>
    /// A class defining the DnsName data type.
    /// </summary>
    public class DnsNameDataType : IDataType
    {
        #region Private members

        /// <summary>
        /// The dns name.
        /// </summary>
        private string _name = String.Empty;

        /// <summary>
        /// The dns name port range.
        /// </summary>
        private string _portRange = String.Empty;

        /// <summary>
        /// The full value.
        /// </summary>
        private string _value = String.Empty;

        #endregion

        #region Constructors

        /// <summary>
        /// Default constructor.
        /// </summary>
        internal DnsNameDataType()
        {
        }

        /// <summary>
        /// Creates a new DnsNameDataType using the name as a string.
        /// </summary>
        /// <param name="value">The name as a string.</param>
        public DnsNameDataType(string value)
        {
            _value = value;
            //TODO: add a regular expression to extract the values.
            //  dnsName = hostname [ ":" portrange ]
            //  portrange = portnumber | "-"portnumber | portnumber"-"[portnumber]
        }

        #endregion

        #region Public methods

        /// <summary>
        /// The HashCode method overloaded because of a compiler warning. The base class is called.
        /// </summary>
        /// <returns>The HashCode calculated at the base class.</returns>
        public override int GetHashCode()
        {
            return _value.GetHashCode();
        }

        /// <summary>
        /// Equals method overloaded to compare two values of the same data type.
        /// </summary>
        /// <param name="obj">The object to compare with.</param>
        /// <returns>true, if both values are equals, otherwise false.</returns>
        public override bool Equals(object obj)
        {
            DnsNameDataType compareTo = obj as DnsNameDataType;
            if (compareTo == null)
            {
                return base.Equals(obj);
            }

            return String.Compare(_value, compareTo._value, true, CultureInfo.InvariantCulture) == 0;
            //TODO: check the real equal operation in the last version of the spec.
        }

        #endregion

        #region IDataType Members

        /// <summary>
        /// Return the function that compares two values of this data type.
        /// </summary>
        /// <value>An IFunction instance.</value>
        public IFunction EqualFunction
        {
            get { return new DnsNameEqual(); }
        }

        /// <summary>
        /// Return the function that verifies if a value is contained within a bag of values of this data type.
        /// </summary>
        /// <value>An IFunction instance.</value>
        public IFunction IsInFunction
        {
            get { return new DnsNameIsIn(); }
        }

        /// <summary>
        /// Return the function that verifies if all the values in a bag are contained within another bag of values of this data type.
        /// </summary>
        /// <value>An IFunction instance.</value>
        public IFunction SubsetFunction
        {
            get { return new DnsNameSubset(); }
        }

        /// <summary>
        /// The string representation of the data type constant.
        /// </summary>
        /// <value>A string with the Uri for the data type.</value>
        public string DataTypeName
        {
            get { return Consts.Schema2.InternalDataTypes.DnsName; }
        }

        /// <summary>
        /// Return an instance of an DnsName form the string specified.
        /// </summary>
        /// <param name="value">The string value to parse.</param>
        /// <param name="parNo">The parameter number being parsed.</param>
        /// <returns>An instance of the type.</returns>
        public object Parse(string value, int parNo)
        {
            return new DnsNameDataType(value);
        }

        #endregion
    }
}


text:
using System;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = false, AccessRights = AccessRights.None)]
    public class StochasticCCI : Indicator
    {
        [Output("StochCCI", Color = Colors.Blue)]
        public IndicatorDataSeries StochCCI { get; set; }

        [Output("Trigger", Color = Colors.Red)]
        public IndicatorDataSeries trigger { get; set; }

        [Parameter(DefaultValue = 14, MinValue = 2)]
        public int Period { get; set; }

        private CommodityChannelIndex cci;
        private IndicatorDataSeries value1;

        protected override void Initialize()
        {
            cci = Indicators.CommodityChannelIndex(Period);
            value1 = CreateDataSeries();
        }

        public override void Calculate(int index)
        {
            double cciL = cci.Result[index];
            double cciH = cci.Result[index];
            for (int i = index - Period + 1; i <= index; i++)
            {
                if (cciH < cci.Result[i])
                {
                    cciH = cci.Result[i];
                }
                if (cciL > cci.Result[i])
                {
                    cciL = cci.Result[i];
                }
            }
            if (cciH != cciL)
            {
                value1[index] = ((cci.Result[index] - cciL) / (cciH - cciL));
            }
            StochCCI[index] = (4 * value1[index] + 3 * value1[index - 1] + 2 * value1[index - 2] + value1[index - 3]) / 10;
            StochCCI[index] = 2 * (StochCCI[index] - 0.5);

            trigger[index] = 0.96 * (StochCCI[index - 1] + 0.02);
        }
    }
}


text:
<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class User extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'username' => Yii::t('app', 'Username'),
            'auth_key' => Yii::t('app', 'Auth Key'),
            'password_hash' => Yii::t('app', 'Password Hash'),
            'password_reset_token' => Yii::t('app', 'Password Reset Token'),
            'email' => Yii::t('app', 'Email'),
            'status' => Yii::t('app', 'Status'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
        ];
    }
}


text:
We encourage and welcome contributions from the development community. There are many ways to contribute.
1. Open issues for any bugs or improvements you see in the library.
2. Contributing bug fixes, examples and documentation.
3. Contributing features. Features may be accepted but will need to be first be discussed.

## Pre-Requisites for Contributing
1. Fork the repository into your GitHub account.
2. Clone your fork locally to your computer.
3. Configure a remote to "upstream" Azure/amqpnetlite repository so that you can keep your local repo up-to-date.
4. Get familiar with the code base and see what you can help.
5. Sign a Contribution License Agreement (one time activity) if you would like to open Pull Requests. This can be done after you open the first PR. Detailed instructions will be posted to help you sign the CLA.

## Basic Workflow for Contributions
1. All Pull Requests should be tracked by issues. For existing issue, please comment on the issue first to avoid duplication of effort. Open a new one if the issue does not exist.
2. Keep your local branch up-to-date.
4. Make your changes, test them, and commit them locally. If you created a new topic branch, you can commit as often as you need. However, the branch from which you open the PR should not contain many, small, and incomplete commits. Ideally any commit should build clean and pass the tests. If you do have such commits, consider squash merging them into master and open the PR there.
5. When you are happy with the changes, open a pull request.
6. Address code review comments, if any, and update your pull request.

## Coding Guidelines
1. Keep the code base consistent by following the existing conventions (e.g. naming, layout, etc.).
2. New source files should have the copyright header on the top. Please copy and paste the header from an existing source file. We do not accept code with a different copyright header.
3. New project output path should be set to "bin\$(Configuration)\$(MSBuildProjectName)\" and intermediate output path should be set to "obj\$(Configuration)\$(MSBuildProjectName)\" (relative to the solution directory).

Thank you for your contribution!


text:
define(["require", "exports", "./util"], function (require, exports, util_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class Log {
        constructor(logElemId, consoleElemId = null) {
            this.consoleElem = null;
            this.cmdHandler = null;
            this.scrollPending = false;
            this.logElem = util_1.getElement(logElemId);
            if (consoleElemId) {
                this.consoleElem = util_1.getElement(consoleElemId);
                this.consoleElem.addEventListener('keypress', (e) => {
                    let elem = this.consoleElem;
                    if (e.keyCode == 13) {
                        let cmd = elem.innerText.trim();
                        if (cmd != '' && this.cmdHandler) {
                            this.cmdHandler(cmd);
                        }
                        elem.innerHTML = '';
                        e.preventDefault();
                        return false;
                    }
                });
            }
        }
        log(msg, className = '') {
            let child;
            if (typeof msg == 'string') {
                if (msg == '') {
                    msg = ' ';
                }
                child = document.createElement('div');
                child.innerText = msg;
                if (className != '') {
                    child.className = className;
                }
            }
            else {
                child = msg;
            }
            this.logElem.appendChild(child);
        }
        clear() {
            this.logElem.innerHTML = '';
        }
        scroll() {
            if (!this.scrollPending) {
                this.scrollPending = true;
                window.requestAnimationFrame(() => {
                    this.scrollPending = false;
                    if (this.logElem.lastElementChild) {
                        this.logElem.lastElementChild.scrollIntoView();
                    }
                });
            }
        }
        onConsoleCmd(cmdHandler) {
            this.cmdHandler = cmdHandler;
        }
        get hasFocus() {
            return this.consoleElem && document.activeElement == this.consoleElem;
        }
        focus() {
            if (this.consoleElem) {
                this.consoleElem.focus();
            }
        }
        blur() {
            if (this.consoleElem) {
                this.consoleElem.blur();
            }
        }
    }
    exports.Log = Log;
});
//# sourceMappingURL=log.js.map