text:
#Point on ray

Determining if a point is on a ray or not comes down to the dot product. The key here is to realize that given the direction of the ray we have a normal vector. If we subtract the point from the ray, and normalize the resuling vector, we have a normal from the origin of the ray to the test point. At this point we have two normals. Remember, the dot product of two normals is:

* __0__ if the two vectors point in the same direction
  * That is to say, if the vectors are perpendicular
* __positive__ If the vectors point in the same direction
* __negative__ If the vectors point in opposing direction

Of course you need to use a very small epsilon here, because of floating point error. A visual example of the above bullet points:

![DOTSIMPLE](dotsimple.jpg)

In a more practical example, if we know the forward vector of a guard, a player is in the guards view if the dot product of the guards forward and the vector from the guard to the player are positive.

![SNEAK](sneak.jpg)

Now, there is one edge case to all this. What happens if the point we are testing and the origin of the ray are the same point? Well, the dot product breaks down and we get no new normal vector. But that point is on the ray. You should add a special case if check for that.

See if you can implement this on your own before looking at the code below.

### The algorithm

Implementing the above in code is fairly straight forward:

```
bool PointOnRay(Point point, Ray ray) {
    // If point and ray are the same, return true

    Vector3 newNorm = point - ray.Position;
    newNorm.Normalize();

    float d = Vector3.Dot(newNorm, ray.Normal);
    return Math.Abs(1f - d) < 0.000001f; // SUPER SMALL EPSILON!
}
```

## On Your Own

Add the following function to the ```Collisions``` class:

```cs
public static bool PointOnRay(Point point, Ray ray)
```

And provide an implementation for it!

### Unit Test

You can [Download](../Samples/CollisionRay.rar) the samples for this chapter to see if your result looks like the unit test.

The constructor of this code will spit out errors if they are present. A ray is rendered, along with a random sampling of points. Any point that falls on the ray is rendered in red, points not on the ray are rendered in blue.

![UNIT](point_on_ray_sample_01.PNG)

```cs
using OpenTK.Graphics.OpenGL;
using Math_Implementation;
using CollisionDetectionSelector.Primitives;

namespace CollisionDetectionSelector.Samples {
    class PointOnray : Application {
        protected Vector3 cameraAngle = new Vector3(120.0f, -10f, 20.0f);
        protected float rads = (float)(System.Math.PI / 180.0f);

        Ray testRay = new Ray(new Point(-3, -2, -1), new Vector3(3, 2, 1));
        Point[] testPoints = new Point[] {
            new Point(-3, -2, -1),
            new Point(12, 8, 4),
            new Point(0, 0, 0),
            new Point(-18, -12, -6),
            new Point(-4, -7, -8),
            new Point(7, 8, 5),
            new Point(1, 5, -5),
            new Point(-6, 5, 7),
            new Point(1, 6, 8),
            new Point(-7, -10, -4),
            new Point(-4.5f, -3f, -1.5f)
        };

        public override void Intialize(int width, int height) {
            GL.Enable(EnableCap.DepthTest);
            GL.PointSize(4f);

            for (int i = 0; i < 3; ++i) {
                if (!Collisions.PointOnRay(testPoints[i], testRay)) {
                    System.Console.ForegroundColor = System.ConsoleColor.Red;
                    System.Console.WriteLine("Expected point: " + testPoints[i].ToString() + " to be on Ray!");
                }
            }

            for (int i = 3; i < testPoints.Length; ++i) {
                if (Collisions.PointOnRay(testPoints[i], testRay)) {
                    System.Console.ForegroundColor = System.ConsoleColor.Red;
                    System.Console.WriteLine("Expected point: " + testPoints[i].ToString() + " to NOT be on Ray!");
                }
            }
        }

        public override void Render() {
            Vector3 eyePos = new Vector3();
            eyePos.X = cameraAngle.Z * -(float)System.Math.Sin(cameraAngle.X * rads * (float)System.Math.Cos(cameraAngle.Y * rads));
            eyePos.Y = cameraAngle.Z * -(float)System.Math.Sin(cameraAngle.Y * rads);
            eyePos.Z = -cameraAngle.Z * (float)System.Math.Cos(cameraAngle.X * rads * (float)System.Math.Cos(cameraAngle.Y * rads));

            Matrix4 lookAt = Matrix4.LookAt(eyePos, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f));
            GL.LoadMatrix(Matrix4.Transpose(lookAt).Matrix);

            GL.Color3(1f, 0f, 1f);
            testRay.Render();

            foreach (Point point in testPoints) {
                if (Collisions.PointOnRay(point, testRay)) {
                    GL.Color3(1f, 0f, 0f);
                }
                else {
                    GL.Color3(0f, 0f, 1f);
                }
                point.Render();
            }
        }

        public override void Update(float deltaTime) {
            cameraAngle.X += 45.0f * deltaTime;
        }

        public override void Resize(int width, int height) {
            GL.Viewport(0, 0, width, height);
            GL.MatrixMode(MatrixMode.Projection);
            float aspect = (float)width / (float)height;
            Matrix4 perspective = Matrix4.Perspective(60, aspect, 0.01f, 1000.0f);
            GL.LoadMatrix(Matrix4.Transpose(perspective).Matrix);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
        }
    }
}
```

license: Unlicense


text:
# sfdx-mobilesdk-plugin

