text:
import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges, OnDestroy, ViewEncapsulation } from '@angular/core';
import { UntypedFormGroup, UntypedFormBuilder, AbstractControl } from '@angular/forms';
import { DateAdapter } from '@angular/material/core';
import { MatDialog } from '@angular/material/dialog';
import { debounceTime, filter, takeUntil, finalize, switchMap, tap } from 'rxjs/operators';
import { Subject, Observable, Subscription } from 'rxjs';
import moment, { Moment } from 'moment';
import { AppsProcessCloudService } from '../../../app/services/apps-process-cloud.service';
import { ProcessFilterCloudModel, ProcessFilterProperties, ProcessFilterAction, ProcessFilterOptions, ProcessSortFilterProperty } from '../models/process-filter-cloud.model';
import { TranslationService, UserPreferencesService, UserPreferenceValues } from '@alfresco/adf-core';
import { ProcessFilterCloudService } from '../services/process-filter-cloud.service';
import { ProcessFilterDialogCloudComponent } from './process-filter-dialog-cloud.component';
import { ProcessCloudService } from '../../services/process-cloud.service';
import { DateCloudFilterType, DateRangeFilter } from '../../../models/date-cloud-filter.model';
import { IdentityUserModel } from '../../../people/models/identity-user.model';

export const PROCESS_FILTER_ACTION_SAVE = 'save';
export const PROCESS_FILTER_ACTION_SAVE_AS = 'saveAs';
export const PROCESS_FILTER_ACTION_DELETE = 'delete';
export const PROCESS_FILTER_ACTION_SAVE_DEFAULT = 'saveDefaultFilter';
export const PROCESS_FILTER_ACTION_RESTORE = 'restoreDefaultFilter';
const DEFAULT_PROCESS_FILTER_PROPERTIES = ['status', 'sort', 'order', 'lastModified'];
const DEFAULT_SORT_PROPERTIES = ['id', 'name', 'status', 'startDate'];
const DEFAULT_ACTIONS = ['save', 'saveAs', 'delete'];

export interface DropdownOption {
    value: string;
    label: string;
}

@Component({
    selector: 'adf-cloud-edit-process-filter',
    templateUrl: './edit-process-filter-cloud.component.html',
    styleUrls: ['./edit-process-filter-cloud.component.scss'],
    encapsulation: ViewEncapsulation.None
})
export class EditProcessFilterCloudComponent implements OnInit, OnChanges, OnDestroy {
    /** The name of the application. */
    @Input()
    appName: string = '';

    /** roles to filter the apps */
    @Input()
    role: string = '';

    /** Id of the process instance filter. */
    @Input()
    id: string;

    /** List of process filter properties to display */
    @Input()
    filterProperties = DEFAULT_PROCESS_FILTER_PROPERTIES;

    /** List of sort properties to display. */
    @Input()
    sortProperties = DEFAULT_SORT_PROPERTIES;

    /** List of sort actions. */
    @Input()
    actions = DEFAULT_ACTIONS;

    /** Toggles editing of process filter actions. */
    @Input()
    showFilterActions = true;

    /** Toggles editing of the process filter title. */
    @Input()
    showTitle = true;

    /** Toggles the appearance of the process filter name . */
    @Input()
    showProcessFilterName = true;

    /** Emitted when a process instance filter property changes. */
    @Output()
    filterChange = new EventEmitter<ProcessFilterCloudModel>();

    /** Emitted when a filter action occurs i.e Save, SaveAs, Delete. */
    @Output()
    action = new EventEmitter<ProcessFilterAction>();

    private _filter: ProcessFilterCloudModel;
    protected filterHasBeenChanged = false;

    get processFilter() {
        return this._filter;
    }

    @Input()
    set processFilter(value: ProcessFilterCloudModel) {
        const isChanged = this.isFilterChanged(this._filter, value);

        this._filter = value;

        if (value?.appName) {
            this.appName = value.appName;
        }

        if (value?.id) {
            this.id = value.id;
        }

        this.processFilterProperties = this.createAndFilterProperties();
        this.processFilterActions = this.createAndFilterActions();

        this.buildForm(this.processFilterProperties);

        if (isChanged) {
            this.filterChange.emit(value);
        }
    }

    status: Array<DropdownOption> = [
        { value: '', label: 'ADF_CLOUD_PROCESS_FILTERS.STATUS.ALL' },
        { value: 'RUNNING', label: 'ADF_CLOUD_PROCESS_FILTERS.STATUS.RUNNING' },
        { value: 'SUSPENDED', label: 'ADF_CLOUD_PROCESS_FILTERS.STATUS.SUSPENDED' },
        { value: 'CANCELLED', label: 'ADF_CLOUD_PROCESS_FILTERS.STATUS.CANCELLED' },
        { value: 'COMPLETED', label: 'ADF_CLOUD_PROCESS_FILTERS.STATUS.COMPLETED' }
    ];
    directions: Array<DropdownOption> = [
        { value: 'ASC', label: 'ADF_CLOUD_PROCESS_FILTERS.DIRECTION.ASCENDING' },
        { value: 'DESC', label: 'ADF_CLOUD_PROCESS_FILTERS.DIRECTION.DESCENDING' }
    ];
    actionDisabledForDefault = [
        PROCESS_FILTER_ACTION_SAVE,
        PROCESS_FILTER_ACTION_DELETE
    ];
    applicationNames: any[] = [];
    allProcessDefinitionNamesOption: DropdownOption = {
        label: 'ADF_CLOUD_PROCESS_FILTERS.STATUS.ALL',
        value: ''
    };
    processDefinitionNames: any[] = [];
    editProcessFilterForm: UntypedFormGroup;
    processFilterProperties: ProcessFilterProperties[] = [];
    processFilterActions: ProcessFilterAction[] = [];
    toggleFilterActions: boolean = false;
    appVersionOptions: ProcessFilterOptions[] = [];
    initiatorOptions: IdentityUserModel[] = [];

    private onDestroy$ = new Subject<boolean>();
    isLoading: boolean = false;
    private filterChangeSub: Subscription;

    constructor(
        private formBuilder: UntypedFormBuilder,
        public dialog: MatDialog,
        private dateAdapter: DateAdapter<Moment>,
        private userPreferencesService: UserPreferencesService,
        private translateService: TranslationService,
        private processFilterCloudService: ProcessFilterCloudService,
        private appsProcessCloudService: AppsProcessCloudService,
        private processCloudService: ProcessCloudService) {
    }

    ngOnInit() {
        this.userPreferencesService
            .select(UserPreferenceValues.Locale)
            .pipe(takeUntil(this.onDestroy$))
            .subscribe(locale => this.dateAdapter.setLocale(locale));
    }

    ngOnChanges(changes: SimpleChanges) {
        const id = changes['id'];
        if (id && id.currentValue !== id.previousValue) {
            this.retrieveProcessFilterAndBuildForm();
        }
    }

    ngOnDestroy() {
        this.onDestroy$.next(true);
        this.onDestroy$.complete();
    }

    buildForm(processFilterProperties: ProcessFilterProperties[]) {
        this.editProcessFilterForm = this.formBuilder.group(this.getFormControlsConfig(processFilterProperties));
        this.onFilterChange();
    }

    getFormControlsConfig(processFilterProperties: ProcessFilterProperties[]): any {
        const properties = processFilterProperties.map((property) => {
            if (!!property.attributes) {
                return this.getAttributesControlConfig(property);
            } else {
                return { [property.key]: property.value };
            }
        });
        return properties.reduce(((result, current) => Object.assign(result, current)), {});
    }

    private getAttributesControlConfig(property: ProcessFilterProperties) {
        return Object.values(property.attributes).reduce((result, key) => {
            result[key] = property.value[key];
            return result;
        }, {});
    }

