text:
# 00 TypeScript

In this demo we will add support for TypeScript. We will do the transpilation process in two steps:
  - From Typescript to ES6 using Typescript plumbing.
  - From ES6 to ES5 using babel.

¿Why this approach? We want our project to be as standard as possible, if you transpile from es6 to es5
using babel you will be using the same approach as many existing projects an libraries.

We will start from sample _00 react_, install TypeScript locally,
configure a tsconfig file, add some ts like, install awesome-typescript-loader and apply it to webpackconfig.

Summary steps:
 - Install TypeScript as a local dependency.
 - Configure TypeScript for our project (tsconfig)
 - Port our project to TypeScript and add use in our code some of the ts features.
 - Install [awesome-typescript-loader](https://github.com/s-panferov/awesome-typescript-loader).
 - Add the proper configuration in `webpack.config.js`

## Prerequisites

Prerequisites, you will need to have nodejs installed in your computer (at least v. 8.9.2). If you want to follow this step guides you will need to take as starting point sample _00 react_.

## steps

- _npm install_ to install previous sample packages:

```bash
npm install
```

- TypeScript is a nice superset of JavaScript that allows static typings amongst other interesting features. All the code we type in TypeScript will not run on the browser, so we need to transpile it. Let's start by installing TypeScript locally(\*).

```
npm install typescript --save-dev
```

_(*) Why installing TypeScript locally and not globally? By installing it locally the project does not depend on global dependencies and is easier to e.g make build and pass unit tests on a clean CI (Continuous Integration) machine like [Travis](https://travis-ci.org/), [Docker](https://www.docker.com/), [Jenkins](https://jenkins.io/), etc.

Another benefit of installing locally is that we can set up a specific version of TypeScript with no rely on the global version installed on the machine is being executed._

- The next step is to add a TypeScript configuration file, *`tsconfig.json`*.
In this file will define the settings that we want, e.g to transpile to ES5 amongst others.

_./tsconfig.json_

```json
{
  "compilerOptions": {
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node",
    "declaration": false,
    "noImplicitAny": false,
    "jsx": "react",
    "sourceMap": true,
    "noLib": false,
    "suppressImplicitAnyIndexErrors": true,
    "esModuleInterop": true
  },
  "compileOnSave": false,
  "exclude": ["node_modules"]
}

```

- In order to get JQuery and React intellisense, we can install JQuery and React typings:

```
npm install @types/jquery @types/react @types/react-dom --save-dev
```

> Play a bit with JQuery statement and intellisense

- Let's port our code to TypeScript, we are going to rename the files *`students.jsx`*, *`averageService.js`* and *`averageComponent.jsx`* to _students.**tsx**_, _averageService.**ts** and _averageComponent.**ts**_.

- Let's introduce some TypeScript, in *`students.tsx`* we are going to type the
variables we are using (check... this type is not needed typescript
already infers the values):

_./src/students.tsx_

```diff
import React from 'react';
import ReactDOM from 'react-dom';
import { AverageComponent } from './averageComponent';
- import logoImg from './content/logo_1.png';
+ const logoImg = require('./content/logo_1.png');

...

```

- Next we'll type our function in *`averageService.ts`*:

_./src/averageService.ts_

```diff
- export function getAvg(scores) {
+ export function getAvg(scores: number[]): number {
   return getTotalScore(scores) / scores.length;
  }

- function getTotalScore(scores) {
+ function getTotalScore(scores: number[]): number {
    return scores.reduce((score, count) => {
      return score + count;
    });
  }
```

- And *`averageComponent.tsx`*:

_./src/averageComponent.tsx_

```diff
import React from 'react';
import { getAvg } from './averageService';

- export const AverageComponent = () => {
+ export const AverageComponent: React.FunctionComponent  = () => {
- const [average, setAverage] = React.useState(0);
+ const [average, setAverage] = React.useState<number>(0);

  React.useEffect(() => {
-   const scores = [90, 75, 60, 99, 94, 30];
+   const scores: number[] = [90, 75, 60, 99, 94, 30];
    setAverage(getAvg(scores));
  }, []);

  return (
    <div>
      <span>Students average: {average}</span>
    </div>
  );
};

```

- Now it's time to configure *wepback*, let's install a loader that will manage
TypeScript: [awesome-typescript-loader](https://github.com/s-panferov/awesome-typescript-loader).

```
npm install awesome-typescript-loader --save-dev
```

- Let's update *`webpack.config.js`* in order to use this loader on **ts** extension files and in order to avoid having to add the extensions to the ts imports we can just add it to the array of extensions to be resolved:

_./webpack.config.js_
```diff
module.exports = {
  context: path.join(basePath, 'src'),
  resolve: {
-   extensions: ['.js', '.jsx'],
+   extensions: ['.js', '.jsx', '.ts', '.tsx'],
  },
  entry: {
-   app: ['regenerator-runtime/runtime', './students.jsx'],
+   app: ['regenerator-runtime/runtime', './students.tsx'],
...
  },
```

- And let's configure the proper loader for the _.ts_ extension

_./webpack.config.js_
```diff
  module: {
    rules: [
+     {
+       test: /\.(ts|tsx)$/,
+       exclude: /node_modules/,
+       loader: 'awesome-typescript-loader',
+       options: {
+         useBabel: true,
+         "babelCore": "@babel/core", // needed for Babel v7
+       },
+     },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
```

> It is possible to use directly babel 7 to transpile to typescript (preset-typescript) but type checking will be skipped:
https://blogs.msdn.microsoft.com/typescript/2018/08/27/typescript-and-babel-7/, it turns out is a fast process but you
have to rely on the editor capabilities to show that issues.

- Enable `sourceMaps` in `webpack config`:

### ./webpack.config.js

```diff
...

  plugins: [
    //Generate index.html in /dist => https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html', //Name of file in ./dist/
      template: 'index.html', //Name of template in ./src
    }),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
+ // For development https://webpack.js.org/configuration/devtool/#for-development
+ devtool: 'inline-source-map',

```

- If we run the app (`npm start`) we can check that everything is working as expected.

- If we open browser console we can access to `.ts` files and add breakpoints thanks to previous `sourceMap` configuration:

### ./tsconfig.json
```javascript
{
  "compilerOptions": {
    ...
    "sourceMap": true,
    ...
  },
  ...
}

```

### ./webpack.config.js

```javascript
...
  devtool: 'inline-source-map',

```

repository: Lemoncode/webpack-by-sample

path: /version 4/02 fx/01 typescript/README.md

repo_name: Lemoncode/webpack-by-sample


text:
# Instructions

In this exercise you'll be writing code to keep track of international dialing codes via an international dialing code hashmap.

The map uses an integer for its keys (the dialing code) and a string (country name) for its values.

You have 11 tasks which involve dialing-codes.

## 1. Create a pre-populated hashmap

There exists a pre-populated hashmap which contains the following 3 dialing codes: "United States of America" which has a code of 1, "Brazil" which has a code of 55 and "India" which has a code of 91. Define the `countries` var to store the pre-populated hashmap:

```clojure
countries
;;=> {1 "United States of America", 55 "Brazil", 91 "India"}
```

## 2. Add a country to a map

Add "United Kingdom" with a dialing code of 44 to the map created in task 1:

```clojure
(add-country countries 44 "United Kingdom")
;;=> {1 "United States of America", 44 "United Kingdom", 55 "Brazil", 91 "India"}
```

## 3. Get the country name matching a country code

Retrieve the name of the country with dialing code 55

```clojure
(country-name countries 55)
;;=> "Brazil"
```

## 4. Update a country name

Change the name of "United States of America" to "Les États-Unis":

```clojure
(update-map countries 1 "Les États-Unis")
;;=> {1 "Les États-Unis", 55 "Brazil", 91 "India"}
```

## 5. Check that a country exists in the map

Check that a record for Brazil exists in the map created in task 1

```clojure
(code-exists? countries 55)
;;=> true
```

## 6. Attempt to update name of country that is not in the map

Try to change the name of a country with a code that is not in the map e.g. 999. This should result in no change to the map:

```clojure
(update-map countries 999, "Newlands")
;;=> {1 "United States of America", 44 "United Kingdom", 55 "Brazil", 91 "India"}
```

## 7. Remove a country from the map

Remove India from the map:

```clojure
(remove-country countries 91)
;;=> {1 "United States of America", 55 "Brazil"}
```

## 8. Find the country with the longest name

Process the values in the map to find the one with the longest name:

```clojure
(longest-name countries)
;;=> "United States of America"
```

license: MIT

repository: exercism/clojure

branch_name: refs/heads/main

extension: md

gha_language: Clojure

gha_license_id: MIT

license_type: permissive

repo_name: exercism/clojure


text:
# ERC-Summer-Assignment-2020

This repository contains the solutions for the following questions:

1. Use an arduino to measure the value of a resistor (between 0 and 1K), and
display the value on an LCD screen.

2. Use a potentiometer to control angle of a servo motor and display the
current angle on a 3-digit 7-segment display using an arduino as
microcontroller. (Hint: You can use the  CD4511 IC).

3. Create a circuit using Arduino and an IR sensor/remote. The user should
be able to use the remote to do the following:
a. Control the brightness of a light bulb (not LED).
b. Set the speed of a DC motor as high, medium, low, or off.

4. Design a circuit for an automatic LED night light using LDR and LM741,
which is an op-amp IC.

The links to the Arduino simulation are given in the document ERC-Summer-Assignment.odt

branch_name: refs/heads/master


text:
# LightGallery image gallery for NodeBB
-----------
Adds [lightGallery](https://github.com/sachinchoolur/lightGallery) support for beautiful image viewing.  Per the lightGallery GitHub page, lightGallery is:
> A customizable, modular, responsive, lightbox gallery plugin for jQuery.

Note: You do not need to install lightGallery, JUST THIS PLUGIN.  LightGallery is a dependancy and as such will be automatically installed by nodebb-plugin-lightgallery.

Goal for this project was simply to enable basic functionality with the default settings.  Currently no functionality exists with this plugin to change any of the default lightGallery settings (ie a NodeBB plugin control panel).

## Installation
![Imgur](https://i.imgur.com/YixeZ5l.gif)

Or in the case you want to contribute to the project, you can git clone/npm install it into your node_modules directory following the directions here: [https://docs.nodebb.org/configuring/plugins/](https://docs.nodebb.org/configuring/plugins/)

2.  NPM Install:
	```
	npm install nodebb-plugin-lightgallery
	```

3.  Or clone the repo:
	```
	git clone https://github.com/june07/nodebb-plugin-lightgallery.git
	```

<!--stackedit_data:
eyJoaXN0b3J5IjpbNzIzMTE2MzUwLC0yOTU5ODYzNzQsLTE3Mz
I1ODczMSwtMTQyMzI1NjIzOF19
-->

gha_language: JavaScript


text:
# Context

This repository can be used to setup the necessary tools for running git, terraform, terragrunt and awscli in an ubuntu docker container.

## Setup

Clone this repository in a local directory. This directory shall then be mounted to the ubuntu linux docker container's workspace we will create for the tutorial.

```bash
git clone https://github.com/Riinkesh/iaac_tools.git
```

## Usage
1) Run a docker container using the command as below-

```bash
docker run -it -v C:\Users\IAMUser\Desktop\IAAC:/opt/workspace ubuntu
```
Here *C:\Users\IAMUser\Desktop\IAAC* is the path in a windows system, where the repository has been cloned.

2) Exec into the docker container and navigate (cd) to the path */opt/workspace*.

3) Run the startup script mounted from the repository in local-

```bash
./startup-script.sh
```
This script will install-

- Git
- AWS CLI Version 2
- Terraform (v 0.13.2)
- Terragrunt (v 0.23.40)
- and few other necessary packages (curl, vim, and unzip).

Run the below commands to confirm the installation once the above script completes.

```bash
git --version
aws --version
terraform -v
terragrunt -v
```
## Configuring the AWS CLI

This section explains how to configure the settings that the AWS CLI uses to interact with AWS. These include your security credentials, the default output format, and the default AWS Region.

Among different methods of configuring these settings is the environment variables method, which can be useful for scripting or temporarily setting a named profile (IAM User) as the default.

We are using the environment variables method in this tutorial.
The following examples show how you can configure environment variables for the default user.

```bash
export AWS_ACCESS_KEY_ID=YOURIAMUSERACCESSKEY
export AWS_SECRET_ACCESS_KEY=YOURIAMUSERSECRETaBcDxYzEXAMPLEACCESSKEY
export AWS_DEFAULT_REGION=us-central-1
```
Setting the environment variable changes the value used until the end of your session, or until you set the variable to a different value.

## License
[MIT](https://choosealicense.com/licenses/mit/)

license: MIT,Unlicense

detected_licenses: MIT Unlicense


text:
# Sawtooth-CapBAC

[Sawtooth](https://github.com/hyperledger/sawtooth-core) transaction family for [Capability Based Access Control](https://www.sciencedirect.com/science/article/pii/S089571771300054X).

**DISCLAIMER**: This implementation is a proof of concept not meant to be used for real-world applications.

## Testing environment

```bash
cd sawtooth-capbac/test/
```

*Requires [Docker Engine](https://docs.docker.com/install/) (17.03.0-ce or higher) and [Docker Compose](https://docs.docker.com/compose/install/).

### Build and start

```bash
docker-compose up --build
```

### Stop and clean

```bash
docker-compose down
```
*Stopping the processes is not enough for a clean restart (issued tokens will stay).

### Restart
```bash
docker-compose up
```

### Exec commands

```bash
docker exec <container name> <command>
```
*For more information see [docker exec](https://docs.docker.com/engine/reference/commandline/exec/).

### Attach a container

```bash
docker exec -it <container name> bash
```

Detach with:
```bash
exit
```

## Walkthrough

*Examples require the testing environment to be up and running.

### List capabilities

```bash
capbac list <server URI>
```
*The **capbac** command can run on any docker container featuring a [capbac-client](https://gitlab.com/kappanneo/sawtooth-capbac/blob/master/capbac-client/) (*device*, *subject* or *issuer*).

In our scenario *device* is running a [CoAP](https://en.wikipedia.org/wiki/Constrained_Application_Protocol) server, so we run:
```
capbac list coap://device
```

Using **docker exec** to run direclty on *subject*:

```
docker exec subject capbac list coap://device
```

Expected output if no capability token has been issued (only the root token is shown):

```json
{
    "0000000000000000": {
        "AR": {
            "resource": {
                "GET": 100,
                "PUT": 100
            },
            "time": {
                "GET": 100
            }
        },
        "IC": null,
        "II": "1539082955",
        "NA": "2000000000",
        "NB": "1539082954",
        "SU": "03c792d1c05a37e8b9e7afdcc9c72d6b50fd77a79631d5192f754b20202979f5af"
    }
}
```

*Subject's public key (SU) and "Not Before" time (NB) will differ.

### Issue a capability token

```bash
capbac issue [--root] <token as JSON string>
```

*For more datails on the capability token format see [capbac_version.py](https://gitlab.com/kappanneo/sawtooth-capbac/blob/master/capbac_version.py).

Root token issued by *device* before starting the CoAP sever (python dict from [test/Device/coap-server.py](https://gitlab.com/kappanneo/sawtooth-capbac/blob/master/test/Device/coap-server.py)):

```python
capability_token = {
    "ID":"0000000000000000",
    "DE": "coap://device",
    "AR": [{
        "AC": "GET",
        "RE": "time",
        "DD": 100
    }, {
        "AC": "GET",
        "RE": "resource",
        "DD": 100
    }, {
        "AC": "PUT",
        "RE": "resource",
        "DD": 100
    }],
    "NB": str(int(time.time())),
    "NA": "2000000000"
}
```
*The timestamp and the signature are not required since they are added by the [capbac-client](https://gitlab.com/kappanneo/sawtooth-capbac/blob/master/capbac-client/) when using **capbac issue**. Also, since this is a root token, the issuer's capability is always **null** and the public key of the subject is the same one of the issuer, so both are not required either.

Command used (from the same file):
```python
["capbac","issue","--root",json.dumps(capability_token)]
```
*If an error occurs during the issuing of the root token (e.g. a root token for that resource is already committed) the server will not start.

This gives *device* the control over the access rights for its resources.

*device* can delegate the access rights administation to a different device by issuing a new token dependant on the root one.

Example of dependant token (can only be issued by *device*):

```python
{
    "ID": "0000000000000001",
    "DE": "coap://device",
    "AR": [{
        "AC": "GET",
        "RE": "time",
        "DD": 99
    }, {
        "AC": "GET",
        "RE": "resource",
        "DD": 99
    }, {
        "AC": "PUT",
        "RE": "resource",
        "DD": 99
    }],
    "NB": "1525691114",
    "NA": "1540691114",
    "IC": "0000000000000000",
    "SU": <public key of the subject>
}
```
*The public key of the issuer, the timestamp and the signature are not required since they are added by the [capbac-client](https://gitlab.com/kappanneo/sawtooth-capbac/blob/master/capbac-client/) when using **capbac issue --root**.

Corresponding command with *issuer* as the subject of the token:

```bash
docker exec device capbac issue '{"ID":"0000000000000001","DE":"coap://device","AR":[{"AC":"GET","RE":"time","DD":99},{"AC":"GET","RE":"resource","DD":99},{"AC":"PUT","RE":"resource","DD":99}],"NB":"1525691114","NA":"1540691114","IC":"0000000000000000","SU":"'$(docker exec issuer cat /root/.sawtooth/keys/root.pub)'"}'
```
*In a real scenario *device* will know *issuer*'s public key (as every one else), but here we exploit **docker exec** to retrieve it.

Expected output:
```json
{
"link": "http://rest-api:8008/batch_statuses?id=2d3a434d275fdd2e0f4723e6f8bcfa1968ae9bb3b60d44dca982d5f05982017f2f9c6b31425187bfbad2f9b74d2bddc45b87d185f9bf79afaa91f6d100efdb45"
}
```
*Identifiers will always differ.

Access link using **curl**:
```bash
docker exec device curl <link>
```

Expected output:
```json
{
"data": [
    {
    "id": "2d3a434d275fdd2e0f4723e6f8bcfa1968ae9bb3b60d44dca982d5f05982017f2f9c6b31425187bfbad2f9b74d2bddc45b87d185f9bf79afaa91f6d100efdb45",
    "invalid_transactions": [],
    "status": "COMMITTED"
    }
],
"link": "http://rest-api:8008/batch_statuses?id=2d3a434d275fdd2e0f4723e6f8bcfa1968ae9bb3b60d44dca982d5f05982017f2f9c6b31425187bfbad2f9b74d2bddc45b87d185f9bf79afaa91f6d100efdb45"
}
```
Now *issuer* can manage the access rights for the resources in *device*. He does that by issuing more tokens.

Example of token that can be issued by *issuer*:

```python
{
    "ID": "0000000000000002",
    "DE": "coap://device",
    "AR": [{
        "AC": "GET",
        "RE": "resource",
        "DD": 0
    }, {
        "AC": "PUT",
        "RE": "resource",
        "DD": 0
    }],
    "NB": "1525691114",
    "NA": "1540691114",
    "IC": "0000000000000001",
    "SU": <public key of the subject>
}
```
Correspondong command with *subject* as the subject of the token:
```bash
docker exec issuer capbac issue '{"ID":"0000000000000002","DE":"coap://device","AR":[{"AC":"GET","RE":"resource","DD":0},{"AC":"PUT","RE":"resource","DD":0}],"NB":"1525691114","NA":"1540691114","IC":"0000000000000001","SU":"'$(docker exec subject cat /root/.sawtooth/keys/root.pub)'"}'
```

If the token is committed, *subject* will be able to perform PUT and GET requests on *resouce*.
*subject* will not be able to delegate this capabilities any further since for both the Delegation Depth (DD) is set to zero.

### Request a resource

Using the simple client from [aiocoap](https://aiocoap.readthedocs.io/en/latest/module/aiocoap.cli.client.html) one can send CoAP requests with:

```bash
aiocoap-client [-m <method>] [--payload <payload string>] <resource URI>
```
However, since our CoAP server is CapBAC-aware, it will always return UNAUTHORIZED unless a signed access token, pointing to a committed capability token with matchin access rights, is pre-fixed to the payload (if any, else it is sent as the payload itself). This results in the following sintax:

```bash
aiocoap-client [-m <method>] --payload "<access token JSON as string>[<payload string>]" <resource URI>
```
*For more datails on the access token format see [capbac_version.py](https://gitlab.com/kappanneo/sawtooth-capbac/blob/master/capbac_version.py).

Example of access token to be signed:
```json
{
    "DE": "coap://device",
    "AC": "GET",
    "RE": "time",
    "IC": "0000000000000002"
}
```
The token is signed using **capbac sign**:
```bash
capbac sign '{"DE":"coap://device","AC":"GET","RE":"resource","IC":"0000000000000002"}'
```
Outuput (prettified):
```json
{
    "AC": "GET",
    "VR": "1.0",
    "DE": "coap://device",
    "IC": "0000000000000002",
    "SI": "c229618d223e9a1a18245bb7b2c0d9953b33981ae2f245bb1efbdcb8a9d15b8b5b64447dc6c07c883b7b40c0913b3ce4a35bf1d31c6c9f1a8bb4cede60c13756",
    "RE": "resource",
    "II": "1539261923"
}
```
*Issue Istant (II) and Version (VR) are added before the Signature (SI).

So a GET request like:

```bash
aiocoap-client coap://device/resource
```

Becomes:
```bash
aiocoap-client --payload "$(capbac sign '{"DE":"coap://device","AC":"GET","RE":"resource","IC":"0000000000000002"}')" coap://device/resource
```

Using **docker exec** on *subject*:
```bash
docker exec subject aiocoap-client --payload "$(docker exec subject capbac sign '{"DE":"coap://device","AC":"GET","RE":"resource","IC":"0000000000000002"}')" coap://device/resource
```

While a PUT request like:
```bash
aiocoap-client -m PUT --payload "some string" coap://device/resource
```
Becomes:
```bash
aiocoap-client -m PUT --payload "$(capbac sign '{"DE":"coap://device","AC":"PUT","RE":"resource","IC":"0000000000000002"}')some string" coap://device/resource
```
Using **docker exec** on *subject*:
```bash
docker exec subject aiocoap-client -m PUT --payload "$(docker exec subject capbac sign '{"DE":"coap://device","AC":"PUT","RE":"resource","IC":"0000000000000002"}')some string" coap://device/resource
```
### Revoke capabilities

```bash
capbac revoke <revocation request as JSON string>
```
*For more datails on the revocation request format see [capbac_version.py](https://gitlab.com/kappanneo/sawtooth-capbac/blob/master/capbac_version.py).

Example of revocation before it is signed by **capbac revoke**:
```json
{
    "ID": "0000000000000000",
    "IC": "0000000000000000",
    "DE": "coap://device",
    "RT": "ALL"
}
```
*RT stands for "Revocation Tipe" and can be one of the following:
1. Discendant Capabilities Only (DCO)
2. Identified Capability Only (ICO)
3. Both 1. and 2. (ALL)

Corresponding command:

```bash
docker exec device capbac revoke '{"ID":"0000000000000000","IC":"0000000000000000","DE":"coap://device","RT":"ALL"}'
```
*This will remove all the capability tokens including the root one.

repository: gordengooner/Sawtooth-CapBAC

repo_name: gordengooner/Sawtooth-CapBAC


text:
# Timed LRU

[![Build Status](https://github.com/bsm/timed_lru/actions/workflows/ruby.yml/badge.svg)](https://github.com/bsm/timed_lru/actions/workflows/ruby.yml)
[![Dependency Status](https://gemnasium.com/bsm/timed_lru.png)](https://gemnasium.com/bsm/timed_lru)

My implementation of a simple, thread-safe LRU with (optional) TTLs
and constant time operations. There are many LRUs for Ruby available but
I was unable to find one that matches all three requirements.

## Install

Install it via `gem`:

```ruby
gem install timed_lru
```

Or just bundle it with your project.

## Usage Example

```ruby
# Initialize with a max size (default: 100) and a TTL (default: none)
lru = TimedLRU.new max_size: 3, ttl: 5

# Add values
lru["a"] = "value 1"
lru["b"] = "value 2"
lru["c"] = "value 3"
lru.keys # => ["a", "b"]

# Wait a second
sleep(1)

# Add more values
lru["d"] = "value 4"
lru.keys # => ["b", "c", "d"]

# Sleep a little longer
sleep(4)
lru["c"] # => "value 3"
lru.keys # => ["c", "d"]
```

gha_language: Ruby

gha_license_id: NOASSERTION


text:
[![npm version](https://badge.fury.io/js/sails-pagination-middleware.svg)](https://badge.fury.io/js/sails-pagination-middleware)
[![npm](https://img.shields.io/npm/dt/sails-pagination-middleware.svg)]()

# sails-pagination-middleware

## About

Middleware for sails.js for finding the total count by criteria, via a Django rest framework inspired transformed request.

Criteria pagination / filtering is built in to Sails, with keywords `limit`, `skip`, `where`. This package only adds a totalCount field to aid with building page indicators. You could define your page size in your frontend application with the keyword `limit` and just adjust `skip` accordingly. Meaning you could implement all sorts of different pagination indicators with this system.

Example of the transformed request to `/api/todos?skip=10&limit=10&where={"title":{"contains":"test"}}`:

    {
        "results": [{
            /* results here */
        }],
        "totalCount": 80
    }

Package follows the Sails initiative 'convention over configuration', so installing the middleware assumes, you would like to transform requests at all index endpoints. See section advanced usage for other options.

## Use case example

Check out an use case example over at [vue-sails-todo](https://github.com/xtrinch/vue-sails-todo).

## Basic Usage

    npm install --save sails-pagination-middleware

Then in your `config/http.js`, add `paginate` to first place in array:

    middleware: {
        paginate: require('sails-pagination-middleware'),
        order: [
          'paginate',
          // ...
         ]

## Sails version support
It only supports __Sails 1.x+__

## Advanced Usage

You can create a policy, say we called it `api/policies/paginate.js`

    module.exports = require('sails-pagination-middleware').generate({});

Then in `config/policies.js` you can specify which `find` call will get augmented with the count field.

    UserController: {
        'find': ['isLoggedIn', 'paginate'],
    }

## Extra Options

There are options that you can change, just call the `generate()` function

        require('sails-pagination-middleware').generate({
            // if you want to add/remove an action i.e. 'user/search' or whatever
            // the array can contain a string for exact match or a regular expression for a pattern
            // if you use this options, the array you use will override the default, it will NOT concat
            // this is the default,
            // it will match all the usual :model/find, :model/:id/:association/populate
            actions: ['find', 'populate', /^.*\/(find|populate)$/]

            // if the .count() calls fails, to throw an error or not
            silentError: false // default
        }),


text:
# Design and Analysis of Algorithms (B-2018)

## Overview

Welcome to the advanced course of algorithms at ULA! Here
you will find any aspect discussed during lectures and
practice sessions.  Let's adapt as soon as possible.

## Table of Contents

1. [Description of the course](#description-of-the-course)
2. [Recommendations to get good grades](#recomendations-to-get-good-grades)
3. [Books and Videos](#books-and-videos)
4. [Instructions](#instructions)

## Description of the course

This is the advanced course of programming at ULA. This course will allow you to develop a big variety of approaches during problem solving. You will study concepts such as dynamic programming, graph theory, applied discrete mathematics, flow networks, advanced data structures, and complexity. Those concepts are **critical knowledge** when you start your career as a professional. We will design huge projects and use vanguard programming tools. During practice sessions, we will solve competitive programming problems extracted from one of the [biggest online judges](https://www.spoj.com/) with the most active community on internet.

## Recommendations to get good grades

This is a course where you will need to be highly focused and
opened to learn new things. So here is a set of recommendations
you should follow if you want to get the best grade and the highest
quantity and quality of knowledge:

- Make all your readings BEFORE you reach to the lectures. The classes are for discussions.
Don't be lost during lectures or sessions, don't waste your time, be smart.
- **Don't waste your time, AGAIN**, it's too precious in this course, use it
wisely.
- If you've any doubt, don't hesitate: **Ask!**
- Enjoy every moment when you're in this course!

## Books and videos

It's **strongly recommended** for all of you to take this courses during the semester:

- https://www.youtube.com/playlist?list=PLUl4u3cNGP6317WaSNfmCvGym2ucw3oGp (MIT 6.046J)

- https://www.youtube.com/watch?v=_vfCXMSLMAU&list=PLNPbxFpuCy0-6GIUmiHCvj0H0hNxstOie (METU CENG773)

About books, besides of the readings recommended in those courses, you will find them here:

http://webdelprofesor.ula.ve/ingenieria/alejandromujica/sitio/ayda/

MIT is considered the **TOP UNIVERSITY IN THE WHOLE WORLD**, and the METU is
the best from the middle east, so here comes this question:

Do you want to be the best programmer with the best salary? Be the best, **take those courses**!

## Instructions

### How do I configure my repository and relate it with the Telegram Channel?

It is very simple. You will first need a GitHub or BitBucket repository. I assume you've
git installed in your OS but if it's not the case, here you have some [instructions](https://www.linode.com/docs/development/version-control/how-to-install-git-on-linux-mac-and-windows/).

Now, go to [Integromat](https://www.integromat.com/) and create and account there.
It's only one account for repository so there won't be any other troubles.

- Skip all tutorials and go directly to the dashboard.
- Then, click on *Create a new scenario*.
- Type and select Github/BitBucket **and** TelegramBot. (Both must be selected).

Let's go with GitHub/Bitbucket first:

- Click on the question mark and select GitHub/Bitbucket firstly.
- Choose then *Watch push actions*/*Watch pushes*.
- If you are using GitHub, it will ask you for a Webhook to relate your repository to Integromat. Click on *Add*, then *Save*, copy the address generated to your clipboard, and without closing your scenario, follow these steps in another tab:
    - Sign in into your GitHub account, then select the related repository you own.
    - Click on "Settings" tab.
    - Then click on "Webhooks" on the left panel.
    - Click on the "Add WebHook" Button.
    - Paste the copied URL in the Payload URL form field.
    - Select "application/json" as the content type.
    - Click on "Add webhook" to save the webhook.

- If you're using BitBucket, this step is far way simpler. Follow these [instructions](https://www.integromat.com/en/kb/pkg/bitbucket/index.html).

Now let's send that info to Telegram. Go back to your Integromat tab:

- Right click on the scenario canvas, and *Add a module*.
- Choose TelegramBot option.
- Choose **Send a text message or a reply** option.
- Click again in the big circle and add a click, go to *Connection* and click on **Add**.
- Type the name of your wish, and paste this token: **687866749:AAHpCIf5-fyF-3JRKk0ITrL5auLUrbp_q6Y**
- Inside *Chat ID* paste: **@aydab2018**
- Inside *Text* field, add **strictly** this format:

*If GitHub*

```
A PUSH HAS BEEN DONE
-----------------------------------------
Project: {{1.respository.name}}
Author: {{1.headCommit.authorName}} ({{1.pusherName}})
Date: {{1.headCommit.timestamp}}
Message: {{1.headCommit.message}}
-----------------------------------------
Added files
{{1.headCommit.added}}
-----------------------------------------
Modified files
{{1.headCommit.modified}}
-----------------------------------------
Removed files
{{1.headCommit.removed}}
-----------------------------------------
```

*If BitBucket*

```
A PUSH HAS BEEN DONE!
-------------------------------------

Project: {{repository.name}}
Author: {{actorDisplayName}} ({{actorUsername}})
Date: {{new.targetDate}}
Message: {{new.targetMessage}}
-------------------------------------
```

Where {{data}} indicates the card that **must be selected** from the side panel. Finally, click **OK**. **DO NOT COPY AND PASTE** or an error will be displayed when trying to connect. Finally, click on *OK* button.

For testing, Click on **Run Once** and it will log in the console: *The request was accepted. Waiting for data* if setting was successful. If everything's fine, when you make a push from your git folder to your repo, it will appear a Telegram notification indicating that the push was made correctly. If this wasn't the case, make sure you followed up every step indicated in this guide.

Finally, turn on the scheduling option to activate your push notifications. **Don't forget to save your Scenario** (the icon is at the bottom of the screen).

### How do I make my own bot for my team?

- Create a Telegram bot from the [BotFather](https://telegram.me/BotFather).
- Keep the token generated when the creation is successful.
- Add the recently created bot as Administrator to your Telegram group.
- Follow the steps indicated above for Telegram but using your own token and your
own *Chat ID* (here you will paste your group's unique name in the specified format).
- Here you're free to use your own commit format.

### How do I install DeSIGNAR in my computer?

Really, dude? Ugh, that's one of the **easiest things ever**. You will find info [here](https://github.com/R3mmurd/DeSiGNAR).


text:
* Linked list: has a head element, and every element has a pointer to the location in memory where the next element is. Last element has pointer to null, thus we know we're done. Doubly linked list also has the previous item so you can walk the list backward. This differs from a conventional list/array, where each element is stored sequentially. Each item is an object.
    * Advantages: Can grow and shrink dynamically at runtime, limited only by the amount of physical memory available. Deletion/insertion is very fast.
    * Disadvantages: random access is slow because you must pass through each item, unlike in a conventional array where you can find an element in O(1) time given a pointer to the starting of the array.

* Binary trees
    * Middle number placed at root/in middle of sorted list
    * Right branch always has greater number than parent node, left always is lower
        * 57, 12, 19, 68, 45

      57
     /  \
   12    68
    \    | \       Ways to represent a binary tree:
    19   62 75     "Infix Notation" - put a dot underneath each number, start circling around it, and go through the dots.
   /\                               Add whatever number you pass through. Creates an ordered list.
  17  45           "Prefix Notation" - put dot to the left/before number instead. Creates a slightly different result; not ordered.
      |            "Postfix notation" - dot on right side of number. Basically reverse Polish notation because binary trees can represent equations.
     22            IB will ask us to make a tree and then write down in one of these notations.

* Compression
    * Lossy
        * Data changes after compression and the original copy can't be restored.
        * Used for audio and pictures.
    * Lossless
        * Data can be restored exactly in its entirety.
        * Examples:
            * Keyword encoding: replacing common words in text with irregular symbols.
            * Run-length encoding: useful if you have a lot of repeating characters. Assigning a number for each character that repeats a lot, and compressing those by saying, for example, *H6 rather than HHHHHH
            * Huffman coding: using shorter binary sequences to compress text.
                * Example: string with values ABCDEF. Frequency 5 25 7 15 4 12
                * You take the two smallest and put them into a binary tree. Then, you do the same again, and put the former binary tree under the new one. Then you put 0/1 on left/right branches and traverse that binary tree to figure out what the binary code for each letter should be; they will thus never overlap.
                * There can be "fixed-length" encoding as well. For example each letter could have a 6 bit identifier. You don't use a binary tree for this, allegedly.
                * Practice doing this manually!

repository: ErikBoesen/ibhlcs

repo_name: ErikBoesen/ibhlcs


text:
---
title: Starting a blog
layout: post
excerpt_separator: <!--more-->
---

I've decided to take the advice of a number of folks and start blogging about the things I'm learning about.  The idea
being that blogging will serve as a future reference and record for things that I've learned over the years.
<!--more-->

A little about me, I'm a UI/UX developer at [Clear Capital](http://www.clearcapital.com).  I primarily code in AngularJS,
HTML, and CSS.  I moved into this position a couple months ago.  My former position was Web Application Developer.
I was doing full stack development in ColdFusion and AngularJS.

In my own time, I program in Angular, and NodeJS.  I'm currently working my way, slowly, through a Swift iOS8 course.
I took a course a year ago on MongoDB, and I've done a couple projects with it.

A few weeks ago, I participated in the [2015 Reno NASA Space Apps](http://spaceappsreno.org/) challenge and built a
[web app](https://github.com/SpaceAppsReno/solar-system) using Ionic.  That was a fun weekend and maybe I can write
more about that later.

I'm looking to learn more about TypeScript and I think I may make that my next project.

I listen to a number of podcasts on my commute.  Of the ones related to code, I'm currently enjoying
[JavaScript Jabber](http://devchat.tv/js-jabber/) and [CodeNewbie](http://www.codenewbie.org/) the most.  JavaScript
Jabber is an obvious podcast for me to listen to since I write so much JavaScript but CodeNewbie is less obvious.  I've
been programming for a number of years so I don't think I qualify as a newbie any more but they usually have fun topics
and it's interesting to hear how others got their start.

A quick word of thanks to [Joshua Lande's blog](http://joshualande.com/jekyll-github-pages-poole/) for the tutorial on
setting up [Poole](http://getpoole.com/).

## Links
* [JavaScript Jabber Ep. 156 w/ John Sonmez](http://devchat.tv/js-jabber/156-jsj-soft-skills-and-marketing-yourself-as-a-software-developer-with-john-sonmez)
* [CodeNewbie Ep. 18 w/ Scott Hanselman](http://www.codenewbie.org/podcast/getting-involved)
* [Joshua Lande's blog](http://joshualande.com/jekyll-github-pages-poole/)
* [Poole](http://getpoole.com/)
* [Markdown Syntax](http://daringfireball.net/projects/markdown/syntax)


text:
`eye` imports notebooks as Interactive Modules.  With `eye` imports:

* Notebooks can be used as python source.
* The native `importlib.reload` object reloads `eye` modules.
* `eye` provides line level debugging to the source notebook.
* `paramterize` notebooks to makes them `callable`.

```python
    import aye.activate
    import readme
```

Imported notebooks are reloadable.

```python
    from importlib import reload
    assert reload(readme) is readme
```

The [`aye/tests`](eye/tests/) explains more about the basic and advanced features of `aye`

> `aye.tests` are importable.

```python
    import aye.tests.test_basics
    assert aye.tests.test_basics.__complete__ is True
```

Partially loaded notebooks contain an `Exception` on the __complete__ attribute.

```python
    import aye.tests.debug
    assert type(aye.tests.debug.__complete__) is AssertionError
```

```python
    if __name__ == '__main__':
        !source activate p6 && python setup.py develop
        !source activate p6 && python setup.py pytest
        !jupyter nbconvert --to markdown --TemplateExporter.exclude_output=True readme.ipynb
```

repository: deathbeds/aye

gha_language: Jupyter Notebook

repo_name: deathbeds/aye


text:
# Khakis - Arcus Infrastructure

Arcus utilizes Cassandra, Kafka, and Zookeeper in order to support arcusplatform. This sub-project contains the necessary Dockerfiles and scripts to build and run the Arcus containers.
For a production deployment, it is recommended to use some form of container orchestration, e.g. Docker Compose or Kubernetes.
## Building the Arcus docker images

Running the following command on the console will build all of the docker
images required for the Arcus Platform.

```
$ ./bin/build.sh
```

Docker caches intermediate images to speed up image creation, so running this
command after making small changes will not take as long as the first run.

## Bringing up the Arcus docker container

Running the following command on the console will start a new docker container
named "eyeris" using the Arcus Docker image "eyeris/uber".

```
$ ./bin/start.sh
```

There are several environment variables that control the creation of the new
docker container. The most important ones are:

    * EYERIS_PLATFORM_NAME (default: eyeris)
    Setting this to a value other than "eyeris" will allow you to start up
    multiple Arcus uber images. These images, however, will not be clustered
    together. They will just be multiple independent stacks.

    * EYERIS_PLATFORM_CPUSHARES (default: 1)
    This value controls the number of cpu shares given to the Arcus uber
    container. The value only matters if multiple containers are running.

    * EYERIS_PLATFORM_MEMORY (default: 1g)
    This value controls the maximum amount of memory that can be allocated
    inside the container. The JVM heap sizes used inside the container are
    not currently configurable, however.

    * EYERIS_PLATFORM_DIRECT_PORTS (default: empty)
    Setting this value to anything other than the empty string will cause
    the container's ports to be mapped to the same ports on the host. This
    allows for connecting clients running directly on the host to the
    standard service ports. If this value is empty (the default) then
    docker will map the container's ports to a random host port.

## Bringing down an Arcus docker container

Running the following command on the console will stop an existing Arcus uber
container. This command also understands the EYERIS\_PLATFORM\_NAME environment
variable, allowing multiple containers to be started and stopped easily.

```
$ ./bin/stop.sh
```

## Connecting to a running Arcus docker container

Running the following command on the console will run a given executable inside
an existing Arcus uber container. This command also understands the
EYERIS\_PLATFORM\_NAME environment variable.

```
$ ./bin/connect.sh [command]
```

If a command is not given then the script will start a bash shell by default.

## Versioning

if you invoke `./bin/build.sh` to build your containers, the version will be latest, however if you utilize `./gradlew :khakis:distDocker`, the version will be set based on `version.properties`, e.g. `2019.10.0`.

The version can be adjusted by changing `version.properties`, but you should probably use the gradle `branchRelease` and `tagRelease` targets instead.

## Building Docker Containers

```
./gradlew :khakis:distDocker
```

## Pushing docker containers

./khakis/bin/tag.sh and ./khakis/bin/push.sh accept two environment variables which change the path of the image to tag or push.

REGISTRY_SEPERATOR controls the seperator between image names. e.g. eyeris/java or eyeris-java. In the case of Google Container Registry (gcr) this can be '/', but for DockerHub this will need to be '-'.

REGISTRY_NAME specifies where to push the container to, e.g. gcr.io/YOURPROJECT or your DockerHub account name.
`
First tag:
```
REGISTRY_SEPERATOR='/' REGISTRY_NAME=gcr.io/arcus-238802 ./khakis/bin/tag.sh
```
then push:
```
REGISTRY_SEPERATOR='/' REGISTRY_NAME=gcr.io/arcus-238802 ./khakis/bin/push.sh
```

repository: arcus-smart-home/arcusplatform

gha_language: Java

repo_name: arcus-smart-home/arcusplatform


text:
# effect-utils

[ ![Download](https://api.bintray.com/packages/ovotech/maven/natchez-datadog/images/download.svg) ](https://bintray.com/ovotech/maven/logging/_latestVersion)

This repository consists of a number of type classes which add behaviours to a generic `F[_]` type in your cats-effect projects.
Each type class will be deployed to bintray as an independent jar to minimise transitive dependency issues if you only
want to use some of the library.

To create a release, push a tag to master of the format `x.y.z`. See the [semantic versioning guide](https://semver.org/)
for details of how to choose a version number.

## Current modules

| Module        | Description                                                                    | Artifact
----------------|--------------------------------------------------------------------------------|-----------------------------------------
Datadog Metrics | Submits metrics to Datadog over UDP with FS2                                   | "com.ovoenergy.effect" % "datadog-metrics"
Natchez Datadog | Integrates [natchez](https://github.com/tpolecat/natchez) with the Datadog APM | "com.ovoenergy.effect" % "natchez-datadog"
Natchez Doobie  | Integrates [natchez](https://github.com/tpolecat/natchez) with Doobie          | "com.ovoenergy.effect" % "natchez-doobie"
Natchez SLF4J   | Integrates [natchez](https://github.com/tpolecat/natchez) with SLF4J           | "com.ovoenergy.effect" % "natchez-slf4j"
Natchez Combine | Provides a function to combine two Natchez `EntryPoint[F]`s together           | "com.ovoenergy.effect" % "natchez-combine"
Natchez FS2     | Provides an `AllocatedSpan` you submit manually for streams                    | "com.ovoenergy.effect" % "natchez-fs2"
Natchez Testkit | Provides a `TestEntrypoint` backed by a `Ref` for unit tests                   | "com.ovoenergy.effect" % "natchez-testkit"


text:
# memory-info

Reproduces what the kubelet does to calculate 'memory.available' relative to root cgroup.
It also calculates and shows other memory related info which helps you choose values
for kubelet configuration parameters (e.g. kubeReserved and systemReserved).

The value for 'memory.available' is derived from the cgroupfs instead of tools like free.

## Available options

```bash
-a, --clear-all-caches
    clear page cache and reclaimable slab objects (not recommended in production)

-p, --clear-page-cache
    clear page cache only

-s, --short
    less information

-v, --verbose
    more information
```

## Example usage

```bash
$ ./memory-info.sh --clear-all-caches
Clearing OS caches (page cache + reclaimable slab objects): sync; sysctl -w vm.drop_caches=3
vm.drop_caches = 3
---
memory capacity: 3876 MB
---
cgroup based memory info (used by k8s)
  available: 2990 MB
  working set: 886 MB
  usage: 1372 MB
---
cgroup: docker.service
  working set: 194 MB
  resident set size: 357 MB
  usage: 374 MB

cgroup: kubelet.service
  working set: 31 MB
  resident set size: 34 MB
  usage: 38 MB

cgroup: kubepods
  working set: 372 MB
  resident set size: 450 MB
  usage: 472 MB

cgroup: system.slice
  working set: 433 MB
  resident set size: 731 MB
  usage: 802 MB

cgroup: user.slice
  working set: 168 MB
  resident set size: 168 MB
  usage: 183 MB
---
/proc/meminfo based: free -m
              total        used        free      shared  buff/cache   available
Mem:           3876         818        2308           1         749        2954

--- calculations ---
docker.service + kubelet.service cgroups working set: 225 MB
meminfo working set: 921 MB (23.78%)
estimated system working set: 156 MB
estimated system + docker + kubelet working set: 381 MB

memory available delta [cgroup - meminfo]: 35 MB

--- limits ---
kubepods cgroup memory.limit: 2852 MB
kubelet.evictionHard.memory.available: 200Mi
computed allocatable memory for pods: 2652 MB (14.03% in use)
---
Load average: 0.33 0.22 0.26
```

repository: seriva/epiphany

branch_name: refs/heads/develop

repo_name: seriva/epiphany


text:
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.5.1] - 2021-06-10
### Changed
- fixed a small bug that arised sometimes when deleting a vertex on the convex hull

## [0.5.0] - 2021-04-15
### Added
- interplation with natural neighbour (nni, or Sibson's method) is added.
- saving of the triangulation to GeoJSON is added
### Changed
- Delete the robust arithmetic code copied from spades, and use Rust crate "robust"
- interpolation functions are more robust (if no DT exists, if estimation at known vertex)

## [0.4.9] - 2021-03-07
### Added
- Added basic C interface, so startin can be called from other languages (such as C or Julia). Build with `cargo build --features c_api`.

## [0.4.8] - 2021-02-05
### Changed
- Fix a small bug in walk, that seemed to have no real effect (except slowly down a bit)

## [0.4.7] - 2019-11-20
### Changed
- Fix the bug about predicates.rs raised by Martijn Meijers (https://github.com/Stoeoef/spade/issues/48)

## [0.4.6] - 2019-08-22
### Added
- 3 interpolation functions, based on the DT, added: nearest-neighbour, linear in TIN, Laplace.
### Changed
- fixed a bug with walking that sometimes crashed when point outside convex hull were inserted
- the OBJ writer is now about 1283X faster

## [0.4.5] - 2019-07-30
### Changed
- closest_vertex() is now returning the real natural neighbour, and not an approximation

## [0.4.4] - 2019-07-29
### Changed
- fixed a few bugs, most important is when walking when starting vertex was infinity vertex, now no crash
- `all_edges()` function to draw faster, used by startin_wasm project

## [0.4.3] - 2019-07-26
### Changed
- minor improvements to the API, alignment with CGAL SurfaceMesh functions (more or less)
- better doc

## [0.4.2] - 2019-06-12
### Changed
- predicates.c is not used anymore. The Rust port of it (https://github.com/Stoeoef/spade/blob/master/src/exactpred.rs) is used.
- dependencies for the examples are not used/listed for the library anymore.

## [0.4.1] - 2019-06-11
### Changed
- predicates.c has sys removed from include for time.h
- jump-and-walk is not the default anymore, walk starts from last one (no randomness by default thus)

## [0.4.0] - 2019-06-06
### Added
- Deletion of vertices now possible, even those on the boundary of the convex hull
- Integration tests available in the /tests/ folder

## [0.3.1] - 2019-05-06
### Changed
- more examples
- fix of readme.md and a few things for crates.io

## [0.3.0] - 2019-05-02
### Added
- first release and upload to crates.io

repository: QLwin/startin

repo_name: QLwin/startin


text:
## Running transmission tree sensitivity analysis for Mancy et al.

### To reproduce results ---

```
source("trees_se/tree_se_pipeline.R")

```

Note that this could take a few hours depending on the number of cores and memory
you have.

These steps rely on the data cleaning steps in `pre_java_pipeline.R`
having run successfully.

To just reproduce the figures in `trees_se/tree_se_pipeline.R`,
uncomment lines 26 - 27, and comment out line 22.

To run all the steps including generating the full sensitivity analysis for the
transmission tree reconstruction (warning: this will take a long! time,
maybe ~ 6 hrs w/ 3 cores) in `trees_se/tree_se_pipeline.R` set `fast` to `FALSE`.

repository: boydorr/TransmissionScale

repo_name: boydorr/TransmissionScale


text:
(singleuser)=

# The JupyterHub single-user server

When a user logs into JupyterHub, they get a 'server', which we usually call the **single-user server**, because it's a server that's meant for a single JupyterHub user.
Each JupyterHub user gets a different one (or more than one!).

A single-user server is a process running somewhere that is:

1. accessible over http[s],
2. authenticated via JupyterHub using OAuth 2.0,
3. started by a [Spawner](spawners), and
4. 'owned' by a single JupyterHub user

## The single-user server command

The Spawner's default single-user server startup command, `jupyterhub-singleuser`, launches `jupyter-server`, the same program used when you run `jupyter lab` on your laptop.
(_It can also launch the legacy `jupyter-notebook` server_).
That's why JupyterHub looks familiar to folks who are already using Jupyter at home or elsewhere.
It's the same!
`jupyterhub-singleuser` _customizes_ that program to change (approximately) one thing: **authenticate requests with JupyterHub**.

(singleuser-auth)=

## Single-user server authentication

Implementation-wise, JupyterHub single-user servers are a special-case of {ref}`services`
and as such use the same (OAuth) authentication mechanism (more on OAuth in JupyterHub at [](oauth)).
This is primarily implemented in the {class}`~.HubOAuth` class.

This code resides in `jupyterhub.singleuser` subpackage of JupyterHub.
The main task of this code is to:

1. resolve a JupyterHub token to a JupyterHub user (authenticate)
2. check permissions (`access:servers`) for the token to make sure the request should be allowed (authorize)
3. if not authorized, begin the OAuth process with a redirect to the Hub
4. after login, store OAuth tokens in a cookie only used by this single-user server
5. implement logout to clear the cookie

Most of this is implemented in the {class}`~.HubOAuth` class. `jupyterhub.singleuser` is responsible for _adapting_ the base Jupyter Server to use HubOAuth for these tasks.

### JupyterHub authentication extension

By default, `jupyter-server` uses its own cookie to authenticate.
If that cookie is not present, the server redirects you a login page and asks you to enter a password or token.

Jupyter Server 2.0 introduces two new _APIs_ for customizing authentication: the [IdentityProvider](inv:jupyter-server#jupyter_server.auth.IdentityProvider) and the [Authorizer](inv:jupyter-server#jupyter_server.auth.Authorizer).
More information can be found in the [Jupyter Server documentation](https://jupyter-server.readthedocs.io).

JupyterHub implements these APIs in `jupyterhub.singleuser.extension`.

The IdentityProvider is responsible for _authenticating_ requests.
In JupyterHub, that means extracting OAuth tokens from the request and resolving them to a JupyterHub user.

The Authorizer is a _separate_ API for _authorizing_ actions on particular resources.
Because the JupyterHub IdentityProvider only allows _authenticating_ users who already have the necessary `access:servers` permission to access the server, the default Authorizer only contains a redundant check for this same permission, and ignores the resource inputs.
However, specifying a _custom_ Authorizer allows for granular permissions, such as read-only access to subsets of a shared server.

### JupyterHub authentication via subclass

Prior to Jupyter Server 2 (i.e. Jupyter Server 1.x or the legacy `jupyter-notebook` server), JupyterHub authentication is applied via _subclass_.
Originally a subclass of `NotebookApp`,
this approach works with both `jupyter-server` and `jupyter-notebook`.
Instead of using the extension mechanisms above,
the server application is _subclassed_. This worked well in the `jupyter-notebook` days,
but doesn't fit well with Jupyter Server's extension-based architecture.

### Selecting jupyterhub-singleuser implementation

Using the JupyterHub singleuser-server extension is the default behavior of JupyterHub 4 and Jupyter Server 2, otherwise the subclass approach is taken.

You can opt-out of the extension by setting the environment variable `JUPYTERHUB_SINGLEUSER_EXTENSION=0`:

```python
c.Spawner.environment.update(
    {
        "JUPYTERHUB_SINGLEUSER_EXTENSION": "0",
    }
)
```

The subclass approach will also be taken if you've opted to use the classic notebook server with:

```
JUPYTERHUB_SINGLEUSER_APP=notebook
```

which was introduced in JupyterHub 2.

## Other customizations

`jupyterhub-singleuser` makes other small customizations to how the single-user server behaves:

1. logs activity on the single-user server, used in [idle-culling](https://github.com/jupyterhub/jupyterhub-idle-culler).
2. disables some features that don't make sense in JupyterHub (trash, retrying ports)
3. loading options such as URLs and SSL configuration from the environment
4. customize logging for consistency with JupyterHub logs

## Running a single-user server that's not `jupyterhub-singleuser`

By default, `jupyterhub-singleuser` is the same `jupyter-server` used by JupyterLab, Jupyter notebook (>= 7), etc.
But technically, all JupyterHub cares about is that it is:

1. an http server at the prescribed URL, accessible from the Hub and proxy, and
2. authenticated via [OAuth](oauth) with the Hub (it doesn't even have to do this, if you want to do your own authentication, as is done in BinderHub)

which means that you can customize JupyterHub to launch _any_ web application that meets these criteria, by following the specifications in {ref}`services`.

Most of the time, though, it's easier to use [jupyter-server-proxy](https://jupyter-server-proxy.readthedocs.io) if you want to launch additional web applications in JupyterHub.

repository: jupyterhub/jupyterhub

gha_language: Python

repo_name: jupyterhub/jupyterhub


text:
# sudoku
Sudoku Puzzle Solver

This is a work in progress to reduce a sudoku puzzle down and potentially solve
easy puzzles. I'll be fixing this up a lot soon as there are some obvious
shortcuts taken and need for more C++11 updates.

board.txt is an example input file that can be used.

Implemented on a MacBook Pro using clang++ -std=c++11.

repository: PaulMontgomery/sudoku

repo_name: PaulMontgomery/sudoku


text:
## StackStorm Expect Runner

This repository contains StackStorm runner which is based around the ``expect`` Linux tool.

[![Build Status](https://circleci.com/gh/StackStorm/stackstorm-runner-expect/tree/master.svg?style=shield)](https://circleci.com/gh/StackStorm/stackstorm-runner-expect) [![Codecov](https://codecov.io/github/StackStorm/stackstorm-runner-expect/badge.svg?branch=master&service=github)](https://codecov.io/github/StackStorm/stackstorm-runner-expect?branch=master)

## Installation

```bash
/opt/stackstorm/st2/bin/pip install "git+https://github.com/StackStorm/stackstorm-expect-runner.git#egg=stackstorm-runner-expect"

sudo st2ctl reload --register-runners
```

## Copyright, License, and Contributors Agreement

Copyright 2014-2019 StackStorm, Inc.

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

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

By contributing you agree that these contributions are your own (or approved by your employer) and you grant a full, complete, irrevocable copyright license to all users and developers of the project, present and future, pursuant to the license of the project.

repository: StackStorm/stackstorm-runner-expect

repo_name: StackStorm/stackstorm-runner-expect


text:
---
title: Conference Talks
parentcategory: ""
category: "conftalks"
order: 2
description: |
  All of the conference talks Lisa has given, with links to recordings and slides.
---

# Conference Talks

All of the talks I've given live the [lisa/conferences](https://github.com/lisa/conferences) repository. Within that repository I have links to slides and any recordings. That repository will be the authoratative source for links and details; on this blog I'll expand or give some background, where available.

## Talk: Starting Over (2016)

In late 2015 I was invited by a coworker (@ahalliop) to give a talk at a [local meetup][exploretech] she helps organize. At the time, we were creating a new server environment for [PCI compliance](https://www.pcisecuritystandards.org/pci_security/). The previous, non-PCI environment, had grown very organically over time and had proven to have a number of pain points.

## SLO Creation And You: Or, How We Learned To Stop Worrying And Love The Queue Length (2018)

This talk originated from wanting to share some lessons from my team at FreshBooks coming up with the first SLOs. It wasn't an easy process because they were put into an existing monitoring ecosystem. We were trying to get buy-in for service ownership (the idea that people who wrote the software would be responsible for it, instead of "ops team" *de facto* being responsible). While that push never panned out while I was working there, the ops team did pilot a project to come up with some SLOs for MySQL and RabbitMQ.

The talk focuses on RabbitMQ because there are some more lessons there. One of those lessons is that the customer may think your service is the best source of truth for an objective, and that might be incorrect. Talking with the customers to understand the goals and best source of data is important, as is iterating on the SLO-creation process.

To date, this talk has been given twice.

### DevOpsDays Silicon Valley (2018)

I had mentioned to Jennifer Davis, co-author of [Effective DevOps: Building a Culture of Collaboration, Affinity, and Tooling at Scale](http://shop.oreilly.com/product/0636920039846.do), my talk topic and she expressed interest. To fill a speaker slot at the last minute, she graciously invited me to present at the [two-day conference](https://devopsdays.org/events/2018-silicon-valley/welcome/).

The talk was [recorded][dod18-recording]. [Slides for the event are available][dod18-slides].

### ExploreTech (2018)

In October 2018 I was invited back to [ExploreTech][exploretech] to give the SLO talk. There is no recording, but the slightly [modified/updated slides are available][exploretech18-slides].

## LISA19

On October 21st, 2019, I gave a talk at LISA19. Slides can be found on [Speakerdeck][lisa19-slides]. Image credits can be found on my [conferences repository](https://github.com/lisa/conferences). [Video recording is available at the LISA19 website][lisa19-video].

Reference material:

* Images built reside in [Docker Hub](https://hub.docker.com/r/thedoh/lisa19)
* Sample source code, including Makefiles, demo script and "pull" binary, in [lisa/lisa19-containers](https://github.com/lisa/lisa19-containers)

## DevConf.cz (2020)

On January 26, 2020, I co-presented at DevConf.cz 2020 in Brno, Czech Republic with Naveen Malik. Our talk is titled [Implementing Microservices as Kubernetes Operators](https://devconfcz2020a.sched.com/event/YOxf/implementing-microservices-as-kubernetes-operators). Slides are available on [Speakerdeck][devconfcz2020-slides] and sample code in [GitHub.com/jewzaam/pod-operator][devconfcz2020-code].

## Open Source SRE: Sharing how we Grow SRE Practices

On August 18th, 2022 I presented a talk at DevConf.us in Boston, New York titled Open Source SRE: Sharing how we Grow SRE Practices. The talk, based on work at Red Hat, discusses the progress of SIG-SRE (a special interes group inside Red Hat for SRE topics) has spent 2022 producing material to level up SRE practices inside Red Hat. These materials are shared at Operate First's [operate-first/sre][operate-first-sre-git] repository, and will have a landing page soon.

For more information about Operate First, refer to their [webpage][operate-first-web].

The slides for this talk are [available in Github][opensource-sre-slides] in PDF form. A recording will be available soon.

[exploretech]: https://www.meetup.com/ExploreTech-Toronto/ "ExploreTech Toronto Meetup"
[dod18-slides]: https://speakerdeck.com/thedoh/slos-and-you-or-how-we-learned-to-stop-worrying-and-love-the-queue-length
[dod18-recording]: https://www.youtube.com/watch?v=MB0u2-c-2zs
[exploretech18-slides]: https://speakerdeck.com/thedoh/slo-creation-and-you-or-how-we-learned-to-stop-worrying-and-love-the-queue-length
[lisa19-slides]: https://speakerdeck.com/thedoh/multi-architecture-container-images-why-bother-and-how-to
[lisa19-video]: https://www.usenix.org/conference/lisa19/presentation/seelye
[devconfcz2020-slides]: https://speakerdeck.com/jewzaam/implementing-microservices-as-kubernetes-operators
[devconfcz2020-code]: https://github.com/jewzaam/pod-operator
[operate-first-web]: https://operate-first.cloud
[operate-first-sre-git]: https://github.com/operate-first/sre
[opensource-sre-slides]: https://github.com/lisa/thedoh.dev/blob/master/pdfs/devconf%20us%202022%20-%20Open%20Source%20SRE.pdf


text:
PROJECT OVERVIEW
----------------
This project was developed for Web Development and Design course between November and December 2015. I cooperated with one teammate<EMAIL_ADDRESS>
Basically, it is an e-commerce web app for e-devices where users can trade these items. It features chat system and secure login.

INSTALLATION
------------
1. Change the defined variables in 'php/classes/db.php' according to your MySQL Server configuration;
	DB_USERNAME and DB_PASSWORD

	Or change the username and password of your MySQL Server to 'root' for both.

2. Start the MySQL Server.

3. Execute the 'estore.sql' on MySQL.

4. Change the defined variables in 'php/classes/Mailing.php' according to your email configuration.
	Set the properties for the SMTP of your Mail Server.

	You could use GMail but it must first be activated for access from Untrusted Sources /:

	Go here 'https://myaccount.google.com/security' and activate 'Allow less secure apps'

5. Allow HTACCESS by checking 'rewrite_module' in WAMP Apache modules.

6. Place the entire 'estore' folder in the directory 'wamp/www/'

7. Browse to 'localhost/estore/' on an Internet browser.

8. You may login with predefined users<EMAIL_ADDRESS>and<EMAIL_ADDRESS>with password '12341234'


text:
# ♜ Warden

Quickly, **Warden** check periodically your files, run a specific command, and run a git command if you want and the command succeed.

![Warden](http://i.imgur.com/KFJj0K9.png)

Based on [Guardian](https://github.com/f/guardian), but better. :P

## Installation

For **Linux**, just run `sudo ./install/linux.sh`

It install this program into `/usr/bin/warden`, the config file into `/usr/share/warden/config.yml`, and an unstalling  script into `/usr/share/warden/uninstall.sh`.

## Uninstallation (but you don't need it)

* You can run the following command `sudo warden --uninstall`
* You can run `sudo /usr/share/warden/uninstall.sh`
* You can also run `sudo rm -r /usr/share/warden/ /usr/bin/warden`

*N.B.:* all commands are equivalent, but build in option command is recommanded

## Usage

## Run Warden

Simply run `warden` command, easy no?

### Options

* `$ warden -i`              : Init project file automatically
* `$ warden --init`          : Init project file automatically

* `$ warden -d 1500`         : change the delay (in ms) between two files watch (min = 250)
* `$ warden --delay=1500`    : change the delay (in ms) between two files watch (min = 250)

* `$ warden -t 10000`        : Change the time (in ms) before which a command is killed (min = 250)
* `$ warden --timeout=10000` : Change the time (in ms) before which a command is killed (min = 250)

* `$ warden -v`              : output the current version of Warden
* `$ warden --version`       : output the current version of Warden

* `$ warden -h`              : output help
* `$ warden -help`           : output help

* `$ warden --uninstall`     : uninstall this programm (you need to validate it). But ... you don't need this ;)

## Create a project file

`warden --init` or `warden --i` to create automatically a `.warden.yml` files, used by Wardan for.
The project file is **simply a YAML file**

Because I'm lazy, `.warden.yml` is automatically reload when it changed 🐨

## Write your `.warden.yml`

For your `.warden.yml` file, you have some simple parameters:
```yaml

delay: 1000 # change the delay (in ms) between to files watch (min = 250) [Facultative]
timeout: 2000 # Change the time (in ms) before which a command is killed (min = 250) [Facultative]

watch:

  - files: ./src/**/*.cr # all files in src and subdirectories
    run: shards build    # command to run when a file is changed
    git: add             # git command to play when a file is changed
    timeout: 10000       # it's timeout just for these files (useful for compilation)

  - files: ./*.cr                               # all .cr in this folder
    run: "crystal build #{file} -o #{basename}" # run for exemple 'crystal build main.cr main'
    git: none                                   # no git command

  - files: ./*.md # run no command for every ".md" in this folder, simply notify you when it changed
```

### `files` parameter
This option is the glob pattern of files.

### `git` option
This option is facultative, you have some values:
  - **none** -> no git command
  - **add** -> run `git add <your file>`
  - **push** -> run `git push`
  - **pull** -> run `git pull`
  - **commit** -> **_Comming Soon_**

### `run` option
This option is the following command to run when a file is changed.

You have some specifics variables subsitution in this command to do make it easy to use, with the delimiter `#{}`.

Exemple for the file `./src/warden/version.cr` in `warden` folder:
  - `#{file}` -> print raw path of the file: `./src/warden/version`
  - `#{path}` -> print path without filename: `./src/warden/`
  - `#{basename}` -> print the filename without path and extension: `version`
  - `#{extname}` -> print the extension of the file: `.cr`
  - `#{dirname}` -> print the current folder name: `warden`
  - `#{pwd}` -> print the current directory, it's simply bash `pwd` command
  - `#{cwd}` -> like `pwd` but for those who prefer `C/C++` style ;)

**_P.S.:_** You can propose new substitutions :)

## Your own configuration `config.yml`

You have similary configuration with `.warden.yml` like:
  - `delay` in ms
  - `timeout` in ms

`target` is the target of the project file, by default it's `.warden.yml`

The last parameter is the `precommand` parameter, it's exactly like `watch` parameter in project file, but it used in `$ warden --init` for auto configuration, please, don't fucked up your parameter ;)

```yaml
precommand:
  # crystal - sources
  - files: ./src/**/*.cr
    run: shards build
    git: add
  # etc, ...
```

## Contributing

1. Fork it ( https://github.com/diggersheep/warden/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## Contributors

- [[github.com/diggersheep]](https://github.com/diggersheep) diggersheep - creator, maintainer

repository: diggersheep/warden

repo_name: diggersheep/warden


text:
# mmo-dungeon-cube-ancient

##### Background
The first iteration of the MMO project!

This project was in development during 2010, it is a multiplayer online battle arena!

Project video: https://www.youtube.com/watch?v=Eu0bmbLOIEo (A bit messy as it was a stress test rather than a showcase video :grin:)

##### Install & Build
The project can be built using Delphi 7.
All media files are included in the git repository.
Requires Asphyre (OpenGL/DirectX wrapper)
Support for windows!

##### Features
The project features the following!

* Multiplayer over LAN with UDP
* Lobby for chat and map selection
* A single game mode (kill or be killed!)
* 3 playable classes with 5 unique abilities each!
 * __mage__ (spells with slow and stun!)
 * __thief__ (poison, stealth and backstab!)
 * __warrior__ (shield, teleport and health-based dmg!)
* Patcher for downloading updates
* Map editor for creating your own maps!
* Licensing keys (just a test feature don't use this!)

##### Showcase
Will upload images when I get time to compile this old project.

repository: codingchili/mmo-dungeon-cube-ancient

repo_name: codingchili/mmo-dungeon-cube-ancient


text:
---
layout: default
---

# 1996-04-20 - Re: why compression doesn't perfectly even out entropy

## Header Data

From<EMAIL_ADDRESS>(David Wagner)

To<EMAIL_ADDRESS>Message Hash: d0df7403143101cb00065970777ed3cd5db1217c21dbc174fb0659a39a8b0882

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1996-04-20 10:06:24 UTC

Raw Date: Sat, 20 Apr 1996 18:06:24 +0800

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(David Wagner)
Date: Sat, 20 Apr 1996 18:06:24 +0800
To<EMAIL_ADDRESS>Subject: Re: why compression doesn't perfectly even out entropy
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

In article<EMAIL_ADDRESS>Hal<EMAIL_ADDRESS>wrote:
> So I think the lesson is that there is only one way to estimate entropy,
> and that is to study your source.  I have to agree with Perry that this
> filtering concept is not the way to go.  It is a red herring that lures
> you in the direction of automatic entropy estimation, and that is really
> not safe.

Excellent point!  Very nicely put.

You've convinced me: I was looking at the problem the wrong way.
Thanks for correcting & educating me...

Appreciative of the "signal",
-- Dave Wagner

{% endraw %}
```

## Thread

+ Return to [April 1996](/archive/1996/04)

+ Return to<EMAIL_ADDRESS>(David Wagner)](/authors/daw_at_cs_berkeley_edu_david_wagner_)"
+ Return to "[Hal <hfinney@shell.portal.com>](/authors/hal_hfinney_at_shell_portal_com_)"
+ Return to "["Perry E. Metzger" <perry@piermont.com>](/authors/perry_e_metzger_perry_at_piermont_com_)"

+ 1996-04-19 (Fri, 19 Apr 1996 12:11:33 +0800) - [Re: why compression doesn't perfectly even out entropy](/archive/1996/04/5e776ddf633386ba861db9406e1e8e95a3515366fe308ba2fc3f9e5a3a92e98a) - _Hal<EMAIL_ADDRESS>  + 1996-04-19 (Fri, 19 Apr 1996 15:31:18 +0800) - [Re: why compression doesn't perfectly even out entropy](/archive/1996/04/1aba963cf368d41b23524588b0da95c109ca6d855db2ea032a6df832fa122bf9) - _"Perry E. Metzger"<EMAIL_ADDRESS>  + 1996-04-20 (Sat, 20 Apr 1996 18:06:24 +0800) - Re: why compression doesn't perfectly even out entropy -<EMAIL_ADDRESS>(David Wagner)_


text:
# ESP32_Unterputz
A PCB to allow an ESP32 in an Underputz spacing, using this small spacing underneath a wall mount means that the tolerances are extraordinarily small. Therefor use your own brain to make it work, Modules other than the ESP32-WROOM-U do not specifically work, because the pre-mounted antenna is using too much space.

![The main schematic](https://github.com/ReneSpanl/ESP32_Unterputz/blob/master/images/Plan.svg)
![Upper side of the PCB](https://github.com/ReneSpanl/ESP32_Unterputz/blob/master/images/ESP32_Unterputz_upper.png?raw=true)

![Lower side of the PCB](https://github.com/ReneSpanl/ESP32_Unterputz/blob/master/images/ESP32_Unterputz_lower.png?raw=true)


text:
# **Finding Lane Lines on the Road**

Jupyter notebook file containing a pipeline that identifies lane lines on road images and / or road videos.

---

## Pipeline Description

The pipline defined in function `lane_detection()` constructs segmented lane lines in six steps.

1. Image is converted to grayscale.

2. A Gaussian blur is applied to the grayscale image.

3. Canny Edge detection algorithm is applied to the blurred image.

4. Masking the "Canny" image to only display the relevant edges that correspond to road lines.

5. Hough Transform algorithm to find lane lines from the edges is applied to the masked image.

6. The lane lines are drawn onto the original image.

---

The function `lane_detection_store()` can be used to apply the above pipeline to a series of images stored in a folder. For each pipeline step, the processed images are stored in a folder specified by the user.

---

Aditionally the segmented lane lines can be extrapolated by calling the function `extrapolate()` to draw a solid line on each road side.

This function takes as input a masked image and returns an image with solid lane lines drawn on a black image. The following steps are applied:

- Seperating all lines from the masked image into right-hand and left-hand lines by determining the slope of each line.

  Negative slope ---> right-hand line // positive slope ---> left-hand line

- Seperating the x and y coordinates for each of the right-hand and left-hand lines.

- Fitting a line with polynominal of degree one through the points. One line through the coordinates that correspond to the right-hand lines and one line through the coordinates that correspond to the left-hand lines.

- Calculating the points for extrapolation based on the equation for a straight line:  $y=mx+b$.

- Draw the extrapolated lines on a black image with the same dimensions as the input image

## Limitations

This is a simple pipeline that does the job for basic roadline detection under ideal lightning conditions and on straight roads.

Shadows and or curvy roads will significantly impact the pipelines performance and lead to wrong results -> see last video included in the notebook. Also lane markings drawn on the road (e.g. arrows) may confuse the detector.

## Improvements

Ways to improve the lane dectector might be to measure the curvature in the images, adjust for changing lightning conditions or use a Convolutional Neural Network to train the lane detector in finding the lines.

repository: Cordcouch/lane-detection

repo_name: Cordcouch/lane-detection


text:
# Paul's Reading Notes

## Code #301

### Class 9: Refactoring and Functional Programming

**Reading Material (or Exercise) for the Assignment**
1. [Functional Programming Concepts)](https://medium.com/the-renaissance-developer/concepts-of-functional-programming-in-javascript-6bc84220d2aa)
- pure functions are deterministic meaning if given the same input, they return the same output
- reading files is not a pure function
- any randomness makes a function unpure
- pure functions do not modify global varibles
- pure functions are easier to read and test
- use immutable data; if you need a value changed... create a new variable
- a function returning the same value for the same inputs is called referential transparency
- *functions as first class entities* means that functions can be treated as *values* and used as *data*
- *higher order functions* means either the function 1) takes one or more functions as arguments AND/OR 2) returns a function as a result
- filter, map, and reduce are examples of common and extremely useful higher order functions

1. [Refactoring Javascript for Readability)](https://dev.to/healeycodes/refactoring-javascript-for-performance-and-readability-with-examples-1hec)
- refactoring code can make it shorter and easier to read
- return early from functions: instead of if=true do this code block; say if=false, jump out of this line of code.  The practice removes indentions and curly brackets.
- cache variables by replacing typical indexes (i,j,k,l) with more descriptive names
- check for web APIs before creating your own function

[Return to Table of Contents for Paul's Reading Notes](https://paul-leonard.github.io/reading-notes/ "Go back to find more notes!")

---

Thank you for visiting my page of notes.  I hope they were helpful to you.  Please also check out [my GitHub portfolio page](https://github.com/paul-leonard "Paul's GitHub Portfolio").

repository: paul-leonard/reading-notes

repo_name: paul-leonard/reading-notes


text:
# Rector Nette to Symfony

Do you need to migrate from Nette to Symfony? You can ↓

- [How we Migrated 54 357-lines Application from Nette to Symfony in 2 People under 80 Hours](https://tomasvotruba.com/blog/2019/08/26/how-we-migrated-54-357-lines-of-code-nette-to-symfony-in-2-people-under-80-hours/)

3 part series in more depth:

- [How we Migrated from Nette to Symfony in 3 Weeks - Part 1](https://tomasvotruba.com/blog/2019/02/21/how-we-migrated-from-nette-to-symfony-in-3-weeks-part-1/)
- [Why we Migrated from Nette to Symfony in 3 Weeks - Part 2 - Escaping Semantic Hell](https://tomasvotruba.com/blog/2019/03/07/why-we-migrated-from-nette-to-symfony-in-3-weeks-part-2/)
- [Why we Migrated from Nette to Symfony in 3 Weeks - Part 3 - Brain Drain Dead Packages-Lock](https://tomasvotruba.com/blog/2019/03/11/why-we-migrated-from-nette-to-symfony-in-3-weeks-part-3/)

See available [rules](/docs/rector_rules_overview.md)

## Install

This package is already part of [rector/rector](http://github.com/rectorphp/rector) package, so it works out of the box.

All you need to do is install the main package, and you're good to go:

```bash
composer require rector/rector --dev
```

## Use Sets

To add a set to your config, use `Rector\Symfony\Set\SymfonySetList` class and pick one of constants:

```php
use Rector\NetteToSymfony\Set\NetteToSymfonySetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->import(NetteToSymfonySetList::NETTE_TO_SYMFONY);
};
```

## Read a First Book About Rector

Are you curious, how Rector works internally, how to create your own rules and test them and why Rector was born? In May 2021 we've released the very first book: *Rector - The Power of Automated Refactoring*.

By [buying a book](https://leanpub.com/rector-the-power-of-automated-refactoring) you directly support maintainers who are working on Rector.

## Support

Rector is a tool that [we develop](https://getrector.org/) and share for free, so anyone can automate their refactoring. But not everyone has dozens of hours to understand complexity of abstract-syntax-tree in their own time. **That's why we provide commercial support - to save your time**.

Would you like to apply Rector on your code base but don't have time for the struggle with your project? [Hire us](https://getrector.org/contact) to get there faster.

repository: OXID-eSales/rector

repo_name: OXID-eSales/rector


text:
# For users

You should access Deepnote notebooks by following the chapter links.  To run the notebook and/or make changes, you will need to:
- Log in
- "Duplicate" the project, but clicking on the icon in the top right next to Login.

You will want to duplicate the project again whenever the staff pushes new content; you can copy over any changes from your previous duplicate.  The notebooks are versioned by the docker environment.

# For developers

Any changes to .ipynb in this repo must be "released" (manually, for now) on Deepnote.  We have a separate Deepnote project for each chapter under the Deepnote [Manipulation team](https://deepnote.com/dashboard/Manipulation/projects).  This workflow was recommended by the Deepnote team; it allows users to duplicate small pieces at a time and for developers to version each chapter with the most recent/relevant dockerfile.

This requires:
- Pushing a new dockerfile to `russtedrake/manipulation:tagname`.
  - Instructions for (manually) updating the dockerhub instance are in [setup/docker/Dockerfile](setup/docker/Dockerfile).
  - Push to tagname with the short SHA (using `git rev-parse --short HEAD`) and also to `latest`.
  - I am working on adding github integration for the docker.  See [#147](https://github.com/RussTedrake/manipulation/issues/147).
- Open the deepnote project, and
  - Update the environment dockerfile to point to the new tag.
  - Manually copy the files from `/root/manipulation` to `~/work`.
  - Make sure that the "Allow incoming connections" is enabled in the Environment settings.

The manipulation dockerfile builds on the drake dockerfile.  Ideally this would be `robotlocomotion/drake:focal`.  This is updated nightly with binaries representing the master branch.  If we need changes to drake that are not yet in the nightly binaries then we can:
- [Create experimental drake binaries](https://drake.mit.edu/jenkins.html#building-binary-packages-on-demand)
- [Create a drake dockerfile](https://github.com/RobotLocomotion/drake/tree/master/tools/install/dockerhub/focal)
- Push the experimental drake dockerfile with e.g. `docker push russtedrake/drake:tagname` .

repository: stereo-weld/manipulation

repo_name: stereo-weld/manipulation


text:
Multiple Select Box
===================

A Django admin type multiple select box.

What is This?
-------------

If you have ever used the Django admin and wondered how you could use the
multiple select box, then stop your search, here is a possible solution to
your problem.

> I'm still in the process of converting this code from a Django code base
so please be patient. This will not be a huge project, but I will need to
get back to it at some time in the future.


text:
---
title: EdgeMesh Design
status: implementable
authors:
    - "@qizha"
    - "@sids-b"
approvers:
  - "@kevin-wangzefeng"
  - "@CindyXing"
creation-date: 2019-03-20
last-updated: 2019-03-27
---

# Edge Mesh on edge

## Abstract
To support service mesh capabilities on edge to support microservice communication cross cloud and edge.
The service discovery, communication should be considered in this feature.
Developers can define services on top of the deployments deployed on the cloud or edges in a unified manner without caring about their location. The service name is the only thing they need to know to do the communication. For example, the following address can be used for a REST request:
`http://{service_name}/resources`

## Motivation
The cloud native and microservice architecture is becoming more and more popular and the edge node is becoming more and more powerful. The users want to decompose their application into multiple microservices. Some of those microservices need to be deployed in edge node to get close to the data generated by devices. By simplifying the development, the users need to use the same mechanism to do the service discovery and communication with what they are doing on cloud.

## Constraints and Assumptions
1. No DNS services available for edge.
2. The identification and authentication should be handled by microservices.
3. When service communication between edge to edge, they may work offline. With the purpose to deliver an "expected result" to the user system, the service definition should be pushed down to the edge right after the definition operation. That is to say, the istio model may not be suitable for edge, in istio model, the service definition is pulled from K8S master when the service is invoked.
4. Only support HTTP communication in the first step
5. All edge nodes are in the same subnetwork, and they have the network reachability.

## Use cases

### Register the service located on cloud
* CS0.1: User create service(type ClusterIP) in K8S API Server
* CS0.2: ServiceController get the service definition and create router rules with the edge ServiceBus as source and service clusterIP as target.
* CS0.3: Send the service definition to edge

### Register the service located on edge
* CS1: User create service(headless service without ClusterIP) in K8S API Server
* CS2, CS3: ServiceController get the service definition and update the service ClusterIP to itself. Then create router rule with the EC(Router) address as the source and edge ServiceBus as target.
* CS4: Send the service definition to edge

### Service discovery on cloud
* Application access service with the same mechanism no matter it located on cloud or edge

### Service discovery on edge
* Use iptables to redirect inbound and outbound traffic to the EdgeHub/ServiceBus. Then do service discovery in EdgeHub/ServiceBus by pick up the right POD from the service definition. The idea is similar with what istio is doing in the init_container: https://github.com/istio/istio/blob/master/tools/packaging/common/istio-iptables.sh

### Service communication from cloud to edge
* ESD1: Application on cloud visit service with clusterIP and request goes to EC(refer to step CS2, CS3)
* ESD2: Router find out the PODs in this service and pick one with some kind of load balance mechanism. Then send the request to the chosen edge with the router rule set in CS3.
* ESD3: EdgeHub/ServiceBus get the request and redirect to the POD

### Service communication between edges
* ESR1: Application send the request to ServiceBus(refer to the "Service discovery on edge")
* ESR2: ServiceBus pick one POD in this service with some kind of load balance mechanism. If the target is in the same node, just forward the request. If not, edgehub wrapper the request and send to the target.
* ESR3: EdgeHub open the wrapped package and forward to the POD

### Service communication from edge to cloud
* ESU1: Application send the request to ServiceBus(refer to the "Service discovery on edge")
* ESU2: ServiceBus pick one POD in this service with some kind of load balance mechanism. The target is on cloud, EdgeHub send the request to cloud.
* ESU3: Router send the request to the corresponding POD on cloud following the rule created in CS0.2

## Proposal Changes
### Add servicebus on Edge to handle request proxy
ServiceBus is in the same process with EdgeHub as a module

### Router
Add two endpoints definition:

| Endpoint   | Type   | Capability                                       |
|------------|--------|--------------------------------------------------|
| ClusterIP  | Target | Request Forward                                  |
| ServiceBus | Source | Request Forward, Service Discovery, Load Balance |
| ServiceBus | Target | Request Forward                                  |
| Router     | Source | Request Forward, Service Discovery, Load Balance |

* R1: ServiceController(SC) watches on k8s apiserver for Services/Endpoints.
* R2: SC get the service definition and create router rule definition and save in DB(ETCD).
* R3: Router gets the rule definition from DB and initializes the listeners/handlers for source and target.
* R4: Users/Applications create a request.
* R5: Router receives the request and forwards it to the target based on rule.

Since Router fetches rules from DB, in later versions it can be started as a different process than edge-controller. Also, it enables router to retrieve all the rules after process restarts.
### Router Low-level Design

### Providers
Providers are plugins to reach a service running on edge or on cloud. For example (ServiceBus, EventBus running in edgecore)
Providers can be classified into two types
1) Source
2) Target

In Alpha only ServiceBus, REST and EventBus providers will be supported.

Providers in router work in following way.

1) Router rule is added by SC say REST as source and ServiceBus at edge as target.
2) Router receives the rule and registers a listener in the source which is REST in this case.
3) REST provider starts listening on the path mentioned in the SourceResource of the rule.
for eg: http://${rest_endpoint}:${rest_endpoint_port}/${node_id}${path of rule.source_resource}
4) 4.1 User/App make a request to the endpoint in 3.

   4.2 REST provider forwards the request to ServiceBus provider.
5) 5.1 ServiceBus provider then creates a beehive message and sends it to CloudHub.

   5.2 CloudHub then forwards the message to edgeHub.

   5.3 EdgeHub send the message to ServiceBus module.
6) 6.1 ServiceBus at edge receives the message, makes the http request to applications running at edge.

   6.2  Receives the response back from the application.
7) 7.1 ServiceBus at Edge sends the response in beehive message back to EdgeHub.

   7.2 EdgeHub forwards the message to CloudHub.

   7.3 CloudHub sends the message back to router.

   7.4 The message is then converted to http response and sent to the user/application which made the request in step 4.1

### Source Interfaces

Each provider that wants to register as a Source should implement following interfaces.

```go
type Source interface {
	// Name Returns name of the provider
	Name() string
	// RegisterListener is used to register listener for a rule with this source type
	RegisterListener(rule model.Rule, res model.Map, handler func(interface{})) error
	// UnregisterListener is used to unregister a listener when rule is deleted
	UnregisterListener(rule model.Rule, res map[string]interface{})
	// Callback is function for sending response/ACK if required for a request
	Callback(map[string]interface{})
}
```

```go
type SourceFactory interface {
	// Type returns type of the source
	Type() string
	// GetSource returns Source implementation
	GetSource(ep *model.Endpoint) Source
}
```

### Target Interfaces

Each provider that wants to register as a Target should implement following interfaces.

```go
type Target interface {
	// Name returns name of the provider
	Name() string
	// Forward is used to forward the request to target
	Forward(map[string]interface{}, interface{}, func(map[string]interface{})) error
}
```

```go
type TargetFactory interface {
	// Type returns type of the target
	Type() string
	// GetTarget returns Target implementation
	GetTarget(ep *model.Endpoint) Target
}
```

### Rule Definition

```go
// Rule define message translate from Endpoint to Endpoint
type Rule struct {
	// ID is unique id of rule
	ID              string    `orm:"column(id); size(36); pk" json:"id" yaml:"id"`
	// Name is the name of the Rule
	Name            string    `orm:"column(name); size(64)" json:"name" yaml:"name"`
	// ProjectID can be used to differentiate rules across projects
	ProjectID       string    `orm:"column(project_id); size(36); index" json:"project_id" yaml:"project_id"`
	// DomainID is the domain from where the source is accessed
	DomainID        string    `orm:"column(domain_id); size(36); index" json:"domain_id" yaml:"domain_id"`
	// Source is the source Endpoint
	Source          *Endpoint `orm:"column(source); rel(fk)" json:"source" yaml:"source"`
	// SourceResource is a map used to store resources required for source
	SourceResource  Map       `orm:"column(source_resource); size(1024)" json:"source_resource" yaml:"source_resource"`
	// Target is target endpoint
	Target          *Endpoint `orm:"column(target); rel(fk)" json:"target" yaml:"target"`
	// TargetResource is a map used to store resources required for target
	TargetResource  Map       `orm:"column(target_resource); size(1024)" json:"target_resource" yaml:"target_resource"`
	// InUse is flag to check if rule is in use
	InUse           bool      `orm:"column(in_use); default(true)" json:"in_use" yaml:"in_use"`
	// IsDeleted is flag to check if rule is deleted
	IsDeleted       bool      `orm:"column(is_deleted); default(false)" json:"is_deleted" `
	// CreatedAt is rule creation timestamp
	CreatedAt       time.Time `orm:"column(created_at); auto_now_add; type(datetime)" json:"created_at" `
	// UpdatedAt is last rule updation timestamp
	UpdatedAt       time.Time `orm:"column(updated_at); auto_now; type(datetime)" json:"updated_at" `
	// SuccessMessages is the number of success messages for this rule
	SuccessMessages uint64    `orm:"column(success_messages); default(0)" json:"success_messages" `
	// FailMessages in the number of fail messages for this rule
	FailMessages    uint64    `orm:"column(fail_messages); default(0)" json:"fail_messages" `
	// Error is reverse maping of error messages for this rule
	Error           []*Error  `orm:"reverse(many)" json:"-"`
}
```

### Endpoint Definition

```go
// Endpoint define how to access external service
type Endpoint struct {
	// ID is the ID of the endpoint
	ID         string    `orm:"column(id); size(36); pk" json:"id" yaml:"id"`
	// Type is type of the endpoint
	Type       string    `orm:"column(type); size(64)" json:"type" yaml:"type"`
	// Name is name of the endpoint
	Name       string    `orm:"column(name); size(64)" json:"name" yaml:"name"`
	// ProjectID can be used to differentiate endpoints across projects
	ProjectID  string    `orm:"column(project_id); size(36); index; null" json:"project_id" yaml:"project_id"`
	// IsShared is flag to check if endpoint is shared
	IsShared   bool      `orm:"column(is_shared); default(false)" json:"is_shared" `
	// URI is unique resource identifier of the endpoint
	URI        string    `orm:"column(uri); size(256)" json:"uri" yaml:"uri"`
	// Properties is map used to store properties of an Endpoint
	Properties Map       `orm:"column(properties); size(10240)" json:"properties" yaml:"properties"`
	// CreatedAt is endpoint creation timestamp
	CreatedAt  time.Time `orm:"column(created_at); auto_now_add; type(datetime)" json:"created_at" `
	// UpdatedAt is last endpoint updation timestamp
	UpdatedAt  time.Time `orm:"column(updated_at); auto_now; type(datetime)" json:"updated_at" `
	// Rule is reverse mapping of Rules of this endpoint
	Rule       []*Rule   `orm:"reverse(many)" json:"-"`
}
```
### EdgeHub
* Listen to the edge communication
* Package the message and send to the target

### EdgeController
* Listen the service definition and create routing rule
* Listen the service definition to PODs deployed on edge and update the ClusterIP

repository: kubeedge/kubeedge

gha_language: Go

repo_name: kubeedge/kubeedge


text:
# React-ing with YouTube

Monkeying Around with YouTube APIs using React

###Getting Started###

There are two methods for getting started with this repo.

####Familiar with Git?#####
Checkout this repo over http, install dependencies, then start up with the following:

```
	> git clone https://github.com/mikeneder/React-ing-with-YouTube.git
	> cd React-ing-with-YouTube
	> npm install
	> npm start
```

####Not Familiar with Git?#####
Click [here](https://github.com/mikeneder/React-ing-with-YouTube/releases) then download the .zip file.  Extract the contents of the zip file, then open your terminal, change to the project directory, and:

```
	> npm install
	> npm start
```

repository: CodeMonkey-Mike/React-ing-with-YouTube

repo_name: CodeMonkey-Mike/React-ing-with-YouTube