text:
---
title: Managing User Roles in React
date: "2019-03-13T23:46:37.121Z"
description: "How I handled user permissions in my application using CASL, Redux, and React Router"
---

So the best place to start when deciding authentiction systems is **use case**. For myself it was being implemented in a team software project as part of my degree.

We had to implement a grants proposal system which required various user interfaces for the **different types** of users.

The user roles we had in our system were:

- Researcher

- Reviewer

- Admin

## Libraries

### CASL

From some research online I found [CASL](https://github.com/stalniy/casl) (which has a nice [ReactJS package](https://github.com/stalniy/casl/tree/master/packages/casl-react)). CASL (pronounced _castle_) is described by the author as:

> An isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access.

From reading up on this package it seemed perfect for my use case.

### Redux

Needs no introduction really, everyone who uses React knows about Redux. This was what I was most comfortable with for the storage of user information and the various responses to API calls within the application.

## Implementation

I am going to continue on the premise that you have a [functional redux store](https://medium.com/backticks-tildes/setting-up-a-redux-project-with-create-react-app-e363ab2329b8).

### Install Packages

To begin, you must first install the CASL packages neccessary. To do so run:

```bash
npm i @casl/react @casl/ability
```

### Scoping Can

For this section I will be operating with **2 files**, `ability.js` and `Can.js`. Both these files I have placed in a `config` folder. For help with file structure, please see [this helpful post](http://react-file-structure.surge.sh) by Dan Abramov.

Why should we scope `Can`? Well, if you don't scope it you must pass the `ability` we are checking against with every `Can` call (e.g. `<Can I="create" a="Post" ability={ability}>`, where `ability` is the abilities we defined in the `ability.js` file, or wherever you placed the abilities).

Scoping was implemented for cases where you define serveral abilities abilities in your app or you want to restrict a particular `Can` component to check abilities using another instance.

I took the implementation for our `Can.js` file from [the docs](https://github.com/stalniy/casl/tree/master/packages/casl-react):

```jsx
// Can.js
import { createCanBoundTo } from "@casl/react"
import ability from "./ability"

export default createCanBoundTo(ability)
```

We import our `ability` (defined in the next section) and scope this particular `Can` component to handle the those abilities.

### Defining Abilities For User Roles

```jsx{3}
// Can.js
import { createCanBoundTo } from "@casl/react"
import ability from "./ability"

export default createCanBoundTo(ability)
```

As you saw above, we import `ability`, which is where all user permissions are defined. So lets go to that file now. I am going to break it down into sections and then at the end show you the entire file.

```jsx
//ability.js
import { Ability, AbilityBuilder } from "@casl/ability"
import store from "../store/index"

// Defines how to detect object's type
function subjectName(item) {
  if (!item || typeof item === "string") {
    return item
  }
  return item.__type
}

const ability = new Ability([], { subjectName })
```

Okay, so what's going on here? The `subjectName` function takes in the object and will return the property `__type` of that object if it exits. Otherwise if the item passed is a string it will simply return that string, etc (I.E. if you pass `subjectName('Admin')` it will return `Admin`).

```jsx{13}
//ability.js
import { Ability, AbilityBuilder } from "@casl/ability"
import store from "../store/index"

// Defines how to detect object's type
function subjectName(item) {
  if (!item || typeof item === "string") {
    return item
  }
  return item.__type
}

const ability = new Ability([], { subjectName })
```

Now, what is this? Well, this is [one of two ways](https://www.npmjs.com/package/@casl/react#2-defining-abilities) to define an `Ability` instance. What we are doing here is defining an empty `Ability` instance, which will use the provided `subjectName` to help decide what rules to attach to a particular user.

Next, we will bring in the redux store to get the current logged in user, if there is any:

```jsx
//ability.js
...
const ability = new Ability([], { subjectName });

let currentAuth;
store.subscribe(() => {
  const prevAuth = currentAuth;
  currentAuth = store.getState().currentUserReducer;
  if (prevAuth !== currentAuth) {
    ability.update(defineRulesFor(currentAuth));
  }
});
```

Here we are subscribing to changes in the `store` and will call the `ability.update(defineRulesFor(currentAuth))` function with the current user in the store when the store **updates** the `currentUserReducer` object. For reference, here's my `currentUserReducer` object:

```jsx
//CurrentUserReducer
const initialState = {
  isLoggedIn: null,
  user: null,
  role: "",
  errorMsg: "",
}
```

But wait, what's the `defineRulesFor` function? Well, we implement this ourselves. Here we will return the rules for the current user based on their role. Here is our function:

```jsx
//ability.js
// this is just below store.subscribe()

function defineRulesFor(auth) {
  const { can, rules } = AbilityBuilder.extract()
  if (auth.role === "researcher") {
    can("view", "Proposal")
    can("view", "Draft")
    can("apply", "Proposal")
    can("view", "Profile")
    can("view", "Teams")
  }
  if (auth.role === "admin") {
    can("add", "Proposal")
    can("view", "Proposal")
    can("accept", "Application")
    can("reject", "Application")
    can("view", "PendingReviews")
  }
  if (auth.role === "reviewer") {
    can("review", "Proposal")
  }
  return rules
}
```

We are using CASL's `AbilityBuilder` to define the abilities for the user. We are calling the `extract()` method simply to make things more legible (_avoid nesting_). Otherwise it would look something like this:

```jsx
function defineRulesFor(auth) {
  return AbilityBuilder.define((can, cannot) => {
    if (user.role === "researcher") {
      can("view", "Proposal")
      can("view", "Draft")
      can("apply", "Proposal")
      can("view", "Profile")
      can("view", "Teams")
    }
  })
  //etc.
}
```

So this is just for my personal preference, both are perfectly fine I just find the first option easier to read.

Now, let's take the `researcher` role for an example to explain what's going on. We are saying that if the user is an researcher we want them to be able to:

- View a Proposal
- View a Draft
- Apply for a Proposal
- View a Profile
- View Teams

The `can` function will add these abilities to the `rules` for this user, once we have the rules defined for the user we then return them at the end of the function.

Now, we have covered how I specified the role based rules for each role. Let's get to implementing them in the UI!

### Checking rules in the UI

I will give two examples here where I have done this, one is which menu items appear in the sidebar for users to click, which takes them to a particular route, and the other is in rendering the routes only if you have the correct role.

#### Sidebar

We now use the `Can` component we previously defined (see the `Can.js` file above) to conditionally render components. Here is the `SidebarRoutes` component which renders `ListItemLink`'s where you pass the route and text displayed on the menu item:

```jsx
//SidebarRoutes.jsx
//Other imports here
import Can from '../../config/Can';

...

const SidebarRoutes = ({ classes }) => (
  <List className={classes.root}>
    <ListItemLink text="Home" />
    <Can I="view" a="Profile">
      {() => <ListItemLink route="profile" text="Profile" />}
    </Can>
    <NestedProposals />
  </List>
);
```

We import the `Can` component and check if **I can view a Profile**. If this is **true** then it will render the `ListItemLink`, otherwise it simply won't render it.

I do the same thing for the various rules in the `NestedProposals` component, which a snippet of can be seen below:

```jsx
//NestedProposals.jsx
...
<Can I="add" a="Proposal">
    {() => (
        <ListItemLink
        route="admin/proposals/add"
        text="Add Proposals"
        className={classes.nested}
        />
    )}
</Can>
<Can I="review" a="Proposal">
    {() => (
        <ListItemLink
        route="proposals/respond"
        text="Respond To Applications"
        className={classes.nested}
        />
    )}
</Can>
...
```

Essentially the same thing. I check if user roles permit them to do certain things, and if they are allowed I will render the link.

 Here it is:

```jsx
//routes.jsx
...
const Routes = () => (
  <Switch>
    <Route exact path="/" component={GridCards} />

    <Route
      path="/profile"
      render={props => (
        <Can I="view" a="Profile">
          {() => <Profile {...props} />}
        </Can>
      )}
    />
</Switch>
...

```

So we make use of React Router's `render` prop to let us check the rules of the current user and do the appropriate rendering. As you can see it's pretty much the same across the board for implementation once you have the rules properly defined.

## End

Thank you for reading! I would appreciate any input (positive/negative) on my writing to improve it going forward. Any thoughts/queries please feel free to shoot me a DM on Twitter.


text:
# Confluent Cloud

This tool was designed to work with Confluent Cloud. It can manage service accounts, topics, and ACLs for Confluent Cloud clusters.

## Getting Started

Ensure you have installed `kafka-gitops` or are using the `kafka-gitops` docker image as described in the [installation][installation] instructions.

You must have the `ccloud` command line tools installed if you wish to auto-populate the `principal` fields on services.

## Desired State File

Create a basic desired state file, `state.yaml`, such as:

```yaml
settings:
  ccloud:
    enabled: true

topics:
  test-topic:
    partitions: 6
    replication: 3

services:
  test-service:
    type: application
    produces:
      - test-topic
```

To give an overview, throughout this guide, this will create:

- A topic named `test-topic`
- A service account named `test-service`
- An `WRITE` ACL for topic `test-topic` tied to the service account `test-service`

## Configuration

To use `kafka-gitops` with Confluent Cloud, you'll need to set a few environment variables.

* `KAFKA_BOOTSTRAP_SERVERS`: Your Confluent Cloud cluster URL
* `KAFKA_SASL_JAAS_USERNAME`: Your Confluent Cloud API key
* `KAFKA_SASL_JAAS_PASSWORD`: Your Confluent Cloud API secret
* `KAFKA_SECURITY_PROTOCOL`: `SASL_SSL`
* `KAFKA_SASL_MECHANISM`: `PLAIN`
* `KAFKA_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM`: `HTTPS`

Additionally, you'll need to login to the `ccloud` tool. You can automate this by setting the following environment variables:

* `XX_CCLOUD_EMAIL`: Your Confluent Cloud administrator email
* `XX_CCLOUD_PASSWORD`: Your Confluent Cloud administrator password

Then, you can run `ccloud login` and it will run without a prompt. This is great for CI builds.

You can optionally specify a path to a `ccloud` executable:

* `CCLOUD_EXECUTABLE_PATH`: `/full/path/to/ccloud`

Otherwise, `ccloud` must be on your path.

## Validate

First, validate your state file is correct by running:

```bash
kafka-gitops -f state.yaml validate
```

An example success message would look like:

```text
[VALID] Successfully validated the desired state file.
```

## Accounts

Before generating an execution plan, you will need to create the service accounts. This can be done by running:

```bash
kafka-gitops -f state.yaml account
```

This currently only creates service accounts; it will not delete any.

## Plan

We're now ready to generate a plan to execute against the cluster. By using the plan command, we are **NOT** changing the cluster.

Generate a plan by running:

```bash
kafka-gitops -f state.yaml plan -o plan.json
```

This will generate an execution plan to run against the cluster and save the output to `plan.json`.

The command will also pretty-print what changes it wants to make to the cluster.

## Apply

To execute a plan against the cluster, we use the apply command.

!> **WARNING**: This will apply changes to the cluster. This can be potentially destructive if you do not have all topics and ACLs defined.

By default, the apply command will generate a plan and then apply it. For most situations, **you should output a plan file from the plan command and pass it to the apply command**.

Example:

```bash
kafka-gitops -f state.yaml apply -p plan.json
```

Congrats! You're now using `kafka-gitops` to manage your Confluent Cloud cluster. Once you've practiced locally, you should commit your state file to a repository and create CI/CD pipelines to create plans and execute them against the cluster.

Welcome to GitOps!

[installation]: /installation.md

repository: jleemoneylion/kafka-gitops

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: jleemoneylion/kafka-gitops


text:
[![CircleCI](https://circleci.com/gh/ninjinkun/blog-feedback-app.svg?style=svg&circle-token=f9faff2d125195261cccf6cf8f6c9aabd1733603)](https://circleci.com/gh/ninjinkun/blog-feedback-app)

BlogFeedback is a PWA visualize your blog's impact.

<img src="https://user-images.githubusercontent.com/113420/50003891-97424b80-ffe8-11e8-949f-def709c14aa5.gif">

This app is based on below modules and services.
- React
- create-react-app
- styled-component
- Redux
- redux-thunk
- redux-saga
- Firebase
  - Authentication
  - Cloud Firestore
  - Cloud Functions

# Commands
## Run
```
$ yarn start
```

## Storybook
You can access Storybook [here](https://ninjinkun.github.io/blog-feedback-app/).

or

```
$ yarn storybook
```

## Staging Build
```
$ yarn build
```

## Production Build
```
$ yarn build:production
```

# Test
```
$ yarn firebase serve --only firestore
$ yarn test
```

license: MIT

repository: ninjinkun/blog-feedback-app

gha_language: TypeScript

gha_license_id: MIT

repo_name: ninjinkun/blog-feedback-app


text:
---
customer: CNES
customer_long: Centre National d'Etudes Spatiales
prime_contractor:
image: Project-CNES-SUPPORT FDS ATV-EN pict 1.png
size: small
name: SUPPORT FDS ATV
title: ATV – Flight Dynamics Support
domains: Flight Dynamics
department: SPACE
program: ATV
domains: Flight Dynamics
summary: "Support for flight dynamics operations on FDS ATV. Monitoring of the 'GNC' (Guidance, Navigation and Control System). Orbit determination, collision risks. Calculation of trajectories and maneuvers"
---

> __Customer__\: Centre National d'Etudes Spatiales (CNES)

> __Programme__\: ATV

> __Supply Chain__\: CNES >  CS Group SPACE

# Context

CS Group responsabilities for ATV – Flight Dynamics Support are as follows:
* Orbitography operations at the ATV Control Center (at CNES) for ATV 2 (February 16, 2011), then ATV 3 (March 23, 2012 launch), then ATV 4 (June 5, 2013 launch) , then the ATV 5 (firing July 29, 2014)

![Main Picture](Project-CNES-SUPPORT FDS ATV-EN pict 1.png)

The features are as follows:
* Adaptation and validation of operational procedures
* Participation in operational qualification training (with all ATV-CC teams)
* Participation in all FDS operations from ATV-2 to ATV-5 missions (LEOP, phasing, rendezvous, docking, deorbit and reentry)
* Mission analysis
* Real-time FDS tool performance studies
* FDS tool development monitoring, acceptance testing
* Post flight report

# Project implementation

The project objectives are as follows:
* Support for flight dynamics operations on FDS ATV
* Monitoring of the 'GNC' (Guidance, Navigation and Control System)
* Orbit determination, collision risks
* Calculation of trajectories and maneuvers

The processes for carrying out the project are:
* Technical Assistance

# Technical characteristics

The solution key points are as follows:
* Critical operations
* Relevant and responsive support for FDS teams
* Expert support for teams
* Experience in the field of mission analysis and critical operations in orbitography

The main technologies used in this project are:

{:class="table table-bordered table-dark"}
| Domain | Technology(ies) |
|--------|----------------|
|Hardware environment(s)|PC|
|Operating System(s)|Linux, Suse, Windows|
|Programming language(s)|Korn-shell, SCILAB, F90, JAVA|
|Main COTS library(ies)|cygwin, oscar, doors, vts|

{::comment}Abbreviations{:/comment}

*[CLI]: Command Line Interface
*[IaC]: Infrastructure as Code
*[PaaS]: Platform as a Service
*[VM]: Virtual Machine
*[OS]: Operating System
*[IAM]: Identity and Access Management
*[SIEM]: Security Information and Event Management
*[SSO]: Single Sign On
*[IDS]: intrusion detection
*[IPS]: intrusion prevention
*[NSM]: network security monitoring
*[DRMAA]: Distributed Resource Management Application API is a high-level Open Grid Forum API specification for the submission and control of jobs to a Distributed Resource Management (DRM) system, such as a Cluster or Grid computing infrastructure.

filename: Project-CNES-SUPPORT FDS ATV-EN.md


text:
---
title: "My second Blog post"
description: This post is related to the gatsbyjs
date: '2018-09-26'
image: 'time.jpg'
---
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into
electronic typesetting, remaining essentially unchanged. It was popularised in
the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
and more recently with desktop publishing software like Aldus PageMaker
including versions of Lorem Ipsum.
## Why do we use it?
It is a long established fact that a reader will be distracted by the
readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters,
as opposed to using 'Content here, content here', making it look like readable
English. Many desktop publishing packages and web page editors now use Lorem Ipsum
as their default model text, and a search for 'lorem ipsum' will uncover many web
sites still in their infancy. Various versions have evolved over the years, sometimes
by accident, sometimes on purpose (injected humor and the like).

repository: peredetrenes/miopiniondemierda

repo_name: peredetrenes/miopiniondemierda


text:
# CNN BenchMark

## 1. How to run

> 1. At first, you should parse the caffe model with [Anakin Parser(Converter)](../../docs/Manual/Converter_en.md).
> 2. Switch to *source_root/benchmark/CNN* directory. Use 'mkdir ./models' to create ./models and put anakin models into this file.
> 3. Use command 'sh run.sh', we will create files in logs to save model log with different batch size. Finally, model latency summary will be displayed on the screen.
> 4. If you want to get more detailed information with op time, you can modify CMakeLists.txt with setting `ENABLE_OP_TIMER` to `YES`, then recompile and run. You will find detailed information in  model log file.

# RNN BenchMark

Not Support Yet.

repository: ROCmSoftwarePlatform/Anakin

branch_name: refs/heads/developing

repo_name: ROCmSoftwarePlatform/Anakin


text:
# Redux Tiny Router

A Router made for Redux and made for universal apps! stop using the router as a controller... its just state!

Its simple, and its small

### Using client side

Create your store with the redux-tiny-router middleware and reducer

```es6
import { createStore, applyMiddleware, combineReducers} from 'redux';
import { middleware as reduxTinyRouterMiddleware, reducer as reduxTinyRouterReducer } from 'redux-tiny-router';
import * as yourReducers from './reducers'

  var reducer  = combineReducers(Object.assign({},reduxTinyRouterReducer,yourReducers));
  // reduxTinyRouterMiddleware needs to come after your middleware if you want to enable thinkgs like stoping routes on your middleware
  var finalCreateStore = applyMiddleware(appMiddleware,reduxTinyRouterMiddleware)(createStore);
  store = finalCreateStore(reducer,{});
```

Standard stuff, for now you just added a middleware and a reducer from redux-tiny-router, you should turn this in to a function
that returns the store  that you can import for convenience and if you plan on doing an Universal app

Now you only have to call the init function with the store before you render your app:
```es6
import { reduxTinyRouter } from 'redux-tiny-router';

 reduxTinyRouter.init(store);

 React.render(<App store={store}/>,
      document.getElementById('app')
  );

...
```
DONE!

If you enter any paths to your url you will notice that you also have a router object on your state containing relevant information about the current route,
but how to change the route inside the app?

### redux-tiny-router action creactors
Yup, you call an action, first import the router actions:
```
import {routerActions} from 'redux-tiny-router'
//navigates to a route with optional search object
routerActions.rtrNavigateTo('/somepath', {message:1});
```
The router will navigate to (/somepath?message=1) and set the router object with the info, for that it fires an action `type:'RTR_ROUTER_NAVIGATION'`
that you can use to intercept the action on your middleware and do all sorts of interesting thinks, more later...

Some more cool actions:
 ```
 rtrPreventNavigation(); //bonus! call this with a string and will prevent the user from navigating away from the page too!
 ```
Does what it says, after you call this you lock navigation, usefull if the user is on a form and you want to warn him about pending changes,
if the user attemps to navigate, it fires and action `type:RTR_PREVENTED_NAVIGATION_ATTEMPTED` that will set a field in your router with
the attempted route, you actualy dont need to wory about this, you can just check on your app if the value on the router.attemptedOnPrevent
is set to a value and router.preventNavigation is true (this will change to a new boolean field in a future version),
in this case you can show a popup warning the user of pending changes. But what if the users whats to navigate away?

 ```
  rtrDoPreventedNavigation();
 ```
You call this action!, it will read the value from router.attemptedOnPrevent and navigate there! (it handles back and forward buttons just fine)

```
 rtrAllowNavigation();
```
That just allows navigation again. if you want to handle the navigate after confirm implementation yourself.

### How to?

##### Basic routing

You could just do this, inside your react app,
```
@connect((state ) => {  //only get what you need, getting the whole thing for simplicity
    return {
        state:state
    }
})
const Comp = React.createClass({
  render() {
    switch (this.props.state.router.path) {
        case 'home':
            return <Home/>;
        case 'messages':
            return <Settings/>
    }
  }
});
```
If you want more flexibility you could do thinks a little diferent, inside your reducer you could listen to whatever action you like
and dispatch that from your middleware

```
inside you reducer...

switch (action.type) {

     case 'MY_ROUTER':
            return {
                ...state,
                directory: action.router.path
            };

     case ....

```
and in your middleware you listen to the ```RTR_ROUTER_NAVIGATION``` action
```
  inside you middleware...

      if (action.type === 'RTR_ROUTER_NAVIGATION'){
             disptach({     //on your app please use an action creator ..
                type:'MY_ROUTER'
                directory:path
             })
       }

```
Now on the app you look at your directory propery on the state, why is this more flexible?, where did the path came from? ... read on

you tipicaly do your routing inside your middleware, in this middleware you will check for an action with type ```RTR_ROUTER_NAVIGATION```
this action carries the router object with all the information parsed for you. ex:

```
inside you middleware...

if (action.type === 'RTR_ROUTER_NAVIGATION'){
     var path = action.router.path;

     switch (path){
        case '/secureplace':
          // check if the user is logged in, if not
          routerActions.rtrNavigateTo('/login'); //redirect him to login
          return  //notice i am not returning next(action) this stops the RTR_ROUTER_ACTION as it not forwarded to the reduces, therefore navigation to /secureplace is halted

          // if the user is logged in just let it pass
          return next(action)

        case '/home': {
            // do stuff for the home route if you want including fething or anything you like
            return next(action)
        }

        case '/messages': {
           path = path + '/' + action.router.search.param1; // now on your app you can expect a diferent path for this one
           you could for instance do this:
           action.router.path = path ;
           delete action.router.search //// and you rewrote the url from a query string to a id style on the fly to your router
           // you could not do this last stap and just use the re-writen path on your own state, and look there for the path,
           // in summary you decide how to route your app anyway you like its just state!

        }

        case '/notfound': {
           return next(action);
        }

        default:
            routerActions.rtrNavigateTo('/notfound'); //redirect to not found

     }

            disptach({
                  type:'MY_ROUTER'
                  directory:path   // <-- notice that in the case of messages we have manipulated this string (hance flexibility)
             })

     return

}
```

You could do your all your routing just by looking at the router.path and router.search and other fileds that you create on the router object on your own state,
mix and match that with your stuff, just use your stuff, its up to you.

### Universal Apps

 docs todo  (implementation is done...)

Inspired by cerebral reactive router

### License

MIT

repository: quazzie/redux-tiny-router

repo_name: quazzie/redux-tiny-router


text:
# LCS Playoff Contention

Displays and calculates the standings and playoff positions for the LCS regular season.

To start simply run:

```bash
dotnet run
```

or with a docker container

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

## Build the application

First install [paket][1] using .NET Core

To build run the following commands:

```bash
dotnet paket restore
dotnet build
```

### Docker

Building the docker image:

```bash
dotnet publish -c Release
docker build -t <image-tag> .
```

or

```bash
.\build.cmd
```

Pushing the docker image:

```bash
docker login docker.io --username <DockerUser> --password <DockerPassword>
docker push <DockerUser>/<DockerImageName>
```

or

```bash
.\release.cmd
```

[1]: https://fsprojects.github.io/Paket/index.html

repository: bagelhobbit/lcs-playoff-contention

gha_language: F#

repo_name: bagelhobbit/lcs-playoff-contention


text:
---
title: Install Shopify App CLI
section: getting-started
toc: false
redirect_from: "/install/"
---

Shopify App CLI can be installed on a variety of systems, using a variety of package managers.
> Note that for systems that have multiple installation options, you only need to use one of these methods to install.

---
### macOS

Shopify App CLI is available through Homebrew _or_ RubyGems.

**Homebrew**

You’ll need to run `brew tap` first to add Shopify’s third-party repositories to Homebrew.

```console
$ brew tap shopify/shopify
$ brew install shopify-cli
```

**RubyGems**

See the [RubyGems]({{ site.baseurl }}/getting-started/install/#rubygems-all-platforms) section for further details.

---

### Debian/Ubuntu Linux

On Debian-based Linux systems, Shopify App CLI is available through the `apt` command _or_ RubyGems.

**apt**

You’ll need to install a downloaded `.deb` file with an explicit version number. Check the [releases page](https://github.com/Shopify/shopify-app-cli/releases) to make sure you install the latest package.

1. Download the `.deb` file from the [releases page](https://github.com/Shopify/shopify-app-cli/releases)
1. Install the downloaded file
```console
$ sudo apt install /path/to/downloaded/shopify-cli-x.y.z.deb
```

**RubyGems**

See the [RubyGems]({{ site.baseurl }}/getting-started/install/#rubygems-all-platforms) section for further details.

---

### CentOS 8+/Fedora/Red Hat/SUSE Linux

On RPM-based Linux systems, Shopify App CLI is available through the `yum` command _or_ RubyGems.

**yum**

You’ll need to install a downloaded `.rpm` file with an explicit version number. Check the [releases page](https://github.com/Shopify/shopify-app-cli/releases) to make sure you install the latest package.

1. Download the `.rpm` file from the [releases page](https://github.com/Shopify/shopify-app-cli/releases)
1. Install the downloaded file
```console
$ sudo yum install /path/to/downloaded/shopify-cli-x.y.x.rpm
```

**RubyGems**

See the [RubyGems]({{ site.baseurl }}/getting-started/install/#rubygems-all-platforms) section for further details.

---

### Windows 10

On Windows 10 systems, Shopify App CLI is available through [RubyGems]({{ site.baseurl }}/getting-started/install/#rubygem-all-platforms).

---

### RubyGems (all platforms)

Shopify App CLI is available on all platforms as a RubyGem through [RubyGems.org](https://rubygems.org/).

```console
$ gem install shopify-cli
```

---

### To check that Shopify App CLI is installed correctly:

```console
$ shopify version
1.0.0
$
```

> Note 1: the version displayed may be newer.

> Note 2: If you have the `shopify_api` gem installed, you may see the following response:
> ```console
> shopify command is no longer bundled with shopify_api.
> if you need these tools, install the shopify_cli gem
> ```
>
> If so, then you will also need to upgrade the `shopify_api` gem to v9.2.0+ to remove a deprecated `shopify` command that is contained in that gem.
>
> If you also have the `shopify_app` gem (which depends on `shopify_api` gem), you'll need to install or update `shopify_api` first, then uninstall the older version.
>
> To get a list of the version(s) of `shopify_api` currently installed:
> ```console
> $ gem list shopify_api
> ```
>
> To install the latest version:
> ```console
> $ gem install shopify_api
> ```
>
> To uninstall the older version:
> ```console
> $ gem uninstall shopify_api -v x.y.z
> ```
> Replace x.y.z with a version number listed from the `gem list` command.  Repeat as needed.


text:
# birthdays
Compute the True Value of the Birthday Problem

See accompanying post [link forthcoming]

Data from [FiveThirtyEight](https://github.com/fivethirtyeight/data/tree/master/births)

repository: rcharan/birthdays

repo_name: rcharan/birthdays


text:
# idunno.Authentication.Basic

This project contains an implementation of [Basic Authentication](https://tools.ietf.org/html/rfc1945#section-11) for ASP.NET.

It started as a demonstration of how to write authentication middleware and **not** as something you would seriously consider using, but enough of
you want to go with the world's worse authentication standard, so here we are. *You* are responsible for hardening it.

## Getting started

First acquire an HTTPS certificate (see Notes below). Apply it to your website. Remember to renew it when it expires, or go the
Lets Encrypt route and look like a phishing site.

In your web application add a reference to the package, then in the `ConfigureServices` method in `startup.cs` call
`app.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme).AddBasic(...);` with your options,
providing a delegate for `OnValidateCredentials` to validate any user name and password sent with requests and turn that information
into an `ClaimsPrincipal`, set it on the `context.Principal` property and call `context.Success()`.

If you change your scheme name in the options for the basic authentication handler you need to change the scheme name in
`AddAuthentication()` to ensure it's used on every request which ends in an endpoint that requires authorization.

You should also add `app.UseAuthentication();` in the `Configure` method, otherwise nothing will ever get called.

You can also specify the Realm used to isolate areas of a web site from one another.

For example;

```c#
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
            .AddBasic(options =>
            {
                options.Realm = "idunno";
                options.Events = new BasicAuthenticationEvents
                {
                    OnValidateCredentials = context =>
                    {
                        if (context.Username == context.Password)
                        {
                            var claims = new[]
                            {
                                new Claim(
                                    ClaimTypes.NameIdentifier,
                                    context.Username,
                                    ClaimValueTypes.String,
                                    context.Options.ClaimsIssuer),
                                new Claim(
                                    ClaimTypes.Name,
                                    context.Username,
                                    ClaimValueTypes.String,
                                    context.Options.ClaimsIssuer)
                            };

                            context.Principal = new ClaimsPrincipal(
                                new ClaimsIdentity(claims, context.Scheme.Name));
                            context.Success();
                        }

                        return Task.CompletedTask;
                    }
                };
            });

    // All the other service configuration.
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();

    // All the other app configuration.
}
```

For .NET 6 minimal templates

```c#
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
    .AddBasic(options =>
    {
        options.Realm = "Basic Authentication";
        options.Events = new BasicAuthenticationEvents
        {
            OnValidateCredentials = context =>
            {
                if (context.Username == context.Password)
                {
                    var claims = new[]
                    {
                                    new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
                                    new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
                                };

                    context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                    context.Success();
                }

                return Task.CompletedTask;
            }
        };
    });
builder.Services.AddAuthorization();
```

and then, before calls to any app.Map functions

```c#
app.UseAuthentication();
app.UseAuthorization();
```

In the sample you can see that the delegate checks if the user name and password are identical. If they
are then it will consider that a valid login, create set of claims about the user, using the `ClaimsIssuer` from the handler options,
then create an `ClaimsPrincipal` from those claims, using the `SchemeName` from the handler options, then finally call `context.Success();`
to show there's been a successful authentication.

Of course you'd never implement such a simple validation mechanism would you? No? Good. Have a cookie.

If you want to use Basic authentication within an Ajax application then it you may want to stop the browser prompting for a user name and password.
This prompt happens when a `WWWAuthenticate` header is sent, you can suppress this header by setting the `SuppressWWWAuthenticateHeader` flag on options.

The handler will throw an exception if wired up in a site not running on HTTPS and will refuse to respond to the challenge flow
which ends up prompting the browser to ask for a user name and password.   If you're
using a non-interactive client, and are sending a user name and password to a server over HTTP the handler will not throw and
will process the authentication header because frankly it's too late, you've sent everything in plain text, what's the point?

The original Basic Authentication RFC never specifically set a character set for the encoding/decoding of the user name and password, and the superseding RFC 7616 only requires it
to be compatible with US ASCII (which limits the encoding to Utf8) so various clients differ in what encoding they use. You can switch been encodings by using the `EncodingPreference`
options property.

The `EncodingPreference` property to allow you to select from three possible values, `Utf8`, `Latin1`, and `PeferUtf8`.
* `EncodingPreference.Utf8` will only decode using Unicode
* `EncodingPreference.Latin1` will only attempt decoding using ISO-8859-1/Latin1.
* `EncodingPreference.PreferUtf8` will first attempt to decode using Unicode, and if an exception is thrown during the Unicode decoding it will then attempt to decode using ISO-8859-1/Latin1.

There is no fall back from Latin1 to Unicode as every possible byte sequence is a valid Latin1 string, so it will always decode "successfully", but not correctly if fed UTF8 encoded strings.

RFC 7616 also allows [the server to specify the charset/encoding it accepts](https://www.rfc-editor.org/rfc/rfc7617#section-2.1). To enable this set the `AdvertiseEncodingPreference` flag on options to true.

There is no ability for a client to specify the encoding as part if the user name or password as suggested by [RFC2616, section 2.1](https://www.rfc-editor.org/rfc/rfc2047#section-2), as that way lies madness
and no sane client does this.

## Accessing a service inside your delegate

For real functionality you will probably want to call a service registered in DI which talks to a database or other type of
user store. You can grab your service by using the context passed into your delegates, like so

```c#
services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
  .AddBasic(options =>
  {
    options.Realm = "idunno";
    options.Events = new BasicAuthenticationEvents
    {
      OnValidateCredentials = context =>
      {
        var validationService =
          context.HttpContext.RequestServices.GetService<IUserValidationService>();
        if (validationService.AreCredentialsValid(context.Username, context.Password))
        {
          var claims = new[]
          {
            new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
            new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
          };

          context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
          context.Success();
        }

        return Task.CompletedTask;
      }
    };
  })
```

## Using Basic Authentication in production

I'd never recommend you use basic authentication in production unless you're forced to in order to comply with a standard, but, if you must here are some ideas on how to harden your validation routine.

1. In your `OnValidateCredentials` implementation keep a count of failed login attempts, and the IP addresses they come from.
2. Lock out accounts after X failed login attempts, where X is a count you feel is reasonable for your situation.
3. Implement the lock out so it unlocks after Y minutes. In case of repeated attacks increase Y.
4. Be careful when locking out your administration accounts. Have at least one admin account that is not exposed via basic auth, so an attacker cannot lock you out of your site just by sending an incorrect password.
5. Throttle attempts from an IP address, especially one which sends lots of incorrect passwords. Considering dropping/banning attempts from an IP address that appears to be under the control of an attacker. Only you can decide what this means, what consitutes legimate traffic varies from application to application.
6. Always use HTTPS. Redirect all HTTP traffic to HTTPS using `[RequireHttps]`. You can apply this to all of your site via a filter;

    ```c#
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });
    ```
7. Implement [HSTS](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) and [preload](https://hstspreload.org/)
   your site if your site is going to be accessed through a browser.
8. Reconsider your life choices, and look at using OAuth2 or OpenIDConnect instead.

## Support for older versions of ASP.NET Core

Older versions are available in the appropriate branch.

| ASP.NET Core MVC Version | Branch                                                           |
|--------------------------|------------------------------------------------------------------|
| 1.1                      | [rel/1.1.1](https://github.com/blowdart/idunno.Authentication/tree/rel/1.1.1) |
| 1.0                      | [rel/1.0.0](https://github.com/blowdart/idunno.Authentication/tree/rel/1.0.0) |

No nuget packages are available for older versions of ASP.NET Core.

## Notes

Basic Authentication sends credentials unencrypted. You should only use it over [HTTPS](https://en.wikipedia.org/wiki/HTTPS).

It may also have performance impacts as credentials are sent and validated with every request. As you should not be storing passwords in clear text your validation procedure will have to hash and compare values
with every request, or cache results of previous hashes (which could lead to data leakage).

Remember that hash comparisons should be time consistent to avoid [timing attacks](https://en.wikipedia.org/wiki/Timing_attack).

branch_name: refs/heads/dev

gha_language: C#


text:
title: Data Table
---
Quasar Grid is a Vue Component which allows you to display data in a tabular manner. Features:
  * Responsive (changes design when width is smaller than 600px to best accommodate small screens)
  * Sticky columns
  * Sticky headers
  * Filter (by all columns or by one column)
  * Sorting by columns
  * Cell formatter methods
  * Cell component renderer (through Vue scoped slots)
  * Pagination
  * Columns picker
  * Row selection (single or multiple)
  * Refresh functionality

**Data Table is highly optimized to support a large number of rows**, but its good to check "Performance" section below to make the most of it.

_Best way to display a Grid is on a desktop so you might want to check that first_. Resize the browser window to see sticky columns and the responsiveness.
<input type="hidden" data-fullpage-demo="web-components/data-table">

## Basic Usage

``` html
<q-data-table
  :data="table"
  :config="config"
  :columns="columns"
  @refresh="refresh"
>
  <!-- Custom renderer for "message" column -->
  <template slot="col-message" scope="cell">
    <span class="light-paragraph">{{cell.data}}</span>
  </template>

  <!-- Custom renderer for "source" column -->
  <template slot="col-source" scope="cell">
    <span v-if="cell.data === 'Audit'" class="label text-white bg-primary">
      Audit
      <q-tooltip>Some data</q-tooltip>
    </span>
    <span v-else class="label text-white bg-negative">{{cell.data}}</span>
  </template>

  <!-- Custom renderer when user selected one or more rows -->
  <template slot="selection" scope="selection">
    <button class="primary clear" @click="changeMessage(selection)">
      <i>edit</i>
    </button>
    <button class="primary clear" @click="deleteRow(selection)">
      <i>delete</i>
    </button>
  </template>
</q-data-table>
```

## Vue Properties
All Vue properties are **required**.

| Vue Property | Description |
| --- | --- |
| `config` | Config object (see "Config Property" below). |
| `columns` | Object defining columns (see "Columns Definition" below). |
| `data` | Data containing Array of rows to display. |

## Vue Methods
| Vue Method | Description |
| --- | --- |
| `refresh([Boolean])` | If parameter is missing or `true` then it puts Data Table in refresh mode. If parameter is `false` then components gets out of refresh mode. |

## Vue Events
| Vue Event | Description |
| --- | --- |
| `@refresh(Function done)` | Triggered when user clicks/taps on "Refresh" button. Call `done()` when refresh is over. |

## Configuring Data Table
Some things worth mentioning before digging into how to configure Data Table:
* You must specify `rowHeight` property
* You must specify each columns' width

### Config Property
Below is an example enabling all features:

``` js
config = {
  // [REQUIRED] Set the row height
  rowHeight: '50px',

  // (optional) Title to display
  title: 'Data Table',

  // (optional) No columns header
  noHeader: true,

  // (optional) Display refresh button
  refresh: true,

  // (optional)
  // User will be able to choose which columns
  // should be displayed
  columnPicker: true,

  // (optional) How many columns from the left are sticky
  leftStickyColumns: 0,

  // (optional) How many columns from the right are sticky
  rightStickyColumns: 2,

  // (optional)
  // Styling the body of the data table;
  // "minHeight", "maxHeight" or "height" are important
  bodyStyle: {
    maxHeight: '500px'
  },

  // (optional) By default, Data Table is responsive,
  // but you can disable this by setting the property to "false"
  responsive: true,

  // (optional) Use pagination. Set how many rows per page
  // and also specify an additional optional parameter ("options")
  // which forces user to make a selection of how many rows per
  // page he wants from a specific list
  pagination: {
    rowsPerPage: 15,
    options: [5, 10, 15, 30, 50, 500]
  },

  // (optional) User can make selections. When "single" is specified
  // then user will be able to select only one row at a time.
  // Otherwise use "multiple".
  selection: 'multiple',

  // (optional) Override default messages when no data is available
  // or the user filtering returned no results.
  messages: {
    noData: '<i>warning</i> No data available to show.',
    noDataAfterFiltering: '<i>warning</i> No results. Please refine your search terms.'
  },

  // (optional) Override default labels. Useful for I18n.
  labels: {
    columns: 'Coluuuuumns',
    allCols: 'Eeeeeeeeevery Cols',
    rows: 'Rooows',
    selected: {
      singular: 'item selected.',
      plural: 'items selected.'
    },
    clear: 'clear',
    search: 'Search',
    all: 'All'
  }
}
```

### Columns definition
``` js
columns = [
  {
    // [REQUIRED] Column name
    label: 'Date',

    // [REQUIRED] Row property name
    field: 'isodate',

    // [REQUIRED] Column width
    width: '100px',

    // (optional) Column CSS style
    style: {color: '#ff09fa'},
    // "style" can be a function too if you want to apply
    // certain CSS style based on cell value:
    // style (cell_value) { return .... }

    // (optional) Column CSS classes
    classes: 'bg-primary',
    // "classes" can be a function too if you want to apply
    // certain CSS class based on cell value:
    // classes (cell_value) { return .... }

    // (optional) Can filter/search be applied to this column?
    filter: true,

    // (optional) Sortable column? Type is inferred automatically
    sort: true,
    // or you can specify a custom sorting method;
    // works same as Array.prototype.sort().
    // Return codes:
    //   < 0 --> "a" should be before "b"
    //   0   --> "a" is same as "b"
    //   > 0 --> "a" should be after "b"
    sort (a, b) {
      return (new Date(a)) - (new Date(b))
    },
    // or you have a third option to use a built-in sorting method:
    // "string", "number", "date", "moment", "boolean"
    sort: 'string',

    // (optional)
    // use a formatter for this column;
    // transforms original String in another String
    format (value, row) {
      return new Date(value).toLocaleString()
    }
  },
  ...
]
```

## Features
Describing below some of the features so it makes configuring more clear.

### Data Table Height
Use `config.bodyStyle` optional property to define the height of your Data Table component. This property of `config` should contain CSS props and values:
* If you want to have a maximum height, specify `maxHeight` CSS prop
* If you want to have a minimum height, specify `minHeight` CSS prop
* If you want to have a fixed height, specify `height` CSS prop

### Making a column sortable
In the columns definition array specify `sort: true` for the Object defining that column.
```js
columns = [
  {
    label: '...',
    ...,
    sort: true // <<<<
  }
]
```

### Formatting a Cell
There are two options to do this: use a formatter method or render cell through a component.

#### Formatter Method
In the columns definition array specify `format()` method for the Object defining that column.
```js
columns = [
  {
    label: '...',
    ...,
    format (value) { // <<<<
      return 'a' + value + 'b'
    }
  }
]
```

#### Rendering with Component
Sometimes you need to use a Tooltip or some specific component to render the cell. You can define a Vue component through a scoped slot:

``` html
<q-data-table ...>
  <!-- Custom renderer for "message" column -->
  <template slot="col-message" scope="cell">
    <span class="light-paragraph">{{cell.data}}</span>
  </template>
</q-data-table>
```

The `scope` property here (named `cell`) is an Object containing:

| Scope Property | Description |
| --- | --- |
| `row` | Object containing the row of the respective cell. |
| `col` | Object containing column definition for the respective cell. |
| `data` | Cell value. |

> Slot attribute must have a value of the following form: `col-[field_name]`.
Examples: "col-msg" (for field "msg"), "col-date" (for field "date").

A field is a property name of a row. Example of Data Table `data` Vue property (which is an Array of all rows):
``` js
data = [
  {
    date: '21-10-2016',
    msg: 'Some message',
    ...
  },
  ...
]
```

## Performance
Performance is always important when dealing with a high number of rows. Data Table component is written to be as efficient as possible (with lots of optimizations behind the scenes -- **it's one of the fastest data table component out there!**), but it's a good thing to make an idea of what features are the most costly to have. So, in descending order:

* Rendering a cell with a component
* Rendering a cell with a formatter method. The formatter method must be really quick, so strip out whatever is not needed and avoid making complex computations.

The more rows you are displaying at a time the more time it will take for Data Table to render the cells. It's a good idea to force pagination when you're using lots of formatters or rendering with lots of components.


text:
# twitter-analysis
Cascading applications to analyze twitter data in HBase.

To compile the Cascading classes into a single jar with dependencies

    mvn clean compile assembly:single

To run the Cascading application on Hadoop, execute the following:

    hadoop jar memex-cascading-jar-with-dependencies-1.0.jar gov.darpa.analysis.twitter.memex.TwitterEbolaP1AfterTrailsCount


text:
# HospitalRun Components

[![NPM Version](https://badgen.net/npm/v/@hospitalrun-org/components)](https://www.npmjs.com/package/@hospitalrun-org/components) [![Build Status](https://travis-ci.com/HospitalRun/components.svg?branch=master)](https://travis-ci.com/HospitalRun/components) [![NPM Downloads](https://badgen.net/npm/dt/@hospitalrun-org/components)](https://www.npmjs.com/package/@hospitalrun-org/components)
[![Build Status](https://dev.azure.com/HospitalRun/components/_apis/build/status/HospitalRun.components?branchName=master)](https://dev.azure.com/HospitalRun/components/_build/latest?definitionId=1&branchName=master)
[![Last commit](https://badgen.net/github/last-commit/hospitalrun/components)](https://github.com/HospitalRun/components/commits/master) [![Bundlephobia](https://badgen.net/bundlephobia/min/@hospitalrun-org/components)](https://bundlephobia.com/result?p=@hospitalrun-org/components) [![dependabot](https://badgen.net/dependabot/dependabot/dependabot-core/?icon=dependabot)](https://github.com/HospitalRun/components)  [![MIT](https://badgen.net/github/license/HospitalRun/components)](https://github.com/HospitalRun/components/blob/master/LICENSE) [![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/hospitalrun)

This repository will host reusable react components made for the HospitalRun frontend.

---

# Install

Install components:
```
npm install @hospitalrun-org/components
```

Install react-bootstrap:
```
npm install react-bootstrap
```

[Optional] You may need `node-sass` if you want to import components' `.scss` files:
```
npm install -D node-sass
```

# Contributing

Contributions are always welcome. Before contributing please read our [contributor guide](https://github.com/HospitalRun/components/blob/WIP-updates-readme/.github/CONTRIBUTING.md).

1. Fork this repository to your own GitHub account and then clone it to your local device
2. Navigate to the cloned folder: `cd components`
3. Install the dependencies: `npm install`
4. Run `npm link` to link the local repo to the global npm folder
5. Run `npm run dev` to build and watch for code changes
6. In another terminal window create a [new react project](https://reactjs.org/docs/create-a-new-react-app.html#create-react-app) with `npx create-react-app my-app`
7. Navigate (`cd my-app`) to your react project and install [node-sass](https://www.npmjs.com/package/node-sass): `npm install -D node-sass`. Components styles are coded using scss and you need this dependency in order to successfully import components' `.scss` files
8. Link the components repo inside your newly created react project with `npm link components`
9. Start your react project with `npm start` and enjoy hot reloading when applying changes in the components repo

# Examples

## Spinner

Spinner it's a customizable spinner component. It's a wrapper component built upon react-spinners.

Example:

```
import React from "react";
import { Spinner } from "components";
import "components/scss/main.scss";

class App extends React.Component {
  render() {
    return (
      <Spinner
        type="ScaleLoader"
        loading={true}
        color={"orange"}
        size={[5, 25]}
        sizeUnit={["px", "px"]}
      />
    );
  }
}

export default App;

```

**MANDATORY PARAMETERS**

`type: string`
Choose the spinner type. You can choose from:

* BarLoader
* BeatLoader
* BounceLoader
* ClimbingBoxLoader
* ClipLoader
* DotLoader
* FadeLoader
* PulseLoader
* RotateLoader
* ScaleLoader
* SyncLoader

`loading: boolean`
This prop tells Spinner when to show itself. It should be linked to something dynamic, like a property in the parent component's state.

**OPTIONAL PARAMETERS**

`color: string`
Choose the spinner color.

`margin: string`
Adds a margin to the Spinner component.

`size: number | [number, number]`
Declares the size of the spinner. If you choose to declare it, in the following spinners it must be an array of two numbers (for width & height):

* BarLoader
* FadeLoader
* ScaleLoader

`sizeUnit: "px" | "%" | "em" | ["px" | "%" | "em", "px" | "%" | "em"]`
Declares the unit of measure for the previous size parameter. If you choose to declare it, in the following spinners it must be an array of two strings (respectively for width & height):

* BarLoader
* FadeLoader
* ScaleLoader

# Behind HospitalRun

## Hosted by

[](https://openjsf.org/projects/#atlarge)

## Sponsors

[![Sponsors](https://opencollective.com/hospitalrun/sponsors.svg?width=890)](https://opencollective.com/hospitalrun/contribute/sponsors-336/checkout)

## Backers

[![Backers](https://opencollective.com/hospitalrun/backers.svg?width=890)](https://opencollective.com/hospitalrun/contribute/backers-335/checkout)

## Lead Maintainer
[
Maksim Sinik](https://github.com/fox1t)

## Core Team

|[
Riccardo Gulin](https://github.com/bazuzu666)  | [
Matteo Vivona](https://github.com/tehKapa)  |  [
Stefano Casasola](https://github.com/irvelervel) | [
Stefano Miceli](https://github.com/StefanoMiC) |
|---|---|---|---|

## Medical Supervisor

[
M.D. Daniele Piccolo](https://it.linkedin.com/in/danielepiccolo)

## Contributors

[![Contributors](https://opencollective.com/hospitalrun/contributors.svg?width=960&button=false)](https://github.com/HospitalRun/hospitalrun-frontend/graphs/contributors)

## Founders

| [
John Kleinschmidtr](https://github.com/jkleinsc) | [
Joel Worrall](https://github.com/tangollama)  | [
Joel Glovier](https://github.com/jglovier)  |
|---|---|---|

# License

Released under the [MIT license](LICENSE).

repository: tjboudreaux/components

repo_name: tjboudreaux/components


text:
# node-red-contrib-uk-ea-flood-warnings

[Node-RED](http://nodered.org) wrapper to the UK Environment Agency Real Time
Flood-monitoring [API](http://envrionment/data.gov.uk/flood-monitoring/doc/reference)

## Install
Use the manage palette option to install this node

## Usage
This node allows you to run queries against the UK Environment Agency Flood Warning API

## Configuration
Use the configuration to select the mode.
If floods are selected then `All Flooded Areas` will return
all active flood alerts. If tides are selected then `All Stations` will return details and measurements for all tidal measurement stations.

### Input
 `msg.payload` is not required. The node needs to be configured
to select an area. A list of available areas and tidal stations is
automatically retrieved by the node, making use of the API.

You can override the area setting by setting `msg.floodarea`, which must be a comma separated
string.

### Output
The output is a json array on `msg.payload`. When running in flood mode and there are no
flood alerts in the selected area then the array is empty.

## Contributing
For simple typos and fixes please just raise an issue pointing out our mistakes. If you need to raise a pull request please read our [contribution guidelines](https://github.com/ibm-early-programs/node-red-contrib-uk-ea-flood-warnings/blob/master/CONTRIBUTING.md) before doing so.

## Copyright and license

Copyright 2018 IBM Corp. under the Apache 2.0 license.

gha_language: JavaScript


text:
---
hrs_structure:
  division: '2'
  volume: '11'
  title: '26'
  chapter: 482C
  section: 482C-1
type: hrs_section
tags:
  - Business
menu:
  hrs:
    identifier: HRS_0482C-0001
    parent: HRS0482C
    name: 482C-1 Unlawful transfer of recorded sounds
weight: 41005
title: Unlawful transfer of recorded sounds
full_title: 482C-1 Unlawful transfer of recorded sounds
---
**[§482C-1] Unlawful transfer of recorded sounds.** It shall be unlawful for any individual, firm, partnership, corporation or association to transfer or cause to be transferred, without the consent of the person who owns the master phonograph record, master disc, master wire, master tape, master film or other device or article from which the sounds are derived, any sounds recorded on a phonograph record, disc, wire, tape, film, or other article on which sounds are recorded, with intent to sell or cause to be sold, or use or cause to be used for profit through public performance the article onto which such sounds are recorded. [L 1975, c 81, pt of §1]

repository: SamMade/BlueAndKrabby

repo_name: SamMade/BlueAndKrabby


text:
# jobq

## License

 `jobq` Copyright (C) 2016 Kazumichi Yamamoto.

  This project is published under [Apache 2.0 License](LICENSE.txt).

## Author

  * Kazumichi Yamamoto ([@yamamoto-febc](https://github.com/yamamoto-febc))

repository: yamamoto-febc/sacloud-delete-all

repo_name: yamamoto-febc/sacloud-delete-all


text:
# Card Skeleton Loader - By Jon D Jones 💥

This project makes uses of:

- HTML
- CSS
- JS

## 👻 Live Site URL & Status 👺

[https://card-skeleton-loader.netlify.app/](https://card-skeleton-loader.netlify.app/)

[![Netlify Status](https://api.netlify.com/api/v1/badges/834c5030-37ef-4bcc-b0b2-5d854c9957b4/deploy-status)](https://app.netlify.com/sites/card-skeleton-loader/deploys)

## 👾 How To Use ☄

Load the site.. its HTML only!

repository: jondjones-poc/card-skeleton-loader

repo_name: jondjones-poc/card-skeleton-loader


text:
# Pseudophacidium P. Karst. GENUS

#### Status
ACCEPTED

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

#### Published in
Acta Soc. Fauna Flora fenn. 2(no. 6): 157 (1885)

#### Original name
Pseudophacidium P. Karst.

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
# Examples/usage

To get started, there are only a handful of header files you need to familarize yourself with. Namely:
* cbpro++/marketdata/products.h
* cbpro++/marketdata/currencies.h
* cbpro++/accounts/accounts.h
* cbpro++/orders/orders.h
* cbpro++/auth.h

(As the library expands and covers more functionality, there may be additional headers).

When you make a request, typically an object (or a vector of objects) encapsulating the Coinbase response is returned. You don't need to
concern yourself with the various response types (simply use auto). Within the following directories are select examples of what can be
done with the library.

branch_name: refs/heads/main


text:
# Azure IoT Edge Hands On Labs

## Overview

This hands-on lab demonstrates setting up, configuring, and developing modules for [Azure IoT Edge](https://azure.microsoft.com/en-us/services/iot-edge/).  The intent of these labs is not to cover exhaustively every IoT Edge topic, but rather cover a scenario that allows the student to learn and understand the basics of IoT Edge, develop modules and Edge ASA jobs, and perform Edge configuration, all in a pseudo-realistic use case.

In this workshop you will:

* Setup and configure a simple IoT Device, based on the [MXChip IoT DevKit](https://aka.ms/iot-devkit), to simply send sensor data over the serial port usign a custom protocol every 3 seconds
* Create an "IoT Device" that reads the data from the serial port and connects to IoT Hub __**through**__ IoT Edge
* Create an IoT Edge module that reads the simple CSV temp/humidity data from the device and converts to JSON and passes the message along
* Create an Azure Stream Analytics module that a) aggregates the "every 3 seconds" data to a 30 second frequency to send to IoT Hub in the cloud and b) looks for temperatures above a certain threshold.  When a threshold violation occurs, the module will drop an "alert" message on Edge
* create an IoT Edge module that reads the "alert" message from ASA and sends a Direct Method call to the IoT Device to light up an "alert" LED

The labs are broken up into the following modules:

* [Module 1](module1) - Prerequisites and IoT Edge setup
* [Module 2](module2) - Setup and program the "IoT Device" using on of the following options
* [Module 3](module3) - Develop "Formatter" module
* [Module 4](module4) - Azure Stream Analytics Edge job
* [Module 5](module5) - Develop "Alert" module

If you have questions or issues for the lab, check out our [troubleshooting](troubleshooting.md) guide!

Below is a conceptual flow for the labs to help visualize what is taking place and how the data is flowing through the system  ("T/H" is short for "temperature and humidity)

![conceptual drawing](/images/IoT-Edge-Labs-Conceptual-Design.png)

## Hardware

For this lab, for simplicity of setup, we are using our Windows 10 desktops (running Docker and Linux containers) as the Edge device.  For the sensor device, we leverage an Arduino Uno or an MXChip IoT DevKit. Alternatively you are free to use any device that can send data over serial.

## Prerequisites

>Note: For the lab exercises, we need an IoT Hub created in an Azure Subscription for which you have administrative access.

In order to execute the hands-on labs, there are a number of pre-requisites that need to be installed and configured.  Unless otherwise noted, the default installation of the items below are fine

* Windows 10 Fall Creators Update (build 16299)
* [Docker for Windows](https://docs.docker.com/docker-for-windows/install/)   ** the "community edition" is fine.  Make sure you install the STABLE version.  A reboot may be required to enable Hyper-V

>NOTE:  The labs are intended to be run with Linux containers (on a Windows host).  Please ensure that you are running Linux containers.  The best way to tell is to right-click on the "whale" in your notification bar and make sure you see "Switch to Windows containers" in the context menu.  That shows that you are currently running Linux containers.  If not, please make the switch.

* [Visual Studio Code](https://code.visualstudio.com/)
* [.NET Core SDK](https://www.microsoft.com/net/core#windowscmd)
* [Arduino IDE](http://www.arduino.cc/)
* [Open SSL](https://sourceforge.net/projects/openssl/)
    * for the lab instructions later, create a c:\utils folder and unzip the downloaded OpenSSL zip to c:\utils\
    (so you should a folder structure that looks like this->    c:\utils\OpenSSL)
* [git](https://git-scm.com/downloads/)   ** installation of the default components and default configurations are fine

* [Python 2.7 for Windows](https://www.python.org/downloads/)  -- __**make sure it's 2.7.x, NOT 3.x.x**__
    * during setup, elect to "add python 2.7 folder to the path"  (see screenshot below -- You will need to SCROLL DOWN to see it)

![python_install](/images/python_install.png)

[MXChip IoT DevKit](https://aka.ms/iot-devkit) requires the installation of some additional libraries and toolchains. Whilst These can be installed [manually](https://microsoft.github.io/azure-iot-developer-kit/docs/installation/), We encourage you to use the following [one-click installation process](https://microsoft.github.io/azure-iot-developer-kit/docs/get-started/#install-development-environment) to prepare the development environment. This will install a complete development environment including:
* Node.js and Yarn: Runtime for the setup script and automated tasks.
* Azure CLI 2.0 MSI - Cross-platform command-line experience for managing Azure resources. The MSI contains dependent Python and pip.
* Visual Studio Code (VS Code): Lightweight code editor for DevKit development.
* Visual Studio Code extension for Arduino: Extension that enables Arduino development in Visual Studio Code.
* Arduino IDE: The extension for Arduino relies upon this tool.
* DevKit Board Package: Tool chains, libraries, and projects for the DevKit.
* ST-Link Utility: Essential tools and drivers.

If you already have any these installed, the script will detect that and skip them.

Get Started with [Module 1](module1)

repository: dtoronto/azure-iot-edge-hol

repo_name: dtoronto/azure-iot-edge-hol


text:
HalVM on Fedora
===============

This Docker image contains a Fedora system with HalVM.
Based on [afdudley/halvm](https://registry.hub.docker.com/u/afdudley/halvm/) (which uses Arch Linux).

Github page: <https://github.com/stadlerb/halvm_fedora_docker>

See [the HalVM Github page](https://github.com/GaloisInc/HaLVM) for more details.


text:
### Expected Behavior

### Actual Behavior

### Steps to reproduce the behavior

### Versions

Pandoc and context versions

    pandoc --version
    context --version

OS information on non-Windows can use one of the following commands

    cat /etc/*-release
    lsb_release -a


text:
# Packet Sniffer - C Implementation

Packet Sniffer, implemented in C, using raw sockets. Can capture both in promiscuous mode (for the entire network) and normal mode (just for your machine).

For now, dumps everything to console but support for dumping to files will be added soon!

## Architecture

Stars processing a packet from the bottom-up i.e., `Link Layer (Ethernet)` --> `Network Layer` --> `Transport Layer`.

Later on, support will be added for processing HTTP, FTP and other common application layer protocols.

## Files

1. `includes.h` - One place for all includes.
2. `packet.c` - Includes all the logic to process a captured packet.
3. `ui.c` - Includes all the view related stuff. Printing a packet and different parts of it (Link Layer, Network layer, Transport Layer etc.).
4. `sniffer.c` - Main entry point for the application.

## Future

- This was done just for learning purposes but to finish this up, support for processing HTTP, FTP and other common application layer protocols will be added.

- Another version of this same program will use `libpcap` instead of directly tapping into the raw socket stream.

repository: fabgithub/Packet-Sniffer

repo_name: fabgithub/Packet-Sniffer


text:
Twilio
======

Twilio angularjs service to send sms, mms messages

Additional Notes
=================
Using Sendgrid in your own app is easy now.

Simply reference phone in your module:

     var app = angular.module('myapp', ['firebase', 'phone']);

and then $phone in your controller:

     function MyController($scope, $firebase, $phone, $http, $log)

Set your API user and Key Variables (I'm hoping this will change in the future):

      var api_user = "";
      var api_key = "";

Finally send an email:

     $phone.$send_sms(fill out the variables);

(Then you can write a router to manage when the user opens the site to their unique address)

If you'd like to create a service for another email provider, simply make a pull request, and create a service that contains the send function with the same parameters.

Right now we'll call this version 0.1 but eventually the send will be locked down for all future releases and we'll have a 1.0 release.


text:
# Duplicate image remove assistant

This is a GUI tool I made in an afternoon to assist deleting repeated images.

![](screenshots/two.png)
![](screenshots/three.png)

# Usage

```
 ./duplicate_sh.py [duplicate_sets_list.txt] [output_script.sh]
```

## Keybindings

 - left/right arrow: go to previous/next image
 - [1-9]: select images to save
 - enter: confirm numeric selection
 - d: save only the first image
 - s: save all images (don't delete any)
 - w: write deletion script

# Dependencies

- `python-pillow`

# Input & Output

The tool takes as input a text file with list of similar/repeated images grouped in sets, like this:

```
Images/vg/1520136382070.jpg
Images/game posters/1549056255824.jpg

Images/space/planets/1529148850014.jpg
Images/space/planets/1529148851879.jpg
Images/space/planets/1529148854975.jpg
Images/space/planets/1540001496237.jpg

Images/to-classify/deviantart/dcky9lc-1dc57080-4f49-4a7c-830f-3969eaa29a43.jpg
Images/to-classify/deviantart/kicks_by_rossdraws-dcky9lc.jpg
Images/to-classify/deviantart/dcky9lc.jpg
```

The tool allows viewing each set of images at once to decide which ones to save
and which ones to delete.  The result is written to a shell script that can be
later executed.  The resulting script looks like this (showing the final
selection in a comment):

```
#!/bin/sh

# [0]
# rm 'Imatges/wallpapers/1274533397659.jpg'
rm 'Imatges/wallpapers/1312909785960.jpg'
rm 'Imatges/wallpapers/1289925824279.jpg'

# [0, 2]
# rm 'Imatges/wallpapers/1291557899968.jpg'
rm 'Imatges/wallpapers/1304163762136.jpg'
# rm 'Imatges/wallpapers/1312911526166.jpg'
rm 'Imatges/wallpapers/1314755398122.jpg'
```

# How to generate the list

This tool only focuses on assiting the deletion of repeated/similar images once
the list of repeated/similar images is done.  In order to get the list I
recommend using the [imgdupes](https://github.com/knjcode/imgdupes) tool from
knjcode.  It can be used from docker like this:

```
docker run -it -v $PWD:/app knjcode/imgdupes --sort imagesize --no-subdir-warning -m -r Images phash 2 | grep -v 'Calculating image hashes' | tee duplicate_sets_list.txt
```

imgdupes allows you to find similar images that have different resolutions or
contain minimal image variations.

The output file will need some cleaning to look like the example shown in this README.

# License

The code is released under the 3-clause BSD License.


text:
# Phyllostachys pubescens var. heterocycla VARIETY

#### Status
SYNONYM

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

#### Published in
Bambou (Mons) 1:55, 97, 118. 1906

#### Original name
null

### Remarks
null

path: /life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Phyllostachys/Phyllostachys edulis/ Syn. Phyllostachys pubescens heterocycla/README.md


text:
---
title: "What is JSX Pragma"
date: "2019-11-14"
description: A pragma is a compiler directive. It tells the compiler how it should handle the contents of a file. JSX syntax on its own isn’t readable by the browser. In order to ship something readable to the browser, JSX needs to be converted to plain JavaScript.
category: Gatsby
---

[What is JSX Pragma](https://www.gatsbyjs.org/blog/2019-08-02-what-is-jsx-pragma/)

If you’re looking into using [Theme UI](https://theme-ui.com/) , you’ll come across some (potentially) unfamiliar looking syntax:

```js
/** @jsx jsx */
import { jsx } from "theme-ui"
```

This is a JSX pragma.  I had heard the phrase, but not thought too much about it until it came up with Gatsby theming — and lots of other folks hadn’t either.

What is a pragma?

A pragma is a compiler directive. It tells the compiler how it should handle the contents of a file.

An example of this in JavaScript is 'use strict' mode. 'use strict' is a directive that enables JavaScript’s [Strict Mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode), which is a way to opt in to a more restricted variant of JavaScript. It denotes that the code should be processed in a specific way.

What is JSX pragma?

JSX syntax on its own isn’t readable by the browser. In order to ship something readable to the browser, JSX needs to be converted to plain JavaScript.

Most React-based frameworks (like Gatsby), come with tooling already set up to support this conversion (usually Babel). How does that tooling know how to transform JSX? By default, the [Babel plugin](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx) will convert JSX into JavaScript that calls the React.createElement function.

Take the following JSX, for example:

```js
const element = <h1 className="greeting">Hello, world!</h1>
```

That JSX syntax compiles to a call to React.createElement, like this:

```
const element = React.createElement(
  "h1",
  { className: "greeting" },
  "Hello, world!"
)
```

Using a custom JSX pragma

There are two ways to specify a custom function (and therefore replace React.createElement):

- Add an option to the Babel plugin
- Set a pragma comment at the beginning of a module

Add an option to the Babel plugin

Changing the function in the Babel plugin will transform all JSX in an application to use the specified function.

[Babel Preset](https://emotion.sh/docs/@emotion/babel-preset-css-prop)

This method will not work with [Create React App](https://github.com/facebook/create-react-app) or other projects that do not allow custom babel configurations. Use the JSX Pragma method instead.

.babelrc
```
{
  "presets": ["@emotion/babel-preset-css-prop"]
}
```

Set a pragma comment

Using a pragma comment will limit the change to the modules the comment is added to. Therefore, you can use React.createElement by default, and opt in to the custom function only where needed. This is [the approach taken in Theme UI](https://www.gatsbyjs.org/docs/theme-ui/#adding-styles-to-elements).

repository: taislu/mobilelu-starter-blog

repo_name: taislu/mobilelu-starter-blog


text:
Orecore Payment Protocol
==============================

A module for [orecore](https://github.com/GAB5TER/orecore) that implements Payment Protocol and other related BIPs.

## Getting Started

This library is distributed in both the npm and bower packaging systems.

```sh
npm install orecore-lib
npm install orecore-payment-protocol
```

There are many examples of how to use it on the developer guide [section for payment protocol](https://bitcore.io/api/paypro). For example, the following code would verify a payment request:

```javascript
const PaymentProtocol = require('orecore-payment-protocol');

const body = PaymentProtocol.PaymentRequest.decode(rawbody);
const request = new PaymentProtocol().makePaymentRequest(body);

const version = pr.get('payment_details_version');
const pki_type = pr.get('pki_type');
const pki_data = pr.get('pki_data');
const serializedDetails = pr.get('serialized_payment_details');
const signature = pr.get('signature');

// Verify the signature
const verified = request.verify();
```

## Contributing

See [CONTRIBUTING.md](https://github.com/GAB5TER/orecore/blob/master/CONTRIBUTING.md) on the main orecore repo for information about how to contribute.

## License

Code released under [the MIT license](https://github.com/GAB5TER/orecore/blob/master/LICENSE).

Copyright 2013-2015 BitPay, Inc. Bitcore is a trademark maintained by BitPay, Inc.


text:
# Data Validation

[![report](https://img.shields.io/badge/report-data%20inconsistencies-orange)](https://mbed-target.s3.eu-west-2.amazonaws.com/validation/index.html)

Mbed has historically had a number of ways to manage target information, which has led to inconsistencies over time
where some sources have been updated while others have not. This repository contains a tool that compares the various
sources of data and generates a report of their consistency. This report is generated on a daily basis and this is
available via the link above.

The following table describes the data sources and usage for Mbed 5.

| Data Source | Definition Location | Used By |
| :---------- | :------------------ | :------ |
| Tools Platform Database | [mbed-os-tools](https://github.com/ARMmbed/mbed-os-tools/blob/master/src/mbed_os_tools/detect/platform_database.py) | `mbed-ls` `mbed detect` |
| `targets.json` | [mbed-os](https://github.com/ARMmbed/mbed-os/blob/master/targets/targets.json) | `mbed compile`, Online Compiler |
| Online Database | OS Site Database (os.mbed.com) | Product Code reservation, Public Websites, Mbed Studio |

## Single Source of Truth

The tools for Mbed 6 use a single source of truth for each piece of data, although all data may not come from the same
source. For all common data, the source will be the OS Site Online Database, for example the `Product Code` to
`Build Target` mapping will be stored in the OS Site Database and all other definitions will be considered irrelevant.
Other information, such as build configuration, will continue to be stored in Mbed OS as it is only relevant to Mbed
OS. However, it will not be duplicated elsewhere.

There is the potential for confusion during the transition from Mbed 5 to Mbed 6. For example, the `mbed-tools devices`
command may identify boards differently from the tool `mbed-ls`, which it is replacing. But ensuring there is a single
source of truth will mean that Mbed OS and all tools will be consistent in the future.

# Mbed Targets Offline Database

This package contains an internal database of the relevant information from the OS Site Online Database so that it can
be used in an offline mode. This database is generated as part of CI, which is run on a daily basis and results in a
Pull Request in GitHub if any information needs to be updated. Updates to the database are then released as a new
version of the Python package on PyPI.

The following diagram shows an example usage of this package (`mbed-targets`) by the `mbed-tools devices` command, which
needs to identify the `Build Target` from the `Product Code`. This can be attempted in an offline, online or auto mode,
which uses the internal database first, falling back to accessing the online database if the `Product Code` is unknown.

![Mbed Targets Dataflow](http://www.plantuml.com/plantuml/proxy?cache=no&src=https://raw.githubusercontent.com/ARMmbed/mbed-targets/master/diagrams/data_validation/mbed_targets_dataflow.puml)

repository: ARMmbed/mbed-targets

gha_language: Python

repo_name: ARMmbed/mbed-targets


text:
# GitHub

You will have to provide a token with a permission to clone/pull/push to Private Repository:
![PIC](images/token.png)

# Route53

Required IAM Policy:

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "route53:ListHostedZones",
                "route53:ListResourceRecordSets"
            ],
            "Resource": "*"
        }
    ]
}
```

repository: anton-yurchenko/dns-exporter

gha_language: Go

repo_name: anton-yurchenko/dns-exporter


text:
# CMake module replacements for Tegra CUDA builds

This repository contains replacements for the old-style
FindCUDA.cmake module and its helpers for use in cross-building
CUDA applications for Jetson systems using Yocto Project/OpenEmbedded
build tools.

They are direct copies from upstream CMake sources with
minor modifications that fix issues with cross builds:

* Upstream FindCUDA.cmake attempts to invoke the C compiler
  with modified flags, which fails in the OE build environment.

* Recent JetPack releases containing CUDA 10.2 package the
  libcublas library differently from earlier releases.

Even though CMake's FindCUDA module has been deprecated in favor
of CUDA language support and the FindCUDAToolkit module for some
time, many applications still use FindCUDA.

1. Run the `./configure` script to create the Makefile.
2. `make all`

## Installing

Once built, just use `make install` to install the default
system root and prefix.  You can specify an alternate root
by passing `DESTDIR=<path>` on the command, and an alternate
prefix with `prefix=<path>`.


text:
# IRB Rocks!

[IRB Rocks](http://irb.rocks) is a blog about Ruby. It contains articles to improve in this language or some tricks to hack your code ;).

This repository contains all code of the articles. You can clone it to use in your personal projects or fork and contribute to the blog.

# Index

* 15 January 2016 - [Reduce nil verifications in nested hashes](https://github.com/irbrocks/blog-sources/tree/master/reduce-nil-verifications-nested-hashes)
* 16 October 2015 - [Determine if model is just created](https://github.com/irbrocks/blog-sources/tree/master/determine-if-a-model-is-just-created)
* 24 July 2015 - [Colorize Rails unit tests](https://github.com/irbrocks/blog-sources/tree/master/colorize-rails-unit-tests)

repository: irbrocks/blog-sources

repo_name: irbrocks/blog-sources


text:
# csh scripts
exploring the differences csh has with sh

## Contributing
please make any changes you like, I'm looking for novel differences as a learning method for exploring different shell design features through code examples

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

repository: jamesfranklinnetsec/scripts-idk

repo_name: jamesfranklinnetsec/scripts-idk


text:
# Ipomoea deccana var. lobata (Clarke) S.C.Johri VARIETY

#### Status
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
null

### Remarks
null


text:
# random

fun and dumb stuff ive coded

- conjugate/getconj.js: conjugate a french verb and display the result in lynx. `conjugate aller`

- dec: decode messages expressed as groups of 3 numbers. `dec 852 431 110 202`

- dfree: format `btrfs filesystem usage`, getting a list of paths from a dfree.conf file. `dfree`

- getmod: download modules from modarchive.org. `getmod desert_dawn.mod`

- ruin: decrement every byte in a file. `ruin wedding-photo.tiff`

- strlen: get the length of 1 or more strings. `strlen -h`

- vote-new: rewrite of a program a friend made. `vote!`

license: Unlicense


text:
# ActiveRecord SQL Server Adapter (SQL Server version 2014 hack)

The SQL Server adapter for ActiveRecord. This particular fork adds support for SQL Server version 2014, since it is backwards compatible with SQL Server version 2012.

Questions/suggestions/issues/pull-requests are welcome.

Enjoy.

repository: pirminis/activerecord-sqlserver-adapter

repo_name: pirminis/activerecord-sqlserver-adapter


text:
# CDCL(Crypto)

CDCL(Crypto) is a CDCL SAT solver for cryptanalysis problems (inspired by the
CDCL(T) paradigm in SMT solvers). It uses a programmatic SAT design to extend
the logical reasoning components of a SAT solver (propagation and conflict
analysis) with domain-specific knowledge about the cryptographic primitives
being analyzed by the solver. The base solver used in this project is MapleSAT.

## Usage

This repository hosts the implementation of the general framework of
CDCL(Crypto) described in [1]. The programmatic callback is the function
`Solver::callbackFunction` within `src/core/Solver.cc`, which contains
comments and a sample code on how to use the function. For each problem,
the user should encode their higher level constraints inside this function. The assigned value to each variable `x` can be read by `value(x)`, and returned reason/conflict clauses should be in `vec<Lit>` (Minisat format).

## References

[[1]](https://arxiv.org/abs/2005.13415) Nejati, Ganesh, "CDCL(Crypto) SAT
Solvers for Cryptanalysis", CASCON 2019.

[[2]](https://link.springer.com/chapter/10.1007/978-3-319-98334-9_47) Nejati,
Horacek, Gebotys, Ganesh, "Algebraic Fault Attack on SHA Hash Functions Using
Programmatic SAT Solvers", CP 2018


text:
MergeLife: JavaScript
=====================

This folder contains 3 MergeLife JavaScript/NodeJS projects:

* **mergelife-lib** - The main MergeLife JS implementation.
* **mergelife-util** - A command line utility to allow MergeLife to render, evaluate, and evolve.
* **viewer-web** - How to use the mergelife-lib in a browser as a viewer.

repository: jeffheaton/mergelife

gha_language: Java

repo_name: jeffheaton/mergelife


text:
# Challenge 4: Integrate web app with deployed AutoML model

## Prerequisites

1. A deployed AutoML model trained on an image dataset of faces
   - The API endpoint for making predictions with this model
   - permissions to make calls to this API

2. A web app back end

## Considerations

## Requirements
To pass this challenge, the solution needs to satisfy all the requirements listed below:
- Able to make individual image predictions using images captured by the application

## Objectives
In this challenge, you will learn:
- How to make authenticated AutoML Vision API calls from an application back end

## Resources & Helpful Links
### Guides

### APIs & SDKs
- AutoML Python Client API - <https://googleapis.dev/python/automl/latest/index.html>
- AutoML REST API - <https://cloud.google.com/vision/automl/docs/reference/rest>
### Examples
- AutoML online individual prediction - <https://cloud.google.com/vision/automl/docs/predict>

repository: danielwnn/GCP-Hackathon

repo_name: danielwnn/GCP-Hackathon


text:
# Grafana Compare Query Datasource

---

[中文文档](README.md)

Webpack copy of
[grafana-meta-queries](https://github.com/GoshPosh/grafana-meta-queries)
[grafana-compare-queries](https://github.com/AutohomeCorp/grafana-compare-queries)

This plugin is built as a datasource plugin that combines and calc multi queries with arithmetic formula

# Next Step

- add more functions of financial Engineering

# Screenshots

![Screenshot1](/img/img1.png)

# Installation

```shell
cd /var/lib/grafana/plugins
sudo git clone git@github.com:GoshPosh/grafana-meta-queries.git
sudo service grafana-server restart
```

# Usage

- Create a datasource and select the Compare Calc Datasource plugin.
- Create a basic arithmetic formula,click calc

# Credits

Based on

- [grafana](https://github.com/grafana/grafana)
- [simple-json-datasource](https://github.com/grafana/simple-json-datasource)
- [grafana-meta-queries](https://github.com/GoshPosh/grafana-meta-queries)
- [grafana-compare-queries](https://github.com/AutohomeCorp/grafana-compare-queries)

Made by ray@og

repository: rayleeafar/grafana-calc-queries

repo_name: rayleeafar/grafana-calc-queries


text:
---
layout: post
title: ActiveRecord find_or_create_by and concurrency - how to handle it?
 One of them is a `find_or_create_by` which is cool, because it avoids using IF statement.
Unfortunately, as in life, everything that is easy to use, isn't always optimal. Under certain conditions, we may encounter some problems. Sometimes, even though it will work on one thread well, doesn't mean it will be working correctly on parallel.

## Case:
Imagine that we have simple AR model:
```ruby
class CounterCache < ApplicationRecord; end
```

```ruby
class CreateCounterCaches < ActiveRecord::Migration[5.2]
  def change
    create_table :counter_caches do |t|
      t.string :key, null: false
      t.integer :value, default: 0, null: false

      t.timestamps
    end
  end
end
```

Then we use this model in parallel sidekiq worker:
```ruby
class CounterCacheWorker
  include Sidekiq::Worker

  def perform(key)
    CounterCache.find_or_create_by!(key: key).touch
  end
end
```

We have there `find_or_create_by` method which will create a new record if Postgres doesn't find record with specific key. Then we simple `touch` this record, but that isn't important - we want to focus on `find_or_create_by`.

Do you see any issues with the above code? Maybe it looks good at first glance, but this won't work, because our `find_or_create_by` is not atomic.

> We can define an atomic operation as any operation that is uninterruptible. - Robert C. Martin, Clean code

As the name of the method indicates, we have 2 operations to perform - find and create (if record doesn't exist). Let's see what is going on under the hood:

```ruby
# File activerecord/lib/active_record/relation.rb, line 211
def find_or_create_by(attributes, &block)
  find_by(attributes) || create(attributes, &block)
end
```

As we can see if record exists, `find_or_create_by` returns `SELECT` query, if not - it executes second `INSERT` query. Because of that there is a s chance that our parallel worker will create duplicated records (with the same key). It is called a `race conditions` - when few threads or instances try to execute queries at one time, they can make SELECT on one moment and then execute INSERT or UPDATE in an incorrect way.

{: style="width: 100%; text-align: left;"}
**Time ASC** | **Thread 1** | **Thread 2**
--- | --- | ---
    | *Read data* |
    |  | *Read data*
    |  | *Write data*
    | *Write data* |

## First attempt

I wrote simple script which I'll use for testing:
```ruby
10.times { CounterCacheWorker.perform_at(30.seconds.from_now, "books") }
```

Result:

![_config.yml]({{ site.baseurl }}/images/posts/atomic-ar/1.png)
{: style="text-align: center;"}

Using ActiveRecord `find_or_create_by` we have duplicated records - that was easy to predict.
Let's have fun trying different ways to solve the problem!

## Pure PostgreSQL find_or_create_by query

![_config.yml]({{ site.baseurl }}/images/posts/atomic-ar/postgresql-ride-it-like-you-stole-it.jpg)
{: style="text-align: center;"}

I added new method to our CounterCache model:

```ruby
class << self
  def select_or_insert_key(key)
    sel = <<-SQL
      INSERT INTO #{table_name} ("key")
      SELECT '#{key}'
      WHERE NOT EXISTS (SELECT 1 FROM "#{table_name}" WHERE ("#{table_name}"."key" = '#{key}'));
    SQL
    ActiveRecord::Base.connection.execute(sql)
  end
end
```

So, the scenario I want to check is based on the assumption that finding a record and creating a new one in a database will be fast enough to avoid duplication.

Result:

![_config.yml]({{ site.baseurl }}/images/posts/atomic-ar/2.png)
{: style="text-align: center;"}

It's better - we haven't got any duplication, but we have to remember that this method is still non atomic. Let's try again, but now I'll change number of threads running in one moment from 2 to 10:

![_config.yml]({{ site.baseurl }}/images/posts/atomic-ar/3.png)
{: style="text-align: center;"}

The conclusion is simple - with more parallel query executions, `INSERT WHERE NOT EXISTS` doesn't work.

##  PostgreSQL lock

What about locking the table?

We can achieve it quite easily:

```ruby
class << self
  def find_or_create_by_with_lock!(attributes, &block)
    ActiveRecord::Base.transaction do
      ActiveRecord::Base.connection.execute("LOCK #{table_name} IN ACCESS EXCLUSIVE MODE")
      find_or_create_by!(attributes, &block)
    end
  end
end
```
I wrote `find_or_create_by_with_lock!` method, which allows me to use AR's `find_or_create_by!` in transaction with a lock `IN ACCESS EXCLUSIVE MODE`. This type of lock is the most strict of [all PostgreSQL locks](https://www.postgresql.org/docs/11/explicit-locking.html), because when one process accesses the table, PostgreSQL doesn't allow to read and write for others.

And it works! But it also has a side effect - performance. How big? Let's measure:

```ruby
Benchmark.measure do
  1000.times { CounterCache.find_or_create_by!(key: "books") }
end
```
=> total time: 2.51s
```ruby
Benchmark.measure do
  1000.times { CounterCache.find_or_create_by_with_lock!(key: "books") }
end
```
=> total time: 6.12s

The sad thing is that it's almost 3 times slower! And if we run `find_or_create_by_with_lock!` parallel even slower, because threads will block each other.

## Unique index

We are going for success. The case is that we can set unique index on table column or even group of them. Thanks to that our database prevent duplications and raises an `UNIQUE INDEX` error.

```ruby
class AddIndexForCounterCaches < ActiveRecord::Migration[5.2]
  def change
    add_index :counter_caches, :key, unique: true
  end
end
```

In the result we haven't got any duplications, but we have 9 errors on Sidekiq:
```ruby
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_counter_caches_on_key" DETAIL: Key (key)=(books) already exists. : INSERT INTO "counter...
```

Quick fix:
```ruby
def perform(key, logger = Rails.logger)
  CounterCache.find_or_create_by!(key: key).touch
rescue ActiveRecord::RecordNotUnique => exception
  logger.warn("Skipping an existing product: #{exception.message}")
  # Here we can add logic to perform whatever we need
end
```

We, Ruby developers, know that raising exceptions is expensive, but we need to remember that ActiveRecord can be even more ([check it](https://gist.github.com/paneq/a643b9a3cc694ba3eb6e)), so I think using unique index is a good way to solve our `find_or_create_by` problem.

## I want more fun!
Will we be able to avoid raising exceptions? Let's find out!

We know that AR isn't atomic, locks aren't efficient and we don't want to raise an exception. For me we should focus on database capabilities, is it possible at all?

![_config.yml]({{ site.baseurl }}/images/posts/atomic-ar/maybe-i-can-i-dont-know.jpg)
{: style="text-align: center;"}

So, let's check what we can do with [PG INSERT](https://www.postgresql.org/docs/11/sql-insert.html). I see some interesting options there:
```
INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ]
    [ OVERRIDING { SYSTEM | USER} VALUE ]
    { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
    [ ON CONFLICT [ conflict_target ] conflict_action ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

where conflict_target can be one of:

    ( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opclass ] [, ...] ) [ WHERE index_predicate ]
    ON CONSTRAINT constraint_name

and conflict_action is one of:

    DO NOTHING
    DO UPDATE SET { column_name = { expression | DEFAULT } |
                    ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
                    ( column_name [, ...] ) = ( sub-SELECT )
                  } [, ...]
              [ WHERE condition ]
```

Maybe we can use ON CONFLICT option. After quick research I found [library](https://github.com/jesjos/active_record_upsert) which we can use for tests.

First of all we must indicate in which column a conflict may occur. We can do that by adding to model:
```ruby
upsert_keys :key
```

In next step we have to update our worker:
```ruby
class CounterCacheWorker
  include Sidekiq::Worker

  def perform(key)
    CounterCache.upsert!(key: key)
  end
end
```

And run it..
Bang, it works! The queries looks like these:

![_config.yml]({{ site.baseurl }}/images/posts/atomic-ar/4.png)
{: style="text-align: center;"}

Postgres tried to create a new record but because there was a record with key "books" - instead of raising error, it updates its fields (in our case any field needs update).
I think that upserts can be useful in situations where we care about the latest record value, which isn't calculated on its previous versions (for example `increment` still won't work, but it's a topic for another blog post).


text:
# Asteridiella turpiniicola Hosag., 1990 SPECIES

#### Status
SYNONYM

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

#### Published in
in Hosagoudar & Goos, Mycotaxon 36(2): 341 (1989)

#### Original name
Asteridiella turpiniicola Hosag., 1990

### Remarks
null

path: /life/Fungi/Ascomycota/Dothideomycetes/Meliolales/Meliolaceae/Prataprajella/Prataprajella turpiniicola/ Syn. Asteridiella turpiniicola/README.md


text:
# Crypto AES CTR

[![NPM version](http://img.shields.io/npm/v/crypto-aes-ctr.svg)](https://www.npmjs.com/package/crypto-aes-ctr)

A convenience wrapper around node's `aes-256-ctr` cipher stream that allows one to specify the starting `counter` for AES CTR mode.  This gives the option to start reading an AES encrypted file in the middle of the file (i.e. 'seek') vs CBC mode which requires that you start from the beginning.

The `counter` parameter is the AES block index that the file stream is starting at.  The block size of AES is 128 bits or 16 bytes, so you need to start the file steam at a byte location that is a multiple of 16.  See this [wikipedia page](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation) for more details on how AES CTR mode works.

## Install

```shell
npm install --save crypto-aes-ctr
```

## Usage

```javascript

var cryptoAesCtr = require("crypto-aes-ctr");
var crypto = require("crypto");

// key is a 32 byte buffer
var key = crypto.pbkdf2Sync(password, salt, iterations, 32);

// iv is an 16 byte buffer (it is important that it is random)
var iv = crypto.randomBytes(16);
var cipherStream = cryptoAesCtr.createStream(key, iv);

// pipe encrypted input stream to cipherStream

```

This example works for both encryption and decryption of an entire file.

If you would like to start decrypting in the middle of a file, you just need to pass in a counter of the AES block you are starting the file stream at (starting from zero).

```javascript

// discard 3 AES blocks
var aesBlockSize = 16;
var counter = 3;

// starting in middle of encrypted file
var fileInStream = fs.createReadStream(myFile, { start: (aesBlockSize * counter) });

// ...

// create cipher stream with correct counter
var cipherStream = cryptoAesCtr.createStream(key, iv, counter);

// pipe encrypted input stream to cipherStream
fileInStream.pipe(cipherStream);

```

## License

[MIT License](http://en.wikipedia.org/wiki/MIT_License)

repository: jrnewell/crypto-aes-ctr

repo_name: jrnewell/crypto-aes-ctr