    /**
     * Fetches process instance filter by application name and filter id and creates filter properties, build form
     */
    retrieveProcessFilterAndBuildForm() {
        this.isLoading = true;
        this.processFilterCloudService
            .getFilterById(this.appName, this.id)
            .pipe(finalize(() => this.isLoading = false))
            .subscribe(response => {
                this.filterHasBeenChanged = false;
                this.processFilter = new ProcessFilterCloudModel(
                    Object.assign({}, response || {}, this.processFilter || {})
                );
            });
    }

    /**
     * Check process instance filter changes
     */
    onFilterChange() {
        if (this.filterChangeSub) {
            this.filterChangeSub.unsubscribe();
            this.filterChangeSub = null;
        }

        this.filterChangeSub = this.editProcessFilterForm.valueChanges
            .pipe(
                debounceTime(500),
                filter(() => this.isFormValid()),
                takeUntil(this.onDestroy$)
            )
            .subscribe((formValues: ProcessFilterCloudModel) => {
                this.setLastModifiedToFilter(formValues);

                const newValue = new ProcessFilterCloudModel(Object.assign({}, this.processFilter, formValues));
                const changed = !this.compareFilters(newValue, this.processFilter);
                this.filterHasBeenChanged = changed;

                if (changed) {
                    this._filter = newValue;
                    this.filterChange.emit(newValue);
                }
            });
    }

    createAndFilterProperties(): ProcessFilterProperties[] {
        this.checkMandatoryFilterProperties();

        if (this.filterProperties.includes('appName')) {
            this.getRunningApplications();
        }

        if (this.filterProperties.includes('processDefinitionName')) {
            this.getProcessDefinitions();
        }

        if (this.filterProperties.includes('appVersionMultiple')) {
            this.getAppVersionOptions();
        }

        if (this.filterProperties.includes('initiator')) {
            this.initiatorOptions = !!this.processFilter.initiator
                ? this.processFilter.initiator.split(',').map(username => Object.assign({}, { username }))
                : [];
        }

        const defaultProperties = this.createProcessFilterProperties(this.processFilter);
        let filteredProperties = defaultProperties.filter((filterProperty) => this.isValidProperty(this.filterProperties, filterProperty.key));

        if (!this.filterProperties.includes('sort')) {
            filteredProperties = filteredProperties.filter(property => property.key !== 'order');
        }

        if (this.filterProperties.includes('lastModified')) {
            filteredProperties = [
                ...filteredProperties,
                ...this.createLastModifiedProperty(this.processFilter)
            ];
        }

        return filteredProperties;
    }

    checkMandatoryFilterProperties() {
        if (this.filterProperties === undefined || this.filterProperties.length === 0) {
            this.filterProperties = DEFAULT_PROCESS_FILTER_PROPERTIES;
        }
    }

    private isValidProperty(filterProperties: string[], key: string): boolean {
        return filterProperties ? filterProperties.indexOf(key) >= 0 : true;
    }

    get createSortProperties(): ProcessFilterOptions[] {
        this.checkMandatorySortProperties();
        const defaultSortProperties = this.createProcessSortProperties();
        return defaultSortProperties.filter((sortProperty) => this.isValidProperty(this.sortProperties, sortProperty.key));
    }

    getAppVersionOptions() {
        this.appVersionOptions = [];

        this.processCloudService.getApplicationVersions(this.appName).subscribe((appVersions) => {
            appVersions.forEach(appVersion => {
                this.appVersionOptions.push({ label: appVersion.entry.version, value: appVersion.entry.version });
            });
        });
    }

    checkMandatorySortProperties() {
        if (this.sortProperties === undefined || this.sortProperties.length === 0) {
            this.sortProperties = DEFAULT_SORT_PROPERTIES;
        }
    }

    createAndFilterActions() {
        this.checkMandatoryActions();
        const actions = this.createFilterActions();
        return actions.filter((action) => this.isValidAction(this.actions, action));
    }

    checkMandatoryActions() {
        if (this.actions === undefined || this.actions.length === 0) {
            this.actions = DEFAULT_ACTIONS;
        }
    }

    private isValidAction(actions: string[], action: ProcessFilterAction): boolean {
        return actions ? actions.indexOf(action.actionType) >= 0 : true;
    }

    isFormValid(): boolean {
        return this.editProcessFilterForm.valid;
    }

    getPropertyController(property: ProcessFilterProperties): AbstractControl {
        return this.editProcessFilterForm.get(property.key);
    }

    onDateChanged(newDateValue: Moment, dateProperty: ProcessFilterProperties) {
        if (newDateValue) {
            const controller = this.getPropertyController(dateProperty);

            if (newDateValue.isValid()) {
                controller.setValue(newDateValue);
                controller.setErrors(null);
            } else {
                controller.setErrors({ invalid: true });
            }
        }
    }

    onDateTypeChange(dateType: DateCloudFilterType, property: ProcessFilterProperties) {
        this.editProcessFilterForm.get(property.attributes.dateType).setValue(dateType);
    }

    onDateRangeFilterChanged(dateRange: DateRangeFilter, property: ProcessFilterProperties) {
        this.editProcessFilterForm.get(property.attributes?.from).setValue(
            dateRange.startDate ? dateRange.startDate : null
        );
        this.editProcessFilterForm.get(property.attributes?.to).setValue(
            dateRange.endDate ? dateRange.endDate : null
        );
        this.editProcessFilterForm.get(property.attributes.dateType).setValue(DateCloudFilterType.RANGE);
    }

    onChangedUser(users: IdentityUserModel[], processProperty: ProcessFilterProperties) {
        this.getPropertyController(processProperty).setValue(users.map(user => user.username).join(','));
    }

    hasError(property: ProcessFilterProperties): boolean {
        const controller = this.getPropertyController(property);
        return controller.errors && controller.errors.invalid;
    }

    compareFilters(editedQuery: ProcessFilterCloudModel, currentQuery: ProcessFilterCloudModel): boolean {
        return JSON.stringify(editedQuery).toLowerCase() === JSON.stringify(currentQuery).toLowerCase();
    }

    getRunningApplications() {
        this.applicationNames = [];

        this.appsProcessCloudService
            .getDeployedApplicationsByStatus('RUNNING', this.role)
            .subscribe((applications) => {
                if (applications && applications.length > 0) {
                    applications.map((application) => {
                        this.applicationNames.push({ label: application.name, value: application.name });
                    });
                }
            });
    }

    getProcessDefinitions() {
        this.processDefinitionNames = [];

        this.processCloudService.getProcessDefinitions(this.appName).subscribe((processDefinitions) => {
            if (processDefinitions && processDefinitions.length > 0) {
                this.processDefinitionNames.push(this.allProcessDefinitionNamesOption);
                processDefinitions.map((processDefinition) => {
                    this.processDefinitionNames.push({ label: processDefinition.name, value: processDefinition.name });
                });
            }
        });
    }

    executeFilterActions(event: Event, action: ProcessFilterAction): void {
        if (action.actionType === PROCESS_FILTER_ACTION_SAVE) {
            this.save(action);
        } else if (action.actionType === PROCESS_FILTER_ACTION_SAVE_AS) {
            this.saveAs(action);
        } else if (action.actionType === PROCESS_FILTER_ACTION_DELETE) {
            this.delete(action);
        } else if (action.actionType === PROCESS_FILTER_ACTION_SAVE_DEFAULT) {
            this.save(action);
        } else if (action.actionType === PROCESS_FILTER_ACTION_RESTORE) {
            this.reset(action);
        }
        event.stopPropagation();
    }

