text:
---
author: Arun Bhai
date: '2011-01-24 22:26:19'
layout: post
slug: avatars-how-we-did-it
status: publish
tags: [indie, movie, kdenlive, short film, effects, ubuntu, blender]
title: 'Avatars - How we did it '
wordpress_id: '381'
---

"Avatars" is our nomination multiple award-winning short film to a movie making contest within our organisation on the theme "Digital Consumers". Rather than make a boring mockumentary about mobile computing and social networking, I thought we should do something more ambitious. We wanted to make a decent short movie about technology that had characters, dialogues, storyline etc. Basically you know, all the works.

If you haven't seen the movie yet, play the embedded video below or click on the [vimeo link][avatars_vid] to see it in high-quality HD:

[avatars_vid]: http://vimeo.com/19102846

### How it all started

I have been part of a handful of skits and short films. The process inevitably starts with a core idea. A skeleton plot is built on top of it and later a script fleshes out the details. The initial script goes through numerous iterations before and during the realisation. In other words, the script is a key working manuscript for the entire team. Most of the time, it's a simple Word document with the dialogs in an free-flowing manner.

In the case of "Avatars", I wanted the script to be more visual-oriented and less on dialogues. In other words, we wanted the script to mention scenes, locations etc. After a lot of research, I found the [standard screenplay template][screenplay] extensively used in Hollywood. Despite being slightly cryptic to write, it proved to be quite presentable and handy while shooting.

[screenplay]: http://www.zoetrope.com/files/pri/168/scrw.doc

When I got the invitation for the movie making contest, I had dropped a mail to my old movie club pals, Manu and Nithya. I shared my outline script with them and they liked my elevator pitch of "one guy waking up in the morning to find a stranger in the apartment who turns out to be his avatar".

Once I finished the draft screenplay titled "Doppelgangers" and shared it with them, they were already visualising the movie in terms of how it would look and how the treatment of the subject should be.

Next we were hunting the actors and planning out the logistics. We had only four days in our hands and practically zero budgets. A number of factors helped us and we were very lucky to find some good acting talent and superb locations. We made a few modifications to the script and retitled it to "Avatars", corresponding to the meaning of "online identity". Now is perhaps a good time to delve into the concept behind "Avatars".

### Symbolisms in Avatars

The entire narrative of Avatars can be divided into three parts - The Dream, The Avatars and Catching the Taxi. This is a conventional [three part narrative][threepart] arc used in majority of films and even books with a - beginning, middle and end. The dream establishes the characters - Ranjan and Jo.

[threepart]: http://en.wikipedia.org/wiki/Dramatic_structure

The dream also tries to convey their flagging relationship through several hints - the meeting at sun-set, Jo's uncertainity by plucking the petals in a he-loves-me-he-loves-me-not fashion, her looking away when Ranjan comes etc.

