text:
@ECHO OFF
@ECHO.

REM  Set up environment variables.  You will probably have to change these.

@SET Compare=FC
@SET CRUNCH=Call Crunch

@SET ADAMS=Call ADAMS08
REM @SET ADAMS=Call ADAMS05
@SET DateTime=DateTime.exe
@SET Editor=NotePad.EXE

REM  FAST test sequence definition:

@SET  TEST01=Test #01: AWT-27CR2 with many DOFs with fixed yaw error and steady wind.  AA plots.
@SET  TEST02=Test #02: AWT-27CR2 with many DOFs with startup and shutdown and steady wind.  Time plots.
@SET  TEST03=Test #03: AWT-27CR2 with many DOFs with free yaw and steady wind.  AA plots.
@SET  TEST04=Test #04: AWT-27CR2 with many DOFs with free yaw and FF turbulence.  PMF plots.
@SET  TEST05=Test #05: AWT-27CR2 with many DOFs with startup and shutdown and FF turbulence.  Time plots.
@SET  TEST06=Test #06: AOC 15/50 with many DOFs with gen start loss of grid and tip-brake shutdown.  Time plots.
@SET  TEST07=Test #07: AOC 15/50 with many DOFs with free yaw and FF turbulence.  PMF plots.
@SET  TEST08=Test #08: AOC 15/50 with many DOFs with fixed yaw error and steady wind.  AA plots.
@SET  TEST09=Test #09: UAE Phase VI (downwind) with many DOFs with yaw ramp and a steady wind.  Time plots.
@SET  TEST10=Test #10: UAE Phase VI (upwind) with no DOFs in a ramped wind.  Time plots.
@SET  TEST11=Test #11: WindPACT 1.5 MW Baseline with many DOFs undergoing a pitch failure.  Time plots.
@SET  TEST12=Test #12: WindPACT 1.5 MW Baseline with many DOFs with VS and VP and ECD wind.  Time plots.
@SET  TEST13=Test #13: WindPACT 1.5 MW Baseline with many DOFs with VS and VP and FF turbulence.  PMF plots.
@SET  TEST14=Test #14: WindPACT 1.5 MW Baseline with many DOFs and system linearization.  Column chart.
@SET  TEST15=Test #15: SWRT with many DOFs with free yaw tail-furl and VS and EOG wind.  Time plots.
@SET  TEST16=Test #16: SWRT with many DOFs with free yaw tail-furl and VS and EDC wind.  Time plots.
@SET  TEST17=Test #17: SWRT with many DOFs with free yaw tail-furl and VS and FF turbulence.  PMF plots.

@SET  DASHES=---------------------------------------------------------------------------------------------
@SET  POUNDS=#############################################################################################

@IF EXIST ADAMSCertTest.out  DEL ADAMSCertTest.out

ECHO.                                               >> ADAMSCertTest.out
ECHO           ************************************* >> ADAMSCertTest.out
ECHO           **  ADAMS Acceptance Test Results  ** >> ADAMSCertTest.out
ECHO           ************************************* >> ADAMSCertTest.out

ECHO.                                                                             >> ADAMSCertTest.out
ECHO ############################################################################ >> ADAMSCertTest.out
ECHO # Inspect this file for any differences between your results and the saved # >> ADAMSCertTest.out
ECHO # results.  Any differing lines and the two lines surrounding them will be # >> ADAMSCertTest.out
ECHO # listed.  The only differences should be the time stamps at the start of  # >> ADAMSCertTest.out
ECHO # each file.                                                               # >> ADAMSCertTest.out
ECHO #                                                                          # >> ADAMSCertTest.out
ECHO # If you are running on something other than a PC, you may see differences # >> ADAMSCertTest.out
ECHO # in the last significant digit of many of the numbers.                    # >> ADAMSCertTest.out
ECHO ############################################################################ >> ADAMSCertTest.out

ECHO.                                            >> ADAMSCertTest.out
ECHO Date and time this acceptance test was run: >> ADAMSCertTest.out
%DateTime%                                       >> ADAMSCertTest.out
ECHO.                                            >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST01%

@SET TEST=01

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST01%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.azi TstFiles\Test%TEST%_ADAMS.azi >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST02%

@SET TEST=02

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST02%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST03%

@SET TEST=03

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST03%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.azi TstFiles\Test%TEST%_ADAMS.azi >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST04%

@SET TEST=04

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST04%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.pmf TstFiles\Test%TEST%_ADAMS.pmf >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST05%

@SET TEST=05

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST05%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST06%

@SET TEST=06

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST06%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST07%

@SET TEST=07

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST07%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.pmf TstFiles\Test%TEST%_ADAMS.pmf >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST08%

@SET TEST=08

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST08%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.azi TstFiles\Test%TEST%_ADAMS.azi >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST09%

@SET TEST=09

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST09%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST10%

@SET TEST=10

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST10%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST11%

@SET TEST=11

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST11%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST12%

@SET TEST=12

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST12%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST13%

@SET TEST=13

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST13%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.pmf TstFiles\Test%TEST%_ADAMS.pmf >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST14%

@SET TEST=14

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS_LIN

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS_LIN.out  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST14%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS_LIN.out TstFiles\Test%TEST%_ADAMS_LIN.out >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST15%

@SET TEST=15

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST15%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST16%

@SET TEST=16

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST16%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem *******************************************************

@echo ADAMS %TEST17%

@SET TEST=17

rem Run ADAMS.

%ADAMS% Test%TEST%_ADAMS

REM:JASON--ADAMS2003 and ADAMS2005 have a bug in that it always returns an OS return code of 1; this will be fixed in a future release of ADAMS:IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.plt  GOTO ERROR

rem Crunch the ADAMS output.
%CRUNCH% Test%TEST%_ADAMS.cru

IF ERRORLEVEL 1  GOTO ERROR

@IF NOT EXIST Test%TEST%_ADAMS.sts  GOTO ERROR

echo.                                                        >> ADAMSCertTest.out
echo %POUNDS%                                                >> ADAMSCertTest.out
echo.                                                        >> ADAMSCertTest.out
echo %TEST17%                                                >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.sts TstFiles\Test%TEST%_ADAMS.sts >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.pmf TstFiles\Test%TEST%_ADAMS.pmf >> ADAMSCertTest.out
echo %DASHES%                                                >> ADAMSCertTest.out
%Compare% Test%TEST%_ADAMS.opt TstFiles\Test%TEST%_ADAMS.opt >> ADAMSCertTest.out

rem ******************************************************
rem  Let's look at the comparisons.

%Editor% ADAMSCertTest.out
goto END

:ERROR
@echo ** An error has occurred in Test #%TEST% **
goto END

:END

@SET CRUNCH=
@SET Compare=
@SET DASHES=
@SET DateTime=
@SET Editor=
@SET ADAMS=
@SET POUNDS=
@SET TEST=
@SET TEST01=
@SET TEST02=
@SET TEST03=
@SET TEST04=
@SET TEST05=
@SET TEST06=
@SET TEST07=
@SET TEST08=
@SET TEST09=
@SET TEST10=
@SET TEST11=
@SET TEST12=
@SET TEST13=
@SET TEST14=
@SET TEST15=
@SET TEST16=
@SET TEST17=

type Bell.txt
@echo Processing complete.


text:
package com.uit_252254.mr3chi.kltn;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.raizlabs.android.dbflow.sql.language.Select;
import com.uit_252254.mr3chi.kltn.Utils.AppConstants;
import com.uit_252254.mr3chi.kltn.Utils.FileUtils;
import com.uit_252254.mr3chi.kltn.models.Kid;
import com.uit_252254.mr3chi.kltn.models.Mom;
import com.uit_252254.mr3chi.kltn.models.Notification;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Mr3chi on 7/15/2015.
 */

public class NotificationAdapter extends RecyclerView.Adapter {

    Context   mContext;
    List<Kid> savedList;
    String    momImage;
    List<Notification> mDataSet;
    IEditableNotification mCallback;