    save(saveAction: ProcessFilterAction) {
        this.processFilterCloudService
            .updateFilter(this.processFilter)
            .subscribe(() => {
                saveAction.filter = this.processFilter;
                this.filterHasBeenChanged = false;
                this.action.emit(saveAction);
            });
    }

    /**
     * Delete a process instance filter
     */
    delete(deleteAction: ProcessFilterAction) {
        this.processFilterCloudService
            .deleteFilter(this.processFilter)
            .pipe(
                filter((filters) => {
                    deleteAction.filter = this.processFilter;
                    this.action.emit(deleteAction);
                    return filters.length === 0;
                }),
                switchMap(() => this.restoreDefaultProcessFilters()))
            .subscribe(() => { });
    }

    /**
     * Save As a process instance filter
     */
    saveAs(saveAsAction: ProcessFilterAction) {
        const dialogRef = this.dialog.open(ProcessFilterDialogCloudComponent, {
            data: {
                name: this.translateService.instant(this.processFilter.name)
            },
            height: 'auto',
            minWidth: '30%'
        });
        dialogRef.afterClosed().subscribe((result) => {
            if (result && result.action === ProcessFilterDialogCloudComponent.ACTION_SAVE) {
                const filterId = Math.random().toString(36).substr(2, 9);
                const filterKey = this.getSanitizeFilterName(result.name);
                const newFilter = {
                    name: result.name,
                    icon: result.icon,
                    id: filterId,
                    key: 'custom-' + filterKey
                };
                const resultFilter: ProcessFilterCloudModel = Object.assign({}, this.processFilter, newFilter);
                this.processFilterCloudService
                    .addFilter(resultFilter)
                    .subscribe(() => {
                        saveAsAction.filter = resultFilter;
                        this.filterHasBeenChanged = false;
                        this.action.emit(saveAsAction);
                    });
            }
        });
    }

    reset(resetAction: ProcessFilterAction) {
        this.processFilterCloudService.resetProcessFilterToDefaults(this.appName, this.processFilter).pipe(
            tap((filters: ProcessFilterCloudModel[]) => {
                resetAction.filter = filters.find(defaultFilter => defaultFilter.name === this.processFilter.name) || this.processFilter;
                this.action.emit(resetAction);
            }),
            switchMap(() => this.restoreDefaultProcessFilters()))
            .subscribe(() => { });
    }

    /**
     * Return filter name
     *
     * @param filterName
     */
    getSanitizeFilterName(filterName: string): string {
        const nameWithHyphen = this.replaceSpaceWithHyphen(filterName.trim());
        return nameWithHyphen.toLowerCase();
    }

    /**
     * Return name with hyphen
     *
     * @param name
     */
    replaceSpaceWithHyphen(name: string): string {
        const regExt = new RegExp(' ', 'g');
        return name.replace(regExt, '-');
    }

    restoreDefaultProcessFilters(): Observable<ProcessFilterCloudModel[]> {
        return this.processFilterCloudService.getProcessFilters(this.appName);
    }

    onExpand() {
        this.toggleFilterActions = true;
    }

    onClose() {
        this.toggleFilterActions = false;
    }

    isDisabledAction(action: ProcessFilterAction): boolean {
        return (
            this.processFilterCloudService.isDefaultFilter(this.processFilter.name) &&
            this.actionDisabledForDefault.includes(action.actionType)
        ) ? true : this.hasFilterChanged(action);
    }

    hasFilterChanged(action: ProcessFilterAction): boolean {
        return action.actionType === PROCESS_FILTER_ACTION_SAVE ||
            action.actionType === PROCESS_FILTER_ACTION_SAVE_AS ?
            !this.filterHasBeenChanged : false;
    }

    private setLastModifiedToFilter(formValues: ProcessFilterCloudModel) {
        if (formValues.lastModifiedTo && Date.parse(formValues.lastModifiedTo.toString())) {
            const lastModifiedToFilterValue = moment(formValues.lastModifiedTo);
            lastModifiedToFilterValue.set({
                hour: 23,
                minute: 59,
                second: 59
            });
            formValues.lastModifiedTo = lastModifiedToFilterValue.toDate();
        }
    }

    private createFilterActions(): ProcessFilterAction[] {
        return [
            {
                actionType: PROCESS_FILTER_ACTION_SAVE,
                icon: 'adf:save',
                tooltip: 'ADF_CLOUD_EDIT_PROCESS_FILTER.TOOL_TIP.SAVE'
            },
            {
                actionType: PROCESS_FILTER_ACTION_SAVE_AS,
                icon: 'adf:save-as',
                tooltip: 'ADF_CLOUD_EDIT_PROCESS_FILTER.TOOL_TIP.SAVE_AS'
            },
            {
                actionType: PROCESS_FILTER_ACTION_DELETE,
                icon: 'delete',
                tooltip: 'ADF_CLOUD_EDIT_PROCESS_FILTER.TOOL_TIP.DELETE'
            },
            {
                actionType: PROCESS_FILTER_ACTION_SAVE_DEFAULT,
                icon: 'adf:save',
                tooltip: 'ADF_CLOUD_EDIT_PROCESS_FILTER.TOOL_TIP.SAVE'
            },
            {
                actionType: PROCESS_FILTER_ACTION_RESTORE,
                icon: 'settings_backup_restore',
                tooltip: 'ADF_CLOUD_EDIT_PROCESS_FILTER.TOOL_TIP.RESTORE'
            }
        ];
    }

