text:
# Overview

This is a straightforward demonstration of an Apache Kafka with NodeJS, featuring a dead letter queue functionality.
Each message in the Kafka queue contains subscription data for an email campaign. The contact submission consumer's main
task is to attempt the submission of the subscription data to a campaign API. In the event of a failure during this
process, the message will be forwarded to the dead letter queue. Here, it will be accompanied by a reason for the
failure and a timestamp, providing valuable information about the unsuccessful attempt.

### Pre-requisites

* Docker or you can setup kafka on your own
* Nodejs >= 18.12.0.

### Step 1: Bootstrap kafka

The provided docker compose file offers a easy quick setup for Kafka.

```
docker-compose up -d
```

### Step 2: Create topics

To utilize the following commands, please download Kafka from official website to your local machine and navigate to
the `bin` directory.

```
./kafka-topics.sh --create --bootstrap-server <IP_ADDRESS>:9094 --replication-factor 1 --partitions 4 --topic contact-submission-queue
./kafka-topics.sh --create --bootstrap-server <IP_ADDRESS>:9094 --replication-factor 1 --partitions 2 --topic dead-letter-queue
```

Created topics can be easily listed by running following command.

```
./kafka-topics.sh --list --bootstrap-server <IP_ADDRESS>:9094
```

Output should be something like:

```
contact-submission-queue
dead-letter-queue
```

### Step 3: Install packages from npm

```
$ npm i
```

### Step 4: Setup environment variables

