text:
# Classifier Evaluator
#### _a classification model evaluation package_

## Abstract
This package provides an easy way to run model evaluation and comparison among multiple classification models.
The evaluation metrics include:
- TP, FN, FP, TN;
- Recall, FNR, FPR & TNR;
- Precision, FDR, FOR & NPV;
- LR+, LR-, DOR, F1;
- Prevalence, Accuracy;
- Confusion Matrix & Confusion Matrix by thresholds (Binary Classification);
- ROC, AUC;
- Trade Off Margin;
- Visualisations of multiple curves;
- Dual-Threshold;

## Installation
`$ pip install --upgrade git+https://github.com/yitistica/classifier_evaluator.git`

## Usage

#### 1. Using Standalone Metrics
Metrics can be accessed in the `metrics` module.

#### 2. Using an Evaluation Panel (Binary Classification)
'Evaluation Panel' is used to compute given metrics for comparison among models at once for a binary classification.
```python
from classifier_evaluator.eval_panel import ClassifierEvalPanel

# init:
eval_panel = ClassifierEvalPanel()

# inject data (the easy way)
eval_panel + true_series + predicted_prob_m_1 + predicted_prob_m_1 + ...

# run metrics:
eval_panel.confusion_matrix_by_prob()
```
The resulting confusion matrix table will be computed for a given set of thresholds (where threshold is defined as, [0, 1], the threshold set on predicted probabilities such that any predicted probability greater or equal to the threshold will be classified as the positive class).

|    |   threshold |   TP |   FN |   FP |   TN |   Recall |   FNR |   FPR |   TNR |   Precision |   FOR |   FDR |   NPV |   Prevalence |   Accuracy |   LR+ |   LR- |    DOR |    F1 |
|---:|------------:|-----:|-----:|-----:|-----:|---------:|------:|------:|------:|------------:|------:|------:|------:|-------------:|-----------:|------:|------:|-------:|------:|
|  0 |         0.4 |  109 |   27 |   47 |  174 |    0.801 | 0.199 | 0.213 | 0.787 |       0.699 | 0.134 | 0.301 | 0.866 |        0.381 |      0.793 | 3.769 | 0.252 | 14.946 | 0.747 |
|  1 |         0.5 |  102 |   34 |   37 |  184 |    0.75  | 0.25  | 0.167 | 0.833 |       0.734 | 0.156 | 0.266 | 0.844 |        0.381 |      0.801 | 4.48  | 0.3   | 14.919 | 0.742 |
|  2 |         0.6 |   96 |   40 |   28 |  193 |    0.706 | 0.294 | 0.127 | 0.873 |       0.774 | 0.172 | 0.226 | 0.828 |        0.381 |      0.81  | 5.571 | 0.337 | 16.543 | 0.738 |

When injecting the predicted values of a binary case into the panel, use predicted probability of the positive class instead of the predicted class.

#### 3. Plots (Examples)
```python
from classifier_evaluator import vis
```
_**confusion matrix plot**_

_**roc plot**_

_**trade off plot**_

#### 3. Dual Threshold Confusion Matrix
Dual threshold confusion matrix is also provided when we want to neglect the subset of observations with predicted probabilities bounded between the lower and the upper thresholds, i.e., only make prediction on a sample where their predicted prob
is very low (close to negative class) or very high (close to positive class), and ignore the "doubtful" predictions. This can be used when we want to deploy discriminative policies regarding
the results of our prediction. The following is an example with two set of threshold bounds:

|    |   l_threshold |   u_threshold |   TP |   FN |   FP |   TN |   Recall |   FNR |   FPR |   TNR |   Precision |   FOR |   FDR |   NPV |   Prevalence |   Accuracy |   LR+ |   LR- |    DOR |    F1 |   Open_Count |   Open_Positive |   Open_Negative |   Open_Prevalence |
|---:|--------------:|--------------:|-----:|-----:|-----:|-----:|---------:|------:|------:|------:|------------:|------:|------:|------:|-------------:|-----------:|------:|------:|-------:|------:|-------------:|----------------:|----------------:|------------------:|
|  0 |           0.4 |           0.6 |   96 |   33 |   28 |  181 |    0.744 | 0.256 | 0.134 | 0.866 |       0.774 | 0.154 | 0.226 | 0.846 |        0.382 |       0.82 | 5.555 | 0.295 | 18.805 | 0.759 |           19 |               7 |              12 |          0.368421 |
|  1 |           0.5 |           0.6 |   96 |   34 |   28 |  186 |    0.738 | 0.262 | 0.131 | 0.869 |       0.774 | 0.155 | 0.226 | 0.845 |        0.378 |       0.82 | 5.644 | 0.301 | 18.756 | 0.756 |           13 |               6 |               7 |          0.461538 |

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


text:
---
layout: default
---

# 1994-07-06 - Re: Please post your article

## Header Data

From<EMAIL_ADDRESS>(Bruce Schneier)

To<EMAIL_ADDRESS>(Harry Bartholomew)

Message Hash: d5fc83b022c773f345e20d002f2e72fc2a6b5613eaf864dfac203f78bf8652bb

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1994-07-06 21:48:31 UTC

Raw Date: Wed, 6 Jul 94 14:48:31 PDT

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(Bruce Schneier)
Date: Wed, 6 Jul 94 14:48:31 PDT
To<EMAIL_ADDRESS>(Harry Bartholomew)
Subject: Re: Please post your article
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

                                                   Bruce Schneier
                                                730 Fair Oaks Ave
                                              Oak Park, IL  60302
<PHONE_NUMBER>
                                                        750 words

       IDEA - THE INTERNATIONAL DATA ENCRYPTION ALGORITHM

For the past fifteen years, most of us have relied on the Data
Encryption Standard, or DES, for encryption.  It's a good
algorithm, and very secure against the mid-1970s technology is
was designed for.  Advances in computing power and new
discoveries in cryptanalysis have made the algorithm vulnerable.
DES is no longer secure against the world's most powerful
adversaries.  Cryptographers are looking for alternatives to
serve their needs well into the 21st century.  IDEA may be the
current best choice.

IDEA is the International Data Encryption Algorithm, and it was
invented in 1991 by James Massey and Xuejia Lai of ETH Zurich in
Switzerland.  An earlier variant of the algorithm was called PES:
Proposed Encryption Standard.  After strengthening the algorithm
against differential cryptanalysis, they changed its name to
IPES, for Improved Proposed Encryption Standard, and then to
IDEA.

The algorithm is structured along the same general lines of DES.
It is an iterated block cipher, with a 64-bit block size and a
128-bit key size.  "Iterated" means that the algorithm uses a
simple encryption function multiple times.  "Block cipher" means
that the algorithm encrypts data in blocks: 64 bits of plaintext
go in one end, and 64 bits of ciphertext come out the other.  And
the algorithm accepts a 128-bit key.

This means that IDEA can be a plug-in replacement for DES, only
with a longer key length.  IDEA can be used in all the different
modes of operation--electronic codebook, cipher block chaining,
output feedback, and cipher feedback-- specified for DES in FIPS
PUB 81 or ANSI X3.106.

The design philosophy behind IDEA is one of "mixing operations
from different algebraic groups."  The operations are XOR,
modular addition, and modular multiplication.  All operations are
based on 16-bit words, and hence are efficiently implemented in
software.  (DES has numerous bit twiddling operations, making it
very inefficient in software.)  IDEA only has eight iterations,
compared with DES's 16, but each IDEA iteration can be thought of
as a double DES iteration.  IDEA is also faster than DES when
implemented in software.

IDEA's 128-bit key length over twice that of DES; its key length
is even longer than triple-DES.  And it is much faster than
triple-DES.  A brute-force attack against IDEA would have to try
2^128, or 3*10^38, possible keys.  Michael Wiener's brute-force
DES-cracking machine, which could find a DES key in an average of
3.5 hours would require 10^18 years to break IDEA.  A machine a
million times faster would still require 10^12, or one trillion,
years to break IDEA.

Does this mean that IDEA is secure?  Is there a more efficient
way to break IDEA than brute force?  No one knows.  IDEA is a
very new algorithm.  Remember that it took cryptographers fifteen
years of studying DES to invent differential cryptanalysis,
something that the NSA knew about all along.  Who knows what
tricks the NSA knows about now that allows them to break IDEA.
Maybe they know none.  Maybe they know something that we will
discover for ourselves around the year 2006.

There are no assurances in the cryptography business.  Several
academic groups have tried to cryptanalyze IDEA with no success.
Yet.  Several military intelligence agencies have tried to
cryptanalyze IDEA; they're not talking about what they found.
IDEA is a good-looking algorithm, but it is also a new algorithm.
Ten years from now we will all consider it an amazing feat of
security or an impressive failure.  I would bet on the former,
but recognize that it is a bet.

The most widespread product that uses IDEA is PGP: Pretty Good
Privacy.  PGP uses IDEA in cipher feedback mode for data
encryption.  Several other security companies offer the algorithm
as an optional alternative to DES.  It is available both in
software and as a custom ASIC.

Details of the algorithm (with source code) can be found in:

     X. Lai, J. Massey, and S. Murphy, "Markov Ciphers and
     Differential Cryptanalysis," Advances in Cryptology--
     EUROCRYPT '91 Proceedings, Berlin: Springer-Verlag, 1991,
     pp. 17-38.

     B. Schneier, "The IDEA Encryption Algorithm." Dr. Dobbs
     Journal, Dec 93, pp. 50-56.

     B. Schneier, Applied Cryptography, New York: John Wiley &
     Sons, 1994.

