text:
# RSpec TextMate Bundle

## Installation

    mkdir -p ~/Library/Application\ Support/TextMate/Pristine\ Copy/Bundles
    cd ~/Library/Application\ Support/TextMate/Pristine\ Copy/Bundles
    git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle
    osascript -e 'tell app "TextMate" to reload bundles'

## Support for both RSpec-1 and RSpec-2

This `RSpec.tmbundle` works with both rspec-1 and rspec-2. Given
that they work differently, the `RSpec.tmbundle` tries its best to
figure out which one you're using in each project when you try to
run RSpec examples. There are two separate parts to this process,
and you have some control over how each one works.

### LOAD_PATH

The `RSpec.tmbundle` prepares the `LOAD_PATH` as follows:

1. If a `Gemfile` is present, `Bundler` is used to prepare the
Load Path with `requires 'bundler'` and then `Bundler.setup` is
executed. (This can be overridden - see below).

2. If `Bundler` isn't being used, `vendor/plugins` and
`vendor/gems` are searched for `rspec`. If `rspec` is found, then
it's `lib` directory is added to `LOAD_PATH`.

### RSpec-version

Once the `LOAD_PATH` is prepared, `RSpec-tmbundle` tries to
determine which version of RSpec to use as follows:

1. `RSpec-tmbundle` checks for an `./rspec-tm` file in the
project's root directory. If that file is exists, then
`RSpec-tmbundle` attempts to set the RSpec version from the
configuration found there.

To configure the version using this method add a file named
`.rspec-tm` to the project's root directory containing:

    --rspec-version 2.0.0

or whichever version you are using.

This is the one foolproof way to ensure that the right version is
invoked, but you don't really need to do this in most cases.

2. If no version is configured, `RSpec-tmbundle` searches for
`rspec` in the `vendor/gems` and the `vendor/plugins` directories.
If `rspec` is found, `RSpec-tmbundle` determines the version to
use based on the files present there.

3. If no version is configured and no rspec directory could be
found in vendor, then `RSpec-tmbundle` attempts to run rspec-2
with:

    require 'rspec/core'

If that raises an exception, `RSpec-tmbundle` makes a final
attempt by trying to run rspec-1 with:

    require 'spec/autorun'

### Which Approach Should I Use?

The effectiveness of each approach is partially dependent on how
you manage your gem environment. The simplest (and suggested)
approach is to first just see if it just works, and if not, then
configure the version you want in the `.rspec-tm` file.

## Rubygems

The RSpec TextMate bundle does not `require "rubygems"` so that
users who choose other packaging mechanisms can still use it. If
you _are_ using Rubygems as your package manager, then the
simplest thing to do is

* open the TextMate Preferences
* go to the `Advanced` tab
* add a variable named `RUBYOPT` with the value `rubygems`

## Options

You can set the following options in an `.rspec-tm` file in the
root directory of your project:

### --rspec-version

see RSpec-version, above.

### --bundler

Use `Bundler`, even if there is no `Gemfile` (in which case you
should have the `BUNDLER_GEMFILE` environment variable set).

### --skip-bundler

Don't use `Bundler`, even if there is a `Gemfile`.

## TextMate shell variables

In addition to the standard TextMate shell variables, the RSpec
TextMate bundle supports the following:

### TM_RSPEC_FORMATTER

Set a custom formatter other than RSpec's TextMate formatter. Use
the full classname, e.g. `'Spec::Core::Formatters::WebKit'`

### TM_RSPEC_OPTS

Use this to set RSpec options just as you would in an `.rspec`
file.

### TM_RSPEC_HOME

If you're hacking on rspec yourself, point this to the
`rspec-core` project directory for rspec-2, or the `rspec`
directory for rspec-1.

## RVM Integration

There are lots of ways to configure TextMate to work with `rvm`,
but this is the one the we recommend:

With rvm installed, take the full path to `rvm-auto-ruby`,
found via: `which rvm-auto-ruby`

Next, set up a `TM_RUBY` option in
`TextMate/Preferences/Advanced/Shell Variables` that points to the
`rvm-auto-ruby` command.

Learn more at:

