/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; 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.
 */
package org.camunda.bpm.engine.impl;

import java.util.List;

import org.camunda.bpm.engine.impl.batch.BatchConfiguration;
import org.camunda.bpm.engine.impl.batch.DeploymentMappings;
import org.camunda.bpm.engine.impl.cmd.AbstractProcessInstanceModificationCommand;

/**
 *
 * @author Anna Pazola
 *
 */
public class RestartProcessInstancesBatchConfiguration extends BatchConfiguration {

  protected List<AbstractProcessInstanceModificationCommand> instructions;
  protected String processDefinitionId;
  protected boolean initialVariables;
  protected boolean skipCustomListeners;
  protected boolean skipIoMappings;
  protected boolean withoutBusinessKey;

  public RestartProcessInstancesBatchConfiguration(List<String> processInstanceIds,
      List<AbstractProcessInstanceModificationCommand> instructions, String processDefinitionId,
      boolean initialVariables, boolean skipCustomListeners, boolean skipIoMappings, boolean withoutBusinessKey) {
    this(processInstanceIds, null, instructions, processDefinitionId, initialVariables, skipCustomListeners, skipIoMappings, withoutBusinessKey);
  }

  public RestartProcessInstancesBatchConfiguration(List<String> processInstanceIds, DeploymentMappings mappings,
      List<AbstractProcessInstanceModificationCommand> instructions, String processDefinitionId,
      boolean initialVariables, boolean skipCustomListeners, boolean skipIoMappings, boolean withoutBusinessKey) {
    super(processInstanceIds, mappings);
    this.instructions = instructions;
    this.processDefinitionId = processDefinitionId;
    this.initialVariables = initialVariables;
    this.skipCustomListeners = skipCustomListeners;
    this.skipIoMappings = skipIoMappings;
    this.withoutBusinessKey = withoutBusinessKey;
  }

  public List<AbstractProcessInstanceModificationCommand> getInstructions() {
    return instructions;
  }

  public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) {
    this.instructions = instructions;
  }

  public String getProcessDefinitionId() {
    return processDefinitionId;
  }

  public void setProcessDefinitionId(String processDefinitionId) {
    this.processDefinitionId = processDefinitionId;
  }

  public boolean isInitialVariables() {
    return initialVariables;
  }

  public void setInitialVariables(boolean initialVariables) {
    this.initialVariables = initialVariables;
  }

  public boolean isSkipCustomListeners() {
    return skipCustomListeners;
  }

  public void setSkipCustomListeners(boolean skipCustomListeners) {
    this.skipCustomListeners = skipCustomListeners;
  }

  public boolean isSkipIoMappings() {
    return skipIoMappings;
  }

  public void setSkipIoMappings(boolean skipIoMappings) {
    this.skipIoMappings = skipIoMappings;
  }

  public boolean isWithoutBusinessKey() {
    return withoutBusinessKey;
  }

  public void setWithoutBusinessKey(boolean withoutBusinessKey) {
    this.withoutBusinessKey = withoutBusinessKey;
  }
}

{'repo_name': 'camunda/camunda-bpm-platform', 'stars': '1508', 'repo_language': 'Java', 'file_name': 'DmnBusinessRuleTaskTest.java', 'mime_type': 'text/x-java', 'hash': -1699234431319759976, 'source_dataset': 'data'}


# strip-json-comments [![Build Status](https://travis-ci.org/sindresorhus/strip-json-comments.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-json-comments)

> Strip comments from JSON. Lets you use comments in your JSON files!

This is now possible:

```js
{
	// rainbows
	"unicorn": /* ❤ */ "cake"
}
```

It will replace single-line comments `//` and multi-line comments `/**/` with whitespace. This allows JSON error positions to remain as close as possible to the original source.

Also available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin.

## Install

```
$ npm install --save strip-json-comments
```

## Usage

```js
const json = '{/*rainbows*/"unicorn":"cake"}';

JSON.parse(stripJsonComments(json));
//=> {unicorn: 'cake'}
```

## API

### stripJsonComments(input, [options])

#### input

Type: `string`

Accepts a string with JSON and returns a string without comments.

#### options

##### whitespace

Type: `boolean`
Default: `true`

Replace comments with whitespace instead of stripping them entirely.

## Related