There are also various hints to convey that we are in a dream. Being late is a common motif in dreams. Dreams have incoherence in location and words (hence the shaky shots and abrupt edits). They have elements of the real world just before you wake up. "Train station" was a deliberate crossover from real-life (Jo's message was probably being played while he was asleep) to dreams. It also added a certain humour element to the script.

The symbolism of having Avatars is probably the most obvious. After considerable thought, each Avatar was given a different personality. One was geeky, another was chatty etc. This was based on the fact that each Avatar represented an identity within an online service or a social networking site. We may manifest ourselves in different ways in each of these sites, perhaps forming distinct individual personalities. After all, our Avatars will not be an exact mirror of the real you. Conversely they might collectively represent you.

All in all, the visual treatment of the script will reward you well in repeat viewings. Considering the four minute limit of a short film, a lot can be said through images. However, to the casual audience, we needed to have something jazzy. That's where the effects come into picture.

### Special Effects

Perhaps you came directly to this section. Wouldn't blame you, as we intended "Avatars" to be effects-laden to highlight the use of modern and even futuristic technology. When we realised that the showing multiple avatars in the same frame, being key to the believability of the story, we realised that we needed to perfect those scenes.

Being completely new to special effects, we did what most software engineers do - Prototype! I did a test shot of being in two places in two different shots. Manu took these shots and blended them on Adobe Premiere using masking tools. The result looked much more "believable" than the Green screen effect. In fact, Green/Blue screens needed a lot more effort and correcting the interplay of light and shadow would have been a nightmare.

Given the limited time, we decided to opt for masking for these trick shots. There was considerable effort in getting the lighting correct in these shots so that the videos would blend correctly without noticeable artifacts. One three-second shot needing the three Ranjans in one frame, took seven extremely long retakes across two days.

A major time-saving step was testing these trick shots immediately on the laptop at location. By this approach, we could quickly check if the shots matched correctly. This helped us avoid disappointment and saved a lot of time potentially lost in post processing corrections.

Most of effects were simplified due to careful planning before shooting. So by the time we shot the scenes with the overlay effects we knew that the camera angles had to leave some room for showing the dynamic menu selections.

### Movie Making 101

Given the competition deadline, we had to finish a lot of things in the extremely short deadline. There are a lot of [good resources][bbc] on the web about short film making. But from our personal experience, here are some of the elements that went into "Avatars":

[bbc]: http://www.bbc.co.uk/filmnetwork/filmmaking/guide/introduction/what-makes-a-good-short

- **Storyboarding 101:** Avatars' storyboard was pretty much about the camera angles and how the relative positions of the characters were maintained especially in conversation.

- **Camera-work 101:** The widescreen frames helped a lot especially when 3 characters came together in the  triangle seating for the trick shot. Some of the funny angles we tried were camera-in-the-bag and running-with-the-actor shots. Realised time and time again that hiding the camera from all the reflections is a big pain!

- **Screenplay 101:** Shooting happened out of order and its very difficult to keep track of what's not covered without a screenplay. Sometimes continuity-errors would crop up in editing (such as the bouquet in the final shot) and the scene would be reshot.

- **Acting 101:** The more the number of actors, the more retakes is a good rule of thumb.

- **Directing 101:** A simple line like "OSCON went bust" can be said in a zillion different ways - comical, matter-of-fact or even condescendingly. A director needs to imbibe the spirit of the script and apply his imagination in these areas.

- **Lighting 101:** Proper lighting will take 60% of your time. Avatars predominantly used bounce lights supplemented by free hanging fluorescent lamps and incandescent bulbs. Fluorescent lamps have a noticeable flicker.

- **BGM 101:** The background music defines the mood and the tempo of a movie. The rock music in appropriate parts really helped.

- **Editing 101**: Editing probably took way more time than I thought leading to all-nighters towards the end. It was entirely done in [KDEnlive][kdenlive], a fantastic open source editor. Throughout the workflow, care was taken to keep in the intermediates in high quality HD.

- **Effects 101**: There is an entire section on Effects above. Later, Manu got really good with the animated overlays and soon he couldn't stop making them enough! :)

- **Titles 101**: The titles were a 3D rendering of Google maps with cloned Google-pointers floating over a map of Mangalore. The entire modelling and compositing was done in [Blender][blender]. Took 3 hours to render.

- **Compositing 101**: We did minimal compositing for Avatars. Some color correction was added from Kdenlive to give the appearance of a film rather than a digital camera.

- **Marketing 101**: The posters were done in GIMP overlaying the title renders on the film frames.

[blender]: http://www.blender.org/
[kdenlive]: http://www.kdenlive.org/

### What Worked What Didn't

Now that the movie is completed, it is probably a good time to do a post-mortem of what worked and what didn't

#### What Worked

1. Having a full screenplay: Great communication tool and sometimes a management tool
2. Having a team: Having your friends to collaborate makes the process more fun and focused at the same time. Late night mailers on gmail does keep you focused!
3. Prototype: Checking the double-effect shot first
4. Natural Lighting: We didn't spend anything on lighting. We chose locations that were brightly lit. The living room and bedroom actually belong to different houses :)

#### What Didn't Work
1. Sound recording: I have always found dubbing to be an issue in indie film making. We used a good mic and decent noise cancellation software, yet it was always unnatural sounding
2. Learning Curve: When you have a deadline, its not always the best time to learning a new piece of software like KDEnlive. But Windows Movie Maker wouldn't have cut it (pun intended).

### Conclusion

All in all, it was a fantastic experience doing something creative with such a brilliant team. Avatars is a work that we are all proud of. Hope you enjoyed watching it as well!

### Frequently Asked Questions

__Q. Which camera did you use?__
A. We used a Panasonic Lumix DMC-Z3. This is an inexpensive point-and-shoot with HD video recording capabilities. We also used a tripod in some shots.

__Q. What software did you use?__
A. We used mostly open source tools like [KDEnlive][kdenlive], [Blender 2.56][blender] and [Audacity][audacity]. It was completely edited on [Ubuntu 10.10][ubuntu].

[kdenlive]: http://www.kdenlive.org/
[blender]: http://www.blender.org/
[audacity]: http://audacity.sourceforge.net/
[ubuntu]: http://www.ubuntu.com/

__Q. How long did you take to make the film?__
A. It took one day to make the screenplay, followed by 2.5 days of shooting and finally, 2 days for editing and dubbing.

__Q. Where all did you shoot?__
A. The entire movie is shot in Mangalore. The exterior shots were taken at Bondel Road and near Infosys. The interior shots were shot in Binary Homes and at my residence.

__Q. Is there a bloopers video showing all the mistakes?__
A. You bet there is. The bloopers and some behind the scenes stuff is here: <http://www.vimeo.com/18817334>

__Q. What was your budget?__
A. We filmed on nearly zero budget. We reused as much stuff as we could. The only things we bought for the movie were props like the bouquet and the coffee cups.

__Q. Where did you get the name 'Oskon'?__
A. I had named the poor target of the Chinese mega-corp as OSKON without much thought. Later, I noticed that the toilet flushing system sensor at office had the letters ASKON engraved on it. So subliminal, huh?

repository: patilswapnilv/arunrocks

gha_language: JavaScript

repo_name: patilswapnilv/arunrocks


text:
---
layout: essay
type: essay
title: E5 Reflecting on Assignment 2 Technical Essay
date: 2021-05-03
labels:
---

Provide a brief introduction to the assignment along with a link to this page for further details

In assignment 2, we had to create a login/register page for our website. With the registration and login pages we needed users to register an account into the server and login in order to successfully redirect them to checkout the items in the invoice page. To make sure the user is registered on the server, the server checks to validate the username and password and if it is correct the user can go to the invoice page, if they are not registered an error happens they are not allowed to go through the invoice page.

What did you learn from this assignment?

In assignment 2 I learned how to create a registration/login page for a website using the POST method. Also, being able to make the server validate a user before moving on to the next page, and redirect a user if the login is not correct or registered.
Another thing I learned from this assignment was that it takes a lot of time and patience. I need to set more time aside to work on the assignments.

Did you work with a partner? Assign an estimated percentage on the amount each team member contributed to the assignment (including yourself).

No, I did not work with a partner. I worked by myself.

How did you get help when you needed it? What did you need help with?

When I needed help I would refer back to the lectures and look back at the previous labs we did in class. If I was completely stuck I scheduled a meeting with Professor Port. I needed help fixing my invoice page not appearing when submitting the quantity of items after logging in.

How was developing this assignment different than assignment #1?

Assignment 1 was more difficult because we had to build the foundation for assignment 2 and we had to work on all the files. But for assignment 2 it was more focused on the server file. It was not easy but very still different from assignment 1.

Estimate the % of time you spent (a) thinking about how to do something, (b) writing code (but do not include testing, (c) testing and debugging

I spent about 35% of my time thinking about how to do something, 15% writing code, and 50% testing and debugging.

Describe what worked well with this project? What did not work well?

What worked well for me in this project was creating the CSS and register/login page because it was like assignment 1. Also, there were not many changes to the code since I used the templates from w3schools.
What did not work well was copying and pasting code from previous labs because it got me a little confused and lost when trying to solve the issues I was having.

If you could go back in time and do things differently, what would you do differently?

If I could go back in time things I would do differently are manage my time better and ask for more help. Time management was one of my biggest issues because on top of managing all my other courses and working it made it difficult for me to find time to spend a large amount of time working on this assignment. What I would do is start earlier so I can plan ahead and have more time to work on assignment 2. Another issue I had was trying to figure out my problems and not requesting for help earlier. This affected me because it set me back on my time management and being able to finish the assignment in a timely manner. What I would do differently is not to be afraid to request for help as much as I needed.

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# PyBankPoll_Challenge

Created a new repository for this project called PyBankPoll_Challenge and cloned it to a local git repository
Created ssh key pair for my github account
Defined global config variables for the git repository
  git config --global user.email<EMAIL_ADDRESS>  git config --global user.name "sandykolu"

Created subdirectories PyBank and PyPoll with each having the following:
  A new file called main.py. This will be the main script to run for each analysis.
  A “Resources” folder that contains the CSV files you used.
  An “analysis” folder that contains budget_analysis.txt and poll_analysis.txt that has the results from the analysis.

Completed mutiple commits to the git project using the following:
  Git add .
  Git commit -m "Message"
  git push origin main

PyBank_Challenge
Created a Python script for analyzing the financial records of the company dataset - budget_data.csv. The dataset is composed of two columns: Date and Profit/Losses

  Calculate each of the following:

  The total number of months included in the dataset
  The net total amount of “Profit/Losses” over the entire period
  Calculate the changes in “Profit/Losses” over the entire period, then find the average of those changes
  The greatest increase in profits (date and amount) over the entire period
  The greatest decrease in losses (date and amount) over the entire period

PyPoll_Challenge
Created a Python script that analyzes the votes using a dataset of poll data - election_data.csv. The dataset is composed of three columns: Voter ID, County, and Candidate.

  Calculates each of the following:

  The total number of votes cast
  A complete list of candidates who received votes
  The percentage of votes each candidate won
  The total number of votes each candidate won
  The winner of the election based on popular vote.

branch_name: refs/heads/main


text:
Upgrade NNS UI canister to commit `1e5a24e4cc8071e2d9c0ac6aa4fdaa0719a68275`.

Wasm hash: `fc022d364efb5ef3e69057570dfc6341fd182ba3914a138b311044575b76d879` (https://github.com/dfinity/dfinity_wallet/runs/2746166653?check_suite_focus=true)

Changes:

```
git log --oneline --first-parent a005f2d4e343a8eaecd6357a08172c3ef49cb3db..1e5a24e4cc8071e2d9c0ac6aa4fdaa0719a68275

1e5a24e (HEAD -> main, origin/main, origin/HEAD) fix: neuron page font sizes (#69)
4ba4491 Handle 'Top-up Neuron' transactions originating from external accounts (#70)
eb0d380 Switch post_upgrade to work with the new stable memory format (#68)
2cad8d6 fix: make stake buttons column when in mobile mode (#66)
```

repository: luismompohanden/nns-proposals

repo_name: luismompohanden/nns-proposals


text:
# General Information

___

### Free Tuition
There is no charge for the instruction one receives at the **_Bible Institute of Missouri_.**

___

### A Two Year Program
The program lasts for eight quarters, which makes up two academic years.

___

### Over Forty Courses Taught
Bible or Bible related subjects, including Greek, are taught.

___

### Twenty-Four Hundred Hours Plus of Classroom Time
Students attend classes for six hours a day, five days a week.

___

### Verse by Verse Study
This includes the New Testament and Old Testament, when possible.

gha_language: CSS

gha_license_id: MIT


text:
# ESP-IDF AXP20x_Library example

This is an example of using [AXP202X_Library](https://github.com/lewisxhe/AXP202X_Library) to program in esp-idf. For more examples, please refer to [AXP202X_Library](https://github.com/lewisxhe/AXP202X_Library)

-------------------------------
After setting up the correct environment

```
git clone --recursive https://github.com/lewisxhe/ESP_IDF_AXP20x_Library.git
cd ESP_IDF_AXP20x_Library
idf.py menuconfig
idf.py build
idf.py -p [PORT] -b [BAUD] flash
```


text:
# **Script is outdated because of release of discord.js v13**

# multibot
Run muliple Discord bots with same code in one window.

## Setup
Install node.js v14.xx, preferably LTS. Then in npm, download discord.js module and then paste tokens in 'tokens.txt', each token being newline separated, and then run! If you have prior experience in JS, i guess you can edit 'bot.js' to your liking.

## Running
This program should work on any Unix or Unix-like shells. Run by executing `start.sh`


text:
## FanfouHandpick 饭否精选

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

FanfouHandpick's API comes from [Anthonyeef](https://github.com/Anthonyeef)'s repo [FanfouDaily](https://github.com/Anthonyeef/FanfouDaily),Thanks for him.

饭否精选的API来自 [Anthonyeef](https://github.com/Anthonyeef) 的repo [FanfouDaily](https://github.com/Anthonyeef/FanfouDaily),在此向他表示感谢。

## Environment 环境
This project is developed by **Kotlin**, if you use **Java** rather than Kotlin, you need to install the plugins and configure your environment before you compile it.

本项目采用 **Kotlin** 开发，如果你使用的是 **Java** 进行Android开发，那么，在编译次项目时，需要在Android Studio中安装插件，并进行相关的配置。

## Screenshots 截图
![0](https://github.com/marktony/FanfouHandpick/blob/master/screenshots/0.png)

## Download 下载
Our app is now available on Google Play 谷歌商店:

[![google-play-badge](https://github.com/marktony/FanfouHandpick/blob/master/screenshots/google-play-badge.png)](https://play.google.com/store/apps/details?id=com.marktony.fanfouhandpick)

Scan the QR code 扫描二维码:

![fir.im](https://github.com/marktony/FanfouHandpick/blob/master/screenshots/download_link.png)

[fir.im](http://fir.im/1nq6)

## License 许可证

    Copyright 2016 lizhaotailang

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

repository: liliuhuan/FanfouHandpick

repo_name: liliuhuan/FanfouHandpick


text:
---
name: Something is broken
about: incorrect data or returning null
title: ''
labels: bug
assignees: ''

---

⚠ This project is an unofficial way to get data from BoxRec.  Things will break as time goes on because we cannot control the BoxRec website and changes they make.  It is free to use and therefore do not expect things to always work and don't expect things to necessarily be fixed hastily.  If you want things fixed, please consider [helping to fix them](https://github.com/boxing/boxrec/blob/master/CONTRIBUTING.md#development-walkthrough) and creating a PR.  If you need any more information on how things work, please feel free to get in touch.

If you are just pointing out that something is broken, that is fine and appreciated.

Please understand that the project is non-sponsored, free to use and [personally](https://github.com/mikedidomizio), I have other projects I would like to work on.

Thank you for understanding⚠

**Describe the bug**
A clear and concise description of what the bug is.

**Expected behavior**
A clear and concise description of what you expected to happen.

**Additional context**
Add any other context about the problem here.

repository: boxing/boxrec

gha_language: TypeScript

repo_name: boxing/boxrec


text:
---
layout: default
title: COOP Interceptor
parent:
    title: Interceptors
    url: interceptors.html
---

# Cross-Origin Opener Policy Interceptor

## Description

Interceptor that implements _Cross-Origin Opener Policy_ on incoming requests.

COOP is a security mitigation that lets developers isolate their resources against side-channel attacks and information
leaks. The COOP response header allows a document to request a new browsing context group to better isolate itself
from other untrustworthy origins. Separating browsing contexts is necessary because at least two types of attacks
are possible when a document shares a browsing context group and possibly an operating system process with cross-origin documents:

- Cross-window attacks. A malicious document can open a victim document in a new window and later navigate the window
  to a look-alike document to trick the user, or attempt to exploit postMessage vulnerabilities in the victim document.
- Process-wide attacks. Side channel and transient execution attacks like Spectre may provide an opportunity
  to the malicious document to get access to sensitive data from the victim document, if they share an OS process.

The COOP header can have one of 3 values:
- `same-origin`
- `same-origin-allow-popups`
- `unsafe-none`

If the COOP values are the same, and the origins of the documents match the relationship declared in the COOP header
value, documents can interact with each other. Otherwise, if at least one of the documents sets COOP, the browser
will create a new browsing context group severing the link between the documents. Sites can use `same-origin-allow-popups`
to allow popups they open to be in their browsing context group (unless the popup's own COOP prevents this).

COOP is now supported by all major browsers. [More information about COOP](https://web.dev/why-coop-coep/#coop).

## Parameters

- `exemptedPaths` - Set of opt out endpoints that are meant to serve cross-site traffic. Paths should contain leading
  slashes and must be relative. This field is empty by default.
- `mode` - The policy mode COOP should follow. Available modes are `same-origin`, `same-origin-allow-popups`,
  `unsafe-none`. Default mode is `same-origin`.

## Examples

```xml
<action  name="someAction" class="com.examples.SomeAction">
    <interceptor-ref name="defaultStack">
        <param name="coop.exemptedPaths">/path1,/path2,/path3</param>
        <param name="coop.mode">same-origin</param>
    </interceptor-ref>
    <result name="success">good_result.ftl</result>
</action>
```

gha_language: HTML


text:
# KEEP-IT-LEVEL: Blood Glucose Monitoring App

> An application used to monitor blood glucose levels for patients with Diabetes.

>Uses the NightScout REST API to display real-time blood glucose data.

## Project Status
This project is currently in development. Users can add their NightScout URL to display glucose levels. Functionality to give users notifications on glucose trend levels is in progress.

## Installation and Setup Instructions

Clone down this repository. You will need `node`, `npm`, and `react` installed on your machine.

#### Installation:

`npm install`

#### To Start Server:

`npm start`

Open [`http://localhost:3000`](http://localhost:3000) to view it in the browser.


text:
[![CircleCI](https://circleci.com/gh/spatialcurrent/go-dfl/tree/master.svg?style=svg)](https://circleci.com/gh/spatialcurrent/go-dfl/tree/master) [![Go Report Card](https://goreportcard.com/badge/spatialcurrent/go-dfl)](https://goreportcard.com/report/spatialcurrent/go-dfl)  [![GoDoc](https://godoc.org/github.com/spatialcurrent/go-dfl?status.svg)](https://godoc.org/github.com/spatialcurrent/go-dfl) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://github.com/spatialcurrent/go-dfl/blob/master/LICENSE.md)

# go-dfl

## Description

**go-dfl** is a Go implementation of the Dynamic Filter Language (DFL).  **go-dfl** depends on:
- [go-adaptive-functions](https://github.com/spatialcurrent/go-adaptive-functions) for many of the basic functions.
- [go-reader-writer](https://github.com/spatialcurrent/go-reader-writer) for reading and writer files.
- [go-counter](https://github.com/spatialcurrent/go-counter) for counting for statistical functions.
- [go-try-get](https://github.com/spatialcurrent/go-try-get) for abstracting how to get values by name from unknown objects.

Using cross compilers, this library can also be called by other languages.  This library is cross compiled into a Shared Object file (`*.so`).  The Shared Object file can be called by `C`, `C++`, and `Python` on Linux machines.  See the examples folder for patterns that you can use.  This library is also compiled to pure `JavaScript` using [GopherJS](https://github.com/gopherjs/gopherjs).

## Usage

**CLI**

The command line tool, `dfl`, can be used to easily covert data between formats.  We currently support the following platforms.

| GOOS | GOARCH |
| ---- | ------ |
| darwin | amd64 |
| linux | amd64 |
| windows | amd64 |
| linux | arm64 |

Pull requests to support other platforms are welcome!  See the [examples](#examples) section below for usage.

**Go**

You can install the go-dfl packages with.

```shell
go get -u -d github.com/spatialcurrent/go-dfl/...
```

You can then import the `dfl` package with:

```go
import (
  "github.com/spatialcurrent/go-dfl/pkg/dfl"
)
```

See [dfl](https://godoc.org/github.com/spatialcurrent/go-dfl/pkg/dfl) in GoDoc for information on how to use Go API.

**Node**

DFL is built as a module.  In modern JavaScript, the module can be imported using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).

```javascript
const { parse, compile, evaluate } = require('./dist/dfl.mod.min.js');
```

In legacy JavaScript, you can use the `dfl.global.js` file that simply adds `dfl` to the global scope.

**C**

A variant of the reader and writer functions are exported in a Shared Object file (`*.so`), which can be called by `C`, `C++`, and `Python` programs on Linux machines.  For complete patterns for `C`, `C++`, and `Python`, see the `examples` folder in this repo.

## Releases

**go-dfl** is currently in **alpha**.  See releases at https://github.com/spatialcurrent/go-dfl/releases.  See the **Building** section below to build from scratch.

**JavaScript**

- `dfl.global.js`, `dfl.global.js.map` - JavaScript global build  with source map
- `dfl.global.min.js`, `dfl.global.min.js.map` - Minified JavaScript global build with source map
- `dfl.mod.js`, `dfl.mod.js.map` - JavaScript module build  with source map
- `dfl.mod.min.js`, `dfl.mod.min.js.map` - Minified JavaScript module with source map

**Darwin**

- `dfl_darwin_amd64` - CLI for Darwin on amd64 (includes `macOS` and `iOS` platforms)

**Linux**

- `dfl_linux_amd64` - CLI for Linux on amd64
- `dfl_linux_amd64` - CLI for Linux on arm64
- `dfl_linux_amd64.h`, `dfl_linuxamd64.so` - Shared Object for Linux on amd64
- `dfl_linux_armv7.h`, `dfl_linux_armv7.so` - Shared Object for Linux on ARMv7
- `dfl_linux_armv8.h`, `dfl_linux_armv8.so` - Shared Object for Linux on ARMv8

**Windows**

- `dfl_windows_amd64.exe` - CLI for Windows on amd64

## Examples:

### Go

See the examples in the [dfl](https://godoc.org/github.com/spatialcurrent/go-dfl/pkg/dfl) package documentation.

### CLI

**Environment**

With the `-env` flag you can use DFL filters against the current environment.

```
./dfl -env -f '@SHELL in [/bin/sh, /bin/bash]' && echo "Shell is set to sh or bash"
```

**Arrays**

You can use DFL to filter integer arrays.

```
./dfl -f '@a == [1, 2, 3, 4]' 'a=[1, 2, 3, 4]'
# returns true as exit code 0
```

You can also use DFl to compare byte arrays.

```
./dfl -f '@a == [137, 80, 78, 71]' 'a=[0x89, 0x50, 0x4E, 0X47]'
# returns true as exit code 0
```

**IP Address Information**

You can use DFL to filter IP addresses.

```
./dfl -f '@ip in <IP_ADDRESS>/16' ip=<IP_ADDRESS>
# returns true as exit code 0
```

**OpenStreetMap**

You can also use DFL to filter OpenStreetMap features.

```
./dfl -f '@pop > (10 - 2)' craft=brewery name=Stone pop=10
# returns true as exit code 0
```

```
./dfl -f '@craft like "brewery"' craft=brewery name=Stone pop=10
# returns true as exit code 0
```

```
./dfl -f '@craft like "brew%"' craft=brewery name=Stone pop=10
# returns true as exit code 0
```

```
./dfl -f '@craft ilike "Stone%"' craft=brewery name=Atlas pop=10
# returns true as exit code 0
```

## Building

Use `make help` to see help information for each target.

**CLI**

The `make build_cli` script is used to build executables for Linux and Windows.

**JavaScript**

You can compile DFL to pure JavaScript with the `make build_javascript` script.

**Shared Object**

The `make build_so` script is used to build Shared Objects (`*.so`), which can be called by `C`, `C++`, and `Python` on Linux machines.

**Changing Destination**

The default destination for build artifacts is `go-dfl/bin`, but you can change the destination with an environment variable.  For building on a Chromebook consider saving the artifacts in `/usr/local/go/bin`, e.g., `DEST=/usr/local/go/bin make build_cli`

## Testing

**Go**

To run Go tests use `make test_go` (or `bash scripts/test.sh`), which runs unit tests, `go vet`, `go vet with shadow`, [errcheck](https://github.com/kisielk/errcheck), [ineffassign](https://github.com/gordonklaus/ineffassign), [staticcheck](https://staticcheck.io/), and [misspell](https://github.com/client9/misspell).

**JavaScript**

To run JavaScript tests, first install [Jest](https://jestjs.io/) using `make deps_javascript`, use [Yarn](https://yarnpkg.com/en/), or another method.  Then, build the JavaScript module with `make build_javascript`.  To run tests, use `make test_javascript`.  You can also use the scripts in the `package.json`.

# Contributing

[Spatial Current, Inc.](https://spatialcurrent.io) is currently accepting pull requests for this repository.  We'd love to have your contributions!  Please see [Contributing.md](https://github.com/spatialcurrent/go-dfl/blob/master/CONTRIBUTING.md) for how to get started.

# License

This work is distributed under the **MIT License**.  See **LICENSE** file.

repository: spatialcurrent/go-dfl

gha_language: Go

repo_name: spatialcurrent/go-dfl


text:
GlassEyeGestureDemo
===================

Demo app for Google Glass's eye gesture detector. This app is capable of detecting "Wink" gesture or "Double blink" gesture. Note that eye gesture only works on new version of Glass. If you are an early explorer and have not swapped yours with new one, it won't work.

### Download
[v1.1 apk file](https://github.com/thorikawa/GlassEyeGestureDemo/releases/download/v1.1/EyeGestureDemo-debug-1.1.apk)

You might need `adb` to install it.

### Source Code
This repo consists of two projects. [EyeGestureStub](EyeGestureStub) is a library project for stubbing Google Glass's core framework [EyeGestureDemoApp](EyeGestureDemoApp) is an actual app.

### How it works
EyeGesture and EyeGestureManager included in this project are just stubs, but once apk file is installed to Google Glass, it uses actual library included in Glass itself.

If you wanna use eye gesture in your own application, you'd better to use EyeGestureStub project as it is. If you want to include those classes in your project, please use EyeGesture and EyeGestureManager class from this project with the SAME package name (com.google.android.glass.eye) and class name.

### License
[Apache Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html)

### Acknowledgements
Refered [winky](https://github.com/kaze0/winky) project to learn how to receive the result of eye gesture. Thank you for the great work! Of course, great thank you for Google Glass's team!

repository: PavelDimitrov/EyeGestureLib

repo_name: PavelDimitrov/EyeGestureLib


text:
# imsm_awesome
My awesome project for the IMSM workshop.

 You will no doubt want to tell all your friends.

## Getting awesome:
This project can be cloned from GitHub by using
```
git clone <url>
```
where `<url>` can be found by clicking on the green "Clone or Download" button above.

$$
\mu + \sigma
$$

## Ways to be awesome
Here are some ways to be awesome:

$$
\mu + \sigma + \tau \delta
$$
1. blah, no, yes
1. blah
1. dot, dot, dot...

## This is me changing this file
Here are some changes.


text:
Preprocessing Data
===================

In this exercise, we will learn how to preprocess our data for alignment. We will be doing some sequencing trimming. Trimming the left side of the reads to remove primer sequence as well as identify and trim off any adapter, or polyA/T sequence from the right edge of the read

**1\.** First, create a directory for the example in your home directory:

    cd # Go back to the home directory
    mkdir rnaseq_workshop

---

**2\.** Next, go into that directory, create a new directory for the Raw Data and link to the directory for your raw data. This data comes from an Yeast project that we did:

    cd rnaseq_workshop
    mkdir 00-RawData
    cd 00-RawData
    ln -s path/to/data/folder .

---

**3\.** Now, take a look inside that directory.

    ls

---

**4\.** Pick a file and look at the contents of the file using the 'zless' command:

    zless the_file_you_choose.fastq.gz

Make sure you can identify which lines correspond to a single read and which lines are the header, sequence, and quality values. Press 'q' to exit this screen. Then, let's figure out the number of reads in this file. A simple way to do that is to count the number of lines and divide by 4 (because the record of each read uses 4 lines). In order to do this, use "zcat" to output the uncompressed file and pipe that to "wc" to count the number of lines:

    zcat the_file_you_choose.fastq.gz | wc -l

Divide this number by 4 and you have the number of reads in this file. One more thing to try is to figure out the length of the reads without counting each nucleotide. First get the first 4 lines of the file (i.e. the first record):

    zcat the_file_you_choose.fastq.gz | head -4

Then, copy and paste the sequence line into the following command (replace [sequence] with the line):

    echo -n [sequence] | wc -c

This will give you the length of the read. See if you can figure out how this command works.

---

**5\.** Now go back to your 'rnaseq_workshop' directory and create another directory called '01-Trimming':

    cd ~/rnaseq_workshop
    mkdir 01-Trimming

---

**6\.** Now, we will use software called 'bbduk' to trim the data. First we will download and install it, then run it on just one file.

find bbdup on the internet, download, extract and move it into the 'rnaseq_workshop' folder.

Next, Looking at the usage.

    ./bbmap/bbduk.sh -h

**7\.** In order to trim adapters we need an adapter file and the sequence file. The adapter file will depend upon which kit you used... typically you can find the adapters from the sequencing provider. In this case, Illumina TruSeq adapters were used, adapter files can be found in the resources folder.

To trim polyA/T we will need to create a file with a polyA and polyT sequence.

    printf ">polyA\nAAAAAAAAAAAAA\n>polyT\nTTTTTTTTTTTTT\n" | gzip - >  bbmap/resources/polyA.fa.gz

**8\.** Now run bbduk specifying an input file, output file, the adapters and polyA/T files, and additional parameters for trimming.

    bbmap/bbduk.sh in=00-RawData/the_file_you_choose.fastq.gz out=01-Trimmed/the_file_you_choose.fastq.gz ref=bbmap/resources/polyA.fa.gz,bbmap/resources/truseq.fa.gz k=13 ktrim=r forcetrimleft=11 useshortkmers=t mink=5 qtrim=t trimq=10 minlength=20

the parameters: k, ktrim, useshortkmers, mink, qtrim, trimq, are all parameters associated with trimming off the

This will take a few minutes to run. When the jobs finish, you will have the file that is  trimmed.

---

**9\.** Once that is done, let's take a look at the differences between the input and output files.

---

**10\.** We have run through adapter & quality trimming for one sample, but now we need to do it for all the samples.

We will need to generate a file called 'samples.txt' that contains all the sample IDs. We will extract this information from the filenames using 'cut'. First, get a listing of all the R1 files:

    ls -1 *R1*.fastq.gz

We will pipe this output to 'cut' to get the fields we want. Give cut the options "-d" with an underscore (usually above the minus sign on a keyboard) as the parameter, and the "-f" option with "1,2" as the parameter in order to get the first and second fields:

    ls -1 *R1*.fastq.gz | cut -d_ -f1,2

This gives us the all the sample IDs. Now we just need to redirect that output to a file:

    ls -1 *R1*.fastq.gz | cut -d_ -f1,2 > samples.txt

Use 'cat' to view the contents of the file to make sure it looks right:

    cat samples.txt

---

**14\.** Take a look at the other script:

    cat qa_for_loop.sh

This script has similar commands, but instead of using a task array, it is using a for loop. So this will loop through all the IDs in samples.txt and assign a new ID on every iteration of the loop. You should use this script if you will be running jobs NOT on a cluster, but on a single machine.


text:
- [CS 1632 - Software Quality Assurance](#cs-1632---software-quality-assurance)
  * [Description](#description)
  * [List of Files](#list-of-files)
  * [How to Run QuickCheck](#how-to-run-quickcheck)
  * [What to do](#what-to-do)
  * [Task 1: Complete IntegerOpsTest](#task-1-complete-integeropstest)
  * [Task 2: Debug IntegerOps](#task-2-debug-integerops)
    + [IntegerOpsTest Lessons](#integeropstest-lessons)
  * [Task 3: Complete StringOpsTest testEquals method](#task-3-complete-stringopstest-testequals-method)
  * [Task 4: Debug StringOps equals method](#task-4-debug-stringops-equals-method)
  * [Task 5: Complete ValidHTMLStringGenerator doShrink method](#task-5-complete-validhtmlstringgenerator-doshrink-method)
  * [Task 6: Debug StringOps isValidHTML method](#task-6-debug-stringops-isvalidhtml-method)
    + [StringOpsTest Lessons](#stringopstest-lessons)
  * [Submission](#submission)
- [Extra Credit](#extra-credit)
  * [Description](#description-1)
  * [What to do](#what-to-do-1)
  * [Extra Credit Submission](#extra-credit-submission)

# CS 1632 - Software Quality Assurance
Summer Semester 2021 - Supplementary Exercise 3

* DUE: July 28 (Wednesday), 2021 6:30 PM

**GitHub Classroom Link:** https://classroom.github.com/g/HXh7JIpY

## Description

For this exercise, you will practice a software testing technique called
property-based testing.  Please review Lecture 14: Property-based Testing
before starting on this exercise.  Property-based testing is a type of dynamic
testing but differs from your regular unit testing in that it tests properties
rather than individual values to check behavior.  Instead of saying: "for this
particular set of input values, I expect this output value to be returned", a
property says: "regardless of what input values are provided, I expect this
property to hold no matter what".

The fact that a property is invariant across the entire set of inputs allows a
property-based test to be used with any input.  That means, instead of manually
encoding inputs (say, as part of JUnit test scripts), we can even auto-generate
some random inputs and test them against our property!  This type of testing
is called stochastic testing, or random testing.  Stochastic testing relies
on property-based tests to check postconditions for a broad range of inputs.

But stochastic testing is not the only place where property-based testing is
used.  Property-based testing is also used in the form of invariant assertions
embedded in source code that do sanity checks during operation.  These
assertions are often left on when the software is deployed on the client site
so that the program will shutdown rather than perform some irrecoverable
disastrous action when a sanity check fails.  These sanity checks have to be
invariants because they need to pass for all inputs and all system
configurations that are legal.  Property-based testing is also useful for model
checking that does exhaustive program state space exploration that we will
practice on Exercise 5.

For this exercise, we are going to use a JUnit extension library called
QuickCheck.  Existing JUnit annotations such as @Test, @Before, @After still
apply as usual but we are going to learn about some new annotations that enable
us to do property-based testing.

## List of Files

IntegerOps.java - Methods to perform simple integer arithmetic such as add and subtract (**modify**).

IntegerOpsTest.java - A QuickCheck JUnit class that performs property-based testing on IntegerOps (**modify**).

StringOpsTest.java - A QuickCheck JUnit class that performs property-based testing on StringOps (**modify**).

ABCStringGenerator.java - A QuickCheck generator class that generates random strings containing the characters 'A', 'B', and 'C'.

ValidHTMLStringGenerator.java - A QuickCheck generator class that generates random valid HTML strings containing HTML tags such as <b>, </b>, <i>, </i> (**modify**).

TestRunner.java - Driver class that contains the main method to invoke JUnit on IntegerOpsTest and StringOpsTest.

## How to Run QuickCheck

1. Running QuickCheck. For Windows do:
    ```
    runTest.bat
    ```
1. For Mac / Linux do:
    ```
    bash runTest.sh
    ```

Initially, you should see one test already failing:
```
testIsValidHTMLTrue(StringOpsTest): Property named 'testIsValidHTMLTrue' failed:
With arguments: [<i><b><i></i></b><b></b><b><i></i></b><i><b><i></i></b></i><i></i></i>]
Seeds for reproduction: [4133865354563074415]

!!! - At least one failure, see above.
```
You may see a different seed and string because it is randomly generated.

Alternatively, I've created an Eclipse project for you so you can use Eclipse
to import the existing project and run either IntegerOpsTest or StringOpsTest
individually as JUnit classes.

## What to do

The goal is to debug IntegerOps and StringOps using the QuickCheck test classes
IntegerOpsTest and StringOpsTest.  The QuickCheck classes are incomplete as of
now so you will have to complete those first.  All places where you need to
modify are marked by // TODO comments.  Pay close attention to the Javadoc
comment above each method that describes what each method does, or is supposed
to do.

## Task 1: Complete IntegerOpsTest

Open IntegerOpsTest.java.  Look at the testAdd method:

```
@Property(trials = 1000)
public void testAdd(int x, int y) {
	// System.out.println("testAdd x='" + x + "', y='" + y + "'");
	// TODO: Fill in.
}
```

Note that each method has the @Property(trials = 1000) annotation.  The
@Property annotation tells QuickCheck that this is a property-based test and
QuickCheck is to do 1000 trial runs using 1000 randomized input values.  Note
that unlike a regular @Test JUnit method, an @Property method has input
parameters x and y.  These input parameters are where the randomized input
values generated by QuickCheck are passed.  So on each of the 1000 trials, x
and y will be passed a different value.  Not only that, the first time you run
it with the 1000 trials will be different from the second set of 1000 trials
(that is, x and y are going to be different values).  You can observe this
yourself by un-commenting the System.out.println.  That is the beauty of
property-based testing: as you run the tests repeatedly, you will gradually
gain higher coverage without you having to do anything!

Now it's time to fill in the method.  Fill in the code according to the
invariant property specified in the Javadoc comment above the method.  If you
implemented it properly, you should get something similar to the following
message when you execute runTest.bat again (actual numbers may differ due to
randomness):

```
testAdd(IntegerOpsTest): Property named 'testAdd' failed:
With arguments: [1091099725,<PHONE_NUMBER>]
First arguments found to also provoke a failure: [1936803025,<PHONE_NUMBER>]
```

This is telling you that QuickCheck was able to determine that testAdd fails
when x =<PHONE_NUMBER> and y =<PHONE_NUMBER>.  What is the part about: "First
arguments found to also provoke a failure"?  That's telling you that among the
1000 trials, [1936803025,<PHONE_NUMBER>] were the first set of values where a
defect was found.  From those values, QuickCheck progressively refined or
"shrunk" them to the final values [1091099725,<PHONE_NUMBER>].  QuickCheck always
tries to "shrink" input values to the simplest or smallest values that still
trigger the defect to make debugging easier.  Rather that just reporting
[1936803025,<PHONE_NUMBER>], [1091099725,<PHONE_NUMBER>] gives you more information.
1091099725 +<PHONE_NUMBER> =<PHONE_NUMBER> which is just slightly bigger than
Integer.MAX_VALUE =<PHONE_NUMBER>.  So this strongly suggests the defect has
something to do with integer overflow.  Otherwise, we would have had to find
this out by trial-and-error.

If you left the System.out.println un-commented, you can see what's happening
behind the scenes by observing the output:

```
testAdd x='-1967126952', y='1194075525'
testAdd x='1191001002', y='529527415'
testAdd x='-427676937', y='1415513158'
testAdd x='898946678', y='-810210174'
testAdd x='-2096855516', y='147305889'
testAdd x='-1427326142', y='201626672'
testAdd x='927999071', y='-507009504'
testAdd x='-1575502058', y='-1850940687'
testAdd x='-82004065', y='-1320953857'
testAdd x='275074581', y='-1498381415'
testAdd x='1936803025', y='1056406418'  <--- First discovery of defect, starting shrinking ...
testAdd x='0', y='1056406418'
testAdd x='968401512', y='1056406418'
testAdd x='1452602268', y='1056406418'
testAdd x='0', y='1056406418'
testAdd x='726301134', y='1056406418'
testAdd x='1089451701', y='1056406418'
...
testAdd x='1090899926', y='1056406418'
testAdd x='1091033125', y='1056406418'
testAdd x='1091099725', y='1056406418'  <--- Smallest input while still triggering defect
testAdd x='0', y='1056406418'
testAdd x='545549862', y='1056406418'
testAdd x='818324793', y='1056406418'
testAdd x='954712259', y='1056406418'
...
```

You can see how QuickCheck is methodically doing the trial-and-error behind the
scenes using bisection, so that you don't have to do it.

## Task 2: Debug IntegerOps

Now debug IntegerOps.add(int x, int y) so that the test passes.  All you have
to do is: if you detect integer overflow (you add two positive numbers but you
end up with a negative number), then return 0.

Complete testSubstract in the same way and debug IntegerOps.subtract(int x, int
y).

### IntegerOpsTest Lessons

These are the three things you should have learned through this exercise:
1. A @Property QuickCheck test goes through many randomized trials during a
   single test run where each trial is provided with randomized input values.
1. A property check must be an invariant assertion that is true no matter what
   randomized input values are tested.  For example, things like: the addition
of two positive integer should result in a positive integer.
1. When a @Property test fails, not only does QuickCheck provide you with the
   set of input values triggering the defect, but it also "shrinks" them to the
smallest set of defect-triggering values meant to help you debug.

## Task 3: Complete StringOpsTest testEquals method

Open StringOpsTest.java.  Let's look at the testEquals method:

```
@Property(trials = 1000)
public void testEquals(String s1, String s2) {
	// System.out.println("testEquals s1='" + s1 + "', s2='" + s2 + "'");
	// TODO: Fill in.
}
```

Note that now the randomized input parameters **s1** and **s2** are now
strings.  A string is a form of a byte stream, since each character in the
string is represented as an ASCII code byte.  So you can consider this to be
an example of **fuzz testing**, a type of stochastic testing that deals with
byte streams.

When you do fuzz testing, you need to be extra careful in choosing a good
distribution of random values, in order to get good test coverage.  Your end
goal should be to get a good number of random values for each equivalence
class, since each equivalence class would exercise a different part of the
code.  For numerical input values, you are likely to hit every equivalence
class, given enough trials.  Or, you can use the **@InRange** annotation to
ensure that random values are generated for a certain range of input values
for a particular equivalence class.

For byte streams, equivalence classes cannot be simply described using a
"range" like numbers.  For byte streams, equivalence classes are things
like a string with less 10 characters, a string in all-caps, a string in
proper XML format, etc.  These cannot be expressed using the @InRange
annotation.  So we need to create a specialized random value generator for
each equivalence class.

Going back to our testEquals test, fill in the test as before based on the
Javadoc comments.  Now even after filling in the test the test passes (and
it will pass no matter how many times you run it unless you are very lucky).
Does that mean StringOps is bug-free?  Absolutely not!  If you see
StringOps.equals(String s1, String s2), you can see the two strings are
compared only up to Integer.min(s1.length(), s2.length()).  So if one string
is shorter than the other, but the two strings are identical up to that
point, equals will return true.  That cannot be correct behavior.

Why wasn't the defect caught during the 1000 trials?  That is because the
defect manifests only when s1 and s2 fit a certain pattern (one is a substring
of the other).  And given uniform distribution, it is very unlikely that s1 and
s2 will show any resemblance whatsoever.  If you uncomment System.out.println
and observe the strings passed, you will see what I mean.

That means we have to generate a distribution more likely to uncover the
defect.  Remember in Lecture 14, I stressed that stochastic testing requires a
lot of thinking about the distribution you generate in order to be effective?
This is just such a case.  Modify the testEquals method declaration as such to
use @From annotations:

```
@Property(trials = 1000)
public void testEquals(@From(ABCStringGenerator.class) String s1, @From(ABCStringGenerator.class) String s2) {
	...
}
```

The @From annotation tells QuickCheck to use the ABCStringGenerator.class
instead of the default uniform String generator to generate s1 and s2.  Open
ABCStringGenerator.java, and focus on the overridden generate method.  I
overrode the default method such that now the generated strings only contain
'A's, 'B's, and 'C's.  This greatly increases the chance that the two strings
will resemble each other, giving us a better chance of uncovering the defect.
Once you make the change, testEquals should fail after one or two runs.  Note
how I also overrode the doShrink method

```
@Override
public List<String> doShrink(SourceOfRandomness random, String larger) {
	if (larger.length() == 0)
		return Collections.emptyList();

	// In this case, the string is shrunk simply by chopping it in half.
	// Both the left and right half are added to the list of strings to check.
	List<String> list = new ArrayList<>();
	list.add(larger.substring(0, larger.length() / 2));
	list.add(larger.substring(larger.length() / 2));
	return list;
}
```

If a String fails a test, it is chopped in half and the lower half and upper
half are tried again respectively.  Implementing the doShrink method allows
QuickCheck to shrink the input values just like before:

```
testEquals(StringOpsTest): Property named 'testEquals' failed:
With arguments: [, A]
First arguments found to also provoke a failure: [AB, ABC]
```

Inputs [AB, ABC] has been shrunk to [, A].  You can see how this is easier to
debug.  The progressive shrinking happens as before:

```
testEquals s1='', s2=''
testEquals s1='AB', s2='ABC'
testEquals s1='A', s2='ABC'
testEquals s1='', s2='ABC'
testEquals s1='', s2='A'
testEquals s1='', s2=''
```
## Task 4: Debug StringOps equals method

Fix equals() based on the feedback given by QuickCheck.

## Task 5: Complete ValidHTMLStringGenerator doShrink method

Now it's time to look at the testIsValidHTML method:

A uniform distribution will not give us valid HTML strings.  So we need a different
generator just like before, namely the HTMLStringGenerator.

```
@Property(trials = 1000)
public void testIsValidHTML(@From(ValidHTMLStringGenerator.class) String s) {
	// System.out.println("testIsValidHTMLTrue s='" + s + "'");
	assertTrue(StringOps.isValidHTML(s));
}
```

ValidHtmlStringGenerator generates randomized HTML strings with matching
**\<b\>...\</b\>** and **\<i\>...\</i\>** tags.  All strings passed by this generator are valid
HTML so the invariant is that they all return true when
StringOps.isValidHTML(s) is called.  ValidHtmlStringGenerator is another custom
generator that is able to rigorously test your program by generating random but
only valid HTML strings.  If you run the above, you will immediately see a
failure.  But the failed input is probably going to be too long for easy
debugging.  That is because the doShrink method is incomplete as of now.
Currently, it returns an empty list of candidates meaning that the candidate
search ends immediately and the original string is not shrunk.

Fill in the doShrink method after reading the comments and comparing against
ABCStringGenerator.  If you implement this properly, you should see something
like this on the console:

```
testIsValidHTMLTrue s='<i><i><i></i></i><b><i><i></i></i><b><i></i><i></i></b></b></i>'
testIsValidHTMLTrue s='<i><i></i><b><i><i></i></i><b><i></i><i></i></b></b></i>'
testIsValidHTMLTrue s='<i><b><i><i></i></i><b><i></i><i></i></b></b></i>'
testIsValidHTMLTrue s='<i><b><i></i><b><i></i><i></i></b></b></i>'
testIsValidHTMLTrue s='<i><b><b><i></i><i></i></b></b></i>'
testIsValidHTMLTrue s='<i><b><b><i></i></b></b></i>'
testIsValidHTMLTrue s='<i><b><b></b></b></i>'
testIsValidHTMLTrue s='<i><b></b></i>'
testIsValidHTMLTrue s='<i></i>'
testIsValidHTMLTrue s=''
```

## Task 6: Debug StringOps isValidHTML method

Debug StringOps.isValidHTML based on the feedback so that now all tests pass.

### StringOpsTest Lessons

These are the two things you should have learned through this exercise:
1. Sometimes a program functions meaningfully only for a certain pattern of
   inputs.  In these situations, going with the default uniform distribution of
inputs will lead to horrible test coverage.
1. QuickCheck allows you to create your own generator by inheriting from
   existing generators and overriding some methods.  This allows you to
customize your own distribution.  In this exercise, we only practiced
generating integers and Strings but there is nothing preventing you from
generating objects.  For example, in the above StringOpsTest.testEquals(String
s1, String s2) method, we could have generated the two strings s1 and s2 as
part of the same object such that we correlate s1 and s2 in some way rather
than generating them separately.

## Submission

Each pairwise group will do one submission to GradeScope as usual.  The
submitting member must use the "View or edit group" link at the top-right
corner of the assignment page after submission to add his/her partner.

Submit the repository created by GitHub Classroom for your team to GradeScope
at the **Supplementary Exercise 3 GitHub** link.  Once you submit, GradeScope
will run the autograder to grade you and give feedback.  If you get deductions,
fix your code based on the feedback and resubmit.  Repeat until you don't get
deductions.

The autograder will test your updated IntegerOpsTest, StringOpsTest, and
ValidHTMLStringGenerator classes against the original IntegerOps and StringOps
classes.  Since we are testing against the original classes before debugging,
we expect all tests to fail, if you have done the work.

# Extra Credit

* DUE: August 7 (Saturday), 2021 11:59 PM

**GitHub Classroom Link:** https://classroom.github.com/g/dv2OpU9n

This extra credit is worth 1 point out of 100 points for the entire course.
Note that you need to get 100/100 on the autograder to get credit.  Partial
credit will be given under the discretion of the instructor and may not
necessarily equate to your GradeScope score.

## Description

We are going to go back to the MonkeySim program we profiled on Exercise 4.
The game is a simulation of the Collatz Conjecture
(https://en.wikipedia.org/wiki/Collatz_conjecture).  The conjecture states that
the game will eventually end (that is the first monkey will eventually get the
banana).

Now it turns out that the MonkeySim does not end given certain arguments.  So
have we disproved the conjecture, something that nobody was able to do since
1937?  Are our names going to be on the cover page of newspapers tomorrow?

Sorry for the downer, but not really.  MonkeySim does not end because it has a
defect in its implementation.  For certain arguments, the game falls into an
infinite loop, where a cycle is formed when a group of monkeys pass the banana
among themselves in a repetitive pattern.

Now, this defect is hard to find using just a handful of test cases you can
write using JUnit.  So we are going to use stochastic testing to feed MonkeySim
with a whole bunch of randomized arguments to see which triggers the infinite
loop.  Complete MonkeySimStochasticTest.java to implement the testMonkeySim
method which checks the invariant that no matter which argument is given,
runSimulation never falls into an infinite loop.  Use the @InRange annotation
to make sure the generated random number for the starting monkey is greater
than or equal to 1, to make sure we do meaningful tests.

So how do we detect when runSimulation falls into an infinite loop?  Maybe add
a timeout to the test and say that if the test does not return within 10
minutes, we consider it to be an infinite loop?  But of course, there is no
guarantee since runSimulation may just be taking a long time to return.  In
order to detect infinite loops reliably, you will have to modify MonkeySim to
be able to detect it when it happens, that is when you detect a cycle forming
within a group of monkeys.  On detection, throw an InfiniteLoopException.  In
the testMonkeySim JUnit method, the check can be done by catching the
InfiniteLoopException and fail()-ing that test run.

## What to do

Create a new GitHub classroom repository by following the link posted above.
Note that this repository, while similar to Exercise 4, differs in a couple
of key ways.  It removed the List<Monkey> ml and MonkeyWatcher mw parameters
from its public methods to give you more freedom to choose your own data
structure for the group of monkeys and make other implementation changes.
And you will have to optimize MonkeySim heavily, beyond what you did for
Exercise 4, in order for the program to be performant enough for stochastic
testing.  Stochastic testing does hundreds of random trials and each trial
must be quick for it to end in a reasonable amount of time.

Also, a new **verbose** flag is added that allows MonkeySim to disable system
output, so that MonkeySim can be further sped up during testing.  You are
expected to turn off this flag for your stochastic tests as specified in the
Javadoc comments.

You will have to:
1. Optimize MonkeySim with the help of VisualVM, while making sure
   MonkeySimPinningTest continues to pass.
1. Modify MonkeySim so that it detects infinite loops and throws the
   InfiniteLoopException when it does, again making sure
MonkeySimPinningTest still passes.
1. Complete the testMainStochastic QuickCheck method in
   MonkeySimStochasticTest.java using the InfiniteLoopException exception.
1. Run testMainStochastic and let QuickCheck find a monkey number argument
   that triggers the infinite loop defect.
1. Create a regular JUnit test case out of that argument named
   testMainInfiniteLoop that checks for infinite loops.  Of course, this
test case will always fail with the current implementation.

In order to run the simulation, you can use the following commandline:
```
java -cp bin MonkeySim <starting_monkey_number>
```

In order to run the MonkeySimPinningTest and MonkeySimStochasticTest JUnit
tests, you can use the following commandline (for Windows):
```
java -cp quickcheck-jars/*:bin TestRunner
```
Or the commandline (for Mac/Linux):
```
java -cp quickcheck-jars/*:bin TestRunner
```

The expectation is that the pinning tests (that check for existing behavior)
should pass and the stochastic tests (that check for the infinite loop
defect), should fail.

## Extra Credit Submission

Modify your GitHub classroom repository to perform the above stochastic
test.  Please submit the repository to a separate **Supplementary Exercise 3
Extra Credit** link.


text:
---
layout: post
series: Cocoa Quicknote
title: A Small Trick to Hide NSPopover's Arrow
tags: [cocoa, macos, swift, nspopover, appkit]
lang: en
---

A friend of mine who works as a macOS developer asked me a strange question - can you hide the arrow of a popover?

This is strange to me because IMO the arrow give you a sence of context, indicating where the popover is pop from, and imply the relation of its content. There's no reason to hide the arrow from the first place.

Any way, back to the question. Is it possible to hide the arrow?

The anwser is **yes**, but this is not tweaking a knob in interface builder nor changing a variable programmatically.

Here is how it works.

Say you have a scroll view, and a button on it, which present a popover relatively to the button when clicked.

Now scroll it til the button is away from visible rect. Guess what happend? The arrow of the popover will follow the button and when the button is outside visible rect, the arrow disappear!

![Default Popover Behavior](/assets/img/2018-08-08-a-small-trick-to-hide-nspopovers-arrow-02.gif)

That is a default behvaior of popover we can make use of. The arrow of popover is always point to it's positioning view when it's possible, and hide itself when the positioning view is not visiable.

That means all we need to do is:

1. Create a different positioning view.
2. Create the popover.
3. present the popover.
4. Move positioning view off visible rect.

And now you have presented a popover with no arrow!

![Popover with no arrow](/assets/img/2018-08-08-a-small-trick-to-hide-nspopovers-arrow-01.gif)

```swift
var popover: NSPopover?
var positioningView: NSView?

@IBAction func showPopover(_ sender: NSButton) {
    positioningView = NSView()
    positioningView?.frame = sender.frame
    view.addSubview(positioningView!, positioned: .below, relativeTo: sender)

    popover = NSPopover()
    // configure popover here

    popover?.show(relativeTo: .zero, of: positioningView!, preferredEdge: .maxX)

    positioningView?.frame = NSMakeRect(0, -200, 10, 10)
}
```

## Bonus: Popover on Statusbar

This trick also works if you want to use a popover as a statusbar menu.

In your status item button's action callback method, simply add a positioning view as a subview of the status item button:

```swift
@IBAction func statusItemButtonDidPushed(_ sender: NSButton) {
    // add positioning view as a suview of sender, that is, `statusItem.button`.
    let positioningView = NSView(frame: sender.bounds)
    // set an identifier for positioning view, so we can easily remove it later.
    positioningView.identifier = NSUserInterfaceItemIdentifier(rawValue: "positioningView")
    sender.addSubview(positioningView)

    // show popover
    popover.show(relaticeTo: posotioningView.bounds, of: positioningView, preferredEdge: .maxY)
    // move positioning view away
    sender.bounds = sender.bounds.offsetBy(dx: 0, dy: sender.bounds.height)
}
```

Later, when the popover is closed, we can remove the positioning view from view hierarchy. This is often done in popover's deelgate method `popoverDidClose(_:)`:

```swift
func popoverDidClose(_ notification: Notification) {
    let positioningView = statusItem.button?.subviews.first {
        $0.identifier == NSUserInterfaceItemIdnetifier(rawValue: "positioningView")
    }
    positioningView?.removeFromSuperview()
}
```

You may find the gap between the statusbar and the popover is a bit large. In this case, you can also move the popover up a bit by setting its window's frame:

```swift
if let popoverWindow = popover.contentViewController?.view.window {
    popoverWindow.setFrame(popoverWindow.frame.offsetBy(dx: 0, dy: 10), display: false)
}
```

gha_language: SCSS


text:
#Android Views

Android Views and it's standard elements such as textview, imageview, edittext, scrollview etc are introduced in this lesson along with details on each.

Any Android app is made up of a lot of Activities, and all the Activities have User interface. Android provides us a lot of prebuilt user interface elements to create a nice looking UI for our app.

In a previous chapter, you have seen how to leverage different layouts to give structure to your application's User Interface. The layout is just an empty placeholder for Android views. Let us see some of the most used Android Layout widgets and some of its interesting properties.

In Android, all layouts are XML based. Even though you get a nice graphical editor, ultimately the elements are nothing but XML code. Let's take a brief look at both :

##Graphical Layout
If you open any Layout in ADT, you will see 2 tabs like the one in this image

<%= image_tag "android_widgets/tabs.png", alt: "Android views Layout Tabs", title: "Android views Layout Tabs" %>

To open Graphical Layout for dragging and dropping UI elements, just click on the Graphical Layout tab.

This is how the Graphical Layout Editor looks like :

<%= image_tag "android_widgets/layout_editor.png", alt: "Android views Layout Editor", title: "Android views Layout Editor" %>

Let us see what are its sub components

###Palette
Palette section has all your basic UI elements categorized into different sections, like Form Widgets, TextFields, Layouts etc. You can just choose any Element by Dragging and Dropping it to the working area on the right of the Screen.

<%= image_tag "android_widgets/layout_palette.png", alt: "Android views Layout Palette", title: "Android views Layout Palette" %>

###Control Bar
The top bar which you see with options like Nexus one, App Theme etc. is called control bar. It has different options to test the UI against different conditions. You can control the size of the screen, orientation,theme etc. from this bar. You can also change Zoom level, check lint warnings etc. from this bar.

<%= image_tag "android_widgets/layout_control.png", alt: "Android views Layout Control", title: "Android views Layout Control" %>

###Design Area
The remaining area to the right side of the palette is the Design Area. Here, you can drag and drop elements to add in the UI, rearrange already added elements, reorder them, change their properties, etc.

##Common Attributes and Properties

All UI elements are of type View and have some common properties which are useful to understand their behavior. Whenever you drag and drop a UI element from Designer view, it also automatically generate at least these 3 properties of the android view.

###android:id
It is used to identify a particular View in Java Code. When you assign an ID to a View, it makes that android view uniquely identifiable through this ID in that Layout. In later chapters, we will see the use of ID in details.

Here is how it will look like in code
        android:id="@+id/textView1"

###android:layout_width
layout_width property of android views defines the width of that view. You should define width in px or dp.

###android:layout_height
layout_height property of android views defines the height of that view. You should define height in px or dp.

Here is how Height and Width will look into code

        android:layout_width="match_parent"
        android:layout_height="wrap_content"

Since all UI elements are inherited from android views, all have an onClick property. We will explore onClick for some of the UI elements.

Here are some common attributes or terminology which will be good to understand before watching UI elements in action

###wrap_content
This is the value which you can assign to layout's width or height. This tells android to make the size of the UI element just equal to the size of content which the UI has.

For example, a text view with the text "HELLO" with width as wrap_content will only be 5 characters wide(as HELLO is 5 characters wide).

###match_parent or fill_parent
Always use match_parent over fill_parent, even though both means same. This value is again to be assigned to width or height. This tells android to match the view's height or width to its parent's height or width. If the parent is taking full size on screen, setting this value on any UI element will also make its height or width equal to the screen size.

###dp
Dp is density independent pixels. As Android devices comes with different density of the screen, this value can be used instead of PX (pixle). If you use dp, Android will automatically calculate px for you based on the screen of the android device.

For Example: On some device 1 dp might be equal to 1 px but on some device 1dp = 5px

###Padding
Padding is the space inside the border, between the border and the actual view's content. Padding is always inside the view and goes completely around content. You can set padding on all 4 sides, or on an individual side.

For Example: If you set padding property in EditText, the cursor inside the EditText will move.

Here is how Padding looks in code:

For all sides

        android:padding="2dp"

For Individual Sides

        android:paddingLeft="2dp"
        android:paddingRight="3dp"
        android:paddingTop="5dp"
        android:paddingBottom="8dp

###Margin
Margins are the spaces outside the border, between the border and the other elements next to this view, IE margin is the outside view, it is a space between 2 Android views, whenever you want to give space between 2 views you can use Margin.

For Example: If you set margin in EditText, the EditText will move by that value from it's parent view.

Here is how Margin will Look at the code:

For all sides

        android:layout_margin="2dp"

For Individual Sides

        android:layout_marginLeft="2dp"
        android:layout_marginRight="3dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="8dp

You might wonder what is the difference between margin and padding. Let's see an Image to Understand better.

<%= image_tag "android_widgets/margin_padding.jpg", alt: "Android views Padding and Margin", title: "Android views Android Padding and Margin" %>

In the image, margin is the gray area outside the entire object. The border is the point where your view ends.

Margin and Padding are the same concept, as in CSS.

###Gravity
Whenever you want to align content inside the view, use gravity. android:gravity sets the gravity of the content of the View its used on. Android Gravity, when applied on a view, specifies the direction of its content to be aligned.

For Example: In A Linear Layout when you set Gravity to Center, all its View will get Center aligned.

This is how you set the gravity of layout
        android:gravity="center"

###Layout Gravity
Layout Gravity is the Outside gravity of the View. It sets the gravity of the View or Layout in its parent.

Here is how you set layout gravity
        android:layout_gravity="right"

HTML/CSS Equivalents:

android:layout_gravity = float in CSS

android:gravity = text-align in CSS

###'android:' namespace

You might wonder why all properties start with android:`. If you notice the first line of any XML file there is a namespace definition :

      xmlns:android="http://schemas.android.com/apk/res/android"

Notice the attribute android here, which is referring to Android Schema. This Schema has all references to values like id, text other attributes. You can read more about XML Schema from [this link](http://en.wikipedia.org/wiki/XML_schema)

##TextView

<%= image_tag "android_widgets/textview.png", alt: "Android views TextView", title: "Android views TextView" %>

Textview is most simple UI element. It is used to display static text, which cannot be changed by the user.

In HTML world, TextView is nothing but a Label.

Lets see some of the useful properties of TextView

###android:text
This property defines the text which will come inside the TextView

###android:textColor

This property defines the color of text. This take HexaDecimal text color for example #ffff00

###android:textSize

This property defines the size of text. It takes values in Sp. For example "15sp"

###Example
This is how a simple textview looks in code.

        <TextView
                android:id="@+id/textView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Hello World"
                android:textColor="#ffff00"
                android:textSize="15sp"/>

A lot of time you require to set the text of TextView Dynamically via code. Let's see how we can change the text of textView via code.

First Step is to get reference of TextView.

        TextView txtView = (TextView)findViewById(R.id.textView1);

Here you call findViewByID method by passing the android:id of the TextView.

Since all the UI elements are view, findViewbyId returns a view object which we need to typecase into correct subview, in this case TextView.

Now, to change the text just call setText method on the txtView object as :

        txtView.setText("Set your Text Here");

With these 2 simple lines of code, you can change the text of textview dynamically

##EditText

<%= image_tag "android_widgets/edittext.png", alt: "Android views Edit Text", title: "Android views EditText" %>

EditText is another most used UI element in Android. Whenever you want to take some input from the user, you can use EditText.

In HTML world EditText is nothing but an input tag.

Lets see some useful properties of EditText

**android:text** : this property defines the text which will come inside the EditText, or the text which user will enter. Typically in Java code, once you have the reference of editText object, this is the property which you call to get the value which user might have set.

**android:hint**: this property defines the hint which you want to give to user, this hint appear inside the edittext but gets disappear once user start typing anything inside the edit text

**android:ems**: this property defines how many characters long the text should be. Since there is no text inside edit text, making it wrap_content will not help. This property helps you in defining the exact width for edit text.

**android:background**: this property defines the background of the edit text. You can either choose a color or set an image as the background of the edit text.

**android:inputType**: this property defines what kind of content the edit text will contain.

For Example: **textPassword** will make the text automatically converted into * as user starts typing. **Number** will change the keyboard layout to numeric, hence helping the user to type the number faster.

This is a very powerful property of EditText and if you know what kind of content your EditText needs, make sure to define that using inputType.

###Code
This is how a simple editText will look like

		<EditText
		        android:id="@+id/editText1"
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:ems="10"
		        android:text="Pranay"
		        android:hint="Enter User Name"
		        android:background="#ff0000"
		        android:inputType="text">

Most of the times, you would want to get the value of EditText or prepopulate the value dynamically. Let's see how we can do this in code.

First let get the reference of the EditText

        EditText edtText = (EditText)findViewById(R.id.editText1);

As discussed earlier, we just call findViewById to get the reference of a view in code.

Now to get the content of the edit text, just call getText method, like this

        edtText.getText()

Similar to TextView, to set the text of EditText, you can call

        edtText.setText("Set your value")

##Button

<%= image_tag "android_widgets/button.png", alt: "Android views Button", title: "Android views Buttons" %>

###What
Button is the most used UI element in Android.

###Properties
Lets see some of the useful properties of a Button

**android:text** : this property defines the text which will come on the top of a button. You can change the text dynamically through code

**android:textColor**: this property defines the color of text on the button. This take HexaDecimal text color for example #ffff00

**android:background**: this property defines the background of the button. You can either choose a color or set a image as background of the button

**android:clickable** : this property makes the button enabled or disabled. This takes boolean values (false/true)

###Click Listener
Button is made to be clicked. Lets see how we can add a click listener to the button. Even though you can directly define a method from the UI which should be called when button is clicked, the best way to do it is using code.

Get the object of the button in code.

        Button b = (Button) findViewById(R.id.button1);

if you notice the above code, you create a button object and then call findViewByID method by passing the android:id of the button.

Since all the UI elements are view, findViewbyId returns a view object which we need to typecast into correct sub view.

Add listener

        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // Do what you want after button click here
            }
        });
In the above code, you add a click listener to the button. Whenever the button is clicked , the onclick method of button is called.

 <%= link_to "Go to hands on tutorial on Click Listener", app_tutorial_module_with_token_path("twitter", LessonModule.find_by_lesson_number(41).lesson.token), class: "btn btn-success btn-large" %>

###Code
This is how a button will look in XML code

        <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#f23400"
        android:clickable="false"
        android:text="Button" />

Similar to editText and textView you can call **setText** method on the button object to change the text on the button dynamically.

## ImageView

<%= image_tag "android_widgets/imageview.png", alt: "Android views ImageView", title: "Android views ImageView" %>

###What
Any android app is incomplete without use of an image. Image View is the UI control which you can use to display image in your android app.

In html, image view is simply img tag.

###Properties
Lets see some of the useful properties of Image View

**android:src** : The most important property of ImageView is src . This property helps you to define the image which will be displayed in the image view. You can pass android drawable or your own drawable. Let's see an example

         android:src="@drawable/ic_launcher"

Here "@drawable" refers to your drawable folder which is present inside res folder. After that, you put the image name without the extension.

**android:contentDescription** : This is not a required property, but it is recommended to set this property. ContentDescription is a text description of the image which you have set. This property helps with accessibility. If this property is set, users facing difficulty in viewing the image can use a Screen Reader, which will read out the text from content description.

###ImageView Example
This is how an ImageView will look in XML code

        <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="Image Description"
                android:src="@drawable/ic_launcher" />

A lot of time you would want to change the image of ImageView dynamically from the code. Let us see how we can do that.

Let's get the reference of image view
        ImageView imView = (ImageView)findViewById(R.id.imageView1);

Once we have the image view object, we can call setImageResource method to change the image. You can pass the drawable which you want to set to the imageview .

        imView.setImageResource(R.drawable.new_image);

##RadioButton

<%= image_tag "android_widgets/radiobutton.png", alt: "Android views Radio Button", title: "Android views RadioButton" %>

###What
If you want your users to pick one from a set of options, use Radio button.

In HTML the input type="radio" is radio button.

###Properties
Let's see what are the properties of radio button

**RadioGroup** : Radio button does not reside on its own. A radio button will always be inside a Radio Group. Radio Group can have multiple radio buttons. All the radio buttons inside the radio group will have a Click event which will be invoked when user selects the radio button.

For example :

        <RadioGroup
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

The orientation of radio group helps you in aligning radio button in vertical or horizontal format.

**android:text** : Android text property of a radio button is used for putting text in radio button.

**android:checked** : Checked property of radio button lets you define preselected/default selected option in a radio group. For example: if you have 3 radio buttons you can use this property in any one button to make it selected by default.

        android:checked="true"

###Click listener
Radio buttons are created to be clicked. In a radio group, all the radio buttons will have a click listener. This click listener will be invoked when the user will click on any of the radio button. There are multiple way to add a click listener, but simple way is to do in code using android:onClick property of a radio button.

Lets see an example of an Android RadioButton :

         <RadioButton
                    android:id="@+id/radio_code"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="onRadioButtonClicked"
                    android:text="Code" />

         <RadioButton
                    android:id="@+id/radio_learn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:onClick="onRadioButtonClicked"
                    android:text="Learn"
                    android:checked="true"
                    />

In the above example, notice the property onClick. Since these 2 radio buttons reside in the same radio group, both have a same click listener.

Here is how the click method looks

        public void onRadioButtonClicked(View view) {
            // Is the button now checked?
            boolean checked = ((RadioButton) view).isChecked();

            // Check which radio button was clicked
            switch(view.getId()) {
                case R.id.radio_code:
                    if (checked)
                        // Code option selected
                    break;
                case R.id.radio_learn:
                    if (checked)
                        // Learn Option Selected
                    break;
            }
        }

You can create a method in your code, in which you define onClick action of a radio button. In this method, you can get the id of the radio via  **view.getId()** . Once you have the id, you can use a switch case statement to determine which radio button was clicked by checking **view.isChecked()**

With a simple code, you can know which radio button selection was made.

### RadioButton Example
Here is how the complete Radio button declaration will look inside the XML

         <RadioGroup
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                 <RadioButton
                                    android:id="@+id/radio_code"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:onClick="onRadioButtonClicked"
                                    android:text="Code" />

                <RadioButton
                                    android:id="@+id/radio_learn"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:onClick="onRadioButtonClicked"
                                    android:text="Learn"
                                    android:checked="true"
                                    />
        </RadioGroup>

##CheckBox

<%= image_tag "android_widgets/checkbox.png", alt: "Android views CheckBox", title: "Android views CheckBox" %>

###What
If you want to select one or more options from a set, use Check Box.

In HTML the input type="checkbox" is checkbox.

###Properties
Let's see what are the properties of checkbox. Most of the properties of checkbox and radio button are similar.

**android:text** : this property of a  checkbox is used for putting text in a radio button.

**android:checked** : Checked property of checbox lets you have the checkbox checked by default.

        android:checked="true"

###Click listener
All the checkbox will have click listener. You can have a common click listener or different click listeners. This click listener will be invoked when the user will select or unselect any checkbox. There are multiple way to add a click listener, but simple way is to do in code using android:onClick property of checkbox.

Let's see an example

        <CheckBox android:id="@+id/feedback"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Feeback"
                android:onClick="onCheckboxClicked"/>

            <CheckBox android:id="@+id/collectdata"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Collect Data"
                android:onClick="onCheckboxClicked"/>

In the above example notice the property onClick. You can either have a common click listener for all the checkbox or can have their individual clicklisteners.

Here is how a common click method looks like :

        public void onCheckboxClicked(View view) {
            // Is the view now checked?
            boolean checked = ((CheckBox) view).isChecked();

            // Check which checkbox was clicked
            switch(view.getId()) {
                case R.id.feedback:
                    if (checked)
                        // send feedback
                    else
                        // don't send feedback
                    break;
                case R.id.collectdata:
                    if (checked)
                        // Collect Data
                    else
                        // Don't collect data
                    break;
            }
        }

You can create a method in your code in which you define onClick event of a Checkbox. Similar to radio button, in this method, you can get the id of the checbox via  **view.getId()**. Once you have the id, you can use a switch case statement to determine which checbox was clicked.  Then you can use **view.isChecked()** to determine if the button was checked or unchecked.

With this simple code, you can find out the state of the check box.

##ListView

###What
Whenever you have a date which is repeated and comes as a collection or list, list view is best User Interface element to use. ListView helps you to display repeating data in the form of a scrollable list. Users can then select any list item by clicking on it.

The ListView is widely used in android applications. A simpler example of list view is your contact book, where you have a list of your contacts displayed in a list view.

> Listview is a complex UI pattern, and we have a separate section about listview. You can read more about list view in ListView Section

 <%= link_to "Go to hands on tutorial on ListView", app_tutorial_module_with_token_path("twitter", LessonModule.find_by_lesson_number(43).lesson.token), class: "btn btn-success btn-large" %>

##GridView

###What
When you have data which you want to display as a grid of row and columns, you can use gridview. GridView displays item in 2 dimensional scrollable grid.

The most simple example of gridview is your Picture Gallery, In Picture Gallery all the pictures are arranged in a grid like format.

> You can read more about gridview at this link : http://developer.android.com/guide/topics/ui/layout/gridview.html

##ScrollView

###What
ScrollView helps you in making any Layout automatically scrollable. When you are not using listview and have content which is going beyond the screen size, you can use scroll view to make this content scrollable.

###Properties

The most important property of Scroll View is it's children. ScrollView can only have 1 child. It means that you need to have all your layouts nested under 1 layout which acts as a children of your list view.

Let's see an Example:

Let's assume we have 2 edit Text in our layouts like this

         <EditText
                        android:id="@+id/editText1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:ems="10"
                        android:text="Pranay"
                        android:hint="Enter User Name"
                        android:background="#ff0000"
                        android:inputType="text">

        <EditText
                        android:id="@+id/editText2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:ems="10"
                        android:text="Airan"
                        android:hint="Enter Password"
                        android:background="#ff0000"
                        android:inputType="text">

Now if we want to make our UI with these 2 Edit Text Scrollable, we need to put them into a parent layout. ScrollView cannot have 2 children, so we cannot put this edit text into a scroll view directly.

Let's add a Linear layout as a parent of this edit text.

         <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                 <EditText
                                android:id="@+id/editText1"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:ems="10"
                                android:text="Pranay"
                                android:hint="Enter User Name"
                                android:background="#ff0000"
                                android:inputType="text">

                <EditText
                                android:id="@+id/editText2"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:ems="10"
                                android:text="Airan"
                                android:hint="Enter Password"
                                android:background="#ff0000"
                                android:inputType="text">

        </LinearLayout>

Now that we have both the edit Text into 1 layout, we can put this Linear layout as child of a ScrollView. You can then go on and add more complex elements inside this layout and all the elements will now be scrollable.

###code
This is how our complete scroll view will look

        <ScrollView
          android:layout_height="wrap_content"
          android:layout_width="wrap_content">

         <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical" >

                         <EditText
                                        android:id="@+id/editText1"
                                        android:layout_width="wrap_content"
                                        android:layout_height="wrap_content"
                                        android:ems="10"
                                        android:text="Pranay"
                                        android:hint="Enter User Name"
                                        android:background="#ff0000"
                                        android:inputType="text">

                        <EditText
                                        android:id="@+id/editText2"
                                        android:layout_width="wrap_content"
                                        android:layout_height="wrap_content"
                                        android:ems="10"
                                        android:text="Airan"
                                        android:hint="Enter Password"
                                        android:background="#ff0000"
                                        android:inputType="text">

                </LinearLayout>
        </ScrollView>

Android has a lot of UI elements which are designed for specific purposes, in this chapter we tried to cover some of the most used UI elements. If you want to read more about other UI controls, you can go to [this link](http://developer.android.com/guide/topics/ui/index.html)