    View.OnClickListener mItemListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mCallback != null){
                if(v.getTag() != null){
                    int pos = (int)v.getTag();
                    mCallback.editNotification(mDataSet.get(pos));
                }
            }

        }
    };

    View.OnClickListener mCbClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(v.getTag() != null){
                final int pos = (int)v.getTag();
                CheckBox temp = (CheckBox)v;

                if(!mDataSet.get(pos).isDone()){
                    //show confirm
                    temp.setChecked(false);
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setMessage(mContext.getString(R.string.dialog_done))
                            .setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mDataSet.get(pos).setDone(true);
                                    NotificationDataChangedHandler.updateIsDone(mContext, mDataSet.get(pos));
                                    notifyItemChanged(pos);
                                }
                            })
                            .setNegativeButton(R.string.dialog_exit, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create().show();
                }else{
                    temp.setChecked(true);
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setMessage(mContext.getString(R.string.dialog_not_done))
                            .setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mDataSet.get(pos).setDone(false);
                                    NotificationDataChangedHandler.updateIsDone(mContext, mDataSet.get(pos));
                                    notifyItemChanged(pos);
                                }
                            })
                            .setNegativeButton(R.string.dialog_exit, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create().show();
                }
            }
        }
    };

    public NotificationAdapter(Context mContext) {
        this.mContext   = mContext;
        this.mCallback  = null;
        savedList = new ArrayList<>();
        resetList();
    }

    public void setCallback(IEditableNotification mCallback){
        this.mCallback = mCallback;
    }

    public void resetList(){
        savedList.clear();
        List<Mom> moms = Select.all(Mom.class);
        if(moms.size() > 0){
            if(moms.get(0).getImage() != null){
                momImage = moms.get(0).getImage();
            }else {
                momImage = "";
            }
        }
    }

    public static class ViewHolder_Header extends RecyclerView.ViewHolder{
        TextView mDate;
        public ViewHolder_Header(View itemView) {
            super(itemView);
            mDate = (TextView) itemView.findViewById(R.id.title);
        }
    }

    public static class ViewHolder_Noti extends RecyclerView.ViewHolder{
        LinearLayout    editLayout;
        CircleImageView mImage;
        TextView        mAuthor;
        TextView        mTime;
        TextView        mContent;
        CheckBox        mIsdone;
        LinearLayout    mIsNotified;

        public ViewHolder_Noti(View itemView) {
            super(itemView);
            editLayout  = (LinearLayout) itemView.findViewById(R.id.edit_layout);
            mImage      = (CircleImageView) itemView.findViewById(R.id.image);
            mAuthor     = (TextView) itemView.findViewById(R.id.noti_author);
            mTime       = (TextView) itemView.findViewById(R.id.noti_time);
            mContent    = (TextView) itemView.findViewById(R.id.noti_info);
            mIsdone     = (CheckBox) itemView.findViewById(R.id.is_done);
            mIsNotified = (LinearLayout) itemView.findViewById(R.id.is_notified);
        }
    }

    public void setData(List<Notification> data){
        mDataSet = data;
    }

    @Override
    public int getItemViewType(int position) {
        if(mDataSet.get(position).getId() == -1){
            return 0;
        }else{
            return 1;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View itemView;
        switch (viewType){
            case 0:
                itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.notification_header,viewGroup, false);
                return new ViewHolder_Header(itemView);
            case 1:
                itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.notification_item,viewGroup, false);

                CheckBox isDone = (CheckBox) itemView.findViewById(R.id.is_done);
                isDone.setOnClickListener(mCbClickListener);

                LinearLayout editLayout = (LinearLayout) itemView.findViewById(R.id.edit_layout);
                editLayout.setOnClickListener(mItemListener);

                return new ViewHolder_Noti(itemView);
        }

        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Notification noti = mDataSet.get(position);
        if(holder instanceof ViewHolder_Header){
            ((ViewHolder_Header)holder).mDate.setText(noti.getName());
        }else if (holder instanceof ViewHolder_Noti){
            ((ViewHolder_Noti)holder).editLayout.setTag(position);
            ((ViewHolder_Noti)holder).mAuthor.setText(noti.getName());
            ((ViewHolder_Noti)holder).mContent.setText(noti.getContent());
            ((ViewHolder_Noti)holder).mTime.setText(AppConstants.AppTimeFormat.format(noti.getTime().getTime()));
            ((ViewHolder_Noti)holder).mIsdone.setChecked(noti.isDone());
            ((ViewHolder_Noti)holder).mIsdone.setTag(position);
            if(noti.isNotified()){
                ((ViewHolder_Noti)holder).mIsNotified.setBackgroundResource(R.color.button_material_light);
            }else{
                ((ViewHolder_Noti)holder).mIsNotified.setBackgroundResource(R.color.white);
            }

            if(noti.getKidId() == -1){
                if(momImage == null || momImage.equals("")){
                    Glide.with(mContext).load(R.drawable.icon_mom).into(((ViewHolder_Noti)holder).mImage);
                }else{
                    Glide.with(mContext).load(FileUtils.getImageFile(mContext, momImage)).into(((ViewHolder_Noti)holder).mImage);
                }
            }else{
                //kid detected, look for cache first
                boolean isdone = false;
                for (int i =0; i < savedList.size();i++){
                    if(savedList.get(i).getId() == noti.getKidId()){
                        if(savedList.get(i).getImage() == null || savedList.get(i).getImage().trim().equals("")){
                            Glide.with(mContext).load(R.drawable.icon_kid).into(((ViewHolder_Noti)holder).mImage);
                        }else
                        {
                            Glide.with(mContext).load(FileUtils.getImageFile(mContext, savedList.get(i).getImage())).into(((ViewHolder_Noti)holder).mImage);
                        }
                        isdone = true;
                        break;
                    }
                }

                if(!isdone){
                    Kid kid = Kid.getKidById(noti.getKidId());
                    if(kid != null){
                        savedList.add(kid);
                        if(kid.getImage() == null || kid.getImage().trim().equals("")){
                            Glide.with(mContext).load(R.drawable.icon_kid).into(((ViewHolder_Noti)holder).mImage);
                        }else
                        {
                            Glide.with(mContext).load(FileUtils.getImageFile(mContext, kid.getImage())).into(((ViewHolder_Noti)holder).mImage);
                        }
                    }
                }
            }
        }
    }

    @Override
    public int getItemCount() {

        if(mDataSet == null) return 0;
        return mDataSet.size();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php include '../header.php';?>

Angela Clarkson

                                   Skills

 #hardware #software #PHP #Javascript

Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in liberty, and dedicated to the proposition that "all men are created equal."

Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle field of that war. We come to dedicate a portion of it, as a final resting place for those who died here, that the nation might live. This we may, in all propriety do.

But, in a larger sense, we can not dedicate – we can not consecrate – we can not hallow, this ground – The brave men, living and dead, who struggled here, have hallowed it, far above our poor power to add or detract. The world will little note, nor long remember what we say here; while it can never forget what they did here.

It is rather for us, the living, we here be dedicated to the great task remaining before us – that, from these honored dead we take increased devotion to that cause for which they here, gave the last full measure of devotion – that we here highly resolve these dead shall not have died in vain; that the nation, shall have a new birth of freedom, and that government of the people, by the people, for the people, shall not perish from the earth.

<?php include '../solve_contact.php';?>

    <?php include '../footer.php';?>


text:
<?php

namespace Magento\Backend\Model\ResourceModel;

/**
 * Backend translate resource model
 */
class Translate extends \Magento\Translation\Model\ResourceModel\Translate
{
    /**
     * Get current store id
     * Use always default scope for store id
     *
     * @return int
     */
    protected function _getStoreId()
    {
        return \Magento\Store\Model\Store::DEFAULT_STORE_ID;
    }
}


text: This test passes if it doesn't crash.


text:
namespace parma {
  typedef std::set<apf::MeshEntity*> Level;
  class dcComponents::Components : public dcPart {
    public:
      Components(apf::Mesh* mesh, unsigned verbose=0);
      ~Components();

      unsigned size();
      unsigned iso();

      unsigned getDepth(unsigned i);
      void setDepth(unsigned i, unsigned d);

      Level* getBdry(unsigned i);
      Level* getCore(unsigned i);
      apf::MeshEntity* getCoreVtx(unsigned i);

      bool has(apf::MeshEntity* e);
      unsigned getId(apf::MeshEntity* e);
    private:
      Components();
      void markVertices();
      void walkComp(apf::MeshEntity* src, unsigned comp);
      void setElmVtxIds(apf::Downward& verts, const int nv, unsigned comp);
      void addElmVtxToBdry(apf::Downward& verts, const int nv, unsigned comp);
      void setId(apf::MeshEntity* e, unsigned id);
      void walkInward(unsigned compId);
      void getCoreVerts();
      void getCoreVtx();
      void sortByDepth();
      void reorder(unsigned*);
      apf::Mesh* m;
      unsigned vb;
      apf::MeshTag* idT;
      unsigned n;
      unsigned* depth;
      Level* bdry;
      Level* core;
  };
}

#endif


text:
description(
"instanceof test"
);

shouldBeTrue("(new Audio()) instanceof Audio");
shouldBeFalse("(new Array()) instanceof Audio");

shouldBeTrue("(new Image()) instanceof Image");
shouldBeFalse("(new Array()) instanceof Image");

// MessageChannel is not available yet.
//shouldBeTrue("(new MessageChannel()) instanceof MessageChannel");
//shouldBeFalse("(new Array()) instanceof MessageChannel");

shouldBeTrue("(new Option()) instanceof Option");
shouldBeFalse("(new Array()) instanceof Option");

shouldBeTrue("(new WebKitCSSMatrix()) instanceof WebKitCSSMatrix");
shouldBeFalse("(new Array()) instanceof WebKitCSSMatrix");

shouldBeTrue("(new Worker('instanceof-operator-dummy-worker.js')) instanceof Worker");
shouldBeFalse("(new Array()) instanceof Worker");

shouldBeTrue("(new XSLTProcessor()) instanceof XSLTProcessor");
shouldBeFalse("(new Array()) instanceof XSLTProcessor");


text:
require 'spec_helper'
require 'jellyfish_azure'

module JellyfishAzure
  module Operation
    describe 'AzureProvisionOperation#execute' do
      let(:cloud_client) do
        OpenStruct.new(
          storage: double,
          deployment: double,
          resource_group: double)
      end

      let(:service) { create :service }
      let(:operation) do
        result = JellyfishAzure::Operation::AzureProvisionOperation.new cloud_client, {}, {}, service

        allow(result).to receive(:setup)
        allow(result).to receive(:template_url).and_return('https://test.com/mytemplate.json')
        allow(result).to receive(:location).and_return('westus')
        allow(result).to receive(:template_parameters).and_return({})

        result
      end

      subject(:service_result) do
        operation.execute
        service
      end

      context 'when deployment successful' do
        before do
          allow(cloud_client.resource_group).to receive(:create_resource_group)
          allow(cloud_client.deployment).to receive(:create_deployment)
          allow(cloud_client.deployment).to receive(:get_deployment_status)
            .and_return(['Succeeded', {}])
        end

        context 'status' do
          it { expect(service_result.status).to eq :available }
          it { expect(service_result.status_msg).to eq 'Deployment successful' }
        end

        context 'service outputs' do
          before do
            allow(cloud_client.deployment).to receive(:get_deployment_status)
              .and_return([
                'Succeeded',
                {
                  output1: { value: 'value1' },
                  output2: { value: 'value2' }
                }])
          end

          subject(:service_outputs) do
            operation.execute
            service.service_outputs.outputs
          end

          it { expect(service_outputs.length).to eq 2 }
          it { expect(service_outputs[0]).to include(name: :output1, value: 'value1', value_type: :string) }
          it { expect(service_outputs[1]).to include(name: :output2, value: 'value2', value_type: :string) }
        end

        context 'request received to' do
          after { service_result }

          it 'create resource group' do
            expect(cloud_client.resource_group).to receive(:create_resource_group)
              .with(operation.resource_group_name, operation.location)
          end

          it 'create deployment' do
            expect(cloud_client.deployment).to receive(:create_deployment)
              .with(operation.resource_group_name, any_args, operation.template_url, {})
          end
        end
      end

      context 'when setup fails' do
        before do
          allow(operation).to receive(:setup).and_raise(ValidationError, 'test failure')
        end

        context 'status' do
          it { expect(service_result.status).to eq :terminated }
          it { expect(service_result.status_msg).to eq 'test failure' }
        end
      end

      context 'when resource group creation fails' do
        context 'due to azure error' do
          before do
            allow(cloud_client.resource_group).to receive(:create_resource_group)
              .and_raise(MsRestAzure::AzureOperationError, 'test failure')
          end

          context 'status' do
            it { expect(service_result.status).to eq :terminated }
            it { expect(service_result.status_msg).to eq 'test failure' }
          end
        end

        context 'due to unknown error, status' do
          before do
            allow(cloud_client.resource_group).to receive(:create_resource_group)
              .and_raise(StandardError, 'test failure')
          end

          context 'status' do
            it { expect(service_result.status).to eq :terminated }
            it { expect(service_result.status_msg).to eq 'Unexpected error: StandardError: test failure' }
          end
        end
      end

      context 'when deployment creation fails' do
        before do
          allow(cloud_client.resource_group).to receive(:create_resource_group)
        end

        context 'due to azure error' do
          before do
            allow(cloud_client.deployment).to receive(:create_deployment)
              .and_raise(MsRestAzure::AzureOperationError, 'test failure')
          end

          context 'status' do
            it { expect(service_result.status).to eq :terminated }
            it { expect(service_result.status_msg).to eq 'test failure' }
          end
        end

        context 'due to unknown error, status' do
          before do
            allow(cloud_client.deployment).to receive(:create_deployment)
              .and_raise(StandardError, 'test failure')
          end

          context 'status' do
            it { expect(service_result.status).to eq :terminated }
            it { expect(service_result.status_msg).to eq 'Unexpected error: StandardError: test failure' }
          end
        end
      end

      context 'when deployment status check fails' do
        before do
          allow(cloud_client.resource_group).to receive(:create_resource_group)
          allow(cloud_client.deployment).to receive(:create_deployment)
        end

        context 'due to deployment error' do
          before do
            allow(cloud_client.deployment).to receive(:get_deployment_status)
              .and_return(['Failed', {}])

            allow(cloud_client.deployment).to receive(:get_deployment_errors)
              .and_return([
                JellyfishAzure::AzureDeploymentError.new('Deployment failure 1'),
                JellyfishAzure::AzureDeploymentError.new('Deployment failure 2')
              ])
          end

          context 'status' do
            it { expect(service_result.status).to eq :terminated }
            it { expect(service_result.status_msg).to eq "Deployment failure 1\nDeployment failure 2" }
          end
        end

        context 'due to azure error' do
          before do
            allow(cloud_client.deployment).to receive(:get_deployment_status)
              .and_raise(MsRestAzure::AzureOperationError, 'test failure')
          end

          context 'status' do
            it { expect(service_result.status).to eq :terminated }
            it { expect(service_result.status_msg).to eq 'test failure' }
          end
        end

        context 'due to unknown error, status' do
          before do
            allow(cloud_client.deployment).to receive(:get_deployment_status)
              .and_raise(StandardError, 'test failure')
          end

          context 'status' do
            it { expect(service_result.status).to eq :terminated }
            it { expect(service_result.status_msg).to eq 'Unexpected error: StandardError: test failure' }
          end
        end
      end

      context 'when deployment times out' do
        before do
          operation.deploy_timeout = 0.2
          operation.deploy_delay = 0.1

          allow(cloud_client.resource_group).to receive(:create_resource_group)
          allow(cloud_client.deployment).to receive(:create_deployment)
          allow(cloud_client.deployment).to receive(:get_deployment_status)
            .and_return(['Running', {}])
        end

        context 'status' do
          it { expect(service_result.status).to eq :terminated }
          it { expect(service_result.status_msg).to eq 'The provisioning operation timed out.' }
        end
      end
    end
  end
end


text:
using Foundation;
using System.CodeDom.Compiler;

namespace Insights.iOS
{
	[Register ("AppsCollectionViewController")]
	partial class AppsCollectionViewController
	{

		void ReleaseDesignerOutlets ()
		{
		}
	}
}


text:
package com.krishagni.catissueplus.core.auth.events;

import com.krishagni.catissueplus.core.common.events.AbstractListCriteria;

public class ListAuthDomainCriteria extends AbstractListCriteria<ListAuthDomainCriteria> {

	@Override
	public ListAuthDomainCriteria self() {
		return this;
	}

}


text:
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ViewPatterns #-}

module Physics.Bullet.SpringConstraint where

import qualified Language.C.Inline.Cpp as C

import Foreign.C
import Linear.Extra
import Control.Monad.Trans
import Data.Monoid
import Physics.Bullet.Types

-----------------
-- Springs
-- See http://bulletphysics.org/Bullet/BulletFull/classbtGeneric6DofSpring2Constraint.html
-----------------

C.context (C.cppCtx <> C.funCtx)

C.include "<btBulletDynamicsCommon.h>"

-- | Adds a constraint between the body and (I think) its current position in the world
addWorldSpringConstraint :: MonadIO m => DynamicsWorld -> RigidBody -> m SpringConstraint
addWorldSpringConstraint (DynamicsWorld dynamicsWorld) (toCollisionObjectPointer->rigidBody) = SpringConstraint <$> liftIO [C.block| void *{
  btDiscreteDynamicsWorld *dynamicsWorld = (btDiscreteDynamicsWorld *) $(void *dynamicsWorld);

  btRigidBody *rigidBody = (btRigidBody *) $(void *rigidBody);

  btQuaternion q     = btQuaternion(btVector3(0,1,0), 0);
  btVector3    p     = btVector3(0,0,0);
  btTransform  frame = btTransform(q, p);

  btGeneric6DofSpring2Constraint *spring = new btGeneric6DofSpring2Constraint(*rigidBody, frame, RO_XYZ);

  dynamicsWorld->addConstraint(spring);

  return spring;

  }|]

addSpringConstraint :: MonadIO m => DynamicsWorld -> RigidBody -> RigidBody -> m SpringConstraint
addSpringConstraint (DynamicsWorld dynamicsWorld) (toCollisionObjectPointer->rigidBodyA) (toCollisionObjectPointer->rigidBodyB) = SpringConstraint <$> liftIO [C.block| void  *{
  btDiscreteDynamicsWorld *dynamicsWorld = (btDiscreteDynamicsWorld *) $(void *dynamicsWorld);
  btRigidBody *rigidBodyA = (btRigidBody *) $(void *rigidBodyA);
  btRigidBody *rigidBodyB = (btRigidBody *) $(void *rigidBodyB);

  btQuaternion q     = btQuaternion(btVector3(0,1,0), 0);
  btVector3    p     = btVector3(0,0,0);
  btTransform  frame = btTransform(q, p);

  RotateOrder rotOrder = RO_XYZ;
  btGeneric6DofSpring2Constraint *spring = new btGeneric6DofSpring2Constraint(
      *rigidBodyA, *rigidBodyB,
      frame, frame,
      RO_XYZ
     );

  dynamicsWorld->addConstraint(spring);

  return spring;
  }|]

removeSpringConstraint :: MonadIO m => DynamicsWorld -> SpringConstraint -> m ()
removeSpringConstraint (DynamicsWorld dynamicsWorld) (SpringConstraint springConstraint) = liftIO [C.block| void {
  btDiscreteDynamicsWorld *dynamicsWorld = (btDiscreteDynamicsWorld *) $(void *dynamicsWorld);
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);
  dynamicsWorld->removeConstraint(spring);
  delete spring;
  }|]

