text:
<title>Docs For Class PHPExcel_DocumentSecurity</title>
<link rel="stylesheet" type="text/css" href="../media/style.css">

    PHPExcel

                                                                                [ class tree: PHPExcel ]
		  [ index: PHPExcel ]
		  	    [ all elements ]

Todo List

      Packages:

              PHPExcel

              com-tecnick-tcpdf

              JAMA

              Math_Stats

              PHPExcel_CachedObjectStorage

              PHPExcel_Calculation

              PHPExcel_Cell

              PHPExcel_Reader

              PHPExcel_Reader_Excel5

              PHPExcel_RichText

              PHPExcel_Settings

              PHPExcel_Shared

              PHPExcel_Shared_Best_Fit

              PHPExcel_Shared_Escher

              PHPExcel_Shared_OLE

              PHPExcel_Style

              PHPExcel_Worksheet

              PHPExcel_Worksheet_Drawing

              PHPExcel_Writer

              PHPExcel_Writer_Excel5

              PHPExcel_Writer_Excel2007

                        Files:

					arialunicid0-chinese-simplified.php

					arialunicid0-chinese-traditional.php

					arialunicid0-japanese.php

					arialunicid0-korean.php

					arialunicid0.php

					Autoloader.php

					CachedObjectStorageFactory.php

					Comment.php

					courier.php

					credits.php

					docs.php

					DocumentProperties.php

					DocumentSecurity.php

					download.php

					example.php

					footer.php

					freesans.php

					freesansb.php

					freesansbi.php

					freesansi.php

					HashTable.php

					header.php

					helvetica.php

					helveticab.php

					helveticabi.php

					helveticai.php

					IComparable.php

					index.php

					IOFactory.php

					LagrangeInterpolation.php

					LagrangeInterpolation2.php

					LevenbergMarquardt.php

					LMQuadTest.php

					NamedRange.php

					navbar.php

					package.php

					PHPExcel.php

					polyfit.php

					ReferenceHelper.php

					test.php

					TestMatrix.php

					tile.php

					trendClass.php

					uni2cid_ac15.php

					uni2cid_ag15.php

					uni2cid_aj16.php

					uni2cid_ak12.php

					WorksheetIterator.php

            Interfaces:

		    		PHPExcel_IComparable

            Classes:

		    		LagrangeInterpolation

	    		LevenbergMarquardt

	    		LMQuadTest

	    		PHPExcel

	    		PHPExcel_Autoloader

	    		PHPExcel_CachedObjectStorageFactory

	    		PHPExcel_Comment

	    		PHPExcel_DocumentProperties

	    		PHPExcel_DocumentSecurity

	    		PHPExcel_HashTable

	    		PHPExcel_IOFactory

	    		PHPExcel_NamedRange

	    		PHPExcel_ReferenceHelper

	    		PHPExcel_WorksheetIterator

	    		TestMatrix

	    		trendClass

Class: PHPExcel_DocumentSecurity

Source Location: /PHPExcel/DocumentSecurity.php

Class Overview

PHPExcel_DocumentSecurity

Author(s):

Copyright:

Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel)

Methods

__construct

getLockRevision

getLockStructure

getLockWindows

getRevisionsPassword

getWorkbookPassword

isSecurityEnabled

setLockRevision

setLockStructure

setLockWindows

setRevisionsPassword

setWorkbookPassword

__clone

Class Details

[line 36]

PHPExcel_DocumentSecurity

Tags:

    copyright:  	Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel)

[ Top ]

Class Methods

constructor __construct [line 76]

		PHPExcel_DocumentSecurity __construct(
)

		Create a new PHPExcel_DocumentSecurity

Tags:

    access:  	public

[ Top ]

method getLockRevision [line 102]

		boolean getLockRevision(
)

		Get LockRevision

[ Top ]

method getLockStructure [line 122]

		boolean getLockStructure(
)

		Get LockStructure

[ Top ]

method getLockWindows [line 142]

		boolean getLockWindows(
)

		Get LockWindows

[ Top ]

method getRevisionsPassword [line 162]

		string getRevisionsPassword(
)

		Get RevisionsPassword (hashed)

[ Top ]

method getWorkbookPassword [line 186]

		string getWorkbookPassword(
)

		Get WorkbookPassword (hashed)

[ Top ]

method isSecurityEnabled [line 91]

		boolean isSecurityEnabled(
)

		Is some sort of dcument security enabled?

[ Top ]

method setLockRevision [line 112]

		PHPExcel_DocumentSecurity setLockRevision(
[boolean
$pValue = false])

		Set LockRevision

Parameters:

        boolean
        $pValue

[ Top ]

method setLockStructure [line 132]

		PHPExcel_DocumentSecurity setLockStructure(
[boolean
$pValue = false])

		Set LockStructure

Parameters:

        boolean
        $pValue

[ Top ]

method setLockWindows [line 152]

		PHPExcel_DocumentSecurity setLockWindows(
[boolean
$pValue = false])

		Set LockWindows

Parameters:

        boolean
        $pValue

[ Top ]

method setRevisionsPassword [line 173]

		PHPExcel_DocumentSecurity setRevisionsPassword(
[string
$pValue = ''], [boolean
$pAlreadyHashed = false])

		Set RevisionsPassword

Parameters:

        string
        $pValue

        boolean
        $pAlreadyHashed
        If the password has already been hashed, set this to true

[ Top ]

method setWorkbookPassword [line 197]

		PHPExcel_DocumentSecurity setWorkbookPassword(
[string
$pValue = ''], [boolean
$pAlreadyHashed = false])

		Set WorkbookPassword

Parameters:

        string
        $pValue

        boolean
        $pAlreadyHashed
        If the password has already been hashed, set this to true

[ Top ]

method __clone [line 208]

		void __clone(
)

		Implement PHP __clone to create a deep clone, not just a shallow copy.

Tags:

    access:  	public

[ Top ]

		    Documentation generated on Tue, 01 Jun 2010 17:02:48 +0200 by phpDocumentor 1.4.3


text:
import React from "react";
import { Section, Input, InputNumber, Switch } from "@/components/visualizations/editor";
import { EditorPropTypes } from "@/visualizations/prop-types";

import { isValueNumber } from "../utils";

export default function FormatSettings({ options, data, onOptionsChange }: any) {
  const inputsEnabled = isValueNumber(data.rows, options);
  return (
    <React.Fragment>
      {/* @ts-expect-error ts-migrate(2745) FIXME: This JSX tag's 'children' prop expects type 'never... Remove this comment to see the full error message */}

        <InputNumber
          layout="horizontal"
          label="Formatting Decimal Place"
          data-test="Counter.Formatting.DecimalPlace"
          defaultValue={options.stringDecimal}
          disabled={!inputsEnabled}
          onChange={(stringDecimal: any) => onOptionsChange({ stringDecimal })}
        />

      {/* @ts-expect-error ts-migrate(2745) FIXME: This JSX tag's 'children' prop expects type 'never... Remove this comment to see the full error message */}

        <Input
          layout="horizontal"
          label="Formatting Decimal Character"
          data-test="Counter.Formatting.DecimalCharacter"
          defaultValue={options.stringDecChar}
          disabled={!inputsEnabled}
          onChange={(e: any) => onOptionsChange({ stringDecChar: e.target.value })}
        />

      {/* @ts-expect-error ts-migrate(2745) FIXME: This JSX tag's 'children' prop expects type 'never... Remove this comment to see the full error message */}

        <Input
          layout="horizontal"
          label="Formatting Thousands Separator"
          data-test="Counter.Formatting.ThousandsSeparator"
          defaultValue={options.stringThouSep}
          disabled={!inputsEnabled}
          onChange={(e: any) => onOptionsChange({ stringThouSep: e.target.value })}
        />

      {/* @ts-expect-error ts-migrate(2745) FIXME: This JSX tag's 'children' prop expects type 'never... Remove this comment to see the full error message */}

        <Input
          layout="horizontal"
          label="Formatting String Prefix"
          data-test="Counter.Formatting.StringPrefix"
          defaultValue={options.stringPrefix}
          disabled={!inputsEnabled}
          onChange={(e: any) => onOptionsChange({ stringPrefix: e.target.value })}
        />

      {/* @ts-expect-error ts-migrate(2745) FIXME: This JSX tag's 'children' prop expects type 'never... Remove this comment to see the full error message */}

        <Input
          layout="horizontal"
          label="Formatting String Suffix"
          data-test="Counter.Formatting.StringSuffix"
          defaultValue={options.stringSuffix}
          disabled={!inputsEnabled}
          onChange={(e: any) => onOptionsChange({ stringSuffix: e.target.value })}
        />

      {/* @ts-expect-error ts-migrate(2745) FIXME: This JSX tag's 'children' prop expects type 'never... Remove this comment to see the full error message */}

        {/* @ts-expect-error ts-migrate(2745) FIXME: This JSX tag's 'children' prop expects type 'never... Remove this comment to see the full error message */}
        <Switch
          // @ts-expect-error ts-migrate(2322) FIXME: Type 'string' is not assignable to type 'never'.
          data-test="Counter.Formatting.FormatTargetValue"
          // @ts-expect-error ts-migrate(2322) FIXME: Type 'any' is not assignable to type 'never'.
          defaultChecked={options.formatTargetValue}
          // @ts-expect-error ts-migrate(2322) FIXME: Type '(formatTargetValue: any) => any' is not assi... Remove this comment to see the full error message
          onChange={(formatTargetValue: any) => onOptionsChange({ formatTargetValue })}>
          Format Target Value
        </Switch>

    </React.Fragment>
  );
}

FormatSettings.propTypes = EditorPropTypes;

redpajama_set_name: RedPajamaGithub


text:
@implementation GKAddress

- (GKAddress *)update:(GKAddress *)newObject
{
  self.addressID = newObject.addressID;
  self.name = newObject.name;
  self.cellPhone = newObject.cellPhone;
  self.postcode = newObject.postcode;
  self.address = newObject.address;
  self.province = newObject.province;
  self.city = newObject.city;
  self.county = newObject.county;
  self.town = newObject.town;
  self.village = newObject.village;
  self.isDefault = newObject.isDefault;
  return self;
}

- (GKAddress *)clone
{
  GKAddress *clone = [[GKAddress alloc] init];
  clone.addressID = self.addressID;
  clone.name = self.name;
  clone.cellPhone = self.cellPhone;
  clone.postcode = self.postcode;
  clone.address = self.address;
  clone.province = self.province;
  clone.city = self.city;
  clone.county = self.county;
  clone.town = self.town;
  clone.village = self.village;
  clone.isDefault = self.isDefault;

  return clone;
}
@end


text:
@font-face {
    font-family: 'CocFont';
    src: url('../font/Supercell-magic-webfont.ttf');
}

.loader-container {
    position: relative;
    min-height: 50px;
    overflow: hidden;
}


text:
package com.amazonaws.services.storagegateway.model;

import java.io.Serializable;

/**
 *

 * Describes a virtual tape object.
 *

 */
public class Tape implements Serializable, Cloneable {