    private createLastModifiedProperty(filterModel: ProcessFilterCloudModel): ProcessFilterProperties[] {
        let lastModifiedFrom;
        let lastModifiedTo;

        if (filterModel.lastModifiedFrom) {
            lastModifiedFrom = moment(filterModel.lastModifiedFrom);
        }

        if (filterModel.lastModifiedTo) {
            lastModifiedTo = moment(filterModel.lastModifiedTo);
        }

        return [
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.LAST_MODIFIED_DATE_FORM',
                type: 'date',
                key: 'lastModifiedFrom',
                value: lastModifiedFrom
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.LAST_MODIFIED_TO',
                type: 'date',
                key: 'lastModifiedTo',
                value: lastModifiedTo
            }
        ];
    }

    private createProcessSortProperties(): ProcessSortFilterProperty[] {
        return [
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.ID',
                key: 'id',
                value: 'id'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_NAME',
                key: 'name',
                value: 'name'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.START_DATE',
                key: 'startDate',
                value: 'startDate'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.STATUS',
                key: 'status',
                value: 'status'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.STARTED_BY',
                key: 'initiator',
                value: 'initiator'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.APP_NAME',
                key: 'appName',
                value: 'appName'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.APP_VERSION',
                key: 'appVersion',
                value: 'appVersion'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_INS_ID',
                key: 'processInstanceId',
                value: 'processInstanceId'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_DEF_ID',
                key: 'processDefinitionId',
                value: 'processDefinitionId'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_DEF_NAME',
                key: 'processDefinitionName',
                value: 'processDefinitionName'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_DEF_KEY',
                key: 'processDefinitionKey',
                value: 'processDefinitionKey'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.LAST_MODIFIED',
                key: 'lastModified',
                value: 'lastModified'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.BUSINESS_KEY',
                key: 'businessKey',
                value: 'businessKey'
            }
        ];
    }

    private isFilterChanged(oldValue: ProcessFilterCloudModel, newValue: ProcessFilterCloudModel): boolean {
        const oldJson = JSON.stringify(
            this.processFilterCloudService.writeQueryParams(oldValue || {}, this.filterProperties)
        );
        const newJson = JSON.stringify(
            this.processFilterCloudService.writeQueryParams(newValue || {}, this.filterProperties)
        );

        return oldJson !== newJson;
    }

    private createProcessFilterProperties(filterModel: ProcessFilterCloudModel): ProcessFilterProperties[] {
        const appVersionMultiple = [];

        if (filterModel.appVersion) {
            appVersionMultiple.push(
                Array.isArray(filterModel.appVersion)
                    ? filterModel.appVersion.map(entry => entry.toString())
                    : `${filterModel.appVersion}`
            );
        }

        return [
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.APP_NAME',
                type: 'select',
                key: 'appName',
                value: filterModel.appName || '',
                options: this.applicationNames
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.APP_VERSION',
                type: 'number',
                key: 'appVersion',
                value: filterModel.appVersion
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.APP_VERSION',
                type: 'multi-select',
                key: 'appVersionMultiple',
                value: appVersionMultiple,
                options: this.appVersionOptions
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_INS_ID',
                type: 'text',
                key: 'processInstanceId',
                value: filterModel.processInstanceId || ''
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_NAME',
                type: 'text',
                key: 'processName',
                value: filterModel.processName || ''
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_DEF_NAME',
                type: 'select',
                key: 'processDefinitionName',
                value: filterModel.processDefinitionName || '',
                options: this.processDefinitionNames
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.STATUS',
                type: 'select',
                key: 'status',
                value: filterModel.status || this.status[0].value,
                options: this.status
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_DEF_ID',
                type: 'text',
                key: 'processDefinitionId',
                value: filterModel.processDefinitionId || ''
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.PROCESS_DEF_KEY',
                type: 'text',
                key: 'processDefinitionKey',
                value: filterModel.processDefinitionKey || ''
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.SORT',
                type: 'select',
                key: 'sort',
                value: filterModel.sort || this.createSortProperties[0].value,
                options: this.createSortProperties
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.DIRECTION',
                type: 'select',
                key: 'order',
                value: filterModel.order || this.directions[0].value,
                options: this.directions
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.COMPLETED_DATE',
                type: 'date',
                key: 'completedDate',
                value: filterModel.completedDate || false
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.STARTED_BY',
                type: 'people',
                key: 'initiator',
                value: filterModel.initiator,
                selectionMode: 'multiple'
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.COMPLETED_DATE',
                type: 'date-range',
                key: 'completedDateRange',
                attributes: { dateType: 'completedDateType', from: '_completedFrom', to: '_completedTo' },
                value: {
                    completedDateType: filterModel.completedDateType || null,
                    _completedFrom: filterModel.completedFrom || null,
                    _completedTo: filterModel.completedTo || null
                }
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.STARTED_DATE',
                type: 'date-range',
                key: 'startedDateRange',
                attributes: { dateType: 'startedDateType', from: '_startFrom', to: '_startTo' },
                value: {
                    startedDateType: filterModel.startedDateType || null,
                    _startFrom: filterModel.startFrom || null,
                    _startTo: filterModel.startTo || null
                }
            },
            {
                label: 'ADF_CLOUD_EDIT_PROCESS_FILTER.LABEL.SUSPENDED_DATE',
                type: 'date-range',
                key: 'suspendedDateRange',
                attributes: { dateType: 'suspendedDateType', from: '_suspendedFrom', to: '_suspendedTo' },
                value: {
                    suspendedDateType: filterModel.suspendedDateType || null,
                    _suspendedFrom: filterModel.suspendedFrom || null,
                    _suspendedTo: filterModel.suspendedTo || null
                }
            }
        ];
    }
}


text: module.exports = {extends: ['traverson']};

redpajama_set_name: RedPajamaGithub


text:
package gov.hhs.fha.nhinc.docquery.aspect;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import gov.hhs.fha.nhinc.event.BaseDescriptionBuilderTest;
import gov.hhs.fha.nhinc.event.EventDescription;
import gov.hhs.fha.nhinc.document.DocumentConstants;

import java.util.List;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryResponse;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ClassificationType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ExtrinsicObjectType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.IdentifiableType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryObjectListType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.SlotType1;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ValueListType;
import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryError;
import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryErrorList;

import org.junit.Test;

import com.google.common.base.Optional;

public class AdhocQueryResponseDescriptionBuilderTest extends BaseDescriptionBuilderTest {

    @Test
    public void emptyBuild() {
        AdhocQueryResponseDescriptionBuilder builder = new AdhocQueryResponseDescriptionBuilder(null);
        EventDescription eventDescription = getEventDescription(builder);
        assertNotNull(eventDescription);
    }

    @Test
    public void basicBuild() {
        AdhocQueryResponse response = getBasicResponse();
        AdhocQueryResponseDescriptionBuilder builder = new AdhocQueryResponseDescriptionBuilder(response);
        assertBasicResponseBuilt(builder);
    }

    @Test
    public void validRespnoseTypes() {
        AdhocQueryResponseDescriptionBuilder builder = new AdhocQueryResponseDescriptionBuilder();
        AdhocQueryResponse response = getBasicResponse();
        builder.setReturnValue(response);
        assertBasicResponseBuilt(builder);
    }

    @Test
    public void nullArguments() {
        AdhocQueryResponseDescriptionBuilder builder = new AdhocQueryResponseDescriptionBuilder();
        try {
            builder.setReturnValue(null);
        } catch (NullPointerException npe) {
            fail("Should accept null gracefully");
        }
    }