* [http://rvm.io/integration/textmate](http://rvm.io/integration/textmate)
* [http://groups.google.com/group/rubyversionmanager/browse_thread/thread/64b84bbcdf49e9b?fwc=1&pli=1](http://groups.google.com/group/rubyversionmanager/browse_thread/thread/64b84bbcdf49e9b?fwc=1&pli=1)

## History

Parts of `RSpec.tmbundle` are based on Florian Weber's TDDMate.

## License

The license of `RSpec.tmbundle` is the same as
[RSpec](http://github.com/rspec/rspec/blob/master/License.txt)'s.

repository: thilo/rspec-tmbundle

repo_name: thilo/rspec-tmbundle


text:
UDP Hole Punching Proof Python implementation.

[![UDP Hole Punching Proof Python implementation](https://s12.postimg.org/627zt4u8t/Screenshot_2016_12_02_18_11_51.png)](https://postimg.org/image/74i6bod21/)

### Usage
Run the following commands on the three different machines.

#### RDV Server
```
./rdv.py
```

#### Peer 1
```
./peer.py <ip> <port> <pool>
```

#### Peer 2
```
./peer.py <ip> <port> <pool>
```

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# LinkButton

This is the button inside the inline toolbar that opens the link modal.

### Required Props
+ `getEditorState`    - A function to get the current Blocksmith `editorState`. This is needed because this component does not receive props in the usual way - see `createInlineToolbarPlugin` in Blocksmith and [the plugin docs](https://www.draft-js-plugins.com/plugin/inline-toolbar).
+ `onToggleLinkModal` - A function to open the Blocksmith LinkModal.

repository: triniti/cms-js

gha_language: JavaScript

repo_name: triniti/cms-js


text:
### [CVE-2009-1660](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-1660)
![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen)

### Description

Stack-based buffer overflow in URUWorks ViPlay3 3.0 and earlier allows remote attackers to cause a denial of service (crash) and possibly execute arbitrary code via a long file entry in a .vpl file.

### POC

#### Reference
- https://www.exploit-db.com/exploits/8644

#### Github
No PoCs found on GitHub currently.

repository: trickest/cve

branch_name: refs/heads/main

gha_language: HTML

gha_license_id: MIT

repo_name: trickest/cve


text:
# DIY React

A ~~basic~~ fairly plain React Typescript project built from scratch with some tooling to get you by. `npm start` to see it in action.

## Note for Windows

If you're having trouble running the npm scripts in a Windows environment, it might be because you're using Command Prompt or Powershell. You most likely want to use the bash shell that comes with [Git for Windows](https://git-scm.com/downloads) instead. Use npm to set a bash shell for running scripts by running the following command:

```bash
npm config set script-shell "C:\\Program Files\\Git\\bin\\bash.exe"
```

## Guide

### Basics

```bash
npm run start       # builds dist dir (if needed) and serves
npm run start prod  # same as above but with a production build of React

npm run rebuild         # rebuilds dir to reflect code changes
npm run reserve [prod]  # does the above & re-serves

npm run lint[:src|:spec]  # tuns tslint on either the src dir, spec dir, or both

npm run test  # runs tests

npm run clean [dist|test|all] # will remove either the dist dir, test dir, or both
```

### Cache

The cache (`.cache/`) contains the most recent snapshots for any component snapshot testing. The npm scripts handle the loading/unloading of these snapshots in the necessary tests.

If you plan on using snapshots, then commit your cache.

## Resources

- [Webpack docs](https://webpack.js.org/guides/typescript/)
- [Typescript w/ Webpack & React](https://www.typescriptlang.org/docs/handbook/react-&-webpack.html)
- [Typescript Project References](https://www.typescriptlang.org/docs/handbook/project-references.html)
- [ts-jest](https://kulshekhar.github.io/ts-jest/)

gha_language: TypeScript


text:
---
layout: post
title: The Empire Builder
date: '2008-10-15 23:20:47 -0700'
mt_id: 1382
blog_id: 1
post_id: 1382
basename: the-empire-builder
categories:
- history
---

If you're more interested in the subject of James J. Hill after reading my mention of him, I would encourage you to read this series of blog entries that does a capable job of an overview:

James J. Hill, Entrepreneur

James J. Hill, Empire Builder

James J. Hill, Conservationist

James J. Hill's Legacy

In the "Conservationist" entry, I cannot believe that the author left out the Great Northern Railway's pivotal role in the development and promotion of what would later become the Glacier National Park. It could have served as an excellent, private model in lieu of the National Park Service.

[UPDATE (10/17/2008): Added "Legacy" link.]

extension: markdown


text:
# Behavioral Cloning

The goals / steps of this project are the following:

* Use the simulator to collect data of good driving behavior

* Build, a convolution neural network in Keras that predicts steering angles from images

* Train and validate the model with a training and validation set

* Test that the model successfully drives around track one without leaving the road

* Summarize the results with a written report

[//]: # (Image References)

[model]: ./pics/model.png "Model Visualization"
[image2]: ./pics/center_lane_driving.png "Center Lane Driving"
[image3]: ./pics/recovering.png "Recovery Image"
[image4]: ./pics/flipped.png "Flipped Image"
[image5]: ./pics/loss.png "Recovery Image"
[image6]: ./examples/placeholder_small.png "Normal Image"
[image7]: ./examples/placeholder_small.png "Flipped Image"

---

### Files Submitted & Code Quality

#### 1. Submission includes all required files and can be used to run the simulator in autonomous mode

My project includes the following files:
* `model.py` containing the script to create and train the model
* `drive.py` for driving the car in autonomous mode
* `model.h5` containing a trained convolution neural network
* `writeup_report.md` or `writeup_report.pdf` summarizing the results

#### 2.	Submission includes functional code

Using the Udacity provided simulator and my `drive.py` file, the car can be driven autonomously around the track by executing

```sh
python drive.py model.h5
```

#### 3. Submission code is usable and readable

The `model.py` file contains the code for training and saving the convolution neural network. The file shows the pipeline I used for training and validating the model, and it contains comments to explain how the code works.

### Model Architecture and Training Strategy

#### 1. An appropriate model architecture has been employed

My model consists of a convolution neural network with 5x5 and 3x3 filter sizes and depths between 24 and 64 (`model.py` lines 166-220). It is similar to the NVIDIA model recommended in the project description. The shape of the images is 160x320x3, hence the input shape of the model is (160, 320, 3), (code line 148). The upper 60 rows and lower 20 rows of the images are removed (code line 153), as they provide no relevant information for the prediction of the steering angle. Afterwards the images are resized to 80x240x3, in order to have the same x-y ratio as in the NVIDIA example and to reduce the number of parameters. The information loss should be negligible.  After these preprocessing steps, the images are fed to the CNN.

The model includes ELU layers to introduce nonlinearity (code line 170).

#### 2. Attempts to reduce overfitting in the model

I also introduced dropout layers (`model.py` lines 171+172) as well as L2 regularization (code line 167) to the model in order to reduce overfitting. However, the performance was better without them. Therefore, in the final model I used early stopping to reduce overfitting and stopped the training after 3 epochs.

The model was trained and validated on different data sets to ensure that the model was not overfitting (code line 144+145). The model was tested by running it through the simulator and ensuring that the vehicle could stay on the track.

#### 3. Model parameter tuning

The model used an adam optimizer, so the learning rate was not tuned manually (`model.py` line 222).

#### 4. Appropriate training data

Training data was chosen to keep the vehicle driving on the road. In addition to the sample data provided by Udacity I used a combination of center lane driving (counterclockwise as well as clockwise) and some extra data for the curves. For recovering from the left and right sides of the road I used the images from the cameras on the left and right and adjusted the steering angle by +/- 0.2.

For details about how I created the training data, see the next section.

### Model Architecture and Training Strategy

#### 1. Solution Design Approach

The overall strategy for deriving a model architecture was to

My first step was to use a convolution neural network model similar to the one from the NVIDIA paper. I thought this model might be appropriate for the simulator task because the authors of the paper reported good predictions of the steering angle based on real world images. Also, the general architecture of the CNN is state-of-the-art and proofed to be good for predictions based on images.

In order to gauge how well the model was working, I split my image and steering angle data into a training and validation set. I found that my first model had a low mean squared error on the training set as well as on the validation set. But after 5 epochs the mean squared error on the validation set increased again. This implied that the model was overfitting.

To combat the overfitting, I reduced the number of training epochs. As mentioned above I also tried dropout and L2 regularization, but the results were worse.

Then I tried different parameter setting for the model (number of neurons, feature depths, batch size, weights initialization, batch normalization, conversion to YUV, masking region of interest, tuning the adjustment angle for cameras on the left and right side) and different training data (center lane driving, reverse driving, vehicle recovering from the left side and right side of the road back to center, extra data for difficult parts of the tracks, flipping the image)

The final step was to run the simulator to see how well the car was driving around track one. There were a few spots where the vehicle fell off the track, especially in the curves. To improve the driving behavior in these cases, I collected better training data (which was not so easy at the beginning) and used the images from the cameras on the sides. It turned out, that with an appropriate model I needed just a little bit more training data apart from the sample data provided by Udacity to accomplish the first track.

At the end of the process, the vehicle is able to drive autonomously around track 1 without leaving the road. Track 2 was more challenging. After fine-tuning the model and using also training data from track 2 I was able to drive almost one lap of track 2. But in one curve near the end the predictor is misled by the shadow of the mountain and the lane below, so the car keeps crashing into the poles. I tried to prevent it by equalizing the images, conversion to YUV and masking out the upper corners of the images. But nothing would help.

#### 2. Final Model Architecture

The final model architecture (model.py lines 151-220) consisted of a convolution neural network with the following layers and layer sizes:

| Layer | Description |
| ----- | ----------- |
| Input	| 160x320x3 RGB image|
| Cropping2D	| cropping upper 60 and lower 20 rows |
| Resize	| rescale image to 80x240x3|
| Normalization	| centering around zero with small standard deviation |
| Convolution 5x5	| 2x2 stride, valid padding, depth 24 |
| ELU	| worked better than ReLU |
| Convolution 5x5	| 2x2 stride, valid padding, depth 36 |
| ELU	| worked better than ReLU |
| Convolution 5x5	| 2x2 stride, valid padding, depth 48 |
| ELU	| worked better than ReLU |
| Convolution 3x3	| 1x1 stride, valid padding, depth 48 |
| ELU	| worked better than ReLU |
| Convolution 3x3	| 1x1 stride, valid padding, depth 64 |
| ELU	| worked better than ReLU |
| Flatten	| flatten convolution |
| Fully connected	| 100 neurons |
| ELU	| worked better than ReLU |
| Fully connected	| 50 neurons |
| ELU	| worked better than ReLU |
| Fully connected	| 10 neurons |
| ELU	| worked better than ReLU |
| Fully connected	| 1 neurons |

Here is a visualization of the architecture:

![model][model]

#### 3. Creation of the Training Set & Training Process

To capture good driving behavior, I first recorded two laps on track one using center lane driving. Here is an example image of center lane driving:

![Center Lane Driving][image2]

I then recorded the vehicle recovering from the left side and right side of the road back to center so that the vehicle would learn to return to center lane driving when it gets too near to the edges. These images show what a recovery looks like starting from the left side:

![Recovery Image][image3]

Then I repeated this process on track two in order to get more data points.

To augment the data set, I also flipped images and angles thinking that this would help the model to better generalize. For example, here is an image that has then been flipped:

![Flipped][image4]

After the collection process, I had 26628 number of data points. I then preprocessed this data by flipping the images randomly and augmented the data by using the left and right images with an angle adjustment of +/-0.2. The rest of the image pre-processing is done in the Keras model as described above.
I finally randomly shuffled the data set and put 20% of the data into a validation set (code line 142).
I used this training data for training the model. The validation set helped determine if the model was over or under fitting. The ideal number of epochs was 3 as evidenced by the loss function (mean squared error) – see the following figure:

![Loss][image5]

I used an adam optimizer so that manually training the learning rate wasn't necessary.

repository: olbedo/CarND-Behavioral-Cloning

repo_name: olbedo/CarND-Behavioral-Cloning


text:
# `Xobin`

The sources for this package are in the main [Xobin](https://github.com/doctorcode-org/xobin) repo. Please file issues and pull requests against that repo.

Usage information and reference details can be found in [Xobin documentation](https://xobinjs.com/docs).

License: MIT

repository: doctorcode-org/xobin

repo_name: doctorcode-org/xobin


text:
# SAML FLOW
Terms:
- Identity Provider (IP)
- Service Provider (SP)
- Single Sign On (SSO_)

Helpful Links:
(https://blog.surf.nl/en/saml-for-dummies/)
(https://en.wikipedia.org/wiki/SAML_2.0)

## Flow Example 1:
- user logs in to their company (IP - could be a website or AD etc)
- user has access to many apps like SalesForce without having to type
  username/password again anywhere

## Conversation between end user’s web browser, SP, and IP
- User tries to reach SP from the browser
- SP generates SAML request
- SP re-directs to Partner’s SSO url at IP
- IP parses SAML request, authenticates user, generates SAML response
- IP returns encoded SAML response to browser, browser sends SAML response
  to ACS url at SP
- ACS url at SP verifies SAML Response
- User is logged in to SP

repository: evanharmon/eph-headspace

repo_name: evanharmon/eph-headspace


text:
# Development startup.

The development instructions here list setup for both the backend (a Python django application with a PostgreSQL database), as well as the frontend (a React application with Babel ES6 javascript). Note that this is a complex web application, and therefore multiple steps are required:

1. Setting up the [python webserver](#python-webserver-setup) backend
2. Setting up the [database](#database-setup)
3. Syncing the [webserver and the database](#webserver-database-sync)
4. Setting up the [frontend bundling environment](#frontend-javascript-bundling)
5. Loading example [ENCODE data](#loading-encode-data)
6. Running the [development server](#starting-the-development-server)

To begin, clone this repository:

    git clone git@github.com:shapiromatron/orio-web.git

The path where this repository is found on your computer will be the project-root path, referred to frequently in the rest of this documentation.

## Python webserver setup

Requires the following software before beginning:

- Python 3.4+
- PostgreSQL 9.4+
- Python virtualenv and virtualenvwrapper
- PhantomJS 2.1+

Create a new python virtual environment, we'll use the virtual environment name `orio-web` throughout the documentation. If you have [virtualenvwrapper](https://pypi.python.org/pypi/virtualenvwrapper/) installed, you can create a new environment using the command below (note that this requires you to specify the path for python 3, which is not the default python with many installations):

    mkvirtualenv orio-web --python=/usr/local/bin/python3

If instead you are using [conda](http://conda.pydata.org/docs/), you can create a new environment using the following command:

    conda create --name orio-web python=3

Next, change paths to the root-path of this project. Then, we'll install all python requirements by running the command:

    pip install -r requirements/dev.txt

Next, change directories into the `/project` path (relative to the root). Copy default django local-development settings:

    cp django_project/settings/local.example.py django_project/settings/local.py

If the virtual environment was created using [virtualenv](https://virtualenv.pypa.io/en/stable/), use the following to set commands to start when activating the virtual environment:

    echo "export DJANGO_SETTINGS_MODULE=django_project.settings.local" >> $VIRTUAL_ENV/bin/postactivate
    echo "unset DJANGO_SETTINGS_MODULE" >> $VIRTUAL_ENV/bin/postdeactivate

If using [conda](http://conda.pydata.org/docs/), use the following commands to properly set up environment variables. First, locate and enter the directory set up for the conda environment, such as `/home/smorrissey/anaconda/envs/orio-web`. Then create the following subdirectories and files:

    cd /home/smorrissey/anaconda/envs/orio-web
    mkdir -p ./etc/conda/activate.d
    mkdir -p ./etc/conda/deactivate.d
    touch ./etc/conda/activate.d/env_vars.sh
    touch ./etc/conda/deactivate.d/env_vars.sh

Edit the two files. `./etc/conda/activate.d/env_vars.sh` should include this:

    #!/bin/sh

    export DJANGO_SETTINGS_MODULE=django_project.settings.local
    export DYLD_FALLBACK_LIBRARY_PATH=$HOME/anaconda/lib/:$DYLD_FALLBACK_LIBRARY_PATH

`./etc/conda/activate.d/env_vars.sh` should include this:

    #!/bin/sh

    unset DJANGO_SETTINGS_MODULE
    unset DYLD_FALLBACK_LIBRARY_PATH

## Database setup

Next, create a database:

    createdb -E UTF-8 orio

## Webserver database sync

Restart your virtual environment (`deactivate`, then `workon orio-web`). Navigate
to the `/project` path in the repository.

    python manage.py migrate
    python manage.py createsuperuser
    python manage.py download_ucsc_tools

## Frontend Javascript bundling

Make sure [node.js](https://nodejs.org/) and [npm](https://www.npmjs.com/) are installed, and are accessible in our environment.

Then, change directory  to the `/project` path of our project. Run the following command, which will install all javascript packages for our development environment:

    npm install --save-dev

After loading all frontend dependencies with the command above, we can run a command to watch our javascript location to compile and push updates to the website (detailed below).

*Note*: if you're using sublime text as a text editor, you may want to download the [Babel](https://github.com/babel/babel-sublime) package for updated syntax definitions. Then, with a Javascript file open, change the default syntax highlighting to Babel.

References:

- [Webpack and django](http://owaislone.org/blog/webpack-plus-reactjs-and-django/)
- [React for beginners](https://reactforbeginners.com/)

## Loading ENCODE data

Input bigWig data are very large and therefore not included in the repository. To load ENCODE data into the development environment, you'll need to have the bigWig files and a JSON file with additional metadata describing these files.

Example data can be downloaded here:

- [ENCODE data subset](http://manticore.niehs.nih.gov/ucscview/shapiroaj4/encode.zip) (15GB :bangbang:)
- [ENCODE data subset JSON metadata](http://manticore.niehs.nih.gov/ucscview/shapiroaj4/load_encode.json) (6 MB)
- [Example feature-list](http://manticore.niehs.nih.gov/ucscview/shapiroaj4/unt1hr.obsTSS.bed) (0.4 MB)
- [Example sort-vector](http://manticore.niehs.nih.gov/ucscview/shapiroaj4/wgEncodeBroadHistoneA549CtcfEtoh02Sig.sortVector.txt) (0.2 MB)

The feature-list and sort-vector are loaded from the the web-interface after the server has been started (see below).

To load the encode data:

1. Unzip the encode data subset into a `/data` folder from the root-folder of the application. After unzipping, the file structure should look like this:

        /
            data/
                encode/
                    hg19/
            docs/
            notebooks/
            project/
            public/
            ...

2. Navigate to the `/project` path, an execute the following command, using the downloaded ENCODE JSON metadata file above:

        python manage.py load_encode /path/to/load_encode.json

**Caution: This management command will delete all ENCODE objects in the database**

## Starting the development server

Whenever we want to start coding, we'll need to start the django backend application and the javascript frontend hot--reloading application.

Start the backend python client in one terminal window:

    workon orio-web
    cd /path/to/orio-web/project/
    python manage.py runserver 9000

Start the javascript bundler in another terminal window:

    cd /path/to/orio-web/project/
    node webpack.devserver.js

Navigate to [localhost:9000](http://<IP_ADDRESS>:9000/), and start developing!

## Using the bundled development environment

For quicker development, ORIO includes a Makefile command which creates a [tmux](https://tmux.github.io/)
terminal for opening all required tabs for development. To execute, use the command:

    make dev

You can modify the tmux environment by creating a local copy:

    cp bin/dev.sh bin/dev.local.sh

# Additional optional commands

## Using celery task manager

On the production server, celery tasks are used to run long-running tasks asynchronously. By default celery is not used on the development environment and tasks are handled synchronously.

To use celery, you'll need to spawn a new celery process:

    workon orio-web
    celery worker -A django_project -l info

In addition, modify your environment variables:

    workon orio-web
    echo "export \"USE_CELERY_IN_DEV=True\"" >> $VIRTUAL_ENV/bin/postactivate

## IPython/Jupyter notebooks (optional)

If interested in the [ipython/jupyter notebooks](http://jupyter.org/) , you can run the notebook server using this command:

    workon orio-web
    python manage.py shell_plus --notebook

Then, navigate to [localhost:8888](http://<IP_ADDRESS>:8888/) to view the notebooks.

repository: shunsunsun/orio-web

repo_name: shunsunsun/orio-web


text:
# react-native-redux-practice

I practice building an app using react-native and redux.

This project was bootstrapped with [Create React Native App](https://github.com/react-community/create-react-native-app).

Below you'll find information about performing common tasks. The most recent version of this guide is available [here](https://github.com/react-community/create-react-native-app/blob/master/react-native-scripts/template/README.md).

## Thanks
- [lorempixel.com/](http://lorempixel.com/)
- [native-base](http://docs.nativebase.io/)
- [react-native-community](https://github.com/react-native-community)
- [react-native](https://facebook.github.io/react-native/)
- [react-navigation](https://reactnavigation.org/)
- [redux-logger](https://github.com/evgenyrodionov/redux-logger)
- [redux-persist](https://github.com/rt2zz/redux-persist)
- [redux](http://redux.js.org/)
- [reselect](https://github.com/reactjs/reselect)

repository: mnishiguchi/react-native-redux-practice

repo_name: mnishiguchi/react-native-redux-practice


text:
# django-passcode
Django passcode is a project to enable mobile device registration and verification using SMS based passcode.
This is the totally reworked fork of original [django-passcode](https://github.com/sgurminder/django-passcode).

Here is how it works:
1. User register on the server using POST request with the mobile phone number and device id.
1. Receive in response passcode
1. Send POST request to "verify" endpoint with mobile phone, device_id, and passcode
1. Receive in response token to access API

## Features and concept of work
1. Only 1 token for one set of device_id and phone number. If you request new token for the same set, the old one will be deleted from the system.
1. Full log of every generated passcode
1. You can set how often one passcode for same device_id and phone number can be requested
1. You can set how long time the passcode can be valid
1. For token management used Knox and basic User model in Django. If automatically generate User with username=mobile_number and password=mobile_number+salt. This is useful if you want to use different authentication methods.
1. It uses the one-to-one field in MobileDevice model to connect to token, which is connected to User model. This save all tokens, which is generated outside the passcode. If there is already some token in this field, it will use owner of this token for token generation.  So you can create user on your app, add his mobile phone number, device_id, and token to the table, and it will work with no problem.
1. User created only after successful verification of the passcode

## Requirments
  - Django Rest Framework (rest_framework)
  - Knox

This must be in INSTALLED_APPS in settings.py:

## Installation

  - Include ``` passcode ``` in Installed apps of your project
  - Add  ``` url(r'^signup/', include('passcode.urls')) ``` in urls.py of your project
  - Add any settings you wish in settings.py of your Django project

# Usage

## API

### 1. Register: POST request to <your_domain>/signup/register/

Post parameters
   - mobile phone
   - Device id

Response: JSON response
On success:
```
{"code" : "Success"}
 ```

On Error:
```
{"code" : "Info about error"}
 ```

### 2. Verify: POST request to <your_domain>/signup/verify/

Post parameters
     - mobile phone
     - Device id
     - passcode

Response : JSON response

On success:
```
{"code" : "Success",
"token": "485288c44d3f37a993a1d7d05ac3ec321016ad14dfffacb26b2e67482079cafc"}
```
On Error:
 ```
  {"code" : "Info about error"}
 ```

 ## Settings

 You can set these settings in your settings.py:

    PASSCODE_SETTINGS = {
        "PASSCODE_SALT": "some random salt for user's password",
        "PASSCODE_LENGTH": 4,
        "PASSCODE_EXPIRE_MIN": 5,
        "TIME_BETWEEN_PASSCODE": 1
        }


text:
# 🗺 CNKit

[![Travis](https://img.shields.io/travis/kiliankoe/CNKit.svg)](https://travis-ci.org/kiliankoe/CNKit)
[![Documentation](https://kiliankoe.github.io/CNKit/badge.svg)](https://kiliankoe.github.io/CNKit/)

Access [Campus Navigator](https://navigator.tu-dresden.de) data through a swift wrapper.

## Installation

CNKit is available through Carthage/Punic and Swift Package Manager, whatever floats your boat.

```swift
// Carthage
github "kiliankoe/CNKit"

// Swift Package Manager
.package(url: "https://github.com/kiliankoe/CNKit", from: "latest version")
```

## Overview

The basic interaction is the same through all model types. Here as an example for the all-encompassing [`Campus`](x-source-tag://Campus) type.

```swift
Campus.fetch { result in
    guard let buildings = result.success else { return }
    for building in buildings {
        print(building.abbrev)
    }
}

// P38, APB, ...
```

All types returned by the API have a method called `fetch` (or very similar) to request either a specific resource or a list of them. Any necessary params are required by the method.

Further documentation can be found here: https://kiliankoe.github.io/CNKit/

repository: kiliankoe/CNKit

gha_language: Swift

repo_name: kiliankoe/CNKit


text:
---
title: v0.3.1
date: 2019-03-07T00:00:00Z
version: 0
subversion: 3
extraversion: 1
codename: Iapetus
commit: 94e6454ede6bf4acc047474f73fe0de2a80a3696
---

This release is a bugfix that adds support for newlib back to
Unikraft. Due to changes in unikraft's vfscore library, newlib did not
properly compile against v0.3. This release fixes this problem.

All xenbits-hosted unikraft repositories (unikraft, newlib, lwip, as
well as the example applications helloworld and httpreply) at
`RELEASE-0.3.1` tag are compatible with each other and can be built and
linked together again.

repository: hlef/docs

gha_license_id: NOASSERTION

repo_name: hlef/docs


text:
Windows
=======

The Windows release is created on Linux using cross compilation. The release is built with `./release.sh windows-amd64`, which runs the Go cross compiler in the `fstab/grok_exporter-compiler-amd64` Docker image.

Continuous integration for Windows is run on [AppVeyor](https://ci.appveyor.com/project/fstab/grok-exporter) as configured in `.appveyor.yml`.

However, if Windows tests fail it is sometimes useful to reproduce this locally in a Windows VM. The following describes how to set up a Windows 10 VM on VirtualBox for running Windows tests locally.

* Create a Windows 10 Home Edition VM using the official ISO from [https://www.microsoft.com/software-download/windows10](https://www.microsoft.com/software-download/windows10). You don't need a license key to do that. I used 8G RAM and 60G disk, but that might not be necessary.
* Install Go as an MSI from [https://golang.org/](https://golang.org/) and add `C:\Go\bin` to your `PATH`.
* Install `msys2-x86_64` from [https://www.msys2.org](https://www.msys2.org).
* Run the mingw64 shell in the msys2 terminal by double-clicking `C:\msys64\mingw64.exe`.
* The following steps must be performed in the msys2 terminal:
  * Repeatedly run `pacman -Syu` until all packages are up-to-date.
  * Run
    ```
    pacman -S base-devel \
              mingw-w64-i686-toolchain \
              mingw-w64-x86_64-toolchain \
              git \
              mingw-w64-i686-cmake \
              mingw-w64-x86_64-cmake
    ```
  * Download the latest `oniguruma` release from [https://github.com/kkos/oniguruma/releases](https://github.com/kkos/oniguruma/releases) and install it as follows (replace 6.9.2 with the current version):
    ```
    tar xfz onig-6.9.2.tar.gz
    cd onig-6.9.2
    ./configure --host=x86_64-w64-mingw32 --prefix=/C/msys64/mingw64
    make
    make install
    ```
  * Clone `grok_exporter` from [https://github.com/fstab/grok_exporter](https://github.com/fstab/grok_exporter). Build and run it as follows:
    ```
    git clone https://github.com/fstab/grok_exporter.git
    cd grok_exporter
    git submodule update --init --recursive
    alias go=/C/Go/bin/go
    go fmt ./...
    go vet ./...
    go test ./...
    go install
    ```
    This will create `grok_exporter.exe` in `C:\Users\...\go\bin\`.

gha_language: Go


text:
---
title: "Circular Visualization in R"
author: "Zuguang Gu"
date: "last revised on 2019-07-08"
site: bookdown::bookdown_site
output: bookdown::gitbook
documentclass: book
bibliography: [book.bib]
biblio-style: apalike
link-citations: yes
github-repo: jokergoo/circlize_book
cover-image: images/circlize_cover.jpg
url: 'https\://bookdown.org/jokergoo/circlize-book/book'
description: "This book provides a comprehensive overview of implementing circular visualization in R by cirlize package, espeically focusing on visualizaing high dimentional genomic data and revealing complex relationships by Chord diagram."
---

# About {-}

This is the documentation of the
[**circlize**](https://cran.r-project.org/package=circlize) package. Examples
in the book are generated under version 0.4.7.

If you use **circlize** in your publications, I am appreciated if you can cite:

Gu, Z. (2014) circlize implements and enhances circular visualization in R.
Bioinformatics. DOI:
[10.1093/bioinformatics/btu393](https://doi.org/10.1093/bioinformatics/btu393)

<img src="images/circlize_cover.jpg" style="width:500px;border:2px solid black;" />


text:
# BlurLockView
[![WoWoViewPager](https://github.com/Nightonke/WoWoViewPager/blob/master/app/src/main/res/mipmap-hdpi/ic_launcher.png?raw=true)](https://github.com/Nightonke/WoWoViewPager)
[![BoomMenu](https://github.com/Nightonke/BoomMenu/blob/master/app/src/main/res/mipmap-hdpi/ic_launcher.png?raw=true)](https://github.com/Nightonke/BoomMenu)
[![CoCoin](https://github.com/Nightonke/CoCoin/blob/master/app/src/main/res/mipmap-hdpi/ic_launcher.png?raw=true)](https://github.com/Nightonke/CoCoin)
[![BlurLockView](https://github.com/Nightonke/BlurLockView/blob/master/app/src/main/res/mipmap-hdpi/ic_launcher.png?raw=true)](https://github.com/Nightonke/BlurLockView)
[![LeeCo](https://github.com/Nightonke/LeeCo/blob/master/app/src/main/res/mipmap-hdpi/ic_launcher.png?raw=true)](https://github.com/Nightonke/LeeCo)
[![GithubWidget](https://github.com/Nightonke/GithubWidget/blob/master/app/src/main/res/mipmap-hdpi/ic_launcher.png?raw=true)](https://github.com/Nightonke/GithubWidget)
[![JellyToggleButton](https://github.com/Nightonke/JellyToggleButton/blob/master/app/src/main/res/mipmap-hdpi/ic_launcher.png?raw=true)](https://github.com/Nightonke/JellyToggleButton)
[![FaceOffToggleButton](https://github.com/Nightonke/FaceOffToggleButton/blob/master/app/src/main/res/mipmap-hdpi/ic_launcher.png?raw=true)](https://github.com/Nightonke/FaceOffToggleButton)

![BlurLockView](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/in_out.gif)

Lock view with blur effect. Easy to customise.

# [中文文档](https://github.com/Nightonke/BlurLockView/blob/master/README-ZH.md)

# Note

1. The blur effect comes from [500px-android-blur](https://github.com/500px/500px-android-blur).
2. More animations for showing or hiding the BlurLockView will be added.
3. In the demo, I use [Material-Dialogs](https://github.com/afollestad/material-dialogs) for convenient.

# Usage

[Demo](https://github.com/Nightonke/BlurLockView#demo)
[Gradle](https://github.com/Nightonke/BlurLockView#gradle)
[Easy to Use](https://github.com/Nightonke/BlurLockView#easy-to-use)
[Show and Hide](https://github.com/Nightonke/BlurLockView#show-and-hide)
[Listeners](https://github.com/Nightonke/BlurLockView#listeners)
[Blur Effect](https://github.com/Nightonke/BlurLockView#blur-effect)
[Keyboard](https://github.com/Nightonke/BlurLockView#keyboard)
[Text](https://github.com/Nightonke/BlurLockView#text)
[Font](https://github.com/Nightonke/BlurLockView#font)
[Style](https://github.com/Nightonke/BlurLockView#style)
[Incorrect Password](https://github.com/Nightonke/BlurLockView#incorrect-password)

### Demo

Try demo here:
[Download from Fir](http://fir.im/yakc)
[Download from Github](https://github.com/Nightonke/BlurLockView/blob/master/Apk/BlurLock-V1.0.0.apk?raw=true)
![Fir](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/fir.png)
You can get all about BlurLockView from the demo.
![Settings](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/test.png)
![Operations](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/operations.png)

### Gradle

Add this to build.gradle:
```java
dependencies {
    ...
    compile 'com.nightonke:blurlockview:1.0.0'
    ...
}
```

### Easy to Use

Add the xml code:
```xml
<com.nightonke.blurlockview.BlurLockView
    android:id="@+id/blurlockview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
```
Notice that you should set the BlurLockView to cover the view than need to be blured.

Add this to initialize the BlurLockView:
```java
// Set the view that need to be blurred
blurLockView.setBlurredView(imageView1);

// Set the password
blurLockView.setCorrectPassword(getIntent().getStringExtra("PASSWORD"));
```

### Show and Hide

You can choose duration, direction and ease type to show or hide the BlurLockView.
For instance, the gif at the start of readme shows as ```ShowType.FADE_IN``` with 1000ms and ```HideType.FADE_OUT``` with 1000ms.
You can check all the directions and ease types in the demo above.

![Ease](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/ease.gif)

### Listeners

BlurLockView.OnPasswordInputListener
```java
@Override
public void correct(String inputPassword) {
    // the input password is correct
    // you can hide the BlurLockView, for example
}

@Override
public void incorrect(String inputPassword) {
    // the input password is incorrect
}

@Override
public void input(String inputPassword) {
    // the password is being input
}
```

BlurLockView.OnLeftButtonClickListener
```java
@Override
public void onClick() {
    // The left button is being clicked
}
```
Implements the listeners above and then:
```java
blurLockView.setOnLeftButtonClickListener(this);
blurLockView.setOnPasswordInputListener(this);
```
Notice that the right button is set as "Backspace" usually, so there is not OnRightButtonClickListener.

### Blur Effect

You can set the effect of blur with 3 parameters.
1. **DownsampleFactor**, with ```setDownsampleFactor(int downsampleFactor)```, the smaller, the clearer.
2. **BlurRadius**, with ```setBlurRadius(int blurRadius)```, the smaller, the clearer.
3. **OverlayColor**, with ```setOverlayColor(int color)```, to change the overlay color of BlurLockView.

Examples:
![clear](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/clear.png)
![unclear](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/unclear.png)

![red](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/red.png)
![blue](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/blue.png)

### Keyboard

You can use different keyboard to get different password.
```java
setType(Password type, boolean smoothly);
```
Choose ```Password.NUMBER```(default) or ```Password.TEXT``` and whether change password type smoothly.
Notice that the password with text is case-insensitive(I will improve this).

![Password Type](https://github.com/Nightonke/BlurLockView/blob/master/Pictures/keyboard.gif)

### Text

1. Set the text of title with ```setTitle(String string)```.
2. Set the text of left button with ```setLeftButton(String string)```.
3. Set the text of right button with ```setRightButton(String string)```.

### Font

You can set all the font of text with ```setTypeface(Typeface typeface)```.

### Style

**1.** Set the background of buttons in Password.TEXT with ```setSmallButtonViewsBackground(int id)```. The default resource drawable is:
```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <shape android:shape="oval"  >

        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="oval"  >
            <stroke android:width="1dip" android:color="@color/default_button_press" />
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>
    <item >
        <shape android:shape="oval"  >
            <stroke android:width="1dip" android:color="@color/default_button_press" />
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>
</selector>
```

**2.** Set the click effect of buttons in Password.TEXT with ```setBigButtonViewsClickEffect(int id)```. The default resource drawable is:
```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item >
        <shape android:shape="oval"  >
            <solid android:color="@color/default_button_press"/>
        </shape>
    </item>
</selector>
```
**3.** When you click the buttoms in Password.TEXT, the effect above will disappear and you can set the duration by ```setSmallButtonViewsClickEffectDuration(int duration)```.

**4.** Similarly, you can set the 3 styles of buttons in Password.NUMBER like above with ```setBigButtonViewsBackground(int id)```, ```setBigButtonViewsClickEffect(int id)``` and ```setBigButtonViewsClickEffectDuration(int duration)```.

**5.** Try to set the color of all the text with ```setTextColor(int color)```.

**6.** You can get the widgets in BlurLockView by:
1. ```public TextView getTitle() {return title;}``` to get the title.
2. ```public TextView getLeftButton() {return leftButton;}``` to get the left button.
3. ```public TextView getRightButton() {return rightButton;}``` to get the right button.
4. ```public BigButtonView[] getBigButtonViews() {return bigButtonViews;}``` to get the 10 number buttons in array.
5. ```public SmallButtonView[][] getSmallButtonViews() {return smallButtonViews;}``` to get all the text buttons in array. Notice that some buttons in the array is null. you can find all the real buttons by this:

```java
private final char CHARS[][] = {
        {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'},
        {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'},
        {   'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'  },
        {        'Z', 'X', 'C', 'V', 'B', 'N', 'M'       }
};
```

### Incorrect Password

BlurLockView counts for incorrect input times. You can use ```getIncorrectInputTimes()``` to get the times and use ```setIncorrectInputTimes(int incorrectInputTimes)``` to reset the times.

# Versions
### 1.0.0

# Todo
1. More animations.
2. Change the Password.TEXT to case-sensitive with other signals.

# License

    Copyright 2016 Nightonke

    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.


text:
---
layout: post
title: "Look What You Made Me Do 歌词+中文翻译"
date: 2020-04-19 06:06:00 +0800
categories: 英文学习
tag: "翻译"
---

* content
{:toc}

```html
I don't like your little games
我不喜欢你那些小把戏
Don't like your tilted stage
不喜欢你那倾斜飘浮空中的舞台
The role you made me play
你让我演的角色
Of the fool, no, I don 't like you
像个白痴，喔，我不喜欢你
I don't like your perfect crime
我不喜欢你自以为完美的犯罪
How you laugh when you lie
还有你说谎时的笑容
You said the gun was mine
你说这枪是我的
Isn't cool, no, I don't like you
说真的，一点都不酷，我不喜欢你

But I got smarter, I got harder in the nick of time
但在最后一刻（最糟糕的事情来临之前，或许指的是死亡）我变得更聪明，我更努力
Honey, I rose up from the dead, I do it all the time
亲爱的，我每天都在死亡边缘挣扎努力
I've got a list of names and yours is in red, underlined
我手上有一些名单，你的名字红色下划线标注
I check it once, then I check it twice, oh!

却将我锁在外头，吃着大餐？
The world goes on, another day, another drama, drama
世界不断前进，或许只是不同天，不同的演出
But not for me, not for me, all I think about is karma
但对我来说不是，对我来说不是，我所想只剩因果轮回
And then the world moves on, but one thing's for sure
世界依然在走，但有一件事是确定的
Baby, I got mine, but you'll all get yours
宝贝，我有我的轮回，你也会找到你自己的

But I got smarter, I got harder in the nick of time
但在最后一刻我变得更聪明，我更努力
Honey, I rose up from the dead, I do it all the time
亲爱的，我从死亡中升起，我一直都在努力
I've got a list of names and yours is in red, underlined
我手上有一些名单，包括你的，画着红线
I check it once , then I check it twice, oh!

抱歉，旧的泰勒斯现在没办法接电话
"Why?"
什么？为什么
"Oh 'cause she's dead!"

url: https://raw.githubusercontent.com/EironnWalker/eironnwalker.github.io/04f80d17d3dbc431f9486d80c426666b962c2005/_posts/english/2020-04-19-Look What You Made Me Do 歌词+中文翻译.md


text:
# Quick Reviews 11/12/2019

## HMAC-based Extract-and-Expand Key Derivation Function (HKDF)

**Approved** | [#corefx/29660](https://github.com/dotnet/corefx/issues/29660#issuecomment-553037689) | [Video](https://www.youtube.com/watch?v=6NLJ1csBw14&t=0h0m0s)

* ~~`Expand`. We should align the optionality of the `info` parameter between the span version and the byte array version.~~
    - This might cause ambiguity. We decided that optionality is omitted from the span versions
    - However, we should align the order to `outputLength` and `output`. We should swap `output` and `info` in the span-based version.

```C#
namespace System.Security.Cryptography
{
    public static class HKDF
    {
        public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm, byte[] salt = null);
        public static int Extract(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> ikm, ReadOnlySpan<byte> salt, Span<byte> prk);

        public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk, int outputLength, byte[] info = null);
        public static void Expand(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> prk, Span<byte> output, ReadOnlySpan<byte> info);

        public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm, int outputLength, byte[] salt = null, byte[] info = null);
        public static void DeriveKey(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> ikm, Span<byte> output, ReadOnlySpan<byte> salt, ReadOnlySpan<byte> info);
    }
}
```
## Add cancellation overloads on HttpClient and HttpContent

**Approved** | [#corefx/32615](https://github.com/dotnet/corefx/issues/32615#issuecomment-553050411) | [Video](https://www.youtube.com/watch?v=6NLJ1csBw14&t=0h23m44s)

* Looks good, but optionality is pointless because the overload without the token already exists
* Name of methods on `HttpContent` should be `ReadAsXxx`
* Return types needs fixing up

```C#
partial class HttpClient
{
    // New APIs

    public Task<byte[]> GetByteArrayAsync(string requestUri, CancellationToken cancellationToken);
    public Task<byte[]> GetByteArrayAsync(Uri requestUri, CancellationToken cancellationToken);

    public Task<Stream> GetStreamAsync(string requestUri, CancellationToken cancellationToken);
    public Task<Stream> GetStreamAsync(Uri requestUri, CancellationToken cancellationToken);

    public Task<string> GetStringAsync(string requestUri, CancellationToken cancellationToken);
    public Task<string> GetStringAsync(Uri requestUri, CancellationToken cancellationToken);

    // Existing APIs

    public Task<byte[]> GetByteArrayAsync(string requestUri);
    public Task<byte[]> GetByteArrayAsync(Uri requestUri);

    public Task<Stream> GetStreamAsync(string requestUri);
    public Task<Stream> GetStreamAsync(Uri requestUri);

    public Task<string> GetStringAsync(string requestUri);
    public Task<string> GetStringAsync(Uri requestUri);
}

partial class HttpContent
{
    // New APIs

    public Task<byte[]> ReadAsByteArrayAsync(CancellationToken cancellationToken);
    public Task<Stream> ReadAsStreamAsync(CancellationToken cancellationToken);
    public Task<string> ReadAsStringAsync(CancellationToken cancellationToken);

    // Existing APIs

    public Task<byte[]> ReadAsByteArrayAsync();
    public Task<Stream> ReadAsStreamAsync();
    public Task<string> ReadAsStringAsync();
}
```
## Add List<T>.CopyTo(Span<T>) overloads

**Approved** | [#corefx/33006](https://github.com/dotnet/corefx/issues/33006#issuecomment-553078596) | [Video](https://www.youtube.com/watch?v=6NLJ1csBw14&t=0h40m29s)

Wow, that took quoit a bit 😄

* Makes sense. We should just make sure that `List<T>.CopyTo(someInt, someArray, anotherInt)` doesn't magically bind to the span version.
    - While not a breaking having the third parameter having different behavior is bad (`arrayIndex` vs. `count`)

```C#
public partial class List<T>
{
    // public void CopyTo(int index, T[] array, int arrayIndex, int count);
    // public void CopyTo(T[] array, int arrayIndex);
    // public void CopyTo(T[] array);

    public void CopyTo(Span<T> destination);
    public void CopyTo(int sourceIndex, int count, Span<T> destination);
}
```
## Expose the match length when using String.IndexOf in culture specific mode

**Needs Work** | [#corefx/33543](https://github.com/dotnet/corefx/issues/33543#issuecomment-553082487) | [Video](https://www.youtube.com/watch?v=6NLJ1csBw14&t=1h29m9s)

@GrabYourPitchforks mentioned that he's planning on addressing this issue in UTF8 string. He's thinking of exposing something like `TryFind` that outputs a `Range`. We should make sure the work aligns.
## Hide Thread.VolatileRead and Thread.VolatileWrite

**Approved** | [#corefx/33701](https://github.com/dotnet/corefx/issues/33701#issuecomment-553086736) | [Video](https://www.youtube.com/watch?v=6NLJ1csBw14&t=1h37m21s)

* This seems like a good candidate for a code fixer that replaces the call site.
* Usage of these APIs is low.
* We should consider this API in our plan for obsoletion.
* Hiding these APIs seems fine.
## ComputeHash Async required

**Approved** | [#corefx/36068](https://github.com/dotnet/corefx/issues/36068#issuecomment-553088815) | [Video](https://www.youtube.com/watch?v=6NLJ1csBw14&t=1h48m11s)

* Makes sense. We shouldn't make the API virtual though because it just does an async read and then forwards to the existing sync API
* Without `virtual`, we don't need `HashCoreAsync`

```C#
public class HashAlgorithm
{
    public Task<byte[]> ComputeHashAsync(Stream inputStream, CancellationToken cancellationToken = default);
}
```

repository: dotnet/apireviews

repo_name: dotnet/apireviews


text:
# Navigation Pane

:heavy_exclamation_mark: There is also a version of [this document with code samples in C#](./navigationpane.md) :heavy_exclamation_mark: |
----------------------------------------------------------------------------------------------------------------------------------------- |

The navigation pane project type includes a navigation menu displayed in a panel at the side of the screen and which can be expanded with the Hamburger icon.

This document covers:

* [Modifying the menu items](#menu)
* [Using the navigation pane with command bars](#commandbar)
* [Have the menu item invoke code rather than navigate](#invokecode)

To update to navigation view read the following [document](./updatetonavigationview.md).

## Modifying the menu items

The menu can be modified in the following ways.

* Change the icon for an item in the navigation panel menu
* Change the text for an item in the navigation panel menu

### Change the icon for an item

By default every item in the navigation pane is displayed with the symbol for a document.
When every item has the same icon it is hard to differentiate between them when the navigation panel is collapsed. In almost all cases you will want to change the icon used.

![](../resources/modifications/NavMenu_Different_Symbols.png)

Navigate to `Views/ShellPage.xaml` and change the `NavigationViewItems` in the `NavigationView MenuItems` property.

The code below shows the symbols used to create the app shown in the image above.

```xml
<NavigationView.MenuItems>
    <!--
    TODO WTS: Change the symbols for each item as appropriate for your app
    More on Segoe UI Symbol icons: https://docs.microsoft.com/windows/uwp/style/segoe-ui-symbol-font
    Or to use an IconElement instead of a Symbol see https://github.com/Microsoft/WindowsTemplateStudio/blob/master/docs/projectTypes/navigationpane.md
    Edit String/en-US/Resources.resw: Add a menu item title for each page
    -->
    <NavigationViewItem
        x:Uid="Shell_Main"
        Icon="Home"
        helpers:NavHelper.NavigateTo="views:MainPage" />
    <NavigationViewItem
        x:Uid="Shell_Map"
        Icon="Map"
        helpers:NavHelper.NavigateTo="views:MapPage" />
    <NavigationViewItem
        x:Uid="Shell_MasterDetail"
        Icon="DockLeft"
        helpers:NavHelper.NavigateTo="views:MasterDetailPage" />
    <NavigationViewItem
        x:Uid="Shell_Tabbed"
        Icon="Document"
        helpers:NavHelper.NavigateTo="views:TabbedPage" />
    <NavigationViewItem
        x:Uid="Shell_WebView"
        Icon="Globe"
        helpers:NavHelper.NavigateTo="views:WebViewPage" />
</NavigationView.MenuItems>
```

The icons are created using the `Windows.UI.Xaml.Controls.Symbol` enumeration. You can view all the symbols available at <https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.symbol>

You can also set the menu item to use an `IconElement` directly. Like this:

```xml
<NavigationView.MenuItems>
    <NavigationViewItem x:Uid="Shell_Map" helpers:NavHelper.NavigateTo="views:MapPage">
        <NavigationViewItem.Icon>
            <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" />
        </NavigationViewItem.Icon>
    </NavigationViewItem>
</NavigationView.MenuItems>
```

### Change the text for an item

The text for a shell navigation item comes from the localized string resources. For an item which defines the x:Uid `Shell_Main` the value `Shell_Main.Content` corresponds with an entry in `Resources.resw`. Change the value in the resources file to alter what is displayed in the navigation menu.

## Using the navigation pane and command bars

The following is intended as an aid to anyone wanting to add a `CommandBar` to one or all pages in an app using a Navigation Pane.

### Avoid page.TopAppBar and page.BottomAppBar

Each page has a property for `TopAppBar` and `BottomAppBar` intended to hold a `CommandBar`. Despite their names, they put the CommandBar at the top (or bottom) of the window, not the Page that declares it. Because the NavigationPane works by putting a page within the ShellPage this causes the CommandBar to overlap with the NavigationView and is not desirable. Instead use one of the techniques shown below.

### Adding a CommandBar to a single page

Because of the issue identified above, to add a `Commandbar` to the **bottom** of a single page, simply position it at the bottom of the grid intended for displaying content.

```xml
    <Grid
        Grid.Row="1"
        Background="{ThemeResource SystemControlPageBackgroundChromeLowBrush}">
        <!--The SystemControlPageBackgroundChromeLowBrush background represents where you should place your content.
            Place your content here.-->

        <CommandBar VerticalAlignment="Bottom">
            <AppBarButton x:Uid="AdminButton" Icon="Admin" />
        </CommandBar>
    </Grid>
```

If adding the bar at the **top** of the page it can incorporate the page's title text in the content area. Like this:

```xml
    <Grid.RowDefinitions>
        <RowDefinition x:Name="TitleRow" Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <CommandBar>
        <CommandBar.Content>
            <Grid>
                <TextBlock
                    x:Name="TitlePage"
                    x:Uid="Main_Title"
                    Text="Navigation Item 2"
                    Style="{StaticResource PageTitleStyle}" />
            </Grid>
        </CommandBar.Content>
        <AppBarButton Icon="Add" Label="Add" />
    </CommandBar>
```

### Adding a CommandBar to every page in the app

By adding a CommandBar to the `ShellPage` it is visible when navigating to any page.

To add `CommandBar` at the bottom of every page, modify the contents of `ShellPage.xaml` to add a `Grid` around the `NavigationView` and also include a `CommandBar`.

```xml
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <NavigationView>
            <!--  Contents of NavigationView menu omitted to brevity  -->
        </NavigationView>
        <CommandBar Grid.Row="1">
            <AppBarButton Icon="Camera" Label="Picture" />
        </CommandBar>
    </Grid>
```

The above approach can be used to put the bar above the `NavigationView` by swapping the rows in the grid.
Alternatively, a bar can be added inside the NavigationView using the HeaderTemplate.

Remove Header property from `NavigationView` declaration.

**MVVM Design Patterns**
```xml
Header="{x:Bind ViewModel.Selected.Content, Mode=OneWay}"
```

**Code Behind**
```xml
Header="{x:Bind Selected.Content, Mode=OneWay}"
```
Adapt the HeaderTemplate setting Selected.Content to the Title TextBlock and adding the CommandBar.

```xml
<NavigationView>
    <!--  Contents of NavigationView menu omitted to brevity  -->
    <NavigationView.HeaderTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <CommandBar Grid.ColumnSpan="2">
                    <AppBarButton Icon="Save" Label="Save" Command="{Binding SaveCommand}" />
                </CommandBar>
                <TextBlock
                    Style="{StaticResource TitleTextBlockStyle}"
                    Margin="12,0,0,0"
                    VerticalAlignment="Center"
                    Text="{Binding Selected.Content}" />
            </Grid>
        </DataTemplate>
    </NavigationView.HeaderTemplate>
<NavigationView>
```

**A Note about the above code examples.**

Events and commands are not shown in the above code but can easily be added like any other button click event or command. Note that if using the techniques for adding the bar to every page, the events or commands should be handled by the ShellPageViewModel (or in ShellPage.xaml.vb if using CodeBehind.)

In all the above code examples the `Label` values have been hard-coded. This is to make the samples simpler. To use localized text, set the `x:Uid` value for the `AppBarButton` and add a corresponding resource entry for "{name}.Label".

The examples also only show a single `AppBarButton` being added. This is to keep the code sample as simple as possible but you can add any appropriate content to the bar, as [documented here](https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/app-bars).

## Invoke code on NavigationView

Extending the app to add this functionality requires making two changes.

1. Add a HyperLink in the FooterTemplate.
2. Add a Command to handle code on HyperLink click.

**ShellPage.xaml**
```xml
<NavigationView>
    <NavigationView.PaneFooter>
        <StackPanel>
            <HyperlinkButton
                x:Uid="Shell_ShowInfo"
                Margin="16,0"
                Command="{x:Bind ViewModel.ShowInfoCommand}" />
        </StackPanel>
    </NavigationView.PaneFooter>
</NavigationView>
```

Add a command to run the code in `ShellViewModel.vb` (MVVMBasic or MVVMLight) or `ShellPage.xaml.vb` (CodeBehind)
```vbnet
    Private _showInfoCommand as ICommand
    Public Property ShowInfoCommand As ICommand
        Get
            Return If(_showInfoCommand, (__InlineAssignHelper(_showInfoCommand, New RelayCommand(OnShowInfo)))
        End Get
    End Property

    Private Sub OnShowInfo()
        'TODO: Run command code
    End Sub
```

repository: Habatchii/WindowsTemplateStudio

branch_name: refs/heads/dev

gha_language: C#

repo_name: Habatchii/WindowsTemplateStudio


text:
# Introduction

## Anonymous Functions

Functions are treated as first class citizens in Elixir. This means that:

- Named and anonymous functions can be assigned to variables.
- Named and anonymous functions can be passed around like data as arguments and return values.
- Anonymous functions can be created dynamically.

Anonymous functions, in contrast to named functions, don't have a static reference available to them, they are only available if they are assigned to a variable or immediately invoked.

We might use anonymous functions to:

- Hide data using lexical scope (also known as a closure).
- Dynamically create functions at run-time.

Anonymous functions start with the reserved word `fn`, the arguments are separated from the body of the function with the `->` token, and they are finished with an `end`. As with named functions, the last expression in the function is _implicitly returned_ to the calling function.

To invoke a function reference, you must use a `.` between the reference variable and the list of arguments:

```elixir
function_variable = fn param ->
  param + 1
end

function_variable.(1)
# => 2
```

You can even use short hand capture notation to make this more concise:

```elixir
variable = &(&1 + 1)

variable.(1)
# => 2
```

## Bit Manipulation

Elixir supports many functions for working with bits found in the _Bitwise module_.

- `band/2`: bitwise AND
- `bsl/2`: bitwise SHIFT LEFT
- `bsr/2`: bitwise SHIFT RIGHT
- `bxor/2`: bitwise XOR
- `bor/2`: bitwise OR
- `bnot/1`: bitwise NOT

Here is an example how to use a bitwise function:

```elixir
Bitwise.bsl(1, 3)
# => 8
```

All bitwise functions only work on integers.

If you are running Elixir version 1.9 or lower, you will need to call `require Bitwise` at the beginning of the module definition to be able to use the _Bitwise_ module.

repository: exercism/elixir

gha_language: Elixir

repo_name: exercism/elixir


text:
Ignitions\_FWI\_11\_2020
================
Zjrobbin
11/19/2020

``` r
library(RColorBrewer)
library(pscl)
```

    ## Warning: package 'pscl' was built under R version 4.0.3

    ## Classes and Methods for R developed in the
    ## Political Science Computational Laboratory
    ## Department of Political Science
    ## Stanford University
    ## Simon Jackman
    ## hurdle and zeroinfl functions by Achim Zeileis

``` r
library(plyr)
```

#### FWI\~ Ignition relationship

The fire weather index and igntion relationship was updated in Nov 2020
I created to script to better explain the new choices available within
the code, code is still based on AK 2017 work -ZR

Here is an example of the input file
<https://github.com/LANDIS-II-Foundation/Extension-SCRPPLE/blob/master/Testing/Core7-SCRAPPLE2.6/scrapple.txt>

The user currently has two choices in shape in fititng the data the
ignition algorithim.

  - Poisson
  - ZeroInflated Poisson

This choice is entered on line 29 If ZeroInflatedPoisson is chosen an
additional four parameters are needed.

  - LightningIgnitionsBinomialB0
  - LightningIgnitionsBinomialB1
  - AccidentalIgnitionsBinomialB0
  - AccidentalIgnitionsBinomialB1

## Example

For this example we will be using data from Karen Shorts Fire Database
from a dataset used for the Southern Applachain Landsacpe

\*\* Short, Karen C. 2017. Spatial wildfire occurrence data for the
United States, 1992-2015 \[FPA\_FOD\_20170508\]. 4th Edition. Fort
Collins, CO: Forest Service Research Data Archive.
<https://doi.org/10.2737/RDS-2013-0009.4>
<https://www.fs.usda.gov/rds/archive/Product/RDS-2013-0009.4/> \*\*

Abstract:This data publication contains a spatial database of wildfires
that occurred in the United States from 1992 to 2015. It is the third
update of a publication originally generated to support the national
Fire Program Analysis (FPA) system. The wildfire records were acquired
from the reporting systems of federal, state, and local fire
organizations. The following core data elements were required for
records to be included in this data publication: discovery date, final
fire size, and a point location at least as precise as Public Land
Survey System (PLSS) section (1-square mile grid). The data were
transformed to conform, when possible, to the data standards of the
National Wildfire Coordinating Group (NWCG). Basic error-checking was
performed and redundant records were identified and removed, to the
degree possible. The resulting product, referred to as the Fire Program
Analysis fire-occurrence database (FPA FOD), includes 1.88 million
geo-referenced wildfire records, representing a total of 140 million
acres burned during the 24-year period.

[metadata](https://www.fs.usda.gov/rds/archive/products/RDS-2013-0009.4/_metadata_RDS-2013-0009.4.html)

These data were spatially located then divided into lightning ignitions
and accidental-human ignited values.

Here we can see the number of lightning ignited fires per year

``` r
red<-RColorBrewer::brewer.pal(9,'YlOrRd')
#plot no of fires/yr
l_fire_days_sort_count<- cbind(l_fire_days_sort, rep(1, nrow(l_fire_days_sort)))
l_fires_count <- cbind.data.frame(unique(l_fire_days_sort_count$YEAR) ,
                                 tapply(l_fire_days_sort_count$`rep(1, nrow(l_fire_days_sort))`,l_fire_days_sort_count$YEAR, sum))
colnames(l_fires_count) <- c("YEAR", "COUNT")

barplot(l_fires_count$COUNT, main ="No of ign/yr Lightning Observed",col=red,names.arg=l_fires_count$YEAR)
```

![](Ignition_FWI_11_2020_files/figure-gfm/unnamed-chunk-2-1.png)<!-- -->

and the human Ignited

``` r
h_fire_dat <- read.csv("FiresInAppsHuman2.csv")
#head(h.fire.dat)
h_fire_days <- as.data.frame(cbind(h_fire_dat$FIRE_YEAR, h_fire_dat$DISCOVER_1)) #Extracting year and julian day
colnames(h_fire_days) <- c("YEAR", "J_DAY")
h_fire_days_sort <- h_fire_days[order(h_fire_days[,1]),] #sorting by year
#plot no of fires/yr
h_fire_days_sort_count<- cbind(h_fire_days_sort, rep(1, nrow(h_fire_days_sort)))
h_fires_count <- cbind.data.frame(unique(h_fire_days_sort_count$YEAR) ,
                                  tapply(h_fire_days_sort_count$`rep(1, nrow(h_fire_days_sort))`,h_fire_days_sort_count$YEAR, sum))
colnames(h_fires_count) <- c("YEAR", "COUNT")
barplot(h_fires_count$COUNT, main ="No of ign/yr Human Accidental Observed",col=red,names.arg=h_fires_count$YEAR)
```

![](Ignition_FWI_11_2020_files/figure-gfm/unnamed-chunk-3-1.png)<!-- -->

Here we Mmtch them up with Fire weather index(FWI) data generated from
the historic record of weather fed through LANDIS-II Fire weather to get
the models calculation of FWI. See the Climate library documentation for
assistance getting FWI.

``` r
ign_types <- c("Lightning", "HumanAccidental")

fire_days_list <- list(l_fire_days_sort, h_fire_days_sort) ##organizing all ignition types into a list

##Import daily historic FWI data
FWI_dat <- read.csv("Climate-future-input-log.csv")

FWI_dat<-with(FWI_dat,aggregate(FWI,by=list(Year=Year,Timestep=Timestep),FUN=mean))

FWI_dat <- FWI_dat[,c(1,2,3)]
colnames(FWI_dat)[3]<-"FWI"
FWI_dat$ID <- paste(FWI_dat$Year, "_", FWI_dat$Timestep, sep="") #creating date identifier out of date and julian day
igns_list <- list()

for (i in 1:length(ign_types[1:2])){#THIS DOESN'T INCLUDE RX BURNS BUT THATS CAUSE WE ARE PROVIDING THOSE TO SCRAPPLE DIRECT
  ign_type_select <- fire_days_list[[i]] ##selecting each ignition type individually
  fire_days_count <- ddply(ign_type_select, .(ign_type_select$YEAR, ign_type_select$J_DAY), nrow) #finds duplicate rows in fire data
  colnames(fire_days_count) <- c("YEAR", "JD", "No_FIRES") #Renaming columns for consistency
  fire_days_count$ID <- paste(fire_days_count$YEAR, "_", fire_days_count$JD, sep="") #creating date identifier out of date and julian day

  ##Merging dataframes by year and julian day
  fire_days_short <- subset(fire_days_count, fire_days_count$YEAR < 2014) ##restricting fire records to climate file years
  FWI_short <- subset(FWI_dat, FWI_dat$Year > 1991) #restricting climate data to fire history records
  merge_col <- FWI_short$ID
  FWI_fire_merge <- join(FWI_short, fire_days_short, type="left") ##Merging based on unique date id
  FWI_fire_number <- FWI_fire_merge[,c(1,3,7)] #pulling out FWI and number of fires
  FWI_fire_number[is.na(FWI_fire_number)] <- 0 #converting NAs to 0, meaning 0 fires
  plot(FWI_fire_number[,2], FWI_fire_number[,3], main =ign_types[i], xlab = "dailyFWI", ylab = "noFires") #plotting FWI against no of fires just to look at pattern
  igns_list[[i]] <- FWI_fire_number
}
```

    ## Joining by: ID
    ## Joining by: ID

![](Ignition_FWI_11_2020_files/figure-gfm/unnamed-chunk-4-1.png)<!-- -->![](Ignition_FWI_11_2020_files/figure-gfm/unnamed-chunk-4-2.png)<!-- -->

``` r
#Lighting
print("Lighting")
```

    ## [1] "Lighting"

``` r
summary(igns_list[[1]])
```

    ##       Year           FWI            No_FIRES
    ##  Min.   :1992   Min.   : 0.000   Min.   :0.00000
    ##  1st Qu.:1998   1st Qu.: 3.105   1st Qu.:0.00000
    ##  Median :2004   Median :10.750   Median :0.00000
    ##  Mean   :2004   Mean   : 9.305   Mean   :0.07112
    ##  3rd Qu.:2010   3rd Qu.:14.533   3rd Qu.:0.00000
    ##  Max.   :2016   Max.   :41.593   Max.   :8.00000

``` r
#Humnan
print("Human")
```

    ## [1] "Human"

``` r
summary(igns_list[[2]])
```

    ##       Year           FWI            No_FIRES
    ##  Min.   :1992   Min.   : 0.000   Min.   : 0.000
    ##  1st Qu.:1998   1st Qu.: 3.105   1st Qu.: 0.000
    ##  Median :2004   Median :10.750   Median : 0.000
    ##  Mean   :2004   Mean   : 9.305   Mean   : 2.545
    ##  3rd Qu.:2010   3rd Qu.:14.533   3rd Qu.: 2.000
    ##  Max.   :2016   Max.   :41.593   Max.   :74.000

Now we individual fit the two models: One for the Lightning and one for
the Human Accidetnal.

This is where we can decide whether our model will be Poisson or Zero
Inflated Poisson:

You can read more about Poisson and Zero Inflate Poisson here.
<https://math.usu.edu/jrstevens/biostat/projects2013/rep_ZIP.pdf>

In the simpliest terms we are interested in whether the number of zeros
causes the fixed varaince in the poisson model to make the model
overdispersed. <https://en.wikipedia.org/wiki/Overdispersion>
<https://stats.stackexchange.com/questions/66586/is-there-a-test-to-determine-whether-glm-overdispersion-is-significant>

Here is both models fit to a Poisson

``` r
Lightning<-as.data.frame(igns_list[[1]])
POIS_mod_L <- glm(No_FIRES~FWI,data=Lightning, family="poisson")
summary(POIS_mod_L)
```

    ##
    ## Call:
    ## glm(formula = No_FIRES ~ FWI, family = "poisson", data = Lightning)
    ##
    ## Deviance Residuals:
    ##     Min       1Q   Median       3Q      Max
    ## -2.8054  -0.4359  -0.3245  -0.1674   7.9812
    ##
    ## Coefficients:
    ##              Estimate Std. Error z value Pr(>|z|)
    ## (Intercept) -4.268433   0.104651  -40.79   <2e-16 ***
    ## FWI          0.135562   0.006719   20.18   <2e-16 ***
    ## ---
    ## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    ##
    ## (Dispersion parameter for poisson family taken to be 1)
    ##
    ##     Null deviance: 4021.3  on 9124  degrees of freedom
    ## Residual deviance: 3590.1  on 9123  degrees of freedom
    ## AIC: 4626.6
    ##
    ## Number of Fisher Scoring iterations: 6

``` r
Accidental<-as.data.frame(igns_list[[2]])
POIS_mod_A <- glm(No_FIRES~FWI,data=Accidental, family="poisson")
summary(POIS_mod_A)
```

    ##
    ## Call:
    ## glm(formula = No_FIRES ~ FWI, family = "poisson", data = Accidental)
    ##
    ## Deviance Residuals:
    ##     Min       1Q   Median       3Q      Max
    ## -2.5357  -2.2003  -2.0163  -0.1212  18.6261
    ##
    ## Coefficients:
    ##              Estimate Std. Error z value Pr(>|z|)
    ## (Intercept)  1.167798   0.010503  111.18   <2e-16 ***
    ## FWI         -0.026771   0.001005  -26.64   <2e-16 ***
    ## ---
    ## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    ##
    ## (Dispersion parameter for poisson family taken to be 1)
    ##
    ##     Null deviance: 62891  on 9124  degrees of freedom
    ## Residual deviance: 62179  on 9123  degrees of freedom
    ## AIC: 74788
    ##
    ## Number of Fisher Scoring iterations: 6

Both of these parameters have two parameters so if you chose this model
your parameter file would read

(lines 24-29)

> LightningIgnitionsB0 -4.268433
> LightningIgnitionsB1 0.135562
> AccidentalIgnitionsB0 1.167798
> AccidentalIgnitionsB1 -0.026771

> IgnitionDistribution Poisson \<\< Poisson or ZeroInflatedPoisson

and you would include nothing in the example until line 37 (Maximum Fine
Fuels)

If you were unhappy with the fit of that model you can try a Zero
Inflated Poisson

### Zero Inflated Poisson

``` r
Lightning<-as.data.frame(igns_list[[1]])

###Lightning
zeroinf_mod_L <- zeroinfl(No_FIRES~FWI,data=Lightning, dist="poisson")
summary(zeroinf_mod_L)
```

    ##
    ## Call:
    ## zeroinfl(formula = No_FIRES ~ FWI, data = Lightning, dist = "poisson")
    ##
    ## Pearson residuals:
    ##      Min       1Q   Median       3Q      Max
    ## -0.93051 -0.25133 -0.18220 -0.08572 27.06358
    ##
    ## Count model coefficients (poisson with log link):
    ##             Estimate Std. Error z value Pr(>|z|)
    ## (Intercept) -0.63779    0.23558  -2.707  0.00678 **
    ## FWI          0.01623    0.01523   1.066  0.28648
    ##
    ## Zero-inflation model coefficients (binomial with logit link):
    ##             Estimate Std. Error z value Pr(>|z|)
    ## (Intercept)  3.83717    0.24847  15.443   <2e-16 ***
    ## FWI         -0.14822    0.01705  -8.692   <2e-16 ***
    ## ---
    ## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    ##
    ## Number of iterations in BFGS optimization: 10
    ## Log-likelihood: -2097 on 4 Df

``` r
#Tst<-predict(zeroinf_mod,type="zero")
```

``` r
Accidental<-as.data.frame(igns_list[[2]])
#Lightning$No_FIRES
###Lightning
zeroinf_mod_A<- zeroinfl(No_FIRES~FWI,data=Accidental, dist="poisson")
summary(zeroinf_mod_A)
```

    ##
    ## Call:
    ## zeroinfl(formula = No_FIRES ~ FWI, data = Accidental, dist = "poisson")
    ##
    ## Pearson residuals:
    ##      Min       1Q   Median       3Q      Max
    ## -0.83517 -0.77786 -0.74329 -0.05562 21.05612
    ##
    ## Count model coefficients (poisson with log link):
    ##              Estimate Std. Error z value Pr(>|z|)
    ## (Intercept)  1.920144   0.010591  181.30   <2e-16 ***
    ## FWI         -0.021641   0.001023  -21.16   <2e-16 ***
    ##
    ## Zero-inflation model coefficients (binomial with logit link):
    ##             Estimate Std. Error z value Pr(>|z|)
    ## (Intercept) 0.115584   0.036608   3.157  0.00159 **
    ## FWI         0.009369   0.003238   2.893  0.00381 **
    ## ---
    ## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    ##
    ## Number of iterations in BFGS optimization: 6
    ## Log-likelihood: -2.51e+04 on 4 Df

These models each have four parameters so your input would look as
follows
From line (24-35)

> LightningIgnitionsB0 -0.63779
> LightningIgnitionsB1 0.01623
> AccidentalIgnitionsB0 1.920144
> AccidentalIgnitionsB1 -0.021641

> IgnitionDistribution ZeroInflatedPoisson \<\< Poisson or
> ZeroInflatedPoisson

> LightningIgnitionsBinomialB0 3.83717
> LightningIgnitionsBinomialB1 -0.14822
> AccidentalIgnitionsBinomialB0 0.115584
> AccidentalIgnitionsBinomialB1 0.009369

How these models impact your ignition model will be data dependent.

### Testing

Here we can test how those formulas will play out within the model

``` r
FWI_dat<- read.csv("Climate-future-input-log.csv")
FWI_dat<-with(FWI_dat,aggregate(FWI,by=list(Year=Year,Timestep=Timestep),FUN=mean))

FWI_dat<-FWI_dat[FWI_dat$Year %in% seq(1992,2016),]
FWI_Test<-FWI_dat$x
Pb0<-(1.167798)
Pb1<-(-.026771)
###Possion model
Acc_Ign_Test_Pois<-rpois(9125, lambda = exp((Pb0+(Pb1*FWI_Test))))

##ZIPS model

binomb0=.115584
binomb1=.009369

b0=(1.920144)
b1=(-.021641)

alpha<-exp(binomb0+binomb1*FWI_Test)
zeroprob= alpha/(alpha+1)
Acc_Ign_Test<-ifelse((zeroprob<=runif(length(zeroprob),0,1)),
        round(rpois(9125, lambda = exp((b0+(b1*FWI_Test))))),
       0)

### Aggregate to the year
Acc_Ign_df<-cbind(FWI_dat[,c(1,2)],Acc_Ign_Test)
Acc_Years<-aggregate(list(Ignitions=Acc_Ign_df$Acc_Ign_Test),by=list(Year=Acc_Ign_df$Year),FUN=sum)

PAcc_Ign_df<-cbind(FWI_dat[,c(1,2)],Acc_Ign_Test_Pois)
PAcc_Years<-aggregate(list(Ignitions=PAcc_Ign_df$Acc_Ign_Test_Pois),by=list(Year=PAcc_Ign_df$Year),FUN=sum)

plot(PAcc_Years$Year,PAcc_Years$Ignitions,col="darkgreen",ylim=c(400,1500),pch=16,cex=1.3,xlab="Accidental Ignition",ylab="Year")
points(Acc_Years$Year,Acc_Years$Ignitions,col="purple",pch=16,cex=1.3)
points(h_fires_count$YEAR,h_fires_count$COUNT,col="orange",pch=16,cex=1.3)

legend(1995,600,legend=c("Accidental Possion","Accidental ZIPS","Karen Short"),pch=c(16,16,16),col=c("darkgreen","purple","orange"))
```

![](Ignition_FWI_11_2020_files/figure-gfm/unnamed-chunk-10-1.png)<!-- -->

We can see there is not a huge differnce but perhaps the ZIPS model has
a larger variance annually. However there is perhaps more variation in
the realworld data than is captured in the model.

Here we can compare to the results we get from the model

``` r
ZIP_Ignitions<-read.csv("scrapple-ignitions-log.csv")
Pois<-read.csv("scrapple-ignitions-logPois_2.csv")

ZIP<-aggregate(x=list(Count=ZIP_Ignitions$ActualNumberIgnitions,OtherCount=ZIP_Ignitions$AttemptedNumberIgnitions),
              by=list(Year=ZIP_Ignitions$SimulationYear,Type=ZIP_Ignitions$IgnitionType),
              FUN=sum)
P_inf<-aggregate(x=list(Count=Pois$ActualNumberIgnitions,OtherCount=Pois$AttemptedNumberIgnitions),
              by=list(Year=Pois$SimulationYear,Type=Pois$IgnitionType),
              FUN=sum)

#OIL<-OI[OI$Type==" Accidental",]

ZIPA<-ZIP[ZIP$Type==" Accidental",]
P_infA<-P_inf[P_inf$Type==" Accidental",]
#unique(Merged$IgnitionType)
plot(PAcc_Years$Year,ZIPA$Count[1:25],ylim=c(400,1500),pch=16,col="red",main="LANDIS-Accidental",ylab="Accidental Ignition",xlab="Year")
points(PAcc_Years$Year,P_infA$Count[1:25],col="blue",pch=16)
points(PAcc_Years$Year,PAcc_Years$Ignitions,col="darkgreen",pch=16,cex=1.3,xlab="Accidental Ignition",ylab="Year")
points(Acc_Years$Year,Acc_Years$Ignitions,col="purple",pch=16,cex=1.3)
points(h_fires_count$YEAR,h_fires_count$COUNT,col="orange",pch=16,cex=1.3)

legend(1995,700,legend=c("Accidental Possion","Accidental ZIPS","Karen Short","LANDIS POISSON","LANDIS ZIPS"),pch=c(16,16,16,16,16),col=c("darkgreen","purple","orange",'blue','red'))
```

![](Ignition_FWI_11_2020_files/figure-gfm/unnamed-chunk-11-1.png)<!-- -->

We see agian the ZIPs model has more variance, more akin to the the
data.

Here is the ligthning ignitoin

``` r
FWI_dat<- read.csv("Climate-future-input-log.csv")
FWI_dat<-with(FWI_dat,aggregate(FWI,by=list(Year=Year,Timestep=Timestep),FUN=mean))

FWI_dat<-FWI_dat[FWI_dat$Year %in% seq(1992,2016),]
FWI_Test<-FWI_dat$x
Pb0<-(-4.268433)
Pb1<-(.135562)
###Possion model
Lig_Ign_Test_Pois<-rpois(9125, lambda = exp((Pb0+(Pb1*FWI_Test))))

##ZIPS model

binomb0=3.83717
binomb1=-.14822

b0=(-.63779)
b1=(.01623)

alpha<-exp(binomb0+binomb1*FWI_Test)
zeroprob= alpha/(alpha+1)
Lig_Ign_Test<-ifelse((zeroprob<=runif(length(zeroprob),0,1)),
        round(rpois(9125, lambda = exp((b0+(b1*FWI_Test))))),
       0)

### Aggregate to the year
Lig_Ign_df<-cbind(FWI_dat[,c(1,2)],Lig_Ign_Test)
Lig_Years<-aggregate(list(Ignitions=Lig_Ign_df$Lig_Ign_Test),by=list(Year=Lig_Ign_df$Year),FUN=sum)

PLig_Ign_df<-cbind(FWI_dat[,c(1,2)],Lig_Ign_Test_Pois)
PLig_Years<-aggregate(list(Ignitions=PLig_Ign_df$Lig_Ign_Test_Pois),by=list(Year=PLig_Ign_df$Year),FUN=sum)

plot(PLig_Years$Year,PLig_Years$Ignitions,col="darkgreen",ylim=c(0,100),pch=16,cex=1.3,ylab="Lightning Ignition",xlab="Year")
points(Lig_Years$Year,Lig_Years$Ignitions,col="purple",pch=16,cex=1.3)
points(l_fires_count$YEAR,l_fires_count$COUNT,col="orange",pch=16,cex=1.3)

legend(1995,100,legend=c("Lightning Possion","Lightning ZIPS","Karen Short"),pch=c(16,16,16),col=c("darkgreen","purple","orange"))
```

![](Ignition_FWI_11_2020_files/figure-gfm/unnamed-chunk-12-1.png)<!-- -->

and with the LANDIS Scrpple lightning outputs using the above parameters

``` r
ZIPL<-ZIP[ZIP$Type==" Lightning",]
P_infL<-P_inf[P_inf$Type==" Lightning",]

plot(PAcc_Years$Year,ZIPL$Count[1:25],ylim=c(0,100),pch=16,col="red",main="LANDIS-Lightning",xlab="Lightning Ignition",ylab="Year")
points(PAcc_Years$Year,P_infL$Count[1:25],col="blue",pch=16)
points(PLig_Years$Year,PLig_Years$Ignitions,col="darkgreen",pch=16,cex=1.3,xlab="Accidental Ignition",ylab="Year")
points(Lig_Years$Year,Lig_Years$Ignitions,col="purple",pch=16,cex=1.3)
points(l_fires_count$YEAR,l_fires_count$COUNT,col="orange",pch=16,cex=1.3)

legend(1995,100,legend=c("Accidental Possion","Accidental ZIPS","Karen Short","LANDIS POISSON","LANDIS ZIPS"),pch=c(16,16,16,16,16),col=c("darkgreen","purple","orange",'blue','red'))
```

![](Ignition_FWI_11_2020_files/figure-gfm/unnamed-chunk-13-1.png)<!-- -->

repository: ZacharyRobbins/Extension-SCRPPLE

repo_name: ZacharyRobbins/Extension-SCRPPLE


text:
[![Build status](https://ci.appveyor.com/api/projects/status/n558pyl787ymf3bd/branch/master?svg=true)](https://ci.appveyor.com/project/terminatorul/perl-odbc/branch/master)
[![Build status](https://travis-ci.org/terminatorul/perl-ODBC.svg?branch=master)](https://travis-ci.org/terminatorul/perl-ODBC)

# perl-ODBC
Perl 6 module for listing available ODBC database drivers. Tested for Windows, Linux and MacOS.

Only available functions are:
 - list installed drivers and driver attributes
 - show available ODBC version

The module will load iodbc library on MacOS, unixodbc on Linux and ODBC32 dll on Windows.

## Installation
Clone the repository and manually copy the module to Perl 6 modules directory, since there is no module distribution archive packaged or uploaded to the Perl6 ecosystem for this module.

## Notification messages
`ODBC` module will send notifications for informational SQLState values (error class '01000') reported by the Driver Manager. These notifications are exception classes of the form `X::ODBC::SQLInfo[$sqlcode]`, that inherit from the standard `CX::Warn` class.

The intended use is for the application to handle these notifications in a Perl 6 `CONTROL` phaser, that would maybe display the message to the console and then `.resume` the exception. With the current issues in Perl 6 language implementation, the `CONTROL` phaser must also handle the standard `CX::Warn` exception in a similar fasion, for example:

```perl6
use X::ODBC;

# ... call ODBC methods

CONTROL
{
    when (X::ODBC::SqlInfo['01001'])
    {
        note .message
        .resume
    }

    when (CX::Warn)
    {
        note .message
        .resume
    }
}
```

This is entirely similar to a `CATCH` phaser for actual exceptions (that are not intended to be `.resume`d and do not inherit from `CX::Warn` or from `X::Control`). SQLState exceptions from `ODBC` module have the form `X::ODBC::SQLState['07001']`. Both `SQLInfo` and `SQLState` inherit from `X::ODBC::SQLNotification`.

Alternatively, set `&ODBC::notificationHandle` to any routine with one argument, to directly handle the notifications without the `CONTROL` phaser above, for example:
```perl6

$ODBC::notificationHandler = sub (X::ODBC::SQLNotification $notification)
{
    note $notification.message;
}
```

Most `SQLInfo` and `SQLState` exceptions also have a descriptive name, for example `SQLState['07002']` is `ColumnCountMismatch`, and `SQLState['07005']` is `CursorExpected`.

There is another class for exceptions that are not related to SQL statements: `X::ODBC::SqlReturn[$code]`, for example: `SqlReturn[ODBC::SQL::INVALID_HANDLE]`, which also has the descriptive name `X::ODBC::InvalidHandle`.

Here is the parent class tree for `X::ODBC` exceptions:

```txt
SqlReturn[$retcode]
    Error
        Exception

SQLState[$sqlstate]
    SQLNotification
        Exception

SQLInfo[$sqlstate]
    SQLNotification
        Exception
    CX::Warn
        X::Control
            Exception
```

## Selecting the required ODBC version
The module will by default require ODBC version 3, which is not the lastes ODBC version from Microsoft 3.58. This is currently needed for MacOS X, and can be changed when the constructor for ODBC::Environment is called.

## Using ANSI/Unicode ODBC functions

Currently the module is using the ANSI functions by default, until auto-detection based on the version string can be implemented. Unicode functions require ODBC v3.50 or later. You can select which API functions to be used by setting the `$ODBC::unicode` variable to a `True` value for Unicode functions and `False` value for ANSI functions. This may potentially have an effect on performance, since the optimum case is when ODBC Driver Manager is connecting:
    - Unicode applications with Unicode drivers
    - ANSI applications with ANSI drivers.

However, for Windows:
 - ANSI functions require extra conversions in the Perl module (compared to the Unicode functions), based on WinAPI function `MultiByteToWideChar()`
 - in case of ANSI applications connected to ANSI drivers, a few conversions are still needed in the ODBC Driver Manager also.

For MacOS X:
 - Unicode functions require extra conversions in the Perl module, based on the C run-time library function `wctomb`.
 - Unicode functions will change the current locale of the C library to the user-defined locale, named `""`. This locale setting is global and will affect the entire process.

In general the recommended use is to set:
```perl6
    $ODBC::unicode = True;
```
during startup.

## Reading ODBC version string
```perl6
use ODBC;

my ODBC::Environment $env .= new;
my ODBC::Connection  $con .= new($env);

say $con.version;
```

##  Listing installed ODBC drivers

```perl6

use ODBC;

my ODBC::Environment $env .= new;
say .key for $env.drivers:
```
Drivers are provided as a hash of hashes, with the registered driver name as the first-level key, and possible driver attributes as the nested (second-level) key. A `driverList()` method is also available, to provide the drivers and attributes as a list of pairs holding lists, in the same order enumerated by the ODBC API.

license: Unlicense

repository: terminatorul/perl-ODBC

repo_name: terminatorul/perl-ODBC


text:
# Aspect ratio and size control tutorial

A very common problem in plotting is dealing with aspect ratios and other ways to precisely control figures.

For example, many plots need square axes.
If you have looked at the documentation of `Axis`, you might know that it has an `aspect` attribute that can control the aspect ratio of the axis box.
This aspect is not concerned with what the data limits are, it's just about the relative visual length of the axes.

Let's look at one common example, a square axis with a colorbar next to it:

\begin{examplefigure}{svg = true}
```julia
using CairoMakie
CairoMakie.activate!() # hide

set_theme!(backgroundcolor = :gray90)

f = Figure(resolution = (800, 500))
ax = Axis(f[1, 1], aspect = 1)
Colorbar(f[1, 2])
f
```
\end{examplefigure}

As you can see, the axis is square, but there's also a large gap between it and the colorbar.
Why is that?

We can visualize the reason by adding a Box to the same cell where the axis is:

\begin{examplefigure}{svg = true, name = "aspect_tutorial_example"}
```julia
Box(f[1, 1], color = (:red, 0.2), strokewidth = 0)
f
```
\end{examplefigure}

The red area of the box extends out into the whitespace left by the Axis.
This demonstrates what the `aspect` keyword is actually doing.
It reduces the size of the Axis, such that the chosen aspect ratio is achieved.
It doesn't tell the layout that the Axis lives in "please make this cell adhere to this aspect ratio".
As far as the layout is concerned, the Axis has an undefined size and its layout cell can therefore have any size that the layout deems correct, based on all other content of the layout and the figure size.

Therefore, using `aspect` will always cause gaps, unless the layout cell where the Axis lives happens to have exactly the correct aspect ratio by chance.
This means `aspect` should only be used if the whitespace caused by it does not matter too much.

For all other cases, there is a different approach.

We want to force the layout to keep the axis cell at a specific aspect ratio.
Therefore, we have to manipulate the layout itself, not the axis.

By default, each GridLayout row and column has a size of `Auto()`.
This means that the size can depend on fixed-size content if there is any, otherwise it expands to fill the available space.
If we want to force a cell to have an aspect ratio, we need to set either its respective row or column size to `Aspect`.

Let's try the example from above again, but this time we force the column of the Axis to have an aspect ratio of 1.0 relative to the row of the Axis, which is row 1.

\begin{examplefigure}{svg = true}
```julia
f = Figure(resolution = (800, 500))
ax = Axis(f[1, 1])
Colorbar(f[1, 2])
colsize!(f.layout, 1, Aspect(1, 1.0))
f
```
\end{examplefigure}

As you can see, this time the colorbar sticks close to the axis, there is no unnecessary whitespace between them.
We can visualize the effect of `Aspect` again with a red box, that shows us the extent of the layout cell:

\begin{examplefigure}{svg = true}
```julia
# hide
Box(f[1, 1], color = (:red, 0.2), strokewidth = 0)
f
```
\end{examplefigure}

So this time the layout cell itself is square, therefore the Axis that fills it is also square.
Let me just demonstrate that we can play the same game again and give the Axis an `aspect` that is different from the square one that the layout cell has.
This will again cause unnecessary whitespace:

\begin{examplefigure}{svg = true}
```julia
ax.aspect = 0.5
f
```
\end{examplefigure}

And now we change the column aspect again, to remove this gap:

\begin{examplefigure}{svg = true}
```julia
colsize!(f.layout, 1, Aspect(1, 0.5))
f
```
\end{examplefigure}

Let's return to our previous state with a square axis:

\begin{examplefigure}{svg = true}
```julia
# hide
f = Figure(resolution = (800, 500))
ax = Axis(f[1, 1])
Colorbar(f[1, 2])
colsize!(f.layout, 1, Aspect(1, 1.0))
f
```
\end{examplefigure}

Now you might think that there is no whitespace anymore between Axis and Colorbar, but there is a lot of it to the left and the right.
Why can the layout not fix this problem for us?

Well, in Makie, the layout has to operate within the confines of the figure size that we have set.
It cannot just decrease the figure size if there's too little content.
This is because lots of times, figures are created to fit the sizing rules of some academic journal exactly, therefore the content you plot is not allowed to mess with the figure size.

So what we have done in our example is introducing constraints to the sizes of objects in our layout, such that it's impossible to fill all the space that is theoretically available.
If you think about it, it's impossible to fill this Figure with a square axis and a thin colorbar while filling the rectangular space.
We need a smaller figure!

But how small should it be exactly?
It would be quite difficult to eyeball this, but thankfully there's a function for this exact purpose.
By calling `resize_to_layout!`, we can adjust the figure size to the size that the layout needs for all its content.

Let's try it out:

\begin{examplefigure}{svg = true}
```julia
resize_to_layout!(f)
f
```
\end{examplefigure}

As you can see, the whitespace at the sides has been trimmed.
(If the scaling looks smaller or bigger, that is just because of the display on this site, not the underlying figure size).

This technique is useful for all kinds of situations where the content should decide the figure size, and not the other way around.

For example, let's say we have a facet plot with 25 square axes which are all of size 150 by 150.
We can just make these axes with fixed widths and heights.
The `Auto` sized columns and rows of the default layout pick up these measurements and adjust themselves accordingly.

Of course, the figure size will by default not be appropriate for such an arrangement, and the content will clip:

\begin{examplefigure}{svg = true}
```julia
f = Figure()
for i in 1:5, j in 1:5
    Axis(f[i, j], width = 150, height = 150)
end
f
```
\end{examplefigure}

But like before we can call `resize_to_layout!` and the size will be corrected so no clipping occurs.

\begin{examplefigure}{svg = true}
```julia
set_theme!() # hide
resize_to_layout!(f)
f
```
\end{examplefigure}

gha_language: Julia