    /**
     *

     * The Amazon Resource Name (ARN) of the virtual tape.
     *

     */
    private String tapeARN;
    /**
     *

     * The barcode that identifies a specific virtual tape.
     *

     */
    private String tapeBarcode;
    /**
     *

     * The size, in bytes, of the virtual tape.
     *

     */
    private Long tapeSizeInBytes;
    /**
     *

     * The current state of the virtual tape.
     *

     */
    private String tapeStatus;
    /**
     *

     * The virtual tape library (VTL) device that the virtual tape is associated
     * with.
     *

     */
    private String vTLDevice;
    /**
     *

     * For archiving virtual tapes, indicates how much data remains to be
     * uploaded before archiving is complete.
     *

     *

     * Range: 0 (not started) to 100 (complete).
     *

     */
    private Double progress;

    /**
     *

     * The Amazon Resource Name (ARN) of the virtual tape.
     *

     *
     * @param tapeARN
     *        The Amazon Resource Name (ARN) of the virtual tape.
     */

    public void setTapeARN(String tapeARN) {
        this.tapeARN = tapeARN;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the virtual tape.
     *

     *
     * @return The Amazon Resource Name (ARN) of the virtual tape.
     */

    public String getTapeARN() {
        return this.tapeARN;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the virtual tape.
     *

     *
     * @param tapeARN
     *        The Amazon Resource Name (ARN) of the virtual tape.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Tape withTapeARN(String tapeARN) {
        setTapeARN(tapeARN);
        return this;
    }

    /**
     *

     * The barcode that identifies a specific virtual tape.
     *

     *
     * @param tapeBarcode
     *        The barcode that identifies a specific virtual tape.
     */

    public void setTapeBarcode(String tapeBarcode) {
        this.tapeBarcode = tapeBarcode;
    }

    /**
     *

     * The barcode that identifies a specific virtual tape.
     *

     *
     * @return The barcode that identifies a specific virtual tape.
     */

    public String getTapeBarcode() {
        return this.tapeBarcode;
    }

    /**
     *

     * The barcode that identifies a specific virtual tape.
     *

     *
     * @param tapeBarcode
     *        The barcode that identifies a specific virtual tape.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Tape withTapeBarcode(String tapeBarcode) {
        setTapeBarcode(tapeBarcode);
        return this;
    }

    /**
     *

     * The size, in bytes, of the virtual tape.
     *

     *
     * @param tapeSizeInBytes
     *        The size, in bytes, of the virtual tape.
     */

    public void setTapeSizeInBytes(Long tapeSizeInBytes) {
        this.tapeSizeInBytes = tapeSizeInBytes;
    }

    /**
     *

     * The size, in bytes, of the virtual tape.
     *

     *
     * @return The size, in bytes, of the virtual tape.
     */

    public Long getTapeSizeInBytes() {
        return this.tapeSizeInBytes;
    }

    /**
     *

     * The size, in bytes, of the virtual tape.
     *

     *
     * @param tapeSizeInBytes
     *        The size, in bytes, of the virtual tape.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Tape withTapeSizeInBytes(Long tapeSizeInBytes) {
        setTapeSizeInBytes(tapeSizeInBytes);
        return this;
    }

    /**
     *

     * The current state of the virtual tape.
     *

     *
     * @param tapeStatus
     *        The current state of the virtual tape.
     */

    public void setTapeStatus(String tapeStatus) {
        this.tapeStatus = tapeStatus;
    }

    /**
     *

     * The current state of the virtual tape.
     *

     *
     * @return The current state of the virtual tape.
     */

    public String getTapeStatus() {
        return this.tapeStatus;
    }

    /**
     *

     * The current state of the virtual tape.
     *

     *
     * @param tapeStatus
     *        The current state of the virtual tape.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Tape withTapeStatus(String tapeStatus) {
        setTapeStatus(tapeStatus);
        return this;
    }

    /**
     *

     * The virtual tape library (VTL) device that the virtual tape is associated
     * with.
     *

     *
     * @param vTLDevice
     *        The virtual tape library (VTL) device that the virtual tape is
     *        associated with.
     */

    public void setVTLDevice(String vTLDevice) {
        this.vTLDevice = vTLDevice;
    }

    /**
     *

     * The virtual tape library (VTL) device that the virtual tape is associated
     * with.
     *

     *
     * @return The virtual tape library (VTL) device that the virtual tape is
     *         associated with.
     */

    public String getVTLDevice() {
        return this.vTLDevice;
    }

    /**
     *

     * The virtual tape library (VTL) device that the virtual tape is associated
     * with.
     *

     *
     * @param vTLDevice
     *        The virtual tape library (VTL) device that the virtual tape is
     *        associated with.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Tape withVTLDevice(String vTLDevice) {
        setVTLDevice(vTLDevice);
        return this;
    }

    /**
     *

     * For archiving virtual tapes, indicates how much data remains to be
     * uploaded before archiving is complete.
     *

     *

     * Range: 0 (not started) to 100 (complete).
     *

     *
     * @param progress
     *        For archiving virtual tapes, indicates how much data remains to be
     *        uploaded before archiving is complete.

     *

     *        Range: 0 (not started) to 100 (complete).
     */

    public void setProgress(Double progress) {
        this.progress = progress;
    }

    /**
     *

     * For archiving virtual tapes, indicates how much data remains to be
     * uploaded before archiving is complete.
     *

     *

     * Range: 0 (not started) to 100 (complete).
     *

     *
     * @return For archiving virtual tapes, indicates how much data remains to
     *         be uploaded before archiving is complete.

     *

     *         Range: 0 (not started) to 100 (complete).
     */

    public Double getProgress() {
        return this.progress;
    }

    /**
     *

     * For archiving virtual tapes, indicates how much data remains to be
     * uploaded before archiving is complete.
     *

     *

     * Range: 0 (not started) to 100 (complete).
     *

     *
     * @param progress
     *        For archiving virtual tapes, indicates how much data remains to be
     *        uploaded before archiving is complete.

     *

     *        Range: 0 (not started) to 100 (complete).
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Tape withProgress(Double progress) {
        setProgress(progress);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getTapeARN() != null)
            sb.append("TapeARN: " + getTapeARN() + ",");
        if (getTapeBarcode() != null)
            sb.append("TapeBarcode: " + getTapeBarcode() + ",");
        if (getTapeSizeInBytes() != null)
            sb.append("TapeSizeInBytes: " + getTapeSizeInBytes() + ",");
        if (getTapeStatus() != null)
            sb.append("TapeStatus: " + getTapeStatus() + ",");
        if (getVTLDevice() != null)
            sb.append("VTLDevice: " + getVTLDevice() + ",");
        if (getProgress() != null)
            sb.append("Progress: " + getProgress());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof Tape == false)
            return false;
        Tape other = (Tape) obj;
        if (other.getTapeARN() == null ^ this.getTapeARN() == null)
            return false;
        if (other.getTapeARN() != null
                && other.getTapeARN().equals(this.getTapeARN()) == false)
            return false;
        if (other.getTapeBarcode() == null ^ this.getTapeBarcode() == null)
            return false;
        if (other.getTapeBarcode() != null
                && other.getTapeBarcode().equals(this.getTapeBarcode()) == false)
            return false;
        if (other.getTapeSizeInBytes() == null
                ^ this.getTapeSizeInBytes() == null)
            return false;
        if (other.getTapeSizeInBytes() != null
                && other.getTapeSizeInBytes().equals(this.getTapeSizeInBytes()) == false)
            return false;
        if (other.getTapeStatus() == null ^ this.getTapeStatus() == null)
            return false;
        if (other.getTapeStatus() != null
                && other.getTapeStatus().equals(this.getTapeStatus()) == false)
            return false;
        if (other.getVTLDevice() == null ^ this.getVTLDevice() == null)
            return false;
        if (other.getVTLDevice() != null
                && other.getVTLDevice().equals(this.getVTLDevice()) == false)
            return false;
        if (other.getProgress() == null ^ this.getProgress() == null)
            return false;
        if (other.getProgress() != null
                && other.getProgress().equals(this.getProgress()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getTapeARN() == null) ? 0 : getTapeARN().hashCode());
        hashCode = prime
                * hashCode
                + ((getTapeBarcode() == null) ? 0 : getTapeBarcode().hashCode());
        hashCode = prime
                * hashCode
                + ((getTapeSizeInBytes() == null) ? 0 : getTapeSizeInBytes()
                        .hashCode());
        hashCode = prime * hashCode
                + ((getTapeStatus() == null) ? 0 : getTapeStatus().hashCode());
        hashCode = prime * hashCode
                + ((getVTLDevice() == null) ? 0 : getVTLDevice().hashCode());
        hashCode = prime * hashCode
                + ((getProgress() == null) ? 0 : getProgress().hashCode());
        return hashCode;
    }

    @Override
    public Tape clone() {
        try {
            return (Tape) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
describe 'ops/_rbac_group_details.html.haml' do
  context 'add new group' do
    before do
      miq_server = FactoryBot.create(:miq_server)
      edit = {:new                 => {:description => ''},
              :key                 => "settings_authentication_edit__#{miq_server.id}",
              :ldap_groups_by_user => [],
              :roles               => %w(fred wilma),
              :projects_tenants    => [["projects", %w(foo bar)]]}
      view.instance_variable_set(:@edit, edit)
      @group = FactoryBot.create(:miq_group, :description => 'flintstones')
      allow(view).to receive(:current_tenant).and_return(Tenant.seed)
      allow(view).to receive(:session).and_return(:assigned_filters => [])
      FactoryBot.create(:classification, :name => 'folder_selected', :show => true)

      sb = {
        :trees                 => {},
        :active_rbac_group_tab => 'rbac_customer_tags',
      }
      view.instance_variable_set(:@sb, sb)

      @ems_azure_network = FactoryBot.create(:ems_azure_network)
      @hac_tree = TreeBuilderBelongsToHac.new(:hac_tree,
                                              sb,
                                              true,
                                              :edit           => nil,
                                              :group          => @group,
                                              :selected_nodes => {})
      @vat_tree = TreeBuilderBelongsToVat.new(:vat_tree,
                                              sb,
                                              true,
                                              :edit           => nil,
                                              :group          => @group,
                                              :selected_nodes => {})
    end

    it 'should not show "Look up groups" checkbox and label for auth mode amazon' do
      stub_settings(:authentication => { :mode => 'amazon' }, :server => {})
      render :partial => 'ops/rbac_group_details'
      expect(rendered).not_to have_selector('input#lookup')
      expect(rendered).not_to include('Look up Amazon Groups')
    end

    it 'should show "Look up groups" checkbox and label for auth mode httpd' do
      stub_settings(:authentication => { :mode => 'httpd', :saml_enabled => false, :oidc_enabled => false}, :server => {})
      render :partial => 'ops/rbac_group_details'
      expect(rendered).to have_selector('input#lookup')
      expect(rendered).to include('Look up External Authentication Groups')
    end

    it 'should not show "Look up groups" checkbox and label for auth mode httpd with SAML enabled' do
      stub_settings(:authentication => { :mode => 'httpd', :saml_enabled => true, :oidc_enabled => false}, :server => {})
      render :partial => 'ops/rbac_group_details'
      expect(rendered).not_to have_selector('input#lookup')
      expect(rendered).not_to include('Look up External Authentication Groups')
    end

    it 'should not show "Look up groups" checkbox and label for auth mode httpd with OIDC enabled' do
      stub_settings(:authentication => { :mode => 'httpd', :saml_enabled => false, :oidc_enabled => true}, :server => {})
      render :partial => 'ops/rbac_group_details'
      expect(rendered).not_to have_selector('input#lookup')
      expect(rendered).not_to include('Look up External Authentication Groups')
    end

    it 'should not show "Look up groups" checkbox and label for auth mode database' do
      stub_settings(:authentication => { :mode => 'database' }, :server => {})
      render :partial => 'ops/rbac_group_details'
      expect(rendered).not_to have_selector('input#lookup')
      expect(rendered).not_to include('Look up External Authentication Groups')
    end

    context 'choosing Role from the drop down while adding Group' do
      before { view.instance_variable_set(:@edit, :ldap_groups_by_user => [], :new => {}, :roles => {'<Choose a Role>' => nil}, :projects_tenants => []) }

      it 'disables Choose a Role option' do
        render :partial => 'ops/rbac_group_details'
        expect(rendered).to include('<option selected="selected" disabled="disabled" value=""><Choose a Role></option>')
      end
    end
  end
end


text:
package org.broadinstitute.hellbender.tools.walkers.readorientation;

import com.google.common.collect.ImmutableMap;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMReadGroupRecord;
import htsjdk.samtools.metrics.MetricsFile;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.samtools.util.Histogram;
import htsjdk.samtools.util.IOUtil;
import org.broadinstitute.hellbender.CommandLineProgramTest;
import org.broadinstitute.hellbender.utils.genotyper.IndexedSampleList;
import org.broadinstitute.hellbender.utils.genotyper.SampleList;
import org.broadinstitute.hellbender.utils.read.ArtificialReadUtils;
import org.broadinstitute.hellbender.utils.read.GATKRead;
import org.broadinstitute.hellbender.utils.read.ReadUtils;
import org.broadinstitute.hellbender.utils.read.SAMFileGATKReadWriter;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * Created by tsato on 3/14/18.
 */
public class CollectF1R2CountsIntegrationTest extends CommandLineProgramTest {
    @Test
    public void testOnSyntheticBam() throws IOException {
        final File refMetrics = createTempFile("ref", ".metrics");
        final File altMetrics = createTempFile("alt", ".metrics");
        final File altTable = createTempFile("alt", ".table");

        final int numAltReads = 30;
        final int numRefReads = 70;
        final int depth = numAltReads + numRefReads;
        final File samFile = createSyntheticSam(numRefReads, numAltReads);

        final String[] args = {
                "-R", hg19_chr1_1M_Reference,
                "-I", samFile.getAbsolutePath(),
                "--" + CollectF1R2Counts.ALT_DATA_TABLE_LONG_NAME, altTable.getAbsolutePath(),
                "--" + CollectF1R2Counts.REF_SITE_METRICS_LONG_NAME, refMetrics.getAbsolutePath(),
                "--" + CollectF1R2Counts.ALT_DEPTH1_HISTOGRAM_LONG_NAME, altMetrics.getAbsolutePath()
        };

        runCommandLine(args);

        final MetricsFile<?, Integer> referenceSiteMetrics = new MetricsFile<>();
        final Reader in = IOUtil.openFileForBufferedReading(refMetrics);
        referenceSiteMetrics.read(in);
        CloserUtil.close(in);

        List<Histogram<Integer>> histograms = referenceSiteMetrics.getAllHistograms();
        List<AltSiteRecord> altDesignMatrix = AltSiteRecord.readAltSiteRecords(altTable);

        /** Expected result
         *
         * (position chr1: {@code alignmentStart})
         *
         * coord.:    99,990             100,000             100,010             100,020
         *              |                   |                   |                   |
         * reference: | T C A T C A C A C T C A C T A A G C A C A C A G A G A A T A A T
         * alt read:  | T C A T C A C A C T C T C T G A C C A A A G A G A A T A A T A A
         *                                    *     *   *     *
         *
         * At each alt site, we have 75 ref and 25 alt reads
         *
         * context, alt counts, alt f1r2 counts, depth
         * -------------------------------------------
         * CAC, {70, 0, 0, 30}, {35, 0, 0, 15}, 100
         * TAA, {70, 0, 30, 0}, {35, 0, 15, 0}, 100
         * AGC, {0, 30, 70, 0}, {0, 15, 35, 0}, 100
         * ACA, {30, 70, 0, 0}, {15, 35, 0, 0}, 100
         *
         *
         * Ref: 6 sites at depth 100
         * TCA, CAT, ATC, TCA, CAC, ACA, CAC, ACT, CTC, TCA, ACT, CTA, AAG, GCA, CAC, CAC, ACA, CAG, AGA, GAG, AGA, GAA, AAT, ATA, TAA, AAT
         * TCA*3, CAT, ATC, CAC*4, ACA*2, ACT*2, CTC, CTA, AAG, GCA, CAG, AGA*2, GAG, GAA, AAT*2, ATA, TAA
         *
         **/

        // alt site tests
        Assert.assertEquals(altDesignMatrix.size(), 4);
        AltSiteRecord recordCAC = altDesignMatrix.stream().
                filter(rec -> rec.getReferenceContext().equals("CAC")).findFirst().get();
        Assert.assertEquals(recordCAC.getRefCount(), 70);
        Assert.assertEquals(recordCAC.getAltCount(), 30);
        Assert.assertEquals(recordCAC.getRefF1R2(), 35);
        Assert.assertEquals(recordCAC.getAltF1R2(), 15);

        AltSiteRecord recordTAA = altDesignMatrix.stream().
                filter(rec -> rec.getReferenceContext().equals("TAA")).findFirst().get();
        Assert.assertEquals(recordTAA.getRefCount(), 70);
        Assert.assertEquals(recordTAA.getAltCount(), 30);
        Assert.assertEquals(recordTAA.getRefF1R2(), 35);
        Assert.assertEquals(recordTAA.getAltF1R2(), 15);

        AltSiteRecord recordAGC = altDesignMatrix.stream().
                filter(rec -> rec.getReferenceContext().equals("AGC")).findFirst().get();
        Assert.assertEquals(recordAGC.getRefCount(), 70);
        Assert.assertEquals(recordAGC.getAltCount(), 30);
        Assert.assertEquals(recordAGC.getRefF1R2(), 35);
        Assert.assertEquals(recordAGC.getAltF1R2(), 15);

        AltSiteRecord recordACA = altDesignMatrix.stream().
                filter(rec -> rec.getReferenceContext().equals("ACA")).findFirst().get();
        Assert.assertEquals(recordACA.getRefCount(), 70);
        Assert.assertEquals(recordACA.getAltCount(), 30);
        Assert.assertEquals(recordACA.getRefF1R2(), 35);
        Assert.assertEquals(recordACA.getAltF1R2(), 15);

        // check ref histograms
        // ImmutableMap.of can take up to 5 elements, and ImmutableMap.Builder is ugly
        final ImmutableMap<String, Integer> expectedReferenceCounts1 = ImmutableMap.of(
                "TCA", 3,
                "CAT", 1,
                "ATC", 1,
                "CAC", 4,
                "ACA", 2);
        final ImmutableMap<String, Integer>  expectedReferenceCounts2 = ImmutableMap.of(
                "ACT", 2,
                "CTC", 1,
                "CTA", 1,
                "AAG", 1,
                "GCA", 1);
        final ImmutableMap<String, Integer>  expectedReferenceCounts3 = ImmutableMap.of(
                "CAG", 1,
                "AGA", 2,
                "GAG", 1,
                "GAA", 1,
                "AAT", 2);
        final ImmutableMap<String, Integer>  expectedReferenceCounts4 = ImmutableMap.of("ATA", 1, "TAA", 1);

        for (ImmutableMap<String, Integer> expectedContextCountPairs : Arrays.asList(
                expectedReferenceCounts1, expectedReferenceCounts2, expectedReferenceCounts3, expectedReferenceCounts4)){
            expectedContextCountPairs.entrySet().stream().forEach(entrySet -> {
                final String context = entrySet.getKey();
                final double expectedCount = entrySet.getValue();
                Histogram<Integer> histogram = histograms.stream()
                        .filter(hist -> hist.getValueLabel().equals(context))
                        .findFirst().get();
                Assert.assertEquals(histogram.get(depth).getValue(), expectedCount);
                Assert.assertEquals(histogram.getSumOfValues(), expectedCount );
            });
        }
    }

    @Test
    public void testHistograms() throws IOException {
        final File refMetrics = createTempFile("ref", ".metrics");
        final File altMetrics = createTempFile("alt", ".metrics");
        final File altTable = createTempFile("alt", ".table");
        final File sam = createSyntheticSam(30, 1);

        final String[] args = {
                "-R", hg19_chr1_1M_Reference,
                "-I", sam.getAbsolutePath(),
                "--" + CollectF1R2Counts.ALT_DATA_TABLE_LONG_NAME, altTable.getAbsolutePath(),
                "--" + CollectF1R2Counts.REF_SITE_METRICS_LONG_NAME, refMetrics.getAbsolutePath(),
                "--" + CollectF1R2Counts.ALT_DEPTH1_HISTOGRAM_LONG_NAME, altMetrics.getAbsolutePath()
        };

        runCommandLine(args);

        final MetricsFile<?, Integer> altSiteMetrics = new MetricsFile<>();
        final Reader altMetricsReader = IOUtil.openFileForBufferedReading(altMetrics);
        altSiteMetrics.read(altMetricsReader);
        CloserUtil.close(altMetricsReader);

        List<Histogram<Integer>> histograms = altSiteMetrics.getAllHistograms();

        // TODO: should there be 64*3*2 = 384 histograms or just the non-zero ones?
        final String[] expectedTransitions = new String[]{"CAC_T_F2R1", "TAA_G_F2R1", "AGC_C_F2R1", "ACA_A_F2R1"};
        // Assert.assertEquals(histograms.size(), expectedTransitions.length, "alt histogram must contain the expected number of contexts");

        for (String transition : expectedTransitions ){
            Optional<Histogram<Integer>> histogram = histograms.stream()
                    .filter(h -> h.getValueLabel().equals(transition))
                    .findFirst();
            Assert.assertTrue(histogram.isPresent(), "histogram must exist");
            Assert.assertEquals((int) histogram.get().getSumOfValues(), 1, "histogram must only contain one read");
        }
    }

    private File createSyntheticSam(final int refDepth, final int altDepth) throws IOException {
        // create a sam header
        final int alignmentStart = 99_991;
        final int numChromosomes = 1;
        final int startingChromosome = 1;
        final int chromosomeSize = 1_000_000;
        final String readGroupName = "HELLO.1";
        final SAMFileHeader samHeader = ArtificialReadUtils.createArtificialSamHeader(
                numChromosomes, startingChromosome, chromosomeSize);
        samHeader.addReadGroup(new SAMReadGroupRecord(readGroupName));

        // create a sample list
        final int chromosomeIndex = 0;
        final String sampleName = "samthreetree";
        final SampleList sampleList = new IndexedSampleList(sampleName);

        // specify characteristics of reads
        final int depth = altDepth + refDepth;

        final byte[] refReadBases = "CATCACACTCACTAAGCACACAGAGAATAAT".getBytes();
        final byte[] altReadBases = "CATCACACTCTCTGACCAAACAGAGAATAAT".getBytes();
        final int readLength = refReadBases.length;
        final byte baseq = 26;
        final byte[] quals = new byte[readLength];
        Arrays.fill(quals, baseq);
        final int mapq = 60;

        // create reads
        final List<GATKRead> reads = new ArrayList<>(depth);
        for (int i = 0; i < depth; i++) {
            final byte[] bases = i < altDepth ? altReadBases : refReadBases;
            final String cigar = refReadBases.length + "M";
            final GATKRead read = ArtificialReadUtils.createArtificialRead(samHeader, "Read" + i, chromosomeIndex,
                    alignmentStart, bases, quals, cigar);
            read.setReadGroup(readGroupName);
            read.setMappingQuality(mapq);
            read.setIsFirstOfPair();
            read.setIsReverseStrand(i % 2 == 0);
            reads.add(read);
        }

        final File samFile = File.createTempFile("synthetic", ".sam");
        final SAMFileGATKReadWriter writer = new SAMFileGATKReadWriter(
                ReadUtils.createCommonSAMWriter(samFile, null, samHeader, true, false, false));
        reads.forEach(writer::addRead);
        writer.close(); // closing the writer writes to the file

        return samFile;
    }

}


text:
module Steps::Details
  class TaxpayerIndividualDetailsForm < TaxpayerDetailsForm
    attribute :taxpayer_individual_first_name, String
    attribute :taxpayer_individual_last_name, String

    validates_presence_of :taxpayer_individual_first_name,
                          :taxpayer_individual_last_name

    def name_fields
      [:taxpayer_individual_first_name, :taxpayer_individual_last_name]
    end

    def show_fao?
      false
    end

    def show_registration_number?
      false
    end

    private

    def persist!
      super(
        taxpayer_individual_first_name: taxpayer_individual_first_name,
        taxpayer_individual_last_name: taxpayer_individual_last_name
      )
    end
  end
end


text:
package org.usfirst.frc5933.ubot.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

public class Pos5Mote extends CommandGroup {
    public Pos5Mote() {
        addParallel(new LiftingArmDown(1));
        addSequential(new EncoderDriveStraight(100));
    }
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Categories Class
 *
 * @author Colan
 */
class Categories extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper('url');
        $this->load->library('session');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->model('admin/categories_model');
        $this->load->model('admin/age_groups_model');

        cipl_admin_auth();
    }

    public function index() {}

    // List Categories
    public function list_categories() {

        $data['categories'] = $this->categories_model->getAllCategories();

        $this->load->view('admin/common/header');
        $this->load->view('admin/categories/list', $data);
        $this->load->view('admin/common/footer');
    }

    // Add Category
    public function add_category() {

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $config = array(
                array(
                    'field' => 'category_name',
                    'label' => 'Category Name',
                    'rules' => 'trim|required'
                ),
                array(
                    'field' => 'category_type',
                    'label' => 'Category Type',
                    'rules' => 'required'
                ),
                array(
                    'field' => 'sort_order',
                    'label' => 'Sort Order',
                    'rules' => 'trim|is_natural_no_zero|required'
                )
            );

            $this->form_validation->set_rules($config);

            if ($this->form_validation->run() != FALSE) {

                $update_array = array(
                    "category_name" => $this->input->post('category_name'),
                    /*"category_name_arabic" => $this->input->post('category_name_arabic'),*/
                    "category_type" => $this->input->post('category_type'),
                    "parent_id"     => $this->input->post('parent_id'),
                    "section_id"    => $this->input->post('section_id'),
                    "sort_order"    => $this->input->post("sort_order"),
                    "need_payment"  => $this->input->post("need_payment"),
                    "created_on"    => date('Y-m-d H:i:s'),
                    "updated_on"    => date('Y-m-d H:i:s')
                );

                $age_groups = $this->age_groups_model->get_all_age_groups();
                $background_images_array = array();
                $background_images_error = false;
                $background_images_error_messages = '';
                foreach($age_groups as $age_group):
                    if ( isset($_FILES['background_image-' . $age_group['age_group_id']]) && $_FILES['background_image-' . $age_group['age_group_id']]["name"] != '' ) {
                        $upload_path = 'assets/categoryImages/';
                        $ext_image_name = explode(".", $_FILES['background_image-' . $age_group['age_group_id']]['name']);
                        $count_ext_img = count($ext_image_name);
                        $image_ext = $ext_image_name[$count_ext_img - 1];
                        $file_name = base64_encode(trim($this->input->post('category_name'))) . '_' . md5(rand(1000000, 1000000000)) . '.' . $image_ext;
                        $file_name = str_replace('=', '', $file_name);
                        $image_info = getimagesize($_FILES["background_image-" . $age_group["age_group_id"]]["tmp_name"]);
                        $image_width = $image_info[0];
                        $image_height = $image_info[1];
                        $background_image = cipl_image_upload($_FILES['background_image-' . $age_group['age_group_id']], 'background_image-' . $age_group['age_group_id'], $upload_path, $file_name, $image_width, $image_height);

                        if (isset($background_image['success'])) {
                            $background_images_array[$age_group["age_group_id"]] = $upload_path . $file_name;
                        } else {
                            $background_images_error = true;
                            $background_images_array[$age_group["age_group_id"]] = '';
                            $background_images_error_messages .= $background_image['messages']['error'];
                        }
                    } else {
                        $background_images_array[$age_group["age_group_id"]] = '';
                    }
                endforeach;
                if ($background_images_error == false) {
                    $background_image_result_array = array("background_image" => serialize($background_images_array));
                    $update_array = array_merge($background_image_result_array, $update_array);
                    $this->categories_model->addCategory($update_array);
                    $this->session->set_flashdata('Success', 'Category added successfully.');
                    redirect('usadmin/categories', 'refresh');
                } else {
                    $this->session->set_flashdata('Error', $background_images_error_messages);
                }
            }
        }

        $data['root_categories'] = $this->categories_model->getRootCategories();
        $data['sections'] = $this->categories_model->getAllSections();
        $data['age_groups'] = $this->age_groups_model->get_all_age_groups();

        $this->load->view('admin/common/header');
        $this->load->view('admin/categories/add', $data);
        $this->load->view('admin/common/footer');
    }

    // Edit Category
    public function edit_category($category_id) {

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $config = array(
                array(
                    'field' => 'category_name',
                    'label' => 'Category Name',
                    'rules' => 'trim|required'
                ),
                array(
                    'field' => 'category_type',
                    'label' => 'Category Type',
                    'rules' => 'required'
                ),
                array(
                    'field' => 'sort_order',
                    'label' => 'Sort Order',
                    'rules' => 'trim|is_natural_no_zero|required'
                )
            );

            $this->form_validation->set_rules($config);

            if ($this->form_validation->run() != FALSE) {

                $update_array = array(
                    "category_name" => $this->input->post('category_name'),
                    /*"category_name_arabic" => $this->input->post('category_name_arabic'),*/
                    "category_type" => $this->input->post('category_type'),
                    "parent_id"     => $this->input->post('parent_id'),
                    "section_id"    => $this->input->post('section_id'),
                    "sort_order"    => $this->input->post("sort_order"),
                    "need_payment"  => $this->input->post("need_payment"),
                    "updated_on"    => date('Y-m-d H:i:s')
                );

                $age_groups = $this->age_groups_model->get_all_age_groups();
                $background_images_array = array();
                $background_images_error = false;
                $background_images_error_messages = '';
                foreach($age_groups as $age_group):
                    if ( isset($_FILES['background_image-' . $age_group['age_group_id']]) && $_FILES['background_image-' . $age_group['age_group_id']]["name"] != '' ) {
                        $upload_path = 'assets/categoryImages/';
                        $ext_image_name = explode(".", $_FILES['background_image-' . $age_group['age_group_id']]['name']);
                        $count_ext_img = count($ext_image_name);
                        $image_ext = $ext_image_name[$count_ext_img - 1];
                        $file_name = base64_encode(trim($this->input->post('category_name'))) . '_' . md5(rand(1000000, 1000000000)) . '.' . $image_ext;
                        $file_name = str_replace('=', '', $file_name);
                        $image_info = getimagesize($_FILES["background_image-" . $age_group["age_group_id"]]["tmp_name"]);
                        $image_width = $image_info[0];
                        $image_height = $image_info[1];
                        $background_image = cipl_image_upload($_FILES['background_image-' . $age_group['age_group_id']], 'background_image-' . $age_group['age_group_id'], $upload_path, $file_name, $image_width, $image_height);

                        if (isset($background_image['success'])) {
                            // Delete the old background image
                            unlink(FCPATH . base64_decode($this->input->post('background_image_old-' . $age_group['age_group_id'])));
                            $background_images_array[$age_group["age_group_id"]] = $upload_path . $file_name;
                        } else {
                            $background_images_error = true;
                            $background_images_array[$age_group["age_group_id"]] = '';
                            $background_images_error_messages .= $background_image['messages']['error'];
                        }
                    } else {
                        $background_images_array[$age_group["age_group_id"]] = base64_decode($this->input->post('background_image_old-' . $age_group['age_group_id']));
                    }
                endforeach;
                if ($background_images_error == false) {
                    $background_image_result_array = array("background_image" => serialize($background_images_array));
                    $update_array = array_merge($background_image_result_array, $update_array);
                    $this->categories_model->updateCategory($update_array, $category_id);
                    $this->session->set_flashdata('Success', 'Category updated successfully.');
                    redirect('usadmin/categories', 'refresh');
                } else {
                    $this->session->set_flashdata('Error', $background_images_error_messages);
                }
            }
        }

        $result = $this->categories_model->getCategory($category_id);
        $data['category'] = $result[0];

        $data['root_categories'] = $this->categories_model->getRootCategories();
        $data['sections'] = $this->categories_model->getAllSections();
        $data['age_groups'] = $this->age_groups_model->get_all_age_groups();

        $this->load->view('admin/common/header');
        $this->load->view('admin/categories/edit', $data);
        $this->load->view('admin/common/footer');
    }