    @Test
    public void errors() {
        AdhocQueryResponse response = new AdhocQueryResponse();
        RegistryError error = new RegistryError();
        error.setErrorCode(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE);
        addError(response, error);

        error = new RegistryError();
        error.setErrorCode(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE);
        addError(response, error);

        error = new RegistryError();
        error.setErrorCode(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS);
        addError(response, error);

        AdhocQueryResponseDescriptionBuilder builder = new AdhocQueryResponseDescriptionBuilder(response);
        EventDescription eventDescription = getEventDescription(builder);

        assertEquals(3, eventDescription.getErrorCodes().size());
        assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE, eventDescription.getErrorCodes().get(0));
        assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE, eventDescription.getErrorCodes().get(1));
        assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS,
                eventDescription.getErrorCodes().get(2));
    }

    @Test
    public void mixedPayloadTypes() {
        AdhocQueryResponse response = new AdhocQueryResponse();

        addQueryResult(response, Optional.of("payloadType"), Optional.of(12345));
        addQueryResult(response, Optional.of("payloadType2"), Optional.of(1));

        AdhocQueryResponseDescriptionBuilder builder = new AdhocQueryResponseDescriptionBuilder(response);
        EventDescription eventDescription = getEventDescription(builder);

        assertEquals(2, eventDescription.getPayloadTypes().size());
        assertEquals("payloadType", eventDescription.getPayloadTypes().get(0));
        assertEquals("payloadType2", eventDescription.getPayloadTypes().get(1));
        assertEquals(2, eventDescription.getPayloadSizes().size());
        assertEquals("" + 12345, eventDescription.getPayloadSizes().get(0));
        assertEquals("" + 1, eventDescription.getPayloadSizes().get(1));
    }

    @Test
    public void keepDuplicateDescriptionElements() {
        AdhocQueryResponse response = new AdhocQueryResponse();

        addQueryResult(response, Optional.of("payloadType"), Optional.of(12345));
        addQueryResult(response, Optional.of("payloadType"), Optional.of(12345));

        AdhocQueryResponseDescriptionBuilder builder = new AdhocQueryResponseDescriptionBuilder(response);
        EventDescription eventDescription = getEventDescription(builder);

        assertEquals(2, eventDescription.getPayloadTypes().size());
        assertEquals("payloadType", eventDescription.getPayloadTypes().get(0));
        assertEquals("payloadType", eventDescription.getPayloadTypes().get(1));
        assertEquals(2, eventDescription.getPayloadSizes().size());
        assertEquals("" + 12345, eventDescription.getPayloadSizes().get(0));
    }

    @Test
    public void missingPayloadInfoCoercedToEmpty() {
        AdhocQueryResponse response = new AdhocQueryResponse();

        addQueryResult(response, Optional.<String> absent(), Optional.<Integer> absent());

        AdhocQueryResponseDescriptionBuilder builder = new AdhocQueryResponseDescriptionBuilder(response);
        EventDescription eventDescription = getEventDescription(builder);

        assertEquals(1, eventDescription.getPayloadTypes().size());
        assertEquals("", eventDescription.getPayloadTypes().get(0));
        assertEquals(1, eventDescription.getPayloadSizes().size());
        assertEquals("", eventDescription.getPayloadSizes().get(0));
    }

    private AdhocQueryResponse getBasicResponse() {
        AdhocQueryResponse response = new AdhocQueryResponse();
        response.setStatus(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS);
        addQueryResult(response, Optional.of("payloadType"), Optional.of(12345));
        return response;
    }

    private void assertBasicResponseBuilt(AdhocQueryResponseDescriptionBuilder builder) {
        EventDescription eventDescription = getEventDescription(builder);

        assertEquals(1, eventDescription.getStatuses().size());
        assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS, eventDescription.getStatuses().get(0));
        assertEquals(1, eventDescription.getRespondingHCIDs().size());
        assertEquals("home", eventDescription.getRespondingHCIDs().get(0));
        assertEquals(1, eventDescription.getPayloadTypes().size());
        assertEquals("payloadType", eventDescription.getPayloadTypes().get(0));
        assertEquals(1, eventDescription.getPayloadSizes().size());
        assertEquals("" + 12345, eventDescription.getPayloadSizes().get(0));

        assertNull(eventDescription.getTimeStamp());
        assertNull(eventDescription.getNPI()); // TODO: check with BH - is that correct
        assertNull(eventDescription.getInitiatingHCID());
    }

    private void addError(AdhocQueryResponse response, RegistryError error) {
        RegistryErrorList registryErrorList = response.getRegistryErrorList();
        if (registryErrorList == null) {
            registryErrorList = new RegistryErrorList();
            response.setRegistryErrorList(registryErrorList);
        }
        List<RegistryError> registryError = registryErrorList.getRegistryError();
        registryError.add(error);
    }

    private void addQueryResult(AdhocQueryResponse response, Optional<String> payloadType, Optional<Integer> size) {
        ExtrinsicObjectType extrinsicObject = new ExtrinsicObjectType();
        extrinsicObject.setStatus(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS);
        extrinsicObject.setHome("home");

        if (payloadType.isPresent()) {
            addPayloadType(extrinsicObject, payloadType.get());
        }
        if (size.isPresent()) {
            addPayloadSize(extrinsicObject, size.get());
        }

        addQueryResult(response, extrinsicObject);
    }

    private void addPayloadType(ExtrinsicObjectType extrinsicObject, String payloadType) {
        ClassificationType classificatonType = addClassification(extrinsicObject);
        SlotType1 slotType = addSlot(classificatonType, DocumentConstants.EBXML_RESPONSE_CODE_CODESCHEME_SLOTNAME);
        addValue(payloadType, slotType);
    }

    private void addPayloadSize(ExtrinsicObjectType extrinsicObject, int size) {
        SlotType1 slotType = new SlotType1();
        extrinsicObject.getSlot().add(slotType);

        slotType.setName(DocumentConstants.EBXML_RESPONSE_SIZE_SLOTNAME);
        addValue("" + size, slotType);
    }

    private ClassificationType addClassification(ExtrinsicObjectType extrinsicObject) {
        ClassificationType classificatonType = new ClassificationType();
        extrinsicObject.getClassification().add(classificatonType);
        classificatonType.setNodeRepresentation(DocumentConstants.EBXML_RESPONSE_NODE_REPRESENTATION_FORMAT_CODE);
        return classificatonType;
    }

    private SlotType1 addSlot(ClassificationType classificatonType, String slotName) {
        SlotType1 slotType = new SlotType1();
        classificatonType.getSlot().add(slotType);

        slotType.setName(slotName);
        return slotType;
    }

    private void addValue(String payloadType, SlotType1 slotType) {
        ValueListType valueListType = slotType.getValueList();
        if (valueListType == null) {
            valueListType = new ValueListType();
            slotType.setValueList(valueListType);
        }

        valueListType.getValue().add(payloadType);
    }

    private void addQueryResult(AdhocQueryResponse response, ExtrinsicObjectType extrinsicObject) {
        QName qName = mock(QName.class);
        JAXBElement<ExtrinsicObjectType> jaxbWrapper = new JAXBElement<ExtrinsicObjectType>(qName,
                ExtrinsicObjectType.class, extrinsicObject);

        RegistryObjectListType registryObjectList = response.getRegistryObjectList();
        if (registryObjectList == null) {
            registryObjectList = new RegistryObjectListType();
            response.setRegistryObjectList(registryObjectList);
        }

        List<JAXBElement<? extends IdentifiableType>> identifiable = response.getRegistryObjectList().getIdentifiable();
        identifiable.add(jaxbWrapper);
    }
}


text:
"""
 This module is for the miscellaneous GEOS routines, particularly the
 ones that return the area, distance, and length.
"""
from ctypes import c_int, c_double, POINTER
from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOS_PREPARE
from django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_string
from django.contrib.gis.geos.prototypes.geom import geos_char_p
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc

__all__ = ['geos_area', 'geos_distance', 'geos_length']

### ctypes generator function ###
def dbl_from_geom(func, num_geom=1):
    """
    Argument is a Geometry, return type is double that is passed
    in by reference as the last argument.
    """
    argtypes = [GEOM_PTR for i in xrange(num_geom)]
    argtypes += [POINTER(c_double)]
    func.argtypes = argtypes
    func.restype = c_int # Status code returned
    func.errcheck = check_dbl
    return func

### ctypes prototypes ###

# Area, distance, and length prototypes.
geos_area = dbl_from_geom(GEOSFunc('GEOSArea'))
geos_distance = dbl_from_geom(GEOSFunc('GEOSDistance'), num_geom=2)
geos_length = dbl_from_geom(GEOSFunc('GEOSLength'))

# Validity reason; only in GEOS 3.1+
if GEOS_PREPARE:
    geos_isvalidreason = GEOSFunc('GEOSisValidReason')
    geos_isvalidreason.argtypes = [GEOM_PTR]
    geos_isvalidreason.restype = geos_char_p
    geos_isvalidreason.errcheck = check_string
    __all__.append('geos_isvalidreason')


text:
<?php

namespace Sonata\CoreBundle\Form\Type;

use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class TranslatableChoiceType extends AbstractType
{
    protected $translator;

    /**
     * @param \Symfony\Component\Translation\TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * {@inheritdoc}
     *
     * @todo Remove it when bumping requirements to SF 2.7+
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $this->configureOptions($resolver);
    }

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'catalogue' => 'messages',
        ));
    }

    /**
     * {@inheritDoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['translation_domain'] = $options['catalogue'];
    }

    /**
     * {@inheritDoc}
     */
    public function getParent()
    {
        return 'choice';
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'sonata_type_translatable_choice';
    }
}


