text:
# expressive-hrbac
Expressjs middleware builder to easily create arbitrary Hierarchical Role-Based Access Control middleware with resource granularity.

- [The problems it solves](#the-problems-it-solves)
- [Phylosophy](#phylosophy)
- [Installation](#installation)
- [Usage examples](#usage-examples)
  - [Grant access to role `admin`](#grant-access-to-role-admin)
  - [Associate functions to labels for easy reference](#associate-functions-to-labels-for-easy-reference)
  - [Logically combine functions](#logically-combine-functions)
  - [Roles](#roles)
    - [The role in the request object](#the-role-in-the-request-object)
    - [Role inheritance](#role-inheritance)
  - [Singleton](#singleton)
    - [Named singletons](#named-singletons)
- [Errors](#errors)
- [Methods](#methods)
  - [addRole(role, parents = null)](#addrolerole-parents--null)
  - [addGetRoleFunc(func)](#addgetrolefuncfunc)
  - [isDescendant(descendant, ancestor)](#isdescendantdescendant-ancestor)
  - [addBoolFunc(label, func)](#addboolfunclabel-func)
  - [or(func1, func2)](#orfunc1-func2)
  - [and(func1, func2)](#andfunc1-func2)
  - [not(func)](#notfunc)
  - [middleware(func)](#middlewarefunc)
  - [getInstance(label = null)](#getinstancelabel--null)
  - [addUnauthorizedErrorFunc(func)](#addunauthorizederrorfuncfunc)
  - [addCustomFunctionErrorFunc(func)](#addcustomfunctionerrorfuncfunc)

# The problems it solves
* Provide access to a given resource only when the user has been awarded a certain role.

   Example: admin can edit any blog posts.

* Provide access to a given resource only when a user has a particular right on the resource

   Example: user can edit his own blog posts but not the posts from other users

* Provide a way of combining logically any condition on roles or resouce access

   Example: a blog post can be edited by admin or by user when he is the blog owner.

And much more...

# Phylosophy
**expressive-hrbac** is function-based. You provide synchounous or asynchrounous functions that take the request and response objects as input and return a true boolean when access must be granted or a false boolean when access must be denied.

**expressive-hrbac** provide ways to build easy-to-reuse middleware from logical combinations of such functions.

# Installation
```sh
npm install expressive-hrbac --save
```

# Usage examples
## Grant access to role `admin`
First build a function that return true when the user has role `admin`.
```js
(req, res) => req.user.role ==== 'admin'
```

A middleware can be created from such function using method `middleware()`.

```js
const router = require('express').Router();

const HRBAC = require('expressive-hrbac');

let hrbac = new HRBAC();

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware((req, res) => req.user.role === 'admin'),
  controller
);
```
Now, endpoint `/blogs/:blogId/posts/:postId` will return HTTP STatus `401` if property `req.user.role` is not set to `admin`.

Maybe you prefer asynchronous functions:

```js
router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware(async (req, res) => await getUserRole(req.user.id) === 'admin'),
  controller
);
```

## Associate functions to labels for easy reference
If you intend to use a function for more than one route you can avoid repeating its definition. You can associate it to a label using method `addBoolFunc()`.

```js
hrbac.addBoolFunc('is admin', async (req, res) => req.user.role === 'admin'));

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware('is admin'),
  controller
);

router.put(
  '/blogs/:blogId/comments/:commentId',
  hrbac.middleware('is admin'),
  controller
);
```

**NOTE**: function `middleware()` can be passed a synchounous/asynchrounous function or a string label associated to a function. This is true for every method that accepts functions.

## Logically combine functions
Suppose you want to grant access to role `admin` or to role `user` but only when `user` is the owner of the blog post, you first create all the functions you need and then combine everything in a single function using methods `and()`, `or()`, `not()`.

```js
hrbac.addBoolFunc('is admin', (req, res) => req.user.role = 'admin'));
hrbac.addBoolFunc('is user', (req, res) => req.user.role = 'user'));
hrbac.addBoolFunc('is post owner', async (req, res) => await Posts.findById(req.params.postId).ownerId === req.user.id ));

hrbac.addBoolFunc(
  'is admin or post owner user',
  hrbac.or(
    'is admin',
    hrbac.and(
      'is user',
      'is post owner'
    )
  )
);

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware('is admin or post owner user'),
  controller
);
```

To build a middleware you don't have to build your functions beforehand. If you don't intend to re-use a function, you can pass it directly to the `middleware()` method while mixing it with already-associated functions.

```js
hrbac.addBoolFunc('is admin', (req, res) => req.user.role === 'admin');
hrbac.addBoolFunc('is user', (req, res) => req.user.role === 'user');

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware(
    hrbac.or(
      'is admin',
      hrbac.and(
        'is user',
        async (req, res) => await Posts.findById(req.params.postId).ownerId === req.user.id
      )
    )
  ),
  controller
);
```

## Roles
So far we have used roles improperly. You should not provide functions checking for roles but use the `addRole()` method instead.

```js
hrbac.addRole('admin');
```

By so doing **expressive-hrbac** will automatically add a boolean function that checks for the `admin` role and associates it to label `admin`.

```js
hrbac.addRole('admin');

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware('admin'),
  controller
);
```

> **NOTE**: as soon as you define a role, you can NOT use the role string as a label for you custom functions.

The role functions can be combined with other funcitons. You simply reference to it with the role string itself. For example here we provide access to `admin` or to any user with ID different from 10.

```js
hrbac.addRole('admin');

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware(
    hrbac.or(
      'admin',
      hrbac.not((req, res) => req.user.userId === 10)
    ),
    controller
  )
);
```

By deafult, **expressive-hrbac** will look into `req.user.role` for the user role. You can change that behaviour providing a function that returns the role from the request object with method `addGetRoleFunc()`.

```js
hrbac.addGetRoleFunc(async (req, res) => await getUserRole(req.user.id));

hrbac.addRole('admin');

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware('admin'),
  controller
);
```
Now, when a request arrives, `expressive-hrbac` will first apply your function provided with `addGetRoleFunc()` in order to extract the user role, and the will apply the role middleware checking if the role is `admin`.

The role defined in the request object can be an array of roles. Meaning that a user can have multiple roles and **expressive-hrbac** will check if any one of them can be granted access.

```js
// assume incoming request has property: req.user.role = ['admin', 'blog_admin']

hrbac.addRole('admin');

// Middleware below will GRANT access as user has
// role `admin` in the list of user's roles
router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware('admin'),
  controller
);
```

### The role in the request object
By way of the the function provided with method `addGetRoleFunc()` or setting the request property `req.user.role` a valid role must be provided to the **expressive-hrbac** middleware. A valid role consists in a string representing the user role or an array of strings representing the user roles. In case no valid role is provided **expressive-hrbac** will call `next()` passing an instance of class `Error` set to HTTP error `401 Unauthorized` (see section [Errors](#errors) below).

### Role inheritance
A role can have one or more parent roles. The role will inherit all access permissions of each of its parent roles. If access is not granted for the role, a second check will be attenped for each parent role, and for each parent role of each parent role and so on.

Role parents are declared as a second argument to the `addRole()` method.

Suppose role `superadmin` should be able to access every resource that `admin` can access.

```js
hrbac.addRole('admin');
hrbac.addRole('superadmin', 'admin');
```
> **NOTE**: a role must have been added before we can inherit from it

In case `superadmin` should inherit from both `admin` and `blog_admin` you pass an array as the second parameter.

```js
hrbac.addRole('admin');
hrbac.addRole('blog_admin');
hrbac.addRole('superadmin', ['admin', `blog_admin`]);
```
Now if `superadmin` does not get access, **expressive-hrbac** will try again with role `admin` and in case of failure with role `blog_admin`.

If `blog_admin` further inherited from `user`, then if `superadmin` does not get access, **expressive-hrbac** will try again with role `admin`, role `blog_admin` and role `user` traversing the inheritance tree.

```js
hrbac.addRole('user');
hrbac.addRole('blog_admin','user');
hrbac.addRole('admin');
hrbac.addRole('superadmin', ['admin', 'blog_admin']);
```

> **NOTE**: when the request object contains an array of roles, the inheritance will be activated for each role in the array.

## Singleton
So far we have worked with single instances of the HRBAC class. This implies that the HRBAC instance that you create an configure in a script will not be available in another script of your application. This might not be what you want. Typically you want to centralize your Access Control. To do so you can use the `getInstance()` method to get a singleton so that you can easily access your Access Control from anywhere in your application.

file1.js
```js
const HRBAC = require('expressive-hrbac');

let hrbac = HRBAC.getInstance('main');

hrbac.addRole('admin');
```

file2.js
```js
const HRBAC = require('expressive-hrbac');

let hrbac = HRBAC.getInstance('main');

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware('admin'),
  controller
);

```

Changing the label you provide to the `getInstance()` you can create as many instances of the HRBAC class accessible from any script file just providing the right label to `getIntance()`.

file1.js
```js
const HRBAC = require('expressive-hrbac');

let hrbacMain  = HRBAC.getInstance('main');
hrbacMain.addRole('admin');

let hrbacGroup = HRBAC.getInstance('groups');
hrbacGroup.addRole('groupadmin');
```

file2.js
```js
const HRBAC = require('expressive-hrbac');

let hrbac = HRBAC.getInstance('main');

router.put(
  '/blogs/:blogId/posts/:postId',
  hrbac.middleware('admin'),
  controller
);

```

file3.js
```js
const HRBAC = require('expressive-hrbac');

let hrbac = HRBAC.getInstance('groups');

router.put(
  '/groups/:groupId',
  hrbac.middleware('groupadmin'),
  controller
);

```

# Errors
In case of denied access **expressive-hrbac** will call `next()` passing an instance of class `Error` set to HTTP error `401 Unauthorized`. You can change such behaviour providing a function to handle access denials using method `addUnauthorizedErrorFunc()`. In the example below we return HTTP `403 Forbidden` except for user with id 10 which will get a `400 Bad Request`.

```js
hrbac.addUnauthorizedErrorFunc((req, res, next) => {
  let err = new Error();
  if (req.user.id === 10) {
    err.message = 'Bad Request';
    err.status = 400;
  } else {
    err.message = 'Forbidden';
    err.status = 403;
  }
  next(err);
})
```

The `addUnauthorizedErrorFunc()` can also take a fourth argument to further customise, on a per-endpoint basis, the returned error in case of access denial. Start by passing a second argument to the `middleware()` function that defines an access control rule for an endpoint.

```js
router.put(
  '/groups/:groupId',
  hrbac.middleware('groupadmin', { userName: 'James', http: { code: 404, message = 'Not Found'}}),
  controller
);
```

In case of access denial the function you defined with `addUnauthorizedErrorFunc()` will be called with a fourth argument containing your extra argument.

```js
hrbac.addUnauthorizedErrorFunc(async (req, res, next, myData) => {
  let err = new Error();
  if (await User.getName(req.user.id) === myData.name) {
    err.message = myData.http.message;
    err.status = myData.http.code;
  } else {
    err.message = 'Forbidden';
    err.status = 403;
  }
  next(err);
})
```

In case of errors in the custom functions added using method `addBoolFunc()` **expressive-hrbac** will call `next()` passing an instance of class `Error` set to HTTP error `500 Internal Server Error (<original error message>)` where `<original error message>` will be set to the message of the thrown internal message. You can change such behaviour providing a function to handle error in custom functions using method `addCustomFunctionErrorFunc()`. The first argument passed to `addCustomFunctionErrorFunc()` is the error thrown by the server due to the error in the custom function. In the example below we return HTTP `500 This is very bad! This is what happened: <original error message>`.

```js
hrbac.addCustomFunctionErrorFunc((err, req, res, next) => {
  err.message = 'This is very bad! This is what happened: ' + err.message;
  err.status = 500;
  next(err);
});
```
# Methods

## addRole(role, parents = null)
Adds a role to the HRBAC instance. Also add a function associated to the role string.

**Parameters**:
-   `role`: [**string**] - The role string to be added
-   `parents`: (_optional_) [**string | string[]**] - The parent role or array of parent roles for this role

**Returns**:
-   [**HRBAC**] current HRBAC instance.

**Throws**:
-   `UndefinedParameterError`: When `role` is undefined.
-   `NullParameterError`: When `role` is null.
-   `EmptyParameterError`: When `role` is empty string.
-   `NotAStringError`: when `role` is not a string.
-   `RoleAlreadyExistsError`: If `role` already exists.
-   `LabelAlreadyInUseError`: If `role` has already been used as label for a function.
-   `MissingRoleError`: If any parent role has not been added yet.

## addGetRoleFunc(func)
Adds a function to get the role from the request object

**Parameters**:
-   `func`: [**sync/async function**] - Function to be called

**Returns**:
-   [**HRBAC**] current HRBAC instance.

**Throws**:
-   `UndefinedParameterError`: When `func` is undefined.
-   `NullParameterError`: When `func` is null.
-   `NotAFunctionError`: when `func` is not a sync/async function.
-   `ParameterNumberMismatchError`: when `func` does not take exactly 2 arguments.

## isDescendant(descendant, ancestor)
Informs if in currently configured HRBAC instance a role is descandant of another role

**Parameters**:
-   `descendant`: [**string**] - The descendant role string
-   `ancestor`: [**string**] - The ancestor role string

**Returns**:
-   [**boolean**] `true` if `descendant` role is a descendant of `ancestor` role. `false` otherwise.

**NOTE**: roles are NOT descendants of themselves.

**Throws**:
-   `UndefinedParameterError`: When `descendant` or `ancestor` is undefined.
-   `NullParameterError`: When `descendant` or `ancestor` is null.
-   `EmptyParameterError`: When `descendant` or `ancestor` is empty string.
-   `NotAStringError`: when `descendant` or `ancestor` is not a string.
-   `MissingRoleError`: If `descendant` or `ancestor` role has not been added yet.

## addBoolFunc(label, func)
Adds a boolean function and associates it to the provided label

**Parameters**:
-   `label`: [**string**] - The label to associate the function to
-   `func`: [**sync/async function**] - Function returning boolean.

**Returns**:
-   [**HRBAC**] current HRBAC instance.

**Throws**:
-   `UndefinedParameterError`: When `label` or `func` is undefined.
-   `NullParameterError`: When `label` or `func` is null.
-   `EmptyParameterError`: When `label` is empty string.
-   `NotAStringError`: when `label` is not a string.
-   `NotAFunctionError`: when `func` is not a sync/async function.
-   `LabelAlreadyInUseError`: If `label` has already been used as label.
-   `ParameterNumberMismatchError`: when `func` does not take exactly 2 arguments.

## or(func1, func2)
Combines two function with boolean OR.

**Parameters**:
-   `func1`: [**string | sync/async function**] - Label or actual function
-   `func2`: [**string | sync/async function**] - Label or actual function

**Returns**:
-   [**sync/async function**] - Combined function

**Throws**:
-   `UndefinedParameterError`: When `func1` or `func2` is undefined.
-   `NullParameterError`: When `func1` or `func2` is null.
-   `EmptyParameterError`: When `func1` or `func2` is a string which is empty.
-   `MissingFunctionError`: When `func1` or `func2` is a string but it is not associated to a function
-   `NotAFunctionError`: When `func1` or `func2` is not a string and it is not a sync/async function.
-   `ParameterNumberMismatchError`: when `func1` or `func2` is not a string and it is not a function which takes exactly 2 arguments.

## and(func1, func2)
Combines two function with boolean AND.

**Parameters**:
-   `func1`: [**string | sync/async function**] - Label or actual function
-   `func2`: [**string | sync/async function**] - Label or actual function

**Returns**:
-   [**sync/async function**] - Combined function

**Throws**:
-   `UndefinedParameterError`: When `func1` or `func2` is undefined.
-   `NullParameterError`: When `func1` or `func2` is null.
-   `EmptyParameterError`: When `func1` or `func2` is a string which is empty.
-   `MissingFunctionError`: If `func1` or `func2` is a string but it is not associated to a function.
-   `NotAFunctionError`: when `func1` or `func2` is not a string and it is not a sync/async function.
-   `ParameterNumberMismatchError`: when `func1` or `func2` is not a string and it is not a function which takes exactly 2 arguments.

## not(func)
Returnes negated function

**Parameters**:
-   `func`: [**string | sync/async function**] - Label or actual function

**Returns**:
-   [**sync/async function**] - Negated function

**Throws**:
-   `UndefinedParameterError`: When `func` is undefined.
-   `NullParameterError`: When `func` is null.
-   `EmptyParameterError`: When `func` is a string which is empty.
-   `MissingFunctionError`: If `func` is a string but it is not associated to a function
-   `NotAFunctionError`: when `func` is not a string and it is not a sync/async function.
-   `ParameterNumberMismatchError`: when `func` is not a string and it is not a function which takes exactly 2 arguments.

## middleware(func, userArg = null)
Returns middleware function.

**Parameters**:
-   `func`: [**string | sync/async function**] - Function label or actual function
-   `userArg`: (_optional_) [**any type**] - user-defined argument passed to error function in case of access denial

**Returns**:
-   [**sync/async function**] - middleware

**Throws**:
-   `UndefinedParameterError`: When `func` is undefined.
-   `NullParameterError`: When `func` is null.
-   `EmptyParameterError`: When `func` is a string which is empty.
-   `MissingFunctionError`: If `func` is a string but it is not associated to a function
-   `NotAFunctionError`: when `func` is not a string and it is not a sync/async function.
-   `ParameterNumberMismatchError`: when `func` is not a string and it is not a function which takes exactly 2 arguments.

## getInstance(label = null)
Returns, and create if necessary, an HRBAC instance associated to `label`. If `label` is not provided will return an application-wide singleton.

**Parameters**:
-   `label`: (_optional_) [**string**] - label to associate the instance to. If not provided will return an application-wide singleton.

**Returns**:
-   [**HRBAC**] HRBAC instance associated to `label` if provided or  an application-wide singleton.

**Throws**:
-   `EmptyParameterError`: When `label` is empty string.
-   `NotAStringError`: when `label` is not a string.

## addUnauthorizedErrorFunc(func)
Adds a function to handle access denials.

**Parameters**:
-   `func`: [**sync/async function**] - Function to be called

**Returns**:
-   [**HRBAC**] current HRBAC instance.

**Throws**:
-   `UndefinedParameterError`: When `func` is undefined.
-   `NullParameterError`: When `func` is null.
-   `NotAFunctionError`: when `func` is not a sync/async function.
-   `ParameterNumberMismatchError`: when `func` does not take 3 or 4 arguments.

## addCustomFunctionErrorFunc(func)
Adds a function to handle errors with the boolean functions provided.

**Parameters**:
-   `func`: [**sync/async function**] - Function to be called

**Returns**:
-   [**HRBAC**] current HRBAC instance.

**Throws**:
-   `UndefinedParameterError`: When `func` is undefined.
-   `NullParameterError`: When `func` is null.
-   `NotAFunctionError`: when `func` is not a sync/async function.
-   `ParameterNumberMismatchError`: when `func` does not take exactly 4 arguments.


text:
---
graph_title: Mountain Green Cover Index (CBB)
target_id: 15.4.2
indicator: 15.4.2
sdg_goal: 15
permalink: /en/statistics_glob/15-4-2/
source_url: null
graph: null
pre: 1
jednostka: percent
zmienne: null
kategorie: null
indicator_variable_1: total
layout: indicator
title: Mountain Green Cover Index (CBB)
lang: en
nazwa_wskaznika: 15.4.2 Mountain Green Cover Index (CBB)
cel: Goal 15. Life on land
zadanie: >-
  15.4 By 2030, ensure the conservation of mountain ecosystems, including their
  biodiversity, in order to enhance their capacity to provide benefits that are
  essential for sustainable development
uwagi: >-
  Mountains classification described in: Kapos V. Developing a map of the
  world's mountain forests., w M.Price i N.Butt (EDS.) Forests in sustainable
  mountain development: a state of knowledge report for 2000. Wallingford: CAB
  International.
published: true
definicja: >-
  The percentage ratio of green vegetation in mountain areas (i.e. forest,
  grassland, shrubland, pasture land, crop land, etc.) to mountain area.
jednostka_prezentacji: 'percent [%]'
dostepne_wymiary: 'total, Kapos class'
wyjasnienia_metodologiczne: >-
  Mountains are defined according to the UNEP-WCMC classification that
  identifies them according to altitude, slope and local elevation range as
  described by Kapos et al. 2000:
 Class 1: elevation > 4,500 meters

  Class 2: elevation 3,500–4,500 meters
 Class 3: elevation 2,500–3,500
  meters
 Class 4: elevation 1,500–2,500 meters and slope > 2
 Class 5:
  elevation 1,000–1,500 meters and slope > 5 or local elevation range (LER 7
  kilometer radius) > 300 meters
 Class 6: elevation 300–1,000 meters and
  local elevation range (7 kilometer radius) > 300 meters

zrodlo_danych: ' Head Office of Geodesy and Cartography'
czestotliwosc_dostępnosc_danych: Annual data; since 2019.
---

repository: JoWojc/sdg-indicators-pl

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: JoWojc/sdg-indicators-pl


text:
# Role Name

`download_linux_packages_src`

## Description

This role is the Linux equivalent of the `download_win_packages_src` role.

Downloads the contents of `gs://skia-buildbots/skolo/linux/linux_package_src` into a temporary
directory on the local machine, and makes it available to subsequent tasks via the
`linux_package_src` variable. The temporary directory will be automatically cleaned up via a
handler.

If the GCS directory grows too big, this might take several minutes. To skip the download and use a
local copy, invoke your playbook with `--extra-vars linux_package_src=path/to/local/copy`.

## Example Playbook

```yml
- hosts: all_linux
  user: chrome-bot
  gather_facts: yes

  roles:
    - download_linux_packages_src

  tasks:
    - name: Copy Nvidia driver installer
      copy:
        src: '{{ linux_package_src }}/NVIDIA-Linux-x86_64-535.86.05.run'
        dest: /tmp/NVIDIA-Linux-x86_64-535.86.05.run
```

repository: google/skia-buildbot

branch_name: refs/heads/main

gha_language: Go

repo_name: google/skia-buildbot


text:
# Emoji Haiku!

> 🌌 🏕

> 🇹🇩 🖖

> 🎽 📛
>
> MILKY WAY CAMPING

> FLAG FOR CHAD VULCAN SALUTE

> RUNNING SHIRT NAME BADGE

## What?

Emoji Haiku is a small program that generates nonsense poems in a 5-7-5 syllable pattern based on
the Unicode emoji descriptions.

Generate your own, bespoke haiku at [capnfabs.net/emoji-haiku](http://capnfabs.net/emoji-haiku), or follow
[@emojihaikus on twitter](http://twitter.com/emojihaikus) for one every 6 hours 😁

## How do I use it?

Head to http://capnfabs.net/emoji-haiku.

Alternatively, take a look at [developer_notes.md](developer_notes.md) for details about how the code works, and how to run various things.

## Acknowledgements
Somewhat inspired by:
- [Haiku by Robot](https://twitter.com/haiku_by_robot)
- [Wizard Generator](https://twitter.com/WizardGenerator)
- [Aubergine Bot](https://twitter.com/AubergineBot)
- [Emoji Tracker](http://emojitracker.com/)
- ...and plenty of others.

With apologies to anyone who has ever put time and energy into a real poem.

repository: capnfabs/emoji-haiku

repo_name: capnfabs/emoji-haiku


text:
# JavaScript Logging
Forwards JavaScript console logs to ASP.NET Core applications.

| Windows | Linux | NuGet |
| --- | --- | --- |
| [![Windows Build status](https://ci.appveyor.com/api/projects/status/rnf0a0wpsi8td146?svg=true)](https://ci.appveyor.com/project/henkmollema/logging-javascript) | [![Linux Build Status](https://travis-ci.com/webenablebv/Logging.JavaScript.svg?branch=master)](https://travis-ci.com/webenablebv/Logging.JavaScript) | [![NuGet](https://img.shields.io/nuget/vpre/Webenable.Logging.JavaScript.svg)](https://www.nuget.org/packages/Webenable.Logging.JavaScript) |

JavaScript Logging is a small library which forwards client-side JavaScript logging via `console.info`, `console.error`, etc. to your ASP.NET Core application and logs the message with the equivalent log level using the `ILogger` interface. This library is inspired by the [blogpost](http://hishambinateya.com/integrate-javascript-logging-with-asp.net-core-logging-apis) and [sample application](https://github.com/hishamco/jsLogger) of Hisham and I took the liberty to create a NuGet package from his idea.

## Getting started

Install the package from NuGet:

```
dotnet add package Webenable.Logging.JavaScript
```

Configure the logging library in your Startup class:

```cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddJavaScriptLogging();

    // ...
}
```

The library will automatically inject the necessary JavaScript and register a middleware to handle the logging HTTP requests.

## Dependencies
The library uses jQuery to post log messages to your application using AJAX. Please make sure that jQuery is available when using this library.

## Using the library

Any calls to the following `console` methods are intercepted and will post a log message to the server which logs the message with the corresponding log level. The default behavior of the `console` method is executed as well.

- `console.trace`
- `console.debug`
- `console.info`
- `console.warn`
- `console.error`

Please note that the `console.log` method is _not_ intercepted.

license: MIT


text:
# Section 03: Getting Structure Ready

- [The Cross-Origin Requests](#the-cross-origin-requests)
- [The Django REST Framework](#the-django-rest-framework)
- [Store Images in Django](#store-images-in-django)
- [Setting Django API Structure](#setting-django-api-structure)
- [Handling API Route](#handling-api-route)

## The Cross-Origin Requests

The first packages we should install would be the [`django-cors headers`](https://github.com/adamchainz/django-cors-headers) because we're going to allow the resources to be accessed on other domains. It adds [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) headers to responses and allows in-browser requests to our Django application from other origins.

```bash
# install django-cors-headers
$ pipenv install django-cors-headers
```

After install the package, we should edit the `setting.py` file:

1. Add `'corsheaders'` to `INSTALLED_APPS`.
2. Add `'corsheaders.middleware.CorsMiddleware'` to `MIDDLEWARE`.
3. Set `ALLOWED_HOSTS` to be `['*']`. Because we want all the hosts to be allowed to interact an app.
4. Set `CORS_ORIGIN_ALLOW_ALL` to be `True`.

  [ ↥ Back To Top ]

## The Django REST Framework

The second package should be installed would be [`djangorestframework`](https://github.com/encode/django-rest-framework) because we are going to use the django server as an API server and expose the RESTful API for React front-end.

```bash
# install django-rest-framework
$ pipenv install djangorestframework
```

After install the package, we should edit the `setting.py` file:

1. Add `'rest_framework'` to `INSTALLED_APPS`. The `rest_framework` is going to be required for throwing up the JSON format for product categories, orders and so on.
2. Add `'rest_framework.authtoken'` to `INSTALLED_APPS`. The `'rest_framework.authtoken'` is going to be required so that customers signup can be created.
3. Setup `REST_FRAMEWORK`. Just paste the code shown below:
    ```python
    REST_FRAMEWORK = {
        # Use Django's standard `django.contrib.auth` permissions,
        # or allow read-only access for unauthenticated users.
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.BasicAuthentication',
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.TokenAuthentication',
        ],
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
        ]
    }
    ```

After doing so, we can edit the `urls.py` file and add the routes:

```python
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth', include('rest_framework.urls'))
]
```

  [ ↥ Back To Top ]

## Store Images in Django

There are a couple of ways and couple of strategies that we can follow while holding up images, audios and videos. We're going to create a folder `media` to keep the images and insert the following code to `settings.py` (be careful to add slash `/` after the path):

```python
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
```

Don't forget to add the path to `urls.py`:

```python
...
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    ...
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```

  [ ↥ Back To Top ]

## Setting Django API Structure

It's a better approach to create another app which will be `API` to be interacted, transferred or received instead of serving APIs in the `ecom` app.

```bash
# create another app
$ django-admin startapp api
```

Then we're going to create `category`, `order`, `payment`, `product` and `user` inside the app `api`.

```bash
# don't forget to move into the directory of api
$ cd api

# create apps inside api
$ django-admin startapp category
$ django-admin startapp order
$ django-admin startapp payment
$ django-admin startapp product
$ django-admin startapp user
```

  [ ↥ Back To Top ]

## Handling API Route

Remember that any installed app needs to be taken up in `INSTALLED_APPS` in `settings.py`. Then we need to edit the `urls.py` in `ecom` folder:

```python
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth', include('rest_framework.urls')),
    path('api/', include('api.urls'))
]
```

Notice that we include the `urls` inside the `api` so that we should create the `urls.py` in the `api` folder:

```python
from django.urls import path, include
from rest_framework.authtoken import views
from .views import home

urlpatterns = [
    path('', home, name='api.home'),
]
```

Notice that the `home` is from `views.py` in the `api` folder:

```python
from django.http import JsonResponse

# Create your views here.
def home(request):
    return JsonResponse({'info': 'Django React Course', 'name': 'hitech'})
```

  [ ↥ Back To Top ]

path: /03 - Getting Structure Ready/README.md


text:
# Laravel 5.5 Lumen 5.5 Github Code API

[![Build Status](https://travis-ci.org/laravel/lumen-framework.svg)](https://travis-ci.org/laravel/lumen-framework)
[![Total Downloads](https://poser.pugx.org/laravel/lumen-framework/d/total.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![Latest Stable Version](https://poser.pugx.org/laravel/lumen-framework/v/stable.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![Latest Unstable Version](https://poser.pugx.org/laravel/lumen-framework/v/unstable.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![License](https://poser.pugx.org/laravel/lumen-framework/license.svg)](https://packagist.org/packages/laravel/lumen-framework)

INSTALLATION
-------------------
```
Step1. cd /var/www
git clone -b master https://github.com/sirinibin/codeapi.git codeapi

Note:Make sure you have  at least php7.1  or php7.0  or else you may face some issues while installing laravel lumen.

Step2. cd codeapi
       composer install

Step3. Point API end point URL to /var/www/codeapi/public

      eg: http://codeapi.dockerboxes.us

```

## Security Vulnerabilities

If you discover a security vulnerability within this template, please send an e-mail to Sirin k at<EMAIL_ADDRESS>All security vulnerabilities will be promptly addressed.

## License

The Lumen framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)

repository: sirinibin/codeapi

repo_name: sirinibin/codeapi


text:
## Sentiment Analysis Example

```python
from ekphrasis.classes.preprocessor import TextPreProcessor
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.utils.nlp import polarity

sentences = [
    "So there is no way for me to plug it in here in the US unless I go by a converter.",
    "Good case, Excellent value.",
    "Works great!",
    'The design is very odd, as the ear "clip" is not very comfortable at all.',
    "Needless to say, I wasted my money."
]

# define preprocessing pipeline
text_processor = TextPreProcessor(
    fix_text=True,
    unpack_contractions=True,
    tokenizer=SocialTokenizer(lowercase=True).tokenize,
)

# pass each sentence through the pipeline
tokenized_sentences = list(text_processor.pre_process_docs(sentences))
for sent in tokenized_sentences:
    _polarity, _scores = polarity(sent)
    print("{:.4f}\t".format(_polarity) + " ".join(sent))
```

#### Output

```shell
0.0139	so there is no way for me to plug it in here in the us unless i go by a converter .
0.3750	good case , excellent value .
0.0000	works great !
0.0500	the design is very odd , as the ear " clip " is not very comfortable at all .
0.0500	needless to say , i wasted my money .
```

repository: cbaziotis/ekphrasis

gha_language: Python

gha_license_id: MIT

repo_name: cbaziotis/ekphrasis


text:
# Google Charts Generator

----
## Overview

The Google Charts Generator is a suite of javascript files and stylesheets allowing a user to draw Google Charts using only HTML.

For a preview of the latest development snapshot, [visit the app's page on Plunker](http://plnkr.co/v0o82y "Plunker - Google Charts Generator").

> Example 1:

            {Name}

...Will display a Table Chart.

The columns and rows are set using data tags (e.g., "data-label") and custom attributes (e.g., "visibility"). No custom javascript coding is necessary, meaning non-developers can implement Google Charts simply by editing familiar html, and referring to these instructions.

The Generator (or "application") should fit the majority of basic use cases, but the code can be edited directly and extended. If, for instance, you need certain jQuery events to be triggered by the Google Charts API, you will need to write your own custom functions and callbacks and hook into the chartGenerator.js file.

----
## Dependencies
The application primarily depends on the Google Charts API, and so that will need to be loaded in the header (or above the html used to draw the chart).

There are also several other libraries that are referenced in the chartConstructor and chartGenerator files, and so also need to be referenced in the header (or first body section). You can download several of these libraries straight from source, or use a CDN, but specific version are provided here as well.

Some of the files need to be referenced in a particular order, and others don't, so for simplicity, reference the files in your header in this order:

1. FontAwesome (CSS)
2. Bootstrap (CSS)
3. ChartGenerator (CSS)
4. jQuery (JS)
5. Google API Loader (JS)

And in the footer (or below the html defining how to draw the charts), reference, in order, the following:

1. ChartConstructor (JS)
2. Chart Generator (JS)

## Constructing the Main Table
*See Example 1, above*

### Steps:
1. Create a div element with an arbitrary id.
2. Assign the div the following classes: "gChart mainTable chartVisible".
3. Assign the div a data tag to specify the chart type (currently either "table" or "pie"). For example, a the main table is constructed with "data-charttype="table".
4. Include a div inside the mainTable with class of "dataColumns."
5. For each column you want in your table, add a div with the following attributes:
    * id,
    * data-type: (number, string, or calc),
    * data-label,
    * data-key,
    * width

## Creating Data Columns
*See Example 1, above*

All data columns, regardless of chart type, need to be placed in a div (class: "dataColumns" within the parent div (class: "gChart"). The subordinate divs (subordinate to ".dataColumns") do not need any classes of their own.

Within each column div, specify the following parameters:

* id: This is an arbitrary string used to distinguish one data column from another.
* data-type: number, string, or calc.
* data-label: The label that appears in the header for the column.
* data-key: This is the key used to retrieve the data. It has to match the JSON data exactly, and you need to know it in advance.
  * Example: In sample-data.js, the identifier (or key) for the employee's name is "name". Note the lower case (case matters).
* width: Specify the width of the table column in pixels. Note: width will not affect the display for other chart types (like pie, bar, etc.), so it only needs to be included in table charts.
* visibility: If visibility="hidden", you hide the entire column.

## Creating Calculated Columns

> Example 2:

        {Name}

Whether you are using calculated columns in a table visualization, a pie visualization, or any other type, the approach is the same:

1. Create a data column div with some additional parameters:
  * data-calcdispose: Available values (preserve or replace) specify whether to keep the source columns in the data table or not. You can always hide the source columns, so there's really not much reason to select replace, but you might need to. Default: "preserve".
  * data-calctype: Specifies whether the calculated column function will be performing mathematics (e.g., data-calctype="number") or text replacements (e.g., data-calctype="string").
2. If you are creating a column that inserts texts from the values in other columns, simply use enclosing brackets ("{" and "}") to specify the source columns. The text within the brackets must match the id (not the label) of another data column.

## The Dashboard

> Example 3:

There can only be one dashboard per page, so to create a dashboard, simply create a div with an id of "dashboard" and a class of "gDashboard". (The need to include a class at all will eventually be phased out).

Within the dashboard, create a div (class: "dashControls").

Within .dashControls, create divs for your controls, including the following parameters:

1. id: Arbitrary
2. data-label: Must match the id (not the label) of a data column specified in a chart.
3. data-type: The type of data being filtered against (e.g., for the "name" column, this value would be "string").
4. data-controltype: Can be one of several values:
  * category: a dropdown selecting text
  * number: a slider allowing the selection of values within a range
  * string: a text input akin to a search box
  * date: a slider allowing the selection of dates within a range

repository: chrisbuck/google-charts-generator

repo_name: chrisbuck/google-charts-generator


text:
# Java Light

The purpose of this section is to introduce some common aspects of the Java programming language **without delving into any depths**.  When discussing any topic in some detail we may need to also touch other topics that have not yet been mentioned.  For example, loops and collections go together and either way you start, one needs to come before the other.  This section acts as an introduction, hopefully simplifying the digesting the rest of the boot camp.  Do not worry if some of the concepts do not sink in as each item is discussed in depth later on.

## TOC

1. [Setup](#setup)
1. [JShell](#jshell)
1. [Java single file execution](#java-single-file-execution)
1. [Introduction to classes and methods](#introduction-to-classes-and-methods)
    1. [Source and class files](#source-and-class-files)
    1. [Methods](#methods)
1. [Using existing functionality](#using-existing-functionality)
1. [Introduction to variables and types](#introduction-to-variables-and-types)
1. [Introduction to collections](#introduction-to-collections)
    1. [Arrays](#arrays)
    1. [Lists](#lists)
1. [Introduction to control-flow](#introduction-to-control-flow)
    1. [If-Else](#if-else)
    1. [switch](#switch)
    1. [For loop](#for-loop)
1. [Annotations](#annotations)

## Setup

1. Clone Repo: [java-boot-camp-blueprint](https://github.com/albertattard/java-boot-camp-blueprint)

    ```bash
    $ git clone https://github.com/albertattard/java-boot-camp-blueprint.git
    ```

1. Open the repo in IDE

## JShell

The [Java Shell tool (JShell)](https://docs.oracle.com/javase/9/jshell/introduction-jshell.htm) is an interactive tool for learning the Java programming language and prototyping Java code.  JShell is a Read-Evaluate-Print Loop (REPL), which evaluates declarations, statements, and expressions as they are entered and immediately shows the results.

**⚠ JShell maximise simplicity and relaxed some of the rules that apply to a normal Java program.  While the JShell is great to practice and try somethings out, code that works in JShell may not work in Java.**

1. Open JShell

    ```bash
    $ jshell
    ```

    The following error maybe shown

    ```bash
    Unable to locate an executable at "~/.sdkman/candidates/java/current/bin/jshell" (-1)
    ```

    Verify the version of Java

    ```bash
    $ java -version
    openjdk version "1.8.0_252"
    OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_252-b09)
    OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.252-b09, mixed mode)
    ```

    **JShell requires Java 9 or higher**

    ```jshelllanguage
    |  Welcome to JShell -- Version 14.0.1
    |  For an introduction type: /help intro

    jshell>
    ```

    To exit JShell, type `/exit`

    ```jshelllanguage
    jshell> /exit
    ```

1. Help

    ```jshelllanguage
    jshell> /help
    |  Type a Java language expression, statement, or declaration.
    |  Or type one of the following commands:
    |  /list [<name or id>|-all|-start]
    |  	list the source you have typed
    |  /edit <name or id>
    |  	edit a source entry
    |  /drop <name or id>
    ...
    |  rerun
    |  	a description of ways to re-evaluate previously entered snippets
    ```

1. Create a variable

    ```jshelllanguage
    jshell> a = 7
    |  Error:
    |  cannot find symbol
    |    symbol:   variable a
    |  a = 7
    |  ^
    ```

    **In Java, variables require a type**.  [Java is a statically typed language](https://docs.oracle.com/javase/specs/jls/se14/html/jls-4.html).

    ```jshelllanguage
    jshell> int a = 7
    a ==> 7
    ```

    Normally, a semicolon needs to be added at the end of the statement, indicating the end of statement (as defined by the [JLS 14.8](https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.8)).

    ```jshelllanguage
    jshell> int a = 7;
    a ==> 7
    ```

    **⚠ Note that while the semicolon is optional in JShell, this is required in a Java program.  The program will not compile if we ignore the semicolon at the end of the statement**.

    Enter the variable name to print its value

    ```jshelllanguage
    jshell> a
    a ==> 7
    ```

    Java 10 introduced Local Variable Type Inference ([JEP 286](https://openjdk.java.net/jeps/286)).  Previously, all local variable declarations required an explicit (manifest) type on the left-hand side.  With type inference, the explicit type can be replaced by the reserved type name `var` for local variable declarations that have initializers.  The type of the variable is inferred from the type of the initializer.

    ```jshelllanguage
    jshell> var x = 7
    x ==> 7
    ```

    For more information about Local Variable Type Inference please refer to the [style guidelines](http://openjdk.java.net/projects/amber/LVTIstyle.html) and [article Java Feature Spotlight: Local Variable Type Inference by Brian Goetz](https://www.infoq.com/articles/java-local-variable-type-inference/).

    Note that once a variable is created, it cannot change its type.  Once we create an `int`, that variable will stay an `int` and cannot accept anything else.

    ```jshelllanguage
    jshell> int x = 7
    jshell> x = 7.7
    |  Error:
    |  incompatible types: possible lossy conversion from double to int
    |  x = 7.7
    |      ^-^
    ```

    Different from many other languages, [Java is a statically typed language](https://docs.oracle.com/javase/specs/jls/se14/html/jls-4.html) and we cannot compare the integer `1` to the boolean `true`

    ```jshelllanguage
    jshell> 1 == true
    |  Error:
    |  incomparable types: int and boolean
    |  1 == true
    |  ^-------^
    ```

1. Arithmetic Operations

    ```jshelllanguage
    jshell> int b = 3
    b ==> 3

    jshell> a + b
    $4 ==> 10
    ```

    The result is stored in a new temporary variable, `$4`, (crated by JShell) which can be accessed as any other variable.

    ```jshelllanguage
    jshell> $4
    $4 ==> 10
    ```

1. Use existing functionality

    JShell imports automatically classes and functionality from the following packages

    ```jshelllanguage
    jshell> /imports
    |    import java.io.*
    |    import java.math.*
    |    import java.net.*
    |    import java.nio.file.*
    |    import java.util.*
    |    import java.util.concurrent.*
    |    import java.util.function.*
    |    import java.util.prefs.*
    |    import java.util.regex.*
    |    import java.util.stream.*
    ```

    For example, we can use the `Random` class, found in the `java.util` package.

    ```jshelllanguage
    jshell> var r = new Random()
    r ==> java.util.Random@533ddba

    jshell> r.nextInt(10)
    $3 ==> 8
    ```

    JShell has tab completion.  Type `Math.` and then press the `[tab]` key

    ```jshelllanguage
    jshell> Math.
    E                 IEEEremainder(    PI                abs(              acos(             addExact(         asin(             atan(             atan2(            cbrt(             ceil(             class             copySign(
    cos(              cosh(             decrementExact(   exp(              expm1(            floor(            floorDiv(         floorMod(         fma(              getExponent(      hypot(            incrementExact(   log(
    log10(            log1p(            max(              min(              multiplyExact(    multiplyFull(     multiplyHigh(     negateExact(      nextAfter(        nextDown(         nextUp(           pow(              random()
    rint(             round(            scalb(            signum(           sin(              sinh(             sqrt(             subtractExact(    tan(              tanh(             toDegrees(        toIntExact(       toRadians(
    ulp(
    jshell> Math.
    ```

    You will see all methods (functionality) available to the `Math` class.

    ```jshelllanguage
    jshell> int a = 7
    jshell> int b = 3
    jshell> Math.max(a, b)
    $5 ==> 7
    ```

    We can import all methods available in the `Math` class so that we can invoke these methods by their name.

    ```jshelllanguage
    jshell> import static java.lang.Math.*

    jshell> max(a, b)
    $5 ==> 7

    jshell> PI
    PI ==> 3.141592653589793
    ```

    A list of functions available in the Math class can be found [here](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Math.html).

1. Add new functionality (a method)

    ```jshelllanguage
    jshell>  int sum(int a, int b) {
       ...> return a+b;
       ...> }
    |  created method sum(int,int)
    ```

    The created a method, named `sum()`, takes two integers and returns their sum.

    ```jshelllanguage
    jshell> sum(4,5)
    $7 ==> 9
    ```

For more information about JSHell, please refer to the [JShell documentation](https://docs.oracle.com/javase/10/jshell/JSHEL.pdf).

## Java single file execution

Java 11 introduced Java Single File Execution ([JEP-330](https://openjdk.java.net/jeps/330)) which enhanced the java launcher to run a program supplied as a single file of Java source code, including usage from within a script by means of "[shebang" files](https://openjdk.java.net/jeps/330#Shebang_files) and related techniques.

```java
$ vi hello
```

**The script file name does not need to match the class name**.

```jshelllanguage
#!/usr/bin/java --source 11

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World!!");
  }
}
```

The script needs to be executable

```bash
$ chmod +x hello
```

and can be executed like any other script

```bash
$ ./hello

Hello World!!
```

The [gist x_init](https://gist.github.com/albertattard/3f9a66faf2a90dc2bf6376d37c7c6052) shows a more elaborated example.

## Introduction to classes and methods

### Source and class files

**🚧 Pending...**

```java
package demo;

public class App {
  public static void main( final String[] args ) {
    System.out.println( "Hello World!!" );
  }
}
```

```bash
Hello world!!
```

```bash
$ tree src/main/java
src/main/java
└── demo
    └── App.java
```

```bash
$ tree build/classes/java
build/classes/java
└── main
    └── demo
        └── App.class
```

```bash
$ ./gradlew run

> Task :run
Hello world!!

BUILD SUCCESSFUL in 714ms
2 actionable tasks: 2 executed
```

```bash
$ java -cp build/classes/java/main demo.App
Hello world!!
```

### Methods

**🚧 Pending...**

```java
package demo;

public class App {
  public static void main( final String[] args ) {
    printHello();
  }

  public static void printHello() {
    System.out.println( "Hello world!!" );
  }
}
```

```bash
Hello world!!
```

## Using existing functionality

```java
import java.time.LocalDate;
```

```java
package demo;

import java.time.LocalDate;

public class App {
  public static void main( final String[] args ) {
    System.out.printf( "Today's date is %s%n", LocalDate.now() );
  }
}
```

```bash
Today's date is 2020-04-27
```

## Introduction to variables and types

**🚧 Pending...**

```java
package demo;

public class App {
  public static void main( final String[] args ) {
    int a = 7;
    System.out.printf( "The value of a is %d%n", a );
  }
}
```

```bash
The value of a is 7
```

```java
package demo;

import java.time.LocalDate;

public class App {
  public static void main( final String[] args ) {
    String name = "Aden";
    LocalDate dateOfBirth = LocalDate.of( 2011, 4, 12 );
    System.out.printf( "%s was born on %s%n", name, dateOfBirth );
  }
}
```

```bash
Aden was born on 2011-04-12
```

## Introduction to collections

### Arrays

**🚧 Pending...**

```java
package demo;

import java.util.Arrays;

public class App {
  public static void main( final String[] args ) {
    int[] numbers = { 4, 7, 2, 8, 6 };
    numbers[0] = 1;

    System.out.printf( "Numbers: %s%n", Arrays.toString( numbers ) );
    System.out.printf( "Length of array: %d%n", numbers.length );
    System.out.printf( "First number: %d%n", numbers[0] );
    System.out.printf( "Last number: %d%n", numbers[4] );
  }
}
```

```java
Numbers: [1, 7, 2, 8, 6]
Length of array: 5
First number: 1
Last number: 6
```

### Lists

**🚧 Pending...**

```java
package demo;

import java.util.ArrayList;
import java.util.List;

public class App {
  public static void main( final String[] args ) {
    List<String> names = new ArrayList<>();
    names.add( "Jade" );
    names.add( "Aden" );

    System.out.printf( "Names: %s%n", names );
    System.out.printf( "Size of list: %d%n", names.size() );
    System.out.printf( "First name: %d%n", names.get( 0 ) );
  }
}
```

```bash
Names: [Jade, Aden]
Size of list: 2
First name: Jade
```

## Introduction to control-flow

### If-Else

**🚧 Pending...**

```java
package demo;

import java.util.ArrayList;
import java.util.List;

public class App {
  public static void main( final String[] args ) {
    List<String> names = new ArrayList<>();
    names.add( "Jade" );
    names.add( "Aden" );

    if ( names.size() == 0 ) {
      System.out.println( "List is empty" );
    } else if ( names.size() == 1 ) {
      System.out.println( "List has one element" );
    } else {
      System.out.println( "List has many elements" );
    }
  }
}
```

```bash
List has many elements
```

### switch

```java
package demo;

import java.util.ArrayList;
import java.util.List;

public class App {
  public static void main( final String[] args ) {
    List<String> names = new ArrayList<>();
    names.add( "Jade" );
    names.add( "Aden" );

    switch ( names.size() ) {
      case 0:
        System.out.println( "List is empty" );
      case 1:
        System.out.println( "List has one element" );
      default:
        System.out.println( "List has many elements" );
    }
  }
}
```

```bash
List has many elements
```

### For loop

```java
package demo;

import java.util.ArrayList;
import java.util.List;

public class App {
  public static void main( final String[] args ) {
    List<String> names = new ArrayList<>();
    names.add( "Jade" );
    names.add( "Aden" );

    System.out.println( "Names in the list" );
    for ( int i = 0; i < names.size(); i++ ) {
      System.out.printf( "[%d] %s%n", i, names.get( i ) );
    }
  }
}
```

```bash
Names in the list
[0] Jade
[1] Aden
```

```java
package demo;

public class App {
  public static void main( final String[] args ) {
    String[] names = { "Jade", "Aden" };

    System.out.println( "Names in array" );
    for ( int i = 0; i < names.length; i++ ) {
      System.out.printf( "[%d] %s%n", i, names[i] );
    }
  }
}
```

```bash
Names in array
[0] Jade
[1] Aden
```

## Annotations

**🚧 Pending...**

repository: brisitw/java-boot-camp

path: /_original/02 - Java Light.md

filename: 02 - Java Light.md

repo_name: brisitw/java-boot-camp


text:
# Decode-Me

This repository contains the solution to the puzzle "Decode Me" that was made for the Clash of Code mode on [CodinGame](https://www.codingame.com).

The contribution link can be found [here](https://www.codingame.com/contribute/view/832ff572b5be085add926260a18fa6d7323).

repository: TheOmyNomy/Decode-Me

repo_name: TheOmyNomy/Decode-Me


text:
# Local and Mid-range Propagation for video object detection (VID)

Code for ACM MM Workshop paper [Online Video Object Detection via Local and Mid-Range Feature Propagation](https://dl.acm.org/doi/10.1145/3422852.3423477)

## Introduction

<img src="https://user-images.githubusercontent.com/23008175/90168988-89058d80-ddd0-11ea-8f7b-c2c669d1f6cf.png" height="60%" width="60%" >

## Installation

This work is implemented based on mmdetection (version 1.0.rc0+477543e, commit hash `97d0855`)

## License

This project is released under the [Apache 2.0 license](LICENSE).
See also https://github.com/open-mmlab/mmdetection/blob/master/LICENSE

## Contact

Feel free to email me<EMAIL_ADDRESS>!

repository: zhifanzhu/Local-Mid-Propagation

repo_name: zhifanzhu/Local-Mid-Propagation


text:
---
layout: simple
math: true
---

# CMPT 295: Unit - Machine-Level Programming

Lecture 9 – Assembly language basics: Data, move operation

## Last Lecture

* Review: von Neumann architecture
* Data and code are both stored in memory during program execution

1. Question: How does our C program end up being represented as a
series of 0’s and 1’s (i.e., as machine code)?
  * Compiler: C program -> assembly code -> machine level code
  * gcc: 1) C preprocessor, 2) C compiler, 3) assembler, 4) linker
2. Question: How does our C program (once it is represented as a series of
0’s and 1’s) end up being stored in memory? Annotation: Loader
  * When C program is executed (e.g. from our demo: ./ss 5 6 )
3. Question: How does our C program (once it is represented as a series of
0’s and 1’s and it is stored in memory) end up being executed by the
microprocessor (CPU)?
  * CPU executes C program by looping through the fetch-execute cycle

## Summary - Turning C into machine level code - gcc

The big picture:

Annotation: Lab 1

* C program (.c) -> sum_store.c
  * C Preprocessor: `gcc -g sum_store.c > sum_store.i` (Annotation: sum_store.c, sum_store.i are text)
    * Expands the header(s) found at the top of the C program by including their content into the C program.
* Preprocessed source (.i) -> sum_store.i
  * C Compiler: `gcc -Og -S sum_store.i` OR `gcc -Og -S sum_store.c`
    * Compiled the C program into an assembly lanaugage program.
* Assembly program (.s) -> sum_store.s
  * Assembler: `gcc -g -c main.s sum_stoore.s` (Annotation: main.s, sum_store.s are text)
    * Assembles the assembly language program into an object file (series of 0's and 1's) which is a combination of machine language instructions, data and info needed to place all of this properly into memory.
* Object (.o) -> sum_store.o
  * Linker: `gcc -o ss main.o sum_store.o` (Annotation: main.o, sum_store.o are binary)
    * Combines independently assembled machine language programs with library routines into an executable file.
* Executable: ss
  * Loader: `./ss 5 6`
    * Loads machine code (from files) into proper memory locations for execution by CPU.
  * (optional) Disassembler, gdb/ddd debugger: `objdump -d ss`
    * disassembled object file is text and binary
* Instruction Set Architecture (ISA)
* Computer executes it.
  * CPU
  * Memory

## Today’s Menu

* Introduction
  * C program -> assembly code -> machine level code
* Assembly language basics: data, move operation
  * Memory addressing modes
* Operation leaq and Arithmetic & logical operations
* Conditional Statement – Condition Code + cmov\*
* Loops
* Function call – Stack
* Array
* Buffer Overflow
* Floating-point operations

## Programming in C versus in x86-64 assembly language

When programming in C, we can …

* Store/retrieve data into/from memory, i.e. variables
* Perform calculations on data
  * e.g., arithmetic, logic, shift
* Transfer control: decide what part of the program to execute
next based on some condition
  * e.g., if-else, loop, function call

When programming in assembly language, we can do the
same things, however …

## Programming in x86-64 assembly

* … with assembly language (and machine code), parts of
the microprocessor state are visible to assembly
programmers that normally are hidden from C programmers
* As assembly programmers, we now have access to …

### Testing a diagram idea

Done with MathML:

{% katex display %}
\text{CPU} = [\text{Registers}, \text{Condition Codes}, \text{PC}] \\
\text{CPU} \xleftrightarrow{Data}{} \text{Memory} \\
\text{CPU} \xrightarrow{Addresses}{} \text{Memory} \\
\text{CPU} \xleftarrow{instructions}{} \text{Memory}
{% endkatex %}

Description: CPU contains registers, condition codes and PC.
CPU has a right arrow pointing to memory labled "addresses".
Memory has a left arrow pointing to CPU labled "instructions".
CPU and Memory have a two sides arrow pointing to eachother with the label "data".

## Hum … Why are we learning assembly language?

(empty slide outside of title)

## x86-64 Assembly Language - Data

* Integral numbers not stored in variables but in registers
  * Distinction between different integer size: 1, 2, 4 and 8 bytes
* Addresses not stored in pointer variables but in registers
  * Size: 8 bytes
  * Treated as integral numbers
* Floating point numbers stored in different registers than integral values
  * Distinction between different floating point numbers: 4 and 8 bytes
* No aggregate types such as arrays or structures

## x86-64 Assembly Language – Data

Integer Registers

* Storage locations in CPU -> fastest storage
* 16 registers are used explicitly – must name them in assembly code (annotation: `%eax`)
* Some registers are used implicitly
  * e.g., PC, FLAGS
* Each register is 64 bits in size, but we can refer to its:
  * first byte LSB (8 bits),
  * first 2 bytes (16 bits),
  * first 4 bytes (32 bits),
  * or to all of its 8 bytes (64 bits)

Integer Registers table (note, the blank first column of the "8-bit" column is intentional):

64-bit (quad)|32-bit (double)|16-bit (word)|8-bit (byte)|8-bit (byte)|Transcriber's Note
63..0|31..0|15..0||7..0|
---|---|---|---|---|---
rax|eax|ax||al|
rbx|ebx|bx||bl|
rcx|ecx|cx||cl|
rdx|edx|dx||dl|
rsi|esi|si||sil|
rdi|edi|di||dil|
rbp|ebp|bp||bpl|
rsp|esp|sp||spl|
|||||All cells above are pink and all cells below are yellow. I don't know why.
r8|r8d|r8w||r8b|
r9|r9d|r9w||r9b|
r10|r10d|r10w||r10b|
r11|r11d|r11w||r11b|
r12|r12d|r12w||r12b|
r13|r13d|r13w||r13b|
r14|r14d|r14w||r14b|
r15|r15d|r15w||r15b|

## About these integer registers!

Transcriber's note: 6 slides are compressed into this transcription.

* MSb 63..LSb 0 (`%al`, `%dil`, `%rl2b`)
* 31..LSb 0 (`%ax`, `%di`, `%rl2w`)
* 15..LSb 0 (`%eax`, `%edi`, `%rl2d`)
* 7..LSb 0 (`%rax`, `%rdi`, `%rl2`)

If I want 8 bits worth of data, then I can use register names such as `%al` or `%dil` or `%r12b`

If I want 16 bits worth of data, then I can use register names such as `%ax` or `%di` or `%r12w`

If I want 32 bits worth of data, then I can use register names such as `%eax` or `%edi` or `%r12d`

If I want 64 bits worth of data, then I can use register names such as `%rax` or `%rdi` or `%r12`

## Remember that for all 16 registers …

Let’s use the
register associated
with the names
%rax, %eax, %ax
and %al
as an example:

* `%rax`, `%eax`, `%ax` and %al all refer to the same register
* However…
  * Each refer to a different section of this register
  * `%rax` refers to all 64 bits of this register
  * `%eax` refers to only 32 bits of this register
    * the LS 32 bits of it -> bit 0 to bit 31
  * `%ax` refers to only 16 bits of this register
    * the LS 16 bits of it -> bit 0 to bit 15
  * `%al` refers to only 8 bits of this register
    * the LS 8 bits of it -> bit 0 to bit 7

## x86-64 Assembly Language - Instructions

* “2 operand” assembly language
* x86-64 functionally complete -> i.e., it is “Turing complete”. There are 3 classes of instructions.
  1. Memory reference => Data transfer instructions---Transfer data between memory and registers
    * Load data from memory into register
    * Store register data into memory
    * Move data from one register to another
  2. Arithmetic and logical => Data manipulation instructions---Perform calculations on register data
    * e.g., arithmetic, logic, shift
  3. Branch and jump => Program control instructions---Transfer control
    * Unconditional jumps to/from functions
    * Unconditional/conditional branches

## Move data – mov\*

Size designators:

* `...q` for long/64-bit
* `...l` for int/32-bit
* `...w` for short/16-bit
* `...b` for char/8-bit

Annotation: Homework: `movl $0xFF4150AC, %eax` (both `$0x...` and `%eax` are 32 bits, notice the size designation: `l`)

1. Memory reference => Data transfer instructions

* Transfer data between memory and registers
* Syntax: `mov* Source, Destination`
  * Diagram: $$\text{movq}\space\text{Source}\rightarrow\text{Destination}$$
* Example: `movq %rdi, %rax`
  * Diagram: $$\text{movq}\space\text{\%rdi}\rightarrow\text{\%rax}$$
* Allowed moves:
  * From register to register (Move)
  * From memory to register (Load)
  * From register to memory (Store)
* Conditional move (cmov\*)
  * Same as above, but based on result of comparison

## Demo – Swap Function

* Problem: Let’s swap the contents of two variables
* For now, we need to know that
  * Argument 1 of function swap(…) -> saved in `%rdi`
  * Argument 2 of function swap(…) -> saved in `%rsi`

## Demo – Swap Function

C code:

```
void swap(long *xp, long *yp)
{
  long L1 = *xp;
  long L2 = *yp;
  *xp = L2;
  *yp = L1;
  return;
}
```

Annotation: Because `xp` and `yp` contain an address of 64-bits, `%rdi` & `%rsi` are used to hold the value of `xp` and `yp`, respectively.

Assembly code:

```
wrap: # xp -> %rdi, yp -> %rsi
  movq    (%rdi), %rax # L1 = *xp; parenthasies indicate "indirect"
  movq    (%rsi), %rdx # L2 = *yp
  movq    %rdx, (%rdi) # *xp = L2
  movq    %rax, (%rsa) # *yp = L1
  ret
```

Register|Address
---|---
%rdi|0x0020
%rsi|0x0000
%rax|123
%rdx|456

Remember this is a compressed view of memory.

Address|Value
---|---
0x0020|(deleted)123 (annotation, inserted)456
0x0018|
0x0010|
0x0008|
0x0000|(deleted)456 (annotation, inserted)123

## Operand Combinations for mov\*

Source|Dest|Assembly (instruction (space) source, dest)|in C
---|---|---|---
Immediate|Register|`movq $0x4,%rax`|`result=0x4;`
Immediate|Memory|`movq $-147,(%rax)`|`*result=-147;`
Register|Register|`movq %rax,%rdx`|`var=result;`
Register|Memory|`movq %rax,(%rdx)`|`*var1=result;`
Memory|Register|`movq (%rax),%rdx`|`var1=*result;`

Cannot do memory-memory transfer with a single mov\* instruction

## Homework 2

* Since we cannot do memory-memory transfer with a single mov\* instruction …
  * Can you write a little x86-64 assembly program that transfers
data stored at address `0x0000` to address `0x0018`?

Registers|Value
---|---
%rdi|
%rsi|
%rax|
%rdx|

Address|Value
---|---
0x0020|
0x0018|
0x0010|
0x0008|
0x0000|6

## Summary

* As x86-64 assembly s/w dev., we now get to see more of the microprocessor
(CPU) state: PC, registers, condition codes
* x86-64 assembly language – Data
  * 16 integer registers of 1, 2, 4 or 8 bytes + memory address of 8 bytes
  * Floating point registers of 4 or 8 bytes
  * No aggregate types such as arrays or structures
* x86-64 assembly language – Instructions
  * mov\* instruction family
    * From register to register
    * From memory to register
    * From register to memory
  * Memory addressing modes
  * Cannot do memory-memory transfer with a single mov\* instruction

## Next Lecture

* Introduction
  * C program -> assembly code -> machine level code
* Assembly language basics: data, move operation
  * Memory addressing modes
* (selected) Operation leaq and Arithmetic & logical operations
* Conditional Statement – Condition Code + cmov\*
* Loops
* Function call – Stack
* Array
* Buffer Overflow
* Floating-point operations

gha_language: HTML


text:
## Welcome to the UI repository for the spotify build week project!

This end of the application has no dependencies but uses *less* so in this case you might want the less-watch-compiler to play with.

---

#### Font Awsome

The *font awsome* implementation used with this project was based off of their guide under the *less* how-two which can be found [here](https://fontawesome.com/how-to-use/on-the-web/using-with/less)

---

#### Less

To get less up and running with this project you will first need to make sure you have [NodeJS](https://nodejs.org/en/) installed onto your system. Once *node* is up and running using the node package manager go ahead and type out...

```
npm install -g less
```

with that less should be installed and you are all set!

gha_language: CSS


text:
# FreeBSD-SA-19:02.fd Postmortem

## Summary

FreeBSD 12.0 attempts to handle the case where the receiving process does not provide a sufficiently large buffer for an incoming control message containing rights.  In particular, to avoid leaking the corresponding descriptors into the receiving process' descriptor table, the kernel handles the truncation case by closing descriptors referenced by the discarded message.

The code which performs this operation failed to release a reference obtained on the file corresponding to a received right.  This bug can be used to cause the reference counter to wrap around and free the file structure.

## Root Causes

* Don't forget `fdrop` to avoid `struct file` leak

## Resolution

* [ATS2 avoid this issue](./Resolution/ATS2)
* [VeriFast avoid this issue](./Resolution/VeriFast)

## File

* sys/kern/uipc_syscalls.c

## Timeline

### Tue Feb 5 17:55:08 2019 +0000

https://github.com/freebsd/freebsd/commit/255362d099e7d3d7e8c1f143974bc1e764163d61

Fixed by markj.

## Supporting information

* Security Advisory: https://www.freebsd.org/security/advisories/FreeBSD-SA-19:02.fd.asc
* CVE: https://nvd.nist.gov/vuln/detail/CVE-2019-5596

repository: metasepi/postmortem

repo_name: metasepi/postmortem


text:
# desk-manager
 A macOS app that swaps files in and out of your desktop folder.

## Download
[Click here](https://github.com/shaunabanana/desk-manager/releases/download/β-0.4/DeskManager-darwin-x64-b0.4.zip) for the newest version.
For all versions, see the [Releases](https://github.com/shaunabanana/desk-manager/releases) page.

## Usage
* Place the app file in `/Applications`, and launch the app. Upon the first launch, you will likely be asked for permission to access your desktop folder. This is for swapping the files.
* You will notice that there's now a "Desktop Workspaces" folder under your home directory. This is where all the desktop folders live.
* Any folder you create here will be automatically added to the menu, and you can select an item in the menu to swap it out.

## Development
Set up dependencies:
```
npm install
```
Package into app file:
```
electron-packager . DeskManager --overwrite
```

repository: YYLNBL/desk-manager

repo_name: YYLNBL/desk-manager


text:
---
title: " Recipe - A HackDavis 2019 Project"
date: "2019-02-10"
---
[Repository for Receipe (aka Thomato)](https://github.com/fcr3/hackdavis2019)

## What's it about?
Recipe is an iOS app for scanning receipts. From those receipts, we can get tailored recipes that match your grocery bag and other things that you might have in your fridge, pantry, etc. The kicker is this: we care about healthy recipes and we especially care about healthy recipes for you. So you can choose to input data or your medical provider can give us data about you, but whatever the case may be, the app is there to serve you, literally.

## Contributors:
- Owen Bai
- Mrunal Puram
- Christian Reyes
- Owen Zhang

## About us:
We are a hackdavis 2019 team, and this year, we were called to program for social good. Specifically, we were called to focus on three main topics: the environment, health, and education. Undoubetly, our app only hits on mainly one of these three topics, but eventually, we would like to expand this app to meet all three. It was actually born out of an idea to minimize trash. People often lose track of expiration dates and have to throw away an incredible amount of food. It just so happened, though, that we got the image processing and recipe generation down, but not the conservation, which is definitely integral to this app's mission. That being said, we still have a lot to do outside of a hackathon!

## Capabilities:
- Takes an image of a receipt or any document and extracts food item text
- Accessibility to thousands upon thousands of recipes, each having their nutritional analysis

## Todos:
- Health Record Accessbility and Security
- Trained ML models to parse strings for food key words
- MORE TIME!

## Technologies Used:
- Google Cloud Vision API
- Swift 4
- Alamofire with SwiftyJSON
- Firebase
- Edamame Recipe API
- SVProgressHUD

gha_language: JavaScript


text:
Pattern: Use of unusual symbol in command name

Issue: -

## Description

ShellCheck found a command name containing an especially unusual character like a tab or linefeed. This is most likely due to a syntax issue.

In the example, this was due to a Python style documentation string, which a shell will merely interpreted as a multi-line command name sandwiched between two empty strings.

Example of **incorrect** code:

```sh
'''
This script greets the planet
'''
echo "Hello World"
```

Example of **correct** code:

```sh
# This script greets the planet
echo "Hello World"
```

## Further Reading

* [ShellCheck - SC2289](https://github.com/koalaman/shellcheck/wiki/SC2289)

repository: Adroiti/docs-for-code-review-tools

repo_name: Adroiti/docs-for-code-review-tools


text:
# diary

[English Documentation](./README.en.md)

一个基于 [react-native](https://github.com/facebook/react-native) 与 [expo](https://expo.io) 开发的日志应用.

## demo

[expo - diary - @senntyou](https://expo.io/@senntyou/diary).

## 预览

![](./preview/1.jpg)
![](./preview/2.jpg)
![](./preview/3.jpg)
![](./preview/4.jpg)

## 相关

- [react-native](https://github.com/facebook/react-native)
- [expo](https://expo.io)
- [native-base](https://github.com/GeekyAnts/NativeBase)
- [react-navigation](https://github.com/react-navigation/react-navigation)
- [redux](https://github.com/reduxjs/redux)
- [react-redux](https://github.com/reduxjs/react-redux)
- [react-native-timeline-listview](https://github.com/thegamenicorus/react-native-timeline-listview)
- [react-native-datepicker](https://github.com/xgfe/react-native-datepicker)

## 开发

```
# clone 仓库
git clone https://github.com/senntyou/diary.git

# 安装依赖
yarn install

# 开发
expo start
```

repository: deepraining/diary

repo_name: deepraining/diary


text:
# More Concept Guides

- [Incremental Builds](/more-concepts/incremental-builds)
- [Nx and Turborepo](/more-concepts/turbo-and-nx)
- [Nx and the Angular CLI](/more-concepts/nx-and-angular)
- [Monorepos](/more-concepts/why-monorepos)
- [Using Nx at Enterprises](/more-concepts/monorepo-nx-enterprise)
- [Nx Daemon](/more-concepts/nx-daemon)
- [Nx Devkit and Angular Devkit](/more-concepts/nx-devkit-angular-devkit)
- [Micro Frontend Architecture](/more-concepts/micro-frontend-architecture)
- [Applications and Libraries](/more-concepts/applications-and-libraries)
- [Creating Libraries](/more-concepts/creating-libraries)
- [Library Types](/more-concepts/library-types)
- [Grouping Libraries](/more-concepts/grouping-libraries)
- [Buildable and Publishable Libraries](/more-concepts/buildable-and-publishable-libraries)
- [How the Project Graph is Built](/more-concepts/how-project-graph-is-built)
- [Nx and the Nx Wrapper](/more-concepts/nx-and-the-wrapper)

repository: jsaguet/nx

repo_name: jsaguet/nx


text:
# CSC3022F ML Assignment 1 Clustering

We were tasked to create a  program that uses the K-means algorithm to cluster the following 8 examples into 3 clusters.

## Files contained in the folder
cluster.py
output.txt
Makefile
requirements.txt

## How to compile the program
	make
## How to run the test program
	make run
##Example usage:
	make run command should output such results to the txt file named output.txt
	Iteration 0

	Cluster 1: 1
	Centroid: (2, 10)

	Cluster 2: 3, 4, 5, 6, 8
	Centroid: (5, 8)

	Cluster 3: 2, 7
	Centroid: (1, 2)

	Iteration 1

	Cluster 1: 1, 8
	Centroid: (2.0, 10.0)

	Cluster 2: 3, 4, 5, 6
	Centroid: (6.0, 6.0)

	Cluster 3: 2, 7
	Centroid: (1.5, 3.5)

	Iteration 2

	Cluster 1: 1, 4, 8
	Centroid: (3.0, 9.5)

	Cluster 2: 3, 5, 6
	Centroid: (6.5, 5.25)

	Cluster 3: 2, 7
	Centroid: (1.5, 3.5)

	The total number of iterations is 3

#NOTE: Test are saved in the test folder

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

repository: CassandraDacha/cluster

repo_name: CassandraDacha/cluster


text:
### This fork is no longer required as the BCC bug is fixed in [Version 0.7.5](https://github.com/mattupstate/flask-mail/pull/29/files)

Flask-Mail is a Flask extension providing simple email sending
capabilities.

For full information please refer to the online docs:

http://packages.python.org/Flask-Mail

repository: practo/flask-mail

repo_name: practo/flask-mail


text:
luajit-mm
=========

Luajit take full advantage of lower 2G memory on AMD64 platform.

Rumdimentary implementation. Not yet fully tested. Not yet cleanup the code.
Quite a few optimizatio is not yet implemented.

Immediate todo
==============

    o.Refine and finish this README.
    o.test, add enhancements.

problem statement:
==================
  On Linux/x86-64 platform, Luajit can use no more than 1G memory due to the
combination of bunch of nasty issues. 1G is way too small for server-side application.

  This package is trying to replace mmap/munmap/mremap with hence provide up to
about 2G space.

Basic ideas
===========
    o. When a application, which contain luajit, is launched, reserve the the space
       from where `sbrk(0)` indidate all the way to 2G.

    o. Perform page allocation on the reserved space. the mmap/munmap/mremap is built
       on this page allocation. Currently, we use buddy allocation for page allocation
       with some optimizations in an attemp to reduce working set.

repository: tempbottle/luajit-mm

repo_name: tempbottle/luajit-mm


text:
# SlimPower - Slim

[![Latest version][ico-version]][link-packagist]
[![Total Downloads][ico-downloads]][link-downloads]

[![Latest Stable Version](https://poser.pugx.org/matiasnamendola/slimpower-slim/version?format=flat-square)](https://packagist.org/packages/matiasnamendola/slimpower-slim)
[![Latest Unstable Version](https://poser.pugx.org/matiasnamendola/slimpower-slim/v/unstable?format=flat-square)](//packagist.org/packages/matiasnamendola/slimpower-slim)
[![Total Downloads](https://poser.pugx.org/matiasnamendola/slimpower-slim/downloads?format=flat-square)](https://packagist.org/packages/matiasnamendola/slimpower-slim)
[![Monthly Downloads](https://poser.pugx.org/matiasnamendola/slimpower-slim/d/monthly?format=flat-square)](https://packagist.org/packages/matiasnamendola/slimpower-slim)
[![Daily Downloads](https://poser.pugx.org/matiasnamendola/slimpower-slim/d/daily?format=flat-square)](https://packagist.org/packages/matiasnamendola/slimpower-slim)
[![composer.lock available](https://poser.pugx.org/matiasnamendola/slimpower-slim/composerlock?format=flat-square)](https://packagist.org/packages/matiasnamendola/slimpower-slim)

An extension to [Slim Framework][1] that allows you use to dynamically
instantiated controllers with action methods wherever you would use a
closure or callback when routing.

The controller can optionally be loaded from Slim's DI container,
allowing you to inject dependencies as required.

Additionally, this extension implements Json Middleware & View with great ease.

[1]: http://www.slimframework.com/

## Installation

Look at [Installation File](INSTALLATION.md)

## Usage - Dynamic controller instantiation

Use the string format `{controller class name}:{action method name}`
wherever you would usually use a closure:

e.g.

```php
require 'vendor/autoload.php';

$app = new \SlimPower\Slim\Slim();

$app->get('/hello:name', 'App\IndexController:home');
```

You can also register the controller with Slim's DI container:

```php
<?php

require 'vendor/autoload.php';

$app = new \SlimPower\Slim\Slim();

$app->container->singleton('App\IndexController', function ($container) {
    // Retrieve any required dependencies from the container and
    // inject into the constructor of the controller.

    return new \App\IndexController();
});

$app->get('/', 'App\IndexController:index');
```

### Example controller

*SlimPower - Slim Controller* will call the controller's `setApp()`, `setRequest()`
and `setResponse()` methods if they exist and populate appropriately. It will
then call the controller's `init()`` method.

Hence, a typical controller may look like:

```php
<?php

namespace App;

class IndexController {
    // Optional properties.
    protected $app;
    protected $request;
    protected $response;

    public function index() {
        echo "This is the home page";
    }

    public function hello($name) {
        echo "Hello, $name";
    }

    // Optional setters.
    public function setApp($app) {
        $this->app = $app;
    }

    public function setRequest($request) {
        $this->request = $request;
    }

    public function setResponse($response) {
        $this->response = $response;
    }

    // Init
    public function init() {
        // Do things now that app, request and response are set.
    }
}
```

## Usage - Json Middleware

To include the middleware and view you just have to load them using the default _Slim_ way.
Read more about Slim Here (https://github.com/codeguy/Slim#getting-started)

```php
require 'vendor/autoload.php';

$app = new \SlimPower\Slim\Slim();

$app->view(new \SlimPower\Slim\Middleware\Json\JsonView());
$app->add(new \SlimPower\Slim\Middleware\Json\JsonMiddleware());
```

### Example method

All your requests will be returning a JSON output.
the usage will be `$app->render( (int)$HTTP_CODE, (array)$DATA);`

#### Example code

```php

    $app->get('/', function() use ($app) {
        $app->render(200, array(
            'msg' => 'welcome to my API!',
        ));
    });

```

#### Example output

```json
{
    "msg":"welcome to my API!",
    "error":false,
    "status":200
}
```

### Errors

To display an error just set the `error => true` in your data array.
All requests will have an `error` param that defaults to false.

```php
$app->get('/user/:id', function($id) use ($app) {

    // Your code here.

    $app->render(404, array(
        'error' => TRUE,
        'msg'   => 'user not found',
    ));
});
```
```json
{
    "msg":"user not found",
    "error":true,
    "status":404
}
```

You can optionally throw exceptions, the middleware will catch all exceptions and display error messages.

```php
$app->get('/user/:id', function($id) use ($app) {

    // Your code here.

    if(...) {
        throw new \Exception("Something wrong with your request!");
    }
});
```

```json
{
    "error": true,
    "msg": "ERROR: Something wrong with your request!",
    "status": 500
}
```

### Embedding response data and metadata in separate containers

It is possible to separate response metadata and business information in separate containers.

#### To make it possible just init JsonView with containers names

```php
require 'vendor/autoload.php';

$app = new \SlimPower\Slim\Slim();

$app->view(new \SlimPower\Slim\Middleware\Json\JsonView("resource", "meta"));
$app->add(new \SlimPower\Slim\Middleware\Json\JsonMiddleware());
```

#### Response
```json
{
    "resource":{
        "msg":"welcome to my API!"
    },
    "meta":{
        "error":false,
        "status":200
    }
}
```

### Routing specific requests to the API

If your site is using regular HTML responses and you just want to expose an API point on a specific route,
you can use Slim router middlewares to define this.

```php
function jsonResponse(){
    $app = \SlimPower\Slim\Slim::getInstance();
    $app->view(new \SlimPower\Slim\Middleware\Json\JsonView());
    $app->add(new \SlimPower\Slim\Middleware\Json\JsonMiddleware());
}

$app->get('/home',function() use($app){
    // Regular HTML response.
    $app->render("template.tpl");
});

$app->get('/api','jsonResponse',function() use($app){
    // This request will have full JSON responses.

    $app->render(200, array(
        'msg' => 'welcome to my API!',
    ));
});
```

### Middleware

The middleware will set some static routes for default requests.
**if you dont want to use it**, you can copy its content code into your bootstrap file.

***IMPORTANT: remember to use `$app->config('debug', false);` or errors will still be printed in HTML***

## Credits

- [Matías Nahuel Améndola](https://github.com/matiasnamendola)
- [Franco Soto](https://github.com/francosoto)

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[ico-version]: https://img.shields.io/packagist/v/MatiasNAmendola/slimpower-slim.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/MatiasNAmendola/slimpower-slim.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/matiasnamendola/slimpower-slim
[link-downloads]: https://packagist.org/packages/matiasnamendola/slimpower-slim

## Example project

Look at [slimpower-slim-example](https://github.com/matiasnamendola/slimpower-slim-example).

repository: MatiasNAmendola/slimpower-slim

repo_name: MatiasNAmendola/slimpower-slim


text:
# Build Tools

Learn how to use Bootstrap’s included npm scripts to build our documentation, compile source code, run tests, and more.

<hr>

#### Tooling setup

Our package.json includes convenient methods for working with the framework, including compiling code and building it
for production. The template is based on Vue CLI 3 which is a modern tool to build Vue apps. It has numerous plugins and even
a user interface. `vue ui`

#### Vue CLI

We used Vue CLI 3 for Argon. Vue CLI is a very easy and convenient way to develop Vue.js applications. It has great built ins, yet is very
customizable based on your own needs. For more info, check out [their docs](https://cli.vuejs.org/)

#### Autoprefixer

Argon uses Autoprefixer (included in our build process) to automatically add vendor prefixes to some CSS properties at build time.
Doing so saves us time and code by allowing us to write key parts of our CSS a single time while eliminating the need for vendor mixins like those found in v3.

#### Webpack

Vue CLI 3 is powered by Webpack and it's great ecosystem. Under the hood, Vue CLI compiles `.vue` files into javascript and transforms them
into something that is understood by the browser with the help of webpack. You can customize the webpack config quite easily with Vue CLI.
For more info check [their docs](https://cli.vuejs.org/config/#configurewebpack);

#### Babel

Vue CLI uses Babel to convert new Javascript features to features that are understood by the browser.
Note that there is `.browserlistrc` file in the project where you can specify what target browser you aim for.
This way, babel knows what features to convert and what features to not convert. Having a modern browser support (e.g excluding Internet Explorer)
will most likely result in a small javascript bundle.

#### Eslint

Vue CLI comes along with eslint. You can configure it in the `.eslintrc.js` file. Eslint will provide warnings and errors and try to enforce best
practices for the Javascript code. An important note is that you can fix warnings with `npm run lint --fix` command.

repository: hocwebchuan/vue-argon-dashboard-laravel

repo_name: hocwebchuan/vue-argon-dashboard-laravel


text:
---
layout: default
title: "the \"__\" radio should be selected"
parent: Step Definitions
---

# the "\_\_" radio should be selected

Verifies that the specified radio button is selected.
{: .fs-6 .fw-300 }

## Pattern

```
^the "([^"]*)" radio should be selected$
```

## Parameters

| Position | Description | Value Type                   | Restrictions                                                                                |
| :------: | ----------- | ---------------------------- | -------------------------------------------------------------------------------------------- |
|    1     | field       | field id/name/label/selector | Must refer to a [radio button field]({{site.baseurl}}/field_types.html#radio-button-fields). |

## Examples

```gherkin
Then the "Model 3 Tesla" radio should be selected
```


text:
# Try:
#  - zplugin zsh-delorean/circuit-blah atload'circuit-blah; circuit-blah'
#    - after source 88 / before source 88

# build.zsh:
#   - Build hood/88.zsh -> 88
#   - ??? DELOREAN[loc]=${DELOREAN_LOCATION:-"${HOME}/.delorean"}

# Installer will clone zsh-delorean/DeLorean to:
#   ~/.delorean/DeLorean/{build.zsh,hood,.github,.git,.gitignore}
#   ~/.delorean/circuits/{.git,.gitmodules,circuit-git,circuit-editor}
#   ~/.zplugin/

# Where will record of installed circuits be stored?
# Can we use flux-capacitor.zsh list to install missing?

# --------------------------------------------------

# 88 is not necessarily in same directory as ZDOTDIR
#
# .zshenv =__ZDOTDIR__=> ~/.config/ZDOTDIR
# ~/.config/ZDOTDIR/.zshrc =source=> DELOREAN_LOCATION/88 -> ~/.delorean/88
# ~/.delorean/88 =source=> ~/.config/ZDOTDIR/flux-capacitor.zsh
# ~/.delorean/88 =circuit=> ~/.config/ZDOTDIR/circuits/environment/circuit-environment

# If running 88, user wants:
#   - past: Restore old zshenv.
#   - future -c: Copy schematics and change shell.
#   - future: Mark next login shell to rebuild because of .z* or $fpath change.
#
#   - Manage the centralized repository of user functions and aliases?
#   - Enable or disable circuits or reorder?
#
# If user is sourcing 88, DeLorean should:
#   - Flatten fpath if 88 future ran and marked zshenv epoch.
#   - Replace fpath with flattened location.
#   - Load circuits.

# TODO/CONSIDER:
#   - Location after install (compare to zulu)
#     - Zulu cannot load custom repos
#   - login... what about function call 88 when loaded in shell? might need to add back || exit 0
#     - Headless option... --skip-login if ! [ -t 0 ] || [ -p /dev/stdin ]; then
#   - zplugin
#   - Lazy load triggers
#
#   - Brew commands in circuits
#   - Circuits can register mackup-style backups of configs.
#
#   - Will need to be DELOREAN_CIRCUITS.

repository: zsh-delorean/DeLorean

repo_name: zsh-delorean/DeLorean


text:
Listed is a website developed using React and Flask that brings you the best suggestions from Yelp's Fusion API.

To get started, run the following commands:
```
# To start the react server
npm install
npm start

# To start the backend
docker-compose up
```

This is a screenshot of how the website looks as of today:

![alt text](https://raw.githubusercontent.com/gkeswani92/listed/master/public/images/v1.png)

It uses React-Router to route the user to a 404 page if they try to access an invalid URL:

![alt text](https://raw.githubusercontent.com/gkeswani92/listed/master/public/images/404_page.png)


text:
# Bomb.io Game

## How to Run

1. Clone the repository

```
git clone https://github.com/b02902008/CNL.git
```

2. Change directory to cloned project

```
cd CNL
```

3. Install dependency packages

```
npm install
```

4. Run server

```
npm start
```

- Note that lastest NodeJs may cause error, use NodeJs 9.X.X


text:
# Archon

Trading and broker framework for Internet/Crypto exchanges

The framework interacts with the exchanges through the API keys for the purpose of

* all typical exchange functions such as: submitting orders, tracking balances and market prices
* tracking assets, Profit-and-loss statements, strategy analysis
* exchange functionality independent from web-view

Ecosystem which can be built on top

* Trading bots: arbitrage, market-making, directional
* Multi-Exchange trading interface
* Streaming service
* and more

## examples

balance_all.py - send balance report via mail

order.py - submit order example

cancel.py - cancel open order by command line

user_tx.py - user transactions

strategy.py - basic strategy example

## install

see [install doc](docs/install.md)

API keys - recommended is to limit the keys to disallow withdraws

## Telegram group

https://t.me/joinchat/Dzif7RALfRB98BocX72Z3Q

repository: hrebik/archon

repo_name: hrebik/archon


text:
# Implementing an Automated Installation Solution for OKD on vSphere with User Provisioned Infrastructure (UPI)

## Introduction

It's possible to completely automate the process of installing OpenShift/OKD on vSphere with User Provisioned Infrastructure by chaining together the various functions of [OCT](https://github.com/JaimeMagiera/oct) via a wrapper script.

## Steps

1. Deploy the DNS, DHCP, and load balancer infrastructure outlined in the [Prerequisites](#Prerequisites) section.
2. Create an install-config.yaml.template file based on the format outlined in the section [Sample install-config.yaml file for VMware vSphere](https://docs.okd.io/latest/installing/installing_vsphere/installing-vsphere.html#installation-vsphere-config-yaml_installing-vsphere) of the OKD docs. Do not add a pull secret. The script will query you for one or it will insert a default one if you use the --auto-secret flag.
3. Create a [wrapper script](#Wrapper-Script) that:
   * Installs the desired FCOS image
   * Downloads the oc and openshift-installer binaries for your desired release version
   * Generates and modifies the ignition files appropriately
   * Builds the cluster nodes
   * Triggers the installation process.

## Prerequisites

### DNS

* 1 entry for the bootstrap node of the format bootstrap.[cluster].domain.tld
* 3 entries for the master nodes of the form master-[n].[cluster].domain.tld
* An entry for each of the desired worker nodes in the form worker-[n].[cluster].domain.tld
* 1 entry for the API endpoint in the form api.[cluster].domain.tld
* 1 entry for the API internal endpoint in the form api-int.[cluster].domain.tld
* 1 wilcard entry for the Ingress endpoint in the form \*.apps.[cluster].domain.tld

### DHCP
### Load Balancer

vSphere UPI requires the use of a load balancer. There needs to be two pools.

* API: This pool should contain your master nodes.
* Ingress: This pool should contain your worker nodes.

### Proxy (Optional)

If the cluster will sit on a private network, you'll need a proxy for outgoing traffic, both for the install process and for regular operation. In the case of the former, the installer needs to pull containers from the external registires. In the case of the latter, the proxy is needed when applicaton containers need access to the outside world (e.g. yum installs, external code repositories like gitlab, etc.)

The proxy should be configured to accept conections from the IP subnet for your cluster. A simple proxy to use for this purpose is [squid](http://www.squid-cache.org)

## Wrapper Script

``` bash
#!/bin/bash

masters_count=3
workers_count=2
template_url="https://builds.coreos.fedoraproject.org/prod/streams/testing/builds/33.20210314.2.0/x86_64/fedora-coreos-33.20210314.2.0-vmware.x86_64.ova"
template_name="fedora-coreos-33.20210201.2.1-vmware.x86_64"
library="Linux ISOs"
cluster_name="mycluster"
cluster_folder="/MyVSPHERE/vm/Linux/OKD/mycluster"
network_name="VM Network"
install_folder=`pwd`

# Import the template
./oct.sh --import-template --library "${library}" --template-url "${template_url}"

# Install the desired OKD tools
oct.sh --install-tools --release 4.6

# Launch the prerun to generate and modify the ignition files
oct.sh --prerun --auto-secret

# Deploy the nodes for the cluster with the appropriate ignition data
oct.sh --build --template-name "${template_name}" --library "${library}" --cluster-name "${cluster_name}" --cluster-folder "${cluster_folder}" --network-name "${network_name}" --installation-folder "${install_folder}" --master-node-count ${masters_count} --worker-node-count ${workers_count}

# Turn on the cluster nodes
oct.sh --cluster-power on --cluster-name "${cluster_name}"  --master-node-count ${masters_count} --worker-node-count ${workers_count}

# Run the OpenShift installer
bin/openshift-install --dir=$(pwd) wait-for bootstrap-complete  --log-level=info

```

## Future Updates
* Generating the install-config template
* Pull directly from FCOS release feed