Copy `.env.example` to `.env`. Create a dummy campaign list at [klaviyo](https://klaviyo.com) and replace `.env`
configuration with your credentials.

### Step 5: Start consumers

The contact submission service is designed to retrieve messages from the `contact-submission-queue` and attempt to submit
contact data to a third-party API. Contact submission service will join into a Kafka consumer group, you can deploy multiple
instances of this service in various locations, enabling parallel processing of messages.

```
node src/contactSubmission.js
```

In the event of a failed contact submission due to an API error, the data will be moved to a dead letter, allowing for
later analysis and investigation.

```
node src/deadLetter.js
```

### Step 6: Send data to producer

```
node src/sendTestData.js
send to >>> contact-submission-queue - 1
...
send to >>> contact-submission-queue - 3
```

#### Useful commands

Describe a topic:

```
bin/kafka-topics.sh --describe --bootstrap-server <IP_ADDRESS>:9094 --topic provider
```

Increase topic partitions:

```
bin/kafka-topics.sh --bootstrap-server <IP_ADDRESS>:9094 --alter --topic provider --partitions 4
```

### Author

**Joynal Abedin** - [Joynal](https://linkedin.com/in/joynaluu/)

### License

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

repository: joynal/kafka-experiment

repo_name: joynal/kafka-experiment


text:
# Integrate WSO2 API Manager 3.2.0 with Auth0

In this guide, we explain how to integrate the WSO2 API Manager with an external Identity provider Auth0 as the OAuth Authorization Server
to manage the OAuth clients and tokens required by WSO2 API Manager. This is a client implementation that consumes APIs exposed by Auth0

## Follow the instructions below to configure the third-party Key Manager

### Step 1 : Prerequisites

1.  Create an Auth0 account. Get the URL for the tenant. and then sign into the dashboard.

   ![alt text](images/dashboard.png)

2.  The you need to create an application to use the management API. Then need's to allow that application to use the management API.

    ![alt text](images/management-api.png)

    ![alt text](images/New%20Application.png)

    ![alt text](images/permision-to-use-app.png)

   Make sure you have granted all the permissions to Create, Manage Apps and Resource servers.

### Step 2: Configure WSO2 API Manager

1.  Log into the admin portal of the API Manager. And add a new Key Manager.

    ![alt text](images/add-app-admin.png)

2.  Then select the Key manager type as Auth0 and provide the relevant fields accordingly.

    ![alt text](images/km-tyoe.png)

    **List of well know address could be found in advance section of the Auth0 Application settings**
        ![alt text](images/endpoints.png)

3.  The client ID, Client secret of the application created to invoke Manage API should be provided for the settings. You can get to the audience
value from the Manage API.
    ![alt text](images/connector-configs.png)
4.  Finally you can save the configs.

### Step 3 : Create new application and generate keys

1.  Create new application form the developer portal.
    ![alt text](images/dev-app-create.png)

2.  Then click either production or sandbox, Select Auth0 and try to generate the keys.
    ![alt text](images/key-gen.png)

3.  Once the keys generated, It will reflect in the UI. But in order to generate keys, Its need to add the new application to the *WSO2 resource server API* to generate tokens. (Note that *WSO2 resource server API* will be created if not exist).

    ![alt text](images/resoure-api.png)

    ![alt text](images/grant.png)

5. After token could be generate successfully.

    ![alt text](images/success.png)

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# Jeux react Memory

Jeux de mémoire de https://github.com/deliciousinsights/ocr-memory/tree/master
Cours React: https://drive.google.com/file/d/1DnwGaolGxL2989J-XUUiK62rk52xY5v6/view?usp=sharing

Basé sur react-scripts to create development env and the production build

# Scaffold react Project using create-react-app

npm install --global create-react-app
create-react-app Memory

--> Installing react, react-dom, and react-scripts in the project dependencies...
--> create application folders and startup files such as public/index.html or stc/App.js

# Install and rstart dev

npm install
npm run start

# Creating an optimized production build

npm run build

license: MIT

branch_name: refs/heads/main


text:
# Introduction #
This report documents the baseline and load tests against the AIDE. It shows comparisons of baseline and load tests across an AWS cloud environment (SIT) and performant on-premise Pre Prod environment. It also lists any conclusions and identifies any necessary follow-up actions.

# Environment Details #

## AWS Cloud (SIT) Specification ##

| Node      | Specification              |
|-----------|----------------------------|
| SIT-Head1 | 4 vCPU, 16GB ram, 0 GPUs   |
| SIT-Head2 | 4 vCPU, 16GB ram, 0 GPUs   |
| SIT-DGX   | 8 vCPUs, 32GB ram, 1 GPU's |

## On-premise Pre Prod Environment ##

| Node      | Specification              |
|-----------|----------------------------|
| PreProd-Head1 | 48 vCPU, 252GB ram, 1 GPUs   |
| PreProd-Head2 | 48 vCPU, 252GB ram, 0 GPUs   |
| PreProd-Head3   | 48 vCPUs, 252GB ram, 1 GPU's |

# Data #
| Modality | Details                   |
| -------- | ------------------------- |
| RF       | \- 1 slice
\- 1MB      |
| US       | \- 7 slices
\- 17MB    |
| MR       | \- 5 slices
\- 1MB     |
| CT       | \- 324 slices
\- 167MB |

# Applications #
The following dummy applications were published to stress the GPU and CPU. These were written using [stress](https://linux.die.net/man/1/stress) and [gpu-burn](https://github.com/wilicc/gpu-burn)

| Application Name | Specification                                                            | Modality  |
| ---------------- | ------------------------------------------------------------------------ | --------- |
| Small            | CPU: 2
GPU: Access to all
RAM: 1GB
Execution time: 10 seconds   | RF        |
| Medium           | CPU: 8
GPU: Access to all
RAM: 10GB
Execution time: 30 seconds  | US and MR |
| Large            | CPU: 12
GPU: Access to all
RAM: 16GB
Execution time: 60 seconds | CT        |

# Test Types #

## Baseline ##
Single transactions to performance reference point which can be used as a basis for performance comparison

## Load Average ##
Realistic expected usage levels to determine its response time, resource usage, and reliability using GSTT imaging throughput data in an average 1 hour period.

## Load Peak ##
Realistic expected usage levels to determine its response time, resource usage, and reliability using GSTT imaging throughput data in an peak 1 hour period.

## Stress ##
Uplift of peak load by 25%

# Throughput #

## Peak 1 Hour ##

| Modality   | Transactions | Model executions |
| ---------- | ------------ | ---------------- |
| X-ray      | 120          | 120              |
| Ultrasound | 50           | 5                |
| CT         | 30           | 21               |
| MRI        | 25           | 17.5             |

## Avg 1 Hour ##

| Modality   | Transactions | Model executions |
| ---------- | ------------ | ---------------- |
| X-ray      | 60          | 60              |
| Ultrasound | 28           | 2.8                |
| CT         | 10           | 7               |
| MRI        | 13           | 9.1             |

## Stress 1 Hour ##

| Modality   | Transactions | Model executions |
| ---------- | ------------ | ---------------- |
| X-ray      | 180          | 180              |
| Ultrasound | 75           | 7.5                |
| CT         | 45           | 31.5               |
| MRI        | 37.5           | 26.25             |

# KPI and Measurements #

| KPI                     | Details                                                                                | Query Params                                                                                |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| DICOM Payload Processed | How long it took between an association being made to Informatics Gateway, the instances being saved to MinIO and a WorkflowRequestEvent being generated | ServiceName: Monai.Deploy.InformaticsGateway AND "Payload took"                                                       |
| Task Dispatched         | How long it took for the WorkflowRequestEvent to be consumed by the WorkflowManager, a workflow to be triggered and a TaskDispatchEvent to be generated  | ServiceName: Monai.Deploy.WorkflowManager AND messageDescription: WorkflowRequestEvent AND durationMilliseconds > 0   |
| Task Created            | How long it took for the TaskDispatchEvent to be consumed by the TaskManager and create a Task                                                           | ServiceName: Monai.Deploy.WorkflowManager.TaskManager AND messageType: TaskDispatchEvent AND durationMilliseconds > 0 |
| Task Update             | How long it took for the TaskManager to publish a TaskUpdateEvent, the WorkflowManager to consume the event and update the WorkflowInstance              | ServiceName: Monai.Deploy.WorkflowManager AND messageDescription: TaskUpdateEvent AND durationMilliseconds > 0        |
| Argo                    | How long it took for Argo to run the application requested. This includes time from the pod being scheduled and then a TaskCallbackEvent being published | Taken from Argo                                                                                |
| End To End              | Indicative time of the end to end processing of a workflow from dicom association to workflow completion.                                                | Time from Task Update timestamp - (DICOM Payload Process timestamp - processed time)                                  |

# Cloud Execution #

## Details ##
Baseline tests were executed on SIT to validate the cloud environment to compare pre-prod tests against to understand the performance improvements based on specifications.

## Results ##
### Baseline ###
#### Description ####
Send through the same study 5 times, with a 90 second gap to get average metric for a known study, environment and MAP (liver-seg) set up.

#### Metrics ####
|          | DICOM Payload Processed | DICOM Payload Processed | Task Dispatched | Task Dispatched | Task Created  | Task Created | Task Update   | Argo      | Argo          | Argo      | End to End |
| -------- | ----------------------- | ----------------------- | --------------- | --------------- | ------------- | ------------ | ------------- | --------- | ------------- | --------- | ---------- |
| Modality | Average            | Max               | Average    | Max       | Average  | Max     | Average  | Max  | Average (min) | Max (min) | Indicative |
| CT       | 01:11                   | 01:24                   | 14.5            | 20.4            | 2.3           | 2.9          | 0.8           | 1.7       | 01:57         | 02:04     | 03:21      |
| MR       | 13.6                    | 34.5                    | 6.7             | 13.6            | 4.9           | 10           | 1             | 1.5       | 01:24         | 01:32     | 01:23      |
| US       | 6.2                     | 6.8                     | 2.6             | 3.3             | 2.8           | 3.9          | 0.7           | 1.5       | 01:14         | 01:15     | 01:25      |
| RF       | 5.8                     | 9.5                     | 11.3            | 23.6            | 30            | 107.7        | 1.1           | 2.9       | 01:06         | 01:37     | 00:58      |

# On-Premise Execution #

## Details ##
Baseline, Load and Stress tests were executed on on-premise to understand the performance of MONAI-Deploy and AIDE on target production hardware and validate against throughput and metrics.

## Results ##
### Baseline 1 ###
#### Description ####
Send through the same study 5 times, with a 90 second gap to get average metric for a known study, environment and MAP (liver-seg) set up.

#### Metrics ####
|                                                              | DICOM Payload Processed | DICOM Payload Processed | Task Dispatched | Task Dispatched | Task Created  | Task Created | Task Update   | Task Update | Argo          | Argo      | End to End |
| ------------------------------------------------------------ | ----------------------- | ----------------------- | --------------- | --------------- | ------------- | ------------ | ------------- | ----------- | ------------- | --------- | ---------- |
| Modality                                                     | Average (sec)           | Max (sec)               | Average (sec)   | Max (sec)       | Average (sec) | Max (sec)    | Average (sec) | Max (sec)   | Average (min) | Max (min) | Indicative |
| CT ("{{ context.dicom.series.all('0008','0060') }} == 'CT'") | 34.4                    | 36.2                    | 11.6            | 12.5            | 1.1           | 1.2          | 0.4           | 0.9         | 01:54         | 02:07     | 02:30      |
| CT ("{{ context.dicom.series.any('0008','0060') }} == 'CT'") | 34.2                    | 37.8                    | 12.3            | 13.7            | 1.2           | 1.6          | 0.7           | 1           | 01:53         | 02:03     | N/A        |
| MR                                                           | 1.1                     | 1.4                     | 0.7             | 1.1             | 1.2           | 1.5          | 0.6           | 0.8         | 01:06         | 01:10     | 01:18      |
| US                                                           | 1.7                     | 2.3                     | 1.1             | 1.3             | 0.9           | 1.6          | 0.6           | 1           | 01:10         | 01:17     | 01:07      |
| RF                                                           | 0.7                     | 1.2                     | 0.7             | 1.1             | 0.9           | 1.3          | 0.8           | 1           | 00:55         | 00:58     | 00:42      |
| CT (executing Small app & no conditional logic)              | 34.9                    | 37.9                    | 10.6            | 10.8            | 2.08          | 6.3          | 0.9           | 1.9         | 01:06         | 01:13     | 01:47      |
| RF (no conditional logic)                                    | 0.7                     | 0.9                     | 0.8             | 1.4             | 1.3           | 1.8          | 0.7           | 1.3         | 00:55         | 01:00     | 00:52      |

### Baseline 2 ###
#### Description ####
Retest of the MIG following a change to how it was saving data to MinIO.

|          | DICOM Payload Processed | DICOM Payload Processed |
| -------- | ----------------------- | ----------------------- |
| Modality | Average (sec)           | Max (sec)               |
| CT       | 14                      | 16.2                    |

### Load (Avg) ###
#### Description ####
#### Metrics ####

### Load (Peak) ###
#### Description ####
#### Metrics ####

### Stress ###
#### Description ####
#### Metrics ####

repository: Project-MONAI/monai-deploy

gha_language: Python

repo_name: Project-MONAI/monai-deploy


text:
# Getting started

# What is this?

This is a small example of how to use shared Toolbar components.You can pass a schema, which uses to render Toolbar in the specified element.
eg :
```html
 <script>
      var schema = {
        type:"Toolbar",
        title:"Navbar",
        actions:[
          {
            title:'Home',
            url:'#/home',
          },
          {
            title:'Contact',
            url:'#/contact',
          },
        ],
        search:{
          title:"Search",
          onSearch:onSearch
        }
      }
      function onSearch(serchText,e) {
        console.log('onSearch!',searchText,e);
      }
        if(myLibrary){
            var element = document.getElementById('c-toolbar'); // This element is used to render toolbar.
            var toolbarElement = new myLibrary.Toolbar(element);
            toolbarElement.render(schema);
        }
    </script>
```

# How do I use it?

## Build the library

```sh
npm run build
```

# How would I set this up myself?

## Install your dependencies

Either run the following:

```sh
npm i
```

or make sure that you add the appropriate `"devDependencies"` entries to your `package.json` and run `npm install`:

```json
"devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.4.0",
    "@babel/plugin-proposal-class-properties": "^7.4.0",
    "@babel/plugin-proposal-numeric-separator": "^7.2.0",
    "@babel/plugin-proposal-object-rest-spread": "^7.4.0",
    "@babel/preset-env": "^7.7.7",
    "@babel/preset-typescript": "^7.3.3",
    "typescript": "^3.3.3"
}
```

# How do I change it?

## How to change the UI of Toolbar?
You can see all UI styles which is defined in Toolbar class,
```js
export class Toolbar {...}
```
Note : `Toolbar` using bootstrap styles now.
## Adding more elements
This library utilizing `Schema` to render Toolbar component.So,you can extend the schema to add more ui elements support.

repository: salmanul/myToolbar

repo_name: salmanul/myToolbar


text:
#A declaration made by the Archbishop of Collen, vpon the deede of his mariage, sent to the states of his archbishoprike VVith the letter of Pope Gregorie the. 13 against the celebration of the same mariage, and the Bishops aunswer therevnto. According to the coppie imprinted at Collen. 1583.#

##Gebhard, Truchsess von Waldburg, Archbishop and Elector of Cologne, 1547-1601.##
A declaration made by the Archbishop of Collen, vpon the deede of his mariage, sent to the states of his archbishoprike VVith the letter of Pope Gregorie the. 13 against the celebration of the same mariage, and the Bishops aunswer therevnto. According to the coppie imprinted at Collen. 1583.
Gebhard, Truchsess von Waldburg, Archbishop and Elector of Cologne, 1547-1601.

##General Summary##

**Links**

[TCP catalogue](http://www.ota.ox.ac.uk/tcp/)  •
[HTML](http://tei.it.ox.ac.uk/tcp/Texts-HTML/free/A01/A01567.html)  •
[EPUB](http://tei.it.ox.ac.uk/tcp/Texts-EPUB/free/A01/A01567.epub) •
[Page images (Historical Texts)](https://data.historicaltexts.jisc.ac.uk/view?pubId=eebo-99838712e&pageId=eebo-99838712e-3100-1)

**Availability**

This keyboarded and encoded edition of the
	       work described above is co-owned by the institutions
	       providing financial support to the Early English Books
	       Online Text Creation Partnership. This Phase I text is
	       available for reuse, according to the terms of Creative
	       Commons 0 1.0 Universal. The text can be copied,
	       modified, distributed and performed, even for
	       commercial purposes, all without asking permission.

**Major revisions**

1. __2004-03__ __TCP__ *Assigned for keying and markup*
1. __2004-03__ __Aptara__ *Keyed and coded from ProQuest page images*
1. __2004-07__ __Mona Logarbo__ *Sampled and proofread*
1. __2004-07__ __Mona Logarbo__ *Text and markup reviewed and edited*
1. __2004-10__ __pfs__ *Batch review (QC) and XML conversion*

##Content Summary##

#####Front#####

1. ¶To the right reuerend Father in God
Iohn, Bishoppe of London, Thomas Delone,
wisheth increase of grace, and continuall happinesse,
both of body and soule.

#####Body#####

1. ¶A Christian declaration
touching the Religion which the
right reuerend Prince, the Lord Ghebbard,
chosen, and confirmed Archbishop
of Collen, Elector of the Empire,
and Chancelor for the Prouince of
Italie, Duke of Westphalie and Enghern,
and proclaimed throughout
his dominions, the 17. daye
of Ianuarie. 1583.

1. ¶Pope Gregorie the 13. to our right
reuerend and beloued brother, Ghebbard
Archbishop of Collen, Prince, and
Elector of the Empire.

1. To Pope Gregorie the .13. Ghebbard
Archbishop of Collon, Prince, and
Elector of the Empire, sendeth greeting.

**Types of content**

  * Oh, Mr. Jourdain, there is **prose** in there!

There are 1 **ommitted** fragments!
 @__reason__ (1) : illegible: indecipherable (1)  •  @__extent__ (1) : 1 letter (1)

**Character listing**

|Text|string(s)|codepoint(s)|
|---|---|---|
|Latin-1 Supplement|¶éó|182 233 243|
|Combining             Diacritical Marks|̄|772|
|General Punctuation|•|8226|
|Superscripts             and Subscripts|⁴|8308|
|Geometric Shapes|▪|9642|
|Dingbats|❧|10087|

##Tag Usage Summary##

###Header Tag Usage###

|No|element name|occ|attributes|
|---|---|---|---|
|1.|__author__|4||
|2.|__availability__|1||
|3.|__biblFull__|1||
|4.|__change__|5||
|5.|__date__|8| @__when__ (1) : 2004-11 (1)|
|6.|__edition__|1||
|7.|__editionStmt__|1||
|8.|__editorialDecl__|1||
|9.|__extent__|2||
|10.|__idno__|6| @__type__ (6) : DLPS (1), STC (2), EEBO-CITATION (1), PROQUEST (1), VID (1)|
|11.|__keywords__|1| @__scheme__ (1) : http://authorities.loc.gov/ (1)|
|12.|__label__|5||
|13.|__langUsage__|1||
|14.|__language__|1| @__ident__ (1) : eng (1)|
|15.|__listPrefixDef__|1||
|16.|__note__|8||
|17.|__notesStmt__|2||
|18.|__p__|11||
|19.|__prefixDef__|2| @__ident__ (2) : tcp (1), char (1)  •  @__matchPattern__ (2) : ([0-9\-]+):([0-9IVX]+) (1), (.+) (1)  •  @__replacementPattern__ (2) : http://eebo.chadwyck.com/downloadtiff?vid=$1&page=$2 (1), https://raw.githubusercontent.com/textcreationpartnership/Texts/master/tcpchars.xml#$1 (1)|
|20.|__projectDesc__|1||
|21.|__pubPlace__|2||
|22.|__publicationStmt__|2||
|23.|__publisher__|2||
|24.|__ref__|2| @__target__ (2) : https://creativecommons.org/publicdomain/zero/1.0/ (1), http://www.textcreationpartnership.org/docs/. (1)|
|25.|__seriesStmt__|1||
|26.|__sourceDesc__|1||
|27.|__term__|2||
|28.|__textClass__|1||
|29.|__title__|3||
|30.|__titleStmt__|2||

###Text Tag Usage###

|No|element name|occ|attributes|
|---|---|---|---|
|1.|__closer__|2||
|2.|__date__|1||
|3.|__dateline__|1||
|4.|__desc__|1||
|5.|__div__|5| @__type__ (5) : title_page (1), dedication (1), declaration (1), letter (2)|
|6.|__figure__|1||
|7.|__g__|290| @__ref__ (290) : char:leaf (1), char:EOLhyphen (226), char:punc (6), char:cmbAbbrStroke (56), char:EOLunhyphen (1)|
|8.|__gap__|1| @__reason__ (1) : illegible: indecipherable (1)  •  @__extent__ (1) : 1 letter (1)|
|9.|__head__|4||
|10.|__hi__|109| @__rend__ (30) : sup (30)|
|11.|__p__|18||
|12.|__pb__|38| @__facs__ (38) : tcp:3100:1 (2), tcp:3100:2 (2), tcp:3100:3 (2), tcp:3100:4 (2), tcp:3100:5 (2), tcp:3100:6 (2), tcp:3100:7 (2), tcp:3100:8 (2), tcp:3100:9 (2), tcp:3100:10 (2), tcp:3100:11 (2), tcp:3100:12 (2), tcp:3100:13 (2), tcp:3100:14 (2), tcp:3100:15 (2), tcp:3100:16 (2), tcp:3100:17 (2), tcp:3100:18 (2), tcp:3100:19 (2)  •  @__rendition__ (1) : simple:additions (1)|
|13.|__seg__|4| @__rend__ (4) : decorInit (4)|
|14.|__signed__|2||
|15.|__trailer__|1||


text:
---
layout: example
title: What is a good standard?
author: Bert Bos
overview: |
  Why doesn't HTML include tags for style? Why can't you put text inside SMIL? Why doesn't CSS include commands to transform a document? Why, in short, does W3C modularize its specification and why in this particular way? This essay tries to make explicit what the developers in the various W3C working groups mean when they invoke words like efficiency, maintainability, accessibility, extensibility, learnability, simplicity, longevity, and other long words ending in -y.
link: https://www.w3.org/People/Bos/DesignGuide/introduction
principles:
- principle: Maintainability
- principle: Modularity
- principle: Minimum redundancy
- principle: Accessibility
- principle: Device-independency
- principle: Internationality
- principle: Extensibility
- principle: Learnability
- principle: Readability
- principle: Efficiency
- principle: Binary or text format
- principle: Implementability
- principle: Simplicity
- principle: Longevity
- principle: Backwards compatibility
- principle: Interoperability
- principle: Repurposing of content
- principle: Timeliness
- principle: Use what is there
- principle: Design by committee
- principle: Expertise
- principle: Brevity
- principle: Stability
- principle: Robustness

---


text:
---
title: 'Commands'
description: 'Creating and testing custom Artisan Commands in your package. Additionally, this section covers testing a command, without publishing it within your package for testing purposes.'
tags: ['Artisan', 'Commands', 'Testing Commands', 'Test-Only Commands']
image: 'https://www.laravelpackage.com/assets/pages/laravelpackage.jpeg'
date: 2019-09-17
---

# Artisan Commands

Laravel ships with a PHP executable 'artisan' file, providing a command-line interface (CLI) for the framework. Via this CLI, you can access commands as `php artisan migrate` and `php artisan make:model Post`. There are a lot of things you could do with commands. Make sure to read up on the artisan console in the [Laravel documentation](https://laravel.com/docs/artisan).

Let's say that we want to provide an easy artisan command for our end user to publish the config file, via: `php artisan blogpackage:install`.

## Creating a New Command

Create a new `Console` folder in the `src/` directory and create a new file named `InstallBlogPackage.php`. This class will extend Laravel's `Command` class and provide a `$signature` (the command) and a `$description` property. In the `handle()` method we specify what our command will do. In this case, we provide some feedback that we're "installing" the package and we'll call another artisan command to publish the config file. Finally, we let the user know that we're done.

```php
// 'src/Console/InstallBlogPackage.php'
<?php

namespace JohnDoe\BlogPackage\Console;

use Illuminate\Console\Command;

class InstallBlogPackage extends Command
{
    protected $signature = 'blogpackage:install';

    protected $description = 'Install the BlogPackage';

    public function handle()
    {
        $this->info('Installing BlogPackage...');

        $this->info('Publishing configuration...');

        $this->call('vendor:publish', [
            '--provider' => "JohnDoe\BlogPackage\BlogPackageServiceProvider",
            '--tag' => "config"
        ]);

        $this->info('Installed BlogPackage');
    }
}
```

## Registering a Command in the Service Provider

We need to present this package functionality to the end user, thus registering it in the package's service provider.

Since we only want to provide this functionality from the command-line we'll add it within the if-runningInConsole()-statement (don't forget to import the class):

```php
// 'BlogPackageServiceProvider.php'

use JohnDoe\BlogPackage\Console\InstallBlogPackage;

public function boot()
{
    // Register the command if we are using the application via the CLI
    if ($this->app->runningInConsole()) {
        $this->commands([
            InstallBlogPackage::class,
        ]);
    }
}
```

## Testing a Command

To test that our command works, let's create a new unit test called `InstallBlogPackageTest.php` in the Unit test folder.

Since we’re using **Orchestra Testbench**, we have a config folder at `config_path()` containing every file a normal Laravel installation would have. (You can check where this directory lives yourself if you `dd(config_path()))`. Therefore, we can easily assert that this directory should have our `blogpackage.php` config file after running our artisan command. To make sure we're starting at a clean state, let's delete any remainder configuration file from the previous test first.

```php
// 'tests/Unit/InstallBlogPackageTest.php'
<?php

namespace JohnDoe\BlogPackage\Tests\Unit;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use JohnDoe\BlogPackage\Tests\TestCase;

class InstallBlogPackageTest extends TestCase
{
    /** @test */
    function the_install_command_copies_the_configuration()
    {
        // make sure we're starting from a clean state
        if (File::exists(config_path('blogpackage.php'))) {
            unlink(config_path('blogpackage.php'));
        }

        $this->assertFalse(File::exists(config_path('blogpackage.php')));

        Artisan::call('blogpackage:install');

        $this->assertTrue(File::exists(config_path('blogpackage.php')));
    }
}
```

## Hiding a Command

There might be cases where you'd like to exclude the command from the list of Artisan commands. You can define a `$hidden` property on the command class, which will not show the specific command in the list of Artisan commands. Note, however, that the command can still be used and is only hidden.

```php
class InstallBlogPackage extends Command
{
    protected $hidden = true;

    protected $signature = 'blogpackage:install';

    protected $description = 'Install the BlogPackage';

    public function handle()
    {
        // ...
    }
}
```

## Creating a Generator Command

Laravel provides an easy way to create _Generator_ Commands, _i.e._ commands with signatures such as `php artisan make:controller`. Those commands modify a general, predefined template (stub) to a specific application. For example by automatically injecting the correct the namespace.

In order to create a Generator Command, you have to extend the `Illuminate\Console\GeneratorCommand` class, and override the following properties and methods:

- `protected $name`: name of the command
- `protected $description`: description of the command
- `protected $type`: the type of class the command generates
- `protected function getStub()`: method returning the path of the stub template file
- `protected function getDefaultNamespace($rootNamespace)`: the default namespace of the generated class
- `public function handle()`: the body of the command

The `GeneratorCommand` base class provides some helper methods:

- `getNameInput()`: returns the name passed from command line execution
- `qualifyClass(string $name)`: returns the qualified class name for a given class name
- `getPath(string $name)`: returns the file path for a given name

Consider the following example for the `php artisan make:foo MyFoo` command:

```php
<?php

namespace JohnDoe\BlogPackage\Console;

use Illuminate\Console\GeneratorCommand;

class MakeFooCommand extends GeneratorCommand
{
    protected $name = 'make:foo';

    protected $description = 'Create a new foo class';

    protected $type = 'Foo';

    protected function getStub()
    {
        return __DIR__ . '/stubs/foo.php.stub';
    }

    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\Foo';
    }

    public function handle()
    {
        parent::handle();

        $this->doOtherOperations();
    }

    protected function doOtherOperations()
    {
        // Get the fully qualified class name (FQN)
        $class = $this->qualifyClass($this->getNameInput());

        // get the destination path, based on the default namespace
        $path = $this->getPath($class);

        $content = file_get_contents($path);

        // Update the file content with additional data (regular expressions)

        file_put_contents($path, $content);
    }
}
```

Note that the class is exported to a directory **based on the namespace** as specified in the `getDefaultNamespace()` method.

As with the `InstallBlogPackage` command, we'd have to register this new command in the `BlogPackageServiceProvider`:

```php
// 'BlogPackageServiceProvider.php'
use JohnDoe\BlogPackage\Console\{InstallBlogPackage, MakeFooCommand};

public function boot()
{
  if ($this->app->runningInConsole()) {
    // publish config file

    $this->commands([
        InstallBlogPackage::class,
        MakeFooCommand::class, // registering the new command
    ]);
  }
}
```

### Creating a stub

You are free to store stubs in a different directory, but for now consider storing stubs in the `Console/stubs` directory. For our `Foo` class generator, the stub could look as follows:

```php
// 'stubs/foo.php.stub'
<?php

namespace DummyNamespace;

use JohnDoe\BlogPackage\Foo;

class DummyClass implements Foo
{
    public function myFoo()
    {
        // foo
    }
}
```

Note that `DummyNamespace` and `DummyClass` are placeholders (strictly defined in the `GeneratorCommand` base class: Laravel expects these specific names to replace) and are automatically replaced with the correct values.

## Testing Generator Commands

We can add a feature test for this command in the `tests/Feature` directory, called `MakeFooCommandTest.php` which verifies that a new file is created and contains the correct contents:

```php
<?php

namespace JohnDoe\BlogPackage\Tests\Feature;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;
use JohnDoe\BlogPackage\Tests\TestCase;

class MakeFooCommandTest extends TestCase
{
    /** @test */
    function it_creates_a_new_foo_class()
    {
        // destination path of the Foo class
        $fooClass = app_path('Foo/MyFooClass.php');

        // make sure we're starting from a clean state
        if (File::exists($fooClass)) {
            unlink($fooClass);
        }

        $this->assertFalse(File::exists($fooClass));

        // Run the make command
        Artisan::call('make:foo MyFooClass');

        // Assert a new file is created
        $this->assertTrue(File::exists($fooClass));

        // Assert the file contains the right contents
        $expectedContents = <<<CLASS
<?php

namespace App\Foo;

use JohnDoe\BlogPackage\Foo;

class MyFooClass implements Foo
{
    public function myFoo()
    {
        // foo
    }
}
CLASS;

        $this->assertEquals($expectedContents, file_get_contents($fooClass));
    }
}
```

## Creating a Test-Only Command

There are some situations in which you would like to only use a certain command for testing and not in your application itself. For example when your package provides a `Trait` that can be used by Command classes. To test the trait, you want to test with an actual command.

The command itself doesn't add functionality to the package and should therefore not be published. However, merely excluding the command from the service provider is not the solution as you want to be able to run the command in your tests.

An elegant solution [suggested by Marcel Pociot](https://twitter.com/marcelpociot/status/1219274939565514754) is to: register the Command **only** in the tests, by hooking into Laravel's `Application::starting()` method:

```php
<?php

namespace JohnDoe\BlogPackage\Tests\Feature;

use JohnDoe\BlogPackage\Tests\Commands\TestCommand;
use Illuminate\Console\Application;
use Illuminate\Support\Facades\Artisan;
use Orchestra\Testbench\TestCase;

class TestCommandTest extends TestCase
{
   /** @test **/
   public function it_does_a_certain_thing()
   {
        Application::starting(function ($artisan) {
            $artisan->add(app(TestCommand::class));
        });

        // Running the command
        Artisan::call('test-command:run');

       // Assertions...
   }
}
```


text:
## Compass Retinator

This Compass extension will allow you to create retina ready sprites from scratch. Just drop your images on the right folders, type some Compass mumble jumble and you are ready to go!

##Installation

    gem install compass-retinator

Now do a require in your Compass config.rb

```ruby
require 'compass-retinator'
```

## How to use it?

First thing to do is drop your images on the right folders. In this case I have set two folders icons and icons-retina inside my image folder.

Next, we need to tell Compass where those image are. Add this line to variables.sass or somewhere else

```sass
$sprites:        sprite-map("icons/*.png")
$sprites_retina: sprite-map("icons-retina/*.png")
```

Now we need to init awesomeness, add this line to your project:

```sass
@import "compass_retinator"
```

## Using the extension

You can pass several parameters to obtain the right result, some valid options are:

```sass
// This will import plain.png
.plain
  +sprite(plain)

// This will import boat.png, boat_hover.png and boat_active.png
.boat
  +sprite(boat, $hover_state: true, $active_state: true)

// This will import console.png plus 40px of padding on the sides
.console
  +sprite(console, $spacing: 40px)

// This will import people.png and it will not set any dimension on this elements
.people
  +sprite(people, $dimensions: False)
```

## Common Issues

### The sprite position is wrong

Please be sure that your icons scale proportionally. If the non-retina icons are **16x16** your retina icons must be **32x32** and not **30x32** and definitely not **45x34**

### I'm getting a _compass can't convert nil into string_ error

You're probably running a rails app. This is a weird issue with compass-rails. For some reason compass-rails does not create the sprites on demand and doesn't understand the `sprite-map`.

One workaround is to tell Compass to re-declare your sprites assets, so add this line at the top of your variables:

```sass
@import "icons/*.png"
@import "icons-retina/*.png"
```

### The smart layout doesn't seems to work properly

Unfortunately Compass doesn't support extra options with this layout. Try to use the default layout or the horizontal layout.

### When I add some _spacing_ to my sprite the sprite position is not right

Please, keep in mind, if you are adding extra padding around the sprite item, you will also need to tell Compass to add some extra space on every sprite item. Just past the varible `$spacing: XXpx`

```sass
$sprites:        sprite-map("icons/*.png", $spacing: 10px)
$sprites_retina: sprite-map("icons-retina/*.png", $spacing: 20px)
```

## License

Copyright (c) 2013 Restorando

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

repository: mezuka/compass-retinator

repo_name: mezuka/compass-retinator


text:
# Juniperus lucayana Britton SPECIES

#### Status
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. L. Britton & J. A. Schafer, N. Amer. trees 121. 1908

#### Original name
null

### Remarks
null

repository: mdoering/backbone

path: /life/Plantae/Pinophyta/Pinopsida/Pinales/Cupressaceae/Juniperus/Juniperus barbadensis/ Syn. Juniperus lucayana/README.md

repo_name: mdoering/backbone


text:
    Google Ads API

  Unofficial Google Ads API client library for Node

# Features

-   Simple and easy to use API
-   Uses [gRPC](https://grpc.io/) and [Protocol Buffers](https://developers.google.com/protocol-buffers/) internally (recommended by Google)
-   Typescript definitions for all [Google Ads API resources, enums and errors](https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v4.resources)

> The Google Ads API is the new replacement to the AdWords API. Google will deprecate the AdWords API sometime in 2020.

# Installation

```bash
$ yarn add google-ads-api
```

# Documentation

You can find the [full documentation here](https://opteo.com/dev/google-ads-api).

The documentation is divided into two main sections:

- [General concepts](https://opteo.com/dev/google-ads-api) for general usage of this library.
- [Core resources](https://opteo.com/dev/google-ads-api/#accountbudget) for the specific fields and methods available per resource.

You can improve the documentation by sending pull requests with edits to [these files](https://github.com/Opteo/google-ads-api/tree/master/docs/content). More instructions [here](https://github.com/Opteo/google-ads-api/tree/master/docs/). All help and feedback welcome!

# Basic Example

```javascript
import { GoogleAdsApi, types, enums } from 'google-ads-api'

// 1. Create a new client with your credentials
const client = new GoogleAdsApi({
    client_id: '<CLIENT_ID>',
    client_secret: '<CLIENT_SECRET>',
    developer_token: '<DEVELOPER_TOKEN>',
})

// 2. Load a customer with a valid CID & authentication
const customer = client.Customer({
    customer_account_id: '<CUSTOMER_ACCOUNT_ID>',
    refresh_token: '<REFRESH_TOKEN>',
})

// 3. Use the query method for querying customer data
const response = await customer.query(`
    SELECT
        ad_group.id,
        ad_group.name,
        metrics.clicks,
        segments.device
    FROM
        ad_group
    WHERE
        metrics.impressions > 10
        AND segments.date DURING LAST_30_DAYS
    LIMIT 5
`)

// 4. Inspect the data and benefit from ts definitions
for (const row of response) {
    const { ad_group, metrics } = row
    if (ad_group.status === enums.AdGroupStatus.ENABLED) {
        console.log(`Ad group "${ad_group.name}" had ${metrics.clicks} clicks.`)
    }
}

// 5. Create a new campaign
const campaign = {
    name: 'New Campaign',
    campaign_budget: 'customers/123/campaignBudgets/123',
    advertising_channel_type: enums.AdvertisingChannelType.SEARCH,
    status: enums.CampaignStatus.PAUSED,
}

const { results } = await customer.campaigns.create(campaign)

const new_campaign_resource_name = results[0]

// 6. ...modify it...
await customer.campaigns.update({
    resource_name : new_campaign_resource_name,
    name : 'New Campaign EDITED'
})

// 7. ...and delete it.
await customer.campaigns.delete(new_campaign_resource_name)
```

# More examples

There are many more examples in the [full documentation](https://opteo.com/dev/google-ads-api).

You can also find a couple ready-to-run examples in the [/examples directory](https://github.com/Opteo/google-ads-api/tree/master/examples).

repository: taraskuzyk/google-ads-api

repo_name: taraskuzyk/google-ads-api


text:
---
id: react-native
title: React Native
sidebar_label: React Native
---

## React Native

React-Native components are designed to work with expo. If you are using any other eg react-native-cli to start your project, this may not work for you.

## Installing

In your expo project, run this command.

```sh
    npm install --save @expocraft/core
```

Once expo is installed, make sure to create a theme folder [like the one in the project](https://github.com/cloudhubke/expo-components/tree/master/lib/theme). The required configuration parameters are `colors, fonts, sizes`.

Once done, configure pass theme to `ThemeProvider` context.

```js
import ThemeProvider from '@expocraft/core/lib/theme/ThemeProvider';
import { sizes, fonts, colors } from './theme';

<ThemeProvider fonts={fonts} sizes={sizes} colors={colors}>
  <App />
</ThemeProvider>;
```

Your project is now ready to use with your theme and [Materia Ui Theme](https://material-ui.com/customization/theming/).

Example

```js
import { sizes, fonts, colors } from './theme';
import { Button } from '@expocraft/core';

<Button color={colors.primary}>
  <Text white>Click Me</Text>
</Button>;
```

repository: cloudhubke/cloudhub-components-docs

gha_language: JavaScript

gha_license_id: MIT

repo_name: cloudhubke/cloudhub-components-docs


text:
# Alfred

A performant, expressjs like server framework thats easy to use and has all the bits in one place.

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

Quickstart:

```dart
import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.get('/example', (req, res) => 'Hello world');

  await app.listen();
}
```

# Index
- [Core principles](#core-principles)
- [Usage overview](#usage-overview)
    - [Quick start guide](#quick-start-guide)
- [Routing & incoming requests](#routing--incoming-requests)
    - [Route params](#route-params)
    - [Query string variables](#query-string-variables)
    - [Body parsing](#body-parsing)
    - [File uploads](#file-uploads)
- [Middleware](#middleware)
    - [No 'next'?](#what-no-next-how-do-i-even)
    - [CORS](#cors)
- [Responses](#responses)
    - [Custom type handlers](#custom-type-handlers)
    - [Static Files](#static-files)
    - [File downloads](#file-downloads)
- [Error handling](#error-handling)
    - [404 Handling](#404-handling)
- [Databases](#but-what-about-mongo-or-postgres-or-databse-x)
- [What I want to do isn't listed](#what-i-want-to-do-isnt-listed)
- [Websockets](#websockets)
- [Logging](#logging)
    - [Print routes](#print-routes)
- [Multi threading & isolates](#multi-threading-and-isolates)
- [Contributions](#contributions)

## Core principles
- A minimum of dependencies,
- A minimum of code and sticking close to dart core libraries - easy to maintain!
- Ease of use
- Predictable, well established semantics
- 90%+ of everything you need all ready to go

[Read about the background behind the project or why its different to shelf](documentation/background.md)

## Usage overview

If you have ever used expressjs before you should be right at home:

```dart
import 'dart:io';

import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.get('/text', (req, res) => 'Text response');

  app.get('/json', (req, res) => {'json_response': true});

  app.get('/jsonExpressStyle', (req, res) {
    res.json({'type': 'traditional_json_response'});
  });

  app.get('/file', (req, res) => File('test/files/image.jpg'));

  app.get('/html', (req, res) {
    res.headers.contentType = ContentType.html;
    return '<html><body><h1>Test HTML</h1></body></html>';
  });

  await app.listen(6565); //Listening on port 6565
}
```

It should do pretty much what you expect. Handling bodies though do need an "await":

```dart
import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.post('/post-route', (req, res) async {
    final body = await req.body; //JSON body
    body != null; //true
  });

  await app.listen(); //Listening on port 3000
}
```

Internally dart provides a body parser, so no extra dependencies there.

The big difference you will see is the option to not call `res.send` or `res.json` etc - although you still can.
Each route accepts a Future as response. Currently you can pass back the following and it will be sent appropriately:

| Return Dart Type | Returning REST type |
| ----------------- | ------------------ |
| `List<dynamic>` | JSON |
| `Map<String, Object?>` | JSON |
| Serializable object (Object.toJSON or Object.toJson) * see note | JSON |
| `String` | Plain Text |
| `Stream<List<int>>` | Binary |
| `List<int>` | Binary |
| `File` |  Binary, with mime type inferred by extension |
| `Directory` | Serves static files |

\* If your object has a "toJSON" or "toJson" function, alfred will run it, and then return the result

If you want to return HTML, just set the content type to HTML like this:

```dart
import 'dart:io';

import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.get('/html', (req, res) {
    res.headers.contentType = ContentType.html;
    return '<html><body><h1>Title!</h1></body></html>';
  });

  await app.listen(); //Listening on port 3000
}
```

If you want to return a different type and have it handled automatically, you can extend Alfred with
[custom type handlers](#custom-type-handlers).

### Quick start guide

If its all a bit overwhelming @iapicca put together a quick start guide which goes into a little
more detail: https://medium.com/@iapicca/alfred-an-express-like-server-framework-written-in-dart-1661e8963db9

## Routing & incoming requests

Routing follows a similar pattern to the more basic ExpressJS routes. While there is some regex
matching, mostly just stick with the route name and param syntax from Express:

"/path/to/:id/property" etc

So for example:

```dart
import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();
  app.all('/example/:id/:name', (req, res) {
    req.params['id'] != null;
    req.params['name'] != null;
  });
  await app.listen();
}
```

You can also use a wildcard for a route, and provided another route hasn't already resolved the
response it will be hit. So for example if you want to authenticate a whole section of an api youc
can do this:

```dart
import 'dart:async';
import 'dart:io';

import 'package:alfred/alfred.dart';

FutureOr _authenticationMiddleware(HttpRequest req, HttpResponse res) async {
  res.statusCode = 401;
  await res.close();
}

void main() async {
  final app = Alfred();

  app.all('/resource*', (req, res) => _authenticationMiddleware);

  app.get('/resource', (req, res) {}); //Will not be hit
  app.post('/resource', (req, res) {}); //Will not be hit
  app.post('/resource/1', (req, res) {}); //Will not be hit

  await app.listen();
}
```

### Route params

You can access any params for routes from the `req.params` object as below:

```dart
import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();
  app.all('/example/:id/:name', (req, res) {
    req.params['id'] != null;
    req.params['name'] != null;
  });
  await app.listen();
}
```

### Query string variables

Querystring variables are exposed `req.uri.queryParameters` object in the request as below:

```dart
import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.post('/route', (req, res) async {
    /// Handle /route?qsvar=true
    final result = req.uri.queryParameters['qsvar'];
    result == 'true'; //true
  });

  await app.listen(); //Listening on port 3000
}
```

### Body parsing

To access the body, simply call `await req.body`.

Alfred will interpret the body type from the content type headers and parse it appropriately. It handles url encoded, multipart & json bodies out of the box.

```dart
import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.post('/post-route', (req, res) async {
    final body = await req.body; //JSON body
    body != null; //true
  });

  await app.listen(); //Listening on port 3000
}
```

### File uploads

To upload a file the body parser will handle exposing the data you need. Its actually pretty easy
just give it a go and set a breakpoint to see what the body parser spits back.

A working example of file uploads is below to get you started:

```dart
import 'dart:io';

import 'package:alfred/alfred.dart';

final _uploadDirectory = Directory('uploadedFiles');

Future<void> main() async {
  final app = Alfred();

  app.get('/files/*', (req, res) => _uploadDirectory);

  /// Example of handling a multipart/form-data file upload
  app.post(
      '/upload',
      (req, res) => (HttpRequest req, HttpResponse res) async {
            final body = await req.bodyAsJsonMap;

            // Create the upload directory if it doesn't exist
            if (await _uploadDirectory.exists() == false) {
              await _uploadDirectory.create();
            }

            // Get the uploaded file content
            final uploadedFile = (body['file'] as HttpBodyFileUpload);
            var fileBytes = (uploadedFile.content as List<int>);

            // Create the local file name and save the file
            await File('${_uploadDirectory.absolute}/${uploadedFile.filename}')
                .writeAsBytes(fileBytes);

            /// Return the path to the user
            ///
            /// The path is served from the /files route above
            return ({
              'path':
                  'https://${req.headers.host ?? ''}/files/${uploadedFile.filename}'
            });
          });

  await app.listen();
}
```

## Middleware

You can specify a middleware for all routes by using wildcards:

```dart
import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();
  app.all('*', (req, res) {
    // Perform action
    req.headers.add('x-custom-header', "Alfred isn't bad");

    /// No need to call next as we don't send a response.
    /// Alfred will find the next matching route
  });

  app.get('/otherFunction', (req, res) {
    //Action performed next
    return {'message': 'complete'};
  });

  await app.listen();
}
```

Middleware declared this way will be executed in the order its added to the app.

You can also add middleware to a route, this is great to enforce authentication etc on an endpoint:

```dart
import 'dart:async';
import 'dart:io';

import 'package:alfred/alfred.dart';

FutureOr exampleMiddlware(HttpRequest req, HttpResponse res) {
  // Do work
  if (req.headers.value('Authorization') != 'apikey') {
    throw AlfredException(401, {'message': 'authentication failed'});
  }
}

void main() async {
  final app = Alfred();
  app.all('/example/:id/:name', (req, res) {}, middleware: [exampleMiddlware]);

  await app.listen(); //Listening on port 3000
}
```

### What? No 'next'? how do I even?
OK, so the rules are simple. If a middleware resolves a http request, no future middleware gets executed.

So if you return an object from the middleware, you are preventing future middleware from executing.

If you return null it will yield to the next middleware or route.

** returning null is the equivalent of 'next' **

### CORS

There is a cors middleware supplied for your convenience. Its also a great example of how to write a middleware for Alfred

```dart
import 'package:alfred/alfred.dart';
import 'package:alfred/src/middleware/cors.dart';

void main() async {
  final app = Alfred();

  // Warning: defaults to origin "*"
  app.all('*', cors(origin: 'myorigin.com'));

  await app.listen();
}
```

## Responses

Alfred is super easy, generally you just return JSON, a file, a String or a Binary stream and you are all good.

The big difference from express is you will see is the option to not call `res.send` or `res.json` etc - although you still can.
Each route accepts a Future as response. Currently you can pass back the following and it will be sent appropriately:

- `List<dynamic>` - JSON
- `Map<String, Object?>` - JSON
- `String` - Plain text
- `Stream<List<int>>` - Binary
- `List<int>` - Binary
- `File` - Binary, with mime type inferred by extension
- `Directory` - Serves static files

Each type listed above has a `Type Handler` build in. [You can create your own custom type handlers](#custom-type-handlers)

### Custom type handlers
Alfred has a pretty cool mechanism thanks to Dart's type system to automatically resolve a response
based on the returned type from a route. These are called `Type Handlers`.

If you want to create custom type handlers, just add them to the type handler
array in the app object. This is a bit advanced, and I expect it would be more
for devs wanting to extend Alfred:

```dart
import 'package:alfred/alfred.dart';

class Chicken {
  String get response => 'I am a chicken';
}

void main() {
  final app = Alfred();

  app.typeHandlers.add(TypeHandler<Chicken>((req, res, dynamic val) async {
    res.write((val as Chicken).response);
    await res.close();
  }));

  /// The app will now return the Chicken.response if you return one from a route

  app.get('/kfc', (req, res) => Chicken()); //I am a chicken;

  app.listen(); //Listening on 3000
}
```

### Static Files, uploads and deleting

This one is super easy - just pass in a public path and a dart Directory object and Alfred does
the rest.

```dart
import 'dart:io';

import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  /// Note the wildcard (*) this is very important!!
  app.get('/public/*', (req, res) => Directory('test/files'));

  await app.listen();
}
```

You can also pass in a directory and a POST or PUT command and upload files to a local directory if
you are using multipart/form encoding. Simply supply the field as `file`:

```dart
import 'dart:io';

import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.post('/public', (req, res) => Directory('test/files'));

  await app.listen();
}
```

If you want to delete a file?

```dart
import 'dart:async';
import 'dart:io';

import 'package:alfred/alfred.dart';

FutureOr isAuthenticatedMiddleware(HttpRequest req, HttpResponse res) {
  if (req.headers.value('Authorization') != 'MYAPIKEY') {
    throw AlfredException(
        401, {'error': 'You are not authorized to perform this operation'});
  }
}

void main() async {
  final app = Alfred();

  /// Note the wildcard (*) this is very important!!
  ///
  /// You almost certainly want to protect this endpoint with some middleware
  /// to authenticate a user.
  app.delete('/public/*', (req, res) => Directory('test/files'),
      middleware: [isAuthenticatedMiddleware]);

  await app.listen();
}
```

Security? Build in a middleware function to authenticate a user etc.

### File downloads

As mentioned above - if you want to return a file, simply return it from the route callback.
However the browser will probably try to render it in browser, and not download it.

You can just set the right headers, but there is a handy little helper that will do it all for you.

See `res.setDownload` below.

```dart
import 'dart:io';

import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.get('/image/download', (req, res) {
    res.setDownload(filename: 'image.jpg');
    return File('test/files/image.jpg');
  });

  await app.listen(); //Listening on port 3000
}
```

## Error handling

You can either set the status code on the response object yourself and send the data manually, or
you can do this from any route:

app.get("/",(req, res) => throw AlfredException(400, {"message": "invalid request"}));

If any of the routes bubble an unhandled error, it will catch it and throw a 500 error.

If you want to handle the logic when a 500 error is thrown, you can add a custom handler when you
instantiate the app. For example:

```dart
import 'dart:async';

import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred(onInternalError: errorHandler);
  await app.listen();
  app.get('/throwserror', (req, res) => throw Exception('generic exception'));
}

FutureOr errorHandler(HttpRequest req, HttpResponse res) {
  res.statusCode = 500;
  return {'message': 'error not handled'};
}
```

### 404 Handling

404 Handling works the same as 500 error handling (or uncaught error handling). There is a default
behaviour, but if you want to override it, simply handle it in the app declaration.

```dart
import 'dart:async';
import 'dart:io';

import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred(onNotFound: missingHandler);
  await app.listen();
}

FutureOr missingHandler(HttpRequest req, HttpResponse res) {
  res.statusCode = 404;
  return {'message': 'not found'};
}
```

## But what about Mongo or Postgres or <Database x>?

The other two systems that inspired this project to be kicked off - Aqueduct and Angel - both had
some sort of database integration built in.

**You do not need this.**

Access the dart drivers for the database system you want directly, they all use them behind the scenes:

- Mongo - https://pub.dev/packages/mongo_dart
- Postgres - https://pub.dev/packages/postgres
- SQLLite -  https://pub.dev/packages/sqlite3

You will be fine. I have used them this way and they work.

I have rolled my own classes that act as a sort of ORM, especially around Mongo. Its suprisingly effective
and doesn't rely on much code.

## What I want to do isn't listed

While there are bunch of helpers built in - you have direct access to the low level apis available
from the dart:io package. All helpers are just extension methods to:

- HttpRequest: https://api.dart.dev/stable/2.10.5/dart-io/HttpRequest-class.html
- HttpResponse: https://api.dart.dev/stable/2.10.5/dart-io/HttpResponse-class.html

So you can compose and write any content you can imagine there. If there is something you wan't to do
that isn't expressly listed by the library, you will be able to do it with a minimum of research into
underlying libraries. A core part of the architecture is to not build you into a wall.

## Websockets

Alfred supports websockets too!

There is a quick chat client in the examples

```dart
import 'dart:async';
import 'dart:io';

import 'package:alfred/alfred.dart';
import 'package:alfred/src/type_handlers/websocket_type_handler.dart';

Future<void> main() async {
  final app = Alfred();

  // Path to this Dart file
  var dir = File(Platform.script.path).parent.path;

  // Deliver web client for chat
  app.get('/', (req, res) => File('$dir/chat-client.html'));

  // Track connected clients
  var users = <WebSocket>[];

  // WebSocket chat relay implementation
  app.get('/ws', (req, res) {
    return WebSocketSession(
      onOpen: (ws) {
        users.add(ws);
        users
            .where((user) => user != ws)
            .forEach((user) => user.send('A new user joined the chat.'));
      },
      onClose: (ws) {
        users.remove(ws);
        users.forEach((user) => user.send('A user has left.'));
      },
      onMessage: (ws, dynamic data) async {
        users.forEach((user) => user.send(data));
      },
    );
  });

  final server = await app.listen();

  print('Listening on ${server.port}');
}
```

## Logging

For more details on logging [click here](documentation/logging.md).

### Print routes

Want to quickly print out the registered routes? (recommended when you fire up the server)
call Alfred.printRoutes ie:

```dart
import 'package:alfred/alfred.dart';

void main() async {
  final app = Alfred();

  app.get('/html', (req, res) {});

  app.printRoutes(); //Will print the routes to the console

  await app.listen();
}
```

## Multi threading and isolates

You can use the app in multithreaded mode. When spawning this way, requests are evenly distributed
amongst the various isolates. Alfred is not particularly prescriptive about how you manage the isolates
just that "it works" when you fire up multiples.

```dart
import 'dart:isolate';

import 'package:alfred/alfred.dart';

Future<void> main() async {
  // Fire up 5 isolates
  for (var i = 0; i < 5; i++) {
    unawaited(Isolate.spawn(startInstance, ''));
  }
  // Start listening on this isolate also
  startInstance(null);
}

/// The start function needs to be top level or static. You probably want to
/// run your entire app in an isolate so you don't run into trouble sharing DB
/// connections etc. However you can engineer this however you like.
///
void startInstance(dynamic message) async {
  final app = Alfred();

  app.all('/example', (req, res) => 'Hello world');

  await app.listen();
}

/// Simple function to prevent linting errors, can be ignored
void unawaited(Future future) {}
```

# Deployment

There are many ways to skin this cat, you can upload the source code to a VPS yourself, build a binary locally and upload it to a server somewhere, but a fairly elegant way to accomplish a production level deployment is to containerize an AOT build of the server and run it on a PAAS.

Lucky there is a tutorial for that!
https://ryan-knell.medium.com/build-and-deploy-a-dart-server-using-alfred-docker-and-google-cloud-run-from-start-to-finish-d5066e3ab3c6

# Contributions

PRs are welcome and encouraged! This is a community project and as long as the PR keeps within the key principles listed it will probably be accepted. If you have an improvement you would like to to add but are not sure just reach out in the issues section.

Before you submit your code, you can run the `ci_checks.sh` shell script that will do many of the tests the CI suite will perform.

repository: dipendra-sharma/alfred

repo_name: dipendra-sharma/alfred


text:
# Narrative Startup Conditions

This document explores error conditions that may occur during initial Narrative startup.

## Components
- network
- nginx server
- lua nginx code
- docker
- jupyter

## Startup Lifecycle

So I think that in any case in which an unhandled error is issued by the narrative server (the lua proxy) the narrative loader will loop until it times out and then issue an error message. We need to identify specifically the response from the narrative server when a narrative container is loading.

Narrative opening will go through the kbase-ui narrative loading page if the narrative server (i.e. lua code in nginx) detects that a container is not loaded for that user. The loading page will attempt to load the narrative up to 20 times, with a 1 second pause between each one. If there is an error detected upon any loading attempt, an error message is displayed.

The issue is the detection of a container being loaded. We should identify all of the responses from the narrative service, and make sure they are specifically handled. Currently only a few error conditions are detected, and everything else falls through allowing the loop to continue until the end.

## Error Conditions
- network
    - No connection from user to kbase proxy
    - Kbase front proxy to narrative proxy
- nginx server
    - nginx down
- lua nginx code
    - lua program error
    - lua error conditions detected
        - HTTP_REQUEST_TIMEOUT (408) - if there is a timeout locking the user session (could this happen with concurrent access by the same user to the same narrative deployment env?)
HTTP_SERVICE_UNAVAILABLE (503) - if no container could be created
ngx.redirect (302) - if container does not exist yet and is being created.
HTTP_NOT_FOUND (404) - if a container was not found ... then not found ... don't think is possible to reach this condition
- docker
- jupyter

### Network

#### No connection from user to kbase proxy

The connection from the browser to the kbase front end proxy is interrupted.

name
: KBase proxy unreachable

expected
: Nothing, the browser cannot get any response from a KBase service

#### Kbase front proxy to narrative proxy

The connection from the KBase front end proxy to the Narrative proxy is interrupted.

name
: Narrative proxy unreachable

expected
: The user should see an error message specifically stating that the Narrative service is not currently available

currently
: I don't know, but I expect it is a simple 502 or 404.

### Narrative proxy

##### nginx down

The Narrative proxy runs on nginx, and nginx may not be running at all. This differs from the "Narrative proxy unreachable" in that the Narrative proxy can be contacted by the KBase proxy, but will not have the http or https service running on the respective ports.

name
: Narrative proxy does not offer http or https service

expected
: The user should see an error message specifically stating that the Narrative service is not currently available

currently
: I don't know, but I expect it is a simple 502 or 404.

### lua nginx code

The Narrative proxy uses Lua scripts executed during browser connection to route access to the user's Narrative container.

#### lua program error

During the execution of this Lua code, the Lua code itself may experience an error

name
: Narrative proxy program error

expected
: The user should see a message stating that the Narrative service is experiencing internal errors.

currently
: Plain 500 Internal Server Error

todo
: The Narrative proxy nginx should be configured to display a custom error message in the case of all errors, but especially 500.

In addition, the Lua code itself may return the following errors upon detecting certain conditions.

#### HTTP_REQUEST_TIMEOUT (408)

if there is a timeout locking the user session (could this happen with concurrent access by the same user to the same narrative deployment env?)

What should this mean to the user? There really isn't anything meaningful to convey to the user, but the technical reason for the error should be preserved and communicated.

name
: Timeout locking user session

expected
: The user should see a message that there was a temporary error accessing the Narrative, and they should try again

currently
: If this error could be triggered, it would be a runtime error resulting in a generic 500 message. The error handing is incorrectly coded

todo
: Correct the coding of the error; install a custom error page for this condition

#### HTTP_SERVICE_UNAVAILABLE (503)

if no container could be created because the limit on the number of containers that may be created has been exceeded, or the time to create containers is exceeding the ability of the system to respond to new requests

name
: Narrative container could not be created

expected
: The user should receive an error message that the Narrative service has exceeded the capacity, and they should try again later

currently
: It looks like it should return the correct error; the narrative proxy itself will return a generic 503 error message

todo
: The Narrative proxy should return a custom error message. Alternatively, a front end Narrative loading page could ALWAYS be the entry-way to a narrative, in which case it could trap such errors.

#### ngx.redirect (302)

Technically a non-success message, this response is created in the case of a Narrative request requiring the starting of a new Narrative container. The url to the loading page with the Narrative url passed as a parameter is the sent as the Location.

#### HTTP\_NOT\_FOUND (404)

if a container was not found ... then not found ... don't think is possible to reach this condition.

This pathway in the code does not seem possible.

####

## Upstream Errors

What happens when various upstream components have a failure?

### docker

A docker error may affect the initial Narrative startup as well as the Loading loop.

### jupyter

A Jupyter / Narrative app error will not affect the initial Narrative startup, but may affect the Loading loop. This is because an error in the Narrative server code itself may produce any number of http error conditions which would result in an Nginx proxy 502 error.

## Non-Startup Errors

Although not related to startup per se, in the user's mind Narrative access post-startup is no different. It should behave the same.

There are generally two types of Narrative access errors: access and startup.

Access errors are encountered when a user requests a Narrative, but before it is delivered.

- no authorization
- inadequate authorization
- requested object is not a narrative
- requested object does not exist at all
- requested narrative is corrupt

repository: kbase/narrative

branch_name: refs/heads/develop

repo_name: kbase/narrative


text:
### Docker Node Hello World

This project uses `Docker for Mac`

---

### Interactive Development

To interactively develop with docker, you must build the environment and mount the project folder.  If you do not mount the project folder, you will need to rebuild the image each time you make changes.  Remember: if you ran `npm install` outside the container, you will need to `rm -rf /opt/src/node_modules` before you start.

```
git clone https://github.com/kunze83/node-demo.git && cd node-demo;
docker build -t node-demo .;
docker run -d -p 3000:3000 --name node-demo -h node-demo.localhost -v ${pwd}:/opt/src -t node-demo;
```

### Production

In production, we dont want to interactively modify the app code.  Therefore, the steps are simple: `build`, and `run`.

```
git clone https://github.com/kunze83/node-demo.git && cd node-demo;
docker build -t node-demo .;
docker run -d -p 3000:3000 --name node-demo -h node-demo.prod -t node-demo;
```


text:
# Apache Spark Monitoring Extension

Apache Spark is a fast and general purpose cluster computing system. It provides high level APIs in Java, Scala, Python & R as well as an optimized engine that supports general execution graphs. It also supports a tool called Spark SQL for SQL and relational data processing.

The AppDynamics Spark Extension can monitor multiple Spark clusters and worker nodes and extracts metrics from every running and completed Spark application, more specifically the jobs, executors, stages and storage RDDs within these applications. The metrics reported by the extension can be configured by users.

## Related Sandbox

For reference only (Extension deployment is not possible on the current sandbox) [Cisco AppDynamics sandbox](https://devnetsandbox.cisco.com/RM/Diagram/Index/9e056219-ab84-4741-9485-de3d3446caf2?diagramType=Topology)

## Links to DevNet Learning Labs

[AppDynamics Fundamentals](https://developer.cisco.com/learning/modules/appdynamics-fundamentals)

[Installation and Configuration workflow](https://github.com/Appdynamics/apache-spark-monitoring-extension/blob/master/README.md)


text:
# mkCursorClip
Lock mouse to screen or specific area

## Description
Don't you just hate it? When playing in window mode and suddenly the window is no longer in focus, because you clicked outside of it?
Yes!!! So does everyone else!

And because it annoyed the original author, slayit, so much he wrote this little application. It provides a keyboard shortcut to trap your cursor in a window, be it a game or any other program.

## Features
* Configurable hotkeys
* Configurable padding from application border
* Simple and lightweight
* Uses modified version of http://keyboardmousehooks.codeplex.com/ for hotkey handling <-- link will be dead after December 15, 2017
* The project is mirrored at https://bitbucket.org/slayit/mkcursorclip/ <--original author page, last update in 2013, this is serious necro-ware

## How-to

1. It's pretty simple.
1. Download the current release
1. Start it
1. Press the configured hotkeys (default is left-shift + <) and watch your cursor struggle to come out of the current window!
1. Optional: Right-click the tray icon and configure it for your own needs in the settings dialog

# License
**MIT**

# Why?!!!
I found it on codeplex.com, they said they are going down December 15th, 2017. It's license is MIT. Mirrored at bitbucket.org. Decided another mirror can't hurt and maybe I might just want to dabble in C# too.

-- Kreezxil September 5th, 2017

repository: kreezxil/mkCursorClip

repo_name: kreezxil/mkCursorClip


text:
Qtumcore Library
=======

A pure and powerful JavaScript QTUM library.

## Get Started

```
npm install qtumcore-lib
```

```
bower install qtumcore-lib
```

## Security

We're using qtumcore-lib in production, but please use common sense when doing anything related to finances! We take no responsibility for your implementation decisions.

## Contributing

Please send pull requests for bug fixes, code optimization, and ideas for improvement.

## Building the Browser Bundle

To build a qtumcore-lib full bundle for the browser:

```sh
gulp browser
```

This will generate files named `qtumcore-lib.js` and `qtumcore-lib.min.js`.

## Development & Tests

```sh
git clone https://github.com/qtumproject/qtumcore-lib
cd qtumcore-lib
npm install
```

Run all the tests:

```sh
gulp test
```

You can also run just the Node.js tests with `gulp test:node`, just the browser tests with `gulp test:browser`
or create a test coverage report (you can open `coverage/lcov-report/index.html` to visualize it) with `gulp coverage`.

## License

repository: qtumproject/qtumcore-lib

gha_license_id: NOASSERTION

repo_name: qtumproject/qtumcore-lib


text:
#
[![Code Climate](https://codeclimate.com/github/nsweeting/qpush/badges/gpa.svg)](https://codeclimate.com/github/nsweeting/qpush) [![Gem Version](https://badge.fury.io/rb/qpush.svg)](https://badge.fury.io/rb/qpush)

Fast and simple job queue microservice for Ruby. **Please consider it under development at the moment.**

QPush provides a scalable solution to your background job processing needs. Its Redis-backed, with support for forking and threading - letting it process an enormous amount of jobs in short order.

As a microservice, QPush is meant to be independent in its operation and deployment. This means that unlike other job processors such as Sidekiq, DelayedJob, etc - QPush does not hook into a web framework. Jobs must therefore be self-sufficent in their operation. This can often lead to better application designs - but also means QPush will have a minimal memory footprint.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'qpush'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install qpush

## Usage

Before starting, ensure you have a functioning Redis server available.

#### The Server

In order to process queued jobs, we run the QPush server. This is a separate service beyond your web application (Rails, Sinatra, etc). To start the server simply type the following in your console.

    $ bundle exec qpush-server -c path/to/config.rb

By providing a path to a configuration file, we can setup QPush with plain old ruby. At a minimum, we should provide details on our Redis server and connections. There are more configuration options available - [all of which can be viewed here](https://github.com/nsweeting/qpush/wiki/Server-Configuration).

```ruby
# QPush server configuration
QPush::Server.configure do |config|
  # Your redis server url and number of connections to provide
  config.redis_url = ENV['REDIS_URL']
  config.redis_pool = 10
end
```

Once the QPush server is running, it will begin processing any queued jobs based on priority.

#### The Client

Before we can add jobs to our server, we must first ensure our client has the same connection to our Redis server. We can setup our configuration in a similar manner as above.

```ruby
require 'qpush'

# QPush client configuration
QPush::Client.configure do |config|
  # Your redis server url and number of connections to provide
  config.redis_url = ENV['REDIS_URL']
  config.redis_pool = 10
end
```

With our client setup, we can now queue jobs on our QPush server. All we have to do is:

```ruby
QPush.job(klass: 'Example::Job', args: { example: 'Job' })
```

The job above would be equivalent to running the following command on the server.

```ruby
Example::Job.new(example: 'Job').call
```

At a minimum, we must provide the job with a 'klass'. There are many more options that we can provide to the job though - [all of which can be viewed here](https://github.com/nsweeting/qpush/wiki/Options-for-Jobs).

#### Building Jobs

Jobs are simply ruby objects that include the QPush::Job module and contain a 'call' method. If you provide a hash for the 'args' of the job, the job will be initialized with them. Below is an example of a simple mailing job utilizing the 'mail' gem.

```ruby
require 'mail'

class MailJob
  include QPush::Job

  def initialize(options = {})
    @mail = Mail.new(options)
  end

  def call
    @mail.deliver
  end
end
```

From our client, we could then queue a mail job with the following:

```ruby
mail_options = { to<EMAIL_ADDRESS>from<EMAIL_ADDRESS>subject: 'Hello!', body: 'From MailJob' }
QPush.job(klass: 'MailJob', args: mail_options)
```

#### Failed Jobs

Jobs that raise an error will be sent to the retry queue. As a default, they are set to attempt a maximum of 10 retries. Each failed attempt creates a longer delay for subsequent attempts. The job will permanently fail once the max retries has been hit.

#### Cron Jobs

QPush supports cron jobs.  For example, the following would perform our job everyday at 4AM UTC.

```ruby
QPush.job(klass: 'Example::Job', args: { example: 'Job' }, cron: '0 4 * * *')
```

#### Relational Databases

Although QPush is designed to independent in its operation, it still provides access to relational databases via Sequel. You can read more about [how to use Sequel here](https://github.com/jeremyevans/sequel). Suffice to say, its quite easy. We first will need to add the required information to our configuration:

```ruby
# You must remember to require the gem for whatever database you will be using.
require 'pg'

# QPush database configuration
QPush::Server.configure do |config|
  # Redis and additional config omitted
  # ....
  # ....
  # Your database server url and number of connections to provide
  config.database_url = ENV['DATABASE_URL']
  config.database_pool = 10
end
```

We can then access the database from any job. For example, we could retrieve all of our users with the following:

```ruby
  QPush.db[:users].all
```
It is recommended that you read up on Sequel before use.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/nsweeting/qpush. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

repository: nsweeting/qpush

repo_name: nsweeting/qpush


text:
# Using Node.js built-in http package

> To view this page on the Jovo website, visit https://www.jovo.tech/docs/hosting/http-host

[Node.js built-in http package](https://nodejs.org/api/http.html)

While this method is compatible with most platforms (such as Google's [AppEngine](https://cloud.google.com/appengine/)), it's also much more complicated than using Express.JS and its middlewares.

## index.js

To make your app work use the HttpHost, open your `index.js` file in the `src` folder, and create a http server using `http.createServer()` :

```javascript
// @language=javascript

// src/index.js

import * as http from "http";
import app from "./app.js";
import HttpHost from "HttpHost";

const port = process.env.JOVO_PORT || 443;
http.createServer(async (req, res) => {
  let body = "";
  req.on("readable", () => {
    const data = req.read();
    if (data) {
      body += data;
    }
  });
  req.on("end", () => {
    app.handle(new HttpHost(req, body, res));
    }
  });
}).listen(port);

// @language=typescript

// src/index.ts

import * as http from "http";
import app from "./app.js";
import HttpHost from "HttpHost";

const port = process.env.JOVO_PORT || 443;

http.createServer(async (req, res) => {
  let body = "";
  req.on("readable", () => {
    const data = req.read();
    if (data) {
      body += data;
    }
  });
  req.on("end", () => {
    app.handle(new HttpHost(req, body, res));
  });
}).listen(port);
```

## Alexa

When you want to deploy your code to a webserver other than AWS Lambda, you need to verify that Alexa Skill requests are actually coming from Amazon. Otherwise [you will not pass the Alexa Certification for your Skill.](https://developer.amazon.com/docs/custom-skills/handle-requests-sent-by-alexa.html).

These can be implemented using the [Alexa-verifier](https://www.npmjs.com/package/alexa-verifier) package.

<!--[metadata]: {"description": "Deploy your Google Actions and Alexa Skills to any server with the Jovo Framework using the Node.js built-in http package",
		        "route": "hosting/http-host"}-->


text:
# hemelb-hoff: "HemelB High Performance Offload"

The aim of the hemelb-hoff project is to allow easy REST-based access to high performance computational resources such as EPCC's CIRRUS service and SURFSara's LISA service. It is intended to seamlessly integrate with the CompBioMed PolNet workflow suite.

## Detailed aims
The existing PolNet suite (implemented as MatLab scripts) supports a workflow that can be run locally on a user's workstation.
However, stages of this workflow can become computationally expensive and it would be advantageous to offload these expensive steps to more powerful remote services.
In order to support this, hemelb-hoff implements a service that provides a set of REST endpoints for submitting and managing computational jobs on remote high performance resources. The REST endpoints can be accessed using any compatible REST client or library, such as the Python requests library.
The project has focussed on providing access to the HemelB software, but is intended to be general purpose.

### Funding and organisation
This project is funded under CompBioMed, work package 5

### Links
PolNet: https://www.ncbi.nlm.nih.gov/pubmed/29742399
CompBioMed: https://www.compbiomed.eu/
EPCC: www.epcc.ed.ac.uk
SURFSara: www.surfsara.nl

repository: EPCCed/hemelb-hoff

repo_name: EPCCed/hemelb-hoff


text:
**Love双手简谱** 和五线谱完全对应。

_Love_ 是美国歌手Lana Del Rey的一首新单曲，于今年2月18日发行。歌曲MV已出，很有质感。

拉娜·德雷（Lana Del Rey）本名Elizabeth Grant，1985年6月21日出生于美国纽约州，美国女歌手、词曲创作者、模特。

歌词下方是 _Love钢琴谱_ ，喜欢的朋友可以免费下载学习。

path: /流行/Love-Lana Del Rey/README.md


text:
# Webpack

<NpmBadge package="@vuepress/bundler-webpack" />

Webpack bundler is provided by [@vuepress/bundler-webpack](https://www.npmjs.com/package/@vuepress/bundler-webpack) package. It is a dependency of the [vuepress-webpack](https://www.npmjs.com/package/vuepress-webpack) package, and you can also install it separately.

```bash
npm i -D @vuepress/bundler-webpack@next
```

## Options

Reference of webpack bundler options:

```ts
import { webpackBundler } from '@vuepress/bundler-webpack'
import { defineUserConfig } from '@vuepress/cli'

export default defineUserConfig({
  bundler: webpackBundler({
    postcss: {},
    vue: {},
  }),
})
```

### configureWebpack

- Type: `(config: WebpackConfiguration, isServer: boolean, isBuild: boolean) => WebpackConfiguration | void`

- Details:

  Edit the internal webpack config.

  This option accepts a function that will receive a webpack config object as the 1st argument, an `isServer` flag as the 2nd argument and an `isBuild` flag as the 3rd argument. You can either mutate the config directly, or return an object to be merged by [webpack-merge](https://github.com/survivejs/webpack-merge).

### chainWebpack

- Type: `(config: WebpackChainConfig, isServer: boolean, isBuild: boolean) => void`

- Details:

  Edit the internal webpack config with [webpack-chain](https://github.com/mozilla-neutrino/webpack-chain).

  This option accepts a function that will receive a `Config` instance that provided by `webpack-chain` as the 1st argument an `isServer` flag as the 2nd argument and an `isBuild` flag as the 3rd argument.

### devServerSetupMiddlewares

- Type: `(middlewares: Middleware[], devServer: Server) => Middleware[]`

- Details:

  A hook to be called in `devServer.setupMiddlewares` of webpack.

  The arguments of the function are those of `devServer.setupMiddlewares`.

- Also see:
  - [Webpack > Configuration > DevServer > devServer.setupMiddlewares](https://webpack.js.org/configuration/dev-server/#devserversetupmiddlewares)

### vue

- Type: `VueLoaderOptions`

- Details:

  Options for `vue-loader`.

- Also see:
  - [vue-loader > Options Reference](https://vue-loader.vuejs.org/options.html)

### postcss

- Type: `PostcssLoaderOptions`

- Details:

  Options for `postcss-loader`.

- Also see:
  - [postcss-loader > Options](https://github.com/webpack-contrib/postcss-loader#options)

### stylus

- Type: `StylusLoaderOptions`

- Details:

  Options for `stylus-loader`.

- Also see:
  - [stylus-loader > Options](https://github.com/webpack-contrib/stylus-loader#options)

### scss

- Type: `SassLoaderOptions`

- Details:

  Options for `sass-loader` for `.scss` files.

- Also see:
  - [sass-loader > Options](https://github.com/webpack-contrib/sass-loader#options)

### sass

- Type: `SassLoaderOptions`

- Details:

  Options for `sass-loader` for `.sass` files.

- Also see:
  - [sass-loader > Options](https://github.com/webpack-contrib/sass-loader#options)

### less

- Type: `LessLoaderOptions`

- Details:

  Options for `less-loader`.

- Also see:
  - [less-loader > Options](https://github.com/webpack-contrib/less-loader#options)

### evergreen

- Type: `boolean`

- Default: `true`

- Details:

  Set to `true` if you are only targeting evergreen browsers. This will disable some transpilation and polyfills, and result in faster builds and smaller files.

## FAQ

### Referencing Public Files after Changing `base`

Unlike Vite, Webpack won't handle `base` for public files automatically. So if you change the `base` of your site, you'd better to use [Base Helper](../../guide/assets.md#base-helper) when referencing an public image file.

### Using with Default Theme

Default theme is using [SASS](https://sass-lang.com/) as CSS pre-processor, so you might need to install [sass-loader](https://www.npmjs.com/package/sass-loader) as a peer dependency to make it work with Webpack, especially when you are using [pnpm](https://pnpm.io/).


text:
# Demo1 README

## Preface 前言

This article is based on the principle of Github open source P4Demo: Source_Routing.

Before proceeding to the next step, please read the introduction of the Github project : [Github: SourceRouting](https://github.com/p4lang/tutorials/tree/master/SIGCOMM_2015#exercise-1-source-routing)

本文基于Github开源P4Demo：Source_Routing的原理进行实验。

在进行接下来的步骤之前，请阅读Github项目介绍：[Github: SourceRouting](https://github.com/p4lang/tutorials/tree/master/SIGCOMM_2015#exercise-1-source-routing)

## Principle 原理

1.The EasyRoute Protocol packet used in the experiment is structured as follows:

  实验中使用的 EasyRoute Protocol 数据报结构如下：
```
preamble (8 bytes) | num_valid (4 bytes) | port_1 (1 byte) | port_2 (1 byte) |
... | port_n (1 byte) | payload
```

2.Topo：

  拓扑

3.Introduction:

  介绍：

  This experiment was based on the original P4 program provided by Barefoot, and making some changes.

  本实验首先基于Barefoot提供的原始P4程序，进行了相关的改动。

the original P4 program as follow:

原始P4程序如下：

```
/*
Copyright 2013-present Barefoot Networks, Inc.

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

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

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

header_type easyroute_head_t {
    fields {
        preamble: 64;
        num_valid: 32;
    }
}

header easyroute_head_t easyroute_head;

header_type easyroute_port_t {
    fields {
        port: 8;
    }
}

header easyroute_port_t easyroute_port;

parser start {
    return select(current(0, 64)) {
        0: parse_head;
        default: ingress;
    }
}

parser parse_head {
    extract(easyroute_head);
    return select(latest.num_valid) {
        0: ingress;
        default: parse_port;
    }
}

parser parse_port {
    extract(easyroute_port);
    return ingress;
}

action _drop() {
    drop();
}

action route() {
    modify_field(standard_metadata.egress_spec, easyroute_port.port);
    add_to_field(easyroute_head.num_valid, -1);
    remove_header(easyroute_port);
}

table route_pkt {
    reads {
        easyroute_port: valid;
    }
    actions {
        _drop;
        route;
    }
    size: 1;
}

control ingress {
    apply(route_pkt);
}

control egress {
    // leave empty
}
```

**modification**:

**改动：**

1.Add a register `Register_Count` and set it to the **direct** state.

  增加一个寄存器`Register_Count`，并设置为direct状态。

2.Add a flow table named `Count_Table`, the flow table contains the action `_drop` and `Read_Register`. The incoming packets are matched by its port number. We deployed the runtime commands to the switch so that the switch can generate flow entries to execute actions for matched packets. The action `Read_Register` executed as soon as the field `easyroute_port` of the incoming packet was the port 3. The switch drop the packet which is the default action of the flow table if the packet didn't find its matched entry.

  增加一张名为Count_Table的流表，流表内含动作`_drop`与`Read_Register`。该流表根据端口进行匹配：倘若字段easyroute_port与3相匹配，执行动作`Read_Register`；同时设置默认动作`_drop`，当没有匹配到表项时执行丢包。

3.Action `Read_Register`: Logs the information in the register into the metadata.

  动作`Read_Register`：将寄存器中的信息记录到元数据中。

4.Control program: look up the table `Count_Table`  first, and then through the `if`  statement to determine whether the register recorded in metadata is equal to 0 : Yes to route, not the words do not route.

  流控制程序：先查找表`Count_Table`，之后通过if语句判断元数据中记录的寄存器信息是否等于0：是的话执行路由，不是的话不执行路由

  P4 program which is modified:

  改动后的P4程序：

```
/*
Copyright 2013-present Barefoot Networks, Inc.

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

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

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

/*
    Demo 1, FuZhou University, SDNLAB, Chen, 2017/1/11
*/

#define Match_Drop_Num 00000000

header_type easyroute_head_t
{
    fields
    {
        preamble : 64;

        num_valid : 32;
    }
}

header easyroute_head_t easyroute_head;

header_type easyroute_port_t
{
    fields
    {
        port : 8;
    }
}

header easyroute_port_t easyroute_port;

parser start
{
    return select(current(0, 64))
    {
        0 : parse_head;

        default : ingress;
    }
}

parser parse_head
{
    extract(easyroute_head);

    return select(latest.num_valid)
    {
        0 : ingress;
        default : parse_port;
    }
}

parser parse_port
{
    extract(easyroute_port);

    return ingress;
}

action _drop()
{
    drop();
}

header_type Register_Meta_t
{
    fields
    {
        register_tmp : 8;
    }
}

metadata Register_Meta_t Register_Meta;

register Register_Count
{
    width : 32;
    direct : Count_Table;
}

action Read_Register(register_index)
{
    register_read(Register_Meta.register_tmp, Register_Count, register_index);
}

/*
    command.txt:

    table_add Count_Table Read_Register 00000101 => 1
*/

table Count_Table
{
    reads {
        easyroute_port.port : exact;
    }

    actions {

        Read_Register;

        _drop;
    }
}

action route()
{
    modify_field(standard_metadata.egress_spec, easyroute_port.port);

    add_to_field(easyroute_head.num_valid, -1);

    remove_header(easyroute_port);
}

table route_pkt {

    reads {
        easyroute_port: valid;
    }

    actions {

        _drop;

        route;
    }

    size: 1;
}

control ingress
{
    apply(Count_Table);

    if (Register_Meta.register_tmp <= Match_Drop_Num)
    {
        apply(route_pkt);
    }
}

control egress {
    // leave empty
}
```

## Experimental steps 实验步骤

Before executing this experiment, please complete the blog :the content of [Run P4 without p4factory](http://www.cnblogs.com/qq952693358/p/6195385.html) .

在执行本实验之前，请先完成博客：[Run P4 without p4factory](http://www.cnblogs.com/qq952693358/p/6195385.html) 的内容。

*** Starting CLI:
mininet>
```

2.Open xterm of h1 and h2：

  打开h1，h3的xterm：

```
mininet> xterm h1 h3
```

3.Execute the command in the terminal of h3:

  在h3的终端中执行：

```
./receive.py
```

4.Execute the command in the terminal of h1:

  在h1的终端中执行：

```
./send.py h1 h3
```

5.Input `Hello` in the terminal of h1 , and `Hello` appears in the terminal of h3.

  在h1的终端中输入`Hello`，在h3的终端中出现“Hello”字样。

## Comparative experiment 对比实验

Restart, then change the control program of P4 program to:

重启，将P4程序中的流控制程序改为：

```
control ingress
{
    apply(Count_Table);

    if (Register_Meta.register_tmp > Match_Drop_Num)
    {
        apply(route_pkt);
    }
}
```

Re-implementation of the above steps of the experimental phenomenon: in h1 to send information, h3 can not receive.

重新执行上述实验步骤，观察得到实验现象：在h1中发送信息，h3无法接收。

## Conclusion 实验结论

This experiment is a validated test that verifies the following function: The incoming packets would be routed when the field `easyroute_port` of the incoming packet was the port 3; otherwise,it would be dropped by the switch.

本实验为验证性实验，验证以下功能：只有当当前数据报的端口为3时，才执行路由；否则执行丢包。

In the experiment, the P4 switch allocates the configuration generated by the P4 program and adds the entry to the flow table according to the runtime CLI.

实验中，P4交换机部署P4程序生成的相关配置，同时根据运行时CLI为流表添加表项。


text:
# Changelog

All notable changes to this project will be documented in this file, in reverse chronological order by release.

## 2.4.4 - 2015-07-21

### Added

- Nothing.

### Deprecated

- Nothing.

### Removed

- Nothing.

### Fixed

- [#9](https://github.com/zendframework/zend-stdlib/pull/9) fixes an issue with
  count incrementation during insert in PriorityList, ensuring that incrementation only
  occurs when the item inserted was not previously present in the list.

repository: IsaiasMorochi/Gestiondocumental

gha_language: HTML

repo_name: IsaiasMorochi/Gestiondocumental