    // Delete Category
    public function delete_category() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $data["category_id"] = $this->input->post('category_id');
            $result = $this->categories_model->deleteCategory($data);

            if ($result) {
                $this->session->set_flashdata('Success', 'Category deleted successfully.');
                echo 'success';
            } else {
                echo 'Error when delete the data. Try again.';
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
FsVolumeSpi (Apache Hadoop HDFS 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.hadoop.hdfs.server.datanode.fsdataset

Interface FsVolumeSpi

public interface FsVolumeSpi

This is an interface for the underlying volume.

Method Summary

 long
getAvailable()

 String
getBasePath()

 String[]
getBlockPoolList()

 File
getFinalizedDir(String bpid)

 String
getPath(String bpid)

 String
getStorageID()

 StorageType
getStorageType()

Method Detail

getStorageID

String getStorageID()

Returns:
the StorageUuid of the volume

getBlockPoolList

String[] getBlockPoolList()

Returns:
a list of block pools.

getAvailable

long getAvailable()
                  throws IOException

Returns:
the available storage space in bytes.

Throws:

IOException

getBasePath

String getBasePath()

Returns:
the base path to the volume

getPath

String getPath(String bpid)
               throws IOException

Returns:
the path to the volume

Throws:

IOException

getFinalizedDir

File getFinalizedDir(String bpid)
                     throws IOException

Returns:
the directory for the finalized blocks in the block pool.

Throws:

IOException

getStorageType

StorageType getStorageType()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2015 Apache Software Foundation. All Rights Reserved.


text:
package backend.codegen;

import backend.support.MachineFunctionPass;

/**
 * @author Jianping Zeng
 * @version 0.4
 */
public final class MachineCodeVerifier extends MachineFunctionPass {
  public static MachineCodeVerifier createMachineVerifierPass(boolean allowDoubleDefs) {
    return new MachineCodeVerifier(allowDoubleDefs);
  }

  private MachineCodeVerifier(boolean allowDoubleDefs) {

  }

  @Override
  public boolean runOnMachineFunction(MachineFunction mf) {
    return false;
  }

  @Override
  public String getPassName() {
    return null;
  }

}


text:
<!DOCTYPE html>

    <title>require.js: require Async Test</title>

require.js: require Async Test

Test that a define after a require() works.

Check console for messages


text:
// Copyright 2019 The OpenSDS Authors.
//
// 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.

/*
This module implements a entry into the OpenSDS service.

*/

package cli

import (
	"encoding/json"
	"log"
	"os"

	"github.com/opensds/opensds/pkg/model"
	"github.com/spf13/cobra"
)

var fileShareAclCommand = &cobra.Command{
	Use:   "acl",
	Short: "manage fileshare acls in the cluster",
	Run:   fileShareAclAction,
}

var fileShareAclCreateCommand = &cobra.Command{
	Use:   "create <fileshare id>",
	Short: "create a acl of specified fileshare in the cluster",
	Run:   fileShareAclCreateAction,
}

var fileShareAclDeleteCommand = &cobra.Command{
	Use:   "delete <fileshare acl id>",
	Short: "delete a fileshare acl of specified fileshare in the cluster",
	Run:   fileShareAclDeleteAction,
}

var fileShareAclShowCommand = &cobra.Command{
	Use:   "show <fileshare acl id>",
	Short: "show a fileshare acl in the cluster",
	Run:   fileShareAclShowAction,
}

var fileShareAclListCommand = &cobra.Command{
	Use:   "list",
	Short: "list all fileshare acls in the cluster",
	Run:   fileSharesAclListAction,
}

var (
	shareAclType             string
	shareAclAccessCapability string
	shareAclAccessTo         string
	shareAclDesp             string

	shareAclFormatters = FormatterList{"Metadata": JsonFormatter}
)

func init() {
	fileShareAclCommand.AddCommand(fileShareAclCreateCommand)
	fileShareAclCommand.AddCommand(fileShareAclDeleteCommand)
	fileShareAclCommand.AddCommand(fileShareAclShowCommand)
	fileShareAclCommand.AddCommand(fileShareAclListCommand)

	fileShareAclCreateCommand.Flags().StringVarP(&shareAclType, "type", "t", "", "the type of access")
	fileShareAclCreateCommand.Flags().StringVarP(&shareAclAccessCapability, "capability", "c", "", "the accessCapability for fileshare")
	fileShareAclCreateCommand.Flags().StringVarP(&shareAclAccessTo, "accessTo", "a", "", "accessTo of the fileshare")
	fileShareAclCreateCommand.Flags().StringVarP(&shareAclDesp, "description", "d", "", "the description of of the fileshare acl")
}

func fileShareAclAction(cmd *cobra.Command, args []string) {
	cmd.Usage()
	os.Exit(1)
}

func fileShareAclCreateAction(cmd *cobra.Command, args []string) {
	ArgsNumCheck(cmd, args, 1)

	var accessCapability []string
	if "" != shareAclAccessCapability {
		err := json.Unmarshal([]byte(shareAclAccessCapability), &accessCapability)
		if err != nil {
			log.Fatalf("error parsing accessCapability %s: %+v", shareAclAccessCapability, err)
		}
	}

	acl := &model.FileShareAclSpec{
		FileShareId:      args[0],
		Type:             shareAclType,
		AccessCapability: accessCapability,
		AccessTo:         shareAclAccessTo,
		Description:      shareAclDesp,
	}

	resp, err := client.CreateFileShareAcl(acl)
	if err != nil {
		Fatalln(HttpErrStrip(err))
	}

	keys := KeyList{"Id", "CreatedAt", "TenantId", "FileShareId", "Metadata",
		"Type", "AccessCapability", "AccessTo", "Description"}
	PrintDict(resp, keys, shareAclFormatters)
}

func fileShareAclDeleteAction(cmd *cobra.Command, args []string) {
	ArgsNumCheck(cmd, args, 1)

	err := client.DeleteFileShareAcl(args[0])
	if err != nil {
		Fatalln(HttpErrStrip(err))
	}
}

func fileShareAclShowAction(cmd *cobra.Command, args []string) {
	ArgsNumCheck(cmd, args, 1)
	resp, err := client.GetFileShareAcl(args[0])
	if err != nil {
		Fatalln(HttpErrStrip(err))
	}

	keys := KeyList{"Id", "CreatedAt", "UpdatedAt", "TenantId", "FileShareId",
		"Type", "AccessCapability", "AccessTo", "Description", "Metadata"}
	PrintDict(resp, keys, shareAclFormatters)
}

func fileSharesAclListAction(cmd *cobra.Command, args []string) {
	ArgsNumCheck(cmd, args, 0)
	resp, err := client.ListFileSharesAcl()
	if err != nil {
		Fatalln(HttpErrStrip(err))
	}

	keys := KeyList{"Id", "FileShareId",
		"Type", "AccessCapability", "AccessTo", "Description"}
	PrintList(resp, keys, shareAclFormatters)
}


text:
Principes de protection des informations

CATTAN -
Michel

1
 Principes

La protection des informations s'appuie sur les principes suivants :

Les informations ne doivent être communiquées qu'aux personnes ayant besoin de les connaître. Ce besoin de connaître est évalué par rapport à leur fonction et à leur rôle, dans ou en dehors de l'organisme.

Le droit de communiquer une information n'existe qu'avec l'obligation d'appliquer les règles de classification et de diffusion correspondantes.

L'importance de la protection à attacher à une information est évaluée à l'aide de critères.

La classification d'un document ou d'une information consiste à lui attribuer une des classes de protection préalablement définies.

Une classe de protection est attribuée à chaque document, dès son émission ou sa réception par l'organisme. Par convention, en l'absence d'une indication de classe, un document est réputé de classe N (normale).

La diffusion interne comme la diffusion externe sont effectuées selon les règles définies pour chacune des classes de protection.

2
 Identification des informations à protéger

L'identification des informations à protéger se fait en prenant en considération trois critères :

savoir de l'organisme ;

valeur marchande des documents et des informations ;

préjudice potentiel et possibilité de mise en cause de la réputation de l'organisme.

3
 Critère 1 : « savoir de l'organisme »

Le savoir de l'organisme peut être théorique ou pratique et être développé par lui-même ou acquis auprès de tiers. Il peut résulter de travaux techniques ou non techniques, de recherches et de développements effectués par l'organisme ou qu'il a fait effectuer, de méthodes qu'il a développées dans l'exercice de son activité, de réalisations de toute nature qu'il a accomplies.

Ce savoir correspond à des connaissances qui peuvent être matérialisées ou non.

      Dans le domaine commercial, les connaissances apparaissent notamment dans les offres émises (dossier commercial donnant les prix ainsi que les conditions économiques et juridiques).

      Dans le domaine industriel, les connaissances apparaissent notamment dans les notes de directives relatives à la stratégie, à la gestion et à l'organisation, ainsi que les notes d'application émises par les unités opérationnelles et fonctionnelles.

      Dans le domaine technique,  les connaissances apparaissent dans les documents techniques, de fabrication, d'installation (dossiers de méthode, dossiers d'étude, programmes de calcul, procédures, spécifications, plans).

On peut identifier l'existence de « savoir de l'organisme » dans un document en se posant les questions suivantes :

Reprend-il des éléments d'une note ou d'un manuel décrivant des méthodes ou des logiciels ?

Décrit-il une nouvelle technique ?

Décrit-il un nouveau procédé (de fabrication, d'installation, d'entretien) ?

Contient-il des résultats essentiels d'expérimentation ou d'essais en laboratoire ou sur chantier, de qualification de matériel ou de procédé) ?

Contient-il des connaissances obtenues ou acquises auprès de tiers (clients, fournisseurs, partenaires, etc. que l'organisme ne souhaite pas ou n'a pas le droit de divulguer ?

3.1
 Critère 2 : valeur marchande des documents
et des informations

La valeur marchande d'un document est caractérisée par l'intérêt que les informations qu'il contient peuvent susciter pour des tiers auxquels l'organisme peut fournir (ou être en concurrence pour fournir) des produits et des services (clients, fournisseurs, concurrents) ou des tiers avec lesquels l'organisme peut être « associé » pour la fourniture de produits et de services.

La valeur marchande d'un document se traduit donc par le « prix » que ces tiers consentiraient à payer pour disposer des connaissances qu'il contient.

On évalue une telle valeur marchande dans un document en considérant les réponses aux questions suivantes :

Contient-il des informations à caractère stratégique ou financier sur l'organisme ?

Contient-il des connaissances dont la divulgation à des tiers priverait l'organisme de la possibilité d'obtenir des contrats, soit que ces connaissances dispensent un client potentiel d'allouer un tel contrat à l'organisme, soit qu'un concurrent puisse obtenir un tel contrat à la place de l'organisme, grâce à ces connaissances ?

Divulgue-t-il des connaissances dont la possession par un tiers priverait l'organisme de la possibilité de développer ou de fabriquer un produit, ce tiers pouvant effectuer ce développement ou cette fabrication à sa place ?

Contient-il des connaissances susceptibles d'être fournies à des tiers moyennant compensation financière ou autre dans le cadre d'opérations de transfert de technologie ?

Contient-il des informations risquant, soit de contredire des arguments développés pour la défense d'une position contractuelle, ou par la négociation d'un avenant à un contrat, soit de fournir des connaissances pouvant permettre de contrecarrer des arguments utiliser antérieurement ?

Contient-il des résultats d'étude, de recherche ou d'essais non publiés ?

Risque-t-il d'antérioriser une demande de brevet ?

3.2
 Critère 3 : préjudice/réparation

Ce critère caractérise le préjudice commercial quantifiable d'un point de vue strictement économique. On peut reconnaître la potentialité d'un tel préjudice si le document et les informations qu'il contient :

exposent des difficultés de l'organisme concernant son fonctionnement ou ses produits et services ;

exposent l'insuffisance d'une méthode, d'un critère, d'un contrôle, etc., utilisé par l'organisme ;

ne répond pas à un niveau de qualité sur le plan du fond ou de la forme assez satisfaisant pour être diffusé sans précaution supplémentaire.

4
 Définition des classes de protection

Les informations à protéger peuvent être classées selon trois classes de protection.

4.1
 Classe C

Document contenant des informations de première importance qui ne doivent pas, sauf cas très exceptionnel, être communiquées hors de l'organisme et dont l'usage interne est strictement contrôlé.

4.2
 Classe F

Document contenant des informations importantes qui ne peuvent être communiquées hors de l'organisme qu'avec une autorisation particulière.

4.3
 Classe N

Document technique contenant des informations courantes dont la communication hors de l'organisme peut se faire en appliquant les règles générales de diffusion des documents.

5
 Règles de protection

5.1
 Classe C (confidentielle)

L'attribution de la classe C est du ressort de la direction générale, des directions qui lui sont directement rattachées ou des responsables habilités par ces dernières. Les documents ainsi classifiés et les informations qu'ils contiennent ne doivent pas être communiqués à des tiers sauf décision contraire des directions ci-dessus mentionnées.

La frappe de ces documents confidentiels et la gestion de leur reproduction et de leur diffusion sont placées sous la responsabilité de personnes désignées par leur hiérarchie. Tous les exemplaires sont numérotés et enregistrés sur un cahier d'enregistrement réservé à cet effet. Sur les chronos habituels ne figurent que la référence du document confidentiel et la mention « confidentiel » en remplacement du titre.

La mention « CONFIDENTIEL » entre deux barres obliques est apposée sur la première page de l'original. La mention « CLASSE C » doit être apposée sur toutes les pages

Un tampon « CONFIDENTIEL - EXEMPLAIRE N°...... ATTRIBUE A M.... » est apposé à l'encre rouge sur chaque exemplaire.

La diffusion interne nécessite des précautions spéciales (double enveloppe, l'enveloppe intérieure porte la mention « CONFIDENTIEL » entre deux bandes obliques).

Pour le cas, très exceptionnel, d'envoi à un destinataire extérieur à l'organisme, l'accord de la direction générale, d'une direction ou d'un responsable habilité est requis et l'envoi est effectué avec toutes les précautions utiles (accusé réception, limites à la reproduction, conditions de conservation, de restitution éventuelle à l'organisme...)

Les documents de classe C peuvent être retirés de la circulation à tout moment par les émetteurs, et les destinataires sont tenus de les restituer.

Les documents de classe C (originaux et exemplaires numérotés), émis ou reçus, doivent être conservés en armoire forte. Ils en sont extraits pour leur utilisation effective et remis en place aussitôt après.

5.2
 Classe F (filtrée)

La classe F est caractérisée par deux barres obliques apposées sur la première page de l'original. La mention « Diffusion restreinte » peut également être inscrite entre les deux barres. Cette mention est obligatoire en cas de diffusion externe.

La diffusion interne est limitée à ceux qui en ont besoin dans l'exercice de leurs fonctions. Elle doit être effectuée sous enveloppe fermée marquée de deux barres obliques.

La diffusion externe est effectuée aux destinataires ayant signé avec l'organisme un engagement assurant la protection de ces informations. Cet engagement peut être global lorsqu'il s'inscrit dans le cadre d'un contrat (client, fournisseur, assureur...) ou d'un accord (coopération, licence, recherche et développement, etc.), il peut être particulier lorsque le destinataire a été habilité. Lorsqu'il n'y a pas d'engagement général ou particulier, l'envoi à l'extérieur de documents de classe F est accompagné d'une lettre précisant leurs conditions d'utilisation.

Dans le cas de documents provenant de l'extérieur de l'organisme et pour lesquels une protection classa F est requise, la personne habilitée à diffuser doit vérifier que la protection demandée n'implique pas des mesures supplémentaires telles par exemple, d'obtenir, avant d'effectuer la diffusion, l'accord écrit de l'émetteur.

Il n'y a pas de règle particulière concernant la reproduction et la conservation de ces documents.

5.3
 Classe N (normale)

La mention « classe N »sur la première page d'un document n'est pas imposée sauf dans le cas d'un imprimé qui prévoit la mention de la classe de protection. Dans ce cas, celle-ci doit être effectivement explicitée.

La diffusion de ces documents est normalement effectuée à toute personne concernée par le sujet traité, aussi bien à l'intérieur qu'à l'extérieur de l'organisme.

Ces documents peuvent être reproduits par les détenteurs. Les exemplaires ainsi obtenus sont soumis aux mêmes règles de diffusion que le document original.

Nota 1 : Quelle que soit sa classe de protection, un document technique doit mentionner la propriété de l'organisme sur sa première page.

Si aucun autre texte n'est imposé par exemple dans le cadre d'accords de collaboration, le texte suivant peut convenir : « Ce document est la propriété de ... Les informations qu'il contient ne peuvent être communiquées à un tiers sans l'accord préalable de... »

Nota 2 : les documents destinés à une large diffusion tels que communications, plaquettes publicitaires etc., ne sont l'objet d'aucune mesure particulière lors de cette diffusion mais peuvent être soumis à des dispositions dictées par la nécessité de protéger le patrimoine au moment de leur élaboration.

Nota 3 : pour les documents sous forme numérique, leur utilisation et leur diffusion peuvent être conditionnées par l'utilisation de clés ou d'autorisations d'accès en appliquant les mêmes principes que pour les documents sur support papier.

            Tableau 4.1 –

             Résumé des règles de protection

         <colgroup>
            <col width="94.08px" align="left"/>
            <col width="197.76px" align="left"/>
            <col width="197.76px" align="left"/>
         </colgroup>

Classes
de
protection

Raisons pour classifier

Diffusion

                     C

1. contient des informations très importantes sur le savoir propre à l'organisme.

                     Interne  : Nominativement suivant liste contrôlée à l'intérieur de l'organisme.

2. contient des informations dont la valeur marchande est très élevée.

Externe : Exclue, sauf décision contraire prise par un directeur habilité à prendre une telle décision, et application de modalités de diffusion appropriées à la personne destinataire.

3. contient des informations sur des problèmes majeurs existants ou potentiels.

                     F

1. contient des informations importantes qui pourraient :

aider la concurrence

créer des problèmes dans le déroulement des affaires en cours avec clients, fournisseurs, etc

Interne : restreinte à ceux qui en ont besoin dans l'exercice de leur fonction.

2. une protection de ce niveau est demandée pour un document remis à l'organisme

Externe : Limitée à ceux couverts par un accord ou un contrat (partenaires, clients, fournisseurs) ou qui ont accepté les règles de protection définies.

3. contient un jugement sur des interlocuteurs ou sur leurs matériels (choix, évaluation)

                     N

L'information peut être normalement utilisée par ceux qui ont à en connaître.

Interne et externe selon règles
de diffusion correspondantes.


text:
@interface DTTableViewController (UnitTests)

-(BOOL)verifyTableItem:(id)item atIndexPath:(NSIndexPath *)path;
-(void)verifySection:(NSArray *)section withSectionNumber:(NSInteger)sectionNumber;
@end


text:
require 'rails_helper'

RSpec.describe 'Page Factory', type: :factory do
  include FactoryGirl::Syntax::Methods

  describe 'page' do
    it 'creates an page with a name' do
      page = build(:page)
      expect(page.name).to_not eq(nil)
    end

    it 'has all the attributes from the model' do
      expect(attributes_for(:page)).to include(*(factory_attributes(Page) - [:content]))
    end

    it 'produces a valid model' do
      expect(build(:page)).to be_valid
    end
  end
end


text:
namespace ash {

// A registry for progress indicator animations.
//
// Since animations are owned by the registry, they can be shared across
// different UI components as well have a lifetime which is decoupled from UI
// component lifetime.
//
// Supported animation types:
//   * Progress icon animation - independently drive the animation of properties
//     for a progress indicator's inner icon, as opposed to progress ring
//     animations which independently drive the animation of properties for a
//     progress indicator's outer ring.
//   * Progress ring animation - independently drive the animation of properties
//     for a progress indicator's outer ring, as opposed to progress icon
//     animations which independently drive the animation of properties for a
//     progress indicator's inner icon.
class ASH_EXPORT ProgressIndicatorAnimationRegistry {
 public:
  ProgressIndicatorAnimationRegistry();
  ProgressIndicatorAnimationRegistry(
      const ProgressIndicatorAnimationRegistry&) = delete;
  ProgressIndicatorAnimationRegistry& operator=(
      const ProgressIndicatorAnimationRegistry&) = delete;
  ~ProgressIndicatorAnimationRegistry();

  using ProgressIconAnimationChangedCallbackList =
      base::RepeatingCallbackList<void(ProgressIconAnimation*)>;

  // Adds the specified `callback` to be notified of changes to the progress
  // icon animation associated with the specified `key`. The `callback` will
  // continue to receive events so long as both `this` and the returned
  // subscription exist.
  base::CallbackListSubscription AddProgressIconAnimationChangedCallbackForKey(
      const void* key,
      ProgressIconAnimationChangedCallbackList::CallbackType callback);

  using ProgressRingAnimationChangedCallbackList =
      base::RepeatingCallbackList<void(ProgressRingAnimation*)>;

  // Adds the specified `callback` to be notified of changes to the progress
  // ring animation associated with the specified `key`. The `callback` will
  // continue to receive events so long as both `this` and the returned
  // subscription exist.
  base::CallbackListSubscription AddProgressRingAnimationChangedCallbackForKey(
      const void* key,
      ProgressRingAnimationChangedCallbackList::CallbackType callback);

  // Returns the progress icon animation registered for the specified `key`.
  // NOTE: This may return `nullptr` if no such animation is registered.
  ProgressIconAnimation* GetProgressIconAnimationForKey(const void* key);

  // Returns the progress ring animation registered for the specified `key`.
  // NOTE: This may return `nullptr` if no such animation is registered.
  ProgressRingAnimation* GetProgressRingAnimationForKey(const void* key);

  // Sets and returns the progress icon animation registered for the specified
  // `key`. NOTE: `animation` may be `nullptr` to unregister `key`.
  ProgressIconAnimation* SetProgressIconAnimationForKey(
      const void* key,
      std::unique_ptr<ProgressIconAnimation> animation);

  // Sets and returns the progress ring animation registered for the specified
  // `key`. NOTE: `animation` may be `nullptr` to unregister `key`.
  ProgressRingAnimation* SetProgressRingAnimationForKey(
      const void* key,
      std::unique_ptr<ProgressRingAnimation> animation);

  // Erases all animations for all keys.
  void EraseAllAnimations();

  // Erases all animations for the specified `key`.
  void EraseAllAnimationsForKey(const void* key);

  // Erases all animations for all keys for which the specified `predicate`
  // returns `true`.
  void EraseAllAnimationsForKeyIf(
      base::RepeatingCallback<bool(const void* key)> predicate);

 private:
  // Mapping of keys to their associated progress icon animations.
  std::map<const void*, std::unique_ptr<ProgressIconAnimation>>
      icon_animations_by_key_;

  // Mapping of keys to their associated icon animation changed callback lists.
  // Whenever an animation for a given key is changed, the callback list for
  // that key will be notified.
  std::map<const void*, ProgressIconAnimationChangedCallbackList>
      icon_animation_changed_callback_lists_by_key_;

  // Mapping of keys to their associated progress ring animations.
  std::map<const void*, std::unique_ptr<ProgressRingAnimation>>
      ring_animations_by_key_;

  // Mapping of keys to their associated ring animation changed callback lists.
  // Whenever an animation for a given key is changed, the callback list for
  // that key will be notified.
  std::map<const void*, ProgressRingAnimationChangedCallbackList>
      ring_animation_changed_callback_lists_by_key_;
};

}  // namespace ash

#endif  // ASH_SYSTEM_PROGRESS_INDICATOR_PROGRESS_INDICATOR_ANIMATION_REGISTRY_H_


text:
import { Page } from 'puppeteer'
import extendMouseWheel from '../../util/extendMouseWheel'
import getTranslate from '../../util/getTranslate'

jest.setTimeout(1000000)

describe('MouseWheel plugin', () => {
  let page = (global as any).page as Page
  extendMouseWheel(page)

  beforeAll(async () => {
    // emulate pc scene
    await page.emulate({
      viewport: {
        isMobile: false,
        width: 375,
        height: 667,
      },
      // tslint:disable-next-line: max-line-length
      userAgent:
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36',
    })
  })

  describe('MouseWheel & Core', () => {
    it('should scroll correctly in vertical direction when integrating with CoreScroll', async () => {
      await page.goto('http://0.0.0.0:8932/#/mouse-wheel/vertical-scroll')

      await page.waitFor(300)

      await page.dispatchMouseWheel({
        type: 'mouseWheel',
        x: 100,
        y: 100,
        deltaX: 0,
        deltaY: 50,
      })

      await page.waitFor(1000)

      const transformText = await page.$eval('.mouse-wheel-content', (node) => {
        return window.getComputedStyle(node).transform
      })

      const y = getTranslate(transformText, 'y')
      await expect(y).toBeLessThan(0)
    })

    it('should scroll correctly in horizontal direction when integrating with CoreScroll', async () => {
      await page.goto('http://0.0.0.0:8932/#/mouse-wheel/horizontal-scroll')

      await page.waitFor(300)

      await page.dispatchMouseWheel({
        type: 'mouseWheel',
        x: 130,
        y: 130,
        deltaX: 0,
        deltaY: 100,
      })

      await page.waitFor(1000)
      const transformText = await page.$eval('.mouse-wheel-content', (node) => {
        return window.getComputedStyle(node).transform
      })

      const x = getTranslate(transformText, 'x')
      await expect(x).toBeLessThan(0)
    })
  })

  describe('MouseWheel & Slide', () => {
    it('should scroll correctly in vertical direction when integrating with Slide', async () => {
      await page.goto('http://0.0.0.0:8932/#/mouse-wheel/vertical-slide')

      await page.waitFor(300)

      await page.dispatchMouseWheel({
        type: 'mouseWheel',
        x: 100,
        y: 100,
        deltaX: 0,
        deltaY: 200,
      })

      await page.waitFor(3000)

      const transformText = await page.$eval('.slide-content', (node) => {
        return window.getComputedStyle(node).transform
      })

      const y = getTranslate(transformText, 'y')
      await expect(y).toBeLessThan(-667)
    })

    it('should scroll correctly in horizontal direction when integrating with Slide', async () => {
      await page.goto('http://0.0.0.0:8932/#/mouse-wheel/horizontal-slide')

      await page.waitFor(300)

      await page.dispatchMouseWheel({
        type: 'mouseWheel',
        x: 130,
        y: 130,
        deltaX: 0,
        deltaY: 200,
      })

      await page.waitFor(1000)
      const transformText = await page.$eval('.slide-content', (node) => {
        return window.getComputedStyle(node).transform
      })

      const x = getTranslate(transformText, 'x')

      await expect(x).toBeLessThan(-600)
    })
  })

  describe('MouseWheel & PullUp', () => {
    it('should scroll correctly when integrating with PullUp', async () => {
      await page.goto('http://0.0.0.0:8932/#/mouse-wheel/pullup')

      await page.waitFor(300)

      await page.dispatchMouseWheel({
        type: 'mouseWheel',
        x: 100,
        y: 100,
        deltaX: 0,
        deltaY: 10000,
      })

      await page.waitFor(2000)

      const transformText = await page.$eval('.pullup-content', (node) => {
        return window.getComputedStyle(node).transform
      })

      const y = getTranslate(transformText, 'y')
      expect(y).toBeLessThan(0)

      // wait for loading data
      await page.waitFor(2000)

      const itemsCounts = await page.$$eval(
        '.pullup-list-item',
        (element) => element.length
      )

      await expect(itemsCounts).toBeGreaterThanOrEqual(30)
    })
  })

  describe('MouseWheel & PullDown', () => {
    it('should scroll correctly when integrating with PullDown', async () => {
      await page.goto('http://0.0.0.0:8932/#/mouse-wheel/pulldown')

      await page.waitFor(300)

      await page.dispatchMouseWheel({
        type: 'mouseWheel',
        x: 100,
        y: 100,
        deltaX: 0,
        deltaY: -1000,
      })

      // wait for loading data
      await page.waitFor(2000)

      const itemsCounts = await page.$$eval(
        '.pulldown-list-item',
        (element) => element.length
      )

      await expect(itemsCounts).toBeGreaterThanOrEqual(40)
    })
  })

  describe('MouseWheel & Wheel', () => {
    it('should scroll correctly when integrating with Wheel', async () => {
      await page.goto('http://0.0.0.0:8932/#/mouse-wheel/picker')

      await page.waitFor(300)

      await page.click('.open')

      await page.waitFor(500)

      await page.dispatchMouseWheel({
        type: 'mouseWheel',
        x: 200,
        y: 630,
        deltaX: 0,
        deltaY: 100,
      })

      await page.waitFor(1000)

      const transformText = await page.$eval('.wheel-scroll', (node) => {
        return window.getComputedStyle(node).transform
      })

      const y = getTranslate(transformText, 'y')
      expect(y).toBeLessThan(-30)
    })
  })
})


text:
package com.andremanuelbarbosa.editorgrafico;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

/** Classe que gere os eventos sobre a �rea de desenho
 */
public class MyCanvas extends JPanel
{
    String paintRequest;
    MouseEvent mouseEvent;
    DrawArea drawArea;

    private Color c;
    private LinkedList objectos = new LinkedList();

    /** Constructor da classe MyCanvas
     * @param d �rea de desenho correspondente
     */
    public MyCanvas(DrawArea d)
    {
        drawArea = d;
        c = Color.black;
        paintRequest = null;

        drawArea.drawProg.myCanvas = this;

        addMouseListener(new java.awt.event.MouseAdapter ()
        {
            public void mousePressed(java.awt.event.MouseEvent evt)
            {
                myCanvasMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt)
            {
                myCanvasMouseReleased(evt);
            }
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                myCanvasMouseClicked(evt);
            }
        });

        addMouseMotionListener(new java.awt.event.MouseMotionAdapter ()
        {
            public void mouseMoved(java.awt.event.MouseEvent evt)
            {
                myCanvasMouseMoved(evt);
            }
            public void mouseDragged(java.awt.event.MouseEvent evt)
            {
                myCanvasMouseDragged(evt);
            }
        });
    }

    private void myCanvasMousePressed(java.awt.event.MouseEvent evt)
    {
        if(SwingUtilities.isLeftMouseButton(evt))
        {
            mouseEvent = evt;
            paintRequest = "MousePressed";
            repaint();
        }
    }

    private void myCanvasMouseReleased(java.awt.event.MouseEvent evt)
    {
        if(SwingUtilities.isLeftMouseButton(evt))
        {
            mouseEvent = evt;
            paintRequest = "MouseReleased";
            repaint();
        }
    }

    private void myCanvasMouseMoved(java.awt.event.MouseEvent evt)
    {
        drawArea.drawProg.setXY(evt.getX(),evt.getY());
        mouseEvent = evt;
        paintRequest = "MouseMoved";
        repaint();
    }

    private void myCanvasMouseDragged(java.awt.event.MouseEvent evt)
    {
        drawArea.drawProg.setXY(evt.getX(),evt.getY());
        if(SwingUtilities.isLeftMouseButton(evt))
        {
            mouseEvent = evt;
            paintRequest = "MouseDragged";
            repaint();
        }
    }

    private void myCanvasMouseClicked(java.awt.event.MouseEvent evt)
    {
        if(SwingUtilities.isLeftMouseButton(evt))
        {
            mouseEvent = evt;
            if(evt.getClickCount() == 1 ) paintRequest = "MouseClicked";
            if(evt.getClickCount() == 2) paintRequest = "MouseDoubleClicked";
            repaint();
        }
    }

    /** Actualiza a �rea de desenho
     * @param g Graphics onde ir�o ser feitas as altera��es
     */
    public void update(Graphics g)
    {
        paint(g);
    }

    /** Pinta os objectos na �rea de desenho
     * @param g Graphics onde ir�o ser pintados os objectos
     */
    public void paint(Graphics g)
    {
        g.setColor(Color.white);
        g.fillRect(0,0,this.getWidth()-1, this.getHeight()-1);

        for(ListIterator listITR = objectos.listIterator() ; listITR.hasNext() ; )
        {
            ((AnyObject) listITR.next()).paint(g);
        }

        g.setColor(c);
        g.setPaintMode();

        if(paintRequest == "MousePressed")
        {
            if (drawArea.drawProg.getToolSelected() != null) drawArea.drawProg.getToolSelected().mousePressed(g, mouseEvent,objectos,c,drawArea.drawProg.flag);
        }
        else if(paintRequest == "MouseReleased")
        {
            if (drawArea.drawProg.getToolSelected() != null) drawArea.drawProg.getToolSelected().mouseReleased(g, mouseEvent,objectos,c,drawArea.drawProg.flag);
        }
        else if(paintRequest == "MouseDragged")
        {
            if (drawArea.drawProg.getToolSelected() != null) drawArea.drawProg.getToolSelected().mouseDragged(g, mouseEvent,objectos,c,drawArea.drawProg.flag);
        }
        else if(paintRequest == "MouseDoubleClicked")
        {
            if (drawArea.drawProg.getToolSelected() != null) drawArea.drawProg.getToolSelected().mouseDoubleClicked(g, mouseEvent,objectos,c,drawArea.drawProg.flag);
        }
        else if(paintRequest == "MouseMoved")
        {
            if (drawArea.drawProg.getToolSelected() != null) drawArea.drawProg.getToolSelected().mouseMoved(g, mouseEvent,objectos,c,drawArea.drawProg.flag);
        }
        else if(paintRequest == "MouseClicked")
        {
            if (drawArea.drawProg.getToolSelected() != null) drawArea.drawProg.getToolSelected().mouseClicked(g, mouseEvent,objectos,c,drawArea.drawProg.flag);
        }

        paintRequest = null;
    }

    /** Retorna a cor seleccionada
     * @return Cor seleccionada
     */
    public Color getColor ()
    {
        return this.c;
    }

    /** Muda a cor
     * @param c Nova cor
     */
    public void changeColor (Color c)
    {
        this.c = c;
    }

    /** Limpa a �rea de desenho
     */
    public void clearObjectos ()
    {
        this.objectos.clear();
    }
}


text:
from __future__ import absolute_import, unicode_literals

# Third Party Stuff
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic.base import RedirectView, TemplateView

from rest_framework import routers
from junction.schedule import views as schedule_views
from junction.conferences import views as conference_views
from junction.devices.views import DeviceListApiView, DeviceDetailApiView

router = routers.DefaultRouter()

router.register('conferences', conference_views.ConferenceView)
router.register('venues', conference_views.VenueView)
router.register('rooms', conference_views.RoomView)

router.register('schedules', schedule_views.ScheduleView)

'''
Root url routering file.

You should put the url config in their respective app putting only a
reference to them here.
'''

urlpatterns = patterns(
    '',

    # Django Admin
    url(r'^nimda/', include(admin.site.urls)),

    # Third Party Stuff
    url(r'^accounts/', include('allauth.urls')),
    url('^markdown/', include('django_markdown.urls')),

    # Proposals related
    url(r'^(?P<conference_slug>[\w-]+)/proposals/', include('junction.proposals.urls')),
    url(r'^(?P<conference_slug>[\w-]+)/dashboard/reviewers/',
        'junction.proposals.dashboard.reviewer_comments_dashboard',
        name='proposal-reviewers-dashboard'),
    url(r'^(?P<conference_slug>[\w-]+)/dashboard/$',
        'junction.proposals.dashboard.proposals_dashboard', name='proposal-dashboard'),
    url(r'^(?P<conference_slug>[\w-]+)/dashboard/votes/$',
        'junction.proposals.dashboard.reviewer_votes_dashboard',
        name='proposal-reviewer-votes-dashboard'),
    url(r'^(?P<conference_slug>[\w-]+)/dashboard/votes/export/$',
        'junction.proposals.dashboard.export_reviewer_votes',
        name='export-reviewer-votes'),

    url(r'^api/v1/', include(router.urls)),
    url(r'^api/v1/devices/$', DeviceListApiView.as_view(), name='device-list'),
    url(r'^api/v1/devices/(?P<_uuid>[\w-]+)/$', DeviceDetailApiView.as_view(),
        name='device-detail'),
    # User Dashboard
    url(r'^profiles/', include('junction.profiles.urls', namespace="profiles")),

    # Schedule related
    url(r'^(?P<conference_slug>[\w-]+)/schedule/',
        include('junction.schedule.urls')),
    # Static Pages. TODO: to be refactored
    url(r'^speakers/$', TemplateView.as_view(template_name='static-content/speakers.html',), name='speakers-static'),
    url(r'^schedule/$', TemplateView.as_view(template_name='static-content/schedule.html',), name='schedule-static'),
    url(r'^venue/$', TemplateView.as_view(template_name='static-content/venue.html',), name='venue-static'),
    url(r'^sponsors/$', TemplateView.as_view(template_name='static-content/sponsors.html',), name='sponsors-static'),
    url(r'^blog/$', TemplateView.as_view(template_name='static-content/blog-archive.html',), name='blog-archive'),
    url(r'^coc/$', TemplateView.as_view(template_name='static-content/coc.html',), name='coc-static'),
    url(r'^faq/$', TemplateView.as_view(template_name='static-content/faq.html',), name='faq-static'),

    # Proposals as conference home page. TODO: Needs to be enhanced
    url(r'^(?P<conference_slug>[\w-]+)--/',
        RedirectView.as_view(pattern_name="proposals-list"),
        name='conference-detail'),

    # add at the last for minor performance gain
    url(r'^', include('junction.pages.urls', namespace='pages')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^400/$', 'django.views.defaults.bad_request'),  # noqa
        url(r'^403/$', 'django.views.defaults.permission_denied'),
        url(r'^404/$', 'django.views.defaults.page_not_found'),
        url(r'^500/$', 'django.views.defaults.server_error'),
    )


text:
"use strict";

angular.module("CatModule", [])

.directive("cat", ["StyleFactory", function(StyleFactory){
    return {
        scope: { id: "@" },
        replace: true,
        restrict: "E",
        templateUrl: "components/cat/cat.html",
        compile:  function () {
            return {
                pre: function () {
                    StyleFactory.get("cat", "components/cat/cat.css");
                }
            }
        },
        controller: "CatCtrl"
    }
}])

.controller("CatCtrl", ["$scope", "ModelFactory", function($scope, ModelFactory) {
    ModelFactory.get("components/cat/cat.json")
        .success(function(data){
            $scope.model = data;
            console.log($scope.id, $scope.model)
        });
}]);


text:
package com.orange.csr;

import Helpers.Log;
import Helpers.TimerHelper;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * Created by DTBR6182 on 2015-08-26.
 */
public class BaseTest {
    // This will help only if we have different MSISDN's and PIN in the file so that different set of data are used
    protected final static int NO_OF_ATTEMPTS_FOR_WEBSERVICE = Integer.parseInt(System.getProperty("NO_OF_ATTEMPTS_FOR_WEBSERVICE", "1"));
    //static String APPLICATION_URL_FULL = "http://10.170.194.214:1080/SAVOIP2/";

    static String APPLICATION_URL_FULL = "https://self.sso-dev.infra.ftgroup/logingassifaible.jsp?" +
            "activateWindows=true&TYPE=33554433&REALMOID=06-000ad14a-2fb1-1b71-8d9ee8be0aaad064&GUID=" +
            "&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=$SM$xbSpBfm%2bhWHxeQBK%2fUVaOtTlaTiephGDVWxzokSFrQp9WFGjEVlALHaS6jL5m5xG&TARGET=" +
            "$SM$HTTPS%3a%2f%2fself.ssodev.infra.ftgroup%2fAuthForm%2fredirect.jsp%3fRETURN%3dHTTPS%3a%2f%2fself.ssodev.infra." +
            "ftgroup%2fAuthfaible%2flogin.jsp%3fcmd%3dlogin%26noheaderfooter%3dfalse%26showhelp";
    private static final String APPLICATION_URL = System.getProperty("APPLICATION_URL",APPLICATION_URL_FULL);
    private static final String BROWSER = System.getProperty("BROWSER","chrome");
    public static RemoteWebDriver driver;

    @BeforeClass(enabled = true,groups = {"web"})
    public void suiteSetup(){
        Log.info("Opening Browser");
        DesiredCapabilities capabilities;
        switch (BROWSER){
            case "chrome":
                String path = "E:\\Personal\\tools\\chromedriver.exe";
                System.setProperty( "webdriver.chrome.driver", path );
                driver = new ChromeDriver();
                break;
            case "firefox":
                driver = new FirefoxDriver();
                break;
            case "ie":
                capabilities = DesiredCapabilities.internetExplorer();
                capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
                capabilities.setCapability(InternetExplorerDriver.NATIVE_EVENTS,false);
                String IePath = "E:\\Personal\\tools\\IEDriverServer.exe";
                System.setProperty("webdriver.ie.driver",IePath);
                driver = new InternetExplorerDriver(capabilities);
                break;
        }
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
    }

    @BeforeMethod(enabled = true,groups = {"web"})
    public void loadLoginPage(){
        driver.get(APPLICATION_URL);
    }

    @AfterClass(enabled = true,groups = {"web"})
    public void suiteTearDown(){

        driver.manage().deleteAllCookies();
        driver.quit();

    }
    @AfterMethod(enabled = true,groups = {"web"})
    public void TestTearDown(){
        //driver.quit();
    }

    public boolean isElementPresent(By locator){
        if (driver.findElements(locator).size() > 0){
            return true;
        }else {
            return false;
        }
    }
    public String getConfigurationFile( String key ){
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("Conf/" + "TestData.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties.getProperty(key);
    }

    protected JSONObject getConfigFile(String fileName){
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("WebServices/" + fileName);
        return new JSONObject(new JSONTokener(new InputStreamReader(inputStream)));
    }

    public static String takeScreenshot(String testName) {
        SimpleDateFormat sDate = new SimpleDateFormat("HH_mm_ss");
        Date now = new Date();
        String currentTime = sDate.format(now);
        File DestFile = new File("build/reports/" + BROWSER + "/" + testName + "_" + BROWSER + "-" + currentTime + ".png");
        //WebDriver augmentedDriver = new Augmenter().augment(driver);
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(scrFile,DestFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DestFile.getAbsolutePath();
    }
}


text:
@CHARSET "UTF-8";

.main-page-container {
	margin-top: 52px;
}

/* Remove the navbar's default margin-bottom and rounded borders */
.navbar {
  margin-bottom: 0;
  border-radius: 0;
}

/* Set height of the grid so .sidenav can be 100% (adjust as needed) */
.row.content {height: 450px}

/* Set gray background color and 100% height */
.sidenav {
  padding-top: 20px;
  background-color: #f1f1f1;
  height: 100%;
}

/* Set black background color, white text and some padding */
footer {
  background-color: #555;
  color: white;
  padding: 15px;
}

/* On small screens, set height to 'auto' for sidenav and grid */
@media screen and (max-width: 767px) {
  .sidenav {
    height: auto;
    padding: 15px;
  }
  .row.content {height:auto;}
}


text:
Decorators
======================================

Below is the list of decorators available in this project.

.. _ajax_login_required:

ajax_login_required
--------------------------------------

This decorator works like the built-in Django
`login_required <http://docs.djangoproject.com/en/1.3/topics/auth/#the-login-required-decorator>`_
but it handles AJAX requests
differently. For AJAX requests, this decorator passes back custom headers to tell the client
to redirect to the login page. These headers are caught by a `ajaxComplete` listener
contained within `jquery.dj.hilbert.js`.

This is based on answers from the Stackoverflow question
`"How to manage a redirect request after a JQuery Ajax call?" <http://stackoverflow.com/questions/199099/>`_.

.. code-block:: python

    @ajax_login_required
    def authenticated_view(request):
        return HttpResponse()

.. _ajax_only:

ajax_only
--------------------------------------

The :ref:`ajax_only` decorator ensures that all requests made to a particular view are
made as AJAX requests. Non-AJAX requests will recieve a 400 (Bad Request) response.
This is based on `snippet 771 <http://djangosnippets.org/snippets/771/>`_.

.. code-block:: python

    @ajax_only
    def ajax_view(request):
        return HttpResponse()

.. _anonymous_required:

anonymous_required
--------------------------------------

.. versionadded:: 0.2

This decorator is the opposite of
`login_required <http://docs.djangoproject.com/en/1.3/topics/auth/#the-login-required-decorator>`_ .
It ensures that users attempting to view this page are not authenticated. By default this will
redirect autheticated users to the server root '/' or you can specify another
url as either an absolute path or as as named url pattern.

.. code-block:: python

    @anonymous_required(url='/hilbert/test/simple/')
    def anonymous_only_view(request):
        return HttpResponse()

.. _secure:

secure
--------------------------------------

.. versionadded:: 0.2

This decorator is similar to :ref:`SSLRedirectMiddleware` but works independently.
Decorating a view with :ref:`secure` will force this view to be accessed only
over SSL.

.. code-block:: python

    @secure
    def secure_view(request):
        return HttpResponse()


text: from django.views.generic import *