- [strip-json-comments-cli](https://github.com/sindresorhus/strip-json-comments-cli) - CLI for this module
- [strip-css-comments](https://github.com/sindresorhus/strip-css-comments) - Strip comments from CSS

## License

MIT © [Sindre Sorhus](http://sindresorhus.com)

{'repo_name': 'sx1989827/DOClever', 'stars': '2669', 'repo_language': 'JavaScript', 'file_name': 'parse.js', 'mime_type': 'text/plain', 'hash': -4127388294274543513, 'source_dataset': 'data'}


<!doctype html>

    <title>{{title}}</title>
    <meta charset="utf-8" />
    <meta name="keywords" content="{{keywords}}" />
    <meta name="description" content="{{description}}" />
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link href="//dn-staticfile.qbox.me/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" media="screen">

    {% block nav %}{% include "component/nav.html" %}{% endblock %}

    {% block body %}{% endblock %}

Maintained by the eggjs team.

GitHub

·

Issues

{'repo_name': 'eggjs/examples', 'stars': '1441', 'repo_language': 'JavaScript', 'file_name': 'user.js', 'mime_type': 'text/plain', 'hash': 5019274948349971593, 'source_dataset': 'data'}


From 9a5009d7589367ab887b7e7641224d402428ba2e Mon Sep 17 00:00:00 2001
From: Ioana Ciornei <ioana.ciornei@nxp.com>
Date: Thu, 15 Mar 2018 12:05:33 -0500
Subject: [PATCH 281/448] bus: fsl-mc: add fsl_mc_allocator cleanup function

The userspace support for fsl-mc requires a fsl_mc_allocator
cleanup function. Add the needed function.

Signed-off-by: Ioana Ciornei <ioana.ciornei@nxp.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
---
 drivers/bus/fsl-mc/fsl-mc-allocator.c |    5 +++++
 drivers/bus/fsl-mc/fsl-mc-private.h   |    2 ++
 2 files changed, 7 insertions(+), 0 deletions(-)

diff --git a/drivers/bus/fsl-mc/fsl-mc-allocator.c b/drivers/bus/fsl-mc/fsl-mc-allocator.c
index 452c5d7..fb1442b 100644
--- a/drivers/bus/fsl-mc/fsl-mc-allocator.c
+++ b/drivers/bus/fsl-mc/fsl-mc-allocator.c
@@ -646,3 +646,8 @@ int __init fsl_mc_allocator_driver_init(void)
 {
 	return fsl_mc_driver_register(&fsl_mc_allocator_driver);
 }
+
+void fsl_mc_allocator_driver_exit(void)
+{
+	fsl_mc_driver_unregister(&fsl_mc_allocator_driver);
+}
diff --git a/drivers/bus/fsl-mc/fsl-mc-private.h b/drivers/bus/fsl-mc/fsl-mc-private.h
index 52c069d..ea11b4f 100644
--- a/drivers/bus/fsl-mc/fsl-mc-private.h
+++ b/drivers/bus/fsl-mc/fsl-mc-private.h
@@ -525,6 +525,8 @@ int __must_check fsl_mc_device_add(struct fsl_mc_obj_desc *obj_desc,

 int __init fsl_mc_allocator_driver_init(void);

+void fsl_mc_allocator_driver_exit(void);
+
 void fsl_mc_init_all_resource_pools(struct fsl_mc_device *mc_bus_dev);

 void fsl_mc_cleanup_all_resource_pools(struct fsl_mc_device *mc_bus_dev);
--
1.7.1

{'repo_name': 'opencomputeproject/onie', 'stars': '367', 'repo_language': 'Makefile', 'file_name': '50_onie_grub', 'mime_type': 'text/x-shellscript', 'hash': 3580792444079478027, 'source_dataset': 'data'}


*> \brief  DSPEVX computes the eigenvalues and, optionally, the left and/or right eigenvectors for OTHER matrices
*
*  =========== DOCUMENTATION ===========
*
* Online html documentation available at
*            http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download DSPEVX + dependencies
*>
*> [TGZ]
*>
*> [ZIP]
*>
*> [TXT]
*> \endhtmlonly
*
*  Definition:
*  ===========
*
*       SUBROUTINE DSPEVX( JOBZ, RANGE, UPLO, N, AP, VL, VU, IL, IU,
*                          ABSTOL, M, W, Z, LDZ, WORK, IWORK, IFAIL,
*                          INFO )
*
*       .. Scalar Arguments ..
*       CHARACTER          JOBZ, RANGE, UPLO
*       INTEGER            IL, INFO, IU, LDZ, M, N
*       DOUBLE PRECISION   ABSTOL, VL, VU
*       ..
*       .. Array Arguments ..
*       INTEGER            IFAIL( * ), IWORK( * )
*       DOUBLE PRECISION   AP( * ), W( * ), WORK( * ), Z( LDZ, * )
*       ..
*
*
*> \par Purpose:
*  =============
*>
*> \verbatim
*>
*> DSPEVX computes selected eigenvalues and, optionally, eigenvectors
*> of a real symmetric matrix A in packed storage.  Eigenvalues/vectors
*> can be selected by specifying either a range of values or a range of
*> indices for the desired eigenvalues.
*> \endverbatim
*
*  Arguments:
*  ==========
*
*> \param[in] JOBZ
*> \verbatim
*>          JOBZ is CHARACTER*1
*>          = 'N':  Compute eigenvalues only;
*>          = 'V':  Compute eigenvalues and eigenvectors.
*> \endverbatim
*>
*> \param[in] RANGE
*> \verbatim
*>          RANGE is CHARACTER*1
*>          = 'A': all eigenvalues will be found;
*>          = 'V': all eigenvalues in the half-open interval (VL,VU]
*>                 will be found;
*>          = 'I': the IL-th through IU-th eigenvalues will be found.
*> \endverbatim
*>
*> \param[in] UPLO
*> \verbatim
*>          UPLO is CHARACTER*1
*>          = 'U':  Upper triangle of A is stored;
*>          = 'L':  Lower triangle of A is stored.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*>          N is INTEGER
*>          The order of the matrix A.  N >= 0.
*> \endverbatim
*>
*> \param[in,out] AP
*> \verbatim
*>          AP is DOUBLE PRECISION array, dimension (N*(N+1)/2)
*>          On entry, the upper or lower triangle of the symmetric matrix
*>          A, packed columnwise in a linear array.  The j-th column of A
*>          is stored in the array AP as follows:
*>          if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j;
*>          if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j<=i<=n.
*>
*>          On exit, AP is overwritten by values generated during the
*>          reduction to tridiagonal form.  If UPLO = 'U', the diagonal
*>          and first superdiagonal of the tridiagonal matrix T overwrite
*>          the corresponding elements of A, and if UPLO = 'L', the
*>          diagonal and first subdiagonal of T overwrite the
*>          corresponding elements of A.
*> \endverbatim
*>
*> \param[in] VL
*> \verbatim
*>          VL is DOUBLE PRECISION
*> \endverbatim
*>
*> \param[in] VU
*> \verbatim
*>          VU is DOUBLE PRECISION
*>          If RANGE='V', the lower and upper bounds of the interval to
*>          be searched for eigenvalues. VL < VU.
*>          Not referenced if RANGE = 'A' or 'I'.
*> \endverbatim
*>
*> \param[in] IL
*> \verbatim
*>          IL is INTEGER
*> \endverbatim
*>
*> \param[in] IU
*> \verbatim
*>          IU is INTEGER
*>          If RANGE='I', the indices (in ascending order) of the
*>          smallest and largest eigenvalues to be returned.
*>          1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0.
*>          Not referenced if RANGE = 'A' or 'V'.
*> \endverbatim
*>
*> \param[in] ABSTOL
*> \verbatim
*>          ABSTOL is DOUBLE PRECISION
*>          The absolute error tolerance for the eigenvalues.
*>          An approximate eigenvalue is accepted as converged
*>          when it is determined to lie in an interval [a,b]
*>          of width less than or equal to
*>
*>                  ABSTOL + EPS *   max( |a|,|b| ) ,
*>
*>          where EPS is the machine precision.  If ABSTOL is less than
*>          or equal to zero, then  EPS*|T|  will be used in its place,
*>          where |T| is the 1-norm of the tridiagonal matrix obtained
*>          by reducing AP to tridiagonal form.
*>
*>          Eigenvalues will be computed most accurately when ABSTOL is
*>          set to twice the underflow threshold 2*DLAMCH('S'), not zero.
*>          If this routine returns with INFO>0, indicating that some
*>          eigenvectors did not converge, try setting ABSTOL to
*>          2*DLAMCH('S').
*>
*>          See "Computing Small Singular Values of Bidiagonal Matrices
*>          with Guaranteed High Relative Accuracy," by Demmel and
*>          Kahan, LAPACK Working Note #3.
*> \endverbatim
*>
*> \param[out] M
*> \verbatim
*>          M is INTEGER
*>          The total number of eigenvalues found.  0 <= M <= N.
*>          If RANGE = 'A', M = N, and if RANGE = 'I', M = IU-IL+1.
*> \endverbatim
*>
*> \param[out] W
*> \verbatim
*>          W is DOUBLE PRECISION array, dimension (N)
*>          If INFO = 0, the selected eigenvalues in ascending order.
*> \endverbatim
*>
*> \param[out] Z
*> \verbatim
*>          Z is DOUBLE PRECISION array, dimension (LDZ, max(1,M))
*>          If JOBZ = 'V', then if INFO = 0, the first M columns of Z
*>          contain the orthonormal eigenvectors of the matrix A
*>          corresponding to the selected eigenvalues, with the i-th
*>          column of Z holding the eigenvector associated with W(i).
*>          If an eigenvector fails to converge, then that column of Z
*>          contains the latest approximation to the eigenvector, and the
*>          index of the eigenvector is returned in IFAIL.
*>          If JOBZ = 'N', then Z is not referenced.
*>          Note: the user must ensure that at least max(1,M) columns are
*>          supplied in the array Z; if RANGE = 'V', the exact value of M
*>          is not known in advance and an upper bound must be used.
*> \endverbatim
*>
*> \param[in] LDZ
*> \verbatim
*>          LDZ is INTEGER
*>          The leading dimension of the array Z.  LDZ >= 1, and if
*>          JOBZ = 'V', LDZ >= max(1,N).
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*>          WORK is DOUBLE PRECISION array, dimension (8*N)
*> \endverbatim
*>
*> \param[out] IWORK
*> \verbatim
*>          IWORK is INTEGER array, dimension (5*N)
*> \endverbatim
*>
*> \param[out] IFAIL
*> \verbatim
*>          IFAIL is INTEGER array, dimension (N)
*>          If JOBZ = 'V', then if INFO = 0, the first M elements of
*>          IFAIL are zero.  If INFO > 0, then IFAIL contains the
*>          indices of the eigenvectors that failed to converge.
*>          If JOBZ = 'N', then IFAIL is not referenced.
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*>          INFO is INTEGER
*>          = 0:  successful exit
*>          < 0:  if INFO = -i, the i-th argument had an illegal value
*>          > 0:  if INFO = i, then i eigenvectors failed to converge.
*>                Their indices are stored in array IFAIL.
*> \endverbatim
*
*  Authors:
*  ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup doubleOTHEReigen
*
*  =====================================================================
      SUBROUTINE DSPEVX( JOBZ, RANGE, UPLO, N, AP, VL, VU, IL, IU,
     $                   ABSTOL, M, W, Z, LDZ, WORK, IWORK, IFAIL,
     $                   INFO )
*
*  -- LAPACK driver routine (version 3.4.0) --
*  -- LAPACK is a software package provided by Univ. of Tennessee,    --
*  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
*     November 2011
*
*     .. Scalar Arguments ..
      CHARACTER          JOBZ, RANGE, UPLO
      INTEGER            IL, INFO, IU, LDZ, M, N
      DOUBLE PRECISION   ABSTOL, VL, VU
*     ..
*     .. Array Arguments ..
      INTEGER            IFAIL( * ), IWORK( * )
      DOUBLE PRECISION   AP( * ), W( * ), WORK( * ), Z( LDZ, * )
*     ..
*
*  =====================================================================
*
*     .. Parameters ..
      DOUBLE PRECISION   ZERO, ONE
      PARAMETER          ( ZERO = 0.0D0, ONE = 1.0D0 )
*     ..
*     .. Local Scalars ..
      LOGICAL            ALLEIG, INDEIG, TEST, VALEIG, WANTZ
      CHARACTER          ORDER
      INTEGER            I, IINFO, IMAX, INDD, INDE, INDEE, INDIBL,
     $                   INDISP, INDIWO, INDTAU, INDWRK, ISCALE, ITMP1,
     $                   J, JJ, NSPLIT
      DOUBLE PRECISION   ABSTLL, ANRM, BIGNUM, EPS, RMAX, RMIN, SAFMIN,
     $                   SIGMA, SMLNUM, TMP1, VLL, VUU
*     ..
*     .. External Functions ..
      LOGICAL            LSAME
      DOUBLE PRECISION   DLAMCH, DLANSP
      EXTERNAL           LSAME, DLAMCH, DLANSP
*     ..
*     .. External Subroutines ..
      EXTERNAL           DCOPY, DOPGTR, DOPMTR, DSCAL, DSPTRD, DSTEBZ,
     $                   DSTEIN, DSTEQR, DSTERF, DSWAP, XERBLA
*     ..
*     .. Intrinsic Functions ..
      INTRINSIC          MAX, MIN, SQRT
*     ..
*     .. Executable Statements ..
*
*     Test the input parameters.
*
      WANTZ = LSAME( JOBZ, 'V' )
      ALLEIG = LSAME( RANGE, 'A' )
      VALEIG = LSAME( RANGE, 'V' )
      INDEIG = LSAME( RANGE, 'I' )
*
      INFO = 0
      IF( .NOT.( WANTZ .OR. LSAME( JOBZ, 'N' ) ) ) THEN
         INFO = -1
      ELSE IF( .NOT.( ALLEIG .OR. VALEIG .OR. INDEIG ) ) THEN
         INFO = -2
      ELSE IF( .NOT.( LSAME( UPLO, 'L' ) .OR. LSAME( UPLO, 'U' ) ) )
     $          THEN
         INFO = -3
      ELSE IF( N.LT.0 ) THEN
         INFO = -4
      ELSE
         IF( VALEIG ) THEN
            IF( N.GT.0 .AND. VU.LE.VL )
     $         INFO = -7
         ELSE IF( INDEIG ) THEN
            IF( IL.LT.1 .OR. IL.GT.MAX( 1, N ) ) THEN
               INFO = -8
            ELSE IF( IU.LT.MIN( N, IL ) .OR. IU.GT.N ) THEN
               INFO = -9
            END IF
         END IF
      END IF
      IF( INFO.EQ.0 ) THEN
         IF( LDZ.LT.1 .OR. ( WANTZ .AND. LDZ.LT.N ) )
     $      INFO = -14
      END IF
*
      IF( INFO.NE.0 ) THEN
         CALL XERBLA( 'DSPEVX', -INFO )
         RETURN
      END IF
*
*     Quick return if possible
*
      M = 0
      IF( N.EQ.0 )
     $   RETURN
*
      IF( N.EQ.1 ) THEN
         IF( ALLEIG .OR. INDEIG ) THEN
            M = 1
            W( 1 ) = AP( 1 )
         ELSE
            IF( VL.LT.AP( 1 ) .AND. VU.GE.AP( 1 ) ) THEN
               M = 1
               W( 1 ) = AP( 1 )
            END IF
         END IF
         IF( WANTZ )
     $      Z( 1, 1 ) = ONE
         RETURN
      END IF
*
*     Get machine constants.
*
      SAFMIN = DLAMCH( 'Safe minimum' )
      EPS = DLAMCH( 'Precision' )
      SMLNUM = SAFMIN / EPS
      BIGNUM = ONE / SMLNUM
      RMIN = SQRT( SMLNUM )
      RMAX = MIN( SQRT( BIGNUM ), ONE / SQRT( SQRT( SAFMIN ) ) )
*
*     Scale matrix to allowable range, if necessary.
*
      ISCALE = 0
      ABSTLL = ABSTOL
      IF( VALEIG ) THEN
         VLL = VL
         VUU = VU
      ELSE
         VLL = ZERO
         VUU = ZERO
      END IF
      ANRM = DLANSP( 'M', UPLO, N, AP, WORK )
      IF( ANRM.GT.ZERO .AND. ANRM.LT.RMIN ) THEN
         ISCALE = 1
         SIGMA = RMIN / ANRM
      ELSE IF( ANRM.GT.RMAX ) THEN
         ISCALE = 1
         SIGMA = RMAX / ANRM
      END IF
      IF( ISCALE.EQ.1 ) THEN
         CALL DSCAL( ( N*( N+1 ) ) / 2, SIGMA, AP, 1 )
         IF( ABSTOL.GT.0 )
     $      ABSTLL = ABSTOL*SIGMA
         IF( VALEIG ) THEN
            VLL = VL*SIGMA
            VUU = VU*SIGMA
         END IF
      END IF
*
*     Call DSPTRD to reduce symmetric packed matrix to tridiagonal form.
*
      INDTAU = 1
      INDE = INDTAU + N
      INDD = INDE + N
      INDWRK = INDD + N
      CALL DSPTRD( UPLO, N, AP, WORK( INDD ), WORK( INDE ),
     $             WORK( INDTAU ), IINFO )
*
*     If all eigenvalues are desired and ABSTOL is less than or equal
*     to zero, then call DSTERF or DOPGTR and SSTEQR.  If this fails
*     for some eigenvalue, then try DSTEBZ.
*
      TEST = .FALSE.
      IF (INDEIG) THEN
         IF (IL.EQ.1 .AND. IU.EQ.N) THEN
            TEST = .TRUE.
         END IF
      END IF
      IF ((ALLEIG .OR. TEST) .AND. (ABSTOL.LE.ZERO)) THEN
         CALL DCOPY( N, WORK( INDD ), 1, W, 1 )
         INDEE = INDWRK + 2*N
         IF( .NOT.WANTZ ) THEN
            CALL DCOPY( N-1, WORK( INDE ), 1, WORK( INDEE ), 1 )
            CALL DSTERF( N, W, WORK( INDEE ), INFO )
         ELSE
            CALL DOPGTR( UPLO, N, AP, WORK( INDTAU ), Z, LDZ,
     $                   WORK( INDWRK ), IINFO )
            CALL DCOPY( N-1, WORK( INDE ), 1, WORK( INDEE ), 1 )
            CALL DSTEQR( JOBZ, N, W, WORK( INDEE ), Z, LDZ,
     $                   WORK( INDWRK ), INFO )
            IF( INFO.EQ.0 ) THEN
               DO 10 I = 1, N
                  IFAIL( I ) = 0
   10          CONTINUE
            END IF
         END IF
         IF( INFO.EQ.0 ) THEN
            M = N
            GO TO 20
         END IF
         INFO = 0
      END IF
*
*     Otherwise, call DSTEBZ and, if eigenvectors are desired, SSTEIN.
*
      IF( WANTZ ) THEN
         ORDER = 'B'
      ELSE
         ORDER = 'E'
      END IF
      INDIBL = 1
      INDISP = INDIBL + N
      INDIWO = INDISP + N
      CALL DSTEBZ( RANGE, ORDER, N, VLL, VUU, IL, IU, ABSTLL,
     $             WORK( INDD ), WORK( INDE ), M, NSPLIT, W,
     $             IWORK( INDIBL ), IWORK( INDISP ), WORK( INDWRK ),
     $             IWORK( INDIWO ), INFO )
*
      IF( WANTZ ) THEN
         CALL DSTEIN( N, WORK( INDD ), WORK( INDE ), M, W,
     $                IWORK( INDIBL ), IWORK( INDISP ), Z, LDZ,
     $                WORK( INDWRK ), IWORK( INDIWO ), IFAIL, INFO )
*
*        Apply orthogonal matrix used in reduction to tridiagonal
*        form to eigenvectors returned by DSTEIN.
*
         CALL DOPMTR( 'L', UPLO, 'N', N, M, AP, WORK( INDTAU ), Z, LDZ,
     $                WORK( INDWRK ), IINFO )
      END IF
*
*     If matrix was scaled, then rescale eigenvalues appropriately.
*
   20 CONTINUE
      IF( ISCALE.EQ.1 ) THEN
         IF( INFO.EQ.0 ) THEN
            IMAX = M
         ELSE
            IMAX = INFO - 1
         END IF
         CALL DSCAL( IMAX, ONE / SIGMA, W, 1 )
      END IF
*
*     If eigenvalues are not in order, then sort them, along with
*     eigenvectors.
*
      IF( WANTZ ) THEN
         DO 40 J = 1, M - 1
            I = 0
            TMP1 = W( J )
            DO 30 JJ = J + 1, M
               IF( W( JJ ).LT.TMP1 ) THEN
                  I = JJ
                  TMP1 = W( JJ )
               END IF
   30       CONTINUE
*
            IF( I.NE.0 ) THEN
               ITMP1 = IWORK( INDIBL+I-1 )
               W( I ) = W( J )
               IWORK( INDIBL+I-1 ) = IWORK( INDIBL+J-1 )
               W( J ) = TMP1
               IWORK( INDIBL+J-1 ) = ITMP1
               CALL DSWAP( N, Z( 1, I ), 1, Z( 1, J ), 1 )
               IF( INFO.NE.0 ) THEN
                  ITMP1 = IFAIL( I )
                  IFAIL( I ) = IFAIL( J )
                  IFAIL( J ) = ITMP1
               END IF
            END IF
   40    CONTINUE
      END IF
*
      RETURN
*
*     End of DSPEVX
*
      END

{'repo_name': 'fommil/netlib-java', 'stars': '630', 'repo_language': 'Fortran', 'file_name': 'pom.xml', 'mime_type': 'text/xml', 'hash': -8033767079954513188, 'source_dataset': 'data'}


using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V28.Segment;
using NHapi.Model.V28.Datatype;
using NHapi.Base.Model;

namespace NHapi.Model.V28.Group
{
///
///Represents the CSU_C09_COMMON_ORDER Group.  A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///

///
0: ORC (Common Order)

///
1: PRT (Participation Information) optional repeating

///

///
[Serializable]
public class CSU_C09_COMMON_ORDER : AbstractGroup {

	///
	/// Creates a new CSU_C09_COMMON_ORDER Group.
	///
	public CSU_C09_COMMON_ORDER(IGroup parent, IModelClassFactory factory) : base(parent, factory){
	   try {
	      this.add(typeof(ORC), true, false);
	      this.add(typeof(PRT), false, true);
	   } catch(HL7Exception e) {
	      HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating CSU_C09_COMMON_ORDER - this is probably a bug in the source code generator.", e);
	   }
	}

	///
	/// Returns ORC (Common Order) - creates it if necessary
	///
	public ORC ORC {
get{
	   ORC ret = null;
	   try {
	      ret = (ORC)this.GetStructure("ORC");
	   } catch(HL7Exception e) {
	      HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
	      throw new System.Exception("An unexpected error ocurred",e);
	   }
	   return ret;
	}
	}

	///
	/// Returns  first repetition of PRT (Participation Information) - creates it if necessary
	///
	public PRT GetPRT() {
	   PRT ret = null;
	   try {
	      ret = (PRT)this.GetStructure("PRT");
	   } catch(HL7Exception e) {
	      HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
	      throw new System.Exception("An unexpected error ocurred",e);
	   }
	   return ret;
	}

	///
	///Returns a specific repetition of PRT
	/// * (Participation Information) - creates it if necessary
	/// throws HL7Exception if the repetition requested is more than one
	///     greater than the number of existing repetitions.
	///
	public PRT GetPRT(int rep) {
	   return (PRT)this.GetStructure("PRT", rep);
	}

	/**
	 * Returns the number of existing repetitions of PRT
	 */
	public int PRTRepetitionsUsed {
get{
	    int reps = -1;
	    try {
	        reps = this.GetAll("PRT").Length;
	    } catch (HL7Exception e) {
	        string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
	        HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
	        throw new System.Exception(message);
	    }
	    return reps;
	}
	}

	/**
	 * Enumerate over the PRT results
	 */
	public IEnumerable<PRT> PRTs
	{
		get
		{
			for (int rep = 0; rep < PRTRepetitionsUsed; rep++)
			{
				yield return (PRT)this.GetStructure("PRT", rep);
			}
		}
	}

	///
	///Adds a new PRT
	///
	public PRT AddPRT()
	{
		return this.AddStructure("PRT") as PRT;
	}

	///
	///Removes the given PRT
	///
	public void RemovePRT(PRT toRemove)
	{
		this.RemoveStructure("PRT", toRemove);
	}

	///
	///Removes the PRT at the given index
	///
	public void RemovePRTAt(int index)
	{
		this.RemoveRepetition("PRT", index);
	}

}
}

{'repo_name': 'duaneedwards/nHapi', 'stars': '146', 'repo_language': 'C#', 'file_name': 'Constants.cs', 'mime_type': 'text/plain', 'hash': 8380056893409973632, 'source_dataset': 'data'}


package org.zstack.sdk.databasebackup;

import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;

public class QueryDatabaseBackupAction extends QueryAction {

    private static final HashMap<String, Parameter> parameterMap = new HashMap<>();

    private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();

    public static class Result {
        public ErrorCode error;
        public org.zstack.sdk.databasebackup.QueryDatabaseBackupResult value;

        public Result throwExceptionIfError() {
            if (error != null) {
                throw new ApiException(
                    String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
                );
            }

            return this;
        }
    }

    private Result makeResult(ApiResult res) {
        Result ret = new Result();
        if (res.error != null) {
            ret.error = res.error;
            return ret;
        }

        org.zstack.sdk.databasebackup.QueryDatabaseBackupResult value = res.getResult(org.zstack.sdk.databasebackup.QueryDatabaseBackupResult.class);
        ret.value = value == null ? new org.zstack.sdk.databasebackup.QueryDatabaseBackupResult() : value;

        return ret;
    }

    public Result call() {
        ApiResult res = ZSClient.call(this);
        return makeResult(res);
    }

    public void call(final Completion<Result> completion) {
        ZSClient.call(this, new InternalCompletion() {
            @Override
            public void complete(ApiResult res) {
                completion.complete(makeResult(res));
            }
        });
    }

    protected Map<String, Parameter> getParameterMap() {
        return parameterMap;
    }

    protected Map<String, Parameter> getNonAPIParameterMap() {
        return nonAPIParameterMap;
    }

    protected RestInfo getRestInfo() {
        RestInfo info = new RestInfo();
        info.httpMethod = "GET";
        info.path = "/database-backups";
        info.needSession = true;
        info.needPoll = false;
        info.parameterName = "";
        return info;
    }

}

{'repo_name': 'zstackio/zstack', 'stars': '890', 'repo_language': 'Java', 'file_name': 'Entity.java', 'mime_type': 'text/x-java', 'hash': 2365210238167731491, 'source_dataset': 'data'}


package org.apache.cassandra.utils;
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

import java.nio.ByteBuffer;

import org.github.jamm.MemoryLayoutSpecification;
import org.github.jamm.MemoryMeter;

/**
 * A convenience class for wrapping access to MemoryMeter
 */
public class ObjectSizes
{
    private static final MemoryMeter meter = new MemoryMeter()
                                             .omitSharedBufferOverhead()
                                             .withGuessing(MemoryMeter.Guess.FALLBACK_UNSAFE)
                                             .ignoreKnownSingletons();

    private static final long BUFFER_EMPTY_SIZE = measure(ByteBufferUtil.EMPTY_BYTE_BUFFER);
    private static final long STRING_EMPTY_SIZE = measure("");

    /**
     * Memory a byte array consumes
     * @param bytes byte array to get memory size
     * @return heap-size of the array
     */
    public static long sizeOfArray(byte[] bytes)
    {
        return sizeOfArray(bytes.length, 1);
    }

    /**
     * Memory a long array consumes
     * @param longs byte array to get memory size
     * @return heap-size of the array
     */
    public static long sizeOfArray(long[] longs)
    {
        return sizeOfArray(longs.length, 8);
    }

    /**
     * Memory an int array consumes
     * @param ints byte array to get memory size
     * @return heap-size of the array
     */
    public static long sizeOfArray(int[] ints)
    {
        return sizeOfArray(ints.length, 4);
    }

    /**
     * Memory a reference array consumes
     * @param length the length of the reference array
     * @return heap-size of the array
     */
    public static long sizeOfReferenceArray(int length)
    {
        return sizeOfArray(length, MemoryLayoutSpecification.SPEC.getReferenceSize());
    }

    /**
     * Memory a reference array consumes itself only
     * @param objects the array to size
     * @return heap-size of the array (excluding memory retained by referenced objects)
     */
    public static long sizeOfArray(Object[] objects)
    {
        return sizeOfReferenceArray(objects.length);
    }

    private static long sizeOfArray(int length, long elementSize)
    {
        return MemoryLayoutSpecification.sizeOfArray(length, elementSize);
    }

    /**
     * Memory a ByteBuffer array consumes.
     */
    public static long sizeOnHeapOf(ByteBuffer[] array)
    {
        long allElementsSize = 0;
        for (int i = 0; i < array.length; i++)
            if (array[i] != null)
                allElementsSize += sizeOnHeapOf(array[i]);

        return allElementsSize + sizeOfArray(array);
    }

    public static long sizeOnHeapExcludingData(ByteBuffer[] array)
    {
        return BUFFER_EMPTY_SIZE * array.length + sizeOfArray(array);
    }
    /**
     * Memory a byte buffer consumes
     * @param buffer ByteBuffer to calculate in memory size
     * @return Total in-memory size of the byte buffer
     */
    public static long sizeOnHeapOf(ByteBuffer buffer)
    {
        if (buffer.isDirect())
            return BUFFER_EMPTY_SIZE;
        // if we're only referencing a sub-portion of the ByteBuffer, don't count the array overhead (assume it's slab
        // allocated, so amortized over all the allocations the overhead is negligible and better to undercount than over)
        if (buffer.capacity() > buffer.remaining())
            return buffer.remaining();
        return BUFFER_EMPTY_SIZE + sizeOfArray(buffer.capacity(), 1);
    }

    public static long sizeOnHeapExcludingData(ByteBuffer buffer)
    {
        return BUFFER_EMPTY_SIZE;
    }

    /**
     * Memory a String consumes
     * @param str String to calculate memory size of
     * @return Total in-memory size of the String
     */
    public static long sizeOf(String str)
    {
        return STRING_EMPTY_SIZE + sizeOfArray(str.length(), 2);
    }

    /**
     * @param pojo the object to measure
     * @return the size on the heap of the instance and all retained heap referenced by it, excluding portions of
     * ByteBuffer that are not directly referenced by it but including any other referenced that may also be retained
     * by other objects.
     */
    public static long measureDeep(Object pojo)
    {
        return meter.measureDeep(pojo);
    }

    /**
     * @param pojo the object to measure
     * @return the size on the heap of the instance only, excluding any referenced objects
     */
    public static long measure(Object pojo)
    {
        return meter.measure(pojo);
    }
}

{'repo_name': 'Stratio/stratio-cassandra', 'stars': '197', 'repo_language': 'Java', 'file_name': 'ansi_colors.py', 'mime_type': 'text/x-python', 'hash': -2316200981585254144, 'source_dataset': 'data'}


# nuScenes dev-kit.
# Code written by Freddy Boulton, 2020.

import unittest

import cv2
import numpy as np

from nuscenes.prediction.input_representation.combinators import Rasterizer

class TestRasterizer(unittest.TestCase):

    def test(self):

        layer_1 = np.zeros((100, 100, 3))
        box_1 = cv2.boxPoints(((50, 50), (20, 20), 0))
        layer_1 = cv2.fillPoly(layer_1, pts=[np.int0(box_1)], color=(255, 255, 255))

        layer_2 = np.zeros((100, 100, 3))
        box_2 = cv2.boxPoints(((70, 30), (10, 10), 0))
        layer_2 = cv2.fillPoly(layer_2, pts=[np.int0(box_2)], color=(0, 0, 255))

        rasterizer = Rasterizer()
        image = rasterizer.combine([layer_1.astype('uint8'), layer_2.astype('uint8')])

        answer = np.zeros((100, 100, 3))
        answer = cv2.fillPoly(answer, pts=[np.int0(box_1)], color=(255, 255, 255))
        answer = cv2.fillPoly(answer, pts=[np.int0(box_2)], color=(0, 0, 255))
        answer = answer.astype('uint8')

        np.testing.assert_allclose(answer, image)

{'repo_name': 'nutonomy/nuscenes-devkit', 'stars': '662', 'repo_language': 'Python', 'file_name': 'requirements_tracking.txt', 'mime_type': 'text/plain', 'hash': 3028763413465790961, 'source_dataset': 'data'}


{ lib, fetchurl, buildPythonPackage
, zip, ffmpeg, rtmpdump, phantomjs2, atomicparsley, pycryptodome, pandoc
# Pandoc is required to build the package's man page. Release tarballs contain a
# formatted man page already, though, it will still be installed. We keep the
# manpage argument in place in case someone wants to use this derivation to
# build a Git version of the tool that doesn't have the formatted man page
# included.
, generateManPage ? false
, ffmpegSupport ? true
, rtmpSupport ? true
, phantomjsSupport ? false
, hlsEncryptedSupport ? true
, installShellFiles, makeWrapper }:

buildPythonPackage rec {

  pname = "youtube-dl";
  # The websites youtube-dl deals with are a very moving target. That means that
  # downloads break constantly. Because of that, updates should always be backported
  # to the latest stable release.
  version = "2020.09.14";

  src = fetchurl {
    url = "https://yt-dl.org/downloads/${version}/${pname}-${version}.tar.gz";
    sha256 = "18wfhprbaszpxgqkac3hb050ngvdsaibbcifg88rkv5vc6bc2mq6";
  };

  nativeBuildInputs = [ installShellFiles makeWrapper ];
  buildInputs = [ zip ] ++ lib.optional generateManPage pandoc;
  propagatedBuildInputs = lib.optional hlsEncryptedSupport pycryptodome;

  # Ensure these utilities are available in $PATH:
  # - ffmpeg: post-processing & transcoding support
  # - rtmpdump: download files over RTMP
  # - atomicparsley: embedding thumbnails
  makeWrapperArgs = let
      packagesToBinPath =
        [ atomicparsley ]
        ++ lib.optional ffmpegSupport ffmpeg
        ++ lib.optional rtmpSupport rtmpdump
        ++ lib.optional phantomjsSupport phantomjs2;
    in [ ''--prefix PATH : "${lib.makeBinPath packagesToBinPath}"'' ];

  setupPyBuildFlags = [
    "build_lazy_extractors"
  ];

  postInstall = ''
    installShellCompletion youtube-dl.zsh
  '';

  # Requires network
  doCheck = false;

  meta = with lib; {
    homepage = "https://ytdl-org.github.io/youtube-dl/";
    description = "Command-line tool to download videos from YouTube.com and other sites";
    longDescription = ''
      youtube-dl is a small, Python-based command-line program
      to download videos from YouTube.com and a few more sites.
      youtube-dl is released to the public domain, which means
      you can modify it, redistribute it or use it however you like.
    '';
    license = licenses.publicDomain;
    platforms = with platforms; linux ++ darwin;
    maintainers = with maintainers; [ bluescreen303 phreedom AndersonTorres fpletz enzime ma27 ];
  };
}

{'repo_name': 'NixOS/nixpkgs-channels', 'stars': '161', 'repo_language': 'Nix', 'file_name': 'default.nix', 'mime_type': 'text/plain', 'hash': 5835023624193999356, 'source_dataset': 'data'}


define("funcSet",
            ["require", "exports", "module"],
            function (require, exports, module) {
    module.exports = "funcSet";
});

{'repo_name': 'kwhinnery/node-workshop', 'stars': '146', 'repo_language': 'JavaScript', 'file_name': 'Readme.md', 'mime_type': 'text/plain', 'hash': 8135076968926373199, 'source_dataset': 'data'}


#ifndef BT_CLIP_POLYGON_H_INCLUDED
#define BT_CLIP_POLYGON_H_INCLUDED

/*! \file btClipPolygon.h
\author Francisco Leon Najera
*/
/*
This source file is part of GIMPACT Library.

For the latest info, see http://gimpact.sourceforge.net/

Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#include "bullet/LinearMath/btTransform.h"
#include "bullet/LinearMath/btGeometryUtil.h"

SIMD_FORCE_INLINE btScalar bt_distance_point_plane(const btVector4 & plane,const btVector3 &point)
{
	return point.dot(plane) - plane[3];
}

/*! Vector blending
Takes two vectors a, b, blends them together*/
SIMD_FORCE_INLINE void bt_vec_blend(btVector3 &vr, const btVector3 &va,const btVector3 &vb, btScalar blend_factor)
{
	vr = (1-blend_factor)*va + blend_factor*vb;
}

//! This function calcs the distance from a 3D plane
SIMD_FORCE_INLINE void bt_plane_clip_polygon_collect(
						const btVector3 & point0,
						const btVector3 & point1,
						btScalar dist0,
						btScalar dist1,
						btVector3 * clipped,
						int & clipped_count)
{
	bool _prevclassif = (dist0>SIMD_EPSILON);
	bool _classif = (dist1>SIMD_EPSILON);
	if(_classif!=_prevclassif)
	{
		btScalar blendfactor = -dist0/(dist1-dist0);
		bt_vec_blend(clipped[clipped_count],point0,point1,blendfactor);
		clipped_count++;
	}
	if(!_classif)
	{
		clipped[clipped_count] = point1;
		clipped_count++;
	}
}

//! Clips a polygon by a plane
/*!
*\return The count of the clipped counts
*/
SIMD_FORCE_INLINE int bt_plane_clip_polygon(
						const btVector4 & plane,
						const btVector3 * polygon_points,
						int polygon_point_count,
						btVector3 * clipped)
{
    int clipped_count = 0;

    //clip first point
	btScalar firstdist = bt_distance_point_plane(plane,polygon_points[0]);;
	if(!(firstdist>SIMD_EPSILON))
	{
		clipped[clipped_count] = polygon_points[0];
		clipped_count++;
	}

	btScalar olddist = firstdist;
	for(int i=1;i<polygon_point_count;i++)
	{
		btScalar dist = bt_distance_point_plane(plane,polygon_points[i]);

		bt_plane_clip_polygon_collect(
						polygon_points[i-1],polygon_points[i],
						olddist,
						dist,
						clipped,
						clipped_count);

		olddist = dist;
	}

	//RETURN TO FIRST  point

	bt_plane_clip_polygon_collect(
					polygon_points[polygon_point_count-1],polygon_points[0],
					olddist,
					firstdist,
					clipped,
					clipped_count);

	return clipped_count;
}

//! Clips a polygon by a plane
/*!
*\param clipped must be an array of 16 points.
*\return The count of the clipped counts
*/
SIMD_FORCE_INLINE int bt_plane_clip_triangle(
						const btVector4 & plane,
						const btVector3 & point0,
						const btVector3 & point1,
						const btVector3& point2,
						btVector3 * clipped // an allocated array of 16 points at least
						)
{
    int clipped_count = 0;

    //clip first point0
	btScalar firstdist = bt_distance_point_plane(plane,point0);;
	if(!(firstdist>SIMD_EPSILON))
	{
		clipped[clipped_count] = point0;
		clipped_count++;
	}

	// point 1
	btScalar olddist = firstdist;
	btScalar dist = bt_distance_point_plane(plane,point1);

	bt_plane_clip_polygon_collect(
					point0,point1,
					olddist,
					dist,
					clipped,
					clipped_count);

	olddist = dist;

	// point 2
	dist = bt_distance_point_plane(plane,point2);

	bt_plane_clip_polygon_collect(
					point1,point2,
					olddist,
					dist,
					clipped,
					clipped_count);
	olddist = dist;

	//RETURN TO FIRST  point0
	bt_plane_clip_polygon_collect(
					point2,point0,
					olddist,
					firstdist,
					clipped,
					clipped_count);

	return clipped_count;
}

#endif // GIM_TRI_COLLISION_H_INCLUDED

{'repo_name': 'linyouhappy/kongkongxiyou', 'stars': '261', 'repo_language': 'C++', 'file_name': 'linyou.xml', 'mime_type': 'text/plain', 'hash': 3192773442528300276, 'source_dataset': 'data'}


// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename       : ATA.cs
// Author(s)      : Natalia Portillo <claunia@claunia.com>
//
// Component      : Core algorithms.
//
// --[ Description ] ----------------------------------------------------------
//
//     Creates reports from ATA devices.
//
// --[ License ] --------------------------------------------------------------
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as
//     published by the Free Software Foundation, either version 3 of the
//     License, or (at your option) any later version.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU General Public License for more details.
//
//     You should have received a copy of the GNU General Public License
//     along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2020 Natalia Portillo
// ****************************************************************************/

using System;
using Aaru.CommonTypes.Metadata;
using Aaru.Console;
using Aaru.Decoders.ATA;
using Aaru.Devices;
using Identify = Aaru.CommonTypes.Structs.Devices.ATA.Identify;

namespace Aaru.Core.Devices.Report
{
    public sealed partial class DeviceReport
    {
        public TestedMedia ReportAtaMedia()
        {
            var mediaTest = new TestedMedia();
            AaruConsole.Write("Please write a description of the media type and press enter: ");
            mediaTest.MediumTypeName = System.Console.ReadLine();
            AaruConsole.Write("Please write the media model and press enter: ");
            mediaTest.Model = System.Console.ReadLine();

            mediaTest.MediaIsRecognized = true;

            AaruConsole.WriteLine("Querying ATA IDENTIFY...");
            _dev.AtaIdentify(out byte[] buffer, out _, _dev.Timeout, out _);

            mediaTest.IdentifyData   = ClearIdentify(buffer);
            mediaTest.IdentifyDevice = Identify.Decode(buffer);

            if(mediaTest.IdentifyDevice.HasValue)
            {
                Identify.IdentifyDevice ataId = mediaTest.IdentifyDevice.Value;

                if(ataId.UnformattedBPT != 0)
                    mediaTest.UnformattedBPT = ataId.UnformattedBPT;

                if(ataId.UnformattedBPS != 0)
                    mediaTest.UnformattedBPS = ataId.UnformattedBPS;

                if(ataId.Cylinders       > 0 &&
                   ataId.Heads           > 0 &&
                   ataId.SectorsPerTrack > 0)
                {
                    mediaTest.CHS = new Chs
                    {
                        Cylinders = ataId.Cylinders,
                        Heads     = ataId.Heads,
                        Sectors   = ataId.SectorsPerTrack
                    };

                    mediaTest.Blocks = (ulong)(ataId.Cylinders * ataId.Heads * ataId.SectorsPerTrack);
                }

                if(ataId.CurrentCylinders       > 0 &&
                   ataId.CurrentHeads           > 0 &&
                   ataId.CurrentSectorsPerTrack > 0)
                {
                    mediaTest.CurrentCHS = new Chs
                    {
                        Cylinders = ataId.CurrentCylinders,
                        Heads     = ataId.CurrentHeads,
                        Sectors   = ataId.CurrentSectorsPerTrack
                    };

                    if(mediaTest.Blocks == 0)
                        mediaTest.Blocks =
                            (ulong)(ataId.CurrentCylinders * ataId.CurrentHeads * ataId.CurrentSectorsPerTrack);
                }

                if(ataId.Capabilities.HasFlag(Identify.CapabilitiesBit.LBASupport))
                {
                    mediaTest.LBASectors = ataId.LBASectors;
                    mediaTest.Blocks     = ataId.LBASectors;
                }

                if(ataId.CommandSet2.HasFlag(Identify.CommandSetBit2.LBA48))
                {
                    mediaTest.LBA48Sectors = ataId.LBA48Sectors;
                    mediaTest.Blocks       = ataId.LBA48Sectors;
                }

                if(ataId.NominalRotationRate != 0x0000 &&
                   ataId.NominalRotationRate != 0xFFFF)
                    if(ataId.NominalRotationRate == 0x0001)
                        mediaTest.SolidStateDevice = true;
                    else
                    {
                        mediaTest.SolidStateDevice    = false;
                        mediaTest.NominalRotationRate = ataId.NominalRotationRate;
                    }

                uint logicalSectorSize;
                uint physicalSectorSize;

                if((ataId.PhysLogSectorSize & 0x8000) == 0x0000 &&
                   (ataId.PhysLogSectorSize & 0x4000) == 0x4000)
                {
                    if((ataId.PhysLogSectorSize & 0x1000) == 0x1000)
                        if(ataId.LogicalSectorWords <= 255 ||
                           ataId.LogicalAlignment   == 0xFFFF)
                            logicalSectorSize = 512;
                        else
                            logicalSectorSize = ataId.LogicalSectorWords * 2;
                    else
                        logicalSectorSize = 512;

                    if((ataId.PhysLogSectorSize & 0x2000) == 0x2000)
                        physicalSectorSize = (uint)(logicalSectorSize * ((1 << ataId.PhysLogSectorSize) & 0xF));
                    else
                        physicalSectorSize = logicalSectorSize;
                }
                else
                {
                    logicalSectorSize  = 512;
                    physicalSectorSize = 512;
                }

                mediaTest.BlockSize = logicalSectorSize;

                if(physicalSectorSize != logicalSectorSize)
                {
                    mediaTest.PhysicalBlockSize = physicalSectorSize;

                    if((ataId.LogicalAlignment & 0x8000) == 0x0000 &&
                       (ataId.LogicalAlignment & 0x4000) == 0x4000)
                        mediaTest.LogicalAlignment = (ushort)(ataId.LogicalAlignment & 0x3FFF);
                }

                if(ataId.EccBytes != 0x0000 &&
                   ataId.EccBytes != 0xFFFF)
                    mediaTest.LongBlockSize = logicalSectorSize + ataId.EccBytes;

                if(ataId.UnformattedBPS > logicalSectorSize &&
                   (!(ataId.EccBytes != 0x0000 && ataId.EccBytes != 0xFFFF) || mediaTest.LongBlockSize == 516))
                    mediaTest.LongBlockSize = ataId.UnformattedBPS;

                if(ataId.CommandSet3.HasFlag(Identify.CommandSetBit3.MustBeSet)    &&
                   !ataId.CommandSet3.HasFlag(Identify.CommandSetBit3.MustBeClear) &&
                   ataId.EnabledCommandSet3.HasFlag(Identify.CommandSetBit3.MediaSerial))
                {
                    mediaTest.CanReadMediaSerial = true;

                    if(!string.IsNullOrWhiteSpace(ataId.MediaManufacturer))
                        mediaTest.Manufacturer = ataId.MediaManufacturer;
                }

                ulong checkCorrectRead = BitConverter.ToUInt64(buffer, 0);

                AaruConsole.WriteLine("Trying READ SECTOR(S) in CHS mode...");

                bool sense = _dev.Read(out byte[] readBuf, out AtaErrorRegistersChs errorChs, false, 0, 0, 1, 1,
                                       _dev.Timeout, out _);

                mediaTest.SupportsReadSectors = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                                readBuf.Length                     > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadSectorsData = readBuf;

                AaruConsole.WriteLine("Trying READ SECTOR(S) RETRY in CHS mode...");
                sense = _dev.Read(out readBuf, out errorChs, true, 0, 0, 1, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadRetry = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                              readBuf.Length                     > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadSectorsRetryData = readBuf;

                AaruConsole.WriteLine("Trying READ DMA in CHS mode...");
                sense = _dev.ReadDma(out readBuf, out errorChs, false, 0, 0, 1, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadDma = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                            readBuf.Length                     > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadDmaData = readBuf;

                AaruConsole.WriteLine("Trying READ DMA RETRY in CHS mode...");
                sense = _dev.ReadDma(out readBuf, out errorChs, true, 0, 0, 1, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadDmaRetry = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                                 readBuf.Length                     > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadDmaRetryData = readBuf;

                AaruConsole.WriteLine("Trying SEEK in CHS mode...");
                sense                  = _dev.Seek(out errorChs, 0, 0, 1, _dev.Timeout, out _);
                mediaTest.SupportsSeek = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0;

                AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}", sense,
                                           errorChs.Status, errorChs.Error);

                AaruConsole.WriteLine("Trying READ SECTOR(S) in LBA mode...");
                sense = _dev.Read(out readBuf, out AtaErrorRegistersLba28 errorLba, false, 0, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                            readBuf.Length                     > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadLbaData = readBuf;

                AaruConsole.WriteLine("Trying READ SECTOR(S) RETRY in LBA mode...");
                sense = _dev.Read(out readBuf, out errorLba, true, 0, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadRetryLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                                 readBuf.Length                     > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadRetryLbaData = readBuf;

                AaruConsole.WriteLine("Trying READ DMA in LBA mode...");
                sense = _dev.ReadDma(out readBuf, out errorLba, false, 0, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadDmaLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                               readBuf.Length                     > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadDmaLbaData = readBuf;

                AaruConsole.WriteLine("Trying READ DMA RETRY in LBA mode...");
                sense = _dev.ReadDma(out readBuf, out errorLba, true, 0, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadDmaRetryLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                                    readBuf.Length                     > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadDmaRetryLbaData = readBuf;

                AaruConsole.WriteLine("Trying SEEK in LBA mode...");
                sense                     = _dev.Seek(out errorLba, 0, _dev.Timeout, out _);
                mediaTest.SupportsSeekLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0;

                AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}", sense,
                                           errorChs.Status, errorChs.Error);

                AaruConsole.WriteLine("Trying READ SECTOR(S) in LBA48 mode...");
                sense = _dev.Read(out readBuf, out AtaErrorRegistersLba48 errorLba48, 0, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadLba48 = !sense && (errorLba48.Status & 0x01) != 0x01 && errorLba48.Error == 0 &&
                                              readBuf.Length                       > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadLba48Data = readBuf;

                AaruConsole.WriteLine("Trying READ DMA in LBA48 mode...");
                sense = _dev.ReadDma(out readBuf, out errorLba48, 0, 1, _dev.Timeout, out _);

                mediaTest.SupportsReadDmaLba48 = !sense && (errorLba48.Status & 0x01) != 0x01 &&
                                                 errorLba48.Error                     == 0    && readBuf.Length > 0;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadDmaLba48Data = readBuf;

                // Send SET FEATURES before sending READ LONG commands, retrieve IDENTIFY again and
                // check if ECC size changed. Sector is set to 1 because without it most drives just return
                // CORRECTABLE ERROR for this command.
                _dev.SetFeatures(out _, AtaFeatures.EnableReadLongVendorLength, 0, 0, 1, 0, _dev.Timeout, out _);

                _dev.AtaIdentify(out buffer, out _, _dev.Timeout, out _);

                if(Identify.Decode(buffer).HasValue)
                {
                    ataId = Identify.Decode(buffer).Value;

                    if(ataId.EccBytes != 0x0000 &&
                       ataId.EccBytes != 0xFFFF)
                        mediaTest.LongBlockSize = logicalSectorSize + ataId.EccBytes;

                    if(ataId.UnformattedBPS > logicalSectorSize &&
                       (!(ataId.EccBytes != 0x0000 && ataId.EccBytes != 0xFFFF) || mediaTest.LongBlockSize == 516))
                        mediaTest.LongBlockSize = ataId.UnformattedBPS;
                }

                AaruConsole.WriteLine("Trying READ LONG in CHS mode...");

                sense = _dev.ReadLong(out readBuf, out errorChs, false, 0, 0, 1, mediaTest.LongBlockSize ?? 0,
                                      _dev.Timeout, out _);

                mediaTest.SupportsReadLong = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                             readBuf.Length                     > 0     &&
                                             BitConverter.ToUInt64(readBuf, 0)  != checkCorrectRead;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadLongData = readBuf;

                AaruConsole.WriteLine("Trying READ LONG RETRY in CHS mode...");

                sense = _dev.ReadLong(out readBuf, out errorChs, true, 0, 0, 1, mediaTest.LongBlockSize ?? 0,
                                      _dev.Timeout, out _);

                mediaTest.SupportsReadLongRetry = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                                  readBuf.Length > 0 && BitConverter.ToUInt64(readBuf, 0) !=
                                                  checkCorrectRead;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadLongRetryData = readBuf;

                AaruConsole.WriteLine("Trying READ LONG in LBA mode...");

                sense = _dev.ReadLong(out readBuf, out errorLba, false, 0, mediaTest.LongBlockSize ?? 0, _dev.Timeout,
                                      out _);

                mediaTest.SupportsReadLongLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                                readBuf.Length                     > 0     &&
                                                BitConverter.ToUInt64(readBuf, 0)  != checkCorrectRead;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadLongLbaData = readBuf;

                AaruConsole.WriteLine("Trying READ LONG RETRY in LBA mode...");

                sense = _dev.ReadLong(out readBuf, out errorLba, true, 0, mediaTest.LongBlockSize ?? 0, _dev.Timeout,
                                      out _);

                mediaTest.SupportsReadLongRetryLba = !sense && (errorLba.Status & 0x01) != 0x01 &&
                                                     errorLba.Error                     == 0    && readBuf.Length > 0 &&
                                                     BitConverter.ToUInt64(readBuf, 0)  != checkCorrectRead;

                AaruConsole.DebugWriteLine("ATA Report",
                                           "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}", sense,
                                           errorChs.Status, errorChs.Error, readBuf.Length);

                mediaTest.ReadLongRetryLbaData = readBuf;
            }
            else
                mediaTest.MediaIsRecognized = false;

            return mediaTest;
        }

        /// <summary>Creates a report of an ATA device</summary>
        public TestedMedia ReportAta(Identify.IdentifyDevice ataId)
        {
            var capabilities = new TestedMedia();

            if(ataId.UnformattedBPT != 0)
                capabilities.UnformattedBPT = ataId.UnformattedBPT;

            if(ataId.UnformattedBPS != 0)
                capabilities.UnformattedBPS = ataId.UnformattedBPS;

            if(ataId.Cylinders       > 0 &&
               ataId.Heads           > 0 &&
               ataId.SectorsPerTrack > 0)
            {
                capabilities.CHS = new Chs
                {
                    Cylinders = ataId.Cylinders,
                    Heads     = ataId.Heads,
                    Sectors   = ataId.SectorsPerTrack
                };

                capabilities.Blocks = (ulong)(ataId.Cylinders * ataId.Heads * ataId.SectorsPerTrack);
            }

            if(ataId.CurrentCylinders       > 0 &&
               ataId.CurrentHeads           > 0 &&
               ataId.CurrentSectorsPerTrack > 0)
            {
                capabilities.CurrentCHS = new Chs
                {
                    Cylinders = ataId.CurrentCylinders,
                    Heads     = ataId.CurrentHeads,
                    Sectors   = ataId.CurrentSectorsPerTrack
                };

                capabilities.Blocks =
                    (ulong)(ataId.CurrentCylinders * ataId.CurrentHeads * ataId.CurrentSectorsPerTrack);
            }

            if(ataId.Capabilities.HasFlag(Identify.CapabilitiesBit.LBASupport))
            {
                capabilities.LBASectors = ataId.LBASectors;
                capabilities.Blocks     = ataId.LBASectors;
            }

            if(ataId.CommandSet2.HasFlag(Identify.CommandSetBit2.LBA48))
            {
                capabilities.LBA48Sectors = ataId.LBA48Sectors;
                capabilities.Blocks       = ataId.LBA48Sectors;
            }

            if(ataId.NominalRotationRate != 0x0000 &&
               ataId.NominalRotationRate != 0xFFFF)
                if(ataId.NominalRotationRate == 0x0001)
                    capabilities.SolidStateDevice = true;
                else
                {
                    capabilities.SolidStateDevice    = false;
                    capabilities.NominalRotationRate = ataId.NominalRotationRate;
                }

            uint logicalSectorSize;
            uint physicalSectorSize;

            if((ataId.PhysLogSectorSize & 0x8000) == 0x0000 &&
               (ataId.PhysLogSectorSize & 0x4000) == 0x4000)
            {
                if((ataId.PhysLogSectorSize & 0x1000) == 0x1000)
                    if(ataId.LogicalSectorWords <= 255 ||
                       ataId.LogicalAlignment   == 0xFFFF)
                        logicalSectorSize = 512;
                    else
                        logicalSectorSize = ataId.LogicalSectorWords * 2;
                else
                    logicalSectorSize = 512;

                if((ataId.PhysLogSectorSize & 0x2000) == 0x2000)
                    physicalSectorSize = logicalSectorSize * (uint)Math.Pow(2, ataId.PhysLogSectorSize & 0xF);
                else
                    physicalSectorSize = logicalSectorSize;
            }
            else
            {
                logicalSectorSize  = 512;
                physicalSectorSize = 512;
            }

            capabilities.BlockSize = logicalSectorSize;

            if(physicalSectorSize != logicalSectorSize)
            {
                capabilities.PhysicalBlockSize = physicalSectorSize;

                if((ataId.LogicalAlignment & 0x8000) == 0x0000 &&
                   (ataId.LogicalAlignment & 0x4000) == 0x4000)
                    capabilities.LogicalAlignment = (ushort)(ataId.LogicalAlignment & 0x3FFF);
            }

            if(ataId.EccBytes != 0x0000 &&
               ataId.EccBytes != 0xFFFF)
                capabilities.LongBlockSize = logicalSectorSize + ataId.EccBytes;

            if(ataId.UnformattedBPS > logicalSectorSize &&
               (!(ataId.EccBytes != 0x0000 && ataId.EccBytes != 0xFFFF) || capabilities.LongBlockSize == 516))
                capabilities.LongBlockSize = ataId.UnformattedBPS;

            if(ataId.CommandSet3.HasFlag(Identify.CommandSetBit3.MustBeSet)    &&
               !ataId.CommandSet3.HasFlag(Identify.CommandSetBit3.MustBeClear) &&
               ataId.EnabledCommandSet3.HasFlag(Identify.CommandSetBit3.MediaSerial))
            {
                capabilities.CanReadMediaSerial = true;

                if(!string.IsNullOrWhiteSpace(ataId.MediaManufacturer))
                    capabilities.Manufacturer = ataId.MediaManufacturer;
            }

            ulong checkCorrectRead = 0;

            AaruConsole.WriteLine("Trying READ SECTOR(S) in CHS mode...");

            bool sense = _dev.Read(out byte[] readBuf, out AtaErrorRegistersChs errorChs, false, 0, 0, 1, 1,
                                   _dev.Timeout, out _);

            capabilities.SupportsReadSectors = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                               readBuf.Length                     > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorChs.Status, errorChs.Error, readBuf.Length);

            capabilities.ReadSectorsData = readBuf;

            AaruConsole.WriteLine("Trying READ SECTOR(S) RETRY in CHS mode...");
            sense = _dev.Read(out readBuf, out errorChs, true, 0, 0, 1, 1, _dev.Timeout, out _);

            capabilities.SupportsReadRetry =
                !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 && readBuf.Length > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorChs.Status, errorChs.Error, readBuf.Length);

            capabilities.ReadSectorsRetryData = readBuf;

            AaruConsole.WriteLine("Trying READ DMA in CHS mode...");
            sense = _dev.ReadDma(out readBuf, out errorChs, false, 0, 0, 1, 1, _dev.Timeout, out _);

            capabilities.SupportsReadDma =
                !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 && readBuf.Length > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorChs.Status, errorChs.Error, readBuf.Length);

            capabilities.ReadDmaData = readBuf;

            AaruConsole.WriteLine("Trying READ DMA RETRY in CHS mode...");
            sense = _dev.ReadDma(out readBuf, out errorChs, true, 0, 0, 1, 1, _dev.Timeout, out _);

            capabilities.SupportsReadDmaRetry = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                                readBuf.Length                     > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorChs.Status, errorChs.Error, readBuf.Length);

            capabilities.ReadDmaRetryData = readBuf;

            AaruConsole.WriteLine("Trying SEEK in CHS mode...");
            sense                     = _dev.Seek(out errorChs, 0, 0, 1, _dev.Timeout, out _);
            capabilities.SupportsSeek = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}", sense,
                                       errorChs.Status, errorChs.Error);

            AaruConsole.WriteLine("Trying READ SECTOR(S) in LBA mode...");
            sense = _dev.Read(out readBuf, out AtaErrorRegistersLba28 errorLba, false, 0, 1, _dev.Timeout, out _);

            capabilities.SupportsReadLba =
                !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 && readBuf.Length > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorLba.Status, errorLba.Error, readBuf.Length);

            capabilities.ReadLbaData = readBuf;

            AaruConsole.WriteLine("Trying READ SECTOR(S) RETRY in LBA mode...");
            sense = _dev.Read(out readBuf, out errorLba, true, 0, 1, _dev.Timeout, out _);

            capabilities.SupportsReadRetryLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                                readBuf.Length                     > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorLba.Status, errorLba.Error, readBuf.Length);

            capabilities.ReadRetryLbaData = readBuf;

            AaruConsole.WriteLine("Trying READ DMA in LBA mode...");
            sense = _dev.ReadDma(out readBuf, out errorLba, false, 0, 1, _dev.Timeout, out _);

            capabilities.SupportsReadDmaLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                              readBuf.Length                     > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorLba.Status, errorLba.Error, readBuf.Length);

            capabilities.ReadDmaLbaData = readBuf;

            AaruConsole.WriteLine("Trying READ DMA RETRY in LBA mode...");
            sense = _dev.ReadDma(out readBuf, out errorLba, true, 0, 1, _dev.Timeout, out _);

            capabilities.SupportsReadDmaRetryLba =
                !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 && readBuf.Length > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorLba.Status, errorLba.Error, readBuf.Length);

            capabilities.ReadDmaRetryLbaData = readBuf;

            AaruConsole.WriteLine("Trying SEEK in LBA mode...");
            sense                        = _dev.Seek(out errorLba, 0, _dev.Timeout, out _);
            capabilities.SupportsSeekLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}", sense,
                                       errorLba.Status, errorLba.Error);

            AaruConsole.WriteLine("Trying READ SECTOR(S) in LBA48 mode...");
            sense = _dev.Read(out readBuf, out AtaErrorRegistersLba48 errorLba48, 0, 1, _dev.Timeout, out _);

            capabilities.SupportsReadLba48 = !sense && (errorLba48.Status & 0x01) != 0x01 && errorLba48.Error == 0 &&
                                             readBuf.Length                       > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorLba48.Status, errorLba48.Error, readBuf.Length);

            capabilities.ReadLba48Data = readBuf;

            AaruConsole.WriteLine("Trying READ DMA in LBA48 mode...");
            sense = _dev.ReadDma(out readBuf, out errorLba48, 0, 1, _dev.Timeout, out _);

            capabilities.SupportsReadDmaLba48 = !sense && (errorLba48.Status & 0x01) != 0x01 && errorLba48.Error == 0 &&
                                                readBuf.Length                       > 0;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorLba48.Status, errorLba48.Error, readBuf.Length);

            capabilities.ReadDmaLba48Data = readBuf;

            // Send SET FEATURES before sending READ LONG commands, retrieve IDENTIFY again and
            // check if ECC size changed. Sector is set to 1 because without it most drives just return
            // CORRECTABLE ERROR for this command.
            _dev.SetFeatures(out _, AtaFeatures.EnableReadLongVendorLength, 0, 0, 1, 0, _dev.Timeout, out _);

            _dev.AtaIdentify(out byte[] buffer, out _, _dev.Timeout, out _);

            if(Identify.Decode(buffer).HasValue)
            {
                ataId = Identify.Decode(buffer).Value;

                if(ataId.EccBytes != 0x0000 &&
                   ataId.EccBytes != 0xFFFF)
                    capabilities.LongBlockSize = logicalSectorSize + ataId.EccBytes;

                if(ataId.UnformattedBPS > logicalSectorSize &&
                   (!(ataId.EccBytes != 0x0000 && ataId.EccBytes != 0xFFFF) || capabilities.LongBlockSize == 516))
                    capabilities.LongBlockSize = ataId.UnformattedBPS;
            }

            AaruConsole.WriteLine("Trying READ LONG in CHS mode...");

            sense = _dev.ReadLong(out readBuf, out errorChs, false, 0, 0, 1, capabilities.LongBlockSize ?? 0,
                                  _dev.Timeout, out _);

            capabilities.SupportsReadLong = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                            readBuf.Length > 0 && BitConverter.ToUInt64(readBuf, 0) != checkCorrectRead;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorChs.Status, errorChs.Error, readBuf.Length);

            capabilities.ReadLongData = readBuf;

            AaruConsole.WriteLine("Trying READ LONG RETRY in CHS mode...");

            sense = _dev.ReadLong(out readBuf, out errorChs, true, 0, 0, 1, capabilities.LongBlockSize ?? 0,
                                  _dev.Timeout, out _);

            capabilities.SupportsReadLongRetry = !sense && (errorChs.Status & 0x01) != 0x01 && errorChs.Error == 0 &&
                                                 readBuf.Length > 0 && BitConverter.ToUInt64(readBuf, 0) !=
                                                 checkCorrectRead;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorChs.Status, errorChs.Error, readBuf.Length);

            capabilities.ReadLongRetryData = readBuf;

            AaruConsole.WriteLine("Trying READ LONG in LBA mode...");

            sense = _dev.ReadLong(out readBuf, out errorLba, false, 0, capabilities.LongBlockSize ?? 0, _dev.Timeout,
                                  out _);

            capabilities.SupportsReadLongLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                               readBuf.Length                     > 0     &&
                                               BitConverter.ToUInt64(readBuf, 0)  != checkCorrectRead;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorLba.Status, errorLba.Error, readBuf.Length);

            capabilities.ReadLongLbaData = readBuf;

            AaruConsole.WriteLine("Trying READ LONG RETRY in LBA mode...");

            sense = _dev.ReadLong(out readBuf, out errorLba, true, 0, capabilities.LongBlockSize ?? 0, _dev.Timeout,
                                  out _);

            capabilities.SupportsReadLongRetryLba = !sense && (errorLba.Status & 0x01) != 0x01 && errorLba.Error == 0 &&
                                                    readBuf.Length > 0 && BitConverter.ToUInt64(readBuf, 0) !=
                                                    checkCorrectRead;

            AaruConsole.DebugWriteLine("ATA Report", "Sense = {0}, Status = 0x{1:X2}, Error = 0x{2:X2}, Length = {3}",
                                       sense, errorLba.Status, errorLba.Error, readBuf.Length);

            capabilities.ReadLongRetryLbaData = readBuf;

            return capabilities;
        }

        public static byte[] ClearIdentify(byte[] buffer)
        {
            byte[] empty = new byte[512];

            Array.Copy(empty, 0, buffer, 20, 20);
            Array.Copy(empty, 0, buffer, 216, 8);
            Array.Copy(empty, 0, buffer, 224, 8);
            Array.Copy(empty, 0, buffer, 352, 40);

            return buffer;
        }
    }
}