setSpringWorldPose :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> Quaternion a -> m ()
setSpringWorldPose (SpringConstraint springConstraint) position rotation = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  btQuaternion q = btQuaternion($(float qx), $(float qy), $(float qz), $(float qw));
  btVector3    p = btVector3($(float x), $(float y), $(float z));
  btTransform  frame = btTransform(q, p);

  spring->setFrames(frame, spring->getFrameOffsetB());

  }|]
  where
    (V3 x y z)                    = realToFrac <$> position
    (Quaternion qw (V3 qx qy qz)) = realToFrac <$> rotation

setSpringLinearLowerLimit :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringLinearLowerLimit (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setLinearLowerLimit(btVector3($(float x), $(float y), $(float z)));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringLinearUpperLimit :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringLinearUpperLimit (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setLinearUpperLimit(btVector3($(float x), $(float y), $(float z)));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringAngularLowerLimit :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringAngularLowerLimit (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setAngularLowerLimit(btVector3($(float x), $(float y), $(float z)));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringAngularUpperLimit :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringAngularUpperLimit (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setAngularUpperLimit(btVector3($(float x), $(float y), $(float z)));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringLinearBounce :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringLinearBounce (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setBounce(0, $(float x));
  spring->setBounce(1, $(float y));
  spring->setBounce(2, $(float z));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringAngularBounce :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringAngularBounce (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setBounce(3, $(float x));
  spring->setBounce(4, $(float y));
  spring->setBounce(5, $(float z));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringLinearStiffness :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringLinearStiffness (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setStiffness(0, $(float x));
  spring->setStiffness(1, $(float y));
  spring->setStiffness(2, $(float z));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringAngularStiffness :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringAngularStiffness (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setStiffness(3, $(float x));
  spring->setStiffness(4, $(float y));
  spring->setStiffness(5, $(float z));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringLinearDamping :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringLinearDamping (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setDamping(0, $(float x));
  spring->setDamping(1, $(float y));
  spring->setDamping(2, $(float z));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringAngularDamping :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringAngularDamping (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setDamping(3, $(float x));
  spring->setDamping(4, $(float y));
  spring->setDamping(5, $(float z));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringLinearEquilibrium :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringLinearEquilibrium (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setEquilibriumPoint(0, $(float x));
  spring->setEquilibriumPoint(1, $(float y));
  spring->setEquilibriumPoint(2, $(float z));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setSpringAngularEquilibrium :: (Real a, MonadIO m) => SpringConstraint -> V3 a -> m ()
setSpringAngularEquilibrium (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->setEquilibriumPoint(3, $(float x));
  spring->setEquilibriumPoint(4, $(float y));
  spring->setEquilibriumPoint(5, $(float z));

  }|]
  where (V3 x y z) = realToFrac <$> xyz

setLinearSpringEnabled :: MonadIO m => SpringConstraint -> V3 Bool -> m ()
setLinearSpringEnabled (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->enableSpring(0, $(int x'));
  spring->enableSpring(1, $(int y'));
  spring->enableSpring(2, $(int z'));

  }|]
  where V3 x' y' z' = fromIntegral . fromEnum <$> xyz

setAngularSpringEnabled :: MonadIO m => SpringConstraint -> V3 Bool -> m ()
setAngularSpringEnabled (SpringConstraint springConstraint) xyz = liftIO [C.block| void {
  btGeneric6DofSpring2Constraint *spring = (btGeneric6DofSpring2Constraint *) $(void *springConstraint);

  spring->enableSpring(3, $(int x'));
  spring->enableSpring(4, $(int y'));
  spring->enableSpring(5, $(int z'));

  }|]
  where V3 x' y' z' = fromIntegral . fromEnum <$> xyz


text:
**Targeted for v1.7**

## Goal
Custom Resources in Rook-Ceph can act as data/storage "providers" for other Resources in the
Kubernetes cluster which may be "dependent" on the data/storage provided to them. This dependency
relationship is not codified in Rook, and it is possible for Custom Resources which have dependents
to be deleted, removing the underlying data that dependents need. This leaves those resources
orphaned and could destroy valuable end-user data.

An example of this is a user needing NFS storage from Rook-Ceph. The user needs to create a
CephCluster. They also need a CephFilesystem. Finally, they need a CephNFS which references the
CephFilesystem. In this example, the CephNFS is dependent on the data pool created by the
CephFilesystem which is in turn dependent on the underlying CephCluster.

It should not be possible for an administrator to delete the CephFilesystem until the CephNFS
resource is deleted because a user may be using the CephNFS resource. Similarly, it should not be
possible for an administrator to delete the CephCluster while the CephFilesystem exists because the
filesystem could be in use. It is up to the administrator to ensure users no longer need storage
before they delete resources like CephNFS or CephFilesystem.

The goal of this design is to add safety measures into Rook to help prevent accidental destruction
of end-user data. This design proposes to enable this by tracking resource dependency relationships
and block deletion of any given Rook-Ceph Custom Resource when it is referenced by another resource
in the Kubernetes cluster.

### Summary of changes

1. Block deletion of a CephCluster when there are other Rook-Ceph resources in the same namespace
1. Block deletion of a CephBlockPool, CephFilesystem, CephObjectStore, or CephObjectZone when a
   CephNFS or CephClient uses one of its pools.
1. Block deletion of a CephObjectStore when there is a user bucket present in the store.
   - This allows Rook to block deletion when lib-bucket-provisioner or COSI Bucket resources exist
     without having to probe an external API.
   - This already has an implementation, but it blocks for unrelated lib-bucket-provisioner OBs.
1. Block deletion of a CephBlockPool or CephFilesystem when there is a PersistentVolume reliant on it.
1. Block deletion of a CephObjectStore when there is a CephObjectStoreUser reliant on it.
1. Block deletion of a CephRBDMirror if a CephBlockPool has mirroring enabled.
1. Block deletion of a CephFilesystemMirror if a CephFilesystem has mirroring enabled.
1. Block deletion of object "multisite" resources with their hierarchy:
   CephObjectRealm -> CephObjectZoneGroup -> CephObjectZone -> CephObjectStore

## Inventory of resources that could have dependency relationships
All Rook-Ceph CRDs:
- CephCluster
- CephBlockPool
- CephFilesystem
- CephObjectStore
- CephObjectStoreUser
- CephNFS
- CephClient
- CephRBDMirror
- CephFilesystemMirror
- CephObjectRealm
- CephObjectZoneGroup
- CephObjectZone

Resources for which Rook-Ceph acts as a driver/provisioner:
- ObjectBucket (lib-bucket-provisioner)
- Bucket (COSI)

Kubernetes resources which can depend on Rook:
- StorageClass (Kubernetes)
- PersistentVolume (Kubernetes)

## Proposed dependency relationships
A graph of proposed dependency relationships is shown below with more detail to follow.
![Graph view of resource dependencies](resource-dependencies.png)

#### `CephCluster`
A CephCluster does not create pools itself, but the Ceph cluster it represents houses pools, and
users can manually create pools using Ceph tooling outside of Kubernetes manifests. It is useful but
not critical to understand which resources interact with pools and in what ways.

Dependents which can create/delete pools:
- CephBlockPools in the same namespace
- CephFilesystems in the same namespace
- CephObjectStores in the same namespace
- CephObjectZones in the same namespace

Dependents which can consume arbitrary pools including user-created pools:
- CephNFSes in the same namespace
- CephClients in the same namespace

Dependents that do not interact with pools:
- CephRBDMirrors in the same namespace
- CephFilesystemMirrors in the same namespace
- CephObjectRealms in the same namespace
- CephObjectZoneGroups in the same namespace

It is most safe if the `CephCluster` treats all possible Rook-Ceph CRs besides itself as simple
dependents. If a dependent exists in the same namespace, block deletion. In this way, CephCluster
is the most protected provider resource. It also acts as a root for preserving deletion ordering.

#### `CephBlockPool`
Dependents which can consume this provider's pools:
- CephNFSes in the same namespace that have `spec.pool == <a provider pool>`
- CephClients in the same namespace that have any `spec.caps` value with the string `pool=<a provider pool>`

Dependents via CSI:
- StorageClasses that have:
  - `provisioner == <operator namespace>.rbd.csi.ceph.com` AND
  - `parameters.clusterID == <ceph cluster namespace>` AND
  - `parameters.pool` OR `parameters.dataPool` references a `CephBlockPool` pool
- PersistentVolumes that have:
  - `spec.CSI.Driver` == `<operator namespace>.rbd.csi.ceph.com` AND
  - `spec.CSI.VolumeAttributes["clusterID"] == <ceph cluster namespace>` AND
  - `spec.CSI.VolumeAttributes["pool"]` OR `spec.CSI.VolumeAttributes["journalPool"]` references a `CephBlockPool` pool
  - OR
  - `spec.storageClassName == <name of StorageClass which references the CephBlockPool>`
  - NOTE: dependents should continue to be ignored if `spec.cleanupPolicy.allowUninstallWithVolumes == true`

#### `CephFilesystem`
Dependents which can consume this provider's pools:
- CephNFSes in the same namespace that have `spec.pool == <a provider pool>`
- CephClients in the same namespace that have any `spec.caps` value with the string `pool=<a provider pool>`

Dependents via CSI:
- StorageClasses that have:
  - `provisioner == <operator namespace>.cephfs.csi.ceph.com` AND
  - `parameters.clusterID == <ceph cluster namespace>` AND
  - `parameters.pool` OR `parameters.dataPool` references a `CephBlockPool` pool
- PersistentVolumes that have:
  - `spec.CSI.Driver` == `<operator namespace>.cephfs.csi.ceph.com` AND
  - `spec.CSI.VolumeAttributes["clusterID"] == <ceph cluster namespace>` AND
  - `spec.CSI.VolumeAttributes["pool"]` OR `spec.CSI.VolumeAttributes["journalPool"]` references a `CephBlockPool` pool
  - OR
  - `spec.storageClassName == <name of StorageClass which references the CephBlockPool>`
  - NOTE: dependents should continue to be ignored if `spec.cleanupPolicy.allowUninstallWithVolumes == true`

#### `CephObjectStore`
Dependents which can consume this provider's pools:
- CephNFSes in the same namespace that have `spec.pool == <a provider pool>`
- CephClients in the same namespace that have any `spec.caps` value with the string `pool=<a provider pool>`

Dependents which reference this provider by name:
- CephObjectStoreUsers in the same namespace that have `spec.store == <CephObjectStore.metadata.name>`

Dependents via lib-bucket-provisioner:
- ObjectBucketClaims that have:
  - `spec.endpoint.bucketHost == <provider's service name>.<ceph cluster namespace>.svc` AND
  - `spec.endpoint.bucketName == <a provider bucket>`

Dependents via COSI:
- Buckets with a reference to a provider's service and bucket (specific paths TBD by COSI design)

#### `CephObjectZone`, `CephObjectZoneGroup`, and `CephObjectRealm`
These resources are all part of Rook-Ceph's multi-site object storage strategy.

`CephObjectZone` creates pools. A zone can be effectively thought of as the "object store" itself.
Dependents which can consume this provider's pools:
- CephObjectStores in the same namespace that have `spec.zone.name == CephObjectZone.metadata.name`
- CephNFS in the same namespace that have `spec.pool = <a provider pool>`
- CephClient in the same namespace that has an `spec.caps` value with the string `pool=<a provider pool>`

`CephObjectRealm` has dependents:
- CephObjectZoneGroups in the same namespace that have `spec.realm == CephObjectRealm.metadata.name`

`CephObjectZoneGroup` has dependents:
- CephObjectZones in the same namespace that have `spec.zoneGroup == CephObjectZoneGroup.metadata.name`

#### Mirroring resources
CephRBDMirror has dependents:
- CephBlockPools in the same namespace that have `spec.mirroring.enabled == true`

CephFilesystemMirror has dependents:
- CephFilesystems in the same namespace that have `spec.mirroring.enabled == true`

## Analysis and discussion
### Reusable patterns
We can identify some common metrics for determining whether a resource is a dependent of a given
"provider" resource. Not all metrics are always applicable, but each these metrics appear more than
once. It should be possible to design reusable patterns/methods for reusing logic.
- Is a dependent in the same namespace as the provider?
- Does a dependent reference the current Rook-Ceph operator?
- Does a dependent reference the Ceph cluster namespace of the provider?
- Does the dependent reference pools created by provider?
- Does the dependent reference the provider by name? (e.g., CephObjectZone references CephObjectZoneGroup)

### User feedback
It will be important for the user to understand why resources are not being deleted if Rook is
blocking the deletion. This design proposes that the Rook operator report to the user when it is
blocking deletion of a resource due to dependents in two ways:
- report it in a status condition of the resource object being deleted
- report a Kubernetes Event ([reference](https://kubernetes.io/blog/2018/01/reporting-errors-using-kubernetes-events/))

Using both of these methods will maximize user visibility.

**Status:**
Reported statuses will be modified as follows:
1. Object's status.phase should be changed to "Deleting" as soon as a deletion timestamp is detected
   and never changed
1. A status.condition should be added if the operator is blocking deletion:
   - Type: "DeletionIsBlocked"
   - Status: "True"
   - Reason: "ObjectHasDependents"
   - Message: "object deletion is blocked because it has dependents:" followed by a full list of
     which dependents exist of which Kubernetes Object Kinds (e.g., CephBlockPools or
     PersistentVolumes) or of which Ceph kinds (e.g., pools or buckets).

**Event:**
Reported events will have the following content:
- Type: "Warning"
- Reason: "ReconcileFailed"
- Message: "object deletion is blocked because it has dependents:" followed by a full list of which
  dependents exist of which Kubernetes Object Kinds (e.g., CephBlockPools or PersistentVolumes) or
  of which Ceph kinds (e.g., pools or buckets).

### Detecting PersistentVolume dependents
Rook currently inspects Kubernetes PersistentVolume (PV) resources when deleting CephClusters. This
provides protection from deleting the backing Ceph cluster when user applications are using it.

With the changes proposed here, it would be more specific to block deleting CephBlockPool resources
when there are PVs referencing the specific CephBlockPool. Similarly, it would be more specific to
block deleting CephFilesystem resources when there are PVs referencing the specific CephFilesystem.

Kubernetes APIs are quite stable, and it is unlikely that the methods Rook uses to inspect
PersistentVolumes will require changes with any regularity. If changes are necessary, Kubernetes
will likely give well over a year of time to migrate away from deprecated API elements.

Removing a Ceph cluster that is hosting PVs in use by Kubernetes applications could be disastrous
for users. Therefore, this document proposes to continue checking for PersistentVolumes that depend
on Ceph storage. The document further proposes to increase protection of user data by detecting
dependencies for specific CephBlockPools and CephFilesystems when they are deleted rather than
checking when the CephCluster is deleted. Detecting the existence of PVs when the CephCluster is
deleted then becomes redundant and should be removed.

### Detecting StorageClass dependents
As a note, StorageClasses (SCs) are only used during initial creation of a
PersistentVolume based on the StorageClass.

It may not be a good idea to block deletion when there are StorageClasses that reference Rook-Ceph
block/file storage. An admin may at times wish to leave StorageClasses
(a more user-focused API point) and replace the Rook-Ceph resources providing the storage
represented by the SC without disturbing users' ability to reference the SC. Any user that tried to
use the StorageClass while the cluster was down would merely fail until a replacement cluster came
online.

This document outlines the steps needed to treat StorageClasses as a dependent but proposes not to
implement the dependency at this time. If we get more information in the future that provides a
compelling use-case for treating StorageClasses as dependencies, this functionality can be
implemented at that time.

### Detecting object bucket dependents without querying lib-bucket-provisioner or COSI resources
Detecting lib-bucket-provisioner ObjectBuckets that are dependent on a given CephObjectStore
requires inspecting ObjectBuckets for a reference to a bucket found in the object store as well as a
reference to the address of the Kubernetes Service created for access to RGWs
(`<service name>.<namespace>.svc`). Detecting COSI Buckets will be similar.

This detection does require accessing external APIs (lib-bucket-provisioner and COSI). This is
non-ideal for COSI whose APIs will be progressing from v1alpha1, through beta stages, and then into
v1 in the coming months/years. Rook can merely check for the existence of buckets in order to
support lib-bucket-provisioner and COSI simultaneously with the same code. This would also remove
any need for Rook to update its COSI API for dependency checking though it will still need to
update its API to continue operating as a COSI driver. This would allow Rook to block deletion of
CephObjectStores without care for who has "claimed" a bucket.

Given that a Kubernetes cluster might have many hundreds of ObjectBuckets, or COSI Buckets, having a
simpler way of querying for dependents can lighten the load on the Kubernetes API server and reduce
Rook's resource usage.

Since OBs and COSI Buckets both result in buckets being created in a CephObjectStore, Rook can query
the object store and block deletion if buckets exist.

This is an elegant solution for blocking when buckets are claimed by these outside resources. It
does mean that CephObjectStores that have had buckets created in them directly (by admins or users)
will block until the buckets are manually deleted. An admin may need to request that users remove
unneeded buckets or may instead remove the buckets themselves.

If the admin wishes to preserve the CephObjectStore's pools on deletion along with their data, the
admin may merely remove the finalizer on the CephObjectStore.

While this requires more steps to delete the CephObjectStore, it provides additional safety for user
data by requiring users or admins to inspect and clean up unneeded buckets.

The main downside to this approach is that Rook will not be able to report if there are specific
OBs or COSI Buckets consuming storage from the CephObjectStore. An admin would need to examine the
resources in their cluster to determine if there are claims to the storage manually. A diligent
admin will likely have done this work beforehand.

This document proposes to implement this strategy to avoid reliance on external APIs. Rook
developers should revisit the decision at a later date to discuss whether the strategy is continuing
to adequately meet users' needs and whether the drawbacks noted are causing any issues.

### Implementation in stages
This design will result in changes to every major Rook-Ceph controller. However, it should be quite
easy to tackle these changes in stages so that changes can be more easily implemented and reviewed.

Stages by priority:
1. Block deletion of a CephCluster when there are other Rook-Ceph resources in the same namespace
1. Block deletion of a CephObjectStore when there is a user bucket present in the store.
   - This already has an implementation, but it blocks for unrelated OBs
1. Block deletion of a CephBlockPool, CephFilesystem, CephObjectStore, or CephObjectZone when a
   CephNFS uses one of its pools.
1. Block deletion of a CephBlockPool or CephFilesystem when there is a PersistentVolume reliant on it.
1. Block deletion of a CephObjectStore when there is a CephObjectStoreUser reliant on it.
1. Block deletion of a CephRBDMirror if a CephBlockPool has mirroring enabled, AND
   Block deletion of a CephFilesystemMirror if a CephFilesystem has mirroring enabled.
   - These are such similar checks that they should be simple to do at the same time.
1. Block deletion of object multisite resources with their hierarchy:
   - CephObjectRealm -> CephObjectZoneGroup -> CephObjectZone -> CephObjectStore
1. Block deletion of a CephBlockPool, CephFilesystem, CephObjectStore, or CephObjectZone when a CephClient uses one of its pools.
   - CephClients are seldom used, and few users will be affected if this is not in place.

### Future work
Immediate feedback is always more helpful to users when possible. It should be possible to implement
dependency checks in a validating admission controller quite easily, but we don't currently know if
the controller is able to validate delete requests. This design leaves this investigation for the
future, but implementation of the design can strive to make dependency checking code easily reusable
for the admission controller when work on that might begin.


text:
using Newtonsoft.Json.Linq;
using Skybrud.Essentials.Json;

namespace Skybrud.Social.Dropbox.Models {

    /// <summary>
    /// Class representing an object received from the Dropbox API.
    /// </summary>
    public class DropboxObject : JsonObjectBase {

        #region Constructors

        /// <summary>
        /// Initializes a new instance from the specified <paramref name="obj"/>.
        /// </summary>
        /// <param name="obj">The instance of <see cref="JObject"/> representing the object.</param>
        protected DropboxObject(JObject obj) : base(obj) { }

        #endregion

    }

}


text:
title: Llibre tutorial en espanyol de testing en php
date: 2017-03-21 18:00
categories:
    - programació
tags:
    - testing
    - php
    - rubenDD
---
Seguint amb la meva intenció de millorar cada dia que passa, m'he trobat aquest llibre
que parla sobre testing en PHP, està escrit en castellà i que m'ha semblat molt interessant. Pel que sembla forma part d¡un projecte final de carrera.

Aquí teniu l'enllaç:
Testeo de código en desarrollos PHP

Moltes felicitats Jose perquè està escrit d'una forma molt entenedora. Recomano la seva lectura.


text:
/*
 * SPDX-License-Identifier: Apache-2.0
 */

#include <stdint.h>
#include <nffs/nffs.h>
#include <fs.h>
#include "nffs_test_utils.h"
#include <ztest_assert.h>

extern struct k_mem_slab nffs_block_entry_pool;
extern struct k_mem_slab nffs_inode_entry_pool;

void test_unlink(void)
{
	struct fs_dirent file_stats;
	struct fs_file_t file0, file1;
	u8_t buf[64];
	struct nffs_file *nffs_file;
	u32_t bytes_read;
	int initial_num_blocks;
	int initial_num_inodes;
	int rc;

	rc = nffs_format_full(nffs_current_area_descs);
	zassert_equal(rc, 0, "cannot format nffs");

	initial_num_blocks = k_mem_slab_num_free_get(&nffs_block_entry_pool);
	initial_num_inodes = k_mem_slab_num_free_get(&nffs_inode_entry_pool);

	nffs_test_util_create_file(NFFS_MNTP"/file0.txt", "0", 1);

	rc = fs_open(&file0, NFFS_MNTP"/file0.txt");
	zassert_equal(rc, 0, "cannot open file");
	nffs_file = file0.filep;
	zassert_equal(nffs_file->nf_inode_entry->nie_refcnt, 2, "inode error");

	rc = fs_unlink(NFFS_MNTP"/file0.txt");
	zassert_equal(rc, 0, "");
	zassert_equal(nffs_file->nf_inode_entry->nie_refcnt, 1, "inode error");

	rc = fs_stat(NFFS_MNTP"/file0.txt", &file_stats);
	zassert_not_equal(rc, 0, "no such file");

	rc = fs_write(&file0, "00", 2);

	rc = fs_seek(&file0, 0, FS_SEEK_SET);
	zassert_equal(rc, 0, "cannot set pos in file");

	bytes_read = fs_read(&file0, buf, sizeof(buf));
	zassert_equal(bytes_read, 2, "invalid bytes read");
	zassert_equal(memcmp(buf, "00", 2), 0, "invalid buffer size");

	rc = fs_close(&file0);
	zassert_equal(rc, 0, "cannot close file");

	rc = fs_stat(NFFS_MNTP"/file0.txt", &file_stats);
	zassert_not_equal(rc, 0, "no such file");

	/* Ensure the file was fully removed from RAM. */
	zassert_equal(k_mem_slab_num_free_get(&nffs_inode_entry_pool),
				initial_num_inodes, "file not remove entirely");
	zassert_equal(k_mem_slab_num_free_get(&nffs_block_entry_pool),
				initial_num_blocks, "file not remove entirely");

	/*** Nested unlink. */
	rc = fs_mkdir(NFFS_MNTP"/mydir");
	zassert_equal(rc, 0, "cannot make directory");
	nffs_test_util_create_file(NFFS_MNTP"/mydir/file1.txt", "1", 2);

	rc = fs_open(&file1, NFFS_MNTP"/mydir/file1.txt");
	zassert_equal(rc, 0, "cannot open file");
	nffs_file = file1.filep;
	zassert_equal(nffs_file->nf_inode_entry->nie_refcnt, 2, "inode error");

	rc = fs_unlink(NFFS_MNTP"/mydir");
	zassert_equal(rc, 0, "cannot delete directory");
	zassert_equal(nffs_file->nf_inode_entry->nie_refcnt, 1, "inode error");

	rc = fs_stat(NFFS_MNTP"/mydir/file1.txt", &file_stats);
	zassert_not_equal(rc, 0, "unlink failed");

	rc = fs_write(&file1, "11", 2);

	rc = fs_seek(&file1, 0, FS_SEEK_SET);
	zassert_equal(rc, 0, "cannot set pos in file");

	bytes_read = fs_read(&file1, buf, sizeof(buf));
	zassert_equal(bytes_read, 2, "invalid bytes read");
	zassert_equal(memcmp(buf, "11", 2), 0, "invalid buffer size");

	rc = fs_close(&file1);
	zassert_equal(rc, 0, "cannot close file");

	rc = fs_stat(NFFS_MNTP"/mydir/file1.txt", &file_stats);
	zassert_not_equal(rc, 0, "unlink failed");

	struct nffs_test_file_desc *expected_system =
		(struct nffs_test_file_desc[]) { {
			.filename = "",
			.is_dir = 1,
		} };

	nffs_test_assert_system(expected_system, nffs_current_area_descs);

	/* Ensure the files and directories were fully removed from RAM. */
	zassert_equal(k_mem_slab_num_free_get(&nffs_inode_entry_pool),
				initial_num_inodes, "not all removed from RAM");
	zassert_equal(k_mem_slab_num_free_get(&nffs_block_entry_pool),
				initial_num_blocks, "not all removed from RAM");
}


text:
  NAME=rpyc
  VERSION=3.0
  REVISION=6
  IDENTIFIER=$NAME-$VERSION.$REVISION
  PREFIX=$HOME
  rm -fr $IDENTIFIER.tar.gz
  wget http://superb-east.dl.sourceforge.net/sourceforge/$NAME/$IDENTIFIER.tar.gz
  rm -fr $IDENTIFIER
  tar zxvf $IDENTIFIER.tar.gz
  cd $IDENTIFIER

  python setup.py build
  python setup.py install --prefix=$PREFIX

  cp -f $NAME/servers/classic_server.py $PREFIX/bin
  cp -f $NAME/servers/registry_server.py $PREFIX/bin
  cp -f $NAME/servers/vdbconf.py $PREFIX/bin

  cd ..


text:
<?php

namespace server\socket;

class events
{
	protected $bind = null;
	protected $onReadNotBlock = null;
	protected $onWriteNotBlock = null;
	protected $onTimeout = null;

	public function __isset($event)
	{
		return (isset($this->{$event}) === true && $this->{$event} !== null);
	}

	public function __unset($event)
	{
		if (isset($this->{$event}) === true)
		{
			$this->{$event} = null;
		}

		return $this;
	}

	public function bind($object)
	{
		$this->bind = $object;

		return $this;
	}

	public function onReadNotBlock(callable $callable)
	{
		$this->onReadNotBlock = $callable;

		return $this;
	}

	public function triggerOnReadNotBlock($socket)
	{
		if ($this->onReadNotBlock !== null)
		{
			$onReadNotBlock = $this->onReadNotBlock;

			$this->onReadNotBlock = null;

			call_user_func_array($onReadNotBlock, array($this->bind ?: $socket));
		}

		return $this;
	}

	public function onWriteNotBlock(callable $callable)
	{
		$this->onWriteNotBlock = $callable;

		return $this;
	}

	public function triggerOnWriteNotBlock($socket)
	{
		if ($this->onWriteNotBlock !== null)
		{
			$onWriteNotBlock = $this->onWriteNotBlock;

			$this->onWriteNotBlock = null;

			call_user_func_array($onWriteNotBlock, array($this->bind ?: $socket));
		}

		return $this;
	}

	public function onTimeout(timer $timer, callable $callable)
	{
		$this->onTimeout = array($timer->start(), $callable);

		return $this;
	}

	public function triggerOnTimeout($socket)
	{
		$remaining = null;

		if ($this->onTimeout !== null)
		{
			$remaining =  $this->onTimeout[0]->getRemaining();

			if ($remaining <= 0)
			{
				call_user_func_array($this->onTimeout[1], array($this->bind ?: $socket));
			}
		}

		return $remaining;
	}
}


text:
var sqlite3 = require('..');
var assert = require('assert');

describe('profiling', function() {
    var create = false;
    var select = false;

    var db;
    before(function(done) {
        db = new sqlite3.Database(':memory:', done);

        db.on('profile', function(sql, nsecs) {
            assert.ok(typeof nsecs === "number");
            if (sql.match(/^SELECT/)) {
                assert.ok(!select);
                assert.equal(sql, "SELECT * FROM foo");
                console.log('profile select');
                select = true;
            }
            else if (sql.match(/^CREATE/)) {
                assert.ok(!create);
                assert.equal(sql, "CREATE TABLE foo (id int)");
                create = true;
            }
            else {
                assert.ok(false);
            }
        });
    });

    it('should profile a create table', function(done) {
        assert.ok(!create);
        db.run("CREATE TABLE foo (id int)", function(err) {
            if (err) throw err;
            setImmediate(function() {
                assert.ok(create);
                done();
            });
        });
    });

    it('should profile a select', function(done) {
        assert.ok(!select);
        db.run("SELECT * FROM foo", function(err) {
            if (err) throw err;
            setImmediate(function() {
                assert.ok(select);
                done();
            }, 0);
        });
    });

    after(function(done) {
        db.close(done);
    });
});


text:
package com.store.app.service;

import com.google.appengine.api.datastore.DatastoreService;

public interface DatastoreServiceFactoryInterface {
    public DatastoreService getDatastoreService();
}


text:
"""
:func:`~pandas.eval` source string parsing functions
"""
from __future__ import annotations

from io import StringIO
from keyword import iskeyword
import token
import tokenize
from typing import (
    Hashable,
    Iterator,
)

# A token value Python's tokenizer probably will never use.
BACKTICK_QUOTED_STRING = 100

def create_valid_python_identifier(name: str) -> str:
    """
    Create valid Python identifiers from any string.

    Check if name contains any special characters. If it contains any
    special characters, the special characters will be replaced by
    a special string and a prefix is added.

    Raises
    ------
    SyntaxError
        If the returned name is not a Python valid identifier, raise an exception.
        This can happen if there is a hashtag in the name, as the tokenizer will
        than terminate and not find the backtick.
        But also for characters that fall out of the range of (U+0001..U+007F).
    """
    if name.isidentifier() and not iskeyword(name):
        return name

    # Create a dict with the special characters and their replacement string.
    # EXACT_TOKEN_TYPES contains these special characters
    # token.tok_name contains a readable description of the replacement string.
    special_characters_replacements = {
        char: f"_{token.tok_name[tokval]}_"
        for char, tokval in (tokenize.EXACT_TOKEN_TYPES.items())
    }
    special_characters_replacements.update(
        {
            " ": "_",
            "?": "_QUESTIONMARK_",
            "!": "_EXCLAMATIONMARK_",
            "$": "_DOLLARSIGN_",
            "€": "_EUROSIGN_",
            "°": "_DEGREESIGN_",
            # Including quotes works, but there are exceptions.
            "'": "_SINGLEQUOTE_",
            '"': "_DOUBLEQUOTE_",
            # Currently not possible. Terminates parser and won't find backtick.
            # "#": "_HASH_",
        }
    )

    name = "".join([special_characters_replacements.get(char, char) for char in name])
    name = f"BACKTICK_QUOTED_STRING_{name}"

    if not name.isidentifier():
        raise SyntaxError(f"Could not convert '{name}' to a valid Python identifier.")

    return name

def clean_backtick_quoted_toks(tok: tuple[int, str]) -> tuple[int, str]:
    """
    Clean up a column name if surrounded by backticks.

    Backtick quoted string are indicated by a certain tokval value. If a string
    is a backtick quoted token it will processed by
    :func:`_create_valid_python_identifier` so that the parser can find this
    string when the query is executed.
    In this case the tok will get the NAME tokval.

    Parameters
    ----------
    tok : tuple of int, str
        ints correspond to the all caps constants in the tokenize module

    Returns
    -------
    tok : Tuple[int, str]
        Either the input or token or the replacement values
    """
    toknum, tokval = tok
    if toknum == BACKTICK_QUOTED_STRING:
        return tokenize.NAME, create_valid_python_identifier(tokval)
    return toknum, tokval

def clean_column_name(name: Hashable) -> Hashable:
    """
    Function to emulate the cleaning of a backtick quoted name.

    The purpose for this function is to see what happens to the name of
    identifier if it goes to the process of being parsed a Python code
    inside a backtick quoted string and than being cleaned
    (removed of any special characters).

    Parameters
    ----------
    name : hashable
        Name to be cleaned.

    Returns
    -------
    name : hashable
        Returns the name after tokenizing and cleaning.

    Notes
    -----
        For some cases, a name cannot be converted to a valid Python identifier.
        In that case :func:`tokenize_string` raises a SyntaxError.
        In that case, we just return the name unmodified.

        If this name was used in the query string (this makes the query call impossible)
        an error will be raised by :func:`tokenize_backtick_quoted_string` instead,
        which is not caught and propagates to the user level.
    """
    try:
        tokenized = tokenize_string(f"`{name}`")
        tokval = next(tokenized)[1]
        return create_valid_python_identifier(tokval)
    except SyntaxError:
        return name

def tokenize_backtick_quoted_string(
    token_generator: Iterator[tokenize.TokenInfo], source: str, string_start: int
) -> tuple[int, str]:
    """
    Creates a token from a backtick quoted string.

    Moves the token_generator forwards till right after the next backtick.

    Parameters
    ----------
    token_generator : Iterator[tokenize.TokenInfo]
        The generator that yields the tokens of the source string (Tuple[int, str]).
        The generator is at the first token after the backtick (`)

    source : str
        The Python source code string.

    string_start : int
        This is the start of backtick quoted string inside the source string.

    Returns
    -------
    tok: Tuple[int, str]
        The token that represents the backtick quoted string.
        The integer is equal to BACKTICK_QUOTED_STRING (100).
    """
    for _, tokval, start, _, _ in token_generator:
        if tokval == "`":
            string_end = start[1]
            break

    return BACKTICK_QUOTED_STRING, source[string_start:string_end]

def tokenize_string(source: str) -> Iterator[tuple[int, str]]:
    """
    Tokenize a Python source code string.

    Parameters
    ----------
    source : str
        The Python source code string.

    Returns
    -------
    tok_generator : Iterator[Tuple[int, str]]
        An iterator yielding all tokens with only toknum and tokval (Tuple[ing, str]).
    """
    line_reader = StringIO(source).readline
    token_generator = tokenize.generate_tokens(line_reader)

    # Loop over all tokens till a backtick (`) is found.
    # Then, take all tokens till the next backtick to form a backtick quoted string
    for toknum, tokval, start, _, _ in token_generator:
        if tokval == "`":
            try:
                yield tokenize_backtick_quoted_string(
                    token_generator, source, string_start=start[1] + 1
                )
            except Exception as err:
                raise SyntaxError(f"Failed to parse backticks in '{source}'.") from err
        else:
            yield toknum, tokval


text:
namespace google {
namespace cloud {
namespace dialogflow_es_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

AgentsLogging::AgentsLogging(std::shared_ptr<AgentsStub> child,
                             TracingOptions tracing_options,
                             std::set<std::string> components)
    : child_(std::move(child)),
      tracing_options_(std::move(tracing_options)),
      components_(std::move(components)) {}

StatusOr<google::cloud::dialogflow::v2::Agent> AgentsLogging::GetAgent(
    grpc::ClientContext& context,
    google::cloud::dialogflow::v2::GetAgentRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](grpc::ClientContext& context,
             google::cloud::dialogflow::v2::GetAgentRequest const& request) {
        return child_->GetAgent(context, request);
      },
      context, request, __func__, tracing_options_);
}

StatusOr<google::cloud::dialogflow::v2::Agent> AgentsLogging::SetAgent(
    grpc::ClientContext& context,
    google::cloud::dialogflow::v2::SetAgentRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](grpc::ClientContext& context,
             google::cloud::dialogflow::v2::SetAgentRequest const& request) {
        return child_->SetAgent(context, request);
      },
      context, request, __func__, tracing_options_);
}

Status AgentsLogging::DeleteAgent(
    grpc::ClientContext& context,
    google::cloud::dialogflow::v2::DeleteAgentRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](grpc::ClientContext& context,
             google::cloud::dialogflow::v2::DeleteAgentRequest const& request) {
        return child_->DeleteAgent(context, request);
      },
      context, request, __func__, tracing_options_);
}

StatusOr<google::cloud::dialogflow::v2::SearchAgentsResponse>
AgentsLogging::SearchAgents(
    grpc::ClientContext& context,
    google::cloud::dialogflow::v2::SearchAgentsRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](
          grpc::ClientContext& context,
          google::cloud::dialogflow::v2::SearchAgentsRequest const& request) {
        return child_->SearchAgents(context, request);
      },
      context, request, __func__, tracing_options_);
}

future<StatusOr<google::longrunning::Operation>> AgentsLogging::AsyncTrainAgent(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::dialogflow::v2::TrainAgentRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::cloud::dialogflow::v2::TrainAgentRequest const& request) {
        return child_->AsyncTrainAgent(cq, std::move(context), request);
      },
      cq, std::move(context), request, __func__, tracing_options_);
}

future<StatusOr<google::longrunning::Operation>>
AgentsLogging::AsyncExportAgent(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::dialogflow::v2::ExportAgentRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::cloud::dialogflow::v2::ExportAgentRequest const& request) {
        return child_->AsyncExportAgent(cq, std::move(context), request);
      },
      cq, std::move(context), request, __func__, tracing_options_);
}

future<StatusOr<google::longrunning::Operation>>
AgentsLogging::AsyncImportAgent(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::dialogflow::v2::ImportAgentRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::cloud::dialogflow::v2::ImportAgentRequest const& request) {
        return child_->AsyncImportAgent(cq, std::move(context), request);
      },
      cq, std::move(context), request, __func__, tracing_options_);
}

future<StatusOr<google::longrunning::Operation>>
AgentsLogging::AsyncRestoreAgent(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::cloud::dialogflow::v2::RestoreAgentRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](
          google::cloud::CompletionQueue& cq,
          std::unique_ptr<grpc::ClientContext> context,
          google::cloud::dialogflow::v2::RestoreAgentRequest const& request) {
        return child_->AsyncRestoreAgent(cq, std::move(context), request);
      },
      cq, std::move(context), request, __func__, tracing_options_);
}

StatusOr<google::cloud::dialogflow::v2::ValidationResult>
AgentsLogging::GetValidationResult(
    grpc::ClientContext& context,
    google::cloud::dialogflow::v2::GetValidationResultRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](grpc::ClientContext& context,
             google::cloud::dialogflow::v2::GetValidationResultRequest const&
                 request) {
        return child_->GetValidationResult(context, request);
      },
      context, request, __func__, tracing_options_);
}

future<StatusOr<google::longrunning::Operation>>
AgentsLogging::AsyncGetOperation(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::longrunning::GetOperationRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::longrunning::GetOperationRequest const& request) {
        return child_->AsyncGetOperation(cq, std::move(context), request);
      },
      cq, std::move(context), request, __func__, tracing_options_);
}

future<Status> AgentsLogging::AsyncCancelOperation(
    google::cloud::CompletionQueue& cq,
    std::unique_ptr<grpc::ClientContext> context,
    google::longrunning::CancelOperationRequest const& request) {
  return google::cloud::internal::LogWrapper(
      [this](google::cloud::CompletionQueue& cq,
             std::unique_ptr<grpc::ClientContext> context,
             google::longrunning::CancelOperationRequest const& request) {
        return child_->AsyncCancelOperation(cq, std::move(context), request);
      },
      cq, std::move(context), request, __func__, tracing_options_);
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace dialogflow_es_internal
}  // namespace cloud
}  // namespace google


text:
             <button type="button" class="navbar-toggle" ng-click="headerCtrl.navbarCollapsed = !headerCtrl.navbarCollapsed">
                 Toggle navigation

             </button>

{{NAMES.title}}{{NAMES.sublogo}}

                <search class="hidden-sm hidden-md hidden-lg"></search>

                  <side-bar-menu></side-bar-menu>

                    <search></search>

                    <notification-bell></notification-bell>