IDEA is patented in the United States (J.L. Massey and X. Lai,
"Device for the Conversion of a Digital Block and the Use of
Same," U.S. Patent #5,214,703, 25 May 1993) and in Europe.  The
patents are held by Ascom-Tech AG.  There is no license fee
required for noncommercial use.  Commercial users interested in
licensing the algorithm should contact: Dr. Peter Profos, Ascom
Tech AG, Solothurn Lab, Postfach 151, 4502 Solothurn,
Switzerland; telephone +41 65 242 885; facsimile +41 65 235 761.

From owner-cypherpunks  Wed Jul  6 14:47:07 1994
Return-Path: <owner-cypherpunks>
Received: by toad.com id AA06562; Wed, 6 Jul 94 14:47:07 PDT

{% endraw %}
```

## Thread

+ Return to [July 1994](/archive/1994/07)

+ Return to<EMAIL_ADDRESS>(Bruce Schneier)](/authors/schneier_at_chinet_chinet_com_bruce_schneier_)"

+ _Unknown thread root_
  + 1994-07-06 (Wed, 6 Jul 94 14:48:31 PDT) - Re: Please post your article -<EMAIL_ADDRESS>(Bruce Schneier)_

license: MIT

branch_name: refs/heads/master

extension: md

gha_license_id: MIT

license_type: permissive


text:
---
layout: post
title:  "Draining Thread"
date:   2017-01-01
source: Dark Arts Player's Companion
tags: [cleric, sorcerer, wizard, level4, necromancy, hb, fan]
---

**4th-level necromancy (hemomancy)**

**Casting Time**: 1 action

**Range**: 60 feet

**Components**: V, S

**Duration**: Instantaneous

You open a wound on your body, shooting out a thread of blood between yourself and a creature within range. As you cast the spell, you must expend a number of hit points. The creature must then succeed on a Dexterity saving throw or take 8d6 + the number of hit points spent as necrotic damage. If this damage brings the target to 0 hit points, the hit point cost is refunded as blood drains through the thread back into your body.

**At Higher Levels.** When you cast this spell using a spell slot of 5th level or higher, the damage increases by 2d6 for each slot level above 4th.

repository: Teamdael/spellbook

extension: markdown

repo_name: Teamdael/spellbook


text:
# Telegram Cryptobot

Turn Telegram into a Buda.com interface.

## Getting Started

### Setting up your files

To get the bot working the first thing you need to do is clone the repo:

```console
git clone https://github.com/andreskemeny/telegram-cryptobot.git
```

Create a `credentials.py` file with the following structure:

```python
API_KEY = 'your buda api key'
SECRET = 'your buda secret key'

BOT_TOKEN = 'your telegram bot token'
URL = 'your heroku app url'
```
You'll get `API_KEY` and `SECRET` from your [Buda.com](https://www.buda.com/) account, `BOT_TOKEN` from Telegram and `URL` from your Heroku app.

### Uploading the bot to Heroku

With a Heroku app created, get the Heroku Git URL and push your changes there — assuming your `credentials.py` file was set up correctly, once you push to Heroku, the bot should be deployed.

## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

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

repository: andreskemeny/telegram-cryptobot

repo_name: andreskemeny/telegram-cryptobot


text:
---
# Display name
title: Christian Olsen

# Username (this should match the folder name)
authors:
- admin

# Is this the primary user of the site?
superuser: true

# Role/position
role: PhD Student

# Organizations/Affiliations
organizations:
- name: Quantum Matter Institute, University of British Columbia
  url: "https://qmi.ubc.ca"

# Short bio (displayed in user profile at end of posts)
bio:

interests:
- Quantum Transport
- Quantum Computing
- Programming
- Death/Black Metal
- Hiking
- Road Biking

education:
  courses:
  - course: MSc in Condensed Matter Physics
    institution: The Niels Bohr Institute, University of Copenhagen
    year: 2015
  - course: BSc in Physics
    institution: The Niels Bohr Institute, University of Copenhagen
    year: 2013
  - course: Electrician
    institution: J&E Electric A/S
    year: 2009

# Social/Academic Networking
# For available icons, see: https://sourcethemes.com/academic/docs/page-builder/#icons
#   For an email link, use "fas" icon pack, "envelope" icon, and a link in the
#   form<EMAIL_ADDRESS>or "#contact" for contact widget.
social:
- icon: envelope
  icon_pack: fas
  link<EMAIL_ADDRESS># For a direct email link, use<EMAIL_ADDRESS>  label: Send me an email
  display:
    footer: true

- icon: google-scholar
  icon_pack: ai
  link: https://scholar.google.ca/citations?hl=en&user=aANZ2F8AAAAJ
  label: Published articles
  display:
    header: true
    footer: true

- icon: github
  icon_pack: fab
  link: https://github.com/Chrede88
  label: My Github profile
  display:
    header: true
    footer: true

- icon: instagram
  icon_pack: fab
  link: https://www.instagram.com/christianjsolsen/

- icon: linkedin
  icon_pack: fab
  link: https://www.linkedin.com/in/christian-olsen-a3114a1b8/
  label: Connect on LinkedIn
  display:
    header: true
    footer: true

- icon: strava
  icon_pack: fab
  link: https://www.strava.com/athletes/5166204/
  label: Follow me on Strava

# To enable, copy your resume/CV to `static/files/cv.pdf` and uncomment the lines below.
- icon: cv
  icon_pack: ai
  link: files/cv.pdf
  label: Download my CV
  display:
    header: true

# Enter email to display Gravatar (if Gravatar enabled in Config)
email: ""

# Organizational groups that you belong to (for People widget)
#   Set this to `[]` or comment out if you are not using People widget.
user_groups: []
---

I'm a dane, currently living in Vancouver, British Columbia. Here I'm pursuing a PhD in experimental condensed matter physics at the University of British Columbia, working at the [Quantum Devices Group](https://www.phas.ubc.ca/~qdev/?p=home). I'm currently focusing on two topics: Topological qubits in proximitized 1D InAs nanostructures and emerging anomalous metallic phases in InAs/Al SIT samples.

I received my Masters degree in 2015 from University of Copenhagen, where I worked at the [Center for Quantum Devices](https://qdev.nbi.ku.dk). During my Masters I studied the properties of Fractional Quantum Hall quasi-particles, using QPC's.

Before entering the exciting world of academia, I trained to become an electrician. I received my certificate in 2009 and was at the same time awarded the bronze medal as well as the Massmannske medal of silver.


text:
# How to set up a Cassandra testing

## Install Docker Cassandra
[Docker Cassandra](https://hub.docker.com/_/cassandra/)

### Create docker container
Make it broadcast the ip address and exporting ports 7000 (to be visible to other cassandra nodes), also export the port 9042 for services to connect

```
$ docker run --name cassandra -d -e CASSANDRA_BROADCAST_ADDRESS=<IP_ADDRESS> -p 7000:7000 -p 9042:9042 cassandra:3.7
```

### Set cassandra instance as a service in Consul, creating a config file like
```
{
  "service": {
    "name": "cassandra",
    "tags": ["master", "v3.7"],
    "port": 9042,
    "enableTagOverride": false,
    "checks": [
      {
        "notes": "Ensure cassandra is listening on port 9042",
        "tcp": ":9042",
        "interval": "10s",
        "timeout": "1s"
    },
    {
      "notes": "Ensure cassandra is listening on port 7000 (other cassandra nodes to connect)",
      "tcp": ":7000",
      "interval": "10s",
      "timeout": "1s"
    }
    ]
  }
}
```
### Copy file into consul container and restart
```
$ docker cp ./cassandra.json consul:consul/config/
$ docker restart consul
```

### Note: before running service pluto_user_backend set the following

Connect to cassandra from cqlsh
```
$ docker exec -ti cassandra cqlsh <IP_ADDRESS>
```

```
cqlsh>
    DESCRIBE keyspaces;
    CREATE KEYSPACE pluto_user_backend WITH replication = {'class':'SimpleStrategy','replication_factor':1};
    USE pluto_user_backend;
    CREATE TABLE users (id uuid, name text, email text, password text, PRIMARY KEY (id));
    DESCRIBE tables;
```

repository: aukbit/pluto

gha_language: Go

repo_name: aukbit/pluto


text:
# Prometheus Mesos Exporter

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

Exporter for Mesos master and agent metrics.

## Using
The Mesos Exporter can either expose cluster wide metrics from a master or task
metrics from an agent.

```sh
Usage of mesos_exporter:
  -addr string
        Address to listen on (default ":9105")
  -exportedSlaveAttributes string
        Comma-separated list of slave attributes to include in the corresponding metric
  -exportedTaskLabels string
        Comma-separated list of task labels to include in the corresponding metric
  -master string
        Expose metrics from master running on this URL
  -slave string
        Expose metrics from slave running on this URL
  -timeout duration
        Master polling timeout (default 10s)
  -trustedCerts string
        Comma-separated list of certificates (.pem files) trusted for requests to
        Mesos endpoints
```
When using HTTP authentication, the following values are read from the environment:

- `MESOS_EXPORTER_USERNAME`
- `MESOS_EXPORTER_PASSWORD`

## Prometheus Configuration

Usually you would run one exporter with `-master` for each master and one
exporter for each slave with `-slave`. Monitoring each master individually
ensures that the cluster can be monitored even if the underlying Mesos cluster
is in a degraded state.

- Master: `mesos_exporter -master http://localhost:5050`
- Agent: `mesos_exporter -slave http://localhost:5051`

The necessary Prometheus configuration could look like this:

```
- job_name: mesos-master
  scrape_interval: 15s
  scrape_timeout: 10s
  static_configs:
  - targets:
    - master1.mesos.example.org:9105
    - master2.mesos.example.org:9105
    - master3.mesos.example.org:9105

- job_name: mesos-slave
  scrape_interval: 15s
  scrape_timeout: 10s
  static_configs:
  - targets:
    - node1.mesos.example.org:9105
    - node2.mesos.example.org:9105
    - node3.mesos.example.org:9105
```

A minimal set of alerts to ensure your cluster is operational could then be defined
as follows:

```
ALERT MesosDown
  IF (up{job=~"mesos.*"} == 0) or (irate(mesos_collector_errors_total[5m]) > 0)
  FOR 5m
  LABELS { severity="warning" }
  ANNOTATIONS {
    description="Either the exporter or the associated Mesos component is down.",
    summary="The Mesos instance {{$labels.instance}} cannot be scraped."
  }

ALERT MesosMasterLeader
  IF sum(mesos_master_elected{job="mesos-master"}) != 1
  FOR 5m
  LABELS { severity="page" }
  ANNOTATIONS {
    description="Agents and frameworks require a unique leading Mesos master.",
    summary="Expected one leading Mesos master but there are {{ $value }}."
  }

ALERT MesosMasterTooManyRestarts
  IF resets(mesos_master_uptime_seconds{job="mesos-master"}[1h]) > 10
  FOR 5m
  LABELS { severity="page" }
  ANNOTATIONS {
    description="The number of seconds the process has been running is resetting regularly.",
    summary="The Mesos master {{$labels.instance}} has restarted {{ $value }} times in the last hour."
  }

ALERT MesosSlaveActive
  IF sum(mesos_master_slaves_state{state="active"}) < 0.9 * count(up{job="mesos-slave"})
  FOR 5m
  LABELS { severity="page" }
  ANNOTATIONS {
    description="Mesos agents must be registered with the master in order to receive tasks.",
    summary="More than 10% of all Mesos agents dropped out. Only {{ $value }} active agents remaining."
  }

ALERT MesosSlaveTooManyRestarts
  IF resets(mesos_slave_uptime_seconds{job="mesos-slave"}[1h]) > 10
  FOR 5m
  LABELS { severity="page" }
  ANNOTATIONS {
    description="The number of seconds the process has been running is resetting regularly.",
    summary="The Mesos agent {{$labels.instance}} has restarted {{ $value }} times in the last hour."
  }
```


text:
# Schaereria tenebrosa var. tenebrosa (Flot.) Hertel & Poelt VARIETY

#### Status
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Hawksworth, James & Coppins, Lichenologist 12(1): 107 (1980)

#### Original name
Schaereria tenebrosa var. tenebrosa (Flot.) Hertel & Poelt

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
# Authorino examples

The examples provided in this page show several use cases and how to implement them as Authorino custom resources. Each example presents a feature of Authorino and is independent from the other.

For applications of Authorino into more complex combined real life-like guided examples, see Authorino [Tutorials](/docs/tutorials.md).

## Setting up the environment setup for the examples

The simplest way to try the examples in this page is by launching a local test Kubernetes environment included in the Authorino examples.

Run from the root directory of the Authorino repo:

```sh
make local-setup SKIP_LOCAL_BUILD=1
```

The above will setup the local environment, install and deploy Authorino, Envoy and the sample API to be protected called **Talker API**.

Some of the examples involve having an external identity provider (IdP), such as [Keycloak](https://www.keycloak.org) and/or [Dex](https://dexidp.io), to support authentication. To launch the local test environment including as well both these IdPs deployed to the cluster, run instead:

```sh
make local-setup SKIP_LOCAL_BUILD=1 DEPLOY_IDPS=1
```

> **NOTE:** You can replace `DEPLOY_IDPS` above with `DEPLOY_KEYCLOAK` or `DEPLOY_DEX`, in case you only want one of these auth servers deployed.

**For the examples using Keycloak** – Keycloak will reject tokens whose domain name of the issuer ("iss" claim) differs from the domain name of the request to the Keycloak server. In some examples, Authorino reaches the Keycloak server within the cluster, using the Kubernetes Keycloak service host name (i.e. "keycloak"). Therefore, you cannot get a token issued hitting Keycloak on `http://localhost:8080`, e.g., and later get this token validated through Authorino contacting Keycloak on `http://keycloak:8080`. To work around this limitation, you may need to either get tokens issued always from requests to Keycloak initiated inside the cluster, or, as assumed in the examples below, by resolving outside the cluster the same domain name assigned to the Keycloak service inside the cluster – i.e. `echo "<IP_ADDRESS> keycloak" >> /etc/hosts`.

To finish the setup, forward requests from your local host to the corresponding ports of Envoy, Keycloak, and Dex, running inside the cluster:

```sh
kubectl -n authorino port-forward deployment/envoy 8000:8000 &
kubectl -n authorino port-forward deployment/keycloak 8080:8080 & # (if using Keycloak)
kubectl -n authorino port-forward deployment/dex 5556:5556 &      # (if using Dex)
```

To cleanup, run:

```sh
make local-cleanup
```

For more information on the deployment options and resources included in the local test Kubernetes environment included in Authorino examples, see [Deploying Authorino](/docs/deploy.md).

## Table of examples

- [Simple API key authentication](#simple-api-key-authentication)
- [Alternative credentials location](#alternative-credentials-location)
- [Forbidden IP](#forbidden-ip)
- [IP range allow list](#ip-range-allow-list)
- [Short-lived API keys (the non-OIDC “beta-testers” use case)](#short-lived-api-keys-the-non-oidc-beta-testers-use-case)
- [Read-only outside](#read-only-outside)
- [Kubernetes authentication](#kubernetes-authentication)
- [Kubernetes authorization](#kubernetes-authorization)
- [Simple OAuth2 (token introspection)](#simple-oauth2-token-introspection)
- [Simple OIDC (with Keycloak)](#simple-oidc-with-keycloak)
- [OIDC UserInfo](#oidc-userinfo)
- [Multiple OIDC providers (Keycloak and Dex)](#multiple-oidc-providers-keycloak-and-dex)
- [Resource-level authorization (with UMA resource registry)](#resource-level-authorization-with-uma-resource-registry)
- [Role-Based Access Control (RBAC) (with Keycloak realm roles)](#role-based-access-control-rbac-with-keycloak-realm-roles)
- [External HTTP metadata](#external-http-metadata)
- [Festival Wristbands](#festival-wristbands)
- [Dynamic JSON response](#dynamic-json-response)
- [Envoy Dynamic Metadata](#envoy-dynamic-metadata)
- [Custom Denial Status Messages](#custom-denial-status-messages)

----
## Simple API key authentication

Simple authentication with API keys. Each API key is stored in a Kubernetes `Secret` resource that contains an `api_key` entry and labels matching the ones specified in the identity config.

Config:

```yaml
identity:
  - apiKey:
      labelSelectors: # used to select the matching `Secret`s; resources including these labels will be acepted as valid API keys to authenticate to this service
        group: friends # user-defined
    […]
```

Secrets must contain:

```yaml
metadata:
  labels: # must include the `AuthConfig`'s `spec.identity.apiKey.labelSelectors`
    authorino.3scale.net/managed-by: authorino # required, so the Authorino controller reconciles events related to this secret
    group: friends
stringData:
  api_key: <random-generated-api-key>
```

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/simple-api-key.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/friend-1-api-key-1 created
```

### Try it out:

```sh
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' http://localhost:8000/hello # 200
curl -H 'Host: talker-api' -H 'Authorization: APIKEY nonono' http://localhost:8000/hello # 401
```

----
## Alternative credentials location

By default, Authorino expects credentials passed in the HTTP `Authorization` request header, with value following the default "Bearer" prefix. The example shows how to set up different locations for the credentials.

Config:

```yaml
identity:
  - credentials:
      in: authorization_header
      keySelector: Bearer
    […]
  - credentials:
      in: authorization_header
      keySelector: CustomPrefix # user-defined
    […]
  - credentials:
      in: custom_header
      keySelector: X-API-Key # user-defined
    […]
  - credentials:
      in: query
      keySelector: api_key # user-defined
    […]
  - credentials:
      in: cookie
      keySelector: API-KEY # user-defined
    […]
```

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/alternative-credentials-location.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/friend-1-api-key-1 created
```

### Try it out:

```sh
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' http://localhost:8000/hello # 200
curl -H 'Host: talker-api' 'http://localhost:8000/hello?api_key=ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' # 200
curl -H 'Host: talker-api' -H 'Authorization: Foo ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' 'http://localhost:8000/hello' # 403
```

----
## Forbidden IP

Uses Authorino's JSON pattern matching authorization for block requestes from a given client IP.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/forbidden-ip.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/friend-1-api-key-1 created
```

### Try it out:

```sh
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' http://localhost:8000/hello # 200
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' -H 'X-Forwarded-For: <IP_ADDRESS>' http://localhost:8000/hello # 403
```

----
## IP range allow list

Similar to the [Forbidden IP example](#forbidden-ip), to show how Authorino's JSON pattern matching authorization can be used to allow requests from a range of IPs only.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/ip-range-allow-list.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/friend-1-api-key-1 created
```

### Try it out:

```sh
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' -H 'X-Forwarded-For: <IP_ADDRESS>' http://localhost:8000/hello # 200
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' http://localhost:8000/hello # 403
```

----
## Short-lived API keys (the non-OIDC “beta-testers” use case)

Based on Authorino OPA implementation. The examples uses the `creationTimestamp` of the secrets (API keys) in a Rego policy to limit the time-span of API keys to 5 days only.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/short-lived-api-keys.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/friend-1-api-key-1 created
# secret/beta-tester-1-api-key-1 created
```

### Try it out:

```sh
# User of unlimited group "friends" (API key will never expire)
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' http://localhost:8000/hello # 200

# User of limited group "beta-testers" (API key expires after 5 days)
curl -H 'Host: talker-api' -H 'Authorization: APIKEY 76yh702XoA9GLzFHCuF42fq7lHJz5Etc' http://localhost:8000/hello # 200 (up to 5th day) / 403 (after 5th day)
```

----
## Read-only outside

It authorizes only GET requests whenever the source IP is not the one of a local secure network; full-access otherwise (inside the secure network).

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/read-only-outside.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/friend-1-api-key-1 created
```

### Try it out:

```sh
# safe origin
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' -H 'X-Forwarded-For: <IP_ADDRESS>' http://localhost:8000/hello # 200
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' -H 'X-Forwarded-For: <IP_ADDRESS>' -X POST http://localhost:8000/hello # 200

# unsafe origin
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' -H 'X-Forwarded-For: <IP_ADDRESS>' http://localhost:8000/hello # 200
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' -H 'X-Forwarded-For: <IP_ADDRESS>' -X POST http://localhost:8000/hello # 403
```

----
## Kubernetes authentication

It demonstrates Authorino authentication based on Kubernetes [TokenReview](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.20/#tokenreview-v1-authentication-k8s-io) API.

Config:

```yaml
identity:
  - kubernetes:
      audiences: # user-defined; it must match the audiences inside the valid Kubernetes token; defaults to hostname of the requested service
        - talker-api
    […]
```

### Deploy the example:

```sh
sed -e "s/\${AUTHORINO_NAMESPACE}/authorino/g" ./examples/kubernetes-auth.yaml | kubectl -n authorino apply -f -
# service.authorino.3scale.net/talker-api-protection created
# serviceaccount/sa-token-issuer created
# clusterrolebinding.rbac.authorization.k8s.io/sa-token-issuer created
# serviceaccount/api-consumer created
```

### Try it out:

Get a valid Kubernetes token:

```sh
CURRENT_K8S_CONTEXT=$(kubectl config view -o json | jq -r '."current-context"')
CURRENT_K8S_CLUSTER=$(kubectl config view -o json | jq -r --arg K8S_CONTEXT "${CURRENT_K8S_CONTEXT}"  '.contexts[] | select(.name == $K8S_CONTEXT) | .context.cluster')
export KUBERNETES_API=$(kubectl config view -o json | jq -r --arg K8S_CLUSTER "${CURRENT_K8S_CLUSTER}" '.clusters[] | select(.name == $K8S_CLUSTER) | .cluster.server')
export TOKEN_ISSUER_TOKEN=$(kubectl -n authorino get secret/$(kubectl -n authorino get sa/sa-token-issuer -o json | jq -r '.secrets[0].name') -o json | jq -r '.data.token' | base64 -d)
export API_CONSUMER_TOKEN=$(curl -k -X "POST" "$KUBERNETES_API/api/v1/namespaces/authorino/serviceaccounts/api-consumer/token" \
     -H "Authorization: Bearer $TOKEN_ISSUER_TOKEN" \
     -H 'Content-Type: application/json; charset=utf-8' \
     -d $'{ "apiVersion": "authentication.k8s.io/v1", "kind": "TokenRequest", "spec": { "audiences": ["talker-api"], "expirationSeconds": 600 } }' | jq -r '.status.token')
```

Send requests to the API:

```sh
curl -H 'Host: talker-api' -H "Authorization: Bearer $API_CONSUMER_TOKEN" http://localhost:8000/hello # 200
```

----
## Kubernetes authorization

It demonstrates Authorino authorization based on Kubernetes [SubjectAccessReview](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#subjectaccessreview-v1-authorization-k8s-io) API.

Config:

```yaml
identity:
  - name: service-accounts
    kubernetes: # You can combine Kubernetes authorization with identity sources other than just Kubernetes authentication too
      audiences: ["talker-api"]

authorization:
  - name: kubernetes-rbac
    kubernetes:
      conditions: # Optional. Allows to establish conditions for the policy to be enforced or skipped
        - selector: auth.identity.iss
          operator: eq
          value: https://kubernetes.default.svc.cluster.local
      user:
        valueFrom: # It can be a fixed value as well, by using `value` instead
          authJSON: auth.identity.metadata.annotations.userid
      resourceAttributes: # Omit it to perform a non-resource `SubjectAccessReview` based on the request's path and method (verb) instead
        namespace: # other supported resource attributes are: group, resource, name, subresource and verb
          valueFrom:
            authJSON: context.request.http.path.@extract:{"sep":"/","pos":2}
    […]
```

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/kubernetes-authz.yaml
# authconfig.authorino.3scale.net/talker-api-protection created
# serviceaccount/api-consumer-1 created
# serviceaccount/api-consumer-2 created
# secret/api-key-1 created
# secret/api-key-2 created
# role.rbac.authorization.k8s.io/talker-api-cm-reader created
# rolebinding.rbac.authorization.k8s.io/talker-api-cm-reader-rolebinding created
# clusterrole.rbac.authorization.k8s.io/talker-api-greeter created
# clusterrole.rbac.authorization.k8s.io/talker-api-speaker created
# clusterrolebinding.rbac.authorization.k8s.io/talker-api-greeter-rolebinding created
# clusterrolebinding.rbac.authorization.k8s.io/talker-api-speaker-rolebinding created
```

### Try it out:

Get the Kubernetes API base endpoint and Kubernetes user that is currently logged in the CLI:

```sh
CURRENT_K8S_CONTEXT=$(kubectl config view -o json | jq -r '."current-context"')
CURRENT_K8S_USER=$(kubectl config view -o json | jq -r --arg K8S_CONTEXT "${CURRENT_K8S_CONTEXT}"  '.contexts[] | select(.name == $K8S_CONTEXT) | .context.user')
CURRENT_K8S_CLUSTER=$(kubectl config view -o json | jq -r --arg K8S_CONTEXT "${CURRENT_K8S_CONTEXT}"  '.contexts[] | select(.name == $K8S_CONTEXT) | .context.cluster')
KUBERNETES_API=$(kubectl config view -o json | jq -r --arg K8S_CLUSTER "${CURRENT_K8S_CLUSTER}" '.clusters[] | select(.name == $K8S_CLUSTER) | .cluster.server')
```

Save the Kubernetes user's TLS certificate and TLS key to authenticate to the Kubernetes API (requires [yq](https://github.com/mikefarah/yq)):

```sh
yq r ~/.kube/config "users(name==$CURRENT_K8S_USER).user.client-certificate-data" | base64 -d > /tmp/kind-cluster-user-cert.pem
yq r ~/.kube/config "users(name==$CURRENT_K8S_USER).user.client-key-data" | base64 -d > /tmp/kind-cluster-user-cert.key
```

Use the CLI user's TLS certificate to obtain a short-lived for the `api-consumer-1` `ServiceAccount` and consume the protected API as `api-consumer-1`, which is bound to the `talker-api-cm-reader` role:

```sh
export API_CONSUMER_TOKEN=$(curl -k -X "POST" "$KUBERNETES_API/api/v1/namespaces/authorino/serviceaccounts/api-consumer-1/token" \
     --cert /tmp/kind-cluster-user-cert.pem --key /tmp/kind-cluster-user-cert.key \
     -H 'Content-Type: application/json; charset=utf-8' \
     -d $'{ "apiVersion": "authentication.k8s.io/v1", "kind": "TokenRequest", "spec": { "audiences": ["talker-api"], "expirationSeconds": 600 } }' | jq -r '.status.token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $API_CONSUMER_TOKEN" "http://localhost:8000/v2/authorino/configmaps" # 200
```

Use the CLI user's TLS certificate to obtain a short-lived for the `api-consumer-2` `ServiceAccount` and consume the protected API as `api-consumer-2`, which is NOT bound to the `talker-api-cm-reader` role:

```sh
export API_CONSUMER_TOKEN=$(curl -k -X "POST" "$KUBERNETES_API/api/v1/namespaces/authorino/serviceaccounts/api-consumer-2/token" \
     --cert /tmp/kind-cluster-user-cert.pem --key /tmp/kind-cluster-user-cert.key \
     -H 'Content-Type: application/json; charset=utf-8' \
     -d $'{ "apiVersion": "authentication.k8s.io/v1", "kind": "TokenRequest", "spec": { "audiences": ["talker-api"], "expirationSeconds": 600 } }' | jq -r '.status.token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $API_CONSUMER_TOKEN" "http://localhost:8000/v2/authorino/configmaps" # 403
```

To try Kubernetes authorization for API keys as well, edit `examples/kubernetes-authz.yaml` and comment the `spec.authorization.kubernetes.condition` option. Re-apply the `AuthConfig`:

```sh
kubectl -n authorino apply -f ./examples/kubernetes-authz.yaml
```

Send another `GET` request now authenticating with John's API key, which is bound to `talker-api-cm-reader` role:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx" "http://localhost:8000/v2/authorino/configmaps" # 200
```

Send a `GET` request with Jane's API key, which is NOT bound to `talker-api-cm-reader` role:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY Vb8Ymt1Y2hWvaKcAcElau81ia2CsAYUn" "http://localhost:8000/v2/authorino/configmaps" # 403
```

To try non-resource `SubjectAccessReview`, edit again `examples/kubernetes-authz.yaml` and comment the `spec.authorization.kubernetes.resourceAttributes` option. Re-apply the `AuthConfig`:

```sh
kubectl -n authorino apply -f ./examples/kubernetes-authz.yaml
```

User _John_ can greet:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx" http://localhost:8000/hello # 200
```

So does _Jane_:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY Vb8Ymt1Y2hWvaKcAcElau81ia2CsAYUn" http://localhost:8000/hello # 200
```

_John_ can use the `/say/*` endpoint of the API:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx" http://localhost:8000/say/blah # 200
```

Whereas _Jane_ cannot:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY Vb8Ymt1Y2hWvaKcAcElau81ia2CsAYUn" http://localhost:8000/say/blah # 403
```

----

## Simple OAuth2 (token introspection)

Introspection of supplied OAuth2 access tokens with Keycloak.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/simple-oauth2.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/oauth2-token-introspection-credentials created
```

### Try it out:

```sh
export $(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=john' -d 'password=p' "http://keycloak:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '"ACCESS_TOKEN="+.access_token,"REFRESH_TOKEN="+.refresh_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:8000/hello # 200
```

Revoke access:

```sh
curl -H "Content-Type: application/x-www-form-urlencoded" -d "refresh_token=$REFRESH_TOKEN" -d 'token_type_hint=requesting_party_token' -u demo: "http://keycloak:8080/auth/realms/kuadrant/protocol/openid-connect/logout"
```

Send another request:

```sh
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:8000/hello # 403
```

----
## Simple OIDC (with Keycloak)

The example connects Authorino to a Keycloak realm as source of identities via OIDC. It also sets authorization to allow requests only from users with email verified.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/simple-oidc.yaml
# service.authorino.3scale.net/talker-api-protection created
```

### Try it out:

Try it out with John

```sh
export ACCESS_TOKEN_JOHN=$(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=john' -d 'password=p' "http://localhost:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '.access_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" http://localhost:8000/hello # 200
```

Try it out with Peter (email NOT verified)

```sh
export ACCESS_TOKEN_PETER=$(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=peter' -d 'password=p' "http://localhost:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '.access_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_PETER" http://localhost:8000/hello # 403
```

----
## OIDC UserInfo

It leverages OIDC UserInfo requests during Authorino metadata phase to validate access tokens beyond timestamps and signature verification. Authorino sends a request to the OIDC issuer's UserInfo endpoint, thus live-checking for previous token revocation.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/oidc-active-tokens-only.yaml
# service.authorino.3scale.net/talker-api-protection created
```

### Try it out:

```sh
export $(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=john' -d 'password=p' "http://keycloak:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '"ACCESS_TOKEN="+.access_token,"REFRESH_TOKEN="+.refresh_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:8000/hello # 200
```

Revoke access:

```sh
curl -H "Content-Type: application/x-www-form-urlencoded" -d "refresh_token=$REFRESH_TOKEN" -d 'token_type_hint=requesting_party_token' -u demo: "http://keycloak:8080/auth/realms/kuadrant/protocol/openid-connect/logout"
```

Send another request:

```sh
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:8000/hello # 403
```

----
## Multiple OIDC providers (Keycloak and Dex)

The example sets two sources of identity to verify OIDC tokens (JWTs) – i.e., the Keycloak server and the Dex server, both running inside the cluster. If any of these providers accepts the token, Authorino succeeds in the identity verification phase.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/oidc-multiple-sources.yaml
# service.authorino.3scale.net/talker-api-protection created
```

### Try it out:

Keycloak user:

```sh
export ACCESS_TOKEN_JOHN=$(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=john' -d 'password=p' "http://keycloak:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '.access_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" http://localhost:8000/hello # 200
```

Dex user:

- On a web browser, open http://localhost:5556/auth?scope=openid%20profile%20email&response_type=code&client_id=demo&redirect_uri=http://localhost:3000/callback
- Login with username "marta@localhost" and password "password"
- Copy the authorization code in the URL of the page opened after the scope grant (the page will fail to load but you can still get the authorization code in the address bar)
- Paste the authorization code in the command below (placeholder `<authorization-code>`) to obtain the access token

```sh
export ACCESS_TOKEN_MARTA=$(curl -k -d 'grant_type=authorization_code' -d "code=<authorization-code>" -d 'client_id=demo' -d 'client_secret=aaf88e0e-d41d-4325-a068-57c4b0d61d8e' -d 'redirect_uri=http://localhost:3000/callback' "http://localhost:5556/token" | jq -r '.id_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_MARTA" http://localhost:8000/hello # 200
```

Invalid token (neither Keycloak, nor Dex will accept it):

```sh
curl -H 'Host: talker-api' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' http://localhost:8000/hello # 403
```

----
## Resource-level authorization (with UMA resource registry)

The example uses Keycloak User-Managed Access (UMA) implementation hosting resource data, that is later fetched by Authorino on every request, in metadata phase. See [Authorino architecture > User-Managed Access (UMA)](/docs/architecture.md#user-managed-access-uma) for more information.

The Keycloak server also provides identities for OIDC authentication. The identity subject ("sub" claim) must match the owner of the requested resource, identitfied by the URI of the request.

According to the policy, everyone can send either GET or POST requests to `/greetings` and only the resource owners can send GET, PUT and DELETE requests to `/greetings/{resource-id}`.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/resource-level-authz.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/talker-api-uma-credentials created
```

### Try it out:

Try out with John (owner of `/greetings/1`):

```sh
export ACCESS_TOKEN_JOHN=$(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=john' -d 'password=p' "http://localhost:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '.access_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" http://localhost:8000/greetings # 200
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" http://localhost:8000/greetings/1 # 200
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" -X DELETE http://localhost:8000/greetings/1 # 200
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" http://localhost:8000/greetings/2 # 403
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" http://localhost:8000/goodbye # 403
```

Try out with Jane (owner of `/greetings/2`):

```sh
export ACCESS_TOKEN_JANE=$(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=jane' -d 'password=p' "http://localhost:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '.access_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JANE" http://localhost:8000/greetings # 200
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JANE" http://localhost:8000/greetings/1 # 403
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JANE" -X DELETE http://localhost:8000/greetings/1 # 403
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JANE" http://localhost:8000/greetings/2 # 200
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JANE" http://localhost:8000/goodbye # 403
```

Try out with Peter:

```sh
export ACCESS_TOKEN_PETER=$(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=peter' -d 'password=p' "http://localhost:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '.access_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_PETER" http://localhost:8000/greetings # 200
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_PETER" http://localhost:8000/greetings/1 # 403
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_PETER" -X DELETE http://localhost:8000/greetings/1 # 403
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_PETER" http://localhost:8000/greetings/2 # 403
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_PETER" http://localhost:8000/goodbye # 403
```

----
## Role-Based Access Control (RBAC) (with Keycloak realm roles)

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/keycloak-rbac.yaml
# service.authorino.3scale.net/talker-api-protection created
```

### Try it out:

Try out with John (member user):

```sh
export ACCESS_TOKEN_JOHN=$(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=john' -d 'password=p' "http://localhost:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '.access_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" http://localhost:8000/greetings # 200
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JOHN" http://localhost:8000/goodbye # 403
```

Try out with Jane (admin user):

```sh
export ACCESS_TOKEN_JANE=$(curl -d 'grant_type=password' -d 'client_id=demo' -d 'username=jane' -d 'password=p' "http://localhost:8080/auth/realms/kuadrant/protocol/openid-connect/token" | jq -r '.access_token')

curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JANE" http://localhost:8000/greetings # 200
curl -H 'Host: talker-api' -H "Authorization: Bearer $ACCESS_TOKEN_JANE" http://localhost:8000/goodbye # 200
```

----
## External HTTP metadata

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/ext-http-metadata.yaml
# service.authorino.3scale.net/talker-api-protection configured
# secret/echo-metadata-shared-auth configured
# secret/friend-1-api-key-1 configured
```
### Try it out:

```sh
# safe origin
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' http://localhost:8000/hello # 200
```

----
## Festival Wristbands

Festival Wristbands are OpenID Connect JSON Web Tokens (JWTs) issued and signed by Authorino at the end of the auth pipeline, and passed back to the client, usually in an added HTTP header. It is an opt-in feature that can be used to implement Edge Authentication Architecture (EAA) and enable token normalization.

In this example, we set an API protection that issues a wristband after a successful authentication via API key. Two sets of API keys are accepted to authenticate: API keys defined as Kubernetes `Secret`s containing the metadata labels `authorino.3scale.net/managed-by=authorino` and `authorino.3scale.net/group=users`, and API keys defined as Kubernetes `Secret`s containing the metadata labels `authorino.3scale.net/managed-by=authorino` and `authorino.3scale.net/group=admins`. Each set of API keys represents a distinct group of users of the API.

The issued wristbands include the standard JWT claims `iss`, `iat`, `exp` and `sub`, plus 3 user-defined custom claims: a static custom claim `aud=internal`, a dynamic custom claim `born` whose value (fetched from the authorization JSON) corresponds to the date/time of creation of the Kubernetes `Secret` that represents the API key used to authenticate, and another dynamic custom claim `roles` with value statically set as an extended property of each API key identity source (see the `extendedProperties` option of the Authorino `AuthConfig` CRD).

As enforced by policy defined in the example, users must first send a request to `/auth` to obtain a wristband ("edge authentication"). The wristband will be echoed back to the user by the example upstream API in an added HTTP header `x-ext-auth-wristband`, base64-encoded. `/auth` is the only path that will accept requests authenticated via API key. Then, consecutive requests to other paths of the example API shall be sent authenticating with the obtained wristband.

To authenticate via API key, use the HTTP header in the format `Authorization APIKEY <api-key-value>`. To authenticate via wristband, use `Authorization: Wristband <wristband-token>`.

Requests to `/bye` path are reserved for users with the role `admin`.

The wristband tokens are set to expire after 300 seconds. After that, users need to request another wristband by authenticating again to `/auth` via API key.

Accepting the same wristbands as valid authentication method to consume the API is optional, used in this example to demonstrate the use case for token normalization and edge authentication. Authentication based on wristband tokens relies on Authorino's OIDC identity verification feature. In this example, the issued wristbands are signed using an elliptic curve private key stored in a Kubernetes `Secret`, whose public key set can be obtained from the OpenID Discovery endpoints (see details below).

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/wristband.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/edge-api-key-1 created
# secret/edge-api-key-2 created
# secret/my-signing-key created
# secret/my-old-signing-key created
```

### Try it out:

Obtain a wristband by successfully authenticating via API key:

```sh
export WRISTBAND=$(curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' http://localhost:8000/auth | jq -r '.headers["X-Ext-Auth-Wristband"]')
```

The payload of the wristband (decoded) shall look like the following:

```jsonc
{
  "aud": "internal", # custom claim (static value)
  "born": "2021-05-13T15:42:41Z", # custom claim (dynamic value)
  "exp":<PHONE_NUMBER>,
  "iat":<PHONE_NUMBER>,
  "iss": "https://authorino-oidc.authorino.svc:8083/authorino/talker-api-protection",
  "roles": ["user"],
  "sub": "84d3f3a06f5569e06a050516363f0a65c1789d3433bb4fed5d48801997d5c30e" # SHA256 of the resolved identity in the initial request (based on API key auth)
}
```

Send requests to the same API now authenticating with the wristband:

```sh
curl -H 'Host: talker-api' -H "Authorization: Wristband $WRISTBAND" http://localhost:8000/hello -v # 200
```

Send another request to an endpoint reserved for users with `admin` role:

```sh
curl -H 'Host: talker-api' -H "Authorization: Wristband $WRISTBAND" http://localhost:8000/bye -v # 403
```

You can repeat the steps above using the admin API key `Vb8Ymt1Y2hWvaKcAcElau81ia2CsAYUn` to see the difference.

To discover the OpenID Connect configuration and JSON Web Key Set (JWKS) to verify and validate wristbands issued on requests to this protected API:

```
kubectl -n authorino port-forward service/authorino-oidc 8083:8083
```

OpenID Connect configuration well-known endpoint:

http://localhost:8083/authorino/talker-api-protection/wristband/.well-known/openid-configuration

JSON Web Key Set (JWKS) well-known endpoint:

http://localhost:8083/authorino/talker-api-protection/wristband/.well-known/openid-connect/certs

----
## Dynamic JSON response

This example defines a JSON object response to be generated by Authorino after the authorization phase, and supplied back to the user in an added HTTP header `x-ext-auth-data`. The JSON includes 2 properties: a static value `authorized=true` and a dynamic value `request-time`, fetched in the authorization JSON from Envoy-supplied contextual data, with the JSON pattern `context.request.time.seconds`.

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/dynamic-response.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/edge-api-key-1 created
# secret/edge-api-key-2 created
# secret/wristband-signing-key created
```

### Try it out:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx" http://localhost:8000/hello -v # 200
```

Notice that the response returned by the API includes the HTTP header added by Authorino and Envoy:

```jsonc
{
  "method": "GET",
  "path": "/hello",
  "query_string": null,
  "body": "",
  "headers": {
    …
    "X-Ext-Auth-Data": "{\"authorized\":\"true\",\"geeting-message\":\"Hello, John Doe!\",\"request-time\":\"1628097734\"}",
  },
  …
}
```

----
## Envoy Dynamic Metadata

Authorino can wrap dynamic JSON responses as Envoy [Well Known Dynamic Metadata](https://www.envoyproxy.io/docs/envoy/latest/configuration/advanced/well_known_dynamic_metadata).

This example defines a simple JSON object response that wraps a dynamic value fetched from the resolved user identity object, e.g. `{"ext_auth_data": {"username": "consumer-1"}}`. The JSON object is emitted back to Envoy as Dynamic Metadata and piped to a rate limit filter based on [Limitador](https://github.com/3scale-labs/limitador). Limitador then enforces, for each user, a limit of 5 requests per minute.

### Deploy the Limitador app:

```sh
make limitador
# deployment.apps/limitador created
# service/limitador created
# configmap/limitador created
```

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/dynamic-response.yaml
# service.authorino.3scale.net/talker-api-protection created
# secret/edge-api-key-1 created
# secret/edge-api-key-2 created
# secret/wristband-signing-key created
```

### Try it out:

Send request up to 5 requests per minute with user `consumer-1`:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx" http://localhost:8000/hello -v # 200
```

After the 5th request with user `consumer-1` within a 60-second time span, any consecutive request fails, rejected by the rate limiter:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx" http://localhost:8000/hello -v # 429 Too Many Requests
```

Though requests with user `consumer-2` should still work:

```sh
curl -H 'Host: talker-api' -H "Authorization: APIKEY orVKflEHd5Udtu8iFzmvQQTqN7Em7tRu" http://localhost:8000/hello -v # 200
```

----
## Custom Denial Status Messages

### Deploy the example:

```sh
kubectl -n authorino apply -f ./examples/deny-with.yaml
# authconfig.authorino.3scale.net/talker-api-protection created
# secret/friend-1-api-key-1 created
```

### Try it out:

Send a request missing the API key to authenticate:

```sh
curl -H 'Host: talker-api' http://localhost:8000/hello -i
# HTTP/1.1 302 Found
# location: http://echo-api.3scale.net/login?redirect_to=https://talker-api/hello
# x-ext-auth-reason: Login required
# date: Tue, 05 Oct 2021 22:45:45 GMT
# server: envoy
# content-length: 0
```

Without the customization, the response status code would be `401 Unauthorized`, the `x-ext-auth-reason` header _"credential not found"_, and the `WWW-Authenticate` challenge headers would be present. Instead, status `302 Found` and the `Location` response header are returned.

Send a request forcing an authorization failure:

```sh
curl -H 'Host: talker-api' -H 'Authorization: APIKEY ndyBzreUzF4zqDQsqSPMHkRhriEOtcRx' -H 'X-Mock-Unauthorized: 1' http://localhost:8000/hello -i
# HTTP/1.1 302 Found
# location: http://echo-api.3scale.net/not-found
# x-requested-path: /hello
# x-ext-auth-reason: Unauthorized
# date: Tue, 05 Oct 2021 22:46:16 GMT
# server: envoy
# content-length: 0
```

Without the customization, the response status code would be `403 Forbidden`. Instead, status `302 Found` and the `Location` response header are returned.

Notice as well the presence of a custom HTTP header `x-requested-path`, with value dynamically set to the path of the original request.

repository: pwright/kuadrant

branch_name: refs/heads/main

repo_name: pwright/kuadrant


text:
# Introduction to Neurotechnology

This course is under reconstruction -- slides will be available publicly as they are completed.

### Notes

* We are assuming course takers do not have access to an EEG headset such as the Muse or an OpenBCI. This assumption allows us to scale the course as a UC Berkeley DeCal as well as a MOOC on edX and Coursera.
* We will present demos with EEG headsets and make code/specs available to course takers.
* Homework/labs will be delivered through Jupyter notebooks.

### Lectures (tentative outline)

- [Lecture 1: The Big Picture]()
- [Lecture 2: Neuroscience]()
- [Lecture 3: Brain Imaging Techniques]()
- [Lecture 4: Elementary Signal Processing]()
- [Lecture 5: ]()
- [Lecture 6: ]()
- [Lecture 7: ]()
- [Lecture 8: ]()
- [Lecture 9: ]()
- [Lecture 10: ]()
- [Lecture 11: ]()
- [Lecture 12: ]()

### Labs

- [Lab 1: Getting started with EEG](http://docs.openbci.com/Tutorials/02-Ganglion_Getting%20Started_Guide)
- Lab 2: Sensory extension
- [Lab 3: Detecting event-related potentials](lab3)
- [Lab 4: Neurofeedback](lab4)
- [Lab 5: Steady-state visually evoked potentials](lab5)
- [Lab 6: Detecting stress using biosignals](lab6)
- [Lab 7: Measuring attention using cross-brain correlations](lab7)
- [Lab 8: Detecting and controlling muscle movements](lab8)
- [Lab 9: Characterizing EEG responses to smell](lab9)


text:
# User Maker App Test

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

## Inconvienient Dependencies

A function in testing may have inconvenient dependencies on other objects. To isolate the behavior of the function, it's often desirable to replace the other objects with mocks that simulate the behavior of the real objects. Replacing objects is especially useful if the actual objects are impractical to incorporate into the unit test.

Another use of mocks is as "spies" because they let us spy on the behavior of a function that is called by some other code. Mock functions can keep track of calls to the function and the parameters passed in those calls. We can even define an implementation for the mock, but that's optional. Simpler mocks that implement only enough behavior to execute test code are sometimes called "stubs."

### Lambda School 3.1 React Testing Notes

Module Study Guide: [Testing React](https://learn.lambdaschool.com/tracks/web-development/units/webapplications-ii/sprints/advanced-web-applications/)

Let's implement a helper function with an uncomfortable dependency that makes the helper impure (reliant on something outside of its scope) and, therefore, harder to test:

1. Install the uuid npm library using ```npm i uuid``` and make use of it in the following simple component:
    ```javascript
    import uuid from "uuid";

    export const makeUser = (firstName, lastName) => {
        return {
        id: uuid(),
        fullName: `${firstName} ${lastName}`
        };
    };
    ```

2. Testing expected output against actual output would be complex because ```uuid()``` generates a new, random id each time. We can give it a try, though. Note the use of ```.toEqual()``` to make our assertion. It compares the nested properties of objects, which we need to check here:
    ```javascript
    import { makeUser } from "../utils/makeUser";

    test("generates a user with an id and a full name", () => {
        // Arrange
        const expected = { id: "abcde", fullName: "Peter Parker" }; // fishy...

        // Act
        const actual = makeUser("Peter", "Parker");

        // Assert
        expect(actual).toEqual(expected);
    });
    ```
![Random ID complexity error](/src/assets/error.png)

>By the way, this kind of test is called a unit test - a test for a single unit of code, like an isolated function like makeUser. You'll learn more about unit testing in the backend unit, but we can see what is happening here with the AAA framework.

3. To get around this problem, we can stub out (create) a fake version of uuid that will replace the real one during the execution of the test. Outside of the test block, at the top level of the test file, place the following code:
    ```javascript
    jest.mock("uuid", () => () => "abcde");
    ```

Let's break it down. As the first argument to ```jest.mock()```, we pass the path to the module we want to replace. As the second argument, we pass a callback that returns whatever it is we want the faked thing to be. We wish for ```uuid``` to become a silly stub function that always returns the same string: ```uuid() // "abcde"```. Our tests should be passing now!

#### Challenge
There is a way to centralize mocks that are often used (think  ```uuid```, or ```axios```) in external files to be used in test suites without even bothering with imports. Go to the Jest docs and see if you can find out how!

repository: taratimmerman/user-maker-test

repo_name: taratimmerman/user-maker-test


text:
---
name: Owncast release checklist
about: Use when planning a new public release of Owncast.
title: Owncast release 0.0.x
labels: documentation, Testing
assignees: gabek

---

## Owncast release 0.0.x

The following are intended to address the test scenarios and documentation that should be accomplished for a public release.

- [ ] This release was tested as a fresh install, with no pre-existing data or configuration.
- [ ] This release was tested as an upgrade over a previous install, keeping the data and configuration.
- [ ] This release was tested using a Docker environment.
- [ ] This release was tested with local storage for file distribution.
- [ ] this release was tested with remote S3 storage for file distribution.
- [ ] Release notes and a changelog was written to call out the new features, changes to existing features, and user-impacting behind the scenes updates.
- [ ] The documentation site was updated to reflect the changes in this version.
- [ ] Upgrade instructions were written for migrating from the previous release.
- [ ] The API spec `openapi.yaml` is up to date, and the current version of the release is specified in the file.
- [ ] The API documentation was copied to the public documentation site under `/api/0.0.x` and `/api/latest`.
- [ ] The installer script was updated to point to the new release version.
- [ ] A TODO issue was created to update the DigitalOcean install image.

repository: owncast/owncast

branch_name: refs/heads/develop

gha_language: TypeScript

repo_name: owncast/owncast


text:
#Python Amazon IR Automation Script

##Installing

`pip install git+ssh://github.com/ThreatResponse/python-aws_ir.git@master`

or build and install locally

`python setup.py sdist && sudo pip install dist/*.tar.gz`

### Functions to Build

All function planning has been moved to trello. https://trello.com/b/Dn8VoJAw/aws-ir

### Running Tests for this project

 py.test --cov=aws_ir tests


text:
# Power-Systems-MatLab
So this is a passion project , with a list of scripts and Projects I have previously done on Matlab. They are fairly easy to follow and should anyone need any assitance there's the documentation

|Project| Ideology
---------|---------
Power Systems| Matlab
Power Electroniocs | Power Toolkit
Design of the power Module | Framework


text:
# vilga [![Action Status](https://github.com/rAum/vilga/workflows/vilga%20CI/badge.svg)](https://github.com/rAum/vilga/actions)

**under development, nothing usable yet and it's highly experimental code**

## What is it?
I am prototyping a debug tool inspired by my idea I used to find extremely useful in my previous commercial projects when I was working on monocular SLAM working on mobile/desktop platform.

This prototype is for more abstract tool, basically an async logger for non-textual data like images, matrices, point clouds etc which streams data over network socket.

Example use case is to provide real time debug visualization without much hassle (think about problems with multithreaded rendering/gui..) or to record data for later analysis (e.g. find the first difference to find what breaks determinism).

repository: rAum/vilga

repo_name: rAum/vilga


text:
# FSRCNN_Waifu
Inspired by Waifu2X which use SRCNN: https://github.com/nagadomi/waifu2x

Waifu2X web app: http://waifu2x.udp.jp/index.html

Replicating the FSRCNN model (faster and lighter version of SRCNN) in this paper: http://mmlab.ie.cuhk.edu.hk/projects/FSRCNN.html

Trained on 1000 high resolution images from https://pixiv.net

Demo image: https://www.pixiv.net/artworks/79923044

Input image:

![alt text](https://github.com/Onenightcarnival/FSRCNN_Waifu/blob/master/input.png)

Raw output from model:

![alt text](https://github.com/Onenightcarnival/FSRCNN_Waifu/blob/master/2x%20up%20no%20denoise%20input.png)

Denoise, this is what we want:

![alt text](https://github.com/Onenightcarnival/FSRCNN_Waifu/blob/master/2x%20up%20input.png)

# Run as Web App
required package: streamlit, tensorflow, cv2, keras, PIL

In terminal, run "streamlit run app.py"


text:
# 💿 mqtt-sql-logger

Super simple "set and forget" logger to store history of MQTT messages in a MySQL database.

🔒 Only works with authentication brokers and connections for now.

## Installation

```bash
> npm install mqtt-sql-logger
```

## Using it

1. Create a table in your MySQL database for the log

   ```sql
   CREATE TABLE IF NOT EXISTS `log` ( `id` INT NOT NULL AUTO_INCREMENT , `topic` VARCHAR(200) NULL , `message` TEXT NULL , `ts` INT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
   ```

2. In your Node project, import and create a new logger with your MQTT & DB credentials:

   ```js
   const mqtt_sql_logger = require('mqtt-sql-logger');

   const log = new mqtt_sql_logger.log({
      mqtt_broker    : 'mqtt.broker-url.com',
      mqtt_username  : 'broker_username',
      mqtt_password  : 'broker_password',

      sql_host       : 'db_hostname',
      sql_username   : 'db_username',
      sql_password   : 'db_password',
      sql_database   : 'db_name',

      topic          : 'your/topic/path/+'
   });
   ```

3. That's it!

## Configuration

Here are all the available options, along with their default values. The only required options are those shown in the `How to use` steps above.

```js
const config_defaults = {
   mqtt_broker         : "",    // URL for MQTT broker
   mqtt_username       : "",    // Username for MQTT subscriber user
   mqtt_password       : "",    // Password for MQTT subscriber user
   mqtt_port           : 8083,  // Port for MQTT connection (note default is to use secure web sockets)

   sql_host            : "",    // Hostname for MySQL server
   sql_username        : "",    // Username for MySQL connection
   sql_password        : "",    // Password for MySQL connection
   sql_database        : "",    // MySQL database name

   sql_table           : "log", // Name of MySQL table

   topic               : "+",   // MQTT subscription topic

   save_topic          : true,  // If true, will save full topic path to 'topic' field
   topic_fields        : "",    // Array of table fields to save parts of topic path to (see below)
   topic_save_interval : 300,   // How many seconds to wait between db saves on the same topic

   debug               : true   // Print console debug messages
};
```

### Custom table structures

Sometimes it might be preferrable to save parts of the topic path into a custom table structure.

For example, an MQTT home automation temperature system might sent messages from nodes to topics such as:

```
iot/family-home/temp/garage
iot/holiday-home/temp/kitchen
```

An example SQL table structure is shown:

```sql
mysql> describe log;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| message  | text         | YES  |     | NULL    |                |
| ts       | int(11)      | YES  |     | NULL    |                |
| building | varchar(200) | YES  |     | NULL    |                |
| room     | varchar(200) | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
```

Add the following items to the configuration:

   ```js
   const log = new mqtt_sql_logger.log({
      [...]
      topic        : 'iot/+'
      save_topic   : false,
      topic_fields : ["","building","","room"]
   });
   ```

The resulting log entries will appear as shown:

```sql
mysql> select * from log;
+----+---------+------------+--------------+---------+
| id | message | ts         | building     | room    |
+----+---------+------------+--------------+---------+
|  1 | 18.38   |<PHONE_NUMBER> | family-home  | garage  |
|  2 | 24.17   |<PHONE_NUMBER> | holiday-home | kitchen |
|  3 | 18.18   |<PHONE_NUMBER> | family-home  | garage  |
|  4 | 23.53   |<PHONE_NUMBER> | holiday-home | kitchen |
|  5 | 23.88   |<PHONE_NUMBER> | holiday-home | kitchen |
+----+---------+------------+--------------+---------+
```

repository: gcsalzburg/mqtt-sql-logger

gha_language: JavaScript

repo_name: gcsalzburg/mqtt-sql-logger


text:
ChattyApp
=====================

A real-time ReactJS chat app built with Web Socket Server.

### Usage

Clone the chattyapp and chattyserver into two seperate directories.

```
git clone https://github.com/kkwon39/chattyapp
git clone https://github.com/kkwon39/chattyserver
cd chattyapp
git remote rm origin
git remote add origin [YOUR NEW REPOSITORY]
# Manually update your package.json file
```

Install the dependencies and start the server.

```
npm install
npm start
open http://localhost:3000

```

### Static Files

You can store static files like images, fonts, etc in the `build` folder.

For example, if you copy a file called my_image.png into the build folder you can access it using `http://localhost:3000/build/my_image.png`.

### Linting

This ChattyApp includes React ESLint configuration.

```
npm run lint
```

### Dependencies

* React
* Webpack
* [babel-loader](https://github.com/babel/babel-loader)
* [webpack-dev-server](https://github.com/webpack/webpack-dev-server
* babel-core: "6.23.1"
* babel-loader: "6.3.1"
* babel-preset-es2015: "6.22.0"
* babel-preset-react: "6.23.0"
* babel-preset-stage-0: "6.22.0"
* css-loader: "0.26.1"
* eslint: "3.15.0"
* eslint-plugin-react: "6.9.0"
* node-sass: "4.5.0"
* sass-loader: "6.0.0"
* sockjs-client: "^1.1.2"
* style-loader: "0.13.1"
* webpack: "2.2.1"
* webpack-dev-server: "2.3.0"
)

### Final Product
![HomeScreen](https://github.com/kkwon39/chattyapp/blob/master/Docs/HomeScreen.png)
![UserNameChange](https://github.com/kkwon39/chattyapp/blob/master/Docs/UserNameChange.png)
![UserChatting1](https://github.com/kkwon39/chattyapp/blob/master/Docs/UserChatting1.png)
![UserChatting2](https://github.com/kkwon39/chattyapp/blob/master/Docs/UserChatting2.png)
![CurrentlyOnlineUsers](https://github.com/kkwon39/chattyapp/blob/master/Docs/Currently%20Online%20Users.png)


text:
# EugeneTechBlog

The blog for eugenetech.org. It's a standard Wordpress installation. In this repo are the theme parts only. The directory at wp-content/themes/x is the parent theme. This should only be updated with code supplied by [ThemeCo](https://community.theme.co/users/eugenetech/account/).

repository: anaxamaxan/EugeneTechBlog

repo_name: anaxamaxan/EugeneTechBlog


text:
#ThreadPool 1.0

Kelp http://kelp.phate.org/

MIT License

Thread Pool is a thread queue.

You could push threads to ThreadPool, and then it will process the thread.

```objective-c
ThreadPool *pool = [ThreadPool new];

NSThread *thread = [[NSThread alloc] initWithTarget:self
                                           selector:@selector(threadExecuteCode)
                                             object:nil];
thread.name = @"Thread A";
[pool pushThread:thread];

thread = [[NSThread alloc] initWithTarget:self
                                 selector:@selector(threadExecuteCode)
                                   object:nil];
thread.name = @"Thread B";
[pool pushThread:thread];
```
```objective-c
- (void)threadExecuteCode
{
    for (int index = 0; index < 10; index++) {
        NSLog(@"%@: %i", [NSThread currentThread].name, index);
    }
}
```

repository: nullpic/ThreadPool

repo_name: nullpic/ThreadPool


text:
## Part 1: HDL files

The goal of the first part is to get comfortable with the Sigasi Studio HDL editor. By the end you will be able to _easily detect and fix HDL syntax issues_, _customize editor preferences_ and _know the basic keyboard shortcuts_.

### Setup
* Open the Sigasi application
* In the status bar the status of the Sigasi license is shown
  * If you have a commercial license it should indicate **Sigasi Studio Creator**, **Sigasi Studio XL** or **Sigasi Studio XPRT**
* Import project `Part1`
  1. **File > Import...**
  2. **General > Existing project into Workspace**, **Next**
  3. **Browse** to `Part1`
  5. **Finish**
* Close unrelated projects (Right Click on the project in Project Explorer and select **Close Unrelated Projects**)

### Edit

* Open file `part1_1_edit.vhd` in the _Project Explorer_ view
* Make the editor _full screen_ (Double click on the tab)
* Double click again to exit _full screen_ mode
* Format the VHDL code (**Ctrl+Shift+F**, _Make sure that no text is selected_)
* Undo (**Ctrl+Z**) your previous change to correct a mistake
* Redo (**Ctrl+Shift+Z**) to restore a change that was undone
* Fix all VHDL syntax issues, use the QuickFix where possible (When in doubt, **Hover** over the error Marker)
* Delete a line with **Ctrl+D**
* Comment a line with **Ctrl+/**
* Move a line up and down with **Alt+Up** and **Alt+Down**
* Jump to the next error using **Ctrl+.**
* Autocomplete (**Ctrl+Space**)
    * Signal Name
    * Constant declaration
    * `if` statement in a `process` (Use **tab** to jump to the next field, use **enter** to exit the _template mode_)
    * `if generate` in an `architecture`
* Block select (**Shift+Alt+A**, or button in toolbar)
    * Delete a Block
    * Add content on multiple lines
* Enable _Show whitespace_ (¶-button) and type some _tabs_ and _spaces_ to see the difference
* Find & Replace
    * Experiment with **Ctrl+F**, e.g. find all `TODO`'s
    * Use **Ctrl+K** to find the next occurrence of the current selection
    * Use **Ctrl+J** (and start typing) for an inline, incremental search. _Look at the status bar to see what you have already typed_.
* Use **Quick Access** (top-right text field or **Ctrl+3**) to convert an identifier to UpperCase (Select the identifier, type `upper` in the Quick Access Field in the Toolbar and confirm with **Enter**)
* Mess up the indentation of a part of the source code, select it and **format only the selection**
* Save all changes to your file (**Ctrl+S**)

### Navigate

* Open file `part1_2_navigate.vhd`
* Go to Declaration can be done in various ways (Hover, Right-clik Menu, **F3**)
* Move back to last location (**Alt+Left**)
* Move forward to your original location (**Alt+Right**)
* Go to Line  (**Ctrl+L**)
* Navigate to errors with the gutter (Click red rectangles in scroll bar)
* Navigate to next problem marker (**Ctrl+.**, *Ctrl-key and dot-key*)
* Navigate with the *Outline view* (**Ctrl+O**)

### Customize settings

Preferences can be set via **Window > Preferences**.

* Open file `part1_3_custom.vhd`
* Switch to VHDL 2008 (**Preferences > Sigasi > VHDL**) and note that the syntax error get resolved
* After switching VHDL versions, the _Common Libraries_ need to be reset (Use the _Quick Fix_ offered on the first line of the file)
* Tabs or spaces ( Use the search box in the preference dialog and type `tab`) Use _Show whitespace_ to check.
* Uppercase keywords (**Preferences > Sigasi > VHDL > Formatting**) (Use _format_ to check)
* Add a keyboard shortcut for _Show whitespace_.
* Reset the keywords formatting to your preference (uppercase, lowercase or ignore)

### Optional Extra tasks

* Open file `part1_4_extra.vhd`
* Try *structured select* using **Shift+Alt+cursor** <https://insights.sigasi.com/manual/editor.html#structured-selection>
* *Stuttering* (in the editor, double tap the `.`, `;` or `,` key)
* Drag and drop a file from your file explorer in the Editor part of Sigasi Studio
* Create a new file  (**File > New > VHDL File** or right click on project or folder)
* In **Outline** and **Project Explorer**: Figure out what *Link with editor* button (⇆) does
* Add a keyboard shortcut preference for _show whitespace_ (Search for the **Keys** preference page)
* Use the eclipse file search (**Search > Search...**) to do a textual search/replace in you entire project or workspace.

path: /Sigasi Studio 3/part1.md


text:
# play-with-prisma
play with prisma

### Scripts

- `npm run playground` opens up Prisma Playground.
- `npm run deploy-prisma` deploy changes to prisma and fetch latest schema

repository: subuta/play-with-prisma

repo_name: subuta/play-with-prisma


text:
---
title: "Integrations Overview"
order: 100
---

You can integrate your Racks with external services as part of your deployment processes. In this section, we've documented a few examples:

* [Travis CI](/docs/travis-ci/)
* [Circle CI](/docs/circle-ci/)
* [Datadog](/docs/datadog/)

You're by no means limited to the services above. We invite you to submit a request for documentation on other services by [opening an issue on GitHub](https://github.com/convox/site/issues), or contribute documentation yourself via [pull request](https://github.com/convox/site)!

## See also

* [Connecting to a Rack](/docs/connecting-to-a-rack/)
* [Workflows](/docs/workflows/)

repository: soulshake/hugo-site

repo_name: soulshake/hugo-site


text:
Chaudière
=========

**Chaudière** provides C++ infrastructure for commonly used functionality
such as sockets and multithreading. Conceptually, it's similar to
Apache's Portable Runtime (APR). It is common code that was extracted
from **misère** and **tonnerre**.

License
-------
BSD

Platforms/Compilers
-------------------
This project is implemented with C++ (pre c++11). It is tested with
g++ compiler on Linux (primarily Ubuntu 14.04 server), FreeBSD, and
OpenBSD.

Threading Options
-----------------
This project was initially coded to use Posix threads (pthreads).
Apple's libdispatch is available on Mac OSX and FreeBSD.

Socket Options
--------------
Chaudière supports kernel event mechanisms such as epoll (linux) and
kqueue (freebsd, osx), as well as a built-in socket server.

Status/Maturity
---------------
Parts of the code are very mature and well tested, and other parts
aren't. I wouldn't use this for anything important just yet. It'll
slowly get there.

C++ Standards
-------------
The code is pre-C++11. This is intentional to provide maximum
portability.

Coding Style
------------
You may find my coding style slightly peculiar. It's my personal style
that I've adopted after a lot of experimentation about what works best
for me.

Meaning of Chaudière
--------------------
What does 'Chaudière' mean?  It's a French word that means kettle,
cooking pot, or cauldron.

repository: pauldardeau/chaudiere

repo_name: pauldardeau/chaudiere


text:
# Cybertruck demo in XAML with Uno

- Blog Article : [https://platform.uno/cybertruck-in-xaml-and-running-cross-platform-with-webassembly](https://platform.uno/cybertruck-in-xaml-and-running-cross-platform-with-webassembly/)

- Live WebAssembly implementation of Cybertruck : [https://cybertruck.platform.uno/](https://cybertruck.platform.uno/)

Having the CyberTruck in action running WebAssembly is pretty cool, but you can also customize it directly in our playground – [https://playground.platform.uno/#cybertruck](https://playground.platform.uno/#cybertruck).

See more at [https://platform.uno](https://platform.uno).

repository: unoplatform/cybertruck

gha_language: C#

repo_name: unoplatform/cybertruck


text:
# cookiecutter-python

This is a [cookiecutter](https://github.com/audreyr/cookiecutter) template for creating Python packages that adhere to the [SDSS standard](./\{\{cookiecutter.repo_name\}\}/STYLE.rst).

The full documentation on how to use this template can be found [here](http://sdss-python-template.readthedocs.io/en/latest/).

## User Installation

To install and initialize this template:

    pip install invoke
    pip install bumpversion
    pip install cookiecutter
    cookiecutter https://github.com/sdss/python_template.git

or to optionally install a specific branch:

    cookiecutter https://github.com/sdss/python_template.git --checkout [branchname]

During the installation, you will be asked a series of prompts to specify options and variable names, e.g. your name, the desired package name, etc. These definitions will be inserted into the package in designated places.  The final prompts ask

* do you want to install the new python package with python setup.py install?
* do you want to create a git repository out of your new package?
* do you want to connect your new git repo to an account on github?

## Developers

If you are developing on this template, first clone the product:

    git clone https://github.com/sdss/python_template.git

Now edit / add to the code as one normally does.  This package contains a Jinja2 template structure, with variable substitution that occurs upon installation. Variables to be inserted into the template are defined in `cookiecutter.json`.  To reference a variable inside the template structure use the Jinja2 double bracket nomenclature.

   {{cookiecutter.full_name}}

To test install the cookiecutter package locally, run:

    cookiecutter [path_to_my_local_clone_directory]

It is good practice to test install the package locally before you commit any changes to ensure the package can properly install without error.

## What you get in this template

* Python 2/3 compatibility
* Pip-ready product
* Sphinx Documentation with Read The Docs integration
* Pytest Testing Framework
* Tox for Multiple Python Environment Testing (in a future versions)
* Improved Logging
* [Versioning with BumpVersion](https://github.com/peritus/bumpversion)
* Continuous Integration with Travis
* Code Coverage with Coveralls
* Module File
* Invoke for shell tasks

## Coding standards

Before you start writing your code, make sure to read and digest the [SDSS coding standards](./\{\{cookiecutter.repo_name\}\}/STYLE.rst).


text:
+ Device that will deliver webcam stream using webRTC and Azure IoT
+ Before use:
  + Download P2PmanualSDP form webRTCexperiments
  + Edit line 18 of `device.js` so the appropriate path is given for P2PmanualSDP index.html, remember to keep the #1
  + Add dotenv file with the `CONNECTION_STRING` for the IoT hub (device string)
  + Download and install dependencies with `npm install`

repository: iiingrid/EIT-hub

repo_name: iiingrid/EIT-hub


text:
# react-month-frequency

A small configurable component that displays frequency across months

![Example](https://i.imgur.com/1th31hZ.png)

## Installation

Use the package manager [npm](https://www.npmjs.com/) to install.

```bash
npm install react-month-frequency
```

## Usage

```javascript
import MonthFreq from "react-month-frequency";

render(){
  return(
      <MonthFreq data={data} config={config} />
  )
}
```

## Config (optional)

The default configuration object has the following shape

```javascript
{
 style:{
  container:{
    width: 470,
    backgroundColor: '#161f29',
    radius: 15
  },
  monthBlockSize: {
    height: 80,
    width: 95
  },
  daySquare: {
    height: 8,
    width: 8,
    color: 'white'
  },
  monthTitle: {
    color: 'white',
    fontSize: 10,
  }
 },
  colorThresholds: [
    {
      from: 0,
      to: 1,
      opacity: 0.1
    },
    {
      from: 1,
      to: 3,
      opacity: 0.2
    },
    {
      from: 3,
      to: 5,
      opacity: 0.4
    },
    {
      from: 5,
      to: 7,
      opacity: 0.6
    },
    {
      from: 7,
      to: 9,
      opacity: 0.8
    },
    {
      from: 9,
      opacity: 1
    }
  ]
}
```

`colorThresholds` is used to configure opacity of day blocks based on data `count` value ranges.

## Data

```javascript
[
  {
    date: "2019/10/24",
    count: 7
  },
  {
    date: "2019/10/23",
    count: 3
  }
];
```

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

## License

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

repository: Zazzzles/react-month-frequency

repo_name: Zazzzles/react-month-frequency