text:
TEST(ZSwcMetric, measure)
{
  ZSwcTerminalSurfaceMetric metric;

  ZSwcTree tree1;
  ZSwcTree tree2;

  tree1.load(GET_TEST_DATA_DIR + "/benchmark/bundle1/swc/1.swc");
  tree2.load(GET_TEST_DATA_DIR + "/benchmark/bundle1/swc/2.swc");

  double dist = metric.measureDistance(&tree1, &tree2);

  EXPECT_DOUBLE_EQ(5000, dist);

  tree2.load(GET_TEST_DATA_DIR + "/benchmark/bundle1/swc/3.swc");
  dist = metric.measureDistance(&tree1, &tree2);
  EXPECT_DOUBLE_EQ(19015.232570685483, dist);

  tree2.load(GET_TEST_DATA_DIR + "/benchmark/bundle1/swc/4.swc");
  dist = metric.measureDistance(&tree1, &tree2);
  EXPECT_GT(0, dist);

  ZSwcTerminalAngleMetric metric2;
  metric2.setDistanceWeight(false);
  tree2.load(GET_TEST_DATA_DIR + "/benchmark/bundle1/swc/2.swc");
  dist = metric2.measureDistance(&tree1, &tree2);

  EXPECT_DOUBLE_EQ(0.0, dist);

  tree2.load(GET_TEST_DATA_DIR + "/benchmark/bundle1/swc/3.swc");
  dist = metric2.measureDistance(&tree1, &tree2);

  EXPECT_DOUBLE_EQ(2.8551067559664194, dist);

  tree2.load(GET_TEST_DATA_DIR + "/benchmark/bundle1/swc/4.swc");
  dist = metric2.measureDistance(&tree1, &tree2);

  EXPECT_DOUBLE_EQ(1.5707963267948966, dist);

  ZSwcDeepAngleMetric metric3;
  metric3.setMinDist(10000.0);
  tree2.load(GET_TEST_DATA_DIR + "/benchmark/bundle1/swc/2.swc");
  dist = metric3.measureDistance(&tree1, &tree2);

  EXPECT_DOUBLE_EQ(0.0, dist);

  metric3.setLevel(3);

  dist = metric3.measureDistance(&tree1, &tree2);

  EXPECT_DOUBLE_EQ(0.0, dist);

  std::cout << dist << std::endl;
}

#endif

#endif // ZSWCMETRICTEST_H


text:
package org.bitbucket.mlopatkin.android.liblogcat.filters;

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang3.StringUtils;
import org.bitbucket.mlopatkin.android.liblogcat.LogRecord;

/**
 * Performs filtering based on the PID value of the record. If multiple pids are
 * specified in the filter it matches any of them.
 */
public class MultiPidFilter extends AbstractFilter implements LogRecordFilter {

    private Set<Integer> pids = new TreeSet<Integer>();

    public MultiPidFilter(int[] pids) {
        for (int pid : pids) {
            this.pids.add(pid);
        }
    }

    @Override
    public boolean include(LogRecord record) {
        return pids.contains(record.getPid());
    }

    @Override
    public String toString() {
        return "PID" + (pids.size() > 1 ? "s" : "") + ": " + StringUtils.join(pids, ", ");
    }

    @Override
    protected void dumpFilter(FilterData data) {
        data.pids = Collections.unmodifiableCollection(pids);
    }
}


text:
"""Bundle HDF5 DLLs into an h5py wheel on Windows

This is meant to do something like auditwheel on Linux & delocate on Mac,
but h5py-specific.
"""
from base64 import urlsafe_b64encode
from contextlib import contextmanager
from glob import glob
import hashlib
import os
import os.path as osp
import shutil
import sys
import tempfile
from zipfile import ZipFile, ZIP_DEFLATED

def find_dlls():
    hdf5_path = os.environ.get("HDF5_DIR")
    print("HDF5_DIR", hdf5_path)
    yield from glob(os.path.join(hdf5_path, 'lib', 'hdf*.dll'))
    zlib_root = os.environ.get("ZLIB_ROOT")
    if zlib_root:
        print("ZLIB_ROOT", zlib_root)
        yield os.path.join(zlib_root, 'bin_release', 'zlib.dll')

def file_sha256(path):
    h = hashlib.sha256()
    with open(path, 'rb') as src:
        while True:
            buf = src.read(1024 * 8)
            if not buf:
                break
            h.update(buf)

    return urlsafe_b64encode(h.digest()).decode('ascii').rstrip('=')

def find_wheels():
    wheelhouse_dir = sys.argv[1]
    return glob(osp.join(wheelhouse_dir, '*.whl'))

@contextmanager
def modify_zip(zip_file):
    with tempfile.TemporaryDirectory() as td:
        with ZipFile(zip_file, 'r') as zf:
            zf.extractall(path=td)
        yield td

        with ZipFile(zip_file, 'w', compression=ZIP_DEFLATED) as zf:
            for root, dirs, files in os.walk(td):
                for f in sorted(files):
                    path = osp.join(root, f)
                    zf.write(path, arcname=osp.relpath(path, td))

                dirs.sort()

def bundle(whl_file):
    print("Adding DLLs to", whl_file)

    with modify_zip(whl_file) as td:
        # Find & read RECORD file
        records = glob(osp.join(td, '*.dist-info', 'RECORD'))
        assert len(records) == 1, records
        record_f = records[0]
        with open(record_f, encoding='utf-8') as f:
            record = f.read().strip() + '\n'

        # Copy DLLs & add them to RECORD
        for dll in find_dlls():
            size = os.stat(dll).st_size
            sha = file_sha256(dll)
            dest = 'h5py/' + os.path.basename(dll)
            print(f"{dest} ({size} bytes)")
            shutil.copy2(dll, osp.join(td, dest))

            record += f'{dest},sha256={sha},{size}\n'

        print("Writing modified", record_f)
        with open(record_f, 'w', encoding='utf-8') as f:
            f.write(record)

def main():
    if not sys.platform.startswith('win'):
        print("Non-windows platform, skipping bundle_hdf5_whl.py")
        return

    for whl_file in find_wheels():
        bundle(whl_file)

if __name__ == '__main__':
    main()


text:
<?php
include("DAO/conexao.php");
include("DAO/financeiroDAO.php");

$id_parcela = $_GET['id'];
echo $mes = $_GET['mes'];

confirmaRecebimento($conexao, $id_parcela);

header("location: aReceber.php?mes=".$mes);
die();


text:
@interface iMenu : NSMenu
@property (assign,nonatomic) NSInteger index;
@property (strong,nonatomic) iDeviceGroup *deviceGroup;
@property (strong,nonatomic) iDevice *device;
@property (strong,nonatomic) iAPP *app;
@end


text:
GSSContext::GSSContext( const GSSBuffer& buff )
{
	import_context( buff );
}

void GSSContext::clear()
{
	OM_uint32 min;
	gss_delete_sec_context( &min, &_context, GSS_C_NO_BUFFER );
}

bool GSSContext::initialize(
	GSSBuffer& input, const GSSName& target, const Flags& flags,
	const GSSCredential& cred, GSSMech mech, OM_uint32 time, gss_channel_bindings_t bindings
)
{
	GSSBuffer recv_tok, send_tok;
	OM_uint32 maj_stat, min_stat, ret_flags;

	maj_stat = gss_init_sec_context(
			&min_stat,
			const_cast<GSSCredential&>( cred ),
			&_context,
			target,
			mech,
			flags,
			time,
			bindings,
			input,
			0,
			send_tok,
			&ret_flags,
			0
	);

	if ( !valid() || ( maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED ) ) {
		throw GSSException( maj_stat, min_stat, "gss_init_sec_context" );
	}

	input.swap( send_tok );

	return maj_stat == GSS_S_CONTINUE_NEEDED;
}

