text:
### Qap

[![NPM VERSION](http://img.shields.io/npm/v/qap.svg?style=flat)](https://www.npmjs.org/package/qap)
[![CODACY BADGE](https://img.shields.io/codacy/b18ed7d95b0a4707a0ff7b88b30d3def.svg?style=flat)](https://www.codacy.com/public/44gatti/qap)
[![CODECLIMATE-TEST-COVERAGE](https://img.shields.io/codeclimate/coverage/github/rootslab/qap.svg?style=flat)](https://codeclimate.com/github/rootslab/qap)
[![LICENSE](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://github.com/rootslab/qap#mit-license)

![NODE VERSION](https://img.shields.io/node/v/qap.svg)
[![TRAVIS CI BUILD](http://img.shields.io/travis/rootslab/qap.svg?style=flat)](http://travis-ci.org/rootslab/qap)
[![BUILD STATUS](http://img.shields.io/david/rootslab/qap.svg?style=flat)](https://david-dm.org/rootslab/qap)
[![DEVDEPENDENCY STATUS](http://img.shields.io/david/dev/rootslab/qap.svg?style=flat)](https://david-dm.org/rootslab/qap#info=devDependencies)

[![NPM MONTHLY](http://img.shields.io/npm/dm/qap.svg?style=flat)](http://npm-stat.com/charts.html?package=qap)
![NPM YEARLY](https://img.shields.io/npm/dy/qap.svg)

[![NPM GRAPH](https://nodei.co/npm/qap.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/qap/)

 * __Qap__ is a quick parser for string or buffer patterns.
 * It is optimized for using with pattern strings <= 255 bytes.
 * Better results are achieved with long and sparse patterns.
 * It is an implementation of QuickSearch algorithm.

### Main features

> Given a m-length pattern and n-length data and σ-length alphabet ( σ = 256 ):

 - simplification of the Boyer-Moore algorithm ( *see [Bop](https://github.com/rootslab/bop)* ).
 - uses only a bad-character shift table.
 - preprocessing phase in __O(m+σ)__ time and __O(σ)__ space complexity.
 - searching phase in __O(m*n)__ time complexity.
 - very fast in practice for short patterns and large alphabets.

> See __[Lecroq](http://www-igm.univ-mlv.fr/~lecroq/string/node19.html)__ for reference and also __[Bop](https://github.com/rootslab/bop)__, a Boyer-Moore parser.

### Install
```bash
$ npm install qap [-g]
```

> __require__:

```javascript
var Qap = require( 'qap' );
```

### Run Tests

```javascript
$cd qap/
$npm test
```

### Run Benchmarks

```bash
$ cd qap/
$ npm run-script bench
```

### Constructor

> Create an instance with a Buffer or String pattern.

```javascript
Qap( Buffer || String pattern )
// or
neq Qap( Buffer || String pattern )
```

### Methods

> List all pattern occurrences into a String or Buffer data.
> It returns a new array of indexes, or populates an array passed as the last argument to parse method.

```javascript
// slower with String
Qap#parse( String data [, Number startFromIndex [, Number limitResultsTo [, Array array ] ] ] ) : Array

// faster with Buffer
Qap#parse( Buffer data [, Number startFromIndex [, Number limitResultsTo [, Array array ] ] ] ) : Array
```

> Change the pattern :

```javascript
Qap#set( Buffer || String pattern ) : Buffer
```

### Usage Example

```javascript
var log = console.log
    , assert = require( 'assert' )
    , Qap = require( 'qap' )
    , pattern = 'hellofolks\r\n\r\n'
    , text = 'hehe' + pattern +'loremipsumhellofolks\r\n' + pattern
    , bresult = null
    ;

// create an instance and parse the pattern
var qap = Qap( pattern )
    // parse data from beginning
    , results = qap.parse( text )
    ;

// set a new Buffer pattern
qap.set( new Buffer( pattern ) );

// parse data Buffer instead of a String
bresults = qap.parse( new Buffer( text ) );

// parser results ( starting indexes ) [ 4, 40 ]
log( results, bresults );

// results are the same
assert.deepEqual( results, bresults );

```

#### Benchmark for a small pattern ( length <= 255 bytes )

> Parser uses a Buffer 256-bytes long to build the shifting table, then:

> - Pattern parsing / table creation space and time complexity is O(σ).
> - Very low memory footprint.
> - Ultra fast to preprocess pattern ( = table creation ).

```bash
  $ node bench/small-pattern-data-rate
```

for default it:

> - uses a pattern string of 57 bytes/chars
> - builds a data buffer of 700 MB in memory
> - uses a redundancy/distance factor for pattern strings equal to 2. The bigger the value,
the lesser are occurrences of pattern string into the text buffer.

 **Custom Usage**:

```bash
  # with [testBufferSizeInMB] [distanceFactor] [aStringPattern]
  $ node bench/small-pattern-data-rate.js 700 4 "that'sallfolks"
```

#### Benchmark for a big pattern ( length > 255 bytes )

> Parser uses one Array to build the shifting table for a big pattern, then:

> - table has a size of 256 elements, every element is an integer value that
> could be between 0 and the pattern length.
> - Fast to preprocess pattern ( = table creation ).
> - Low memory footprint

```bash
  $ node bench/big-pattern-data-rate
```

> - it uses a pattern size of 20MB
> - builds a data buffer of 300MB copying pattern 12 times

See __[bench](./bench)__ dir.

### MIT License

> Copyright (c) 2013-present < Guglielmo Ferri<EMAIL_ADDRESS>>

> 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.__

> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
> 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: ilioner/TYZTorrentMagentTools

repo_name: ilioner/TYZTorrentMagentTools


text:
# lab02

Vij and Andrew did pair programming on day 1
Andrew did not have laptop, so vij drove, while Andrew navigated.
On day 2, vij navigated feature 1-2, and andrew completed feature 1, and addressed 3,4.

Lab 01
Number and name of feature: __________Display Images- Feature One______________________

Estimate of time needed to complete: _30min____

Start time: __0940___

Finish time: _1039____

Actual time needed to complete: __40min___

Add this information to your README.

Number and name of feature: _____Feature 2: filter images___________________________

Estimate of time needed to complete: __60min___

Start time: __10:40___

Finish time: ___1:40__

Actual time needed to complete: _3hours____

Number and name of feature: _____________Feature _________

Estimate of time needed to complete: _____

Start time: _____

Finish time: _____

Actual time needed to complete: _____

Number and name of feature: Lab3 Feature 1

Estimate of time needed to complete: 60mins

Start time: 10:07

Finish time: 10:32

Actual time needed to complete: 25mins

Number and name of feature: Lab3 Feature 2

Estimate of time needed to complete: 60mins

Start time: 10:34

Finish time: 11:49

Actual time needed to complete: 75mins

Number and name of feature: Lab3 Feature 3

Estimate of time needed to complete: 45mins

Start time: 12:30

Finish time: 1:30

Actual time needed to complete: 1hr

license: MIT

branch_name: refs/heads/master

extension: md

gha_language: JavaScript

gha_license_id: MIT

license_type: permissive


text:
# opengl-simple-snake

The project was created using http://www.codeblocks.org/

![game window](https://github.com/rodjjo/opengl-simple-snake/blob/master/img/snake-game.jpg?raw=true)

An snake game in c++ and opengl.

repository: rodjjo/opengl-simple-snake

repo_name: rodjjo/opengl-simple-snake


text:
# API APP HELLO WORLD PROJECT

For original details see the BOTOM of this readme.md file...

## DAILY JOURNAL by MV

REFERENCE IN DOCS.MICROSOFT.COM:

https://docs.microsoft.com/en-us/azure/app-service/containers/quickstart-python?tabs=bash

### 2020 05 14 MV:
- CONTINUED work...
- INSPECTED exception message...
- THEORY: my using "-l northcentralus" WASN'T a VALID location?
- CHANGE location to "-l centralus" per sample article
- RE-DEPLOYED
- - => SUCCESSFUL deployment to https://mvhelloworld.azurewebsites.net !!
- ADDED additional app route "/detectpage"
- RE-DEPLOYED
- - => SUCCESSFUL deployment to https://mvhelloworld.azurewebsites.net/detectpage !!
- ADDED mock JSON returns to above app route
- RE-DEPLOYED
- - => SUCCESSFUL deployment & function !
- - BROWSING to https://mvhelloworld.azurewebsites.net/detectpage
-- returns mock JSON  {key1:value1, key2:value2, key3:value3}
- PAUSED on THIS app - time to CLONE, RENAME and EXPAND !!!
- UPDATED readme.md (this file)
- COMMITTED and PUSHED...

### 2020 05 13 MV:
- CONTINUED work on this API App...
- PREPARED to deploy this helloworld app actuall to the Azure Cloud Services
- INSTALLED AzureCLI (for linux) on thing1
- - => SUCCESSFUL :-)
- RAN commands (locally on thing1 using AzureCLI invoked from VSCode's integrated terminal)
- ATTEMPTED deploy-to-AzureCloud of "mvhelloworld" API app as follows:
- - $ az webapp up --sku F1 -n "mvhelloworld"
- - => EXCEPTION immediately
- - exception related to MISSING "location" parame (required in AzureCLI 2.5.0 and above)
- ATTEMPTED deploy-to-AzureCloud of mvhelloworld API app as follows:
- - $ az webapp up --sku F1 -n "mvhelloworld" -l northcentralus
- - => EXCEPTION after 30+ minutes; NOT sure WHY :-( ...
- PAUSED for the night

### 2020 05 12 MV:
- FORKED project to cloud repo in github.com (no changes)
- CLONED project down to thing1
- READ reference (see above)
- RAN project as-is ==> SUCCESFUL :-)

#########################################################################
#########################################################################

---
page_type: sample
description: "This is a minimal sample app that demonstrates how to run a Python Flask application on Azure App Service on Linux."
languages:
- python
products:
- azure
- azure-app-service
---

# Python Flask sample for Azure App Service (Linux)

This is a minimal sample app that demonstrates how to run a Python Flask application on Azure App Service on Linux.

For more information, please see the [Python on App Service quickstart](https://docs.microsoft.com/azure/app-service/containers/quickstart-python).

## Contributing

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode<EMAIL_ADDRESS>with any additional questions or comments.

repository: markvogt/python-docs-hello-world

repo_name: markvogt/python-docs-hello-world


text:
+++
title = "Fault Injection"
description = "Linkerd provides mechanisms to programmatically inject failures into services."
+++

Fault injection is a form of chaos engineering where the error rate of a service
is artificially increased to see what impact there is on the system as a whole.
Traditionally, this would require modifying the service's code to add a fault
injection library that would be doing the actual work. Linkerd can do this
without any service code changes, only requiring a little configuration.

To inject faults into your own services, follow the [tutorial](../../tasks/fault-injection/).

repository: linkerd/website

branch_name: refs/heads/main

repo_name: linkerd/website


text:
# How to restore the data that is deleted by mistake {#concept_zzm_5qs_gfb .concept}

By taking CentOS 7 for example, this document introduces how to use Extundelete, an open source tool, to quickly restore accidentally deleted data.

## Overview {#section_gvz_vkx_gfb .section}

In practice, data may be deleted accidentally. In this case, how to restore the data quickly and effectively? Alibaba Cloud offers several ways to restore data, for example:

-   Roll back a [snapshot](../../../../reseller.en-US/User Guide/Snapshots/Create a snapshot.md#) or [custom image](../../../../reseller.en-US/User Guide/Images/Create custom image/Create a custom image by using a snapshot.md#) through the ECS console.
-   Purchase several ECS instances to implement [load balancing](../../../../reseller.en-US/Product Introduction/What is Server Load Balancer?.md#) and high availability for your services.
-   Use [Object Storage Service \(OSS\)](../../../../reseller.en-US/Product Introduction/What is OSS?.md#) to store a massive amount of data such as web pages, images, and videos.

There are a variety of open source data recovery tools for Linux, such as debugfs, R-Linux, ext3grep, Extundelete, and more. Of them, ext3grep and Extundelete are generally used. Both tools adopt the same recovery techniques, just that Extundelete is more powerful.

Extundelete is a Linux-based open source data recovery software. When using Linux instances, you can install this tool conveniently to quickly restore the data deleted accidentally as no Recycle Bin is available in Linux.

Extundelete can locate the position of an inode block by combining the inode information and logs so as to search for and restore the desired data. This powerful tool supports the disk-wide restoration of ext3/ext4 dual-format partitions.

Once data is deleted accidentally, firstly you need to unmount the disk or disk partition that contains the deleted data. This is because after a file is deleted, only the inode pointers of the file are zeroed while the actual file is still stored on the disk. If the disk is mounted in read/write mode, data blocks of the deleted file may be reallocated by the operating system. Once the data blocks are overwritten by new data, the original data will be lost completely, and cannot be restored by any means. Therefore, mounting a disk in read-only mode can reduce the risk of overwriting the data in blocks, thus improving the chances of restoring the data successfully.

**Note:** During the online restoration process, do not install Extundelete on the disk that has the deleted file. Otherwise, the data to be restored might be overwritten. Keep in mind to back up the disk by taking a snapshot before any operations.

## Intended audience {#section_gtk_qmx_gfb .section}

-   Users who accidentally delete files on a disk and no write operations have been performed on the disk after the deletion.
-   Users whose websites have low traffic and who have few ECS instances.

## Procedure {#section_jbx_rmx_gfb .section}

Software release: e2fsprogs-devel e2fsprogs gcc-c++ make \(compiler and more\) Extundelete-0.2.4.

**Note:** The libext2fs 1.39 or above is required for the normal operation of Extundelete. For ext4 support, however, make sure e2fsprogs 1.41 or higher is provided \(you can run the command dumpe2fs to check the version output\).

The above releases are available when this document is being written. Your downloads may be different.

-   **Deploy Extundelete**

    ```
    wget  http://zy-res.oss-cn-hangzhou.aliyuncs.com/server/extundelete-0.2.4.tar.bz2
    yum -y install  bzip2  e2fsprogs-devel  e2fsprogs  gcc-c++  make    #Install related dependencies and libraries
    tar -xvjf extundelete-0.2.4.tar.bz2
    cd extundelete-0.2.4                                #Enter the program directory
    ./configure                                         #Installed successfully as shown below
    ```

    ![](http://static-aliyun-doc.oss-cn-hangzhou.aliyuncs.com/assets/img/9801/154140567112896_en-US.png)

    ```
    make && make install
    ```

    At this point, the src directory appears. It contains an Extundelete executable file and a corresponding path. As shown below, the default file is installed in usr/local/bin, and the following demo is made in the usr/local/bin directory.

-   **Delete a file and use Extundelete to restore it**

    1.  Check the available disks and partitions of your ECS instance, then format and partition the /dev/vdb partition. For more information about formatting and partitioning, see [Format and mount a data disk](../../../../reseller.en-US/Quick Start for Entry-Level Users/Step 4. Format a data disk/Format a data disk for Linux instance.md#).

        ```
        fdisk -l
        ```

        ![](http://static-aliyun-doc.oss-cn-hangzhou.aliyuncs.com/assets/img/9801/154140567112898_en-US.png)

    2.  Mount the partitioned disk under the /zhuyun directory, and then create a file named hello.

        ```
        mkdir /zhuyun                                #Create the zhuyun directory.
        mount /dev/vdb1 /zhuyun                      #Mount the disk under the zhuyun directory.
        echo test > hello                            #Create a test file.
        ```

    3.  Run the md5sum command to generate the MD5 value of the file and note it down. You can compare the MD5 values of the file before and after the deletion to verify its integrity.

        ```
        md5sum hello
        ```

        ![](http://static-aliyun-doc.oss-cn-hangzhou.aliyuncs.com/assets/img/9801/154140567112899_en-US.png)

    4.  Delete the hello file.

        ```
        rm -rf hello
        cd ~
        fuser -k /zhuyun                     #Terminate the process tree that uses a certain partition (skip this if you are sure that no resources are occupied).
        ```

    5.  Unmount the data disk

        ```
        umount /dev/vdb1                     #Before using any file restoration tool, unmount or mount the partitions to be restored in read-only mode to prevent their data from being overwritten.
        ```

    6.  Use Extundelete to restore the file.

        ```
        extundelete --inode 2 /dev/vdb1       #Query the contents in a certain inode. Using "2" means to search the entire partition. To  search a directory, just specify the inode and directory. Now you can see the deleted file and inode.
        ```

        ![](http://static-aliyun-doc.oss-cn-hangzhou.aliyuncs.com/assets/img/9801/154140567112900_en-US.png)

        ```
        /usr/local/bin/extundelete  --restore-inode 12  /dev/vdb1    #Restore the deleted file.
        ```

        At this point, the RECOVERED\_FILES directory appears under the directory where the command is executed. Check whether the file is restored.

        ![](http://static-aliyun-doc.oss-cn-hangzhou.aliyuncs.com/assets/img/9801/154140567112901_en-US.png)

        Check the MD5 values of the files before and after deletion. If they are the same, restoration is successful.

        ```
        --restore-inode 12                  # --restore-inode Restore by the specified inode.
        --extundelete --restore-all         # --restore-all   Restore all.
        ```

url: https://raw.githubusercontent.com/qmutz/ecs/469837b0855af1486a04065a90314e446f8eb25f/intl.en-US/Best Practices/Data recovery/How to restore the data that is deleted by mistake.md

repository: qmutz/ecs

repo_name: qmutz/ecs


text:
# Context Menu

> Create a new button in a context menu.

This is a basic example to show how to add a new entry to an existent context menu.

![context menu example](preview.gif)

In JupyterLab plugins can expose context menus to offer an easy way to execute commands and perform actions. In this example, you will learn how to add a new entry to the file browser context menu to be displayed on files with extension `.example`.

> It is strongly recommended to read [commands](https://github.com/jupyterlab/extension-examples/tree/main/commands) example before diving into this one.

To implement this example you need to install the `@jupyterlab/filebrowser`, where you can find the interface `IFileBrowserFactory` necessary to require the file browser instance of JupyterLab.

> This is not necessary to create a context menu. But it is a common case to be extended.

First of all, you will start looking into the declaration of the extension:

<!-- prettier-ignore-start -->
```ts
// src/index.ts#L9-L14

const extension: JupyterFrontEndPlugin<void> = {
  id: '@jupyterlab-examples/context-menu:plugin',
  description: 'A minimal JupyterLab example to develop a context-menu.',
  autoStart: true,
  requires: [IFileBrowserFactory],
  activate: (app: JupyterFrontEnd, factory: IFileBrowserFactory) => {
```
<!-- prettier-ignore-end -->

For this extension, you need to require `IFileBrowserFactory` to track the file browser item clicked by the user.

The first step is to define the command that will be executed when clicking on the context menu entry. If you want to access the item information, you need to use the `IFileBrowserFactory` object to obtain the file browser selected item.

<!-- prettier-ignore-start -->
```ts
// src/index.ts#L15-L32

app.commands.addCommand('jlab-examples/context-menu:open', {
  label: 'Example',
  caption: "Example context menu button for file browser's items.",
  icon: buildIcon,
  execute: () => {
    const file = factory.tracker.currentWidget
      ?.selectedItems()
      .next().value;

    if (file) {
      showDialog({
        title: file.name,
        body: 'Path: ' + file.path,
        buttons: [Dialog.okButton()]
      }).catch(e => console.log(e));
    }
  }
});
```
<!-- prettier-ignore-end -->

Then, you can add the command to a context menu using the settings file.
You will need to define a context menu item under the property `context` of the special key
`jupyter.lab.menus`. And the properties of the context menu item are:

- `command`: the command to execute.
- `selector`: the CSS classes of the element on which you want to add the entry.
- `rank`: (optional) number to order the context menu entries

<!-- prettier-ignore-start -->
```json5
// schema/plugin.json#L4-L12

"jupyter.lab.menus": {
  "context": [
    {
      "command": "jlab-examples/context-menu:open",
      "selector": ".jp-DirListing-item[data-file-type=\"text\"]",
      "rank": 0
    }
  ]
},
```
<!-- prettier-ignore-end -->

The `selector` can be any valid [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors). In this case, the first part is the CSS class that identifies the file browser items `.jp-DirListing-item` and the second part `[data-file-type="text"]` is a attribute value to be found on the item; the `data-file-type` attribute is set with the file type name or `text` for generic files. You can omit the second part to add the command to every file type.

You can find some of the CSS classes that identify different widgets in JupyterLab in the [developer documentation](https://jupyterlab.readthedocs.io/en/stable/developer/css.html#commonly-used-css-selectors).

> See also the [documentation](https://jupyterlab.readthedocs.io/en/stable/extension/extension_points.html#context-menu).

repository: jupyterlab/extension-examples

gha_language: TypeScript

repo_name: jupyterlab/extension-examples


text:
[[keywords|Keyword]]: `some`, `in`

A **choice function** is a special form of [[definition]] that introduces a different [[axiom]] than usual: one with an implication operator (`->`) guarded by an [[existential quantifier]].

## Example:

Suppose we want to define a function `finv` that is the inverse of function `f`. We can write the definition like this:

```
definition finv(X) = some Y. f(Y) = X in Y
```

This special form of definition says that `finv(X)` is `Y` for *some* `Y` such that `f(Y) = X`. If there is no such `Y`, `finv(X)` is left undefined. The corresponding axiom is:

```
axiom forall X. ((exists Y. f(Y) = X) -> f(finv(X)) = X)
```

With this definition, `finv` is a function, but it isn't fully specified.  If a given element `Y` has two inverses, `finv` will yield one of them. This isn't a [[nondeterministic choice]], however. Since `f` is a function, it will always yield the *same* inverse of any given value `Y`.

If we want to specify the value of `finv` in case there is no inverse, we can write the definition like this:

```
definition finv(X) = some Y. f(Y) = X in Y else 0
```

The `else` part gives us this additional axiom:

```
axiom forall X. ((~exists Y. f(Y) = X) -> finv(X) = 0)
```

Notice that this axiom contains a quantifier alternation. If this is a problem, we could use a macro instead:

```
definition finv(x) = some Y. f(Y) = x in Y else 0
```

The axiom we get is

```
axiom (~exists Y. f(Y) = x) -> finv(x) = 0)
```

which is alternation-free.

repository: graydon/ivy-notes

path: /markdown/choice function.md

filename: choice function.md

repo_name: graydon/ivy-notes


text:
Name: Muhammad Fakrulfikri Auzaie Bin rohizam

A project for my university final year project (UKM)

# Check Symptom
A Flask Python program that is used as an API to determine the disease with the highest probability, based on given symptoms in Bahasa Melayu. Result (disease name) will also be in Bahasa Melayu. Algo idea by itachi9604/healthcare-chatbot which has been modified to suit the current project's needs.

An absolute beginner. Any help and advice will be appreciated.

## Update
- Changed the symptom and disease database language to Bahasa Melayu.
- Automatic deploy to Heroku PaaS is enabled.
- The working repository has been backed up.
- Stable version has been uploaded.

### How it works
- Use PaaS (Platform as a Service) website/platform to connect to the Git repositories.
- Make sure to set the Dyno type to web.
- Link the connected service as an API to other applications such as android apk.

### I/O
- Input: 5 symptoms from the documented symptoms/diseases data collection.
- Output: 1 possible disease based on symptoms given.

Will update more in the future.

repository: fakrulfikri/MySimptom-diagnosis

repo_name: fakrulfikri/MySimptom-diagnosis


text:
# @cennznet/types

CENNZnet runtime type definitions

## Update metadata + types
1) Add new modules to interfaces/update existing definitions to include additional type stubs and RPC methods.
2) Start a node with the target runtime
3) Run the following
```bash
# Get metadata from local CENNZnet node running target version
curl -H "Content-Type: application/json" -d '{"id":"1", "jsonrpc":"2.0", "method": "state_getMetadata", "params":[]}' http://localhost:9933 > cennznet.json

yarn build
```

branch_name: refs/heads/develop


text:
# Testing

## Unit Tests

```
npm run test:unit
```

Each `src/**/*.ts` source file should have an equivalent `*.test.ts` next to it.
Tests should include comments above each section of the "AAA" testing format:

-   `// Arrange`: Set up dependencies for the code under test
-   `// Act`: Perform the logic under test
-   `// Assert`: Check the results of the acted logic

`tslint-to-eslint-config` requires 100% unit test coverage, excluding the following:

-   `src/cli/main.ts`
-   `src/adapters/*.ts`
-   `src/**/*.stubs.ts`

See [Dependencies](./Dependencies.md) for how static dependencies are stubbed out in functions.
That system is how functions can receive stubs and spies during unit tests.

## End-to-End Tests

```shell
npm run test:end-to-end
```

End-to-end tests that execute the `bin/tslint-to-eslint` command and validate outputs are generated from the directories in `test/tests/`.
Each directory there contains:

-   `test.ts`: Test file that runs `createTests(__dirname);` to set up tests in that directory
-   `.eslintrc.json`: `.gitignore`d output from the most recent test run
-   `expected.json`: Expected output ESLint configuration
-   `stderr.txt`: Expected output written to the process `stderr`
-   `stdout.txt`: Expected output written to the process `stdout`
-   `tslint.json`: Original TSLint configuration file to convert

Within each directory, a test suite will execute `bin/tslint-to-eslint` and validate the outputs match what's on disk.

Use `npm run test:end-to-end:accept` to overwrite the expected contents of files with what is actually written.
These behave similarly to updating snapshots in snapshot testing.

> Note: these end-to-end tests use the compiled result of `npm run tsc`, so if you update source code, re-run `npm run tsc` before `npm run test:end-to-end`.

repository: YashdalfTheGray/tslint-to-eslint-config

repo_name: YashdalfTheGray/tslint-to-eslint-config


text:
# Joplin Generate Tags Plugin

Plugin for Joplin which can be used to extract keywords from note and assign them as a note's tags.

# Demo
![Demo](img/demo.gif)

## Installation

### Automatic

- Go to `Tools > Options > Plugins`
- Search for `Tags Generator`
- Click Install plugin
- Restart Joplin to enable the plugin

### Manual

- Download the latest released JPL package (`joplin.plugin.forcewake.tags-generator.jpl`) from [here](https://github.com/forcewake/joplin-tags-generator/releases/latest)
- Close Joplin
- Copy the downloaded JPL package in your profile `plugins` folder
- Start Joplin

## Commands

- `Generate tags`

### Generate tags

Uses several awesome [unified](https://github.com/unifiedjs) packages in order to process, analyse and extract keywords from *english-based markdown* only notes.

- Select one note (markdown and written in English)
- Click on `Tools > Generate tags...` or use the command `Generate tags...` from the context menu or use the Command palette and find the command `Generate tags...`.

## Keyboard Shortcuts

Under `Options > Keyboard Shortcus` you can assign a keyboard shortcut for `Generate tags...` command.

## Build

To build your one version of the plugin, install node.js and run the following command `npm run dist`

## Updating the plugin framework

To update the plugin framework, run `npm run update`

## Links

- [Joplin - Getting started with plugin development](https://joplinapp.org/api/get_started/plugins/)
- [Joplin - Plugin API reference](https://joplinapp.org/api/references/plugin_api/classes/joplin.html)
- [Joplin - Data API reference](https://joplinapp.org/api/references/rest_api/)
- [Joplin - Plugin examples](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins)

repository: forcewake/joplin-tags-generator

repo_name: forcewake/joplin-tags-generator


text:
---
layout: default
---

# 1994-12-05 - RE: cypher bickering

## Header Data

From: Johnathan Corgan<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: 74e432c98a1bdff847d8672fadcfca4ad22cf8ca1c8898649089788bd5f146db

Message ID: \<Chameleon.4.00.941205083437.jcorgan@\>

Reply To: _N/A_

UTC Datetime: 1994-12-05 16:35:09 UTC

Raw Date: Mon, 5 Dec 94 08:35:09 PST

## Raw message

```
{% raw  %}From: Johnathan Corgan<EMAIL_ADDRESS>Date: Mon, 5 Dec 94 08:35:09 PST
To<EMAIL_ADDRESS>Subject: RE: cypher bickering
Message-ID: <Chameleon.4.00.941205083437.jcorgan@>
MIME-Version: 1.0
Content-Type: text/plain

-----BEGIN PGP SIGNED MESSAGE-----

>In the paper world, I send out many things that I don't sign.  I
>don't sign them because it is of no significance that it be proven that I sent
>it.  It also might be that the information is of such a general nature that it
>makes no neverminds who sent it.  I submit that digital signatures are the same
>way.

While I agree with this, there is another, more practical reason to use
cryptography for everyday, non-sensitive material.  This may seem trivial
to some.

The more we are in the practice and *habit* of using cryptography for both
privacy and authentication, the more *prepared* we are when we unexpectedly
find ourselves in situations that *require* cryptography.

YMMV.

=======================================================================
Johnathan Corgan       "Violence is the last refuge of the incompetent"
<EMAIL_ADDRESS>                     -Isaac Asimov
PGP Public Key:        http://www-swiss.ai.mit.edu/~bal/pks-toplev.html
Or send email to<EMAIL_ADDRESS>Subj: GET jcorgan
=======================================================================

-----BEGIN PGP SIGNATURE-----
Version: 2.6.2

iQCVAwUBLuNAhE1Diok8GKihAQHp7gQAkdsAdTXJ64y3DaHFTzWt5obBVHgDceBx
6nHq3z5gBDMuYWoJR3+8zoyf9wBS0s2N9knZ+1e1QkB2dOy8ntgVpddwaDVioyIH
lMN5LW/VZ9IkufmisrM2/nnEcYCCT9hkact/VFTiveqPBZKkvBMa5XiCIRr+77Y/
hFtYuYfRrqY=
=JL5c
-----END PGP SIGNATURE-----

{% endraw %}
```

## Thread

+ Return to [December 1994](/archive/1994/12)

+ Return to "[Johnathan Corgan <jcorgan@netcom.com>](/authors/johnathan_corgan_jcorgan_at_netcom_com_)"

+ 1994-12-05 (Mon, 5 Dec 94 08:35:09 PST) - RE: cypher bickering - _Johnathan Corgan<EMAIL_ADDRESS>


text:
# Firebase User export to Keycloak import

Utility for importing exported Firebase users to an appropriately configured Keycloak instance.

To be used on a Keycloak instance configured with with the [Keycloak Firebase Scrypt](https://github.com/SmartMoveSystems/keycloak-firebase-scrypt) extension.

## Build

```bash
./gradlew build
```

## Download latest release

```
curl -L https://github.com/SmartMoveSystems/firebase-keycloak-importer/releases/download/1.0.1/firebase-keycloak-importer-1.0.1.jar > firebase-keycloak-importer-1.0.1.jar
```

## Usage

Export your Firebase user database to a JSON file using the [Firebase CLI](https://firebase.google.com/docs/cli/auth)

Export your Firebase project's hash parameters to a JSON file with the format:

```
{
    "hash_config": {
      "algorithm": "SCRYPT",
      "base64_signer_key": "jxspr8Ki0RYycVU8zykbdLGjFQ3McFUH0uiiTvC8pVMXAn210wjLNmdZJzxUECKbm0QsEmYUSDzZvpjeJ9WmXA==",
      "base64_salt_separator": "Bw==",
      "rounds": 8,
      "mem_cost": 14,
    }
}
```

Run the following (the args `"--clientId", "--roles", "--clientSecret", "--default", "--debug"` are optional):

```bash
java -jar build\libs\firebase-keycloak-importer-1.0.1.jar --usersFile example_users.json --hashParamsFile example_hash_config.json --adminUser<EMAIL_ADDRESS>--adminPassword admin --realm smartmove --serverUrl http://localhost:8080/auth --default true
```

The `default` argument specifies that the imported hash parameters will be the ones used for future users.
If you are only importing from one Firebase project, you must set this argument to `true`.

The client with the specified `clientId` and all specified `roles` must already exist in your Keycloak configuration.

## Importing from multiple projects

If there is a user with the same email address between multiple imported projects, the first imported user record wins.

The only difference is that the `phone_verified` claim is set to false if the imported phone numbers differ between projects.

repository: eulersantana/firebase-keycloak-importer

repo_name: eulersantana/firebase-keycloak-importer


text:
# Adonis fullstack application

This is my Adonis simple stock test application.

Contains only Products CRUD.

## Installation

* `git clone https://github.com/silverqx/adonisjs-simple-stock`
* `cd adonisjs-simple-stock`
* `npm install -g @adonisjs/cli`
* `npm install`
* create some mysql database
* rename `env.example` to `.env` and fill out correct data
* `adonis key:generate`
* `adonis migration:run`
* `adonis serve --dev`
* look at http://localhost:3333

## Authentication

Application doesn't contain any seeded users, you have to register one.

repository: silverqx/adonisjs-simple-stock

repo_name: silverqx/adonisjs-simple-stock


text:
# Class 18 \| Socket.io
Article: [Web Sockets](https://en.wikipedia.org/wiki/WebSocket)
Tutorial: [Socket.io Tutorial](https://www.tutorialspoint.com/socket.io/)
Article: [Socket.io vs. Web Sockets](https://www.educba.com/websocket-vs-socket-io/)
Docs: [Socket.io Docs](https://socket.io/docs/)
Article: [Socket.io Server API](https://socket.io/docs/server-api)
Article: [Socket.io Client API](https://socket.io/docs/client-api)
Article: [Socket Testing Tool](https://amritb.github.io/socketio-client-tool/)

## Review Tidbits

What is the benefit of transforming data into packets?

UDP is often refereed to as a connectionless protocol. Why is this?

Can a socket server application have multiple socket connections?

Can a socket connection application be connected to multiple socket servers?

Can an application be both a socket server and a socket connection?

**Document the following Vocabulary Terms**
Term | Defition
--|--
OSI Model |
TCP Model |
TCP |
UDP |
Packets |
Socket |

## Upcoming Lecture

Which 3 things had you heard about previously and now have better clarity on?
  1) x
  2) y
  3) z

Which 3 things are you hoping to learn more about in the upcoming lecture/demo?
  1) x
  2) y
  3) z

What are you most excited about trying to implement or see how it works?
   - xyz

[Back to Home](README.md)


text:
# Background

We're going to leave the main thread now. In Kotlin/Native, if you are *directly* managing your concurrency, you'll probably be using `Worker`. `Worker` is Kotlin/Native's concurrency helper. Each `Worker` has it's own thread internally, and you can schedule work to be done on that thread.

We won't be going into detail about how to use `Worker` directly. It is kind of a low-level feature, and pretty much all apps will use a concurrency library that sits on top of `Worker`. If you are familiar with Java's `Thread`, the situation is similar. Most developers are aware that `Thread` exists, but rarely use it directly.

Instead of using `Worker`, we're going to craft our own concurrency function called `background`.

```kotlin
fun background(block: () -> Unit) {
    val future = worker.execute(TransferMode.SAFE, { block.freeze() }) {
        it()
    }
    collectFutures.add(future)
}

private val worker = Worker.start()
private val collectFutures = mutableListOf<Future<*>>()
```

You call `background` with a lambda argument that executes state on another thread. The details of `Worker.execute` are a bit beyond what we're going to cover here, but the 2nd argument is a function to generate a parameter to the work function, and the 3rd is the work function itself, which gets run on a different thread.

The 2nd parameter returns a value which gets sent to the work function.  `Worker.execute` makes sure that parameter can be given to another thread. According to the 2 state rules, either the value is not referenced by anything in the current thread, and can be transferred and remain mutable (rule #1), or the value is frozen (rule #2).

While you can technically attempt to pass mutable state to other threads, in practice, Kotlin/Native concurrency libraries will automatically freeze state when passing between threads. A general model of Kotlin/Native concurrency libraries has emerged. To perform work in a different thread, you pass a lambda to a function. That lambda, and all of the data is captures, is frozen. `background` does the same.

For a simple example, run `basicBackground()`

```kotlin
fun basicBackground(){
    println("Is main thread $isMainThread")
    background {
        println("Is main thread $isMainThread")
    }
}
```

We've also created a property `isMainThread`, which, you can probably guess, will tell us if we're in the main thread. Running the function `basicBackground()` will print the following:

```
Is main thread true
Is main thread false
```

`basicBackground()` gets us onto another thread to do work, but obviously doesn't do much. This next example will pass some state into the other thread.

Run `captureState()`:

```kotlin
fun captureState(){
    val sd = SomeData("Hello 🥶", 67)
    println("Am I frozen? ${sd.isFrozen}")
    background {
        println("Am I frozen now? ${sd.isFrozen}")
    }
}
```

This will print:

```
Am I frozen? false
Am I frozen now? true
```

`sd` gets frozen when the lambda argument to `background` is frozen. It is very important to understand that concurrency function arguments can capture state, and when they are frozen, that state is also frozen.

As an alternate visualization, see below. When we call `background`, that function argument is frozen, and since it captures `sd`, which is a local `val` in the calling function, `sd` is also frozen.

![Frozen Code](./assets/frozencode.png)

Local values are easy to understand and deal with. Where this becomes more problematic, and triggers more controversy, is when you wind up capturing more state than you had intended.

Run `captureTooMuch()`

We'll be using a more complex model class that has a number you can increment, and when you do, we push that value into a "database" in the background, by way of the function `saveToDb(arg:Int)`:

```kotlin
class CountingModel{
    var count = 0

    fun increment(){
        count++
        background {
            saveToDb(count)
        }
    }

    private fun saveToDb(arg:Int){
        //Do some db stuff
        println("Saving $arg to db")
    }
}
```

Our function to use the model looks like this:

```kotlin
fun captureTooMuch(){
    val model = CountingModel()
    model.increment()
    println("I have ${model.count}")

    model.increment()
    println("I have ${model.count}") //We won't get here
}
```

What's the result? Our old friend, `InvalidMutabilityException`!

```
I have 1
Saving 1 to db
Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen sample.CountingModel@17e01008
        at 0   KNConcurrencySamples.kexe   (nah)
        at 1   KNConcurrencySamples.kexe   (meh)
(etc)

```

To help illustrate the issue here, consider `captureTooMuchAgain()`

```kotlin
fun captureTooMuchAgain(){
    val model = CountingModel()
    println("model is frozen ${model.isFrozen}")
    model.increment()
    println("model is frozen ${model.isFrozen}")
}
```

This prints

```
model is frozen false
model is frozen true
```

`count` is an instance var of `CountingModel`, so capturing `count` in the way what we have will capture the whole model and freeze it.

To help avoid this, it is good practice to move thread-jumping code to another function, and only capture function arguments. Try `captureArgs()`:

```kotlin
fun captureArgs(){
    val model = CountingModelSafer()
    model.increment()
    println("I have ${model.count}")

    model.increment()
    println("I have ${model.count}")
}

class CountingModelSafer{
    var count = 0

    fun increment(){
        count++
        saveToDb(count)
    }

    private fun saveToDb(arg:Int) = background {
        println("Doing db stuff with $arg, in main $isMainThread")
    }
}
```

The modified `saveToDb` function above now handles the `background` call, and only captures the function argument. That won't freeze the parent class.

repository: kotlin-hands-on/hands-on

repo_name: kotlin-hands-on/hands-on


text:
Spurious1090 README
===

Spurious 1090 is a Mode A/C/S display utility designed to work with any
ModeA/C/S receiver that provides TCP/IP output in a Beast style data
stream.

It can be used in the same way as View1090, but displays the data
received in a statistical way. The idea is to try and get receiver
manufacturers to improve the quality of the data they provide, and
not just concentrate on quantity.

Installation
---

There is no installation. If you don't trust executables written by idiots
like me and downloaded from t'interweb then the source code is provided in
the root directory together with a Visual Studio 6.0 C++ project file. Download
it, inspect the source files and then compile it yourself.

There is no Linux make file, although since the code is derived from dump1090
it shouldn't be too difficult for someone to build it under Linux if you so wish.

The pre-compiled Windows exe is available in both Release and Debug forms in the
associated sub directories. I've also included all the non standard windows
DLL's, and a sample batch file to kick things off.

I suggest most users just download all the files in the /Release subdirectory and
put them in a suitable directory on your machine - probably called spurious1090.

Open the batch file in a text editor of your choice, and change the
--net-bo-ipaddr and --net-bo-port parameters to point at the TCP/IP address
and port of your receiver. Then execute the batch file and you should see a
screen full of numbers appear.

The program has been tested on Win7Pro-32bit and Win10Pro-64. It's a simple
console app, so should work on virtually any 32 or 64 bit version of Windows
from NT4 up.

Normal Output
---

So what do all the numbers mean? Some of them will be self evident, some
perhaps not so.

ModeS Frames (All)
---
This is the total count of all the Mode S frames output by your receiver.

To the right of this the individual Download Formats (DF) counts are
displayed. There are 32 DF types defined in the ICAO specificaiton for
Mode S, although only some of them are actually used.

Specifically DF0, DF4, DF5, DF11, DF16, DF17, DF18, DF20, DF21 are
relatively common, and you should see these counts ticking up.

The other DF's are either undefined, or for military use, so in theory you
probably shouldn't see any of these. You may see the occasional spurious
frame from your receiver though.

ModeS Altitude Frames
---
This is the number of Mode S frames containing altitude information.

Mode S Altitude information is included in DF types DF0, DF4, DF16 and DF20.
The individual counts for these DF types is displayed to the right.

ModeS Squawk Frames
---
This is the number of Mode S frames containing squawk information.

Mode S Altitude information is included in DF types DF5, DF21.
The individual counts for these DF types is displayed to the right.

ModeS Short Duplicates
---
This is an annoying feature of several receiver types. They output
the same Frame several times, with a timestamp only a few micro-seconds
apart.

A Short ModeS Frame consists of an 8uS preamble followed by a 56 bit
data stream. The total time to transmit this whole frame is therefore
64uS.

If we see two Frames containing identical data, and whose timestamps
differ by less than 64uS then the two frames cannot possibly both be
'real'. Your receiver must have output the same frame twice - Why?

Receiver manufacturers don't seem to care about this because they aren't
feeding false data, and it does increase their apparant "Message rates"
which is all many of them care about. Of course you can double your
message rate if you output the same frame twice - but you aren't adding
any extra information by doing it.

ModeS Short Overlapping
---
A Short ModeS Frame consists of an 8uS preamble followed by a 56 bit
data stream. The total time to transmit this whole frame is therefore
64uS.

If we see two Frames containing different data, and whose timestamps
differ by less than 64uS then the two frames cannot possibly both be
'real' since they must overlap in time.

This is curious because most ModeS message types are CRC protected,
so if either of the two messages where corrupt the CRC should have
rejected them. So how can they both pass CRC checking, but overlap
in time - huhh?

ModeS Long Duplicates
---
This is an annoying feature of several receiver types. They output
the same Frame several times, with a timestamp only a few micro-seconds
apart.

A Long ModeS Frame consists of an 8uS preamble followed by a 112 bit
data stream. The total time to transmit this whole frame is therefore
120uS.

If we see two Frames containing identical data, and whose timestamps
differ by less than 120uS then the two frames cannot possibly both be
'real'. Your receiver must have output the same frame twice - Why?

Receiver manufacturers don't seem to care about this because they aren't
feeding false data, and it does increase their apparant "Message rates"
which is all many of them care about. Of course you can double your
message rate if you output the same frame twice - but you aren't adding
any extra information by doing it.

ModeS Long Overlapping
---
A Long ModeS Frame consists of an 8uS preamble followed by a 112 bit
data stream. The total time to transmit this whole frame is therefore
120uS.

If we see two Frames containing different data, and whose timestamps
differ by less than 120uS then the two frames cannot possibly both be
'real' since they must overlap in time.

This is curious because most ModeS message types are CRC protected,
so if either of the two messages where corrupt the CRC should have
rejected them. So how can they both pass CRC checking, but overlap
in time - huhh?

ModeAC Frames (All)
---
This is the total number of ModeA/C frames output by the receiver.

Comnpare the count of ModeAC frames to the count of ModeS frames.
In the UK, good receivers (Beast) typically show about 2.5 times the
number of ModeA/C Frames as Mode S.

Lesser receivers (Dongles) typically have ModeAC:ModeS ratios worse
than 1:1 - often much worse - like 1:4 rather than 2.5:1 often seen
with a Beast. The implication then is that the dongle is missing
somewhere in excess of 90% of all ModeAC frames.

The rates will vary due to location around the world, and depend on
what your local radar sites are actually asking for - if they are
only asking for ModeS then of course you won't see any ModeAC.

ModeA Frames (Matching ModeS Squawk)
---
This is the count of the number of ModeA frames which exactly match a
known ModeS_A code (ie a Mode A code derived from ModeS DF5/DF21 data).

Add the "ModeA Frames (Matching ModeS Squawk)" count to the
"ModeC Frames (Matching ModeS Altitude)" and then divide by
"ModeAC Frames (All)".

That gives you a percentage of valid (i.e. non-spurious) ModeAC codes
received. See the problem? Few receivers give better than 70% valid codes.

ModeC Frames (Matching ModeS Altitude)
---
This is the count of the number of ModeC frames which exactly match a
known ModeS_C code (ie a Mode C code derived from ModeS
DF0/DF4/DF16/DF20 data).

Add the "ModeA Frames (Matching ModeS Squawk)" count to the
"ModeC Frames (Matching ModeS Altitude)" and then divide by
"ModeAC Frames (All)".

That gives you a percentage of valid (i.e. non-spurious) ModeAC codes
received. See the problem? Few receivers give better than 70% valid codes.

ModeAC Frames (Duplicates)
---
A ModeAC Frame consists of 15 bit times, each bit period lasting 1.45uS.
Therefore if takes 21.75uS to transmit the frame. Things are slightly
complicated by the SPI (Squawk Ident) bit which occurs outside the main
frame at bit time 24.65uS, lasting another 1.45uS, so 26.1uS

We can argue about what the limit should be here, but I've decided it
should be 26.1uS - which covers the SPI bit.

So if we get the same ModeAC code twice within a 26.1uS interval then either
there are two aircraft transmitting the same code synchronously (unlikely)
or the receiver has output the same frame twice (naughty naughty).

ModeAC Frames (Overlapping)
---
A ModeAC Frame consists of 15 bit times, each bit period lasting 1.45uS.
Therefore it takes 21.75uS to transmit the frame. Things are slightly
complicated by the SPI (Squawk Ident) bit which occurs outside the main
frame at bit time 24.65uS, lasting another 1.45uS, so 26.1uS

We can argue about what the limit should be here, but I'lll argue it
should be 26.1uS - which covers the SPI bit - untill someone convinces me
otherwise.

The '1' bits in a ModeAC only last 0.45uS, and then there is a 1uS space
before the next bit. It is therefore possible for ModeAC codes from two
closely spaced aircraft to be interleaved in such a way that both can be
successfully received. see https://www.radartutorial.eu/13.ssr/sr15.en.html

However, for non-synchronous de-garbling to work the bits of the two frames
must be separated from each other by some odd multiple of half a bit period,
plus or minus a bit.

The Overlapping count is the number of ModeAC frames which occur less than 26.1uS
after the previous frame, and the data is different to the previous frame, and the
timestamps indicate the '1' bits must overlap. This means that both this frame, and
the previous one should be considered garbled, and hence unreliable.

For instance, a typical decode might be (these are real - received by me yesterday!)

5424 received at timestamp +0
2612 received at timestamp +35 (+2.92uS, or 2.01 bit times later)
6616 received at timestamp +36 (+3.00uS, or 2.07 bit times later)
6627 received at timestamp +54 (+4.5uS, or 3.10 bit times later)

If we draw out what the off-air bit pattern would have been for these 4 codes, and delay
each code by the timestamp offset in bit periods we get..

5424 =<PHONE_NUMBER>00111
2612 =<PHONE_NUMBER>11101
6616 =<PHONE_NUMBER>11111
6627 =<PHONE_NUMBER>11111

See what is going on? 4 codes reported, different timestamps, and no way of knowing which,
if any, is valid.

ModeAC Frames (Interleaved)
---
Same description as above in "ModeAC Frames (Overlapping)", except the timestamps
indicate the '1' bits are time aligned such that they interleave correctly and do
not overlap.

This means the two frames may be correctly decoded and hence valid. I wouldn't bet
too much money on it though.

ModeAC Frames (XX0000)
---
Some receivers (Beast for example) spew out an almost constant stream of
useless XX0000 codes day and night. These are almost always spurious, and
probably generated by noise. In my location about 10% of all ModeAC frames
output are XX0000.

ModeAC Frames (One Bit Set)
---
This count is the number of ModeAC frames that had only one data bit set.
There are 12 such codes : XX0001, XX0002, XX0004, XX0010, XX0020, XX0040,
XX0100, XX0200, XX0400, XX1000, XX2000 and XX4000. Some of these might be
valid, but chances are that most are spurious.

ModeA Frames (One Bit Zero Errors)
---
This is the count of the number of ModeA frames which do not exactly match
a known ModeS_A code (i.e. a ModeA code derived from ModeS data), but do
match a known ModeS_A code if you flip one (and only one) of the '0' bits
to a '1' in the received ModeA.

So, for instance, if we know (From ModeS DF5/DF21) that an aircraft should
be Squawking 6401, and we receive a ModeA 6400, and there is no known
aircraft using 6400, then by flipping bit 0 from a '0' to a '1' we can get
6401 and achieve a 'hit'.

This means that the receiver has possibly mis-interpreted the radio signal
which 'should' have been 6401, and spuriously decoded '6400' instead.

ModeA Frames (One Bit One Errors)
---
This is the count of the number of ModeA frames which do not exactly match
a known ModeS_A code (ie a Mode A code derived from ModeS data), but do
match a known ModeS_A code if you flip one (and only one) of the '1' bits
to a '0' in the received ModeA.

So, for instance, if we know (From ModeS DF5/DF21) that an aircraft should be
Squawking 6401, and we receive a ModeA 6403, and there is no known aircraft
using 6403, then by flipping bit 1 from a '1' to a '0' we can get 6401 and
achieve a 'hit'.

This means that the receiver has possibly mis-interpreted the radio signal
which 'should' have been 6401, and spuriously decoded '6403' instead.

ModeC Frames (One Bit Zero Errors)
---
This is the count of the number of ModeC frames which do not exactly match
a known ModeS_C code (ie a ModeC code derived from ModeS data), but do
match a known ModeS_C code if you flip one (and only one) of the '0' bits
to a '1' in the received ModeC.

So, for instance, if we know (From ModeS DF0/DF4/DF16/DF21) that an aircraft
should be emmitting a code corrosponding to FL330 (which is 1324), and we
receive code 0324, and there is no known aircraft flying at FL605 (which is
what 0324 represents) then by flipping bit 9 from a '0' to a '1' we can get
1324 and achieve a 'hit'.

This means that the receiver has possibly mis-interpreted the radio signal
which 'should' have been 1324, and spuriously decoded '0324' instead.

ModeC Frames (One Bit One Errors)
---
This is the count of the number of ModeC frames which do not exactly match
a known ModeS_C code (ie a ModeC code derived from ModeS data), but do
match a known ModeS_C code if you flip one (and only one) of the '1' bits
to a '0' in the received ModeC.

So, for instance, if we know (From ModeS DF0/DF4/DF16/DF21) that an aircraft
should be emmitting a code corrosponding to FL330 (which is 1324), and we
receive code 1724, and there is no known aircraft flying at FL335 (which is
what 1724 represents) then by flipping bit 8 from a '0' to a '1' we can get
1324 and achieve a 'hit'.

This means that the receiver has possibly mis-interpreted the radio signal
which 'should' have been 1324, and spuriously decoded '1724' instead.

ModeAC Frames (Matching Nothing)
---
This is the number of frames that the receiver has output which do not exactly
match a Known ModeS_A or a Known ModeS_C, are'nt XX0000, aren't One bit set,
and can't be explained by One bit one or one bit zero errors.

In other words, we don't know what on earth they are. They are probably a mix
of the following...

1) Completely spurious noise induced codes.
2) Spurious codes caused by receiver decoder generated errors/mistakes.
3) Real Mode 3A/3C codes from an aircraft not equipped with a Mode S transponder
4) Real Mode 3A/3C codes from an aircraft with it's Mode S transponder turned off
5) Real Mode 1/2 SSR codes - often from Military or Govt aircraft.

If you live close to a light aircraft airfield then 3 or 4 may be likely, but
probably only during daylight hours and in good weather.

If you live close to a busy military airfield then 3, 4 and 5 are all possible.

However, I'll stick my neck out and say that for most users 1 and 2 will be the
primary cause of spurious codes. Hence spurious1090.

Contributing
---

Credits
---
Spurious1090 was written by Malcolm Robb, and is derived from an original
codebase developed originally for Dump1090 by Salvatore Sanfilippo
<EMAIL_ADDRESS>which is released under the BSD three clause license.


text:
---
title: Login
default: true
description: This tutorial demonstrates how to use the Auth0 React Native Android SDK to add authentication and authorization to your mobile app
budicon: 448
---

<%= include('../../../_includes/_package', {
  org: 'auth0',
  repo: 'Mobile-Samples.React',
  path: 'Classic/Lock',
  requirements: [
    'NodeJS 6.5.0',
    'react-native-lock 0.4.0',
    'rnpm 1.9.0'
  ]
}) %>

## Install Lock

First, you need to run the following command to install **react-native-lock**

```bash
npm install --save react-native-lock
```

Then, install [rnpm](https://github.com/rnpm/rnpm)

```bash
npm install rnpm -g
```

After that, link **react-native-lock** with your Android project:

```bash
rnpm link react-native-lock
```

Open the file `android/app/build.gradle` and inside add the following into the `android {}` section

```gradle
packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE'
}
```

Then, check in `AndroidManifest.xml` that the application requests the `android.permission.INTERNET` permission. If is not already there, add it inside the `<manifest>` tag:

```xml
<uses-permission android:name="android.permission.INTERNET"/>
```

And finally, you must add the following entries inside the `<application>` tag of the same file:

```xml
<!--Auth0 Lock-->
<activity
  android:name="com.auth0.lock.LockActivity"
<EMAIL_ADDRESS>  android:screenOrientation="portrait"
  android:launchMode="singleTask">
</activity>
<!--Auth0 Lock End-->
<!--Auth0 Lock Embedded WebView-->
<activity
    android:name="com.auth0.identity.web.WebViewActivity"
<EMAIL_ADDRESS></activity>
<!--Auth0 Lock Embedded WebView End-->
<!--Auth0 Lock Passwordless-->
<activity
    android:name="com.auth0.lock.passwordless.LockPasswordlessActivity"
<EMAIL_ADDRESS>    android:screenOrientation="portrait"
    android:launchMode="singleTask">
</activity>
<activity
    android:name="com.auth0.lock.passwordless.CountryCodeActivity"
<EMAIL_ADDRESS></activity>
<!--Auth0 Lock Passwordless End-->
```

::: note
If you need Facebook or Google+ native authentication please continue reading to learn how to configure them. Otherwise please go directly to **[Showing User Information](#showing-user-information)**.
:::

## Implement the login

Now we're ready to implement the Login. First we need to require react-native-lock-android:

${snippet(meta.snippets.setup)}

Then, we can show **Lock**:

${snippet(meta.snippets.use)}

[![Lock.png](/media/articles/native-platforms/reactnative-android/Lock-Widget-Screenshot.png)](https://auth0.com)

::: note
There are multiple ways of implementing the login box. What you see above is the Login Widget, but you can try our passwordless Login Widgets: [SMS](https://github.com/auth0/react-native-lock) or [Email](https://github.com/auth0/react-native-lock)
:::

On successful authentication, the callback function will yield the user's profile and tokens inside the parameters `profile` and `token` respectively.

## Showing User Information

After the user has logged in, we can use the `profile` object which has all the user information (Let's assume the profile is stored in a component's state object):

```jsx
  <Text>Welcome {this.state.profile.name}</Text>
  <Text>Your email is: {this.state.profile.email}</Text>
```

::: note
You can find all of the available properties for the user's profile [here](/user-profile). Please note that some of these depend on the social provider being used.
:::

### FAQ

#### Error: duplicate files during packaging of APK

If you observe an error like this when trying to run the project:

```
Error: duplicate files during packaging of APK /<PATH>/android/app/build/outputs/apk/app-debug-unaligned.apk
  Path in archive: META-INF/NOTICE
  Origin 1: /<PATH>/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-databind/2.4.1/f07c773f7b3a03c3801d405cadbdc93f7548e321/jackson-databind-2.4.1.jar
  Origin 2: /<PATH>/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-core/2.4.1/b130bcfb5a9c410c3cbd2e0adec9437e69a39e2c/jackson-core-2.4.1.jar
You can ignore those files in your build.gradle:
  android {
    packagingOptions {
      exclude 'META-INF/NOTICE'
    }
  }
:app:packageDebug FAILED
```

You must follow the advice and ignore the files adding the following to the `build.gradle` of the `app` module, inside the `android` section:

```
packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE'
}
```


text:
---
title: "Auto and fit"
height: 650
---

Use simply `grid` to create a grid. The algorithm will automatically place cells depending on `cell-*` classes seen previously.

Use `grid-cols-auto-flow`, `grid-rows-auto-flow` classes to control how the auto-placement algorithm works for a grid layout. `grid-auto` shortcut stands for columns auto flow.

Use `grid-cols-fit`, `grid-rows-fit` classes to control the size implicitly-created grid columns and rows and make it fit the content.

repository: mani-peclet/codelibrary

repo_name: mani-peclet/codelibrary


text:
# Elasticsearch-Aknn Benchmarks

This directory contains code for benchmarking an Elasticsearch-Aknn installation
using Glove word vectors.

The `aknn.py` script should give an idea for how to programatically interact
with the Elasticsearch-Aknn plugin.

The `figures.ipynb` notebook should give some ideas on performance for various
configurations.

repository: mattiasarro/elastik-nearest-neighbors

repo_name: mattiasarro/elastik-nearest-neighbors


text:
# Libé Bulma

**Générateur de style pour Libé Six Plus basé sur [Bulma](https://github.com/jgthms/bulma)**

- use bulma style elements
- add Libé fonts & colors
- change `.button` to `.btn`
- overrides form elements based on material design style

```
$ npm run build
```

## License

> The MIT License (MIT)
>
> Copyright (c) Libé Six Plus 2015
>
> 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.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 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: libe-labo/libe-bulma

repo_name: libe-labo/libe-bulma


text:
# People Reader/Writer for Neo4j (people-rw-neo4j) [RETIRED]

[![Circle CI](https://circleci.com/gh/Financial-Times/people-rw-neo4j.svg?style=shield)](https://circleci.com/gh/Financial-Times/people-rw-neo4j)[![Go Report Card](https://goreportcard.com/badge/github.com/Financial-Times/people-rw-neo4j)](https://goreportcard.com/report/github.com/Financial-Times/people-rw-neo4j) [![Coverage Status](https://coveralls.io/repos/github/Financial-Times/people-rw-neo4j/badge.svg)](https://coveralls.io/github/Financial-Times/people-rw-neo4j)
__An API for reading/writing people into Neo4j. Expects the people json supplied to be in the format that comes out of the people transformer.__

## Installation

For the first time:

`go get github.com/Financial-Times/people-rw-neo4j`

or update:

`go get -u github.com/Financial-Times/people-rw-neo4j`

## Running

`$GOPATH/bin/people-rw-neo4j --neo-url={neo4jUrl} --port={port} --batchSize=50 --graphiteTCPAddress=graphite.ft.com:2003 --graphitePrefix=content.{env}.people.rw.neo4j.{hostname} --logMetrics=false

All arguments are optional, they default to a local Neo4j install on the default port (7474), application running on port 8080, batchSize of 1024, graphiteTCPAddress of "" (meaning metrics won't be written to Graphite), graphitePrefix of "" and logMetrics false.

NB: the default batchSize is much higher than the throughput the instance data ingester currently can cope with.

## Updating the model
Use gojson against a transformer endpoint to create a person struct and update the person/model.go file. NB: we DO need a separate identifier struct

`curl http://ftaps35629-law1a-eu-t:8080/transformers/people/ad60f5b2-4306-349d-92d8-cf9d9572a6f6 | gojson -name=person`

## Endpoints

/people/{uuid}

### PUT
The only mandatory field is the uuid, and the alternativeIdentifier uuids (because the uuid is also listed in the alternativeIdentifier uuids list). The uuid in the body must match the one used on the path.

Every request results in an attempt to update that person: unlike with GraphDB there is no check on whether the person already exists and whether there are any changes between what's there and what's being written. We just do a MERGE which is Neo4j for create if not there, update if it is there.

A successful PUT results in 200.

We run queries in batches. If a batch fails, all failing requests will get a 500 server error response.

Example PUT request:

    `curl -XPUT localhost:8080/people/3fa70485-3a57-3b9b-9449-774b001cd965 \
         -H "X-Request-Id: 123" \
         -H "Content-Type: application/json" \
         -d '{"uuid":"3fa70485-3a57-3b9b-9449-774b001cd965","birthYear":1974,"salutation":"Mr","name":"Robert W. Addington","prefLabel":"Robert Addington","twitterHandle":"@rwa","facebookProfile":"raddington","linkedinProfile":"robert-addington","description": "Some text","descriptionXML": "Some text containing markup","_imageUrl": "http://someimage.jpg","alternativeIdentifiers":{"TME":["MTE3-U3ViamVjdHM="],"uuids":["3fa70485-3a57-3b9b-9449-774b001cd965","6a2a0170-6afa-4bcc-b427-430268d2ac50"],"factsetIdentifier":"000BJG-E"},"type":"People"}'`

The type field is not currently validated - instead, the People Writer writes type People and its parent types (Thing, Concept) as labels for People.

Invalid json body input, or uuids that don't match between the path and the body will result in a 400 bad request response.

### GET
Thie internal read should return what got written (i.e., this isn't the public person read API)

If not found, you'll get a 404 response.

Empty fields are omitted from the response.
`curl -H "X-Request-Id: 123" localhost:8080/people/3fa70485-3a57-3b9b-9449-774b001cd965`

### DELETE
Will return 204 if successful, 404 if not found
`curl -XDELETE -H "X-Request-Id: 123" localhost:8080/people/3fa70485-3a57-3b9b-9449-774b001cd965`

### Admin endpoints
Healthchecks: [http://localhost:8080/__health](http://localhost:8080/__health)

Ping: [http://localhost:8080/ping](http://localhost:8080/ping) or [http://localhost:8080/__ping](http://localhost:8080/__ping)

### Logging
 the application uses logrus, the logfile is initialised in main.go.
 logging requires an env app parameter, for all environments  other than local logs are written to file
 when running locally logging is written to console (if you want to log locally to file you need to pass in an env parameter that is != local)
 NOTE: build-info end point is not logged as it is called every second from varnish and this information is not needed in  logs/splunk


text:
# updateGJAccSettings20.php

Updates a user's account settings

## Parameters

### Required Parameters

**accountID** - The accountID of the user whose account is being updated

**gjp** - The [GJP](/topics/encryption/gjp.md) of the user whose account is being updated

**secret** - Wmfv3899gc9

### Optional Parameters

**mS** - Who the user allows messages from: 0 for anyone, 1 for just friends, and 2 for no one

**frS** - Who the user allows friend requests from: 0 for anyone, and 1 for no one

**cS** - Who the user allows to view their comments: 0 for anyone, 1 for just friends, and 2 for only themselves

**yt** - The end of the link to the user's youtube channel, after the `/channel/`. e.g. `UCZoN2WLAooS6uhREa9Cgpwg`

**twitter** - The user's twitter handle

**twitch** - The user's twitch username

## Response

1 if the required parameters are passed, regardless of anything is being updated, -1 otherwise

## Example

<!-- tabs:start -->

### **Python**

```py
import requests

data = {
    "accountID": 173831, # DevExit's account ID
    "gjp": "********", # This would be DevExit's password encoded with GJP encryption
    "secret": "Wmfv3899gc9",
    "mS": 0,
    "frS": 0,
    "cS": 0,
    "yt": "UCZoN2WLAooS6uhREa9Cgpwg",
    "twitter": "DevExit",
    "twitch": "devexit"
}

req = requests.post('http://boomlings.com/database/updateGJAccSettings20.php', data=data)
print(req.text)
```

**Response**
```py
1
```

<!-- tabs:end -->


text:
# `words`

![](https://github.com/lw2904/words/workflows/build/badge.svg)

Because I don't see why I should have to use giants like Hugo or Jekyll if I just want to insert some parsed markdown into simple templates, and sacrifice easy tweaking and fine tuning while I'm at it.

Taking some inspiration from the people over at [suckless](https://suckless.org), this project takes a zero-configuration approach.

- __Want to change the .css of the markdown?__ `$ mv desired.css static/css/markdown.css`
- __Want to insert some custom HTML in every page?__ Go to `templates/item.html` or `front.html` and _do it_.
- __Want to exchange the code parser for some exotic asynchronous one?__ `source/app.d` is <100 LOC, it'll take you a minute or two at most.

## To get started...

Download the latest build from the [releases](https://github.com/LW2904/words/releases) section. These are automatically built from the master branch on every push.

Throw your markdown files into `content/` (or tell `words` about their location with `--content`). If you haven't already, add some front-matter ([see below](https://github.com/LW2904/words#front-matter)) to the markdown files and you're good to go.

Running `./words-*` will build the page in `public/`, you can do what you will from then on.

- Symlinking public to some folder your web server of choice is hosting
- Making `public/` a submodule pointing to `<NAME>.github.io` (et al)
- ...

## Folder Structure

All utilities expect a folder structure like the following, relative to the current working directory.

```
├── [content]       # Your markdown files go here, the location can be
│   │               # customized
│   ├── building-a-brainfuck-interpreter.md
│   ├── cheating-in-osu!mania.md
│   ├── ...
│   .
│
├── public          # The static page will be built to this folder and it is
│                   # deleted and recreated in every run
│
├── static          # This folder and all of its contents will be copied to
│   │               # public/static on building
│   ├── css
│   │   ├── highlighting.css
│   │   └── markdown.css
│   ├── favicon.png
│   └── js
│       └── utils.js
│
└── templates       # mustache template files which are used to build the site
    │
    ├── front.html  # Template for the "landing page" - you will most likely
    │               # want to edit this
    └── item.html   # ...for the items (aka posts, markdown files, ...)
```

## Front matter

I don't like the way this is handled currently. But until I come up with an alternative to throwing some metadata in front of every file that's processed, you will have to add some JSON at the beginning of an `item` (ergo anything in `content/`) and it will be parsed. This looks something like:

```
{ "name": "Front Matter and other Atrocities", "date": "2018-08-31" }

Your content goes here.
The `name` element will be used as the heading for this item.
```

`date` has to be in the ISO 8601 extended date format. Yeah, I had to look that up too, just format it like in the example above, kay?

## Options

The `--content`, `--public`, and `--templates` switches can be used to control input and output paths. They default to their respective names (i. e. `content/`, ...).

## Building from Source

Clone the repository,

```bash
$ git clone https://github.com/LW2904/words.git
```
get yourself a [D compiler](https://wiki.dlang.org/Compilers) and do

```bash
$ dub build
```

in the root of the project.

license: Unlicense

repository: fs-c/words

repo_name: fs-c/words


text:
# SignalFx-Tracing Library for Python: An OpenTracing Auto-Instrumentor

This utility provides users with the ability of automatically configuring
OpenTracing 2.0-compatible community-contributed [instrumentation libraries](https://github.com/opentracing-contrib)
for their Python 2.7 and 3.4+ applications via a single function.

```python
from signalfx_tracing import auto_instrument, create_tracer

tracer = create_tracer(service_name='MyService')
auto_instrument(tracer)
```

If auto-instrumentation of all applicable libraries and frameworks isn't desired,
enabling instrumentation individually can be done by specifying your target module:

```python
from signalfx_tracing import create_tracer, instrument, uninstrument

tracer = create_tracer()
instrument(tracer, flask=True)
# or
instrument(flask=True)  # uses the global Tracer from opentracing.tracer by default

import flask

traced_app = flask.Flask('MyTracedApplication')

@traced_app.route('/hello_world')
def traced_route():
    # Obtain active span created by traced middleware
    span = tracer.scope_manager.active.span
    span.set_tag('Hello', 'World')
    span.log_kv({'event': 'initiated'})
    return 'Hello!'  # Span is automatically finished after request handler

uninstrument('flask')  # prevent future registrations

untraced_app = flask.Flask('MyUntracedApplication')

@untraced_app.route('/untraced_hello_world')
def untraced_route():
    return 'Goodbye!'
```

**Note: Both `instrument()` and `auto_instrument()` invocations can be converted to no-ops if the
`SIGNALFX_TRACING_ENABLED` environment variable is set to `False` or `0`.  This can be helpful when developing your
auto-instrumented application locally or in test environments.**

## Supported Frameworks and Libraries

* [Celery 3.1+](./signalfx_tracing/libraries/celery_/README.md) - `instrument(celery=True)`
* [Django 1.8+](./signalfx_tracing/libraries/django_/README.md) - `instrument(django=True)`
* [Elasticsearch 2.0+](./signalfx_tracing/libraries/elasticsearch_/README.md) - `instrument(elasticsearch=True)`
* [Flask 0.10+](./signalfx_tracing/libraries/flask_/README.md) - `instrument(flask=True)`
* [Psycopg 2.7+](./signalfx_tracing/libraries/psycopg2_/README.md) - `instrument(psycopg2=True)`
* [PyMongo 3.1+](./signalfx_tracing/libraries/pymongo_/README.md) - `instrument(pymongo=True)`
* [PyMySQL 0.8+](./signalfx_tracing/libraries/pymysql_/README.md) - `instrument(pymysql=True)`
* [Redis-Py 2.10+](./signalfx_tracing/libraries/redis_/README.md) - `instrument(redis=True)`
* [Requests 2.0+](./signalfx_tracing/libraries/requests_/README.md) - `instrument(requests=True)`
* [Tornado 4.3-6.x](./signalfx_tracing/libraries/tornado_/README.md) - `instrument(tornado=True)`

## Installation and Configuration

### Library and Instrumentors
The SignalFx-Tracing Library for Python works by detecting your libraries and frameworks and configuring available
instrumentors for distributed tracing via the Python [OpenTracing API 2.0](https://pypi.org/project/opentracing/2.0.0/).
By default, its footprint is small and doesn't declare any instrumentors as dependencies. That is, it operates on the
assumption that you have 2.0-compatible instrumentors installed as needed. As adoption of this API is done on a
per-instrumentor basis, it's highly recommended you use the helpful [bootstrap utility](./scripts/README.md) for
obtaining and installing any applicable, feature-ready instrumentors along with a compatible tracer:

```sh
  $ pip install signalfx-tracing
  $ sfx-py-trace-bootstrap
```

For example, if your environment has Requests and Flask in its Python path, the corresponding OpenTracing
instrumentors will be pip installed.  Again, since OpenTracing-Contrib instrumentation support of API 2.0 is not
ubiquitous, this bootstrap selectively installs custom instrumentors listed in
[the instrumentor requirements file](./requirements-inst.txt).  As such, we suggest being sure to uninstall any previous
instrumentor versions before running the bootstrapper, ideally in a clean environment.

To run the instrumentor bootstrap process without installing the suggested tracer, you can run the following from this
project's source tree:

```sh
  $ scripts/bootstrap.py --deps-only
```

You can also specify a target installation directory, which will include the most recent `signalfx-tracing` as provided
by PyPI:

```sh
  $ sfx-py-trace-bootstrap -t /my/site/packages/directory
```

It's also possible to install the supported instrumentors as package extras from a cloned repository:

```bash
  $ git clone https://github.com/signalfx/signalfx-python-tracing.git
  # Supported extras are dbapi, django, flask, pymongo, pymysql, redis, requests, tornado
  $ pip install './signalfx-python-tracing[django,redis,requests]'
```

**Note: For pip versions earlier than 18.0, it's necessary to include `--process-dependency-links` to
obtain the desired instrumentor versions.**

```bash
  $ git clone https://github.com/signalfx/signalfx-python-tracing.git
  # pip versions <18.0
  $ pip install --process-dependency-links './signalfx-python-tracing[jaeger,tornado]'
```

### Tracer
Not all stable versions of OpenTracing-compatible tracers support the 2.0 API, so we provide
and recommend installing a modified [Jaeger Client](https://github.com/jaegertracing/jaeger-client-python)
ready for reporting to SignalFx. You can obtain an instance of the suggested Jaeger tracer using a
 `signalfx_tracing.utils.create_tracer()` helper, provided you've run:

```sh
  $ sfx-py-trace-bootstrap

  # or as package extra
  $ pip install './signalfx-python-tracing[jaeger]'
  # please use required --process-dependency-links for pip versions <18.0
  $ pip install --process-dependency-links './signalfx-python-tracing[jaeger]'

  # or from project source tree, along with applicable instrumentors
  $ scripts/bootstrap.py --jaeger

  # or to avoid applicable instrumentors
  $ scripts/bootstrap.py --jaeger-only
```

By default `create_tracer()` will enable tracing with constant sampling (100% chance of tracing) and report each span
directly to SignalFx. Where applicable, context propagation will be done via
[B3 headers](https://github.com/openzipkin/b3-propagation).

```python
from signalfx_tracing import create_tracer

# sets the global opentracing.tracer by default:
tracer = create_tracer()  # uses 'SIGNALFX_ACCESS_TOKEN' environment variable if provided

# or directly provide your organization access token if not using the Smart Agent to analyze spans:
tracer = create_tracer('<OrganizationAccessToken>', ...)

# or to disable setting the global tracer:
tracer = create_tracer(set_global=False)
```

All other `create_tracer()` arguments are those that can be passed to a `jaeger_client.Config` constructor:
```python
from tornado_opentracing.scope_managers import TornadoScopeManager
from signalfx_tracing import create_tracer

tracer = create_tracer(
    '<OptionalOrganizationAccessToken>',
    config=dict(jaeger_endpoint='http://localhost:9080/v1/trace'),
    service_name='MyTracedApplication',
    scope_manager=TornadoScopeManager  # Necessary for span scope in Tornado applications
)
```

If a `config` dictionary isn't provided or doesn't specify the desired items for your tracer, the following environment
variables are checked for before selecting a default value:

| Config kwarg | environment variable | default value |
|--------------|----------------------|---------------|
| `service_name` | `SIGNALFX_SERVICE_NAME` | `'SignalFx-Tracing'` |
| `jaeger_endpoint` | `SIGNALFX_ENDPOINT_URL` | `'http://localhost:9080/v1/trace'` |
| `jaeger_password` | `SIGNALFX_ACCESS_TOKEN` | `None` |
| `['sampler']['type']` | `SIGNALFX_SAMPLER_TYPE` | `'const'` |
| `['sampler']['param']` | `SIGNALFX_SAMPLER_PARAM` | `1` |
| `propagation` | `SIGNALFX_PROPAGATION` | `'b3'` |

**Note: By default `create_tracer()` will store the initial tracer created upon first invocation and return
that instance for subsequent invocations.  If for some reason multiple tracers are needed, you can provide
`create_tracer(allow_multiple=True)` as a named argument.**

## Usage

### Application Runner
The SignalFx-Tracing Library for Python's auto-instrumentation configuration can be performed while loading
your framework-based and library-utilizing application as described in the corresponding
[instrumentation instructions](#supported-frameworks-and-libraries).
However, if you have installed the recommended [Jaeger client](#Tracer) (`sfx-py-trace-bootstrap`) and would like to
automatically instrument your applicable program with the default settings, a helpful `sfx-py-trace` entry point
is provided by the installer:

```sh
  $ sfx-py-trace my_application.py --app_arg_one --app_arg_two
  # Or if your Smart Agent is not available at the default endpoint url:
  $ SIGNALFX_ENDPOINT_URL='http://MySmartAgent:9080/v1/trace' sfx-py-trace my_application.py
```

**Note: `sfx-py-trace` cannot, by itself, enable auto-instrumentation of Django projects, as the `signalfx_tracing`
instrumentor must still be added to the project settings' installed apps.  Once the application is specified,
`sfx-py-trace` may be used as described in the [Django instrumentation documentation](./signalfx_tracing/libraries/django_/README.md).**

This command line script loader will create a Jaeger tracer instance using the access token specified via
environment variable or argument to report your spans to SignalFx.  It will then call `auto_instrument()` before
running your target application file in its own module namespace.  It's important to note that due to potential
deadlocks in importing forking code, the standard Jaeger tracer cannot be initialized as a side effect of an import
statement (see: [Python threading doc](https://docs.python.org/2/library/threading.html#importing-in-threaded-code) and
[known Jaeger issue](https://github.com/jaegertracing/jaeger-client-python/issues/60#issuecomment-318909730)).
Because of this issue, and for general lack of HTTP reporting support, we highly suggest you use our modified [Jaeger
tracer](#Tracer) that provides deferred thread creation to avoid this constraint.

The application runner will by default attempt to instrument all available libraries for which there are corresponding
instrumentations installed on your system.  If you would like to prevent the tracing of particular libraries at run time,
you can set the `SIGNALFX_<LIBRARY_NAME>_ENABLED=False` environment variables when launching the `sfx-py-trace` process.
For example, to prevent auto-instrumentation of Tornado, you could run:

```sh
  $ SIGNALFX_TORNADO_ENABLED=False sfx-py-trace my_application.py
```

The supported value of each library name is the uppercase form of the corresponding `instrument()`
[keyword argument](#Supported-Frameworks-and-Libraries).

### Trace Decorator
Not all applications follow the basic architectural patterns allowed by their frameworks, and no single tool will be
able to represent all use cases without user input.  To meaningfully unite isolated traces into a single, more
representative structure, or to decompose large spans into functional units, manual instrumentation will
become necessary.  The SignalFx-Tracing Library provides a helpful function decorator to automatically create spans
for tracing your custom logic:

```python
from signalfx_tracing import trace
import opentracing

from my_app import annotate, compute, report

@trace  # uses global opentracing.tracer set by signalfx_tracing.utils.create_tracer()
def my_function(arg):  # default span operation name is the name of the function
    # span will automatically trace duration of my_function() without any modifications necessary
    annotated = annotate(arg)
    return MyBusinessLogic().my_other_function(annotated)

class MyBusinessLogic:

    @classmethod  # It's necessary to declare @trace after @classmethod and @staticmethod
    @trace('MyOperation')  # Specify span operation name
    def my_other_function(cls, arg):
        # Using OpenTracing api, it's possible to modify current spans.
        # This active span is 'MyOperation', the current traced function and child of 'my_function'.
        span = opentracing.tracer.active_span
        span.set_tag('MyAnnotation', arg)
        value = cls.my_additional_function(arg)
        return report(value)

    @staticmethod
    @trace('MyOtherOperation',  # Specify span operation name and tags
           dict(tag_name='tag_value',
                another_tag_name='another_tag_value'))
    def my_additional_function(arg):
        span = opentracing.tracer.active_span  # This active span is 'MyOtherOperation', the child of 'MyOperation'.
        value = compute(arg)
        span.set_tag('ComputedValue', value)
        return value
```

In the above example, any invocation of `my_function()` will result in a trace consisting of at least three spans
whose relationship mirrors the call graph.  If `my_function()` were to be called from another traced function or
auto-instrumented request handler, its resulting span would be parented by that caller function's span.

**Note: As the example shows, `@trace` must be applied to traced methods before the `@classmethod` and `@staticmethod`
decorators are evaluated (declared after), as the utility doesn't account for their respective descriptor
implementations at this time. Not doing so will likely cause undesired behavior in your application.**

repository: harnitsignalfx/signalfx-python-tracing

gha_license_id: NOASSERTION

repo_name: harnitsignalfx/signalfx-python-tracing