text:
# Single-Page-Portfolio

![Portfolio Screen Capture](./assets/images/portfolio-cap.png "Portfolio Screen Capture")

The single page portfolio lets employers or persepctive clients get an idea of the work that I have done. It is displayed in a quick and clean format.

## Getting Started

Cloning and forking with git are easy. To clone, head over to [single-page-portfolio](https://github.com/BrantKeener/Single-Page-Portfolio) and navigate using the clone or download button. Copy the link, and perform
`git clone {copied link}`.

### Prerequisites

This application runs without any dependencies. After forking or cloning, no further installs will be necessary.

### Installing

This application runs without any dependencies. Simply for or clone.

## Deployment

This applicaton deploys easily to github pages. Simply navigate to settings in the remote repository, and activate GitHub pages for the application.

## Built With

* [JavaScript](http://es6-features.org/#Constants)
* [FontAwesome](https://fontawesome.com/?from=io)

## Contributing

Contributing is currently locked and by invite only.

## Versioning

All versioning is controlled through GitHub

## Authors

* **Brant Keener** - *Primary Author. All JavaScript, and general portfolio direction* - [BrantKeeer](https://github.com/BrantKeener)

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

## Acknowledgments

* Thanks to  for the following: **Noel Keener** - *Design and layout. Additional front end styling.* - [technakal](https://github.com/technakal)

repository: BrantKeener/Single-Page-Portfolio

gha_language: HTML

repo_name: BrantKeener/Single-Page-Portfolio


text:
---
hrs_structure:
  division: '1'
  volume: '3'
  title: '11'
  chapter: 149A
  section: 149A-20
type: hrs_section
tags:
  - Government
menu:
  hrs:
    identifier: HRS_0149A-0020
    parent: HRS0149A
    name: 149A-20 Seizures; "stop-sale" and "removal from sale" orders
weight: 44080
title: Seizures; "stop-sale" and "removal from sale" orders
full_title: 149A-20 Seizures; "stop-sale" and "removal from sale" orders
---
**§149A-20 Seizures; "stop-sale" and "removal from sale" orders.** (a) Any pesticide or device that is distributed, sold, offered for sale, transported, or delivered for transportation in violation of this chapter, may be seized. Any pesticide product or device seized hereunder shall, after entry of decree, be disposed of by destruction or sale as the court directs and the proceeds, if the pesticide product or device is sold, less legal costs, shall be paid to the general fund of the State; provided that the pesticide product or device shall not be sold contrary to this chapter; and provided that upon payment of costs and execution and delivery of a good and sufficient bond conditioned that the pesticide product or device shall not be disposed of unlawfully, the court may direct the pesticide product or device to be delivered to the owner thereof for relabeling or reprocessing as the case may be.

(b) The chairperson or the chairperson's authorized agent may issue and enforce a written or printed "stop-sale" or "removal from sale" order to withhold from sale any pesticide or device that is distributed, sold, offered for sale, transported, or delivered for transportation in violation of this chapter. [L 1972, c 58, pt of §1; am L 1975, c 126, pt of §1; gen ch 1985; am L 1987, c 310, §12]

license: MIT

repository: SamMade/BlueAndKrabby

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: SamMade/BlueAndKrabby


text:
---
layout: post
title: Generating and Installing Signing-Certificates for Identity Server
tags:
- identityserver
- certificates
- makecert
- pvk2pfx
---

A development implementation of an Identity Server (found in almost all examples online) uses a **Temporary Signing Certificate** to sign the JWT tokens. A temporary key is created every time the identity server is restarted. A new signing certificate makes all the tokens generated before invalid. In a production environment however, you want the tokens to be valid after a re-deploy of the identity server. So the signing certificate should be constant. In this post I'd show you how to create and use such self signed certificates.

## Getting the Tools Ready

We are going to use `makecert` and `pvk2pfx` utilities to create a pair of certificates. These two executables are found in "Windows Software Development Kit for Windows 8.1", downloadable from [here](https://developer.microsoft.com/en-us/windows/downloads/windows-8-1-sdk).

The executables are found at `C:\Program Files (x86)\Windows Kits\8.1\bin\x86`.
Open a command prompt and navigate to this folder. We are going to execute some commands there.

## Generating x509 Certificates Ready for Identity Server

We will need a *Certificate Authority* and a *Personal Information Exchange* (that contains a *Private Key* and a *Public Key*).

- The **Private Key** is used to sign the JWT tokens
- The **Public Key** is exposed to the clients, so that they can validate the JWTs.

1. Create a Certificate Authority and a Private Key

> `makecert -n "CN=IdentityServerCN" -a sha256 -sv IdentityServer4Auth.pvk -r IdentityServer4Auth.cer`

2. Store the Private Key and the Public Key in a Personal Information Exchange

> `pvk2pfx -pvk IdentityServer4Auth.pvk -spc IdentityServer4Auth.cer -po -pfx IdentityServer4Auth.pfx`

Now you should have the following three files.

- IdentityServer4Auth.pvk
- IdentityServer4Auth.cer
- IdentityServer4Auth.pfx

Let's go ahead and use them.

## Installing and Using Certificates

Identity Server 4 can retrieve these certificates in two alternative ways.

1. Grab them from the certificate file directly
2. Grab them from the MMC (Microsoft Management Console)

### Using Certs from File

The most simplest. You can save the `pfx` file on a folder. Let's say `C:\workspace\keys\`.

I have created an extension to configure the certificates.

**SigninKeyExtension.cs**

```csharp
public static void AddCertificateFromFile(
    this IIdentityServerBuilder builder,
    IConfigurationSection options,
    ILogger logger)
{
    var keyFilePath = options.GetValue<string>(KeyFilePath);
    var keyFilePassword = options.GetValue<string>(KeyFilePassword);

    if (File.Exists(keyFilePath))
    {
        logger.LogDebug($"SigninCredentialExtension adding key from file {keyFilePath}");

        // You can simply add this line in the Startup.cs if you don't want an extension.
        // This is neater though ;)
        builder.AddSigningCredential(new X509Certificate2(keyFilePath, keyFilePassword));
    }
    else
    {
        logger.LogError($"SigninCredentialExtension cannot find key file {keyFilePath}");
    }
}
```

Here's the config above code uses.

**appsettings.json**

```json
"SigninKeyCredentials": {
    "KeyFilePath": "C:\workspace\keys\IdentityServer4Auth.pfx",
    "KeyFilePassword": "ourpassword"
  }
```

**Startup.cs**
```csharp
var identityServerBuilder = services.AddIdentityServer()
    .AddSigninCredentialFromConfig(Configuration.GetSection("SigninKeyCredentials"), Logger);
```

### Installing Certs in Local Machine using MMC

Certificates are sensitive files and thus keeping them in the file system may not be a good idea. A better way to approach that is to import the certificate to the *Machine Certificate Store* using MMC.

1. Start -> Run -> mmc.exe enter
2. File -> Add or Remove Snap-ins -> Certificates -> Add -> Computer Account -> OK
3. Import the certificate (.cer) to personal -> Trusted Root Certification Authorities)
4. Import the pfx, **with exportable private key support**, to personal -> certificates.

Now you have installed the certificates to the Machine Certificate Store.

Simplar to above, I have created an extension to configure this.

**SigninKeyExtension.cs**

```csharp
private static void AddCertificateFromStore(
    IIdentityServerBuilder builder,
    IConfigurationSection options,
    ILogger logger)
{
    var keyIssuer = options.GetValue<string>(KeyStoreIssuer);
    logger.LogDebug($"SigninCredentialExtension adding key from store by {keyIssuer}");

    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    store.Open(OpenFlags.ReadOnly);

    var certificates = store.Certificates.Find(X509FindType.FindByIssuerName, keyIssuer, true);

    if (certificates.Count > 0)
        builder.AddSigningCredential(certificates[0]);
    else
        logger.LogError("A matching key couldn't be found in the store");
}
```

**appsettings.json**

```json
 "SigninKeyCredentials": {
    "KeyStoreIssuer": "IdentityServerCN"
  }
```

**Startup.cs**

```csharp
var identityServerBuilder = services.AddIdentityServer()
    .AddCertificateFromStore(Configuration.GetSection("SigninKeyCredentials"), Logger);
```

Alternatively, you can make it configurable to use certificates either *from file* or *from store*. You can then configure differently for your local development and build servers.

I have a setup like below, where I can use either based on the configuration.

**SigninKeyExtension.cs**

```csharp
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace IdentityServerWithAspNetIdentity.Config
{
    /// <summary>
    /// Impl of adding a signin key for identity server 4,
    /// with an appsetting.json configuration look similar to:
    /// "SigninKeyCredentials": {
    ///     "KeyType": "KeyFile",
    ///     "KeyFilePath": "C:\\certificates\\idsv4.pfx",
    ///     "KeyStorePath": ""
    /// }
    /// </summary>
    public static class SigninCredentialExtension
    {
        private const string KeyType = "KeyType";
        private const string KeyTypeKeyFile = "KeyFile";
        private const string KeyTypeKeyStore = "KeyStore";
        private const string KeyTypeTemporary = "Temporary";
        private const string KeyFilePath = "KeyFilePath";
        private const string KeyFilePassword = "KeyFilePassword";
        private const string KeyStoreIssuer = "KeyStoreIssuer";

        public static IIdentityServerBuilder AddSigninCredentialFromConfig(
            this IIdentityServerBuilder builder, IConfigurationSection options, ILogger logger)
        {
            string keyType = options.GetValue<string>(KeyType);
            logger.LogDebug($"SigninCredentialExtension keyType is {keyType}");

            switch (keyType)
            {
                case KeyTypeTemporary:
                    logger.LogDebug($"SigninCredentialExtension adding Temporary Signing Credential");
                    builder.AddTemporarySigningCredential();
                    break;

                case KeyTypeKeyFile:
                    AddCertificateFromFile(builder, options, logger);
                    break;

                case KeyTypeKeyStore:
                    AddCertificateFromStore(builder, options, logger);
                    break;
            }

            return builder;
        }

        private static void AddCertificateFromStore(IIdentityServerBuilder builder,
            IConfigurationSection options, ILogger logger)
        {
            var keyIssuer = options.GetValue<string>(KeyStoreIssuer);
            logger.LogDebug($"SigninCredentialExtension adding key from store by {keyIssuer}");

            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            var certificates = store.Certificates.Find(X509FindType.FindByIssuerName, keyIssuer, true);

            if (certificates.Count > 0)
                builder.AddSigningCredential(certificates[0]);
            else
                logger.LogError("A matching key couldn't be found in the store");
        }

        private static void AddCertificateFromFile(IIdentityServerBuilder builder,
            IConfigurationSection options, ILogger logger)
        {
            var keyFilePath = options.GetValue<string>(KeyFilePath);
            var keyFilePassword = options.GetValue<string>(KeyFilePassword);

            if (File.Exists(keyFilePath))
            {
                logger.LogDebug($"SigninCredentialExtension adding key from file {keyFilePath}");
                builder.AddSigningCredential(new X509Certificate2(keyFilePath, keyFilePassword));
            }
            else
            {
                logger.LogError($"SigninCredentialExtension cannot find key file {keyFilePath}");
            }
        }
    }
}
```

Have fun!


text:
# Adaobi C Okoye -  Portfolio with React.JS

## Description:
I am Adaobi C Okoye, a Fullstack web developer. This portfolio contains my work so far in my coding bootcamp.

  # Table of Contents

  - [Installation](#installation)
  - [Technologies](#technologies)
  - [Credits](#credits)
  - [License](#license)
  - [Contribution](#contributing)
  - [Tests](#tests)
  - [Questions](#questions)

  ## Installation:

   Make sure MongoDB is installed. First, clone the repo, install dependencies with npm -i and then run ```npm start``` to run the server.

## Technologies
  - JavaScript
  - React.Js
  - HTML/CSS

  ## Credits:

  Curated by Adaobi C Okoye

  ## License:

  For more information about licenses, please visit:

  [License](https://opensource.org/licenses/MIT)

  ## Contributing:

  [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg)](CODE_OF_CONDUCT.md)

  The project is open-source

  ## Tests:

  no testing

  ## Questions:

  For any questions you may have, please visit my Github profile:
  - [Github Profile](https://github.com/adokoye)

  If you have any additional questions, feel free to email them to me:
  -<EMAIL_ADDRESS>

repository: adokoye/react-portfolio

branch_name: refs/heads/main

repo_name: adokoye/react-portfolio


text:
## Sample 1: Fluid Container

The Container has the `Type` property which specifies the behavior of the Container for large page sizes.

The `Normal` type limits the maximum page width. If the window is wider, the content is not resized beyond the maximum width and it is centered.

The `Fluid` type always utilizes the available horizontal space.

repository: riganti/dotvvm-docs

gha_language: C#

repo_name: riganti/dotvvm-docs


text:
Ludum Dare Project Template
===========================
By mkv25.net games - for Haxe + OpenFL projects using Flash Develop.

+ Github: https://github.com/Markavian/ldtemplate
+ Preview site: http://mkv25.net/ludum/ldtemplate/preview/

Background
----------
I'm approaching my 8th Ludum Dare, and I've settled on a few things with my tools that are common between releases, such as how I package files up to put them on a website, where I put stuff that I'm working on, how I manage screenshots and blog posts, and so on. To make it easy to get all this ready for a new Ludum Dare event I've stripped back one of my projects and built a 1 screen demo that includes all my basic libraries, a few graphics, some text, some buttons, and some sounds.

The project builds in Flash Develop using OpenFL (which will need to be installed) and provides a nice base to work from.

Folder structure
----------------
+ audio/ - audio assets to big to be considered code
+ code/ - all source code, build instructions, final image assets, and final audio
+ design/ - design ideas and inspiration
+ photos/ - screenshots and photos of the project for distribution on social media
+ release/ - packaged releases get stored here
+ website/ - source code for the website lives here with binaries for the game

Contact
-------
+ Markavian, aka John Beech:
+ Email<EMAIL_ADDRESS>+ http://mkv25.net/games/

license: Unlicense


text:
# Appendix A: System Administration

## Overview
MBEE is designed to be deployed in a number of different architectural
configurations. It can be deployed as a single instance of
an application or it can be run in more complex configurations, such as
clustered behind a load balancer. This document will primarily focus on the
first case: a single running instance of the MBEE Core Framework.

### System Requirements
MBEE is designed to be cross-platform, but is primarily tested on Linux and
other Posix systems. Windows support is intended, but not yet fully supported.

> Windows Users: The MBEE Core Framework should be able to run on Windows,
> but plugins may not be fully supported.

The server should have at least 1 CPU and 0.5 GB RAM. The amount of disk space
required is dependent on the total model storage needed.

## Obtaining the MBEE Source Code
The MBEE source code can be obtained from [GitHub](https://github.com/lmco/mbee).

Clone the source code using Git by running:

```bash
git clone https://github.com/lmco/mbee.git
```

Enter the newly created directory containing the source code.

## Building MBEE
Before running MBEE, the software must be built. The build process compiles
Sass into CSS, transpiles React JSX into vanilla JavaScript, builds
documentation, prepares other static files, and more.

The build process will output these runtime files to the `build` directory.

Yarn is the recommended build tool for MBEE. To install it, run

```shell
npm install -g yarn
```

### Quickstart
If you're building MBEE for the first time, the easiest way to get started is
to run

```shell
yarn install # or npm install
```

By default this will install all dependencies and run a post-install script to
build MBEE.

### Build Process Breakdown
The installation process (e.g. `yarn install`) installs the necessary
dependencies to build and run MBEE. The installation includes a
*pre-install* and *post-install* script. The pre-install script cleans and
removes an existing build. The post-install script runs the MBEE build.

Either of these scripts can be turned off by setting the `NOPREINSTALL` or
`NOPOSTINSTALL` environment variables.

```shell
export NOPREINSTALL=1     # Turns off the pre-install script
export NOPOSTINSTALL=1    # Turns off the post-install script
yarn install
```

The build can be run separately from the dependency installation, but the
dependencies must be installed first.

To build MBEE run the following command:

```shell
node mbee build
```

The build process also supports several command line options for only running
certain sections of the build. When no options are provided, all build sections
are executed. The following options are supported:

- **`--copy-deps`** - Copies static runtime dependencies into the build folder.
- **`--jsdoc`** - Builds the JSDoc documentation.
- **`--fm`** - Builds the flight-manual.
- **`--sass`** - Builds the Sass into CSS.
- **`--react`** - Transpiles the React JSX into client-side JavaScript

Additionally, a **`--all`** option tells the build script to run all sections of
the build. This is the default behavior when no options are provided.

### Database Schema Migrations
*Appendix B* of the Flight Manual covers database migration in more detail, but
it will be discussed here briefly.

Database migration refers to altering the database contents and schema with new
versions of MBEE. To facilitate this, MBEE contains a collection of migration
scripts for updating from one version to another.

To run the migrations and update to the latest version, run

```
node mbee migrate
```

By default, this will run the migration scripts to update to the latest version.
MBEE stores the current schema version in the database and compares that version
to the `version` field in the `package.json` file.

When no schema version information can be found in the database, MBEE will
automatically apply any necessary migrations.

The migrations command will typically prompt the user to confirm the action.
To automatically answer *yes* to this prompt (i.e. for scripting the migration
command), the `-y` option can be used.

```shell
node mbee migrate -y
```

## Running MBEE
Before running MBEE, it must be built. See the *Building MBEE* section above
to build MBEE.

### Running in Development
To run MBEE, run the following command:

```shell
node mbee start
```

By default, the Node.js process has a limited amount of memory (this size may
vary depending on your configuration and Node version). To increase the default
memory limit use the `--max-old-space-size` option. For example:

```shell
node --max-old-space-size=8192 mbee start
```

> NOTE: The value above is in megabytes (MB).

### Using PM2
Run `npm install -g pm2` or `yarn global add pm2` to install the `pm2`
process manager for Node.js. Make sure the `pm2` binary is in your PATH.

To run MBEE, run `pm2 start mbee.js -- start`. Run `pm2 logs mbee` to view the
server log output. You should now be able to navigate to MBEE in your web
browser and view the running application.

To stop the running server, run `pm2 stop mbee`. To remove the process from PM2
entirely, run `pm2 delete mbee`. Running `pm2 list` at this point should no
longer include MBEE in the process list.

### Using Docker
MBEE can be run in a docker container and has convenient command line options
for enabling this. To run the commands, use `--[cmd]` after `node mbee docker`.
You must build MBEE first (see the *Building MBEE* section above) before
building the Docker image.

To build the docker image, run `node mbee docker --build`. This will build the
Docker image using the Dockerfile specified in the MBEE configuration file.
Do note that the docker scripts have certain commands that will be run on build
and start commands. The Dockerfile, image name, container name, and other options
can be configured in the MBEE config file.

After the image is built, the docker container can be run using the `--run`
subcommand. The container will be detached, but have interactive processes.
The default runtime configuration will restart the Docker container if the
server crashes. Below is an example of how a docker container can be run:

```bash
node mbee docker --run
```

To get the logs from the docker container, you can use `--get-logs`. This will
print out the container logs, which can be useful if an error has occurred.

If the docker container needs to be rebuilt and the previous build needs to be
removed, use the `--clean` subcommand to remove the previous docker image and
container.

## Advanced Configuration
MBEE stores all it's configuration information in the `config` directory. By
default, it uses the `default.cfg` file, but that can be changed by setting the
`MBEE_ENV` environment variable. On startup, MBEE will load the configuration
file with a name matching the `MBEE_ENV` environment variable. For example,
if `MBEE_ENV=production`, MBEE will look for the file `config/production.cfg`.

The MBEE config is simply a JSON file that allows comments. MBEE is designed to
be largely parameterized by this config file. The file supports options for
defining the server ports, Docker configuration information, enabling and
disabling application components, swapping out authentication schemes, and more.

For a detailed explanation of the fields supported by the config file, see the
detailed comments provided in the example.cfg.

Some of the noteworthy options are

> **NOTE:** The notation below uses `.` characters to describe nested JSON.
> For example `auth.strategy` refers to the `strategy` field within the `auth`
> section. Or as JSON:
> ```json
> {
>   "auth": {
>     "strategy": "someString"
>   }
> }
> ```
>

- **auth**: For authentication-related information.
  - **auth.strategy**: This section is used to define which
  authentication strategy will be used.
  - **auth.token** and **auth.session**: Defines when sessions and tokens will
  expire. In most cases these should be the same.
- **db**: Used to configure the database connection.
- **docker**: Defines the Docker configuration. This is used when running the
`node mbee docker` command.
- **log**: Defines the log level and log file names.
- **server**: This is the bulk of the application configuration.
  - **server.defaultAdminUsername**: The default admin user created on first
  server startup.
  - **server.defaultAdminPassword**: The default admin user's password.
  - **server.defaultOrganizationId**: The default organization ID that all users
  will be members of.
  - **defaultOrganizationName**: The friendly name of the default organization.
  - **server.http**
    - **server.http.enabled**: Used to enable/disable HTTP.
    - **server.http.port**: Defines the HTTP port.
    - **server.http.redirectToHTTPS**: If `true`, redirects all HTTP traffic to
    HTTPS. HTTPS must be enabled.
  - **server.https**:
    - **server.https.enabled**: Used to enable/disable HTTPS.
    - **server.https.port**: Defines the HTTPS port.
    - **server.https.sslCert**: The path to the server SSL certificate
    (e.g. "path/to/your/ssl/cert.crt").
    - **server.https.sslKey**: The path to the server SSL key
    (e.g. "path/to/your/ssl/key.key").
  - **server.requestTimeout**: The time at which server requests will time out
  in seconds.
  - **server.requestSize**: The maximum size request.
  - **server.api**: {
    - **server.api.enabled**:Can be used to enable/disable the API.
    - **server.api.userAPI**: Can be used to disable certain user API endpoints
    such as create and update. This may be useful when using a separate
    authentication provider such as LDAP.
  - **server.plugins**: {
    - **server.plugins.enabled**: Can be used to enable/disable plugins.
    - **server.plugins.plugins**: This is where plugins are defined. This
    section tells MBEE which plugins should be installed and where to obtain
    them.
  - **server.ui**
    - **server.ui.enabled**: Can be used to enable/disable the UI. This may be
    useful if the MBEE API is desired without the front-end GUI.
    - **server.ui.mode**: This is used during build to define the build mode for
    React. Valid options are "development" and "production".
    - **server.ui.banner**: This section can be used to define a banner at the
    top and bottom of the UI for providing sensitivity labels.
  - **server.secret**: This is the secret key used by the server for encrypting
   authentication tokens. If the word "RANDOM" is provided, a key will be
   randomly generated on server startup.
- **test**: Defines test configuration. Used when running `node mbee test`.
- **validators**: Validators can be used to overwrite certain default data model
validation behaviors. Any validator defined in the `app/lib/validators.js` file
can be overwritten here.

## Modular Authentication
MBEE supports modular authentication strategies. These strategies are defined
in the authentication module in `/app/auth`. Which authentication strategy is
used is defined in the config file. The `auth` section contains a field called
`strategy`. This `auth.strategy` section should be set to the module you wish
to use.

These authentication modules have well defined interfaces that can be
dynamically replaced based on the configuration. This allows you
to write a custom authentication module to accommodate the needs of your
company or organization without having to make major changes to MBEE. You can
then specify which authentication module to use in the MBEE config file.

By default, MBEE provides strategies for local authentication or LDAP
authentication. Local is used by default because it has fewer dependencies and
is easiest to get started. LDAP can be used by specifying that strategy in the
default.cfg and altering the `auth.ldap` section of the
config to define your LDAP configuration.

An authentication module has the following requirements:

- It must be located in the `app/auth` directory.
- It must implement and export the following functions
    - handleBasicAuth(req, res, username, password) - Returns a Promise
    - handleTokenAuth(req, res, token) - Returns a Promise
    - doLogin(req, res, next)
    - validatePassword(password, provider) - Returns a boolean

The `handleBasicAuth()` and `handleTokenAuth()` functions both defines how to
authenticate users for their respective input types. Both objects are passed the
request object, `req`, and response object, `res`. `handleBasicAuth()` is
passed the username and password which is obtained from either the authorization
header or form input depending on which is provided (with the former taking
precedence). `handleTokenAuth()` is passed a token which is retrieved either
from the authorization header or the `req.session.token` field (with the former
taking precedence). Both of these functions must return a promise that resolves
the user object on success or rejects with an error if authentication fails.

The `doLogin()` function defines what actions should be done to actually log the
user in when authentication succeeds. This function is called for the following
routes:
    - `/api/login`: This function should set the `req.session.token` and call
    `next()` when done. Control will then be passed to the API controller which
    will return the token in the form `{ "token": "yourReqSessionToken" }`
    -`/login`: This function should perform login actions such as setting the
    `req.session.token` value and then call `next()` when done, which will
    handle appropriate redirection of the user.

The `validatePassword()` function is meant to validate the password of each user
being created. This function should accept the password (and optionally the
provider), verify the password meets some requirements, and return a boolean
denoting whether that password is valid or not. By default, the requirements
provided in the local-strategy expect each password to be at least 8 characters
in length, and have at least one number, uppercase letter, lowercase letter and
at least one special character. For security reasons, it is recommended that
you do not lessen these requirements.

repository: josh-kaplan/mbee

gha_language: JavaScript

gha_license_id: MIT

repo_name: josh-kaplan/mbee


text:
fast-ui
=======

Intro
------
FastUi is a YUI3 module that is focused on building UIs fast. It is inspired from frameworks like GWT and JSF2,
focused on a composition model that is easily described in an easy to understand XML.

This fits like a glove on top of the YUI3 architecture of widgets.

Description
-----------

FastUi is a YUI3 module that allows you to focus on the UI logic, and decouples the actual UI building (layout and I18N)
from JS code, by allowing you de declare it in a very simple to understand XML, and then just bind certain components to
the code.

The YUI3 Widget and DOM Node architecture allows for seamless integration between simple DOM nodes (Y.Node elements) and
custom Widget classes.

Usage
-----
In order to use it, you simple need to use XML namespaces mapped to the actual JS namespaces that you want used. You
can use multiple namespaces, and the "fastui" namespace adds the extra power you need to work with those widgets
or nodes.
The "fastui" namespace contains element building configuration. (see the end of this page for details).

The gallery-fast-ui adds two functions: fastUi and lazyUi.
```
Y.fastUi = function(parent, xmlContent, msg, globalConfig) {..}
// and
Y.lazyUi = function(parent, xmlContent, msg, callback, globalConfig) {..}
```

Functionally they are about the same, except that lazyUi will create the ui only when needed. For example let's assume
that you have a dialog that you want shown only when the user clicks some button. Then you will create the dialog with lazyUi
and instantiate it as such:

```
var ui = Y.lazyUi(parent, xmlContent, msg, function(_ui) {

    // here the _ui object is truly the object created by Y.fastUi, and not a proxy
    // like the case with lazyUi.

}); // ui.dialog is exported

// some callback
someButton.on("click", function() {
    ui().dialog.show(); // only here does the dialog really gets created.
});
```

Features
--------

### True UI Fast Creation
Many times when creating UIs you need to build them from a mixture of widgets (and HTML). FastUi makes creating
complex UIs a breeze, even if they are actually composed from multiple widgets (see the Full demo for a dialog, with a
tab panel and several buttons created in one go).

### Don't mix UI and JS code anymore
Install fast-ui from npm:
```
$ npm install -g fast-ui
```
and then you can run fast-ui in your src folder module. This will scan the ui/ folder for any file, and put them into a
variable into a new JS named js/ui.js, so then you could just do:
```
Y.fastUi(rootNode, uiDefinition['my-dialog.xml'], msg);
Y.fastUi(rootNode, uiDefinition['my-other-dialog.xml'], msg);
```

### I18N out of the box
FastUi takes its template and runs it against handlebars. If the msg parameter is set, it will
automatically replace the values. Furthermore, if the value is set in an attribute of a Widget, it will also get I18N
for free.

### Y.Node and Y.Widget Support
When creating elements, if they are marked using the ui:field attribute they will be automatically
exported into the resulting object, with objects of the corresponding type.

### srcNode Support
When creating widgets FastUi normally creates a placeholder <span> and simply calls widget.render('#idOfSpan').
FastUi also supports creating a different element using ui:srcNode (for example ui:src="div" will
create a div element), and then passing the srcNode as an attribute to the constructor of the widget.

Example
-------
The following example shows how to create a full dialog, with a tab panel and some buttons inside it in a single go.

```
// the HTML code that we want to build
var htmlCode = '' +
    '<Y:Panel ui:field="dialog" ui:srcNode="div" xmlns:Y="Y" xmlns:ui="fastui" headerContent="awesome title">' +
    '    <ui:config name="width">400</ui:config>' +
    '    <ui:config name="centered">true</ui:config>' +
    '    <ui:config name="modal">false</ui:config>' +
    '    <ui:config name="visible">false</ui:config>' +
    '' +
    '    <ui:config name="bodyContent" type="ui">' +
    '        <Y:TabView ui:srcNode="div">' +
    '            <ul>' +
    '                <li><a href="tab1">{HOME}</a></li>' +
    '                <li><a href="tab2">{OTHER}</a></li>' +
    '            </ul>' +
    '            <div>' +
    '                <div id="tab1">' +
    '                    <div>{SOME_MESSAGE}</div>' +
    '                    <Y:Button ui:srcNode="span" ui:field="okButton" label="{OK}"/>' +
    '                    <Y:Button ui:srcNode="span" ui:field="cancelButton" label="{CANCEL}"/>' +
    '                </div>' +
    '                <div id="tab2">' +
    '                    <Y:Button ui:srcNode="span" ui:field="otherButton" label="{OTHER_BUTTON}"/>' +
    '                </div>' +
    '            </div>' +
    '        </Y:TabView>' +
    '    </ui:config>' +
    '</Y:Panel>';

// the I18N object should actually be obtained from Y.Intl
var msg = {
    HOME : "Home",
    OK : "Ok",
    CANCEL : "Cancel",
    SOME_MESSAGE : "Some message",
    OTHER : "Other",
    OTHER_BUTTON : "Other Button"
};

// we render it in the "#demo" div just for the skin.
var ui = Y.fastUi("#demo", htmlCode, msg);

ui.okButton.on("click", function() {
    alert('ok button was clicked');
});
ui.cancelButton.on("click", function() {
    ui.dialog.hide();
});

var showDialogButton = new Y.Button({
	label : "Show dialog"
});

showDialogButton.render("#demo");

showDialogButton.on("click", function() {
    ui.dialog.show();
});
```


text:
# PBS_onGCE
Script to create a cluster of PBS Professional on Google Compute Engine(GCE)

## Discription
This script can create a master node and computation nodes with PBS Pro job control system (https://github.com/pbspro/pbspro) on Google Compute Engine (https://cloud.google.com/compute/).

## How to use
Open a Google Cloud Shell and pull the script file.
```bash
git clone https://github.com/lithium0003/PBS_onGCE.git
cd PBS_onGCE
```
Change parameters for your environments in header of the script file.
```bash
zone=asia-northeast1-b
user=username
homedisk=home
homesize='100GB'
sshkey='(your ssh key)'

num_compute=14
```
Run the script.
```bash
./master.sh
```
## Requirements
By default, total CPU counts of each region on GCE is limted up to 24. If you need more cores, you should request to grow the limitation.


text:
# FPGA Example Design: CRR Binomial Tree Model for Option Pricing

| Optimized for                     | Description
---                                 |---
| OS                                | Linux* Ubuntu* 18.04; Windows* 10 or Windows* Server 2016
| Hardware                          | Intel® Programmable Acceleration Card (PAC) with Intel Arria® 10 GX FPGA; Intel Xeon® CPU E5-1650 v2 @ 3.50GHz
| Software                          | Intel® oneAPI DPC++ Compiler (Beta)

_Notice: Limited support in Windows*, Compiling for FPGA hardware is not supported in Windows*_

Performance

| CRR                               | Performance Data (see performance disclaimers section below)
|:---                               |:---
| SYCL                              | 38 assets/s

## Description

This sample implements the Cox-Ross-Rubinstein (CRR) binomial tree model that is used in the finance field for American exercise options with five Greeks (delta, gamma, theta, vega and rho). The simple idea is to model all possible assets price paths using a binomial tree.

## License
This code sample is licensed under MIT license.

## Design Details

### Design Inputs

This design reads inputs from the `ordered_inputs.csv` file. The inputs are:

| Input                             | Description
---                                 |---
| `nSteps`                          | Number of time steps in the binomial tree. The maximum `nSteps` in this design is 8191.
| `CP`                              | -1 or 1 represents put and call options, respectively.
| `Spot`                            | Spot price of the underlying price.
| `Fwd`                             | Forward price of the underlying price.
| `Strike`                          | Exercise price of the option.
| `Vol`                             | Percent volatility that the design reads as a decimal value.
| `DF`                              | `Spot` or `Fwd`
| `T`                               | Time, in years, to the maturity of the option.

### Design Outputs

This design writes outputs to the `ordered_outputs.csv` file. The outputs are:

| Output                            | Description
---                                 |---
| `value`                           | Option price
| `delta`                           | Measures the rate of change of the theoretical option value with respect to changes in the underlying asset's price.
| `gamma`                           | Measures the rate of change in the `delta` with respect to changes in the underlying price.
| `vega`                            | Measures sensitivity to volatility.
| `theta`                           | Measures the sensitivity of the value of the derivative to the passage of time.
| `rho`                             | Measures sensitivity to the interest of rate.

### Design Correctness

This design tests the correctness by comparing the FPGA results and CPU results.

### Design Performance

This design tests the FPGA performance to determine how many assets can be processed per second, with five valid inputs. Five inputs are sufficient to test the performance.

## Building the CRR Design (Linux)

Perform the following steps:

1. Install the design into the `build` directory from the design directory by running `cmake`:

    ```
    mkdir build
    cd build
    ```

    If you are compiling for the Intel® PAC with Intel Arria® 10 GX FPGA, run `cmake` using the command:

    ```
    cmake ..
    ```

    If instead you are compiling for the Intel® PAC with Intel Stratix® 10 SX FPGA, run `cmake` using the command:

    ```
    cmake .. -DFPGA_BOARD=intel_s10sx_pac:pac_s10
    ```

2. Compile the design through the generated `Makefile`. The following four build targets are provided, matching the recommended development flow:

    * Compile and run for emulation (fast compile time, targets emulated FPGA device). It runs one input data from the input file for emulation.

        ```
        make fpga_emu
        ./crr.fpga_emu ./src/data/ordered_inputs.csv -o=./src/data/ordered_outputs.csv
        ```

    * Generate HTML optimization report. You can find the report in `crr_report.prj/reports/crr_report.html`.

        ```
        make report
        ```

    * Compile and run on the FPGA hardware (longer compile time, targets FPGA device). It runs all the input data from the input file.

        ```
        make fpga
        ./crr.fpga ./src/data/ordered_inputs.csv -o=./src/data/ordered_outputs.csv
        ```

    * Compile and run on the CPU hardware (unoptimized) using:

        ```
        make cpu_host
        ./crr.cpu_host ./src/data/ordered_inputs.csv -o=./src/data/ordered_outputs.csv
        ```

(Optional) As the above hardware compile may take several hours to complete, an Intel® PAC with Intel Arria® 10 GX FPGA precompiled binary can be downloaded here.

## Building the CRR Design (Windows)

Perform the following steps:
Note: `cmake` is not yet supported on Windows, a build.ninja file is provided instead.

1. Enter source file directory.

```
cd src
```

2. Compile the design. The following four build targets are provided, matching the recommended development flow:

    * Compile and run for emulation (fast compile time, targets emulated FPGA device). It runs one input data from the input file for emulation.

        ```
        ninja fpga_emu
        crr.fpga_emu.exe ./data/ordered_inputs.csv -o=./data/ordered_outputs.csv
        ```

    * Generate HTML optimization report. You can find the report in `../src/crr_report.prj/reports/report.html`.

        ```
        ninja report
        ```

        If you are targeting the Intel® PAC with Intel Stratix® 10 SX FPGA, please use the following target and find the report in `../src/crr_s10_pac_report.prj/reports/report.html`.

        ```
        ninja report_s10_pac
        ```

    *  **Not supported yet:** Compile and run on the FPGA hardware.

    * Compile and run on the CPU hardware (unoptimized) using:

        ```
        ninja cpu_host
        crr.cpu_host.exe ./data/ordered_inputs.csv -o=./data/ordered_outputs.csv
        ```

## Building the CRR Design in Third-Party Integrated Development Environments (IDEs)

You can compile and run this example design in the Eclipse* IDE (in Linux*) and the Visual Studio* IDE (in Windows*). For instructions, refer to the following link: [Intel® oneAPI DPC++ FPGA Workflows on Third-Party IDEs](https://software.intel.com/en-us/articles/intel-oneapi-dpcpp-fpga-workflow-on-ide)

## Running the Example Design

Invoke the CRR example design as follows:

```
./crr.fpga <input_file> [-o=<output_file>]

```

### Sample Output

```
============ Correctness Test =============

Running analytical correctness checks...

CPU-FPGA Equivalence: PASS

============ Throughput Test =============

Avg throughput: 66.2 assets/s
```

### Arguments

| Argument                          | Description
---                                 |---
| `<input_file>`                    | Optional argument that provides the input data. The default file is `/data/ordered_inputs.csv`
| `-o=<output_file>`                | Optional argument that specifies the name of the output file. The default name of the output file is `ordered_outputs.csv`.

## Source Code Explanation

| File                              | Description
---                                 |---
| `main.cpp`                        | Contains both host code and SYCL* kernel code.
| `CRR_common.h`                    | Header file for `main.cpp`. Contains the data structures needed for both host code and SYCL* kernel code.

## Backend compiler flags used when compiling the design

| Flag                              | Description
---                                 |---
`-Xshardware`                       | target FPGA hardware
`-Xsfpc`                            | allows backend to remove intermediate roundings
`-Xsparallel=2`                     | uses 2 cores when compiling the bitstream through Quartus
`-Xsseed=5`                         | uses seed 5 during Quartus, yields slightly higher fmax

## Performance disclaimers

Tests document performance of components on a particular test, in specific systems. Differences in hardware, software, or configuration will affect actual performance. Consult other sources of information to evaluate performance as you consider your purchase. For more complete information about performance and benchmark results, visit [www.intel.com/benchmarks](www.intel.com/benchmarks).

Performance results are based on testing as of January 20, 2020 and may not reflect all publicly available security updates. See configuration disclosure for details. No product or component can be absolutely secure.

Intel technologies’ features and benefits depend on system configuration and may require enabled hardware, software or service activation. Performance varies depending on system configuration. Check with your system manufacturer or retailer or learn more at [intel.com](www.intel.com).

The performance was measured by Intel on January 20, 2020

Intel and the Intel logo are trademarks of Intel Corporation or its subsidiaries in the U.S. and/or other countries.

(C) Intel Corporation.

## References

[Khronous SYCL Resources](https://www.khronos.org/sycl/resources)

[Binomial options pricing model](https://en.wikipedia.org/wiki/Binomial_options_pricing_model)

[Wike page for finance Greeks](https://en.wikipedia.org/wiki/Greeks_(finance))

[OpenCL Intercept Layer](https://github.com/intel/opencl-intercept-layer)

license: MIT,Zlib

repository: dmsivkov/BaseKit-code-samples

detected_licenses: MIT Zlib

repo_name: dmsivkov/BaseKit-code-samples


text:
toml2js
=========
A command-line utility to convert TOML to JSON.

[![NPM](https://nodei.co/npm/toml2js.png)](https://nodei.co/npm/toml2js/)

Installation
-----------

```
npm install -g toml2js
```

Usage
-----
```bash
$ toml2js test/simple.toml
```
<pre>
{
  "foo": "bar",
  "anArray": [
    1,
    3,
    5,
    7
  ],
  "bool": true,
  "one": 1
}
</pre>

**EXIT STATUS**

The toml2js utility exits with one of the following values:

| Code |  Description                            |
|------|-----------------------------------------|
|   0  |  input was parsed successfully.         |
|   1  |  failed to parse input.                 |
|   2  |  An error occurred while reading input. |

License
-------
MIT


text:
# MazaServer 2.0 · [![GitHub license](https://img.shields.io/badge/license-ISC-blue.svg)](https://github.com/goldenmaza/maza-server-2/blob/master/LICENSE.md)

**Note:** Obviously a work in progress... You can find the 1.0 version [here](https://github.com/goldenmaza/maza-server-1)...

license: ISC


text:
# binder-box
Base boxes for MyBinder. This tiny repo creates a MyBinder environment then relies on nbgitpuller to connect this to the Jupyter notebooks at github.com/colinleach/astro-Jupyter. This allows frequent updates to the .ipynb files without needing (very slow) rebuilds of the binder environment.

[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/colinleach/binder-box/master/?urlpath=git-pull?repo=https://github.com/colinleach/astro-Jupyter)

Thanks to Tony Hirst ([psychemedia](https://github.com/ouseful-demos/binder-base-boxes)) for his advice on this.

repository: colinleach/binder-box

repo_name: colinleach/binder-box


text:
---
layout: default
---

# 1997-08-15 - Re: Cartel Leaders Set Snipers To Work In Border War

## Header Data

From<EMAIL_ADDRESS>(Anonymous)

To<EMAIL_ADDRESS>Message Hash: bdd60c7a0d4d18c7760aacb6632d2ef82c877797cc89f19c84c6d1a42eb8bcb7

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1997-08-15 11:10:01 UTC

Raw Date: Fri, 15 Aug 1997 19:10:01 +0800

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(Anonymous)
Date: Fri, 15 Aug 1997 19:10:01 +0800
To<EMAIL_ADDRESS>Subject: Re: Cartel Leaders Set Snipers To Work In Border War
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

Tim May wrote:
>
> According to this article, the home addresses of government agents are
> being solicited by Mexican drug dealers, for disposal of agents
> interfering in their business.

  A major thrust of the article deals with the government promotion
of the idea that the "bad guys" have actively declared war upon agents
of the U.S. government, on U.S. soil.
  Strange that this claim should come from a variety of sources at
the same time the government is facing the embarassment of having to
whitwash the actions of heavily armed, camouflaged Marines who felt
so threatened by a goat-herder with a .22 rifle that they slaughtered
him with their M-16's, despite the fact that the child was an American
citizen, doing what he had every right to do, on American soil.

  The drug cartels are having such little trouble getting drugs into
the U.S. that cocaine and heroine are cheaper than a bottle of good
Scotch, yet, according to the government, they have decided that it
is necessary to perform actions which will "force" the government
to 'crack down' on border terrorism with increasing use of armed
force. Right...
  I bet the child pornography cartels are arming themselves, even
as we speak, preparing to join the drug cartels in their war against
the U.S. governement. We'd better send some Marines to Denver, New
York City, and Fargo. Then everybody but the high-school goat herders
will feel much safer, I'm sure.

GiveMeAFuckingBreakMonger
"There is something wrong when U.S. armed forces murder American
 schoolchildren on American soil, under an increasing number of
 unconstitutional laws."

> > Date: Thu, 14 Aug 1997 22:42:08 -0700 (PDT)
> > Message-ID<EMAIL_ADDRESS>> > From: Mix<EMAIL_ADDRESS>> > Comments: This message did not originate from the address above.  It was
> remailed by an anonymous remailing service.  If you have questions or
> complaints, please direct them to<EMAIL_ADDRESS>> > Subject: Cartel Leaders Set Snipers To Work In Border War
> > Newsgroups:
> talk.politics.guns,misc.legal,misc.survivalism,alt.news-media,alt.politics.usa.misc,alt.politics.media,alt.politics.clinton
> > Mail-To-News-Contact<EMAIL_ADDRESS>> > Organization<EMAIL_ADDRESS>> > Lines: 58
> ...
> > Cartel leaders set snipers to work in border 'war'
> > By John Hiscock Electronic Telegraph, London
> >
> > August 11, 1997
> >
> > AMERICAN Border Patrol agents have become targets of snipers working
> > for drug smugglers trying to take control of the border with Mexico. A
> > five-mile strip of frontier near San Diego in California has become so
> > dangerous that a specially-trained squad of border patrol sentries
> > armed with assault rifles has been drafted in to combat the snipers,
> > who have fired at agents seven times in the past two months.
> >
> > The agents believe that Mexican drug cartel leaders have issued
> > instructions to kill any law enforcement officers impeding drug
> > smuggling operations. Their fears have been heightened by a bulletin
> > from the Immigration and Naturalisation Service that said two drug
> > cartel leaders in the Mexican border city of Tijuana had "reportedly
> > contracted with local gangs on both sides of the border to kill
> > federal law enforcement personnel", preferably on American soil. In
> > addition, officers recently received reports that cartel henchmen have
> > put a price on their heads by offering to pay £7,000 for the
> > home address of any United States federal agent.
> >
> > Dianne Feinstein, a Californian senator, says that border patrol
> > agents, whose job until recently was to arrest mainly frightened and
> > unarmed Mexicans trying to cross the frontier at night, are now in the
> > front line of a vicious drug war. "This is a border on alert, a border
> > where anything could happen," she said. "These cartels are moving
> > drugs across the border and are operating with impunity and that adds
> > an increased risk to the lives of border patrol agents. This is a
> > different border than it was two years ago."
> >
> > In addition to being the most popular spot for illegal aliens
> > attempting to cross, the border around San Diego is now the main
> > gateway for cocaine and heroin bound for the US. Since the
> > introduction of Operation Gatekeeper, President Clinton's 1994
> > anti-illegal alien initiative that poured more money and agents into
> > the San Diego area, the drug smugglers have found themselves
> > increasingly caught up in the patrols' swoops on illegal
> > border-crossers.
> >
> > "We've made it increasingly difficult for drug traffic," said John
> > Williams, the chief of San Diego's 2,000-strong border patrol sector.
> > "We're making it tough on crime and that certainly has some bearing on
> > their reaction. The escalation of violence is of grave concern to me
> > and my agents."
> >
> > Members of the elite special protection unit carry M-16 assault
> > rifles, with a range of more than a mile, while all agents are now
> > being issued with semi-automatic pistols and shotguns.
>
> --
> There's something wrong when I'm a felon under an increasing number of laws.
> ---------:---------:---------:---------:---------:---------:---------:----
> Timothy C. May              | Crypto Anarchy: encryption, digital money,
><EMAIL_ADDRESS>408-728-0152 | anonymous networks, digital pseudonyms, zero
> W.A.S.T.E.: Corralitos, CA  | knowledge, reputations, information markets,
> Higher Power: 2^1398269     | black markets, collapse of governments.
> "National borders aren't even speed bumps on the information superhighway."

{% endraw %}
```

## Thread

+ Return to [August 1997](/archive/1997/08)

+ Return to<EMAIL_ADDRESS>(Anonymous)](/authors/nobody_at_replay_com_anonymous_)"

+ 1997-08-15 (Fri, 15 Aug 1997 19:10:01 +0800) - Re: Cartel Leaders Set Snipers To Work In Border War -<EMAIL_ADDRESS>(Anonymous)_


text:
---
permalink: /northeast/what-we-do/executive-committee/
layout: default
title: Executive Committee
---

The Northeast Association Executive Committee, which the "Bylaws" identify as the "Board," is the governing body of the Association, tending to the work of the Association between times the members gather in meeting. This committee coordinates the work of the Association and its Divisions, appoints leadership to fill vacancies between annual meetings, assists in preparing an annual budget, engages in long-range planning, and attends to other business as needed.

The members of the Executive Committee are the four officers of the Association, the chairs of the three Divisions, the Association's four members on the Conference Board of Directors, and four at-large members elected by the Association.

The Executive Committee meets about four times a year.

repository: shirby/neaweb

repo_name: shirby/neaweb


text:
Calabash offsers a shortcut for bash command-lines
------

Bash is both a great and a mad tool.

Calabash calls Bash commands from CoffeeScript.
And make it easier to be used in small tasks.

### Usage

You may install this from NPM:

```
sudo npm install -g calabash
```

And use it togather with `node-dev` to run commands at background:

```coffee
require("calabash").do "first parameter as comment",
  "pkill -f doodle"
  "coffee -o lib/ -wbc coffee/"
  "jade -o build/ -wP layout/"
  "style -o build/ -w layout/"
  "node-dev server.coffee"
  "doodle build/"
```

Or just run in an Array:

```coffee
require('../coffee').run [
  'echo 1'
  'echo 2'
]
```

With `v0.1.0` new syntax is availale to add tasks in `dev.coffee`:

```coffee
bash = require 'calabash'
bash.add 'task lily',
  'echo lily'
bash.add 'task ted',
  'echo ted'
bash.go()
```

and trigger a special task with `coffee dev.coffee lily`.

It would be better to use it with `node-dev` to enable reloading.

### License

MIT

repository: mvc-works/calabash

repo_name: mvc-works/calabash


text:
# 2013-08-16

## Code

## Visualization

### Trends in the full SAAM dataset

I want to repeat some of the charts I made using just the paintings subset of the SAAM collections data.

#### Genres

- `landscape`

- `portraiture` (made from a query of: `(portrait OR portrait male OR portrait female OR portrait group)`)

- `western`

- `abstract`

The same general trend still appears, although the huge dropoff in portraiture paintings is less pervasive when other formats are added in.

It is interesting to see the difference in the trendline for abstract artworks. Paintings have a spike in the late 1960s and then fall off precipitously. However factoring in other artworks, abstraction dips down **but remains at the 25% level from the 1980s onward**.

I also tried adding in `cityscape`, which shows a modest accumulation up through the 1850s, peaking in the 1980s (although with a **distinct dip in the late 1960s coincident with the spike in abstract artworks**)

#### Ethnicities

- `ethnic`

- `indian`

- `african-american`

This shows largely the same trends as the paintings alone.

#### Gender

- `figure male` OR `portrait male`

- `figure female` OR `portrait female`

A preponderance of male figures drops down to rough equilibrium with female figures between 1850-1900, and remains like that for the rest of the time span.

repository: mdlincoln/saam

repo_name: mdlincoln/saam


text:
# Polymorphism for Linux

This part is dedicated for linux's users, if you need a refresh of what is a polymorphic program just clic here. Or if you looking for a windows version clic here

To know what to crypt or where to find the key for instance, we used [sections (ELF)](https://fr.wikipedia.org/wiki/Executable_and_Linkable_Format), which you can see like drawers for your binary content. The key is stocked in `.PoC_Key`, the payload function in `.unix`, and a boolean to know wether we are running it for the first time or not `.unixb`. (Those sections doesn't exist, we can create/alter an already existing sections with `__attribute__((section(x)))` ([variable](http://www.keil.com/support/man/docs/armcc/armcc_chr1359124977848.htm), [function](http://www.keil.com/support/man/docs/armclang_ref/armclang_ref_chr1384876160481.htm), [`#pragma`](https://docs.microsoft.com/fr-fr/cpp/preprocessor/section?view=vs-2019)).

> *Payload :
> Component of a computer virus that runs the malicious commands.*

# How to use :

The CRYPTED_FUNC_SIZE must be the exact size of your new section ! You can use `size -d -A binaryname` to get it.

First one, you need to refer your IP and a Port to use, in `src/main.c` line 74 and 68.
In order to use it over the internet, use your public IP and forward the associated port.

     git clone https://github.com/PoCFrance/Whitecomet-Research.git
     cd Polymorphic
     make re
     ./PoCrypt

Now you get a binary named "**Pocrypt**" this is the malware.
On your device use `nc -l [port]` for waiting the reverse shell connexion.
Then, the binary must be executed on the victim's machine in order for it to connect.
Congratulation you're connected !

## How it works :

There are three main parts in the malware : the Payload, Key and Cryptor.
We're using binary's segments for each parts.

#### The Cryptor - Not Crypted
The first function called when launching the binary. It finds the Key and use it with the [XOR operation](https://en.wikipedia.org/wiki/XOR_cipher) in order to decrypt (on the currently running binary) the Payload segment. When it's done the Cryptor re encrypt the Payload with a new key.

#### The Key - Not Crypted
A random key regenerates at each execution of the program, used to decrypt the Payload. The key and the payload must have the same length in order to have an **One Time Pad encryption**([\*](https://en.wikipedia.org/wiki/One-time_pad)).

#### The Payload - Crypted
Basic reverse shell, the victim execute the program that then opens a server on it's machine on which you can connect and run commands.

##### The forgotten one : Saving - Not Crypted
Very basic file writing with the exception of deleting itself before doing so.

repository: PoCInnovation/Whitecomet-Research

repo_name: PoCInnovation/Whitecomet-Research


text:
Precise Commits

# Why `precise-commits`?

🔎 It is simply **the most exact and least disruptive way** to add consistent code formatting (by [Prettier](https://prettier.io)) to an existing codebase.

✨ You only **reformat the exact code you have modified anyway** as part of your normal development!

| Tool                | Staged files | Existing commits | PR Build | Arbitrary commands | Precision                       |
| ------------------- | ------------ | ---------------- | -------- | ------------------ | ------------------------------- |
| **precise-commits** | ✅           | ✅               | ✅       | ❌                 | **Individual character ranges** |
| lint-staged         | ✅           | ❌               | ❌       | ✅                 | Entire File                     |
| pretty-quick        | ✅           | ❌               | ❌       | ❌                 | Entire File                     |

# Background

Implementing a new code-style in an existing codebase can be really tricky.

[Prettier](https://prettier.io) is an amazing automated code formatting tool, but that does not mean that introducing it into an existing codebase is trivial.

Regardless of how consistent the existing code-style might be, introducing [Prettier](https://prettier.io) will result in larger diffs, which:

1. Increases the complexity and review time burden of PRs on senior team members.
2. Potentially increases the amount of time it takes to complete a PR in the first place.
3. Can block concurrent work on the same codebase and/or result in nasty merge conflicts with outstanding feature branches.

Other tools, such as `lint-staged`, made an excellent first step towards mitigating the scope of the impact of the points above, by only running linters and formatters on files which have changed.

This is great for small codebases, in which the authors do not mind much that they are polluting the git history of the files they are touching, but **it is not enough**.

In large and enterprise codebases (particularly those organized as monorepos), the git history of each file is really important.

> If I make a change on line 10 of a 4000 line file, I shouldn't be forced to reformat all 4000s lines (thus making me the last git user to update all of them) as part of my PR.
>
> I should just need to reformat line 10.

This is where `precise-commits` comes in!

# Our ideal end-goal...

1. All developers on our team develop using consistent, automated formatting as they write their code.
   e.g. Running an IDE-based plugin, such as "vscode-prettier" with "format on save" enabled.

2. Each time they commit, a precommit hook is triggered to _ensure_ that the staged code is formatted consistently.

3. Each time a Pull Request opened on our remote repo, a build is triggered on a CI server, during which the formatting
   is checked to ensure that all the files touched for that PR were formatted consistently.

# How `precise-commits` helps us get there...

1. All developers on our team write their code as they always have.

2. Each time they commit, a precommit hook is triggered which will run `precise-commits` on the code and ensure that **the exact code they already modified** is formatted consistently. Any untouched existing code will not be mutated.

3. Each time a Pull Request opened on our remote repo, a build is triggered on a CI server, during which `precise-commits`
   runs to ensure that all the **committed lines of code** for that PR was formatted consistently.

...and after enough time has passed, **our codebase will be formatted consistently, despite us never having to disrupt our feature-building momentum!**

# How it works

Through analyzing your staged files (or any files modified between two given commit SHAs) `precise-commits` will work out exactly what lines and characters within those files have actually been changed or added.

It then uses this information to run [Prettier](https://prettier.io) in a very focused way, allowing it to only reformat what is relevant for your current work, and allowing you to keep your PRs small and explicit!

# Installation

`precise-commits` expects `prettier` to be available as a `peerDependency`, so you will need to install this yourself as a `devDependency` of your project.

```sh
npm install --save-dev prettier precise-commits
```

# Usage

It is intended that you will run `precise-commits` as a CLI, and it will automatically pick up on any of the standard [Prettier configuration files](https://prettier.io/docs/en/configuration) you may have in your project, including [`.prettierignore`](https://prettier.io/docs/en/ignore#ignoring-files) files.

## 1. Running it manually

1. Add an npm script to your package.json, such as:

```js
{
  //...
  "scripts": {
    "precise-commits": "precise-commits"
  }
  //...
}
```

2. Execute the npm script, e.g. for the one above run:

```sh
npm run precise-commits
```

## 2. "Precommit" Hook

The recommended way to run `precise-commits` is as a "precommit" hook.

A great tool for setting up the hook is [`husky`](https://github.com/typicode/husky). You can install and run it as follows:

```sh
npm install --save-dev husky
```

Update the `"scripts"` section of your `package.json`:

```js
{
  //...
  "scripts": {
    "precise-commits": "precise-commits",
    "precommit": "npm run precise-commits"
  }
  //...
}
```

## 3. As part of a PR build

When running a build for your PR, you can run `precise-commits` to ensure that the author's changes are all formatted consistently.

The key things you need to configure are:

1. The `--check-only` flag for `precise-commits` so that it will error out if it finds any inconsistent formatting
2. The `--head` and `--base` flags so that `precise-commits` knows what commits it should consider when resolving modified files. Most CI servers will have environment variables you can use to resolve these.

For example, if your PR is building on [Travis](https://travis-ci.com/), your config might look like this:

**.travis.yml**

```yaml
# ... Other config options here ...
install:
  - yarn install
script:
  - 'if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then precise-commits --whitelist="src/**/*.ts" --check-only --head=$TRAVIS_PULL_REQUEST_SHA --base=$(git merge-base HEAD $TRAVIS_BRANCH); fi'
  - yarn test
  - yarn e2e
# ... Other config options here ...
```

# CLI Configuration Options

As was hinted at above, the `precise-commits` CLI supports a few different configuration options:

* `--whitelist`: **[String, Default: `"*"`]**
  * Whitelist is a glob pattern ([the glob syntax from the glob module is used](https://github.com/isaacs/node-glob/blob/master/README.md#glob-primer)).
  * It is used to inform what files are considered when resolving modified files (by default all are considered).
  * Don't forget the quotes around the globs! The quotes make sure that `precise-commits` expands the globs rather than your shell.

* `--formatter`: **[String, Default: `"prettier"`]**
  * Currently only prettier is supported
  * If you are interested in adding support for a different formatter, all you need to do is provide an object which [implements this interface](https://github.com/nrwl/precise-commits/blob/master/src/precise-formatter.ts).

* `--check-only`: **[Boolean, Default: `false`]**
  * Only check the code formatting is consistent with the resolved config

* `--base`: **[String, NO DEFAULT]**
  * Base commit SHA to be used in conjunction with the `--head` flag

* `--head`: **[String, CONDITIONAL DEFAULT]**
  * Later commit SHA (e.g. the `HEAD` of a PR branch) to be used in conjunction with the `--base` flag
  * NOTE on conditional default: If no value is provided for `--head`, but a value is given for `--base`, it will default to checking "HEAD"

repository: scythianfuego/precise-commits

repo_name: scythianfuego/precise-commits


text:
# Scalacheck LEGACY API

This describes the LEGACY API syntax (pre 0.34)

## Container types

### Generic Container

The most flexible but less convenient container type is `GenericContainer`. This container allows to launch any docker image with custom configuration.

```scala
class GenericContainerSpec extends AnyFlatSpec with ForAllTestContainer {
  override val container: GenericContainer = GenericContainer("nginx:latest",
    exposedPorts = Seq(80),
    waitStrategy = Wait.forHttp("/")
  )

  "GenericContainer" should "start nginx and expose 80 port" in {
    assert(Source.fromInputStream(
      new URL(s"http://${container.containerIpAddress}:${container.mappedPort(80)}/").openConnection().getInputStream
    ).mkString.contains("If you see this page, the nginx web server is successfully installed"))
  }
}
```

### Docker Compose

```scala
class ComposeSpec extends AnyFlatSpec with ForAllTestContainer {
  override val container: DockerComposeContainer = DockerComposeContainer(new File("src/test/resources/docker-compose.yml"), exposedServices = Seq(ExposedService("redis_1", 6379)))

  "DockerComposeContainer" should "retrieve non-0 port for any of services" in {
    assert(container.getServicePort("redis_1", 6379) > 0)
  }
}
```

### Selenium

Before you can use this type of containers, you need to add the following dependencies to your project:

```scala
"com.dimafeng" %% "testcontainers-scala-scalatest-selenium" % testcontainersScalaVersion % "test"
```

Now you can write a test in this way:

```
class SeleniumSpec extends AnyFlatSpec with SeleniumTestContainerSuite with WebBrowser {
  override def desiredCapabilities = DesiredCapabilities.chrome()

  "Browser" should "show google" in {
      go to "http://google.com"
  }
}

```

In this case, you'll obtain a clean instance of browser (firefox/chrome) within container to which
a test will connect via remote-driver. See [Webdriver Containers](https://www.testcontainers.org/usage/webdriver_containers.html)
for more details.

### Mysql

Requires you to add this dependency:

```scala
"com.dimafeng" %% "testcontainers-scala-mysql" % testcontainersScalaVersion % "test"
```

```scala
class MysqlSpec extends AnyFlatSpec with ForAllTestContainer {

  override val container: MySQLContainer = MySQLContainer()

  "Mysql container" should "be started" in {
    Class.forName(container.driverClassName)
    val connection = DriverManager.getConnection(container.jdbcUrl, container.username, container.password)
      ...
  }
}
```

The container can also be customized using the constructor parameters, this snippet will initialize a docker container from a specific docker image, with a specific schema name and specific username/password
```scala
class MysqlSpec extends AnyFlatSpec with ForAllTestContainer {

  override val container: MySQLContainer = MySQLContainer(mysqlImageVersion = DockerImageName.parse("mysql:5.7.18"),
                                          databaseName = "testcontainer-scala",
                                          username = "scala",
                                          password = "scala")

  "Mysql container" should "be started" in {
    Class.forName(container.driverClassName)
    val connection = DriverManager.getConnection(container.jdbcUrl, container.username, container.password)
      ...
  }
}
```

### PostgreSQL

Requires you to add this dependency:

```scala
"com.dimafeng" %% "testcontainers-scala-postgresql" % testcontainersScalaVersion % "test"
```

```scala
class PostgresqlSpec extends AnyFlatSpec with ForAllTestContainer  {

  override val container: PostgreSQLContainer = PostgreSQLContainer()

  "PostgreSQL container" should "be started" in {
    Class.forName(container.driverClassName)
    val connection = DriverManager.getConnection(container.jdbcUrl, container.username, container.password)
      ...
  }
}
```

### Multiple Containers

If you need to test more than one container in your test, you could use `MultipleContainers` for that. Just define your containers and pass them to the `MultipleContainers` constructor:
```scala
val mySqlContainer = MySQLContainer()
val genericContainer = GenericContainer(...)

override val container: MultipleContainers = MultipleContainers(mySqlContainer, genericContainer)
```

#### Dependent containers

If configuration of one container depends on runtime state of another one, you should define your containers as `lazy`:

```scala
lazy val container1 = Container1()
lazy val container2 = Container2(container1.port)

override val container: MultipleContainers = MultipleContainers(container1, container2)
```

### Fixed Host Port Containers

This container will allow you to map container ports to statically defined ports on the docker host.

```scala
...
val container = FixedHostPortGenericContainer("nginx:latest",
    waitStrategy = Wait.forHttp("/"),
    exposedHostPort = 8090,
    exposedContainerPort = 80
  )
```

### Custom configuration of inner containers

All container types have constructor methods with most popular parameters. In case you're missing some custom option from `testcontainers-java`, there is
a method that provides an elegant way to tune the nested container. **It's not recommended to access inner container directly.**

```
override val container: MySQLContainer = MySQLContainer().configure { c =>
    c.withNetwork(...)
    c.withStartupAttempts(...)
  }
```

### Start/Stop hooks

If you want to execute your code after container start or before container stop you can override `afterStart()` and `beforeStop()` methods.

```scala
class MysqlSpec extends AnyFlatSpec with ForAllTestContainer {

  ...

  override def beforeStop(): Unit = {
    // your code
  }

  override def afterStart(): Unit = {
    // your code
  }
}
```

repository: sullis/testcontainers-scala

repo_name: sullis/testcontainers-scala


text:
# New computer setup

---

## If second-hand
### Format the drive

1. Restart with cmd-R or cmd-D
2. Erase drive / 3x if second-hand
3. Reinstall MacOS

---

## First boot

### Change system password.

### System Prefs
```
  Network
      add Google DNS (https://developers.google.com/speed/public-dns/)
      <IP_ADDRESS>
      <IP_ADDRESS>
      add Open DNS (http://www.opendns.com/opendns-ip-addresses/)
      <IP_ADDRESS>
      <IP_ADDRESS>
```

### Setup SSH keys for Github

- Setup ssh keys for github use:
  ```
  ssh-keygen -t rsa -b 4096 -C<EMAIL_ADDRESS>  ```
- Start the ssh-agent:
  ```
  eval "$(ssh-agent -s)"
  ```
- Add the ssh key to the agent:
  ```
  ssh-add -K ~/.ssh/id_rsa # -K for Mac OS X keychain persistence
  ```
- Get copy of public key:
  ```
  pbcopy < ~/.ssh/id_rsa.pub # paste into GitHub GUI
  ```
- Create new ssh key pairing via github.com: Settings > SSH > New SSH key
- Test setup:
  ```
  ssh -T<EMAIL_ADDRESS>  ```

### Clone dotfiles repo via SSH

```
cd ~
git clone git@github.com:phamann/dotfiles.git
mv dotfiles .dotfiles
```

### Run doftiles bootscript

```
cd ~/.dotfiles
script/bootstrap
scropt/install
```

### Post bootscript setup

- Restart iTerm
- Test vim setup
- Test tmux setup
- Sync iTerm preferences via Dropbox

###

### Setup Chrome

- Login to [LastPass](https://lastpass.com/)
- Copy main Google account password to clipboard
- Login to Chrome
- Ensure all settings and extensions are syncing
- Repeat steps for Chrome Canary

### Setup DropBox

- Open DropBox app
- Login using credentials from LastPass
- Setup sync
- Symlink Documents, Code, Personal

### Install virtual machines

- Download [ievms](//github.com/xdissent/ievms)
- `curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | bash`

----

## Additions

### Change desktop background

- [Suggestion 1](http://pichost.me/1793017/)
- [Suggestion 2](http://pichost.me/1978561/)
- [Suggestion 3](http://howaboutorange.blogspot.co.uk/2012/09/geometric-desktop-wallpapers.html)

repository: phamann/dotfiles

repo_name: phamann/dotfiles


text:
# Pantone Color Picker
I think color pickers are my to-do list. This was a project I built to test out how I could use Svelte.js for practical problems, and work on my styling mimicry, because I like how Google has designed their color picker widget on search.

It's all pretty basic as far as Svelte goes. It uses Margaret2's great Pantone file resource to look up the nearest picked color and make a little card for it, then I generate a Google Image Search URL for that Panton color, or you can copy a color value with a click which is nice.

Some bugs:
- the UI breaks if you put in values outside of the range
- the UI doesn't include hex
- the transitions are slightly out of sync because I'm using `transition: all` somewhere

repository: AXARAU/pantone-picker

repo_name: AXARAU/pantone-picker


text:
# How To: Organize Inputs into Fieldsets

The [wq framework] makes it easy to automatically generate a form from a [model definition], and then [customize the display of each individual input][custom-input].  However, it is common to need to group related fields and customize how they are laid out together on the page.  To do that, you can use wq's fieldset support, as described in this guide.

 * [Initial Setup](#initial-setup)
 * [Step 1: Define Fieldsets](#step-1-define-fieldsets)
 * [Step 2: Customize Fieldset Appearance](#step-2-customize-fieldset-appearance)
 * [Step 3: Implement React Component](#step-3-implement-react-component)

>  wq's fieldsets directly correspond to the `group` XLSForm type, and are stored the same database table as the "parent" survey record.  By contrast, wq's analog to an XLSForm `repeat` requires a separate "attachment" table, as described in [How To: Implement Repeating Nested Forms][nested-forms].

## Initial Setup

For this how-to guide, we'll assume a simple project with a single "survey" app.  You can download the example XLSForm here:

 [**Download survey.csv**][survey.csv]

> See the [getting started][setup] guide for more details about initial project setup.

```bash
wq create myproject --without-npm
cd myproject/db/
wq addform path/to/survey.csv
```

This should result in the following app layout:

#### db/survey/models.py
```python
from django.db import models

class Survey(models.Model):
    name = models.TextField(
        null=True,
        blank=True,
        verbose_name="Name",
        help_text="Project Name",
    )
    code = models.TextField(
        null=True,
        blank=True,
        verbose_name="Code",
        help_text="URL Slug",
    )
    status = models.CharField(
        choices=(
            ("active", "Active"),
            ("pending", "Pending Approval"),
            ("complete", "Complete"),
            ("inactive", "Inactive"),
        ),
        max_length=8,
        null=True,
        blank=True,
        verbose_name="Status",
        help_text="Administrative designation",
    )
    status_note = models.TextField(
        null=True,
        blank=True,
        verbose_name="Admin Notes",
        help_text="Reason for designation",
    )

    class Meta:
        verbose_name = "survey"
        verbose_name_plural = "surveys"
```

#### db/survey/rest.py
```python
from wq.db import rest
from .models import Survey

rest.router.register_model(
    Survey,
    fields="__all__",
)
```

Go ahead and run `./deploy.sh` to update the [app configuration][config].

## Step 1: Define Fieldsets

The example above relies on [wq.db]'s default [`ModelSerializer`][ModelSerializer] class, which automatically generates a form configuration from the Django model fields.  It is possible to override the serializer for a model to organize the fields into fieldsets.  The configuration API is loosely modeled after Django's [`ModelAdmin.fieldsets`][modeladmin-fieldsets] setting.

To configure the serializer, create `db/survey/serializers.py` and define a class that extends `ModelSerializer`.  You can then organize the fields into fieldsets by defining `Meta.wq_fieldsets`.

#### db/survey/serializers.py

```python
from wq.db.rest.serializers import ModelSerializer
from rest_framework import serializers
from .models import Survey

class SurveySerializer(ModelSerializer):
    class Meta:
        model = Survey
        fields = '__all__'
        wq_fieldsets = {
            'general': {
                'label': 'General Information',
                'fields': ['name', 'code'],
            },
            'admin': {
                'label': 'Administration',
                'fields': ['status', 'status_note'],
            }
        }
```

#### db/survey/rest.py (with serializer)
```python
from wq.db import rest
from .models import Survey
from .serializers import SurveySerializer

rest.router.register_model(
    Survey,
    serializer=SurveySerializer,
)
```

> Note that you could also define the groups via separate models with a OneToOne relationship to `Survey`, then specify nested `ModelSerializer` attributes on `SurveySerializer` for each group.  wq will detect this and configure the fieldset/group appropriately, but you will still need to implement the logic for actually creating and/or updating OneToOne relationships manually.  For groups that do not repeat, it is generally easier to just define the fields directly on the Survey model and define `wq_fieldsets`.  (Though as noted above, [nested *repeat* groups][nested-forms] always require a separate table and serializer.)

### Demo 1

After running ./deploy.sh again, you should have an app with essentially the following configuration:

```js
// app/js/data/config.js
const config = {
    "pages": {
        "survey": {
            "name": "survey",
            "url": "surveys",
            "list": true,
            "form": [
                {
                    "label": "General Information",
                    "name": "general",
                    "type": "group",
                    "children": [
                        {
                            "name": "name",
                            "label": "Name",
                            "hint": "Project Name",
                            "type": "text"
                        },
                        {
                            "name": "code",
                            "label": "Code",
                            "hint": "URL Slug",
                            "type": "text"
                        }
                    ]
                },
                {
                    "label": "Administration",
                    "name": "admin",
                    "type": "group",
                    "children": [
                        {
                            "name": "status",
                            "label": "Status",
                            "hint": "Administrative designation",
                            "choices": [
                                {
                                    "name": "active",
                                    "label": "Active"
                                },
                                {
                                    "name": "pending",
                                    "label": "Pending Approval"
                                },
                                {
                                    "name": "complete",
                                    "label": "Complete"
                                },
                                {
                                    "name": "inactive",
                                    "label": "Inactive"
                                }
                            ],
                            "type": "select one"
                        },
                        {
                            "name": "status_note",
                            "label": "Admin Notes",
                            "hint": "Reason for designation",
                            "type": "text"
                        }
                    ]
                }
            ],
            "verbose_name": "survey",
            "verbose_name_plural": "surveys"
        }
    }
};

// app/js/myproject.js
import wq from './wq.js';

wq.init(config).then(...);

// navigate to /surveys/new
```

> As the configuration above shows, defining a fieldset causes the corresponding fields to be nested under a "group" field.  Similarly, the actual JSON data sent from/to the wq.db API will include a nested object containing those attributes.  In general this will all be handled transparently by wq, but if you are using a custom [context plugin] to set defaults, be sure to return a nested object like `{"admin": {"status": "active" }}` (even though the actual database table is not nested).  The [third demo](#demo-3) below includes a context plugin.

## Step 2: Customize Fieldset Appearance

The default [`<Fieldset/>`][Fieldset] component may be sufficient for many cases where just a simple vertical grouping is required.  However, it is common to override the layout with a different component.  In this example, you might want to make the first group horizontal and the second one collapsible.  To do this, we will need to set the `control.appearance` on the entries in `wq_fieldset`.

> While this is the same configuration syntax as that for individual inputs, it draws from the pool of [general components][components], not [input components].

#### db/survey/serializers.py (with appearance)

```python
from wq.db.rest.serializers import ModelSerializer
from rest_framework import serializers
from .models import Survey

class SurveySerializer(ModelSerializer):
    class Meta:
        model = Survey
        fields = '__all__'
        wq_fieldsets = {
            'general': {
                'label': 'General Information',
                'control': {'appearance': 'horizontal-view'},
                'fields': ['name', 'code'],
            },
            'admin': {
                'label': 'Administration',
                'control': {'appearance': 'expansion-panel'},
                'fields': ['status', 'status_note'],
            }
        }
```

### Demo 2

After another deploy, you should end up with the following app configuration:

```js
// app/js/data/config.js
const config = {
    "pages": {
        "survey": {
            "name": "survey",
            "url": "surveys",
            "list": true,
            "form": [
                {
                    "label": "General Information",
                    "control": {
                        "appearance": "horizontal-view"
                    },
                    "name": "general",
                    "type": "group",
                    "children": [
                        {
                            "name": "name",
                            "label": "Name",
                            "hint": "Project Name",
                            "type": "text"
                        },
                        {
                            "name": "code",
                            "label": "Code",
                            "hint": "URL Slug",
                            "type": "text"
                        }
                    ]
                },
                {
                    "label": "Administration",
                    "control": {
                        "appearance": "expansion-panel"
                    },
                    "name": "admin",
                    "type": "group",
                    "children": [
                        {
                            "name": "status",
                            "label": "Status",
                            "hint": "Administrative designation",
                            "choices": [
                                {
                                    "name": "active",
                                    "label": "Active"
                                },
                                {
                                    "name": "pending",
                                    "label": "Pending Approval"
                                },
                                {
                                    "name": "complete",
                                    "label": "Complete"
                                },
                                {
                                    "name": "inactive",
                                    "label": "Inactive"
                                }
                            ],
                            "type": "select one"
                        },
                        {
                            "name": "status_note",
                            "label": "Admin Notes",
                            "hint": "Reason for designation",
                            "type": "text"
                        }
                    ]
                }
            ],
            "verbose_name": "survey",
            "verbose_name_plural": "surveys"
        }
    }
};

// app/js/myproject.js
import wq from './wq.js';

wq.init(config).then(...);

// navigate to /surveys/new
```

## Step 3: Implement React Component

In the above example, the group labels are missing since the selected components aren't reading the `label` prop.  This can be addressed by defining a and registering a custom component, as in the example below.  In addition, it may be nice to have the default `<Fieldset/>` wrap the [`<HorizontalView/>`][HorizontalView].

#### db/survey/serializers.py (with custom components)

```python
from wq.db.rest.serializers import ModelSerializer
from rest_framework import serializers
from .models import Survey

class SurveySerializer(ModelSerializer):
    class Meta:
        model = Survey
        fields = '__all__'
        wq_fieldsets = {
            'general': {
                'label': 'General Information',
                'control': {'appearance': 'horizontal-fieldset'},
                'fields': ['name', 'code'],
            },
            'admin': {
                'label': 'Administration',
                'control': {'appearance': 'collapsible-fieldset'},
                'fields': ['status', 'status_note'],
            }
        }
```

Finally, implement and register custom components as shown in the example JavaScript below.

> Note: When using [`wq create --without-npm`][setup], you will need a way to compile JSX to `React.createElement()` calls.  You could use the [online Babel converter][babel-repl], or use npm to install Rollup and Babel (but not necessarily all of create-react-app and wq's npm dependencies).  If you use Rollup, you may find [@wq/rollup-plugin] useful, as it will allow you to write plain npm imports and have them automatically translated to leverage exports from [`./wq.js`][wq.js].  The `app/js/custom.js` example in the demo below simulates the output of a Rollup build.

### Demo 3

```js
// app/js/custom.js
import { modules } from './wq.js';
const React = modules['react'];
const { Fieldset, HorizontalView, ExpansionPanel } = modules['@wq/material'];

function HorizontalFieldset({label, children}) {
    return <Fieldset label={label}>
        <HorizontalView>
            {children}
        </HorizontalView>
    </Fieldset>
}

function CollapsibleFieldset({label, children}) {
    return <ExpansionPanel summary={label}>
        {children}
    </ExpansionPanel>
}

const custom = {
    components: {
        HorizontalFieldset,
        CollapsibleFieldset
    },
    context(ctx, routeInfo) {
        // Set default status for new surveys
        if (routeInfo.name === "survey_edit:new") {
            return {
                "admin": {
                    "status": "active"
                }
            }
        }
    }
}

// app/js/data/config.js
const config = {
    "pages": {
        "survey": {
            "name": "survey",
            "url": "surveys",
            "list": true,
            "form": [
                {
                    "label": "General Information",
                    "control": {
                        "appearance": "horizontal-fieldset"
                    },
                    "name": "general",
                    "type": "group",
                    "children": [
                        {
                            "name": "name",
                            "label": "Name",
                            "hint": "Project Name",
                            "type": "text"
                        },
                        {
                            "name": "code",
                            "label": "Code",
                            "hint": "URL Slug",
                            "type": "text"
                        }
                    ]
                },
                {
                    "label": "Administration",
                    "control": {
                        "appearance": "collapsible-fieldset"
                    },
                    "name": "admin",
                    "type": "group",
                    "children": [
                        {
                            "name": "status",
                            "label": "Status",
                            "hint": "Administrative designation",
                            "choices": [
                                {
                                    "name": "active",
                                    "label": "Active"
                                },
                                {
                                    "name": "pending",
                                    "label": "Pending Approval"
                                },
                                {
                                    "name": "complete",
                                    "label": "Complete"
                                },
                                {
                                    "name": "inactive",
                                    "label": "Inactive"
                                }
                            ],
                            "type": "select one"
                        },
                        {
                            "name": "status_note",
                            "label": "Admin Notes",
                            "hint": "Reason for designation",
                            "type": "text"
                        }
                    ]
                }
            ],
            "verbose_name": "survey",
            "verbose_name_plural": "surveys"
        }
    }
};

// app/js/myproject.js
import wq from './wq.js';
wq.use(custom);
wq.init(config).then(...);

// navigate to /surveys/new
```

> If a fieldset is configured to use an unregistered component type, an error message will be displayed together with the default fieldset.  You can see this in action by removing `wq.use(custom);` from the example above.

The same approach can be used for any number of customization scenarios.  In general, it is best to pass the `children` directly into the rendered component, since it will already contain an [`<AutoInput/>`][AutoInput] for each of the fields in the group.

It is also possible to explicitly render each [`<Input/>`][input components] within the fieldset component, manually specifying the name and other props as needed.  However, doing so will break the automatic mapping from database fields to the UI.  Only do so if you have a very specific layout that can't be handled by overriding the fieldset and/or [individual input components][custom-input].

[wq framework]: ../index.md
[model definition]: ./describe-your-data-model.md
[custom-input]: ./define-a-custom-input-type.md
[nested-forms]: ./implement-repeating-nested-forms.md
[context plugin]: ../plugins/context.md
[Fieldset]: ../components/Fieldset.md
[ExpansionPanel]: ../components/ExpansionPanel.md
[HorizontalView]: ../components/HorizontalView.md
[components]: ../components/index.md
[input components]: ../inputs/index.md
[setup]: ../overview/setup.md
[survey.csv]: ./organize-inputs-into-fieldsets/survey.csv
[Django model]: https://docs.djangoproject.com/en/3.1/topics/db/models/
[config]: ../config.md
[wq.db]: ../wq.db/index.md
[ModelSerializer]: ../wq.db/serializers.md
[modeladmin-fieldsets]: https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fieldsets
[AutoInput]: ../components/AutoInput.md
[wq.js]: ../wq.md
[babel-repl]: https://babeljs.io/repl
[Rollup]: https://rollupjs.org/
[Babel]: https://babeljs.io/
[@wq/rollup-plugin]: <EMAIL_ADDRESS>

repository: wq/wq

gha_language: Python

repo_name: wq/wq