bool GSSContext::accept( GSSBuffer& input, const GSSCredential& cred, gss_channel_bindings_t bindings )
{
	GSSBuffer output;
	OM_uint32 maj_stat, min_stat, ret_flags;

	maj_stat = gss_accept_sec_context(
			&min_stat,
			&_context,
			const_cast<GSSCredential&>( cred ),
			input,
			bindings,
			0,        // gss_name_t* - name of initiating principle
			0,        // gss_OID*    - security mechanism used
			output,
			0,        // OM_uint32*  - ret_flags
			0,        // OM_uint32*  - time_req
			0         // gss_cred_id_t* - delegated_cred_handle - only valid if ret_flags contains GSS_C_DELEG_FLAG
	);

	if ( !valid() || ( maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED ) )
		throw GSSException( maj_stat, min_stat, "gss_accept_sec_context" );

	input.swap( output );

	return maj_stat == GSS_S_CONTINUE_NEEDED;
}

void GSSContext::import_context( const GSSBuffer& buff )
{
	OM_uint32 maj, min;
	maj = gss_import_sec_context( &min, const_cast<GSSBuffer&>( buff ), &_context );

	if ( maj != GSS_S_COMPLETE )
	{
		throw GSSException( maj, min, "gss_import_sec_context" );
	}
}

GSSBuffer GSSContext::export_context()
{
	OM_uint32 maj, min;
	GSSBuffer exported;
	gss_export_sec_context( &min, &_context, exported );

	if ( maj != GSS_S_COMPLETE )
	{
		throw GSSException( maj, min, "gss_export_sec_context" );
	}

	return exported;
}

GSSBuffer GSSContext::get_mic( const GSSBuffer& message, gss_qop_t qop ) const
{
	OM_uint32 maj, min;
	GSSBuffer mic;

	maj = gss_get_mic( &min, _context, qop, const_cast<GSSBuffer&>( message ), mic );

	if ( maj != GSS_S_COMPLETE )
	{
		throw GSSException( maj, min, "gss_get_mic" );
	}

	return mic;
}

bool GSSContext::verify_mic( const GSSBuffer& message, const GSSBuffer& mic, gss_qop_t * qop_state ) const
{
	OM_uint32 maj, min;
	maj = gss_verify_mic( &min, _context, const_cast<GSSBuffer&>( message ), const_cast<GSSBuffer&>( mic ), qop_state );

	if ( maj == GSS_S_COMPLETE )
		return true;
	if ( maj == GSS_S_BAD_SIG )
		return false;
	throw GSSException( maj, min, "gss_verify_mic" );
}

GSSBuffer GSSContext::wrap( const GSSBuffer& message, bool encrypt, gss_qop_t qop ) const
{
	return wrap( *this, message, encrypt, qop );
}

GSSBuffer GSSContext::wrap( const GSSContext& context, const GSSBuffer& message, bool encrypt, gss_qop_t qop )
{
	OM_uint32 maj, min;
	GSSBuffer wrapped;
	maj = gss_wrap( &min, context, encrypt, qop, const_cast<GSSBuffer&>( message ), 0, wrapped );

	if ( maj != GSS_S_COMPLETE )
	{
		throw GSSException( maj, min, "gss_wrap" );
	}

	return wrapped;
}

void GSSContext::wrap_in_place( GSSBuffer& message, bool encrypt, gss_qop_t qop ) const
{
	wrap_in_place( *this, message, encrypt, qop );
}

void GSSContext::wrap_in_place( const GSSContext& context, GSSBuffer& message, bool encrypt, gss_qop_t qop )
{
	GSSBuffer tmp( wrap( context, message, encrypt, qop ) );
	message.swap( tmp );
}

GSSBuffer GSSContext::unwrap( const GSSBuffer& wrapped, bool * conf_state, gss_qop_t * qop_state ) const
{
	return unwrap( *this, wrapped, conf_state, qop_state );
}

GSSBuffer GSSContext::unwrap( const GSSContext& context, const GSSBuffer& message, bool * conf_state, gss_qop_t * qop_state )
{
	OM_uint32 maj, min;
	int iconf_state;
	GSSBuffer unwrapped;
	maj = gss_unwrap( &min, context, const_cast<GSSBuffer&>( message ), unwrapped, &iconf_state, qop_state );

	if ( maj != GSS_S_COMPLETE )
		throw GSSException( maj, min, "gss_unwrap" );

	if ( conf_state )
		*conf_state = iconf_state;

	return unwrapped;
}

void GSSContext::unwrap_in_place( GSSBuffer& wrapped, bool * conf_state, gss_qop_t * qop_state ) const
{
	unwrap_in_place( *this, wrapped, conf_state, qop_state );
}

void GSSContext::unwrap_in_place( const GSSContext& context, GSSBuffer& message, bool * conf_state, gss_qop_t * qop_state )
{
	GSSBuffer tmp( unwrap( context, message, conf_state, qop_state ) );
	message.swap( tmp );
}

size_t GSSContext::wrap_size_limit( size_t max_size, bool encrypt, gss_qop_t qop ) const
{
	OM_uint32 maj, min, size_limit;
	maj = gss_wrap_size_limit( &min, _context, encrypt, qop, max_size, &size_limit );

	if ( maj != GSS_S_COMPLETE )
		throw GSSException( maj, min, "gss_wrap_size_limit" );

	return size_limit;
}


text:
ivar.namespace('ivar.data');

/**
 * @example
 *	a = {'a':1,
		'b':{'c':[1,2,[3,45],4,5],
			'd':{'q':1, 'b':{q':1, 'b':8},'c':4},
			'u':'lol'},
		'e':2};

	b = {'a':1,
		'b':{'c':[2,3,[1]],
			'd':{'q':3,'b':{'b':3}}},
		'e':2};

	c = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

	var hc = new HashMap();
	hc.put({a:1, b:1});
	hc.put({b:1, a:1});
	hc.put(true);
	hc.put('true');
	hc.put(a)
	console.log(hc.exists(b))
	console.log(hc.exists(a))
	console.log(hc.get(a))
	console.log(hc.exists(c))
	hc.remove(a)
	console.log(hc.exists(a))
	hc.put(c)
	console.log(hc.exists(c))
	console.log(hc.get(c))

 * @class
 * @param	{array}	a	An array of objects {key: key, value: value} to store on init
 */