A plugin for the Salesforce CLI to create mobile applications to interface with the [Salesforce Platform](http://www.salesforce.com/platform/overview/), leveraging the [Salesforce Mobile SDK for iOS](https://github.com/forcedotcom/SalesforceMobileSDK-iOS) and the [Salesforce Mobile SDK for Android](https://github.com/forcedotcom/SalesforceMobileSDK-Android) repos.

## Special Note Regarding SFDX and Oclif

SFDX now supports the Heroku "O"pen "CLI" "F"ramework and sfdx-mobilesdk-plugin v7.1.0 has been updated to be compatible. The new plugin will run in both version 6 and version 7 instances of the SFDX cli. However, older versions of the mobilesdk plugin will not work in the Oclif version of the CLI.

If there is a need to use an older plugin one must first uninstall V7 of the CLI and install a V6 instance.

To determine the latest version of v6 go here:

https://www.npmjs.com/package/sfdx-cli?activeTab=versions

The most reliable way to install a previous version of the CLI is via npm.

`npm install sfdx-cli@<V6 version from npmjs> -g`

## Setup

### Install from source

1. Install the SDFX CLI (https://developer.salesforce.com/tools/sfdxcli).

2. Clone the repository: `git clone git@github.com:forcedotcom/SalesforceMobileSDK-Package`

3. Install npm modules: `npm install`

4. Generate oclif command classes `./sfdx/generate_oclif.js`

5. Link the plugin: `sfdx plugins:link sfdx`

### Install as plugin

1. Install plugin: `sfdx plugins:install sfdx-mobilesdk-plugin`

## Help
```
-> sfdx mobilesdk --help
create mobile apps based on the Salesforce Mobile SDK

USAGE
  $ sfdx mobilesdk:COMMAND

TOPICS
  mobilesdk:android      create an Android native mobile application
  mobilesdk:hybrid       create a hybrid mobile application
  mobilesdk:ios          create an iOS native mobile application
  mobilesdk:reactnative  create a React Native mobile application

```

## Create a native iOS application
### Help for iOS
```
-> sfdx mobilesdk:ios --help
create an iOS native mobile application

USAGE
  $ sfdx mobilesdk:ios:COMMAND

COMMANDS
  mobilesdk:ios:checkconfig         validate store or syncs configuration
  mobilesdk:ios:create              create an iOS native mobile application
  mobilesdk:ios:createwithtemplate  create an iOS native mobile application from
                                    a template
  mobilesdk:ios:listtemplates       list available Mobile SDK templates to
                                    create an iOS native mobile application
  mobilesdk:ios:version             show version of Mobile SDK

```

### Create Objective-C (native) or Swift (native_swift) application
```
-> sfdx mobilesdk:ios:create --help
create an iOS native mobile application

USAGE
  $ sfdx mobilesdk:ios:create

OPTIONS
  -d, --outputdir=outputdir        output directory (leave empty for current
                                   directory)

  -k, --packagename=packagename    (required) app package identifier (e.g.
                                   com.mycompany.myapp)

  -n, --appname=appname            (required) application name

  -o, --organization=organization  (required) organization name (your
                                   company's/organization's name)

  -t, --apptype=apptype            application type (native_swift or native,
                                   leave empty for native_swift)

DESCRIPTION
  This command initiates creation of a new app based on the standard Mobile SDK
  template.

```

### List available native iOS templates
```
-> sfdx mobilesdk:ios:listtemplates --help
list available Mobile SDK templates to create an iOS native mobile application

USAGE
  $ sfdx mobilesdk:ios:listtemplates

DESCRIPTION
  This command displays the list of available Mobile SDK templates. You can copy
  repo paths from the output for use with the createwithtemplate command.

```

### Create iOS application from template
```
-> sfdx mobilesdk:ios:createwithtemplate --help
create an iOS native mobile application from a template

USAGE
  $ sfdx mobilesdk:ios:createwithtemplate

OPTIONS
  -d, --outputdir=outputdir              output directory (leave empty for
                                         current directory)

  -k, --packagename=packagename          (required) app package identifier (e.g.
                                         com.mycompany.myapp)

  -n, --appname=appname                  (required) application name

  -o, --organization=organization        (required) organization name (your
                                         company's/organization's name)

  -r, --templaterepouri=templaterepouri  (required) template repo URI or Mobile
                                         SDK template name

DESCRIPTION
  This command initiates creation of a new app based on the Mobile SDK template
  that you specify. The template can be a specialized app for your app type that
  Mobile SDK provides, or your own custom app that you've configured to use as a
  template. See
  https://developer.salesforce.com/docs/atlas.en-us.mobile_sdk.meta/mobile_sdk/i
  os_new_project_template.htm for information on custom templates.

```

### Check store or syncs config
```
-> sfdx mobilesdk:ios:checkconfig --help
validate store or syncs configuration

USAGE
  $ sfdx mobilesdk:ios:checkconfig

OPTIONS
  -p, --configpath=configpath  (required) path to store or syncs config to
                               validate

  -t, --configtype=configtype  (required) type of config to validate (store or
                               syncs)

DESCRIPTION
  This command checks whether the given store or syncs configuration is valid
  according to its JSON schema.

```

## Create a native Android application
### Help for Android
```
-> sfdx mobilesdk:android --help
create an Android native mobile application

USAGE
  $ sfdx mobilesdk:android:COMMAND

COMMANDS
  mobilesdk:android:checkconfig         validate store or syncs configuration
  mobilesdk:android:create              create an Android native mobile
                                        application
  mobilesdk:android:createwithtemplate  create an Android native mobile
                                        application from a template
  mobilesdk:android:listtemplates       list available Mobile SDK templates to
                                        create an Android native mobile
                                        application
  mobilesdk:android:version             show version of Mobile SDK

```

### Create Java (native) or Kotlin (native_kotlin) application
```
-> sfdx mobilesdk:android:create --help
create an Android native mobile application

USAGE
  $ sfdx mobilesdk:android:create

OPTIONS
  -d, --outputdir=outputdir        output directory (leave empty for current
                                   directory)

  -k, --packagename=packagename    (required) app package identifier (e.g.
                                   com.mycompany.myapp)

  -n, --appname=appname            (required) application name

  -o, --organization=organization  (required) organization name (your
                                   company's/organization's name)

  -t, --apptype=apptype            application type (native_kotlin or native,
                                   leave empty for native_kotlin)

DESCRIPTION
  This command initiates creation of a new app based on the standard Mobile SDK
  template.

```

### List available native Android templates
```
-> sfdx mobilesdk:android:listtemplates --help
list available Mobile SDK templates to create an Android native mobile application

USAGE
  $ sfdx mobilesdk:android:listtemplates

DESCRIPTION
  This command displays the list of available Mobile SDK templates. You can copy
  repo paths from the output for use with the createwithtemplate command.

```

### Create Android application from template
```
-> sfdx mobilesdk:android:createwithtemplate --help
create an Android native mobile application from a template

USAGE
  $ sfdx mobilesdk:android:createwithtemplate

OPTIONS
  -d, --outputdir=outputdir              output directory (leave empty for
                                         current directory)

  -k, --packagename=packagename          (required) app package identifier (e.g.
                                         com.mycompany.myapp)

  -n, --appname=appname                  (required) application name

  -o, --organization=organization        (required) organization name (your
                                         company's/organization's name)

  -r, --templaterepouri=templaterepouri  (required) template repo URI or Mobile
                                         SDK template name

DESCRIPTION
  This command initiates creation of a new app based on the Mobile SDK template
  that you specify. The template can be a specialized app for your app type that
  Mobile SDK provides, or your own custom app that you've configured to use as a
  template. See
  https://developer.salesforce.com/docs/atlas.en-us.mobile_sdk.meta/mobile_sdk/i
  os_new_project_template.htm for information on custom templates.

```

### Check store or syncs config
```
-> sfdx mobilesdk:android:checkconfig --help
validate store or syncs configuration

USAGE
  $ sfdx mobilesdk:android:checkconfig

OPTIONS
  -p, --configpath=configpath  (required) path to store or syncs config to
                               validate

  -t, --configtype=configtype  (required) type of config to validate (store or
                               syncs)

DESCRIPTION
  This command checks whether the given store or syncs configuration is valid
  according to its JSON schema.

```

## Create an hybrid application
### Help for hybrid
```
-> sfdx mobilesdk:hybrid --help
create a hybrid mobile application

USAGE
  $ sfdx mobilesdk:hybrid:COMMAND

COMMANDS
  mobilesdk:hybrid:checkconfig         validate store or syncs configuration
  mobilesdk:hybrid:create              create a hybrid mobile application
  mobilesdk:hybrid:createwithtemplate  create a hybrid mobile application from a
                                       template
  mobilesdk:hybrid:listtemplates       list available Mobile SDK templates to
                                       create a hybrid mobile application
  mobilesdk:hybrid:version             show version of Mobile SDK

```

### Create hybrid application
```
-> sfdx mobilesdk:hybrid:create --help
create a hybrid mobile application

USAGE
  $ sfdx mobilesdk:hybrid:create

OPTIONS
  -d, --outputdir=outputdir        output directory (leave empty for current
                                   directory)

  -k, --packagename=packagename    (required) app package identifier (e.g.
                                   com.mycompany.myapp)

  -n, --appname=appname            (required) application name

  -o, --organization=organization  (required) organization name (your
                                   company's/organization's name)

  -p, --platform=platform          (required) comma-separated list of platforms
                                   (ios, android)

  -s, --startpage=startpage        app start page (the start page of your remote
                                   app; required for hybrid_remote apps only)

  -t, --apptype=apptype            application type (hybrid_local or
                                   hybrid_remote or hybrid_lwc, leave empty for
                                   hybrid_local)

DESCRIPTION
  This command initiates creation of a new app based on the standard Mobile SDK
  template.

```

### List available hybrid templates
```
-> sfdx mobilesdk:hybrid:listtemplates --help
list available Mobile SDK templates to create a hybrid mobile application

USAGE
  $ sfdx mobilesdk:hybrid:listtemplates

DESCRIPTION
  This command displays the list of available Mobile SDK templates. You can copy
  repo paths from the output for use with the createwithtemplate command.

```

### Create hybrid application from template
```
-> sfdx mobilesdk:hybrid:createwithtemplate --help
create a hybrid mobile application from a template

USAGE
  $ sfdx mobilesdk:hybrid:createwithtemplate

OPTIONS
  -d, --outputdir=outputdir              output directory (leave empty for
                                         current directory)

  -k, --packagename=packagename          (required) app package identifier (e.g.
                                         com.mycompany.myapp)

  -n, --appname=appname                  (required) application name

  -o, --organization=organization        (required) organization name (your
                                         company's/organization's name)

  -p, --platform=platform                (required) comma-separated list of
                                         platforms (ios, android)

  -r, --templaterepouri=templaterepouri  (required) template repo URI or Mobile
                                         SDK template name

  -s, --startpage=startpage              app start page (the start page of your
                                         remote app; required for hybrid_remote
                                         apps only)

DESCRIPTION
  This command initiates creation of a new app based on the Mobile SDK template
  that you specify. The template can be a specialized app for your app type that
  Mobile SDK provides, or your own custom app that you've configured to use as a
  template. See
  https://developer.salesforce.com/docs/atlas.en-us.mobile_sdk.meta/mobile_sdk/i
  os_new_project_template.htm for information on custom templates.

```

### Check store or syncs config
```
-> sfdx mobilesdk:hybrid:checkconfig --help
validate store or syncs configuration

USAGE
  $ sfdx mobilesdk:hybrid:checkconfig

OPTIONS
  -p, --configpath=configpath  (required) path to store or syncs config to
                               validate

  -t, --configtype=configtype  (required) type of config to validate (store or
                               syncs)

DESCRIPTION
  This command checks whether the given store or syncs configuration is valid
  according to its JSON schema.

```

## Create a React Native application
### Help for React Native
```
-> sfdx mobilesdk:reactnative --help
create a React Native mobile application

USAGE
  $ sfdx mobilesdk:reactnative:COMMAND

COMMANDS
  mobilesdk:reactnative:checkconfig         validate store or syncs
                                            configuration
  mobilesdk:reactnative:create              create a React Native mobile
                                            application
  mobilesdk:reactnative:createwithtemplate  create a React Native mobile
                                            application from a template
  mobilesdk:reactnative:listtemplates       list available Mobile SDK templates
                                            to create a React Native mobile
                                            application
  mobilesdk:reactnative:version             show version of Mobile SDK

```

### Create React Native application
```
-> sfdx mobilesdk:reactnative:create --help
create a React Native mobile application

USAGE
  $ sfdx mobilesdk:reactnative:create

OPTIONS
  -d, --outputdir=outputdir        output directory (leave empty for current
                                   directory)

  -k, --packagename=packagename    (required) app package identifier (e.g.
                                   com.mycompany.myapp)

  -n, --appname=appname            (required) application name

  -o, --organization=organization  (required) organization name (your
                                   company's/organization's name)

  -p, --platform=platform          (required) comma-separated list of platforms
                                   (ios, android)

DESCRIPTION
  This command initiates creation of a new app based on the standard Mobile SDK
  template.

```

### List available React Native templates
```
-> sfdx mobilesdk:reactnative:listtemplates --help
list available Mobile SDK templates to create a React Native mobile application

USAGE
  $ sfdx mobilesdk:reactnative:listtemplates

DESCRIPTION
  This command displays the list of available Mobile SDK templates. You can copy
  repo paths from the output for use with the createwithtemplate command.

```

### Create React Native application from template
```
-> sfdx mobilesdk:reactnative:createwithtemplate --help
create a React Native mobile application from a template

USAGE
  $ sfdx mobilesdk:reactnative:createwithtemplate

OPTIONS
  -d, --outputdir=outputdir              output directory (leave empty for
                                         current directory)

  -k, --packagename=packagename          (required) app package identifier (e.g.
                                         com.mycompany.myapp)

  -n, --appname=appname                  (required) application name

  -o, --organization=organization        (required) organization name (your
                                         company's/organization's name)

  -p, --platform=platform                (required) comma-separated list of
                                         platforms (ios, android)

  -r, --templaterepouri=templaterepouri  (required) template repo URI or Mobile
                                         SDK template name

DESCRIPTION
  This command initiates creation of a new app based on the Mobile SDK template
  that you specify. The template can be a specialized app for your app type that
  Mobile SDK provides, or your own custom app that you've configured to use as a
  template. See
  https://developer.salesforce.com/docs/atlas.en-us.mobile_sdk.meta/mobile_sdk/i
  os_new_project_template.htm for information on custom templates.

```

### Check store or syncs config
```
-> sfdx mobilesdk:reactnative:checkconfig --help
validate store or syncs configuration

USAGE
  $ sfdx mobilesdk:reactnative:checkconfig

OPTIONS
  -p, --configpath=configpath  (required) path to store or syncs config to
                               validate

  -t, --configtype=configtype  (required) type of config to validate (store or
                               syncs)

DESCRIPTION
  This command checks whether the given store or syncs configuration is valid
  according to its JSON schema.

```

repository: forcedotcom/SalesforceMobileSDK-Package

branch_name: refs/heads/dev

extension: md

gha_language: JavaScript

license_type: permissive

repo_name: forcedotcom/SalesforceMobileSDK-Package


text:
---
layout: lab
num: lab06
ready: true
desc: "Advanced array lists and dynamic arrays"
assigned: 2019-05-15 08:00:00.00-8
due: 2019-05-21 23:59:00.00-8
---

Introduction -- Important: Read this!

The mentors will be looking for (and grading) your programming style, such as proper use of comments, tab indentation, good variable names, and overall block and function designs. You are also required to write pre- and post-conditions for every function you write, whether it is one you need to fill in from the starter code or one that you have declared and define yourself. So, **it is not enough for your lab to pass Gradescope tests**! Please read the instructions herein carefully.

# Goals of this lab

The goal of this lab is get more practice with iterating through arrays and dynamically allocating memory. Continue to practice code tracing to reason about your code.

# Step by Step Instructions: PLEASE READ CAREFULLY!

## Step 1: Getting Started

1. Go to GitHub and create a git repo for this lab following the naming convention specified in previous labs.

2. Log on to your CSIL account and open a terminal window

3. Change into your CS 16 directory

## Step 2: Create a new repo and clone it to your local directory

In lab04,  we have done the same thing. So if you don't know to how to do that, please refer to lab04 for details.
## Step 3: Get the starter code from a local directory
* Copy the starter code by typing the following command:

```
cp /cs/faculty/ykk/cs16/labs/lab06/* ~/cs16/lab06_<username>
```

Typing the list (`ls`) command should show you the following files in your current directory

```
$ ls
arrayFuncs.cpp  Makefile            README.md
arrayFuncs.h    moreArrayFuncs.cpp  tddFuncs.cpp
mafTest.cpp     moreArrayFuncs.h    tddFuncs.h
$

```

Push the initial version of the code to GitHub before making any changes by typing the following commands

```
git add .
git commit -m "Initial version of Lab 6"
git push origin master
```
Note: Remember to push your work to GitHub at the end of EVERY work session.

## Step 4: Reviewing the files and what your tasks are

Here is a list of your tasks for this lab:

### Step 4a: Familiarize yourself with the big picture

Type `make tests` and you will see some tests pass, but some fail.

Your goal is to make all the tests pass.

There is only one file that you need to edit this week:

* moreArrayFuncs.cpp contains more functions that deal with arrays.  These are in addition to the arrayFuncs.cpp that you worked with before in lab04.

### Step 4b: Add the file header

Include the following header block at the top of your moreArrayFuncs.cpp file and make sure to update it accordingly:

```
/*=============================================================================
 |   Assignment:  ASSIGNMENT NUMBER AND TITLE
 |
 |       Author:  STUDENT'S NAME HERE
 |
 |   To Compile:  EXPLAIN HOW TO COMPILE THIS PROGRAM
 |
 |        Class:  NAME AND QUARTER OF THE CLASS FOR WHICH THIS PROGRAM WAS
 |                      WRITTEN
 |     Due Date:  DATE AND TIME THAT THIS PROGRAM IS/WAS DUE TO BE SUBMITTED
 |
 +-----------------------------------------------------------------------------
 |
 |  Description:  DESCRIBE THE PROBLEM THAT THIS PROGRAM WAS WRITTEN TO SOLVE.
 |
 |        Input:  DESCRIBE THE INPUT THAT THE PROGRAM REQUIRES.
 |
 |       Output:  DESCRIBE THE OUTPUT THAT THE PROGRAM PRODUCES.
 |
 |    Algorithm:  OUTLINE THE APPROACH USED BY THE PROGRAM TO SOLVE THE
 |      PROBLEM.
 |
 |   Known Bugs:  IF THE PROGRAM DOES NOT FUNCTION CORRECTLY IN SOME
 |      SITUATIONS, DESCRIBE THE SITUATIONS AND PROBLEMS HERE.
 |
 *===========================================================================*/

```

### Step 4c: Work on the array functions

There are 9 functions you will need to write for this lab:

* indexOfMax
* indexOfMin
* largestValue
* smallestValue
* sum
* copyElements
* copyOddOnly
* multiplyPairwise
* createArray

Each one has a set of tests which can be found under its corresponding heading when you type make tests. For example, the `indexOfMax` tests look like this to start:

```
--------------INDEX_OF_MAX--------------
   FAILED: indexOfMax(fiveThrees,5)
     Expected: 0 Actual: -42
   FAILED: indexOfMax(zeros,3)
     Expected: 0 Actual: -42
   FAILED: indexOfMax(primes,1)
     Expected: 0 Actual: -42
   FAILED: indexOfMax(primes,5)
     Expected: 4 Actual: -42
   FAILED: indexOfMax(primes,10)
     Expected: 9 Actual: -42
   FAILED: indexOfMax(meaning,1)
     Expected: 0 Actual: -42
   FAILED: indexOfMax(mix1,10)
     Expected: 5 Actual: -42
   FAILED: indexOfMax(mix2,10)
     Expected: 5 Actual: -42
   FAILED: indexOfMax(mix1,3)
     Expected: 1 Actual: -42
   FAILED: indexOfMax(mix2,3)
     Expected: 1 Actual: -42
   FAILED: indexOfMax(mix2,1)
     Expected: 0 Actual: -42
   FAILED: indexOfMax(mix2,5)
     Expected: 4 Actual: -42
```

You should replace each function stub with the correct code for the function until all of the tests for each one pass. It is recommended that you work on the functions one at a time in the order that they are presented above. That is, get all the tests to pass for `indexOfMax` then `indexOfMin` and so on. When all the tests pass, move on to the next step.

## Step 5: Checking your work before submitting

When you are finished, you should be able to type  make clean and then make tests and see the following output:

```
-bash-4.2$ make clean
/bin/rm -f mafTest *.o
-bash-4.2$ make tests
clang++ -Wall -Wno-uninitialized   -c -o mafTest.o mafTest.cpp
clang++ -Wall -Wno-uninitialized   -c -o moreArrayFuncs.o moreArrayFuncs.cpp
clang++ -Wall -Wno-uninitialized   -c -o tddFuncs.o tddFuncs.cpp
clang++ -Wall -Wno-uninitialized   -c -o arrayFuncs.o arrayFuncs.cpp
clang++ -Wall -Wno-uninitialized  mafTest.o moreArrayFuncs.o tddFuncs.o arrayFuncs.o -o mafTest
./mafTest
--------------INITIALIZING--------------
PASSED: arrayToString(fiveThrees,5)
PASSED: arrayToString(zeros,3)
PASSED: arrayToString(empty,0)
PASSED: arrayToString(primes,5)
PASSED: arrayToString(primes,10)
PASSED: arrayToString(meaning,1)
PASSED: arrayToString(mix1,10)
PASSED: arrayToString(mix2,10)
PASSED: arrayToString(descending,5)
--------------INDEX_OF_MAX--------------
PASSED: indexOfMax(fiveThrees,5)
PASSED: indexOfMax(zeros,3)
PASSED: indexOfMax(primes,1)
PASSED: indexOfMax(primes,5)
PASSED: indexOfMax(primes,10)
PASSED: indexOfMax(meaning,1)
PASSED: indexOfMax(mix1,10)
PASSED: indexOfMax(mix2,10)
PASSED: indexOfMax(mix1,3)
PASSED: indexOfMax(mix2,3)
PASSED: indexOfMax(mix2,1)
PASSED: indexOfMax(mix2,5)
--------------INDEX_OF_MIN--------------
PASSED: indexOfMin(fiveThrees,5)
PASSED: indexOfMin(zeros,3)
PASSED: indexOfMin(primes,5)
PASSED: indexOfMin(primes,10)
PASSED: indexOfMin(meaning,1)
PASSED: indexOfMin(mix1,10)
PASSED: indexOfMin(mix2,10)
PASSED: indexOfMin(mix1,3)
PASSED: indexOfMin(mix2,3)
PASSED: indexOfMin(descending,5)
PASSED: indexOfMin(descending,1)
--------------LARGEST_VALUE--------------
PASSED: largestValue(fiveThrees,5)
PASSED: largestValue(zeros,3)
PASSED: largestValue(primes,5)
PASSED: largestValue(primes,10)
PASSED: largestValue(meaning,1)
PASSED: largestValue(mix1,10)
PASSED: largestValue(mix2,10)
PASSED: largestValue(mix1,3)
PASSED: largestValue(mix2,3)
PASSED: largestValue(descending,5)
PASSED: largestValue(descending,1)
--------------SMALLEST_VALUE--------------
PASSED: smallestValue(fiveThrees,5)
PASSED: smallestValue(zeros,3)
PASSED: smallestValue(primes,5)
PASSED: smallestValue(primes,10)
PASSED: smallestValue(meaning,1)
PASSED: smallestValue(mix1,10)
PASSED: smallestValue(mix2,10)
PASSED: smallestValue(mix1,3)
PASSED: smallestValue(mix2,3)
PASSED: smallestValue(descending,5)
PASSED: smallestValue(descending,1)
--------------SUM--------------
PASSED: sum(fiveThrees,5)
PASSED: sum(zeros,3)
PASSED: sum(primes,5)
PASSED: sum(primes,10)
PASSED: sum(meaning,1)
PASSED: sum(mix1,10)
PASSED: sum(mix2,10)
PASSED: sum(mix1,3)
PASSED: sum(mix2,3)
PASSED: sum(descending,5)
PASSED: sum(descending,1)
--------------COPY_ELEMENTS--------------
PASSED: arrayToString(primes,10)
PASSED: arrayToString(mix1,10)
PASSED: arrayToString(mix1,10)
PASSED: arrayToString(mix2,10)
PASSED: arrayToString(mix1,10)
PASSED: arrayToString(mix2,10)
--------------COPY_ODD_ONLY--------------
PASSED: copyOddOnly(a,descending,5)
PASSED: arrayToString(descending,5)
PASSED: arrayToString(a,3)
PASSED: copyOddOnly(a,mix2,10)
PASSED: arrayToString(mix2,10)
PASSED: arrayToString(a,5)
--------------MULTIPLY_PAIRWISE--------------
PASSED: arrayToString(fiveThrees,5)
PASSED: arrayToString(descending,5)
PASSED: arrayToString(a,5)
PASSED: arrayToString(primes,5)
PASSED: arrayToString(descending,5)
PASSED: arrayToString(a,4)
PASSED: arrayToString(primes,7)
PASSED: arrayToString(a,7)
--------------CREATE_ARRAY--------------
PASSED: arrayToString(oneElem, 1)
PASSED: arrayToString(threeElems, 3)
PASSED: arrayToString(fiveElems, 5)
PASSED: arrayToString(oneElem, 1)
PASSED: arrayToString(threeElems, 3)
PASSED: arrayToString(fiveElems, 5)
-bash-4.2$
```

At that point, you are ready to try submitting on Gradescope.

## Step 6: Submitting via Gradescope

Go throught the same submit process you have in past labs.

# Grading Rubric

Some of the points will be awarded based on Gradescope automatic grading. Other points will be assigned after visual code inspection by TAs.

 Code can be easily understood by humans familiar with C++ (including both the author(s) of the code, and non-authors of the code.)
2. Code is neatly indented and formatted, following standard code indentation practices for C++ as illustrated in either the textbook, or example code given in lectures and labs
3. Variable names choices are reasonable
4. Code is reasonably "DRY" (as in "don't repeat yourself")—where appropriate, common code is factored out into functions
5. Code is not unnecessarily or unreasonably complex when a simpler solution is available
6. Pre- and Post-conditions

## An important word about academic honesty and the Gradescope system

Make sure to actually solve the problem by writing the correct code -- you will NOT receive credit unless you write the correct functions that are able to work correctly on other inputs. We will test your code against other data files too—not just the default autograder tests that you are able to see.

Any attempt to just "game the system" or use solutions that are not your own is a form of cheating, i.e. a form of "academic dishonesty".  Submitting a program of this kind would be subject not only to a grade of 0, but to possible disciplinary penalties.    If there is any doubt about this fact, please ask your TA and/or your instructor for clarification.

license: MIT

branch_name: refs/heads/master

gha_language: HTML

gha_license_id: MIT


text:
<!---
{"next":"Lectures_class2/Lecture11.md","title":"Intro to Data Science - 9/30"}
-->

# Lecture 10: Intro to Data Science & Final Project

*Details to be confirmed...*

## 🍕 Mid Course Survey 🍕
**[What this means](https://docs.google.com/presentation/d/1r5KrB7bf0rCJpm5MCTy8eQT_5TrUy7AtimURDI-QbpQ/edit#slide=id.g3dd4fa9b7e_0_239)**

## Objectives

1. Understand the basics of data science
2. Review real-life applications of data science

## Agenda

1. **[Data Science](../Topics/nb/data_science.ipynb)**


text:
# htmlcomparator

This is a light-weight python package used to compare two html files and return the differences.

The users can choose whether they want a boolean result or string result that specify the difference. They can also choose the types of differences they want to receive.

## Usage

To start using the comparator, first import the package, and make an object.

```python
from htmlcomparator import HTMLComparator
comparator = HTMLComparator()
```
The method that is used to compare html code is
```python
comparator.compare(html1, html2, quick_compare = True, compare_type = "all")
```

```html1, html2``` are the two html to be compared. If they are both strings, it will treat them as two html strings. If they are both ```io.IOBase``` objects, then the program will treat them as two opened files. Otherwise the program will raise a ```TypeError```.

```quick_compare``` argument is used to specify whether the user want the method to simply return boolean or to return a detailed information of the differences. If it is set to True, then the method will return False as soon as it encounters the first difference, and return True if there are no difference. If it is set to False, then the two html are compared thoroughly, and the method will return a ```string``` to describe the differences. If there are no differences, it will return an empty string.

```compare_type``` argument is used to specify the type of differences to compare. It is ignored if ```quick_compare``` is set to ```True```. If it is set to ```tag```, then only tag differences will be returned. If it is set to ```data``` then tag and data differences will be returned. If it is set to ```all```, then all differences will be considered, including tags, data, and attributes.

For example,
```python
s1 = "<!DOCTYPE xml> <head> <p> test </p> <p> different here </p> </head>"
s2 = "<!DOCTYPE html> <head> <p> this is different </p> </head>"
comparator = HTMLComparator()
print(comparator.compare(s1,s2, compare_type = "all", quick_compare = False))
```
will output:
```
@@ DOCTYPE Difference @@
*DOCTYPE xml
-DOCTYPE html

extra tag <p> in the first html at (1, 36)

@@ (1, 25) , (1, 26) @@
*test
-this is different
```
The tuples ```(1, 36)```, ```(1, 25)```, and ```(1, 25)``` give the line number and the offset of the differences.

## Limitations

Currently doesn't support CSS.

## License

Copyright Mengjia Zhao 2020.
Distributed under the terms of the [Apache 2.0 license](https://github.com/in-the-ocean/htmlcomparator/blob/master/LICENSE).

repository: in-the-ocean/htmlcomparator

repo_name: in-the-ocean/htmlcomparator


text:
# Recipe App

Users can add recipes, view recipes, add photos to recipes and more.  Create a clean UI for users to interact with others recipes and save their favorites

## Features

- [ ] As a User I can see a list of recipes
- [ ] As a User I can see details of a recipe
- [ ] As a User I can add recipes to my favorites list
- [ ] As a User I can create recipes
- [ ] As a User I can add titles, descriptions, ingredients and steps to my recipe
- [ ] As a User I can add a photo to my recipe

repository: Bobleyl/flutter-app-ideas

branch_name: refs/heads/main

repo_name: Bobleyl/flutter-app-ideas


text:
# node-profile-gen

*a command-line application that dynamically generates a PDF profile from a GitHub username.*

Node-profile-gen is a simple Node CLI application that utilizes the Github API to create a brief summary of a user's activity. The application is executed in the terminal. The color of the profile is chosen based on the user's response to a prompt inquiring about their favorite color.
<img width="595" alt="Screen Shot 2019-12-11 at 6 54 16 PM" src="https://user-images.githubusercontent.com/57336277/70674969-3f671080-1c4d-11ea-9d47-38094fc6ad5e.png">

### User Story
As a MANAGER, I want a profile generator so that I can easily prepare reports for stakeholdes.

### Execution
The application is executed by entering the following command into the terminal
```node
node index.js
```
### To do:
* Implement dynamic star count generation.


text:
# Solicitor

Solicitor is small library for feature flags and simple configuration. Feature flags
are a way of controlling the availaibility of features in your application. You
can learn more about the [idea of feature flags](http://code.flickr.net/2009/12/02/flipping-out/).

Your flag names are expected to be in the form of `foo/bar/baz`. The slashes
promote namespacing and lend themselves to clever use in backends.

# Features

* Boolean flags
* Percentage chance (i.e. on for 10% of users)
* Multiple backends
    - Static (for testing and stubbing)
    - HTTP paths with support for multiple, random host pools (e.g. "foo/bar" fetches a value from a example.com/foo/bar)
    - [Typesafe config](https://github.com/typesafehub/config)
    - [Consul](http://www.consul.io/)'s KV [HTTP API](http://www.consul.io/docs/agent/http.html)
    - [Zookeeper](http://zookeeper.apache.org/)

# Status

Solicitor is new and likely has some flaws and missing pieces. Here are some
known TODOs:

* Caching for the HTTP backend
* Ignore comment and empty lines for HTTP backend (documentation in the files is the idea)
* Zookeeper is experimental

# Goals

Solicitor's goals are to enable runtime modification of features in a backend
application or service. You might also be able to use this for front end
decisions if your application can use Scala libaries in it's templates like the
[Play Framework](http://www.playframework.com/).

With the ability to adjust your features on the fly it becomes less necessary
for you to deploy new code for small changes. In addition to just enabling or
disabling a feature you can adjust values by fetching either numeric or string
values from the backend.  Examples:

* Adusting numeric values such as cache durations or concurrency
* Disabling performance features via booleans during problems
* Fetching lists of hosts to use for connecting to other backend services

These are powerful features that, if implemented, can significantly reduce
your time to resolution for production issues by avoiding the latency and
complexity of deployments.

*Note:* This library isn't meant to be configuration for your _entire_ application,
as doing dynamic configuration is really hard. *This is for smaller, critical
values that you can easily reason about being able to change at any time.*

# Types

The content of the response is expected to be
plain text. The following rules are used to interprest the strings into Scala types:

Values | Type | Notes
-------|------|------
true, false | Boolean | Case insensitive
numbers | Double | No special cases for integers
everything else | String! | n/a

## isEnabled and isDisabled

Note that any non boolean value will be considered false by default. Values like
1, 1.0 are not "truthy" in this implementation.

# Defaults

You can also provide defaults in the event that your backend fails to retrieve
a value.

# Backends

Solicitor has pluggable backends that allow you define different ways of retrieving
values.

## HTTP

The HTTP backend uses [Spray's HTTP Client](http://spray.io/documentation/spray-can/http-client/)
to make HTTP requests to url in the form of: `host + "/" + key`.
Therefore if your `host` is `www.example.com` then a request for
`foo/bar` will result in a GET request to `http://www.example.com/foo/bar`.

### Notes

The original idea behind this backend was to expose a simple directory of files.
More specifically, a Git repository of files containing simple values to enable
a combination of simple retrieval and simple auditing of the configuration
information. Git provides history and accountability and hooks can notify
third parties of value changes.

### Example

```scala
import solicitor.Client
import solicitor.backend.HTTP

val solicitor = new Client(
  backend = new HTTP(hosts = Seq(("example.com", 80)))
)
```

## Static

### Example

```
import solicitor.Client
import solicitor.backend.Static

val solicitor = new Client(
  backend = new Static(Map(
    "foo" -> 1,
    "bar" -> true
    "baz" -> "gorch"
  ))
)
```

## Consul

The Consul backend leverages the existing HTTP backend but formats it's requests
to match [Consul's API for KV storage](http://www.consul.io/docs/agent/http.html).

Just like the HTTP backend you can specify multiple hosts. You should do that
to take advantage of Consul's distributed KV.

### Notes

* It is assumed that all values are Base64 encoded UTF-8 strings.
* There is no facility for adding a `dc` parameter to the query. Requests will use the agent's DC as per Consul's documentation.

### Example

```scala
import solicitor.Client
import solicitor.backend.Consul

val solicitor = new Client(
  background = new Consul(hosts = Seq(
    "agent1.example.com", 8500,
    "agent2.example.com", 8500
  ))
)
```

## Zookeeper

The Zookeeper backend uses [Apache Curator](http://curator.apache.org/)'s
[NodeCache](http://curator.apache.org/curator-recipes/node-cache.html) recipe.

### Notes

The data is not guaranteed to be in sync with the store, but will eventually
be as data propogates through the ZK cluster and the NodeCache gets the new
information. Due to latency in establishing the NodeCache the first request for
a key seems to always return a None and therefore your defaults will be important!

### Example
```scala
import solicitor.Client
import solicitor.backend.Zk

val solicitor = new Client(
  background = new Zk(hosts = Seq(
    "zk1.example.com", 2181,
    "zk1.example.com", 2181
  ))
)
```

# Using Solicitor

Here are some examples of common use cases of Solicitor.

## Instantiation

```scala
import solicitor.Client
import solicitor.backend.Static

val solicitor = new Client(
  backend = new Static(Map(
    "foo" -> "true",
    "bar" -> "0.5"
  ))
)
```

## Simple Feature Activation

```scala
if(solicitor.isEnabled("foo")) {
  // Do something!
}

if(solicitor.isDisabled("foo")) {
  // Do something!
}
```

## Percentage Chance of Activation

```scala
if(solicitor.decideEnabled("bar")) {
  // Should happen about 50% of the time!
}
```

## Raw Value Methods

```scala
val t1 = solicitor.getString("baz") // String!

// These methods default to None if unparseable. See Types above.
val t2 = solicitor.getBoolean("bar") // Option[Boolean]
val t3 = solicitor.getDouble("foo") // Option[Double]

// With Defaults
val t4 = solicitor.getBoolean("bar", Some(true)) // Option[Boolean]
val t5 = solicitor.getDouble("foo", Some(100)) // Option[Double]

```

# Testing

Note that tests expect a local HTTP and Consul instance that respond to
queries:

* HTTP: Port 8000, /foo/bar should contain 123
* Consul: KV "poop" should return "butt"

repository: franekrichardson/solicitor

repo_name: franekrichardson/solicitor


text:
# _Programming Language Suggester_

#### _Programming Language Suggester quiz that takes in user's answers and displays which language suits them._

#### By _**Tien Nguyen**_

## Technologies Used
* _HTML5_
* _CSS3_
* _Bootstrap 4.5_
* _jQuery 3.1_

## Description
_This project uses html, CSS, Bootstrap 4.5, and jQuery 3.1 in order to create a quiz that shows the user which programming language they should learn.
 The only question that truly matters is the color to the programming language. For example, blue would be for Python. The other answers from the 5 questions are used to display personal information to the screen, such as greet the user by their first name._

## Setup/Installation Requirements
* _(No installations required.)_
* _Clone the Repo or simply download the repo as a zip._

_If neither option is appeal, please view the live project [here](https://tien96ng.github.io/programming-language-suggester/)!_

## Known Bugs
* _Lacking media breaks for majority of the page._
* _No required input validation to avoid "Null" or "NaN"._
* _Doesn't read the last form value(s) for radio input._
* _If you press the enter key, it'll end the quiz unofficially as submission._

## License
_This software is licensed under the MIT license_

Copyright (c) 2020 __Tien Nguyen__

## Contact Information
_<Tien96ng@github.com>_


text:
# Weather Dashboard

## Assignment
For this assignment I was to create a dashboard for a user that gets weather data for a given city based on a search submission. I used the OpenWeather API for the daily and five day forecast. For the styling of the page I relied on Bootstrap, and really familiarized myself with jQuery.

## Technologies Used
- HTML/CSS
- Bootstrap CSS
- JavaScript
- JQuery
- Web APIs

## Links and Screenshots
[Link to Deployed Website](https://jpeiler97.github.io/weather-dashboard/)

Screenshots:
![Base page](./assets/img/screenshotNoSearch.png)
![Searched weather](./assets/img/screenshotSearch.png)

## Contact Info
E-mail<EMAIL_ADDRESS>LinkedIn: https://www.linkedin.com/in/john-p-eiler/


text:
Cyc Core API Suite CHANGELOG
============================

For more information, view the [README](README.md) bundled with this release or visit the
[Cyc Developer Center](http://dev.cyc.com/api/core/).

**Important note about _backwards-compatibility:_** It is expected that more release candidates will
follow. Until the final 1.0.0 release, it is expected that future release candidates will break
backwards compatibility.

1.0.0-rc3 - 2015-08-14
----------------------

The third release candidate of Cycorp's new Java API suite. 1.0.0-rc3 is _not backwards-compatible_
with earlier releases. Note that _ResearchCyc 4.0q_ and _EnterpriseCyc 1.7-preview_ require
[server code patching](server-patching.md) for compatibility with the 1.0.0-rc3 release.

#### New: Support for upcoming OpenCyc release

Adds support for the planned upcoming release of **OpenCyc 5.0-preview**. Note that the OpenCyc
server will not have support for advanced features such as QuerySearch or ProofViewJustification.
Classes and methods which are not supported by OpenCyc will reflect this in their javadoc
description and in their signature by declaring that they throw a
`com.cyc.session.exception.OpenCycUnsupportedServerException`.

There are no plans to support previous versions of OpenCyc.

#### Improved: Core API Specification

* _Query API_ interfaces moved into CoreAPISpec Maven module.
* Adds the QueryFactory (`com.cyc.query.QueryFactory`) to facilitate query construction.
* Compatibility with different Cyc server editions and versions is now better-documented via the
  `UnsupportedCycOperationException` and `OpenCycUnsupportedFeatureException` exceptions.

#### Other changes

* Speeds up KB API conversion of terms to KBObjects, which in turn speeds up
  `Query#getResultSet()#getKBObject()`. This resolves
  [issue 2](https://github.com/cycorp/CycCoreAPI/issues/2).
* Core API Suite can detect and apply missing SubL code patches to a Cyc server. This behavior is
  disabled by default, but is easily enabled via System properties. See
  [server-patching.md](server-patching.md) for details.
* Links to [Cyc Dev Center](http://dev.cyc.com/) have been modified to reflect improved URL scheme.
* Assorted bug fixes.

1.0.0-rc2 - 2015-04-07
----------------------

The second release candidate of Cycorp's new Java API suite for interacting with the Cyc inference
engine and knowledge base. Note that 1.0.0-rc2 is _not backwards-compatible_ with earlier releases.

#### New: Core API Suite Bundle

Adds the Core API Suite Bundle module (artifact `cyc-core-suite` in the `CoreAPISuite` subdir) which
packages all API interfaces and implementation classes. Details:

* Produces a single `cyc-core-suite` artifact which can be specified instead of individually
  specifying cyc-session, cyc-kb, etc.
* Builds a single jar (in maven parlance, an "uberjar") which contains all of its dependencies.
  Useful for some environments where it is complicated to pull binaries down from the Internet.

#### New: Core API Specification

Adds the Core API Specification module (artifact `cyc-core-api` in the `CoreAPISpec` subdir) to
consolidate and clarify the interfaces which define the Core API Suite. Details:

* _KB API_ interfaces moved into CoreAPISpec.
* _Session API_ interfaces moved into CoreAPISpec.

#### Other changes

* Fixes tests which were failing against EnterpriseCyc.
* Changes parent pom artifactId from `cyc-core-api` to the more accurate `cyc-core-parent`.
* KB API test suite should no longer seem to hang per
  [issue 1](https://github.com/cycorp/CycCoreAPI/issues/1).
* Updates developer email address in pom files to one which people can actually send mail to.
* Assorted updates in pom files to name and description elements.

1.0.0-rc1 - 2015-01-04
----------------------

First release candidate of Cycorp's new Java API suite for interacting with the Cyc inference engine
and knowledge base. Note that 1.0.0-rc1 is _not backwards-compatible_ with earlier releases.

Details:

* Updates the **KB API** (`1.0.0-rc1`), which streamlines the manipulation of CycL-based Java
  objects.
* Updates the **Query API** (`1.0.0-rc1`), which streamlines asking queries and handling answers.
* Introduces the **Session API** (`1.0.0-rc1`), which manages configurations and connections to
  Cyc servers.
* Replaces the Base API with the **Base Client** (`1.0.0-rc1`), a Java client for connecting to a
  Cyc server and handling HL data.
  _Note that the Base Client is subject to frequent change, and so is not supported for external
  developers._

1.0.0-Preview - 2014-07-09
--------------------------

Initial limited preview release! This is a new Java API suite to manipulate and query the Cyc KB.

Details:

* Introduces the **KB API**, which streamlines the manipulation of CycL-based Java objects.
* Introduces the **Query API**, which streamlines asking queries and handling answers.
* Introduces the **Base API**, the successor to the OpenCyc API.


text:
Visit http://simvascular.github.io/docsCompile.html for compilation instructions:

[![Build Status](https://travis-ci.org/SimVascular/svSolver.svg?branch=master)](https://travis-ci.org/SimVascular/svSolver)

The source code in this repository currently uses an input solver file that is incompatible with the format of the solver file produce by the SimVascular **SV FSI** tool. The SimTK svFSI installers are compatible with the  SimVascular **SV FSI** tool format but use an older version of svFSI.

repository: CAD-Team/svFSI

repo_name: CAD-Team/svFSI


text:
#PIP blacklist
-----------------------
Starting with version 0.7.5, StaSh pip includes a blacklist.

It indicates whether a package should not be installed and what reasons
should be given.

## Motivation

The reason for this blacklist is the high number of issues regarding
installation problems of known incompatible packages. I hope that by
slowly adding packages to the blacklist we can reduce the amount of
these issues.

The blacklist was initially discussed in issue #376.

## Details
This blacklist is stored as a JSON file at `$STASH_ROOT/data/pip_blacklist.json`.
It is a dict with two top-level keys:

**`reasons`** Is a dict mapping a reasonID (str) to a message (str).
It is used to reduce redundancy of error messages.

**`blacklist`** Is a dict mapping packagename (str) to details (list).
Every package mentioned in a key of the dict is considered blacklisted.

The first (`i=0`) element of the list is the reasonID (str). Use the `reasons` toplevel
key to determine the actual reason.

The second (`i=1`) element of the list is a bool indicating whether this
blacklisting is fatal. If true, it is considered fatal. This means that
`pip` should abort the installation. Otherwise it is considered nonfatal.
This means that `pip` should skip the installation, but continue the install.
This is useful if the package can not be installed, but Pythonista already
bundles the module.

The third (`i=2`) is either `null`/`None` or a string. If it is a string
and the package is marked non-fatal, use this string as the packagename instead.
In this case, requested extras and version specifier are discarded.

gha_language: Python


text:
# [Dog Breed Picker](http://alexa.amazon.com/#skills/amzn1.ask.skill.d3ccdf1e-631f-4328-9317-f48829362ad0)
![3.5 stars](../../images/ic_star_black_18dp_1x.png)![3.5 stars](../../images/ic_star_black_18dp_1x.png)![3.5 stars](../../images/ic_star_black_18dp_1x.png)![3.5 stars](../../images/ic_star_half_black_18dp_1x.png)![3.5 stars](../../images/ic_star_border_black_18dp_1x.png) 2

To use the Dog Breed Picker skill, try saying...

* *Alexa Open dog breed picker*

This skill is a quiz, where it asks users questions, helping them pick a dog breed. It then gives them information on that breed, if requested.

***

### Skill Details

* **Invocation Name:** dog breed picker
* **Category:** null
* **ID:** amzn1.ask.skill.d3ccdf1e-631f-4328-9317-f48829362ad0
* **ASIN:** B01LWP3TUU
* **Author:** Hoegen Developments
* **Release Date:** October 4, 2016 @ 03:12:15
* **In-App Purchasing:** No


text:
# Kotlin Barcode Reader for Windows

The sample demonstrates how to create a command line barcode reader using Kotlin on Windows.

## Prerequisites
* [Dynamsoft Barcode Reader][1]
* [IntelliJ IDEA Community][2]

## Getting Started
1. Open **IntelliJ IDEA Community**, and import the source code to Kotlin project.
2. Press **Ctrl + Shift + Alt + S** to open project structure. Click **Libraries** to add **com.dynamsoft.barcode.jar**.
3. Run the project.

## Blog
[Building Kotlin Barcode Reader on Windows][3]

[1]:http://www.dynamsoft.com/Downloads/Dynamic-Barcode-Reader-Download.aspx
[2]:https://www.jetbrains.com/idea/download/#section=windows
[3]:http://www.codepool.biz/building-kotlin-barcode-reader-windows.html

repository: dynamsoft-dbr/kotlin-windows

repo_name: dynamsoft-dbr/kotlin-windows


text:
---
layout: default
title: Modeling Snippets
---

[Catalog of Explanation Types](#explanationtypes) | [Modeling of Explanation Types](#modelingexplanations)

<content>

Explanation Types

In this section, we show how our Explanation Ontology can be used to represent the generational needs of different explanation types we identified from our literature review. For more details about our explanation types itself, refer to our paper submission. In this website we present modeling snippets that use classes and properties from our ontology.

<content>

Catalog of Explanation Types

We identified nine explanation types, each with different foci and generational needs, from a literature review we conducted in the computer science and adjacent explanation science domains of philosophy and social sciences. Utilizing the schema provided by our explanation ontology, we can encode the generational needs of these explanation types as OWL restrictions. Below for each explanation type, we present our description, a prototypical question they can address in a clinical setting and the logical formalization of the explanation type. The explanation types are:

    Explanation Type

Case Based

Contextual

Contrastive

Counterfactual

Everyday

Scientific

Simulation Based

Statistical

Trace Based

 Explanation Types

We depict logical formalization of our encoding of the generational needs for explanation type in Manchester OWL syntax, in that classes in the OWL restriction are referred to via their labels, and the color highlights are similar to those that can be viewed in Protege. These logical formalizations presented against the OWL restrictions label for each explanation type are a representation of the sufficiency conditions mentioned before the restrictions.

Case Based Explanation	Top

 Definition: Provides solutions that are based on actual prior cases that can be presented to the user to provide compelling support for the system’s conclusions, and may involve analogical reasoning, relying on similarities between features of the case and of the current situation.

Prototypical Question: To what other situations has this recommendation been applied?

Sufficency Condition:
Is there at least one other prior `case' similar to this situation that requires an `explanation'?
Is there a similarity between this case, and that other case?

 OWL Restriction:

     isBasedOn some
    (Explanation
     and (isBasedOn some
        ('System Recommendation'
         and (prov:wasGeneratedBy some
            ('Artificial Intelligence Task'
             and ('has input' some 'Object Record'))))))

Contextual Explanation	Top

 Definition: Refers to information about items other than the explicit inputs and output, such as information about the user, situation, and broader environment that affected the computation.

Prototypical Question: What broader information about the current situation prompted the suggestion of this recommendation?

Sufficency Condition:
Are there any other extra inputs that are not contained in the `situation' description itself? <br/> And by including those, can better insights be included in the `explanation'?

 OWL Restriction:

     (
     (isBasedOn some
    ('Contextual Knowledge'
     and ('in relation to' some Situation)))
     or
     (isBasedOn some ('Contextual Knowledge'
     and ('in relation to' some  'Object Record'))))
 and (isBasedOn some  'System Recommendation')

Contrastive Explanation	Top

 Definition: Answers the question “Why this output instead of that output,” making a contrast between the given output and the facts that led to it (inputs and other considerations),  and an alternate output of interest and the foil (facts that would have led to it).

Prototypical Question: Why drug A over drug B the one I am typically prescribed?

Sufficency Condition:
Is there a `system recommendation' that was made let’s call it A)? <br/> What `facts' led to it?
 Is there another `system recommendation' that could have happened or did occur, (let’s call it B)? <br/> What was the `foil that led to B?
 Can A and B be compared?

 OWL Restriction:

    (isBasedOn some
    ('System Recommendation'
     and (used some Fact)))
 and
 (isBasedOn some
    ('System Recommendation'
     and (used some Foil)))

Counterfactual Explanation	Top

 Definition:Addresses the question of what solutions would have been obtained with a different set of inputs than those used.

Prototypical Question: What if input A was over 1000?

Sufficency Condition:
Is there a different set of inputs that can be  considered?
 If so what is the alternate `system recommendation'?

 OWL Restriction:

    isBasedOn some
    ('System Recommendation'
     and (used some
        (Knowledge
         and ('in relation to' some 'Object Record'))))

Everyday Explanation	Top

 Definition:Uses accounts of the real world that appeal to the user, given their general understanding and knowledge.

Prototypical Question:Why does Option A make sense?

Sufficency Condition:
Can accounts of the real world be simplified to appeal to the user based on their general understanding and `knowledge'?

 OWL Restriction:

    (
((isBasedOn some
    (Situation
     and ('in relation to' some User))) or (isBasedOn some
    ('Experential Knowledge'
     and ('in relation to' some  User))))
 and (isBasedOn some 'System Recommendation'))
or
(isBasedOn some
    ('System Recommendation'
     and ((used some
        (Situation
         and ('in relation to' some User))) or (used some
        ('Experential Knowledge'
         and ('in relation to' some User)))))
)

Scientific Explanation	Top

 Definition:References the results of rigorous scientific methods, observations, and measurements.

Prototypical Question: What studies have backed this recommendation?

Sufficency Condition:
Are there results of rigorous `scientific methods' to explain the situation? <br> Is there `evidence' from the literature to explain this `situation'?

 OWL Restriction:

    (
(isBasedOn some 'System Recommendation')
 and (isBasedOn some
    ('Scientific Knowledge'
     and ((wasGeneratedBy some study) or (wasGeneratedBy some 'Scientific Method')))))
or
(isBasedOn some
    ('System Recommendation'
     and (used some
        ('Scientific Knowledge'
         and ((wasGeneratedBy some study) or (wasGeneratedBy some 'Scientific Method')))))
)

Simulation Based Explanation	Top

 Definition:Uses an imagined or implemented imitation of a system or process and the results that emerge from similar inputs.

Prototypical Question: What would happened if this recommendation is followed?

Sufficency Condition:
Is there an `implemented' imitation of the `situation' at hand?
 Does that other scenario have inputs similar to the current `situation'?

 OWL Restriction:

    isBasedOn some
    ('System Recommendation'
     and (wasGeneratedBy some
        ('AI Task'
         and ('has input' some
            ('Object Record'
             and (hasSetting some Situation))))))

Statistical Explanation	Top

 Definition:Presents an account of the outcome based on data about the occurrence of events under specified (e.g., experimental) conditions. Statistical explanations refer to numerical evidence on the likelihood of factors or processes influencing the result.

Prototypical Question: What percentage of people with this condition have recovered?

Sufficency Condition:
Is there `numerical evidence'/likelihood account of the `system recommendation' based on data about the occurrence of the outcome described in the recommendation?

 OWL Restriction:

     isBasedOn some
    ('System Recommendation'
     and (used some
        ('Numerical Evidence'
         and ('in relation to' some 'Object Record'))))

Trace Based Explanation	Top

 Definition:Provides the underlying sequence of steps used by the system to arrive at a specific result, containing the line of reasoning per case and addressing the question of why and how the application did something.

Prototypical Question:What steps were taken by the system to generate this recommendation?

Sufficency Condition:
Is there a record of the underlying sequence of steps (`system trace') used by the `system' to arrive at a specific `recommendation'?

 OWL Restriction:

     isBasedOn some
    ('System Recommendation'
     and (wasGeneratedBy some
        ('AI Task'
         and (used some
            (('Decision Tree' or 'Knowledge based Systems')
             and ('has output' some 'System Trace'))))))

 </content>


text:
---
title: TrunkMetricsOptions
---

:::error
**The Ruby SDK is deprecated as of 9/16/2020**

The Genesys Cloud Ruby SDK (v96.0.0) will be frozen at its current version level. Any new enhancements to our API or bug fixes will not be backported. If you do need to take advantage of new features or bug fixes outside the Genesys Cloud Ruby SDK, you will need to use the Genesys Cloud REST endpoints directly. More information can be found in the [Official Announcement](https://developer.mypurecloud.com/forum/t/announcement-genesys-cloud-ruby-sdk-end-of-life/8850).
:::

## PureCloud::TrunkMetricsOptions

## Properties

|Name | Type | Description | Notes|
|------------ | ------------- | ------------- | -------------|
| **proxy_address** | **String** | Server proxy address that this options array element represents. | [optional] |
| **option_state** | **BOOLEAN** |  | [optional] |
| **option_state_time** | **DateTime** | ISO 8601 format UTC absolute date & time of the last change of the option state. | [optional] |
| **error_info** | [**TrunkErrorInfo**](TrunkErrorInfo.html) |  | [optional] |
{: class="table table-striped"}

repository: MyPureCloud/platform-client-sdk-ruby

gha_language: Ruby

repo_name: MyPureCloud/platform-client-sdk-ruby


text:
# pickadate

> A Vue.js project, imitation of [ufr.ee](http://ufr.ee).

## Build Setup

``` bash
# install dependencies
npm install

# serve with hot reload at localhost:8080
npm run dev

# build for production with minification
npm run build
```

For detailed explanation on how things work, consult the [docs for vue-loader](http://vuejs.github.io/vue-loader).

repository: sevtdy/pickadate

repo_name: sevtdy/pickadate


text:
# .linux
common linux settings

# How-to
* Add the following in ~/.inputrc
```
$include ~/.dotfiles/inputrc
```
* Add the following in ~/.bashrc
```
source ~/.dotfiles/bashrc
```
* Add the following in ~/.vimrc
```
set runtimepath^=~/.dotfiles
runtime vimrc
```


text:
# Uplift Web-App Final
---------------
#
#
##### Uplift is a web-app accessibility utility developed using Postgres, Express, React, Node.js, and Jade.
##### The goal of the tool is to allow users to crowdsource data about additional assistive technologies offered by some businesses that aren't easily searchable for on other business/service-finding platforms.

### -> [Presentation](https://docs.google.com/presentation/d/1AnS7UKOgewBZthfMQ196KKfspe2wqifWNJBRXldT-3g/edit#slide=id.g723630543_3_0) <-

### Apis
---------------
#
#
##### To source the majority of the data in the first build of the project I'll be relying on User input, but have so far been able to provide some initial data for hotel chains in other countries that provide Hoyer Lifts on-site for guests who cannot transfer out of their chairs on their own.
#
### Apis that will be utilized during the first build:
##### 1. **Auth0** for user sign-up and log-in
##### 2. **Mapbox: Static Images** for individual business page maps
##### 3. **Mapbox: Static Tiles** where multiple businesses appear close to each other in intial search
#
#
#
### Wireframes
--------------
##### These are a few wireframes of page templates I want to use after deploying the app
#
#
### **Homepage**
---------------

#
#
### **User Sign-Up**
----------------

#
#
### **Business Page Template**
----------------

#
#
### **User Profile Template**
----------------

# *Under Construction*
#

repository: yjwangit/Uplift

repo_name: yjwangit/Uplift


text:
## Montecarlo randomization + Genetic Algorithm
- Find optimal paths given a fitness function, compare function,  and filter function
- Optimized for high memory usage and fast completion time
___

### What is this?
- This is an algorithm for finding optimimal 'paths' given constraints
- For example:
```
0,1,2,5
0,1,1,3
0,0,2,3
-1,1,2,3
```
- Given this, we can write a fitness function to optimize for highest value, and a restriction that the values must be descending
- The optimal path here would be `3, 3, 2, 1`
- This optimal path would have a fitness value of `5+3+2+1` or `11`
___
### How does it work?
- This uses a combination of Montecarlo Randomization and genetic algorithms to find an optimal path.
- Filters are calculated and stored before the genetic algorithm is run to save time
- A working path is found through bruteforce to use as the original parent for all groups
- Children are have slight variations from parent
- Best child is chosen to become a parent
___
### Uses
- I plan to implement this in my course scheduling algorithm to decrease schedule generation times to under 1 second, and to reduce memory usage
___
### Learn More
http://beta.aceparent.me/#/montecarlotree


text:
---
title: A Look At How I Structured My Blog With FW/1
path: /a-look-at-how-i-structured-my-blog-with-fw-1
date: 2013-08-07
summary: A Look At How I Structured My Blog With FW/1
tags: ["ColdFusion", "CFML", "FW1"]
---

#### Note: This post is outdated based on how FW/1 and my structuring practices have evolved. While there may be some take-away from the article, I don't consider this a solid FW/1 structure anymore.

It's been a hot minute since I last posted anything. Today I wanted to touch more on how I use Framework One with my blog; since my last post - [SES URLs In FW/1 with Routes and Apache Mod_Rewrite](http://tonyjunkes.com/blog/ses-urls-in-fw1-with-routes-and-mod-rewrite).

A word to the wise, I am not wise. I'm still grasping a mix of methodologies in building a solid application along with Framework One. I am always open to suggestions or being asked - WTF are you doing that for?

If you are not familiar with Framework One, I highly recommend checking out the FW/1 [Developing Applications Manual](https://github.com/framework-one/fw1/wiki/Developing-Applications-Manual) and [Reference Manual](https://github.com/framework-one/fw1/wiki/Reference-Manual).

So let's rip apart and take a look at some example directory structures I commonly use. Some of these files and directories are pretty straight forward but I'll go over every one in some detail.

## The Root Level

```md
| ROOT
|--- /assets
|--- /org
|--- /app
|--- Application.cfc
|--- index.cfm
|--- .htaccess
```

#### /org

This is where framework.cfc, the entire code base for FW/1, is kept.

#### Application.cfc

The Application.cfc at the root is the base file to my entire application; that extends FW/1 and sets a variety of application scope variables, FW/1 specific vars, request, session and error handling.

Here's a very plain look at some of what I use in the Application.cfc

```java
component extends="org.corfield.framework"
  output="false"
{
  /****
  NOTE This is very plain structure with not a lot of drop in ready code as it's here to show structure.
  ****/

  //This mapping is for including pod like apps into a page.
  THIS.mappings["/modules"] = ExpandPath("./path/to/modules");
  //The classes dir is for any extra Java bits for the app. For example - I use BCrypt sometimes.
  THIS.javaSettings = {LoadPaths = ["./path/to/classes"], watchExtensions = "class"};

  //For more on FW/1s framework vars see https://github.com/framework-one/fw1/wiki/Reference-Manual
  VARIABLES.framework = {
	base = "/app",
  	action = 'page',
	usingSubsystems = true,
	defaultSubsystem = 'public',
	siteWideLayoutSubsystem = 'common',
  	generateSES = true,
  	SESOmitIndex = true,
  	reload = 'refresh',
  	password = 'password',
  	routes = [
   		//FW/1 Routes
		{ "/section/parameter/:parameter" = "/section/item/parameter/:parameter" }
	]
  };

  public function setupApplication() {
  	//Application Scope Vars
  }

  public function setupRequest() {
	//OnRequest handling.
  }

  public function setupSession() {
	//OnSessionStart handling.
  }

  public function onMissingView(struct rc = {}) {
	//Handle views/pages that do not exist. 404 handling etc.
  }

  public void function onError(any exception, string event) {
	//error handling.
  }
}
```

#### index.cfm

This is a blank file used by the framework. All requests and output is routed through this file.

#### /assets

This is where I break down dirs for CSS, JavaScript and Site-wide Image files.

#### .htaccess

Any URL rewrites that I don't handle in the Application.cfc are handled here using Apache Mod_Rewrite.

#### /app

This is the heart of my application. I like to set the base location in FW/1 to another directory (like so) to separate the innards of the application from the main level where site-wide content may be held (assets, Sitemap.xml etc.). My public files, admin, helper files and CFCs are all kept in this directory.

## The Framework One Base Location - /app

```md
| /app
|--- .htaccess
|--- /admin
|--- /public
|--- /classes
|--- /models
|--- /modules
|--- /common
|--- /utils
```

#### .htaccess

I use this file simply to apply a deny-all to restrict access to the /app directory from a browser.

#### /public & /admin

These are both Framework One Subsystems. Subsystems work as mini apps within the entire application. I define /public to be the default base location for FW/1 to look for controllers and views for displaying public content via the root Application.cfc. Both directories contain /controllers and /views folders, where sub-folders are kept within those, pertaining to given pages and actions. In the case of /admin, this area and all of the website pages referenced to it are locked behind the requirement of user authentication.

#### /common

When Subsystems are active in FW/1, the /common directory acts as a shared base for layouts used through the application. The /layouts sub-folder houses a default.cfm that contains the HTML for my site-wide design of the blog.

#### /classes

This is where I keep any Java classes I might use with the application. For example, I use BCrypt a lot; though I've added that to the server class path so it's globally accessible by all of my website applications. All class files are dynamically loaded in via THIS.javaSettings in the Application.cfc.

#### /models

The /models directory is a series of sub-folders housing the logic of the application in different forms. First, a "domains" dir for CFCs that hold the structure logic of any objects created from database tables. These objects consist of properties that relate to the table columns and represent the shell to be filled by a service etc. Next, a "services" dir that holds CFCs with a assortment of functions used by the controllers to accomplish a request; be it conversions, data requests etc. This leads to the "gateways" dir which contains CFCs that act as makeshift DAOs for CRUD and data retrieval. The gateways are the only objects that touch the database.

The /models directory is a work in progress as I am doing a messy play of OO and basing inspiration from other frameworks like Grails. I've also started to throw in some dependency injection as I've built up so many services that are tying to the database and others that are merely helper functions. Some structured management would help.

#### /modules

This is where I keep widget like apps or pods. For example I have modules for retrieving content and creating the display structure to the "recent articles" and "recent comments" in the sidebar. This separates them nicely so that I can include them more or less anywhere. This directory is mapped for the application from THIS.mappings in the Application.cfc.

#### /utils

As typically used, I keep utility functions and CFCs here. For example I have components for form validation, formatting etc.

## There we have it ;)

That's a rough idea on how I've laid out the overall structure of the blog. So much of it has been rigged together though that I change and re-factor constantly. For the better. I didn't touch on much code but this structure is what helps the application make sense and flow so far. Hopefully this gives some ideas or direction on how to take your FW/1 app. As I progress, I definitely want to follow up with some code examples. I just haven't crossed anything that seemed worthy.

Cheers.

gha_language: Vue


text:
# vim-bash

`vim-bash` is filetype plugin for bash.
Only works with the latest version of vim8.

## Features

* Run for current buffer in terminal with function `term_start()`
  * Currently, only vertical split is supported.
* Contain snippets for [vim-vsnip][3]

## Concept

* Recommended to use with the following plugins
  * [vim-lsp][1]
  * [bash-language-server][2]
* out-of-the-box

## Usage

Works without settings.
Provides default mapping for `<Plug>(vim-bash-run)` to `<LocalLeader>r` in bash filetype.

If you want to apply your own mapping, please do as follows.

```vim
let g:vim_bash_disable_default_mapping = 1
augroup vim_bash
  au!
  autocmd FileType sh nmap <silent><buffer> mr <Plug>(vim-bash-run)
augroup END
```

## Settings

| key                                  | Description                               | default |
|--------------------------------------|-------------------------------------------|---------|
| `g:vim_bash_term_size`               | Number of output-buffer zize              | 80      |
| `g:vim_bash_disable_default_mapping` | Set to `1` to disable the default mapping | 0       |

## License

[MIT](LICENSE)

[1]: https://github.com/hrsh7th/vim-vsnip
[2]: https://github.com/prabirshrestha/vim-lsp
[3]: https://github.com/bash-lsp/bash-language-server

repository: halkn/vim-bash

repo_name: halkn/vim-bash


text:
---
layout: post
title: Week 2
---

## June 8 to June 11 ##

### June 8 2021 ###
I had a meeting with Dr. Short regarding my research project for the internship. My interest in research lies very closely with Hang and Jindan's interest. The suggestion was to create research that could help benefit both of them.

Since Hang's research lies closely with finding a solution to avoid giving binary feedback to a robot after completing a task.
  * **Binary feedback** means instead of just saying right and wrong. The researcher gives tips and tricks on how the robot can improve its chance of completing a task correctly

Jindan's research focused on being able to track human interaction with a robot. Then take each human feedback and emulate it into a robot.

My mentor and I decided to focus my research on how different lengths of time with humans and robots can affect the feedback in reinforcement learning. The research that I will be conducting will help benefit both Jindan and Hang's research.

### June 9 2021 ###
I had a meeting with James (PhD. student at Tufts University) to learn more about his field of research. His researches specialize in being able to have the robots be able to know if the human is paying attention to them. This research applies in multi-robot scenarios! It's interesting how there are so many possibilities in research in robotics and machine learning.

Afterward, I did some research to learn more about how human feedbacks can sometimes be a flaw in learning more about human-robot interaction.

### June 10 2021 ###

After reading some more papers on human-robot interaction and reinforcement learning, I wrote a little bit of the introduction to help me get started. I also did some more python practice through [hackerrank](https://www.hackerrank.com/). I recommend this website for practicing coding, algorithms, interview questions, and data structures!

### June 11 2021 ###

I did some outline of articles I wanted to use for my paper. Then also wrote in the blog as well. That is the end of my second week at Tufts University! I'm really exctied to be able to focus more on my research!

gha_language: SCSS


text:
---
layout: post
title: Ruby Page Objects for Capybara Connoisseurs
date: 2015-10-26 04:29:10 +0100
comments: true
sharing: true
published: true
categories: [Ruby, Rails, thoughtbot, TDD, BDD, Test-Driven-Design, RSpec, Factory Girl]
---

{% img /images/Page_Objects/capybara_bigger.png %}

### Topics

+ Acceptance test / feature specs
+ Different types of Page Objects
+ What are Page Objects
+ When and why?
+ How?

+ ### What are Page Objects?

I’ll give you the short pitch first. Its a design pattern to encapsulate markup and page interactions—specifically to refactor your feature specs. Its a combination of a two very common refactoring techniques: *Extract class* and  *Extract method*—which don’t have to happen at the same time because you can gradually build up to extracting a whole class via a new Page Object.

This technique offers you to write high-level feature specs that are very expressive and DRY. In a way they are acceptance tests with application language. You might ask, aren’t specs written with Capybara already high-level and expressive? Sure, for developers who write code on a daily basis, Capybara specs read just fine. Are the DRY out of the box? Not really—actually, certainly not!

``` ruby
feature 'M creates a mission' do
  scenario 'successully' do
    sign_in_as<EMAIL_ADDRESS>
    visit missions_path
    click_on     'Create Mission'
    fill_in      'Mission Name',  with: 'Project Moonraker'
    click_button 'Submit'

    expect(page).to have_css 'li.mission-name', text: 'Project Moonraker'
  end
end
```

``` ruby
feature 'M marks mission as complete' do
  scenario 'successfully' do
    sign_in_as<EMAIL_ADDRESS>
    visit missions_path
    click_on     'Create Mission'
    fill_in      'Mission Name', with: 'Octopussy'
    click_button 'Submit'

    within "li:contains('Octopussy')" do
      click_on 'Mission completed'
    end

    expect(page).to have_css 'ul.missions li.mission-name.completed', text: 'Octopussy'
  end
end
```

When you look at these examples of feature specs, where do you see opportunities to make this read better and how could you extract information to avoid duplication? Also, is this high-level enough for easy modeling of user stories and for non-technical stakeholders to understand? In my mind, there are a couple of ways to improve this and to make everybody happy—developers who can avoid fiddling with the details of interacting with the DOM while applying OOP and other non-coding team members having no trouble jumping between user stories and these tests. The last point is nice to have for sure, but the most important benefits come mostly from making your DOM-interacting specs more robust.

Encapsulation is the key concept with Page Objects. When you write your feature specs you’ll benefit from a strategy to extract the behaviour that is driving through a test flow. For quality code you want to capture the interactions with particular sets of elements on your pages—especially if you stumble upon repeating patterns. As your application grows, you want / need an approach that avoids spreading that logic all over your specs.

”Well isn’t that overkill? Capybara reads just fine!” you say? Ask yourself:
Why wouldn’t you have all the HTML implementation details in one place while having more stable tests? Why shouldn’t UI interaction tests have the same quality as tests for application code?  Due to everyday changes, your Capybara code is vulnerable when spread all over—it introduces possible breakpoints. Let’s say a designer wants to change the text on a button. No biggie right, but do you want to adapt to that change in one central wrapper for that element in your specs or do you prefer to do that all over the place? I thought so!

There are many refactorings possible for your feature specs but Page Objects offer the cleanest abstractions for encapsulating user facing behaviour for pages or more complex flows. You don’t have to simulate the whole page(s) though—focus on the essential bits that are necessary for user flows. No need to overdo it!

+ ### Acceptance Tests / Feature Specs

Before we move on to the heart of the matter, I’d like to take a step back for people new to the whole testing business and clear up some of the lingo that is important in this context. People more familiar with TDD won’t miss much if they skip ahead.

What are we talking about here? Acceptance testing usually comes in at a later stage of projects to evaluate if you have been building something of value for your users, product owner, or whatever stakeholder.  Its sort of a check if the requirements are being met or not. There is something like a pyramid for all sorts of testing layers and acceptance tests are near the very top. Because this process includes often non-technical folks, a high-level language for writing these tests is a valuable asset to communicate back and forth.

Feature specs on the other hand, are a bit lower in the testing food chain. A lot more high-level than unit tests which focus on the technial details and business logic of your models, feature specs describe flows on and in between your pages. Tools like [Capybara](http://jnicklas.github.io/capybara/) help you to avoid doing this manually—meaning that you rarely have to open your browser to test stuff manually. With these kinds of tests we like to automate these tasks as much as possible and test drive the interaction through the browser while writing assertions against pages. Btw, you don’t use **get**, **put**, **post** or **delete** like with request specs.

Feature specs are very similar to acceptance tests—sometimes I feel the differences are too blurry to really care about the terminology. You write tests that exercise your whole application which often involves a multi-step flow of user actions. These interaction tests show if your components work in harmony when they are brought together. In Ruby land, they are the main protagonist when we’re dealing with Page Objects. Feature specs themselves are already very expressive but they can be optimized and cleaned up by extracting their data, behaviour and markup into (a) separate classe(s). I felt clearing up this blurry terminology will help you see that having Page Objects is a bit like doing acceptance level testing while writing feature specs.

### Capybara

Maybe we should go over this really quickly as well. This library describes itself as an “Acceptance test framework for web applications”. You can simulate user interactions with your pages via a very powerful and convenient domain-specific language. In my personal opinion, RSpec paired with Capybara offers atm the best way to write your feature specs. It lets you visit pages, fill in forms, click on links and buttons, look for markup on your pages and you are able to easily combine all kinds of these commands to interact with your pages through your tests.

You basically can avoid opening the browser yourself to test this stuff manually most of the time—which is not only less elegant but also a lot more time consuming and error-prone. Without this tool, the process of “Outside-in-testing”–you drive your code from high-level tests down into your unit-level tests—would be a lot more painful and possibly therefore more neglected. In other words you start writing these feature tests which are based on your user stories and from there you go down the rabbit whole until your unit tests provide the coverage your feature specs needed. After that, when your tests are green of course, the game starts anew and you go back up to continue with a fresh feature test.

+ ### How?

Let’s look at two simple examples of feature specs that lets M create classified missions which can then be completed. In the markup, you have a list of missions and a successful completion creates an addtional class **completed** on the **li** of that particular mission. Straightforward stuff right? As a first approach, I started with small, very common refactorings that extract common behaviour into methods.

**spec/features/m_creates_a_mission_spec.rb**

``` ruby
require 'rails_helper'

feature 'M creates mission' do
  scenario 'successfully' do
    sign_in_as<EMAIL_ADDRESS>
    create_classified_mission_named 'Project Moonraker'

    agent_sees_mission              'Project Moonraker'
  end

  def create_classified_mission_named(mission_name)
    visit missions_path
    click_on     'Create Mission'
    fill_in      'Mission Name', with: mission_name
    click_button 'Submit'
  end

  def agent_sees_mission(mission_mame)
    expect(page).to have_css 'li.mission-name', text: mission_name
  end

  def sign_in_as(email)
    visit root_path
    fill_in      'Email', with: email
    click_button 'Submit'
  end
end
```

**spec/features/agent_completes_a_mission_spec.rb**

``` ruby
require 'rails_helper'

feature 'M marks mission as complete' do
  scenario 'successfully' do
    sign_in_as<EMAIL_ADDRESS>
    create_classified_mission_named 'Project Moonraker'
    mark_mission_as_complete        'Project Moonraker'

    agent_sees_completed_mission    'Project Moonraker'
  end

  def create_classified_mission_named(mission_name)
    visit missions_path
    click_on     'Create Mission'
    fill_in      'Mission Name', with: mission_name
    click_button 'Submit'
  end

	def mark_mission_as_complete(mission_name)
    within "li:contains('#{mission_name}')" do
      click_on 'Mission completed'
    end
  end

  def agent_sees_completed_mission(mission_name)
    expect(page).to have_css 'ul.missions li.mission-name.completed', text: mission_name
  end

  def sign_in_as(email)
    visit root_path
    fill_in      'Email', with: email
    click_button 'Submit'
  end
end
```

Although there are other ways of course to deal with stuff like **sign_in_as**, **create_classified_mission_named** and so on, its easy to see how fast these things can start to suck and to pile up. UI related specs often don’t get the OO treatment they need / deserve I think. They have the reputation of providing too little bang for the buck and of course developers are not most fond of times when they have to touch markup stuff much. In my mind, that makes it even more important to DRY these specs up and make it fun to deal with them by throwing in a couple of Ruby classes.

Let’s do a little magic trick where I hide the Page Object’s implementation for now and only show you the end result applied to the feature specs above:

**spec/features/m_creates_a_mission_spec.rb**

``` ruby
require 'rails_helper'

feature 'M creates mission' do
  scenario 'successfully' do
    sign_in_as<EMAIL_ADDRESS>    visit missions_path
    mission_page = Pages::Missions.new

    mission_page.create_classified_mission_named 'Project Moonraker'

    expect(mission_page).to have_mission_named   'Project Moonraker'
  end
end
```

**spec/features/agent_completes_a_mission_spec.rb**

``` ruby
require 'rails_helper'

feature 'M marks mission as complete' do
  scenario 'successfully' do
    sign_in_as<EMAIL_ADDRESS>    visit missions_path
    mission_page = Pages::Missions.new

    mission_page.create_classified_mission_named         'Project Moonraker'
    mission_page.mark_mission_as_complete                'Project Moonraker'

    expect(mission_page).to have_completed_mission_named 'Project Moonraker'
  end
end
```

Doesn’t read too bad huh?  Your extracted methods do this kind of dirty work now and that way [**Shotgun surgery**](https://en.wikipedia.org/wiki/Shotgun_surgery) is not your problem anymore. Put differently, you encapsulate most of the noisy, down in the weeds DOM interacting code. Gotta say though, sometimes intelligently extracted methods in your feature specs are sufficient and read a bit better since you can avoid dealing with Page Object instances. Anyway, let’s take a look at the implementation:

**specs/support/features/pages/missions.rb**

``` ruby
module Pages
  class Missions
    include Capybara::DSL

    def create_classified_mission_named(mission_name)
      click_on     'Create Mission'
      fill_in      'Mission name', with: mission_name
      click_button 'Submit'
    end

    def mark_mission_as_complete(mission_name)
      within "li:contains('#{mission_name}')" do
        click_on 'Mission completed'
      end
    end

    def has_mission_named?(mission_name)
      mission_list.has_css? 'li', text: mission_name
    end

    def has_completed_mission_named?(mission_name)
      mission_list.has_css? 'li.mission-name.completed', text: mission_name
    end

    private

    def mission_list
      find('ul.missions')
    end
  end
end
```

What you see is a plain old Ruby object—Page Objects are in essence very simple classes really. Normally you don’t instantiate Page Objects with data (when the need occurs you can of course) and you create mostly a language via the API that a user or a non-technical stakeholder on a team might use. When you think about naming your methods, I think its good advice to ask yourself the question: How would a user describe the flow or the action taken?

I should maybe add that without including Capybara the music stops pretty fast.

``` ruby
include Capybara::DSL
```

You probably wonder how these custom matchers work:

``` ruby
expect(page).to have_mission_named           'Project Moonraker'
expect(page).to have_completed_mission_named 'Project Moonraker'

def has_mission_named?(mission_name)
  ...
end

def has_completed_mission_named?(mission_name)
  ...
end
```

RSpec generates these custom matchers based on predicate methods on your Page Objects. RSpec converts them by removing the **?** and changes **has** to **have**. Boom, matchers from scratch without much fuzz! A bit magic, I’ll give you that, but the good kind of wizardry I’d say.

Since we parked our Page Object at **specs/support/features/pages/missions.rb** you also need to make sure that the following is not commented out in **spec/rails_helper.rb**.

``` ruby
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
```

If you run into a **NameError** with an **uninitialized constant Pages** you’ll know what to do.

If you’re curious what happened to the **sign_in_as** method, I extracted it into a module at **spec/support/sign_in_helper.rb** and told RSpec to include that module. This has nothing to do with Page Objects directly—it just makes more sense to store test functionality like **sign in** more globally accessible than via a Page Object.

**spec/support/sign_in_helper.rb**

``` ruby
module SignInHelper
  def sign_in_as(email)
    visit root_path
    fill_in      'Email', with: email
    click_button 'Submit'
	end
end
```

And you need to let RSpec know that you want access to this helper module:

**spec/spec_helper.rb**

``` ruby
...
require 'support/sign_in_helper'

RSpec.configure do |config|
  config.include SignInHelper
	...
end
```

Overall, its easy to see that we succeeded in hiding away the Capybara specifics—like finding elements, clicking links etc. We can now focus on the functionality and less on the actual structure of the markup which is now encapsulated in a Page Object—the DOM structure should be the least of your concerns when you test something as high-level as feature specs.

### Attention!

Setup stuff like factory data belongs in the specs and not in Page Objects. Also assertions are probably better placed outside of your Page Objects to achieve a separation of concerns. There are two differnt perspectives on the topic:

Advocates for putting assertions into Page Objects say it helps with avoiding duplication of assertions. You can provide better error messages and achieve a better “Tell, Don’t Ask” style. On the other hand, advocates for assertion-free Page Objects argue that its better to not mix responsibilities. Providing access to page data and assertion logic are two separate concerns and lead to bloated Page Objects when mixed. Page Object’s responsibility is access to the state of pages and assertion logic belongs to specs.

+ ### Page Objects Types

**Components** represent the smallest units and are more focused—like a form object for example.

**Pages** combine more of these components and are abstractions of a full page.

**Experiences**, as you guessed by now, span the whole flow across potentially many different pages. They are more high-level. They focus on the flow the user experiences while they interact with various pages. A checkout flow which has a couple of steps is a good example to think about this.

+ ### When & Why?

Its a good idea to apply this design pattern a little bit later in a project’s life cycle—when you have amassed a little bit of complexity in your feature specs and when you can identify repeating patterns like DOM structures, extracted methods or other commonalities that are consistent on your pages. So you probably shouldn’t start writing Page Objects right away. You approach these refactorings gradually when the complexity and size of your application / tests grow. Duplications and refactorings that need a better home through Page Objects will be easier to spot over time. My recommendation is to start with extracting methods in your feature specs locally first. Once they’ll hit critical mass, they’ll look like obvious candidates for further extraction and most of them will probably fit the profile for Page Objects. Start small, premature optimization leaves nasty bite marks!

+ ### Final Thoughts

Page Objects provide you the opportunity to write clearer specs that read better and are overall a lot more expressive because they are more high-level. Besides that, they offer a nice abstraction for everybody who likes to write OO code. They hide the specifics of the DOM and also enable you to have private methods that do the dirty work while being unexposed to the public API. Extracted methods in your feature specs don’t offer quite the same luxury. The API of Page Objects don’t need to share the nitty-gritty Capybare details

For all the scenarios when design implementations change, your descriptions of how your app should work doesn’t need to change when you use Page Objects—your feature specs are more focused with user level interactions and don’t care so much about the specifics of the DOM implementations. Since change is inevitable, Page Objects become critical when applications grow and also aid the understanding when the sheer size of the application means drastically increased complexity.

extension: markdown

gha_language: CSS