{'repo_name': 'aaru-dps/Aaru', 'stars': '160', 'repo_language': 'C#', 'file_name': 'Command.cs', 'mime_type': 'text/plain', 'hash': -5516406847032189798, 'source_dataset': 'data'}


EMBEDDED_CONTENT_CONTAINS_SWIFT = YES
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
OTHER_CFLAGS = $(inherited) -iquote "$CONFIGURATION_BUILD_DIR/SnapSliderFilters.framework/Headers"
OTHER_LDFLAGS = $(inherited) -framework "SnapSliderFilters"
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
PODS_FRAMEWORK_BUILD_PATH = $(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Pods-SnapSliderFilters_Tests
PODS_ROOT = ${SRCROOT}/Pods

{'repo_name': 'pauljeannot/SnapSliderFilters', 'stars': '247', 'repo_language': 'Swift', 'file_name': 'SNSlider.swift', 'mime_type': 'text/plain', 'hash': 5490276143502618203, 'source_dataset': 'data'}


/**
 * @fileoverview `webpack-config/modules-false-babel` warns against not having set the propety `modules` to `false` in presets in babel configuration file.
 */
import { HintContext, IHint } from 'hint';
import { debug as d } from '@hint/utils-debug';
import { Severity } from '@hint/utils-types';

import { WebpackConfigEvents, WebpackConfigParse } from '@hint/parser-webpack-config';
import { BabelConfigEvents, BabelConfigParsed } from '@hint/parser-babel-config';

import meta from './meta/modules-false-babel';
import { getMessage } from './i18n.import';

const debug: debug.IDebugger = d(__filename);

/*
 * ------------------------------------------------------------------------------
 * Public
 * ------------------------------------------------------------------------------
 */

export default class WebpackConfigModulesFalseBabel implements IHint {
    public static readonly meta = meta;

    public constructor(context: HintContext<WebpackConfigEvents & BabelConfigEvents>) {

        let webpackEvent: WebpackConfigParse;
        let babelEvent: BabelConfigParsed;

        const webpackConfigReceived = (webpackConfigEvent: WebpackConfigParse) => {
            debug(`'parse::end::webpack-config' received`);

            webpackEvent = webpackConfigEvent;
        };

        const babelConfigReceived = (babelConfigEvent: BabelConfigParsed) => {
            debug(`'parse::end::babel-config' received`);

            babelEvent = babelConfigEvent;
        };

        const validate = () => {
            if (!webpackEvent) {
                debug(`no 'parse::end::webpack-config' received`);

                return;
            }

            if (!babelEvent) {
                debug(`no 'parse::end::babel-config' received`);

                return;
            }

            const version = parseInt(webpackEvent.version);
            const presets = babelEvent.config.presets;

            if (version < 2 || !presets || presets.length === 0) {
                return;
            }

            const modulesFalse = (presets as any[][]).filter((preset) => {
                return preset.length > 1 && preset[1].modules === false;
            });

            if (modulesFalse.length === 0) {
                context.report(
                    babelEvent.resource,
                    getMessage('babelModules', context.language),
                    { severity: Severity.error }
                );
            }
        };

        context.on('parse::end::webpack-config', webpackConfigReceived);
        context.on('parse::end::babel-config', babelConfigReceived);
        context.on('scan::end', validate);
    }
}

{'repo_name': 'webhintio/hint', 'stars': '2929', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -2922109039484915485, 'source_dataset': 'data'}