ivar.data.HashMap = function(a) {
	/**
	 * Keeps values in arrays labeled under typewise crc32 hashes
	 *
	 * @this	HashMap
	 * @protected
	 */
	var storage = {};

	this.getStorage = function() {
		return storage;
	}

	/**
	 * Produces an integer hash of a given value
	 * If the object is passed, before JSON stringification the properties are ordered. Note that because crc32 hashes strings, then boolean true would be the same as string 'true' or a sting '123' would be the same as integer 123, etc... We could add some modifier to solve this but a chance of using this with a set of values different by type is low in common use.
	 *
	 * @this 	HashCache
	 * @protected
	 * @param	{any}	value 	Any value to be hashed
	 * @return	{integer}		Integer hash
	 *
	 * @see 	ivar.orderedStringify
	 * @see 	ivar.whatis
	 * @see 	ivar.types
	 */
	var hashFn = function(value) {
		var type = ivar.types[ivar.whatis(value)];

		if (type === 5 || type === 6) {
			value = ivar.orderedStringify(value);
		} else {
			value = value.toString();
		}

		return	ivar.crc32(value);
	};

	/**
	 * Gets value stored under the submited key
	 *
	 * @this	HashMap
	 *
	 * @param	{any}		key		Submited key
	 * @return	{any}				Value stored under the key
	 *
	 * @see HashMap.storage
	 * @see	ivar.equal
	 */
	this.get = function(key) {
		var hash = hashFn(key);
		var bucket = storage[hash];
		if (bucket && bucket.length > 0) {
			for (var i = 0; i < bucket.length; i++) {
				if(ivar.equal(bucket[i].key, key))
					return bucket[i].value;
			}
		}
	};

	/**
	 * Gets bucket id if the key is already stored under the hash in the bucket
	 * Only for this.put
	 *
	 * @this	HashMap
	 *
	 * @param	{any}		key		Submited key
	 * @return	{integer}			If the key exists in bucket returns positive integer, otherwise -1
	 *
	 * @see HashMap.storage
	 * @see	ivar.equal
	 */
	var getBucketId = function(hash, key) {
		var bucket = storage[hash];
		if (bucket && bucket.length > 0) {
			for (var i = 0; i < bucket.length; i++) {
				if(ivar.equal(bucket[i].key, key))
					return i;
			}
		}
		return -1;
	};

	/**
	 * Hashes the value and stores it in the hash table where the generated hash is a key
	 *
	 * @this	HashMap
	 * @public
	 * @param	{any}	key 	Any value to be stored
	 * @param	{any}	value 	Any value to be stored
	 *
	 * @see	HashMap.hashFn
	 * @see HashMap.storage
	 * @see	HashMap.getBucketId
	 */
	this.put = function(key, value) {
		var hash = hashFn(key);
		var bucket_id = getBucketId(hash, key);
		if(bucket_id === -1) {
			if (storage.hasOwnProperty(hash)) {
				storage[hash].push({key: key, value: value});
			} else {
				storage[hash] = [{key: key, value: value}];
			}
		} else {
			storage[hash][bucket_id] = {key: key, value: value};
		}
	}

	/**
	 * Checks if the value is listed in HashCache instance
	 *
	 * @this	HashMap
	 * @public
	 * @param	{any}	key 	Any key to be checked for existance
	 * @return	{boolean}		If the value is listed
	 *
	 * @see	HashMap.hashFn
	 * @see HashMap.hashHoldsKey
	 */
	this.exists = function(key) {
		var hash = hashFn(key);
		return getBucketId(hash, key) > -1 ? true : false;
	}

	/**
	 * Finds the value listed and removes it from the HashCache instance
	 *
	 * @this	HashMap
	 * @public
	 * @param	{any}	value 	Any value to be removed
	 * @return 	{boolean}		If the value existed and was removed
	 *
	 * @see	HashMap.hashFn
	 * @see HashMap.storage
	 * @see ivar.equal
	 */
	this.remove = function(key) {
		var hash = hashFn(key);
		var bucket_id = getBucketId(hash, key);
		var res = false;
		if(bucket_id > -1) {
			bucket_id > 0 ? storage[hash].splice(bucket_id, 1) : delete storage[hash];
			return true;
		}
		return res;
	}

	//INIT
	if (a !== undefined && ivar.whatis(a) === 'array') {
		for (var i = 0; i < a.length; i++) {
			this.put(a[i].key, a[i].value);
		}
	}
};


text:
if (NOT syngeo_NAME)

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)

include (ExternalProject)
include (ExternalSource)
include (BuildSupport)

include (python)
include (setuptools)

external_git_repo (syngeo
    HEAD
    http://github.com/janelia-flyem/synapse-geometry.git)

message ("Installing ${syngeo_NAME} into FlyEM build area: ${BUILDEM_DIR} ...")
ExternalProject_Add(${syngeo_NAME}
    DEPENDS             ${python_NAME} ${setuptools_NAME}
    PREFIX              ${BUILDEM_DIR}
    GIT_REPOSITORY      ${syngeo_URL}
    GIT_TAG             ${syngeo_TAG}
    UPDATE_COMMAND      ""
    PATCH_COMMAND       ""
    CONFIGURE_COMMAND   ""
    BUILD_COMMAND       ${BUILDEM_ENV_STRING} ${PYTHON_EXE} setup.py install
    BUILD_IN_SOURCE     1
    TEST_COMMAND        ""
    INSTALL_COMMAND     ""
)

set_target_properties(${syngeo_NAME} PROPERTIES EXCLUDE_FROM_ALL ON)

endif (NOT syngeo_NAME)


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_dom_MobileNetworkInfo_h
#define mozilla_dom_MobileNetworkInfo_h

#include "mozilla/dom/MozMobileNetworkInfoBinding.h"
#include "nsIMobileNetworkInfo.h"
#include "nsPIDOMWindow.h"
#include "nsWrapperCache.h"

namespace mozilla {
namespace dom {

class MobileNetworkInfo final : public nsIMobileNetworkInfo
                              , public nsWrapperCache
{
public:
  NS_DECL_NSIMOBILENETWORKINFO
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(MobileNetworkInfo)

  explicit MobileNetworkInfo(nsPIDOMWindow* aWindow);

  MobileNetworkInfo(const nsAString& aShortName, const nsAString& aLongName,
                    const nsAString& aMcc, const nsAString& aMnc,
                    const nsAString& aState);

  void
  Update(nsIMobileNetworkInfo* aInfo);

  nsPIDOMWindow*
  GetParentObject() const
  {
    return mWindow;
  }

  virtual JSObject*
  WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;

  // WebIDL interface
  Nullable<MobileNetworkState>
  GetState() const
  {
    uint32_t i = 0;
    for (const EnumEntry* entry = MobileNetworkStateValues::strings;
         entry->value;
         ++entry, ++i) {
      if (mState.EqualsASCII(entry->value)) {
        return Nullable<MobileNetworkState>(static_cast<MobileNetworkState>(i));
      }
    }

    return Nullable<MobileNetworkState>();
  }

private:
  ~MobileNetworkInfo() {}

private:
  nsCOMPtr<nsPIDOMWindow> mWindow;
  nsString mShortName;
  nsString mLongName;
  nsString mMcc;
  nsString mMnc;
  nsString mState;
};

} // namespace dom
} // namespace mozilla

#endif // mozilla_dom_MobileNetworkInfo_h


text: docker build -t simonellistonball/provisioner ./


text:
<?php
/**
 * The template for displaying archive pages
 */
get_header();
?>
<div <?php mbtheme_content_area_class( array( 'container' ) ); ?>>

    <?php do_action( 'mbtheme_before_site_main', 'archive' ); ?>

    <!-- BEGIN SITE MAIN -->
    <main class="site-main" role="main">

        <?php do_action( 'mbtheme_site_main', 'archive' ); ?>

    </main><!-- .site-main -->
    <!-- END SITE MAIN -->

    <?php do_action( 'mbtheme_after_site_main', 'archive' ); ?>

</div><!-- .site-content-area -->
<?php
get_footer();


text:
<?php
/**
 * @category Ext
 * @package Ext_HandlerSocket
 * @subpackage Driver
 * @author Alexey Rusnak
 * @license https://github.com/rusnak/Ext/wiki/MIT-License MIT License
 */

interface Ext_HandlerSocket_Driver_Encoder_EncoderInterface
{
    public function encode($request);

    public function decode($response);
}


text:
'''
test_file - Tests dns_sprockets_lib.loaders.file module.

.. Copyright (c) 2015 Neustar, Inc. All rights reserved.
.. See COPYRIGHT.txt for full notice.  See LICENSE.txt for terms and conditions.
'''
# pylint: skip-file

import dns.rdatatype
import dns.zone

from dns_sprockets_lib.loaders.file import File

def test_File():

    class test_args(object):
        source = 'dns_sprockets_lib/tests/data/001.cst.net.'
        zone = '001.cst.net'

    test_file = File(test_args())
    assert test_file.rdclass == 'IN'
    assert test_file.allow_include == '1'

    zone_obj = test_file.run()
    assert isinstance(zone_obj, dns.zone.Zone)
    assert zone_obj.get_rdataset('001.cst.net.', dns.rdatatype.SOA)

# end of file