text:
# Cloudflair

[![Build Status](https://travis-ci.org/ninech/cloudflair.svg?branch=master)](https://travis-ci.org/ninech/cloudflair)
[![Gem Version](https://badge.fury.io/rb/cloudflair.svg)](https://badge.fury.io/rb/cloudflair)

A simple Ruby-wrapper around Cloudflare's v4 API.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'cloudflair'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install cloudflair

## A Note on Faraday

We have decided to not tightly control the version of faraday (anymore). The versions of faraday that are known to work are listed below. If you want to update to a newer version, you're doing it at your own risk. (But if it works, which is usually when all specs pass, please send a PR to update the list below.)

To be on the safe side, we recommend to lock `faraday` to any of the versions listed below. This can be done like this:

```ruby
gem 'cloudflair'
gem 'faraday', '>=0.13', '<0.14'
```

### Faraday Versions known to work

* `gem 'faraday', '>= 0.12', '<= 0.13'`
* `gem 'faraday', '>= 0.13', '<= 0.14'` (starting with `gem 'cloudflair', '>= 0.2.0'`)

## Usage

### Configuration

Put this somewhere, where it runs, before any call to anything else of Cloudflair.
If you are using Rails, then this would probably be somewhere beneath `/config`.

```ruby
require 'cloudflair'
Cloudflair.configure do |config|
  config.cloudflare.auth.key = 'YOUR_API_KEY'
  config.cloudflare.auth.email = 'YOUR_ACCOUNT_EMAIL'
  # if you have a user_service_key, you don't need auth.key and auth.email
  config.cloudflare.auth.user_service_key = 'YOUR_USER_SERVICE_KEY'

  # these are optional:
  config.cloudflare.api_base_url = 'https://your_cloudflare_mock.local'
  config.faraday.adapter = :your_preferred_faraday_adapter
  # built-in options: :logger, :detailed_logger; default: nil
  config.faraday.logger = :logger
end
```

### Call An API Endpoint

This gem is organized along the URL schema of Cloudflare (as shown in the examples below). So you're good off to check the original Cloudflare [API documentation](https://api.cloudflare.com) for more information on the URL schema.

```ruby
require 'cloudflair'

# GET https://api.cloudflare.com/client/v4/railguns
Cloudflair.railguns
# => [...]

# GET https://api.cloudflare.com/client/v4/zones
Cloudflair.zones
# => [...]

# GET https://api.cloudflare.com/client/v4/zones/cd7d068de3012345da9420df9514dad0
Cloudflair.zone('023e105f4ecef8ad9ca31a8372d0c353').name
# => "blog.example.com"

# GET https://api.cloudflare.com/client/v4/zones/cd7d068de3012345da9420df9514dad0/settings/development_mode
Cloudflair.zone('023e105f4ecef8ad9ca31a8372d0c353').settings.development_mode.value
# => "on"
# => "off"

# PATCH https://api.cloudflare.com/client/v4/zones/cd7d068de3012345da9420df9514dad0/settings/development_mode
# {"value"="on"}
Cloudflair.zone('023e105f4ecef8ad9ca31a8372d0c353').settings.development_mode.tap do |dm|
  dm.value = 'on'
  dm.save
end

# GET https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records/372e67954025e0ba6aaa6d586b9e0b59
Cloudflair.zone('023e105f4ecef8ad9ca31a8372d0c353').dns_record('372e67954025e0ba6aaa6d586b9e0b59').name
# => "examples.com"
```

You can use any field that Cloudflare's API returns. If a field is covered by some internal field, use `_field`. When you set a new value for a field and then want to access original value, you can use `field!` and `_field!`, respectively.

A good reference on how to use this wrapper are also the Rspecs.

## Implemented Endpoints

* `/railguns` GET, POST
* `/railguns/:railgun_id` GET, PATCH, DELETE
* `/railguns/:railgun_id/zones` GET
* `/zones` GET, POST
* `/zones/:zone_id` GET, PATCH, DELETE
* `/zones/:zone_id/analytics/dashboard` GET
* `/zones/:zone_id/analytics/colos` GET
* `/zones/:zone_id/available_plans` GET
* `/zones/:zone_id/available_plans/:plan_id` GET
* `/zones/:zone_id/available_rate_plans`
* `/zones/:zone_id/custom_hostnames` GET, POST, PATCH
* `/zones/:zone_id/dns_records` GET, POST
* `/zones/:zone_id/dns_records/:record_id` GET, DELETE (PUT not implemented)
* `/zones/:zone_id/purge_cache` POST
* `/zones/:zone_id/railguns` GET
* `/zones/:zone_id/railguns/:railgun_id` GET
* `/zones/:zone_id/railguns/:railgun_id/diagnose` GET, PATCH
* `/zones/:zone_id/settings/advanced_ddos` GET
* `/zones/:zone_id/settings/always_online` GET, PATCH
* `/zones/:zone_id/settings/browser_cache_ttl` GET, PATCH
* `/zones/:zone_id/settings/browser_check` GET, PATCH
* `/zones/:zone_id/settings/cache_level` GET, PATCH
* `/zones/:zone_id/settings/challenge_ttl` GET, PATCH
* `/zones/:zone_id/settings/development_mode` GET, PATCH
* `/zones/:zone_id/settings/email_obfuscation` GET, PATCH
* `/zones/:zone_id/settings/hotlink_protection` GET, PATCH
* `/zones/:zone_id/settings/ip_geolocation` GET, PATCH
* `/zones/:zone_id/settings/ipv6` GET, PATCH
* `/zones/:zone_id/settings/minify` GET, PATCH
* `/zones/:zone_id/settings/mirage` GET, PATCH
* `/zones/:zone_id/settings/mobile_redirect` GET, PATCH
* `/zones/:zone_id/settings/origin_error_page_pass_thru` GET, PATCH
* `/zones/:zone_id/settings/polish` GET, PATCH
* `/zones/:zone_id/settings/prefetch_preload` GET, PATCH
* `/zones/:zone_id/settings/response_buffering` GET, PATCH
* `/zones/:zone_id/settings/rocket_loader` GET, PATCH
* `/zones/:zone_id/settings/security_header` GET, PATCH
* `/zones/:zone_id/settings/server_side_exclude` GET, PATCH
* `/zones/:zone_id/settings/server_level` GET, PATCH
* `/zones/:zone_id/settings/sort_query_string_for_cache` GET, PATCH
* `/zones/:zone_id/settings/ssl` GET, PATCH
* `/zones/:zone_id/settings/tls_1_2_only` GET, PATCH
* `/zones/:zone_id/settings/tls_1_3` GET, PATCH
* `/zones/:zone_id/settings/tls_client_auth` GET, PATCH
* `/zones/:zone_id/settings/true_client_ip_header` GET, PATCH
* `/zones/:zone_id/settings/waf` GET, PATCH
* `/zones/:zone_id/settings/websockets` GET, PATCH

## Development

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

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

### Developing Guidelines

* The number one aim of this API wrapper is to mimic the Cloudflare API as it is laid out in the URL. So if the url is `/zones/:zone_id/analytics/dashboard`, then the corresponding Ruby code should become `Cloudflair.zones('abcdefg').analytics.dashboard`.
* The API should load resources only when required to. So `Cloudflair.zones('abcdefg')` alone would not call out to Cloudflare, but only when `Cloudflair.zones('abcdefg').name` is called. Likewise, `Cloudflair.zones` will immediately call Cloudflare, as it requires the result immediately. (Unless we begin to introduce a kind of 'delayed Array'. Yet we probably don't want that.)
* Adding additional wrappers for the API shall be easy and done in only a few minutes. (Most of the `/zones/:zone_id/settings/*` API calls were implemented in about five minutes.) So the cloudflair internal API should hide the complexity away. (E.g. the complexity of the fetching, parsing, error handling, etc. should be hidden away. See `Connection`, `Communication` and `Entity`, which contain almost all of the complexity of this Gem.)
* Please write Rspecs for each new API endpoint. Use the JSON provided in the official Cloudflare API documentation as test data.

## Contributing

Bug reports and pull requests are welcome on GitHub at [ninech/cloudflair](https://github.com/ninech/cloudflair).

### Whishlist

* Full API support
* Metrics reporting
* Rate Limit Tracking

## License

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

## About

This gem is currently maintained and funded by [nine](https://nine.ch).

[![logo of the company 'nine'](https://logo.apps.at-nine.ch/Dmqied_eSaoBMQwk3vVgn4UIgDo=/trim/500x0/logo_claim.png)](https://www.nine.ch)

repository: ninech/cloudflair

repo_name: ninech/cloudflair


text:
---
layout: doc_page
---

## Downloads

Choose the most recent release version from
[incubator-datasketches-xxx](https://www.apache.org/dyn/closer.cgi?path=/incubator/datasketches).

Or, clone or fork the current SNAPSHOT directly from the relevant repository.

### Version Numbers
Apache DataSketches uses [semantic versioning](https://semver.org/). Version numbers use the form major.minor.incremental and are incremented as follows:

* __major version__ for incompatible API changes
* __minor version__ for new functionality added in a backward-compatible manner
* __incremental version__ for forward-compatible bug fixes

The zip files downloaded from [incubator-datasketches-xxx](https://www.apache.org/dyn/closer.cgi?path=/incubator/datasketches)
include a version number in the name, as in _apache-datasketches-java-1.1.0-incubating-src.zip_.
This same number is also in the top section of the pom.xml file.

If you are developing using Maven and want to use, for example, incubator-datasketches-java, add the following dependencies to your pom.xml file:

```
<dependency>
  <groupId>org.apache.datasketches</groupId>
  <artifactId>datasketches-java</artifactId>
  <version>1.1.0-incubating</version>
</dependency>
```

#### Release Philosophy

These are fully tested, production quality releases, and hopefully as bug-free as humanly possible.
However, the code is continuously evolving and improvements in performance, documentation, additions
to the API, and bug fixes do occur.  When enough of these build up, especially for bug fixes or
performance improvements, a new release will be issued and the minor
digit will be incremented.  The incremental digit will only be used for bug fixes as stated above.

As stated above, the major digit is being reserved for major refactorings of the library where backward API
compatibility may not be guaranteed.

For the repositories that depend on java core, such as incubator-datasketches-hive,
the version number may be incremented just to be in sync with the java core repository,
and may not reflect any actual code changes other than a change in the pom.xml to reflect the new
dependency.

If you just want to run Hive and don't require direct access to the incubator-datasketches-java it is
recommended that you download the "with-shaded-core.jar", which includes the Hive jar as well as
shaded versions of the core jar and memory jar. The shading avoids conflicts with other possible versions
of core and memory that you might have in your system.

#### SNAPSHOT Jars
If you want the latest and greatest version of the code, it is certainly OK for you to create your
own snapshot jars from a clone or fork.
The code is automatically tested using the current test suite, but you might catch the code in
transition to a new future release. Caveat Emptor.

### Version History
Please use GitHub revisions history on the respective repositories

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# EZ Maintenance

Just a simple one page maintenance server based on nginx and a maintenance page.

[Nginx at Docker Hub](https://hub.docker.com/_/nginx/)

The [maintenance page gist](https://gist.github.com/rubyisbeautiful/4945fa431d18c8703f888c8dfc9af3a9) is mine but it is forked and only slightly modified
from [the original](https://gist.github.com/pitch-gist/2999707)

license: MIT

repository: rubyisbeautiful/ez-maintenance

repo_name: rubyisbeautiful/ez-maintenance


text:
# JS Fractal Explorer TODO File

Initial Release:
    [ ] Implement Zooming and Panning using the Cursor (Wheel and click Events)
        - May need to do a Low-resolution Render First before doing a second pass for Higher-resolution
        - https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event
            - Inherits from https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
            - Can get Coordinates, as well as wheel delta. Delta value can change Zoom Amount
        - Also have a slider to reset zoom amount
        - Maybe have decimal coordinates to set the coordinates for viewing certain fractal points
    [ ] Implement Fractal using Self-timeouts to allow for message passing (this is mainly a firefox problem)
        - Chunk the Canvas into NxN blocks (some blocks will have less pixels based on size) that are passed into message queue, and update the image information in that range
            - https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData
            - Allows for writing only part of an image to the canvas
            - May allow for a low-res first pass rendering that may be useful for zooming
            - Need to find a way to estimate how long rendering that chunk will take
                - use Drawing Algorithm to render low-res based on number of chunks
                - Assign priority where faster chunks will be drawn first
        - Implement a progress bar for rendering
            - Bar at top or bottom of screen (div element)
    [ ] Make Control Panel Hideable without using Inspect Element
    [ ] Implement Canvas Resizing resolution
    [ ] Image Export from Canvas
        - https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

Future:
    [ ] Refactor the code to make it more modular
        - Would allow for implementing other Fractals
        - Use Modules and Classes:
            - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
                - Classes will provide interface to produce fractals and draw things on the canvas
                - Should also provide method to populate the control panel (custom element?)
                - Should also provide Color Control Panels
    [ ] Implement Other Coloring algorithms
        - Gradient Editor (number of iterations)
        - https://en.wikipedia.org/wiki/Mandelbrot_set#Histogram_coloring
    [ ] Fully implement the Color Control Panel (Linear, Transform, etc...)
    [ ] Look into adding the ability to adjust the power of the Mandelbrot Set (https://en.wikipedia.org/wiki/File:Mandelbrot_Set_Animation_1280x720.gif)
    [ ] Add https://en.wikipedia.org/wiki/Tricorn_(mathematics)

repository: mboleary/fractals-canvas

gha_language: JavaScript

gha_license_id: MIT

repo_name: mboleary/fractals-canvas


text:
---
layout: default
---

# 1996-09-17 - Re: New Remailers?

## Header Data

From<EMAIL_ADDRESS>To<EMAIL_ADDRESS>(Doug)

Message Hash: 8d6846bfe276131f851f75b12088a2acef70a65e6cabac443104309df82f7556

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1996-09-17 03:03:18 UTC

Raw Date: Tue, 17 Sep 1996 11:03:18 +0800

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>Date: Tue, 17 Sep 1996 11:03:18 +0800
To<EMAIL_ADDRESS>(Doug)
Subject: Re: New Remailers?
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

At 10:53 AM 9/16/96 BST, you wrote:
>I recently secured an account with anon.penet and then a few days later got
>a post informing me that the servive was now terminated. Anybody out there
>know of any remailers where you dont have to have a Phd in computer science
>and a thorough working knowledge of PGP in order to operate?

Raph Levien's remailer list lives at
        http://www.cs.berkeley.edu/~raph/remailer-list.html
Most of the remailers on it are the one-way variety - you can send
mail to someone anonymously, but you don't get an address for
people to reply to you.  They're easy to use.

Some of them also support anonymous reply blocks,
which are a somewhat difficult-to-use feature - you basically PGP-encrypt
your return address (in the correct syntax), and tell anybody who wants
to reply to you to include the block at the beginning of their mail.

There have been some pseudonym servers besides anon.penet.fi,
which provide higher security, and are easier to use than anonymous
reply blocks, once you set them up (which generally involves creating
anonymous reply blocks :-)  Two of them have been spammed to death,
but the cyber remailer at<EMAIL_ADDRESS>is still up.
Send it a request for help to get information.  Raph has a new system
coming soon; see his remailer list for details.

Private Idaho is Joel McNamara's friendly user interface for
remailers and PGP.  http://www.eskimo.com/~joelm/pi_list.html .
Runs on MSWindows.  It made it _much_ easier to use the alpha nymserver
while that was still alive; don't know if the new version supports
cyber yet or not.

Remailer security depends on encryption - otherwise wiretappers
can watch mail going into the remailer and know where it's going.
So you'll need to learn to use PGP, but it's pretty straightforward,
and Private Idaho makes it more convenient.

The Mixmaster remailers provide higher security remailing,
also with no reply capability; you need to get special client software,
which I think isn't ported to Windows yet?

>Also, are there any remailers which will accept binary attachments?

There are three popular ways to do binary attachments -
1) MIME-encoding (uses MIME headers and maybe a 7-bit content transfer
encoding.)
2) UUENCODE (simple-minded header and 7-bit ASCII.)
3) Mail-handler-specific headers with binary stuff following

Uuencode is a no-brainer - just stick the uuencoded binary after
the remailer headers.  As far as I know, none of the remailers are
particularly MIME-aware, but they do glue headers together.
So you could probably start sticking MIME headers after the remailer
headers and try a few times to get it to work.

Mail-handler-specific behaviour is, of course, mail-handler-specific :-)
You can try it and see, and remember that the person at the other end
may not have the same kind of mail handler you do, so even if you sent
the mail directly instead of through a remailer, it might not work.
You may have trouble getting your mail client to do what you want
for sending the message (e.g. if you use Cc:Mail or MSMail.)

I looked at the code for my remailer, which is a modified Ghio2,
though I don't think I modified this part, and it'll trash binaries.
The problem is that, after processing headers, it shoves the rest
of the input stream into the output file by a loop of
        fgets()
        check for cutmarks
        fprintf()
which will trash anything that contains nulls, and may not do
the right thing for newlines either, though it won't bother high-bits.
I suppose it wouldn't be too hard to write a getchar/putchar loop
that checks for cutmarks while transferring data safely
(this would be easier if cutmark behaviour includes outputting the cutmark.)
However, the remailer uses the native mail program (e.g. sendmail)
to forward the mail, so if your sendmail trashes binaries,
or does annoying vestigial things like changing "From " to ">From "
at the beginnings of lines, it'll still lose.

#			Thanks;  Bill
# Bill Stewart, +1-415-442-2215<EMAIL_ADDRESS># <A HREF="http://idiom.com/~wcs">
# You can get PGP software outside the US at ftp.ox.ac.uk/pub/crypto

{% endraw %}
```

## Thread

+ Return to [September 1996](/archive/1996/09)

+ Return to "[stewarts@ix.netcom.com](/authors/stewarts_at_ix_netcom_com)"

+ 1996-09-17 (Tue, 17 Sep 1996 11:03:18 +0800) - Re: New Remailers? -<EMAIL_ADDRESS>


text:
# covid19-variants-worldwide-evolution
2021.08.19 == version 33
- Daily updated reports on COVID-19 variants from our world in Data.
- kaggle datasets download -d gpreda/covid19-variants.
- Source: https://www.kaggle.com/gpreda/covid19-variants

# Context
The data is about COVID-19 variants (see more details about this here).
Data is collected daily from Our World in Data GitHub repository for covid-19, merged and uploaded.

# Content
The data (COVID-19 Variants) contains the following information:

location- this is the country for which the variants information is provided;
date - date for the data entry;
variant - this is the variant corresponding to this data entry;
num_sequences - the number of sequences processed (for the country, variant and date);
perc_sequences - percentage of sequences from the total number of sequences (for the country, variant and date);
num_sequences_total - total number of sequences (for the country, variant and date);
Acknowledgements
I would like to specify that I am only making available Our World in Data collected data about COVID-19 variants to Kagglers. My contribution is very small, just daily collection, merge and upload of the updated version, as maintained by Our World in Data in their GitHub repository.

# Inspiration
Track COVID-19 variants in the World, answer instantly to your questions:

What variants are sequenced and in which country?
How the variants evolved and where?
Where the diversity of the variants is large and where only one variants are proliferating?
Combine this information with the vaccination and daily COVID cases datasets to follow the complex dynamic of virus spreading, morphing in variants, and the effect of vaccination on limiting the virus spread.

repository: dbpedia/healthcare-platform

branch_name: refs/heads/main

gha_language: Jupyter Notebook

repo_name: dbpedia/healthcare-platform


text:
---
title: Payloads
type: guide
order: 4
vue_version: 0.0.1
---

Payloads are data that users send the server. They can be included in a combination of the url path (e.g. `/foo/:fooID`), query parameters (e.g. `/foos?bar=baz`) and request body.

The payload that an endpoint can receive is first specified in the `./design.json` file:

```json
{
  "api": { ... },
  "services": [
    {
      "name": "foos",
      "path": "/foos",
      "descirption": "CRUD the foos",
      "actions": [
        {
          "name": "show",
          "description":  "Return foo by fooID",
          "method": "GET",
          "path": "/:fooID",
          "payload": "ShowFooPayload",
          "response": "Foo"
        },
        { ... }
      ]
    },
    { ... }
  ]
}
```

The payload must then be a named export of the `models` submodule.

```
my-first-api
│   ...
│
└src
    │
    │
    └...
    │
    │
    └models
        │   index.ts
        │
        │
        └foos
            │   index.ts
```

**./src/models/foos/index.ts**
```typescript
import { IsInt, Min } from 'class-validator';

export class Foo { ... }

type showFooPayloadProps = {
  fooID: string;
}

export class ShowFooPayload {
  constructor({ fooID }: showFooPayloadProps) {
    this.fooID = parseInt(fooID);
  }

  @IsInt()
  @Min(0)
  public fooID: number;
}

```

**./src/models/index.ts**
```typescript
// note: all of your models should be exported, here

export * from './foos';
```

design-first uses [class-validator](https://github.com/typestack/class-validator) for payload validation. class-validator has many validation options, including custom-defined functions. Any [validation errors](https://github.com/typestack/class-validator#validation-errors) will be returned back to the user with a [400 http status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400).

design-first requires that all payload classes have a constructor function that has one object as a parameter.

Further note that payload variables passed to the server in the url path or in the query parameters can only be passed as `string`'s. Any necessary type conversions will need to performed in the `constructor` function.

Payload validation is second in the request chain, after middleware, and before authentication.

repository: fossabot/design-first-docs

repo_name: fossabot/design-first-docs


text:
# CXAssetsPicker

## Installation

CXAssetsPicker is available through [CocoaPods](https://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
source 'https://github.com/ishaolin/CXSpecs.git'

pod 'CXAssetsPicker'
```

repository: ishaolin/CXAssetsPicker

repo_name: ishaolin/CXAssetsPicker


text:
---
layout: post
title: Middle holiday working summary
feature-img: "assets/img/portfolio/cabin.png"
img: "assets/img/p/036.jpg"
tags: [project 1, professional proficiency]
date: 2019-10-10
color: brown
---

In this really important middle holiday, I only pay attention on Project 1 without other three papaers. That was a slience time, it is good to considerating any problems and features. I have learnd some technich skills such as React Native, Firebase and some other Component which could imporves our project functionality. What I have done in the holiday. I list the all task below:

![alt text](https://github.com/aemooooon/app/blob/master/assets/img/p/047.png?raw=true "icon changing")

#### 11 Oct, 2019

* fixed running option unable to disable
* added dynamic displaying estimate distance and duration when user has taped marker
* adding watching position feature

#### 09 Oct, 2019

* fixed pause button not working on ios
* fixed the km units and keep two or three digits
* fixed real time speed and distance display
* figure out the routeing coordinates when user location changing

#### 02 Oct, 2019

* adding reset password by send email link function
* add update password function
* fixed upload image does not working properly on IOS
* fix access camera and camera roll (files) before ask users permissons
* finished editing user icon features
* add upload image function
* completed the profile update features

#### 01 Oct, 2019

* design new style for profile form
* customized the gender selection sub component

#### 30 Sep, 2019

* fix sign up form which take out of the back button

#### 29 Sep, 2019

* fit screen size to route size when user taped the marker

#### 28 Sep, 2019

* try to update waypoint under the componentDidUpdate method

#### 27 Sep, 2019

* draw the second polyline for real walking
* separate workout operation area to subcomponent

![alt text](https://github.com/aemooooon/app/blob/master/assets/img/p/051.png?raw=true "reset password by email")

repository: aemooooon/Project-Portfolio

gha_language: HTML

repo_name: aemooooon/Project-Portfolio


text:
## Road Traffic Death Rates Dataset Pre-processing
This file describes the data pre-processing that was done to [the Road Traffic Deaths dataset](http://apps.who.int/gho/data/node.wrapper.imr?x-id=198) for [display on Resource Watch](https://resourcewatch.org/data/explore/3b6f853a-622d-4fff-827c-901b5b4352b0).

The source provided the dataset as a csv file.

Below, we describe the steps used to reformat the table so that it is formatted correctly to upload to Carto.
1. Read in the data as a pandas dataframe and rename all the columns.
2. Split the 'estimated_number_of_road_traffic_deaths_data' column and stored the lower and upper bound of the estimates in two new columns.
3. Add a column for datetime with January 1, 2016 for every row.
4. Reorder the columns.
5. Remove all the spaces within numbers in the 'estimated_number_of_road_traffic_deaths_data' column.

Please see the [Python script](https://github.com/resource-watch/data-pre-processing/blob/master/cit_022_rw1_road_traffic_death_rates/cit_022_rw1_road_traffic_death_rates_processing.py) for more details on this processing.

You can view the processed Road Traffic Death Rates dataset [on Resource Watch](https://resourcewatch.org/data/explore/3b6f853a-622d-4fff-827c-901b5b4352b0).

You can also download the original dataset [directly through Resource Watch](https://wri-public-data.s3.amazonaws.com/resourcewatch/cit_022_rw1_road_traffic_death_rates.zip), or [from the source website](http://apps.who.int/gho/data/node.main.A997?lang=en).

###### Note: This dataset processing was done by [Taufiq Rashid](https://www.wri.org/profile/taufiq-rashid), and QC'd by [Amelia Snyder](https://www.wri.org/profile/amelia-snyder).

repository: resource-watch/data-pre-processing

gha_language: Python

repo_name: resource-watch/data-pre-processing


text:
---
tags: [linux, network]
author: qbbr
---

### configure kernel

edit `/etc/sysctl.conf`:

```bashnet.ipv4.ip_forward=1
net.ipv4.conf.all.mc_forwarding = 1
net.ipv4.conf.default.mc_forwarding = 1
net.ipv4.conf.lo.mc_forwarding = 1
net.ipv4.conf.eth0.mc_forwarding = 1
net.ipv4.conf.wlan0.mc_forwarding = 1
net.inet.ip.mforwarding=1
multicast_router=YES
```

### reboot os && enjoy!!


text:
## Heroku demo:
See [LiveDemo](https://open-representatives.herokuapp.com/graphql) here
___
## Current state:

Right now it does:
 * Download all open discussion reports from the Deutschen Bundestag
 * Parses all talks/comments and metadata
 * Puts (*almost*) everything into a DB
 * Starts a flask backend-server with gunicorn

## How to setup dev:
 * Rename the ``.env_example`` to ``.env``
 * Rename the ``api/db/cache/redis.conf.example`` to ``api/db/cache/redis.conf``
 * Change the pw in redis.conf to the one in your .env file [HowTo](https://stackink.com/how-to-set-password-for-redis-server/)
 * Run docker-compose up or use the [.dev-container](/.devcontainer)

___
## ToDo:
Things to do:
 * ✅ Make parsing more robust
 * ✅ Save it to a database
 * ✅ GraphQL API
 * ✅ Create a WebAPI
 * 🏃♂ Logging
 * 🏃♂ Cache
 * 🏃♂ Deployment
   * Heroku free dynamo sleeps after 30 min
   * PosgresDB is limited to 10.000 rows (current 250k)
 * 🏃♂ Demo Frontend
   * Under Development at [hegerdes/OpenRepresentatives-frontend](https://github.com/hegerdes/OpenRepresentatives-frontend)
 * ⏲ Add more open data
    * Scrape Bundestag
    * Twitter from politicians

repository: hegerdes/OpenRepresentatives-backend

repo_name: hegerdes/OpenRepresentatives-backend


text:
---
layout: "alicloud"
page_title: "Alicloud: alicloud_disks"
sidebar_current: "docs-alicloud-datasource-disks"
description: |-
    Provides a list of disks to the user.
---

# alicloud\_disks

This data source provides the disks of the current Alibaba Cloud user.

## Example Usage

```
data "alicloud_disks" "disks_ds" {
  name_regex = "sample_disk"
}

output "first_disk_id" {
  value = "${data.alicloud_disks.disks_ds.disks.0.id}"
}
```

## Argument Reference

The following arguments are supported:

* `ids` - (Optional) A list of disks IDs.
* `name_regex` - (Optional) A regex string to filter results by disk name.
* `type` - (Optional) Disk type. Possible values: `system` and `data`.
* `category` - (Optional) Disk category. Possible values: `cloud` (basic cloud disk), `cloud_efficiency` (ultra cloud disk), `cloud_ssd` (SSD cloud disk), `ephemeral_ssd` (ephemeral SSD) and `ephemeral` (ephemeral disk).
* `encrypted` - (Optional) Indicate whether the disk is encrypted or not. Possible values: `on` and `off`.
* `instance_id` - (Optional) Filter the results by the specified ECS instance ID.
* `tags` - (Optional) A map of tags assigned to the disks. It must be in the format:
  ```
  data "alicloud_disks" "disks_ds" {
    tags = {
      tagKey1 = "tagValue1",
      tagKey2 = "tagValue2"
    }
  }
  ```
* `output_file` - (Optional) File name where to save data source results (after running `terraform plan`).

## Attributes Reference

The following attributes are exported in addition to the arguments listed above:

* `disks` - A list of disks. Each element contains the following attributes:
  * `id` - ID of the disk.
  * `name` - Disk name.
  * `description` - Disk description.
  * `region_id` - Region ID the disk belongs to.
  * `availability_zone` - Availability zone of the disk.
  * `status` - Current status. Possible values: `In_use`, `Available`, `Attaching`, `Detaching`, `Creating` and `ReIniting`.
  * `type` - Disk type. Possible values: `system` and `data`.
  * `category` - Disk category. Possible values: `cloud` (basic cloud disk), `cloud_efficiency` (ultra cloud disk), `cloud_ssd` (SSD cloud disk), `ephemeral_ssd` (ephemeral SSD) and `ephemeral` (ephemeral disk).
  * `encrypted` - Indicate whether the disk is encrypted or not. Possible values: `on` and `off`.
  * `size` - Disk size in GiB.
  * `image_id` - ID of the image from which the disk is created. It is null unless the disk is created using an image.
  * `snapshot_id` - Snapshot used to create the disk. It is null if no snapshot is used to create the disk.
  * `instance_id` - ID of the related instance. It is `null` unless the `status` is `In_use`.
  * `creation_time` - Disk creation time.
  * `attached_time` - Disk attachment time.
  * `detached_time` - Disk detachment time.
  * `expiration_time` - Disk expiration time.
  * `tags` - A map of tags assigned to the disk.

repository: alibaba/terraform-provider

extension: markdown

gha_language: Go

repo_name: alibaba/terraform-provider


text:
# Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

```
A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗
B:     b1 → b2 → b3
```

begin to intersect at node c1.

**Notes:**

* If the two linked lists have no intersection at all, return null.
* The linked lists must retain their original structure after the function returns.
* You may assume there are no cycles anywhere in the entire linked structure.
* Your code should preferably run in O(n) time and use only O(1) memory.

**Solution:**
```java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
  public ListNode getIntersectionNode(ListNode l1, ListNode l2) {
    if (l1 == null || l2 == null) return null;

    // step 1. count the two lists
    int n1 = count(l1), n2 = count(l2);

    // step 2. move the longer one |n2 - n1| steps
    int n = Math.abs(n1 - n2);

    while (n-- > 0) {
      if (n1 > n2)
        l1 = l1.next;
      else
        l2 = l2.next;
    }

    // step 3. move together and find the meeting point
    while (l1 != l2) {
      l1 = l1.next;
      l2 = l2.next;
    }

    return l1;
  }

  int count(ListNode l) {
    if (l == null) return 0;
    return 1 + count(l.next);
  }
}
```

url: https://raw.githubusercontent.com/riktimmondal/solve-leetcode-problems/38075f20a7590ddb1565b21f589fc02c59edb15e/problems/Intersection of Two Linked Lists.md

repository: riktimmondal/solve-leetcode-problems

filename: Intersection of Two Linked Lists.md

repo_name: riktimmondal/solve-leetcode-problems


text:
---
website: https://github.com/egoist/loglive
---

# LogLive

## Add typescript support (2017-07-27)

### New

Many of you asked, so here it is. TypeScript support with all its strict types glory! As usual, just pick it from the language dropdown in the JavaScript panel.

### whatever

This is for testing random color for title

### how?

some `code`

```js
function foo() {
  console.log('hi')
}
```

## 0.2.0 (2015-06-14)

### Fix

- tons of fixes

### Breaking

- some breaking changes, ya know

## 0.1.0 (2015-05-24)

### Fix

- fix url
- fix user side probleam

### New

- allow user to add contact
- allow to remove account

repository: devpascoe/loglive

repo_name: devpascoe/loglive


text:
# corder

***

The corder ( correlation and order analyzor package ) was made, on July 17 2017, with the aim of analysis structures and its properties from the trajectory of the VASP's first-princiles molecular dynamics ( FPMD ) calculation.

The required files are follows:

| file | role |
|:-----|:-----|
| XDATCAR | trajectory of the VASP's FPMD calculation |
| param.in | parameters that user-controllable for analyze XDATCAR |

### _dependencies_

--

The corder performs with depends on these packages:

| file | role |
|:-----|:-----|
| includes | some auxiliary functions |
| linalg | linear algebra functions that overwritting its operators |
| [voro++](https://github.com/spatialfruitsalad/pomelo/tree/master/lib/voro%2B%2B) | package for calculate Voronoi diagram |
| [qhull](http://www.qhull.org) | package for create convex fulls by Qhull algorithm |

*Note that*, some lines were added into the voro++ source code for perform the corder and draw Voronoi diagrams which is formatted to the POV-Ray style.

### _installation_

--

Download and install:
```
git clone git@github.com:Cetus-K/corder.git
cd ./corder
./INSTALL.sh
```
*Note that*, the install prefix is set to current directory. If you specify the install location, change this line:
```
export PREFIX=/path/to/install/location
```

# Supporting methods

***

The corder supports several geometric algorithms as follows:

| function | calculates |
|:-----|:-----|
| `gofr` | Pair correlation function |
| `sofq` | Static structure factor |
| `dfc`  | Mean-squared displacement for diffusion coefficient, and averaged velocity |
| `lboo` | Local bond-orientational order parameter |
| `bacf` | Bond-angle correlation function |
| `pofqw` | Bond-orientational probability distribution |
| `bofree` | Bond-orientational ( Landau ) free energy coefficient |
| `csform` | Distrubution of cluster's sharing formations w. r. t. its sharing type |
| `povoro` | Make trajectory animtion of Voronoi cell |

### _For related to the atomic specie_

--

Each functions are represented by the total, partial and "specified"-partial component. For example, put a function , the each component are expressed as follows:

| symbol | component |
|:-----|:-----|
|  | total |
|  | partial by - |
|  | partial by -, as user defined;  |

Since this term, I abbreviate the symbol of each component.

### _Pair correlation function_

--

Correlations between each two-atoms-pair related to positions are directly calculated by

.

The  indicates radius between two atoms with unit of , and  means the number of other atoms at the distance  from the center atom.

### _Static structure factor_

--

The spectrums of the interference between neutrons in the structure are calculated by

,

This function is derived by integrate, equal to the Fourier transform of, the pair correlation function as liquid state. Where the  means the norm of the wave vector with unit of . The , and the average atomic density of the structure . The angular bracket indicates the time averaging related to the instantaneous variable .

### _Mean-squared displacement and averaged velocity_

--

The mean-squared displacement , defined by its each instantaneous location from  to , derives its diffusion coefficient  using the Einstein equation:

.

### _Local bond-orientational order parameter_

--

The ligand forms a geometric shape for an atom, which can be represented by the identical values  that is likes the spectrum as follows:

,

where,

.

The coefficients in the summation of  is the Wigner  symbols, and the  is the normal vector of the surface .
For robust calculating of the cluster symmetries, there is the method that takes summation with Voronoi facet area , and the facets , as a weighting parameter.
These values  and  are rotationally invariant so it give us the interpretation for the distinguish cluster symmetry in any coordinates and also perspectives.

### _Bond-angle correlation function_

--

The cluster symmetries are correlated to the other symmetries, and the sustainability directly reflects its order as the correlation length. Also, the length can statistically estimate that the clusters are connected by being tied in a row. The definition is follows:

,

where,

.

This angular bracket takes ensamble average, and swapping the order -summation derives follows by generalized addition theorem, this package actually evaluate it:

,

where  indicates the inner product between bonds which parallel with each normal vector. This returns the value of the -th order correlation related to angular .

### _Bond-orientational ( Landau ) free energy coefficient_

--

Structures have a "geometric" free energy caused by cluster symmetries, and bond-orientational order describes that characteristics as the order parameter of the Landau theory. This function calculates internal and primary external free energy:

where,

The full Landau free energy is constructed from two more additional terms:

The first and second of additional term are secondary external free energy and periodic external free energy. I assume that the first term is usually small value and second term is always zero due to the -point sampling during the FPMD calculation.

### _Distrubution of cluster's sharing formations_

--

Clusters are linked to each other in the system as various shape, and then there are some sharing part on the clusters. These sharing forms are categorized as follows:

| form | sharing part |
|:-----|:-----|
| isolated | nothing |
| corner sharing | a vertex |
| edge sharing | an edge |
| surface sharing | a surface |
| bicap sharing | some part of volume |

This function returns the distribution of these amount.

repository: cetusk/corder

repo_name: cetusk/corder


text:
---
title: Euclidean vs. Cosine Distance
date: 2017-03-25 18:27:10
read: 10
image: ./sources/pixel_art/cosine.png
---

*This post was written as a reply to a question asked in the
[Data Mining](https://catalogus.tilburguniversity.edu/osiris_student_tiuprd/OnderwijsCatalogusSelect.do?selectie=cursus&taal=en&collegejaar=2018&cursus=880022-M-6) course.*

> When to use the cosine similarity?

Let's compare two different measures of distance in a vector space, and why either has its function under different circumstances. Starting off with quite a straight-forward example, we have our vector space `X`, that contains instances with animals. They are measured by their `length`, and `weight`. They have also been labelled by their stage of aging (`young = 0`, `mid = 1`, `adult = 2`). Here's some random data:

```python
import numpy as np

X = np.array([[6.6, 6.2, 1],
              [9.7, 9.9, 2],
              [8.0, 8.3, 2],
              [6.3, 5.4, 1],
              [1.3, 2.7, 0],
              [2.3, 3.1, 0],
              [6.6, 6.0, 1],
              [6.5, 6.4, 1],
              [6.3, 5.8, 1],
              [9.5, 9.9, 2],
              [8.9, 8.9, 2],
              [8.7, 9.5, 2],
              [2.5, 3.8, 0],
              [2.0, 3.1, 0],
              [1.3, 1.3, 0]])
```

## Preparing the Data

We'll first put our data in a `DataFrame` table format, and assign the correct labels per column:

```python
import pandas as pd

df = pd.DataFrame(X, columns=['weight', 'length', 'label'])
df
```

> |     | weight | length |  label |
| --- | ------:| ------:| -------:|
| 0   | 6.6 | 6.2 | 1.0 |
| 1   | 9.7 | 9.9 | 2.0 |
| 2   | 8.0 | 8.3 | 2.0 |
| 3   | 6.3 | 5.4 | 1.0 |
| 4   | 1.3 | 2.7 | 0.0 |
| 5   | 2.3 | 3.1 | 0.0 |
| 6   | 6.6 | 6.0 | 1.0 |
| 7   | 6.5 | 6.4 | 1.0 |
| 8   | 6.3 | 5.8 | 1.0 |
| 9   | 9.5 | 9.9 | 2.0 |
| 10  | 8.9 | 8.9 | 2.0 |
| 11  | 8.7 | 9.5 | 2.0 |
| 12  | 2.5 | 3.8 | 0.0 |
| 13  | 2.0 | 3.1 | 0.0 |
| 14  | 1.3 | 1.3 | 0.0 |

Now the data can be plotted to visualize the three different groups. They are subsetted by their label, assigned a different colour and label, and by repeating this they form different layers in the scatter plot.

```python
%matplotlib inline

ax = df[df['label'] == 0].plot.scatter(x='weight', y='length', c='blue', label='young')
ax = df[df['label'] == 1].plot.scatter(x='weight', y='length', c='orange', label='mid', ax=ax)
ax = df[df['label'] == 2].plot.scatter(x='weight', y='length', c='red', label='adult', ax=ax)
ax
```

> ![png](https://raw.githubusercontent.com/cmry/cmry.github.io/master/sources/output_6_1.png)

Looking at the plot above, we can see that the three classes are pretty well distinguishable by these two features that we have. Say that we apply $k$-NN to our data that will learn to classify new instances based on their distance to our known instances (and their labels). The algorithm needs a distance metric to determine which of the known instances are closest to the new one. Let's try to choose between either euclidean or cosine for this example.

## Picking our Metric

Considering instance #0, #1, and #4 to be our known instances, we assume that we don't know the label of #14. Plotting this will look as follows:

```python
df2 = pd.DataFrame([df.iloc[0], df.iloc[1], df.iloc[4]], columns=['weight', 'length', 'label'])
df3 = pd.DataFrame([df.iloc[14]], columns=['weight', 'length', 'label'])

ax = df2[df2['label'] == 0].plot.scatter(x='weight', y='length', c='blue', label='young')
ax = df2[df2['label'] == 1].plot.scatter(x='weight', y='length', c='orange', label='mid', ax=ax)
ax = df2[df2['label'] == 2].plot.scatter(x='weight', y='length', c='red', label='adult', ax=ax)
ax = df3.plot.scatter(x='weight', y='length', c='gray', label='?', ax=ax)
ax
```

> ![png2](https://raw.githubusercontent.com/cmry/cmry.github.io/master/sources/output_8_1.png)

### Euclidean

Our euclidean distance function can be defined as follows:

$\sqrt{\sum^n_{i=1} (x_i - y_i)^2}$

Where $x$ and $y$ are two vectors. Or:

```python
def euclidean_distance(x, y):
    return np.sqrt(np.sum((x - y) ** 2))
```

Let's see this for all our vectors:

```python
x0 = X[0][:-1]
x1 = X[1][:-1]
x4 = X[4][:-1]
x14 = X[14][:-1]
print(" x0:", x0, "\n x1:", x1, "\n x4:", x4, "\nx14:", x14)
```

>
    x0:  [ 6.6  6.2]
    x1:  [ 9.7  9.9]
    x4:  [ 1.3  2.7]
    x14: [ 1.3  1.3]

Doing the calculations:

```python
print(" x14 and x0:", euclidean_distance(x14, x0), "\n",
      "x14 and x1:", euclidean_distance(x14, x1), "\n",
      "x14 and x4:", euclidean_distance(x14, x4))
```

>
    x14 and x0: 7.21803297305
    x14 and x1: 12.0216471417
    x14 and x4: 1.4

According to euclidean distance, instance #14 is closest to #4. Our 4th instance had the label:

```python
X[4]
```

>
    array([ 1.3,  2.7,  0. ])

`0 = young`, which is what we would visually also deem the correct label for this instance.

Now let's see what happens when we use Cosine similarity.

### Cosine

Our cosine similarity function can be defined as follows:

$\frac{x \bullet y}{ \sqrt{x \bullet x} \sqrt{y \bullet y}}$

Where $x$ and $y$ are two vectors. Or:

```python
def cosine_similarity(x, y):
    return np.dot(x, y) / (np.sqrt(np.dot(x, x)) * np.sqrt(np.dot(y, y)))
```

Let's see these calculations for all our vectors:

```python
print(" x14 and x0:", cosine_similarity(x14, x0), "\n",
      "x14 and x1:", cosine_similarity(x14, x1), "\n",
      "x14 and x4:", cosine_similarity(x14, x4))
```

>
    x14 and x0: 0.999512076087
    x14 and x1: 0.999947942424
    x14 and x4: 0.943858356366

According to cosine similarity, instance #14 is closest to #1. However, our 1st instance had the label:

```python
X[1]
```

>
    array([ 9.7,  9.9,  2. ])

`2 = adult`, which is definitely NOT what we would deem the correct label!

## So What Happened?

Consider the following picture:

![eucos](/sources/eucos.png)

This is a visual representation of euclidean distance ($d$) and cosine similarity ($\theta$). While cosine looks at the **angle** between vectors (thus not taking into regard their weight or magnitude), euclidean distance is similar to using a ruler to actually measure the distance. In our example the angle between `x14` and `x4` was larger than those of the other vectors, even though they were further away.

## When to Use Cosine?

Cosine similarity is generally used as a metric for measuring distance when the magnitude of the vectors does not matter. This happens for example when working with text data represented by word counts. We could assume that when a word (e.g. `science`) occurs more frequent in document 1 than it does in document 2, that document 1 is more related to the topic of `science`. However, it could also be the case that we are working with documents of uneven lengths (Wikipedia articles for example). Then, `science` probably occurred more in document 1 just because it was way longer than document 2. Cosine similarity corrects for this.

Text data is the most typical example for when to use this metric. However, you might also want to apply cosine similarity for other cases where some properties of the instances make so that the weights might be larger without meaning anything different. Sensor values that were captured in various lengths (in time) between instances could be such an example.

## How do Euclidean Distance and Cosine Similarity Relate?

Let's consider two of our vectors, their euclidean distance, as well as their cosine similarity.

```python
print("vectors \t", x0, x1, "\n"
      "euclidean \t", euclidean_distance(x0, x1), "\n"
      "cosine \t\t", cosine_similarity(x0, x1))
```
>
    vectors      [ 6.6  6.2] [ 9.7  9.9]
    euclidean    4.82700735446
    cosine       0.99914133854

Cosine similarity takes a unit length vector to calculate dot products. However, what happens if we do the same for the vectors we're calculating the euclidian distance for (i.e. normalize them)? For this, we can for example use the $L_1$ norm:

$\sum_i x_i$

Or the $L_2$ norm:

$\sqrt{\sum_i  x_i^2 }$

In functions:

```python
def l1_normalize(v):
    norm = np.sum(v)
    return v / norm

def l2_normalize(v):
    norm = np.sqrt(np.sum(np.square(v)))
    return v / norm
```

We divide the values of our vector by these norms to get a normalized vector.

Applying the $L_1$ norm to our vectors will make them sum up to 1 respectively, as such:

```python
x0_n = l1_normalize(x0)
x1_n = l1_normalize(x1)
print(x0_n, x1_n)
```

>
    [ 0.515625  0.484375] [ 0.49489796  0.50510204]

Let's compare the result we had before against these normalized vectors:

```python
print("vectors \t", x0_n, x1_n, "\n"
      "euclidean \t", euclidean_distance(x0_n, x1_n), "\n"
      "cosine \t\t", cosine_similarity(x0_n, x1_n))
```

>
    vectors      [ 0.515625  0.484375] [ 0.49489796  0.50510204]
    euclidean    0.0293124622303
    cosine       0.99914133854

As we can see, before, the distance was pretty big, but the cosine similarity very high. Now that we normalized our vectors, it turns out that the distance is *now* very small. The same pattern occurs when we compare it against vector 4. Unnormalized:

```python
print("vectors \t", x0, x4, "\n"
      "euclidean \t", euclidean_distance(x0, x4), "\n"
      "cosine \t\t", cosine_similarity(x0, x4))
```

>
    vectors      [ 6.6  6.2] [ 1.3  2.7]
    euclidean    6.35137780328
    cosine       0.933079411589

Normalized:

```python
x4_n = l1_norm(x4)

print("vectors \t", x0_n, x4_n, "\n"
      "euclidean \t", euclidean_distance(x0_n, x4_n), "\n"
      "cosine \t\t", cosine_similarity(x0_n, x4_n))
```

>
    vectors      [ 0.515625  0.484375] [ 0.325  0.675]
    euclidean    0.269584460327
    cosine       0.933079411589

Notice that because the cosine similarity is a bit lower between `x0` and `x4` than it was for `x0` and `x1`, the euclidean distance is now also a bit larger. To take this point home, let's construct a vector that is almost evenly distant in our euclidean space, but where the cosine similarity is much lower (because the angle is larger):

```python
x00 = np.array([0.1, 6])

print("vectors \t", x0, x00, "\n"
      "euclidean \t", euclidean_distance(x0, x00), "\n"
      "cosine \t\t", cosine_similarity(x0, x00))
```

>
    vectors      [ 6.6  6.2] [ 0.1  6. ]
    euclidean    6.50307619516
    cosine       0.696726168728

If we normalize this, we should see the same behaviour from our euclidean distance (i.e. it should be larger than for `x0` and `x4`). As follows:

```python
x00_n = l1_normalize(x00)

print("vectors \t", x0_n, x00_n, "\n"
      "euclidean \t", euclidean_distance(x0_n, x00_n), "\n"
      "cosine \t\t", cosine_similarity(x0_n, x00_n))
```

>
    vectors      [ 0.515625  0.484375] [ 0.01639344  0.98360656]
    euclidean    0.706020039207
    cosine       0.696726168728

## Cosine in Action

So when is cosine handy? Let's consider four articles from Wikipedia. We use the Wikipedia API to extract them, after which we can access their text with the `.content` method.

```python
import wikipedia

q1 = wikipedia.page('Machine Learning')
q2 = wikipedia.page('Artifical Intelligence')
q3 = wikipedia.page('Soccer')
q4 = wikipedia.page('Tennis')
```

We represent these by their frequency vectors. Each instance is a document, and each word will be a feature. The feature values will then represent how many times a word occurs in a certain document. So the feature `ball`, will probably be 0 for both machine learning and AI, but definitely not 0 for soccer and tennis. For this example I'll use `sklearn`:

```python
from sklearn.feature_extraction.text import CountVectorizer

cv = CountVectorizer()
X = np.array(cv.fit_transform([q1.content, q2.content, q3.content, q4.content]).todense())
```

The `CountVectorizer` by default splits up the text into words using white spaces. We can do the same to see how many words are in each article. Like this:

```python
print("ML \t", len(q1.content.split()), "\n"
      "AI \t", len(q2.content.split()), "\n"
      "soccer \t", len(q3.content.split()), "\n"
      "tennis \t", len(q4.content.split()))
```

>
    ML        3694
    AI        10844
    soccer    6134
    tennis    9715

AI is a much larger article than Machine Learning (ML). This would mean that if we do not normalize our vectors, AI will be much further away from ML just because it has many more words. ML will probably be closer to an article with less words. Let's try it out:

```python
print("ML - AI \t", euclidean_distance(X[0], X[1]), "\n"
      "ML - soccer \t", euclidean_distance(X[0], X[2]), "\n"
      "ML - tennis \t", euclidean_distance(X[0], X[3]))
```

>
    ML - AI<PHONE_NUMBER>16
    ML - soccer<PHONE_NUMBER>17
    ML - tennis<PHONE_NUMBER>38

Here we can see pretty clearly that our prior assumptions have been confirmed. ML seems to be closest to soccer, which doesn't make a lot of sense intuitively. So, what happens if we look at cosine similairty (thus normalising our vectors)?

```python
print("ML - AI \t", cosine_similarity(X[0], X[1]), "\n"
      "ML - soccer \t", cosine_similarity(X[0], X[2]), "\n"
      "ML - tennis \t", cosine_similarity(X[0], X[3]))
```

>
    ML - AI        0.886729067818
    ML - soccer    0.785735757699
    ML - tennis    0.797450973312

ML is closer to AI! Granted, it still seems pretty close to soccer an tennis judging from these scores, but please note that word frequency is not that great of a representation for texts with such rich content.

### Categorize a Tweet

Now, just for fun, let's see how this plays out for the following tweet by OpenAI:

```python
ml_tweet = "New research release: overcoming many of Reinforcement Learning's limitations with Evolution Strategies."
x = np.array(cv.transform([ml_tweet]).todense())[0]
```

Again we represent this tweet as a word vector, and we try to measure the distance between the tweet and our four wikipedia documents:

```python
print("tweet - ML \t", euclidean_distance(x[0], X[0]), "\n"
      "tweet - AI \t", euclidean_distance(x[0], X[1]), "\n"
      "tweet - soccer \t", euclidean_distance(x[0], X[2]), "\n"
      "tweet - tennis \t", euclidean_distance(x[0], X[3]))
```

>
    tweet - ML<PHONE_NUMBER>15
    tweet - AI<PHONE_NUMBER>69
    tweet - soccer<PHONE_NUMBER>21
    tweet - tennis    1051.61589946

Well, that worked out pretty well at first glance, it's closest to ML. However, see how it's also closer to soccer than AI? There's so many dimensions that come into play here that it's hard to say why this is the case. However, soccer being our second smallest document might have something to do with it. Now we'll do the same for cosine:

```python
print("tweet - ML \t", cosine_similarity(x, X[0]), "\n"
      "tweet - AI \t", cosine_similarity(x, X[1]), "\n"
      "tweet - soccer \t", cosine_similarity(x, X[2]), "\n"
      "tweet - tennis \t", cosine_similarity(x, X[3]))
```

>
    tweet - ML        0.299293065515
    tweet - AI        0.215356854916
    tweet - soccer    0.135323358719
    tweet - tennis    0.129773245953

There we go! This seems definitely more in line with our intuitions. So, remember how euclidean distance in this example seemed to slightly relate to the length of the document? Let's try the same for a soccer tweet, by Manchester United:

```python
so_tweet = "#LegendsDownUnder The Reds are out for the warm up at the @nibStadium. Not long now until kick-off in Perth."
x2 = np.array(cv.transform([so_tweet]).todense())[0]
```

Same trick, different tweet:

```python
print("tweet - ML \t", euclidean_distance(x2, X[0]), "\n"
      "tweet - AI \t", euclidean_distance(x2, X[1]), "\n"
      "tweet - soccer \t", euclidean_distance(x2, X[2]), "\n"
      "tweet - tennis \t", euclidean_distance(x2, X[3]))
```

>
    tweet - ML<PHONE_NUMBER>65
    tweet - AI<PHONE_NUMBER>55
    tweet - soccer<PHONE_NUMBER>46
    tweet - tennis    1048.82124311

See how awfully similar these distances are to that of our previous tweet, even though there's very little overlap? Now let's try the same with cosine similarity:

```python
print("tweet - ML \t", cosine_similarity(x2, X[0]), "\n"
      "tweet - AI \t", cosine_similarity(x2, X[1]), "\n"
      "tweet - soccer \t", cosine_similarity(x2, X[2]), "\n"
      "tweet - tennis \t", cosine_similarity(x2, X[3]))
```

>
    tweet - ML        0.437509648194
    tweet - AI        0.464447992614
    tweet - soccer    0.611865382744
    tweet - tennis    0.597261139457

Nailed it!

Hopefully this, by example, proves why for text data normalizing your vectors can make all the difference!


text:
# Grav Sitemap Plugin

`Sitemap-Multilang` is a [Grav](http://github.com/getgrav/grav) Plugin that generates a [map of your pages](http://en.wikipedia.org/wiki/Site_map) in `XML` format that is easily understandable and indexable by Search engines.

# Installation

Installing the Sitemap plugin can be done in one of two ways. Our GPM (Grav Package Manager) installation method enables you to quickly and easily install the plugin with a simple terminal command, while the manual method enables you to do so via a zip file.

## Manual Installation

To install this plugin, just download the zip version of this repository and unzip it under `/your/site/grav/user/plugins`. Then, rename the folder to `sitemap-multilang`. You can find these files either on [GitHub](https://github.com/mazaka/grav-plugin-sitemap-multilang).

You should now have all the plugin files under

    /your/site/grav/user/plugins/sitemap-multilang

>> NOTE: This plugin is a modular component for Grav which requires [Grav](http://github.com/getgrav/grav), the [Error](https://github.com/getgrav/grav-plugin-error) and [Problems](https://github.com/getgrav/grav-plugin-problems) plugins, and a theme to be installed in order to operate.

# Usage

The `sitemap-multilang` plugin works out of the box. You can just go directly to `http://yoursite.com/sitemap` and you will see the generated `XML`.

# Config Defaults

```
enabled: true
route: '/sitemap'
ignores:
  - /blog/blog-post-to-ignore
  - /ignore-this-route
```

You can ignore your own pages by providing a list of routes to ignore.

## Only allow access to the .xml file

If you want your sitemap to only be accessible via `sitemap.xml` for example, set the route to `/sitemap` and add this to your `.htaccess` file:

`Redirect 301 /sitemap /sitemap.xml`

repository: mazaka/grav-plugin-sitemap-multilang

repo_name: mazaka/grav-plugin-sitemap-multilang


text:
Linux Shortcuts
===============

Custom app shortcuts for Linux -- by, [Chris Kankiewicz](https://www.ChrisKankiewicz.com)

Introduction
------------

Run `install.py` to copy all shortcuts to `~/.local/share/applications/`

Adding a Shortcut
-----------------

You may add a shortcut by creating a new `.desktop` file in the `shortcuts`
folder. Use the following template for your shortcut.

    [Desktop Entry]
    Version=1.0
    Terminal=false
    Type=Application
    Name={{ APPLICATION_NAME }}
    Exec=google-chrome --app={{ APPLICATION_URL }}
    Icon={{ ICON_NAME }}
    StartupWMClass={{ STARTUP_WM_CLASS }}

When adding a new shortcut, to get the `StartupWMClass` of the window run
`xprop WM_CLASS` from a terminal then click on the window.

Troubleshooting
---------------

Please report bugs to the [GitHub Issue Tracker](https://github.com/PHLAK/chrome-apps/issues).

Copyright
---------

This project is licensed under the [MIT License](https://github.com/PHLAK/chrome-apps/blob/master/LICENSE).

repository: PHLAK/linux-shortcuts

repo_name: PHLAK/linux-shortcuts


text:
---
id: version-stable-webstorm
title: WebStorm Setup
original_id: webstorm
---

## Using Prettier in WebStorm

Use the `Reformat with Prettier` action (`Opt-Shift-Cmd-P` on macOS or `Alt-Shift-Ctrl-P` on Windows and Linux) to format the selected code, a file, or a whole directory.

To run Prettier on save in WebStorm 2020.1 or above, open _Preferences | Languages & Frameworks | JavaScript | Prettier_ and enable the option `Run on save for files`.

By default, only JavaScript and TypeScript files will be formatted automatically. You can further configure what files will be updated using the [glob pattern](https://github.com/isaacs/node-glob#glob-primer).

Don’t forget to install Prettier first.

To use Prettier in IntelliJ IDEA, PhpStorm, PyCharm, and other JetBrains IDEs, please install this [plugin](https://plugins.jetbrains.com/plugin/10456-prettier).

To run Prettier on save in older IDE versions, you can set up a file watcher following the instructions below.

## Running Prettier on save using File Watcher

To automatically format your files using Prettier on save in WebStorm 2019.\* or earlier, you can use a [File Watcher](https://plugins.jetbrains.com/plugin/7177-file-watchers).

Go to _Preferences | Tools | File Watchers_ and click **+** to add a new watcher.

In Webstorm 2018.2, select Prettier from the list, review the configuration, add any additional arguments if needed, and click OK.

In older IDE versions, select Custom and do the following configuration:

- **Name**: _Prettier_ or any other name
- **File Type**: _JavaScript_ (or _Any_ if you want to run Prettier on all files)
- **Scope**: _Project Files_
- **Program**: full path to `.bin/prettier` or `.bin\prettier.cmd` in the project’s `node_module` folder. Or, if Prettier is installed globally, select `prettier` on macOS and Linux or `C:\Users\user_name\AppData\Roaming\npm\prettier.cmd` on Windows (or whatever `npm prefix -g` returns).
- **Arguments**: `--write [other options] $FilePath$`
- **Output paths to refresh**: `$FilePathRelativeToProjectRoot$`
- **Working directory**: `$ProjectFileDir$`
- **Environment variables**: add `COMPILE_PARTIAL=true` if you want to run Prettier on partials (like `_component.scss`)
- **Auto-save edited files to trigger the watcher**: Uncheck to reformat on Save only.

## Using Prettier with ESLint

If you are using ESLint with [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier), use the `Fix ESLint Problems` action to reformat the current file – find it using _Find Action_ (`Cmd/Ctrl-Shift-A`) or [add a keyboard shortcut](https://www.jetbrains.com/help/webstorm/configuring-keyboard-shortcuts.html) to it in _Preferences | Keymap_ and then use it.

Make sure that the ESLint integration is enabled in _Preferences | Languages & Frameworks | JavaScript | Code Quality Tools | ESLint_.

## Using Prettier as External Tool

Go to _Preferences | Tools | External Tools_ and click **+** to add a new tool. Let’s name it **Prettier**.

- **Program**: `prettier` on macOS and Linux or `C:\Users\user_name\AppData\Roaming\npm\prettier.cmd` on Windows (or whatever `npm prefix -g` returns), if Prettier is installed globally
- **Parameters**: `--write [other options] $FilePath$`
- **Working directory**: `$ProjectFileDir$`

> If Prettier is installed locally in your project, replace the path in **Program** with `$ProjectFileDir$/node_modules/.bin/prettier` on macOS and Linux or `$ProjectFileDir$\node_modules\.bin\prettier.cmd` on Windows.

![Example](/docs/assets/webstorm/external-tool-prettier.png)

Press `Cmd/Ctrl-Shift-A` (_Find Action_), search for _Prettier_, and then hit `Enter`.

It will run Prettier for the current file.

You can [add a keyboard shortcut](https://www.jetbrains.com/help/webstorm/configuring-keyboard-shortcuts.html) to run this External tool configuration in _Preferences | Keymap_.

repository: brodybits/prettierx

branch_name: refs/heads/dev

repo_name: brodybits/prettierx


text:
> EARLY DRAFT: This section still needs a lot more work before it is ready. Most things here will probably change before it reaches a publishable state.

# Transparency

_The purpose of this document is to define our transparency policy. Partners interested in how we manage transparency at Learners Guild will find answers here._

## Building Trust with Truth

Communication and negotiation among groups of people is difficult, but the more honest we can be with each other, the easier it will be for us to trust one another and work together as a team. Openness and honesty will be critical to our success, which is why this is one of our key values, and why it’s a mantra we repeat in many conversations.

The best way for you to make a decision about what’s good for Learners Guild is to have all of the information about what’s going on at Learners Guild. The same is true for everyone else you work with, so it’s important that we’re all up to date about what’s happening, even with the areas of Learners Guild that we’re not actively involved with.

Transparency may seem like a passive process, like "don’t hide anything," but it’s actually a big challenge to keep everyone up to date and on the same page about stuff they’re not working on on a daily basis, even for a company the size of Learners Guild. These are some of the policies we use to make information more accessible, but our work is ongoing.

## Transparent, Private, and Open

Any information at Learners Guild falls falls into one, and only one, of three categories: open, private, and transparent. These terms are defined succinctly in the [Glossary][glossary]; read those definitions first if you are unsure of their specific, contextual meaning.

At Learners Guild we strive to make the default state of all information transparent, i.e. visible to all partners. When deciding how to share information, all partners should choose to make it transparent _unless they have a really good reason not to_.

**Think of Learners Guild as a fortress with stone exterior walls and glass interior walls.** Internally, we strive to build openness, trust, and a sense of safety for all partners. We protect our vulnerability and create a safe space for learning and growth by being diligent, intentional, and extremely careful about what we expose to the outside world.

Use the External Transparency Matrix below to determine whether a particular piece of information or intellectual property can be shared. Also, some guidance is given under the [Private Information](#private-information) and [Open Information](#open-information) policies below to help partners decide when and why to choose one transparency level over another.

## External Transparency Matrix

Some information needs to be shared with certain members of the outside world, but we need to be cautious in what and how this information is shared.

Use this matrix to answer questions like:

- What is the category of this information?
- With whom do I wish to share it?
- Will sharing this information help or damage our purpose?

| Open to All        | Share with Trusted People\*          | NDA Required      | Never Share               |
|--------------------|--------------------------------------|-------------------|---------------------------|
| Our guide          | Who funds us                         | Amount of funding | Partner salaries & comp   |
| That we are funded | Who is on our board                  | Financial model   | No. of outstanding shares |
| Team profiles      | Launch strategy (timing, location)   |                   | Valuation                 |
|                    | Pitch deck                           |                   |                           |
|                    | Business model                       |                   |                           |
|                    | Curriculum overview                  |                   |                           |

\* for potential hires, affiliate partners, etc. Optionally, use a "[FrieNDA](http://randsinrepose.com/archives/friendda/)".

## Transparent Information

### When and why information should be private

As mentioned above, the default state of information at Learners Guild is transparent. We prioritize transparency for practical reasons (ease of doing our work) as well as values-driven reasons (closing the gaps).

The following are examples of the kinds of information which is transparent, but by no means an exhaustive list.

### Slack Channels

Almost all Slack conversation should happen in public Slack channels where the rest of the team can see it. You may not subscribe to or pay attention to every channel, but conversations that happen in public channels are searchable and readable by the whole team, so when someone wants to know how we decided on some course of action, Slack gives them a place to look back at the conversation.

Not every ping or question needs to happen publicly, but when in question, you should err on the side of posting publicly. Currently about 90% of our conversations happen in public channels, which is a number we hope will keep growing. Think twice before starting or using a private channel. Is it absolutely necessary? Is it essential that nobody else view this conversation?

### Calendars

Work calendars should be shared to make scheduling meetings really easy and also to let the rest of the team see where we’re spending our time. Personal calendars often have sensitive information, and should be kept separate. Work calendars are documentation of how we’re budgeting our hours and are useful for the rest of the team.

### Finances and Salaries

Learners Guild financial information (profit & loss statements, operating budget, etc.) are transparent. So are all the salary and equity ownership data for every partner and external consultant.

### Statistics and Metrics

When we measure something, it should be visible to everyone on the team. Our stats will be great sometimes and disappointing others, but when we hide or silo the hard stats, fewer people can help fix them. We’ll try to keep the most critical stats posted in the office, but any data that we’re collecting should be open to everyone.

## Private Information

### When and why information should be private

Choose to make information private if:

- making it transparent could damage the purpose of the organization
- you do not own the information and do not have the owner's explicit permission to make it transparent
- the information directly concerns another partner and you do not have their explicit permission to make it transparent

The following are examples of the kinds of information which would likely be kept private.

### Specific Personal Data

Highly personal information about a partner, including but not limited to the characteristics listed under our [Equal Opportunity Employment][equal-opportunity-employment] policy, is considered private unless the concerned partner explicitly declares otherwise.

For example, a partner's religious affiliation or sexual orientation are considered private to them and to those with whom they choose to share that information. On no occasion should that information be made transparent or shared without their express permission.

### Partner-to-Partner Feedback

Feedback given from one partner to another is private unless the partner receiving the feedback wishes to share.

Giving and receiving feedback is an integral part of working at Learners Guild. We acknowledge that in order for us all to continuously grow, we need to be able to give and receive feedback on things that push the edges of our comfort zones. Feedback is vulnerable and thus should be respectful and private.

Partners are, of course, encouraged to share as much of their _received_ feedback as they wish, whether to seek support or to stay in integrity.

## Open Information

### When and why information should be open

As we grow, Learners Guild will likely open up more and more information to the outside world.

For the time being, however, we are more or less in "stealth" mode: we are invisible, and we share only select information with a select few people not-partners.

Use the [External Transparency Matrix](#External-Transparency-Matrix) above to determine what information can be shared with whom.

[glossary]: ../GLOSSARY.md
[equal-opportunity-employment]: ../Employment-Policies/Equal-Opportunity-Employment.md

repository: courtlandalves/guide

gha_language: CSS

repo_name: courtlandalves/guide


text:
# Stewed Chickpeas and Cauliflower

This is what happens when you just throw some food in a pot and cook it a long
time.  By varying the ingredients and spices and when you add ingredients, many
flavor variants could be created.  This was a fun experiment that was received
well by my wife.  Even my 5-year old tried it.

Ingredients:

- 2 T olive oil
- 1 diced onion
- 4 diced celery stalks
- 2 minced garlic cloves
- 1 15oz can diced tomatoes
- 1/2 6oz can tomato paste
- 1/2 tsp salt
- 1/2 tsp black peppercorns
- 1/2 tsp dried rosemary
- 2 bay leaves
- 2 C soaked chickpeas (about 1 C dried?)
- 2 C broth (e.g. chicken broth)
- 1 small head of cauliflower, diced

Directions:

- Heat olive oil in large pan or pot that has a cover
- Add onions and sauté on medium heat until clear
- Add celery, garlic, tomatoes, tomato paste, chickpeas, and spices.
- Simmer everything on low heat for an hour
- Add cauliflower and simmer for another hour, until chickpeas are soft and
  everything else is mushy.

repository: todddeluca/recipes

repo_name: todddeluca/recipes


text:
# money-transfer-with-play-akka-macwire
Small pet project for RESTful money transfer app built with Play, Akka and MacWire.

## App details
API is built with Play Framework
Domain logic is built with Akka actors framework (Bank and BankAccount)
Akka and Play are linked together with MacWire DI framework.

### API

next API is supported:
```
 /account                           { "accountName": "aa" }                         	Content-Type: application/json
 /account/:id/deposit               { "amount":  200 }                              	Content-Type: application/json
 /account/:id/withdraw              { "amount":  10 }                               	Content-Type: application/json
 /account/:id/transfer-money        { "destinationAccountId": 2, "amount":  100 }   	Content-Type: application/json

GET
 /account/:id
```

#### Error Handling
Proper error handling is not implemented, e.g. for scenarios when account does not exist but operation for specific account id is requested.

### Distribution
In order to build executables use: `sbt dist` - it will generate platform specific archive with application content.
E.g. for windows:

```
├───bin
	└───money-transfer-with-play-akka-macwire.bat
	└─── ...
├───conf
	└─── ...
├───lib
	└─── ...
└───share
    └───doc
        └───...
```

Running money-transfer-with-play-akka-macwire.bat will launch webserver on port 9000.

### Testing
There are couple unit tests to verify Bank and Bank Account Actors work and integration tests to verify overall app with API works.

Use `sbt test` to run tests


text:
# Dcolscan coefficient calculator

Author: **Adam Hunyadi**

E-mail me<EMAIL_ADDRESS>
This package is designed to calculate coefficients for dynamic inefficiency simulations for the CMS Pixel-detector of CERN.


text:
+++
title = "Analytics Political Science"
categories = ["ai"]
tags = ["analytics", "risk-management", "assistant"]
weight = 42
+++

# Analytics Political Science

---

## Mission

Identify potential political risks in your business beforehand for a secure future

---

## Problem

- Political risks are increasingly becoming hard to foresee
- No solution geared towards specifically on political risks
- Such closed information is hard to access easily on the internet

---

## Solution

- One-stop platform for identifying political risks to protect and alert businesses
- AI powered advice based on risk factors based on closed information
- Lead to a secure connective connection between individuals for prevention

repository: shunkakinoki/pitch

repo_name: shunkakinoki/pitch


text:
### 7. Reverse Integer

---

**Easy**

Given a 32-bit signed integer, reverse digits of an integer.

**Note:**
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

**Example 1:**

```javascript
Input: x = 123;
Output: 321;
```

**Example 2:**

```javascript
Input: x = -123;
Output: -321;
```

**Example 3:**

```javascript
Input: x = 120;
Output: 21;
```

**Example 4:**

```javascript
Input: x = 0;
Output: 0;
```

**Constraints:**

- -231 <= x <= 231 - 1

### Result

---

Runtime: **36 ms**, faster than **35.03%** of Python3 online submissions for **Reverse Integer.**

Memory Usage: **14.2 MB**, less than **67.57%** of Python3 online submissions for **Reverse Integer.**

repository: nickdehart/Leetcode

path: /7. Reverse Integer/README.md

repo_name: nickdehart/Leetcode


text:
# Online/ Offline Budget Tracker

## Description
The user is able to keep track of there money but inputting expenses and when they get paid.

## Table of Contents
1. [Usage](#Usage)
2. [License](#License)
3. [Screen Grabs](#Screen-Grabs)
4. [Links](#Links)

## Usage
By adding a description and an amount the budget tracker will display a graph of your budget and where you spend the most money. You can also add expenses when offline so you are able to access your budget in areas that don't have internet.

## Licence
MIT [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Screen Grabs
![Week19-01](https://user-images.githubusercontent.com/83004232/137897098-348c8c4e-09cc-4cdc-8856-8e8043dc0e01.png)

![week19-02](https://user-images.githubusercontent.com/83004232/137897167-d8be8729-4bab-4624-85a4-95927957d871.png)

![week19-03](https://user-images.githubusercontent.com/83004232/137897221-6183374f-74af-4e91-be9b-50ddbbf01ffa.png)

## Links
Git-Hub:   https://github.com/Adeamer/Online-Offline-Budget-Trackers

Heroku:   https://week19-budget-tracker.herokuapp.com/

Video Demo: https://watch.screencastify.com/v/tXKZneDDhmHYORUlTawg

repository: Adeamer/Online-Offline-Budget-Trackers

repo_name: Adeamer/Online-Offline-Budget-Trackers


text:
# sokal-generator
Postmodern fill text generation system written for Lab 1 in CMSC 23311 at UChicago

## Building
Simply run the command:

```cabal build```

while in the project directory. Note that you may have to install some cabal
packages.

This cabal package produces two executables, `suck` and `spew`.

## suck
The `suck` program takes a list of urls, extracts the text from them, and builds a
model for later text generation.  Then, it generates the requested amount of text. `spew` must
be run in a directory with a pre-existing `sokal.model` file.

```usage: spew [word count (int)]```

repository: Ked-Ki/sokal-generator

repo_name: Ked-Ki/sokal-generator


text:
# GraphQL Rate Limit - User Context

This example illustrates isolating operations between users. Commonly used in a multi user environment.

## Overview

Specify a `keyGenerator` function which uses contextual information from the resolver's `context`.

In this example, a user is identified by the IP address of the request.

## Setup

#### Step 1: Install requirements

```bash
yarn install
```

## Run

#### Step 1: Start server

```bash
node index.js
```

#### Step 2: Open GraphiQL

Navigate to [`http://localhost:4000/graphql`](http://localhost:4000/graphql) in a browser.

#### Step 3: Execute GraphQL operations

Server is configured to allow each root field to be queried once every 15 seconds. Sample query:

```graphql
{
  quote
  books {
    title
    author
  }
}
```

repository: ravangen/graphql-rate-limit

gha_language: TypeScript

repo_name: ravangen/graphql-rate-limit


text:
# test-report

Creates reports over test results in connection with `quarantined_tests.json` and `dont_run_tests.json` file types.

## test-report execution

test-report execution creates a report in html format to show which tests have been run on what lane

It constructs a matrix of test lanes by test names and shows for each test:
* on which lane(s) the test actually was run
* on which lane(s) the test is not supported (taking the information from the 'dont_run_tests.json' configured for the lane
  (see the configurations available)

Tests that are not run on any lane are especially marked in order to emphasize that fact.

Accompanying the html file a json data file is emitted for further consumption.

**Note**: generating a default report can take a while and will emit a report of enormous size, therefore you can strip down
the output by selecting a configuration that reports over a subset of the data using --config. You also can create your
own configuration file to adjust the report output to your requirements.

```
Usage:
test-report execution [flags]

Flags:
--config string         one of {'default', 'compute', 'storage', 'network'}, chooses one of the default configurations, if set overrides default-config.yaml (default "default")
--config-file string    yaml file that contains job names associated with dont_run_tests.json and the job name pattern, if set overrides default-config.yaml
--dry-run               only check which jobs would be considered, do not create an actual report
--endpoint string       jenkins base url (default "https://main-jenkins-csb-cnvqe.apps.ocp-c1.prod.psi.redhat.com/")
-h, --help                  help for execution
--outputFile string     Path to output file, if not given, a temporary file will be used
--overwrite             overwrite output file (default true)
--start-from duration   time period for report (default 336h0m0s)

Global Flags:
--log-level uint32   level for logging (default 4)
```

### Provided default configurations

There are four default configurations, where `default` considers the lanes for all sigs, while `compute`, `network`, `ssp` and `storage` only consider those tests and lanes that are relevant to each respective sig. For details on the configuration of each use case, see the config files in this folder.

If you want to provide your own configuration, you can override the default configs using `--config-file` flag.

## test-report dequarantine report

`test-report dequarantine report` generates a report of the test status for each entry in the `quarantined_tests.json`

The output format is an extended version of the format from `quarantined_tests.json`, added to each record is a
dictionary of test results per test that matches 'Id', ordered by execution time descending.

```
Usage:
  test-report dequarantine report [flags]

Flags:
      --dry-run                      whether to only check what jobs are being considered and then exit (default true)
      --endpoint string              jenkins base url (default "https://main-jenkins-csb-cnvqe.apps.ocp-c1.prod.psi.redhat.com/")
  -h, --help                         help for report
      --job-name-pattern string      the pattern to which all jobs have to match
      --max-conns-per-host int       the maximum number of connections that are going to be made (default 3)
      --output-file string           Path to output file, if not given, a temporary file will be used
      --quarantine-file-url string   the url to the quarantine file
      --start-from duration          time period for report (default 240h0m0s)

Global Flags:
      --log-level uint32   level for logging (default 4)
```

## test-report dequarantine execute

`test-report dequarantine execute` creates a new file matching the format of quarantined_tests.json from the source file where entries for stable tests are omitted

to do that the Jenkins server is asked for build results from the matching lanes within the matching time frame,
then results are filtered by those tests whose names match the entries in the `quarantined_tests.json`.

The remaining build results are inspected for failures. If one of the following conditions applies

* any failure is seen
* not reaching a minimum amount of passed tests (see `--minimum-passed-runs-per-test`)

then that test is seen as unstable and the entry will be transferred into the new file.

The execution filtering logs all activity to make clear why a test is not considered as stable. All output regarding
a test not being considered as stable is done on warning level.

Output on error level is emitted if the record under inspection can not be matched to any test from the test results
that have been acquired.

```shell
Usage:
  test-report dequarantine execute [flags]

Flags:
      --dry-run                            whether to only check what jobs are being considered and then exit (default true)
      --endpoint string                    jenkins base url (default "https://main-jenkins-csb-cnvqe.apps.ocp-c1.prod.psi.redhat.com/")
  -h, --help                               help for execute
      --job-name-pattern string            the pattern to which all jobs have to match
      --max-conns-per-host int             the maximum number of connections that are going to be made (default 3)
      --minimum-passed-runs-per-test int   whether to only check what jobs are being considered and then exit (default 2)
      --output-file string                 Path to output file, if not given, a temporary file will be used
      --quarantine-file-url string         the url to the quarantine file
      --start-from duration                time period for report (default 240h0m0s)

Global Flags:
      --log-level uint32   level for logging (default 4)

```

## Running test-report commands

### using shell wrapper script with podman

The easiest way for running `test-report` is using the shell script. You can find it [here](../../../hack/test-report.sh)

**Note: Since the app is containerized, [`podman`](https://podman.io/) is required for the script!**

```shell
$ ./hack/test-report.sh --help
test-report creates a report about which tests have been run on what lane

Usage:
...
```

### using golang

You can also use [`go`](https://go.dev/) to run it:

```shell
$ go run ./robots/cmd/test-report/... --help
test-report creates a report about which tests have been run on what lane
...
```

### using bazel

You can also use [`bazel`](https://bazel.build/) to run it:

```shell
$ bazel run //robots/cmd/test-report -- --help
INFO: Analyzed target //robots/cmd/test-report:test-report (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
...
test-report creates reports about test executions

Usage:
  test-report [flags]
  test-report [command]

...
```

### using bazel

You can use [`bazel`]() to run it:

```shell
$ bazel run //robots/cmd/test-report -- --help
INFO: Analyzed target //robots/cmd/test-report:test-report (0 packages loaded, 0 targets configured).
...
test-report creates reports about test executions

Usage:
  test-report [flags]
  test-report [command]

...
```

## Checking custom configuration

Use ``--dry-run`` flag to see which jobs are considered for the report ahead of actually creating the report.

repository: kubevirt/project-infra

repo_name: kubevirt/project-infra


text:
# Joconut

Never load a full page on every request again.

# Getting Started
Download the [production version][min] or the [development version][max].

[min]: https://raw.github.com/vdemedes/joconut/master/dist/joconut.min.js
[max]: https://raw.github.com/vdemedes/joconut/master/dist/joconut.js

Include it in your web pages(1kb minified and gzipped):

```html
<script src="joconut.min.js"></script> <!-- you must include jQuery before that -->
```

That's it! Now, all your local links will not cause page refresh. Remote links will work as expected.

# Features

- Lightweight(1kb minified and gzipped)
- Detects and loads scripts and stylesheets from fetched pages, if they do not exist in the current one
- HTML5 History API support with fallback to location.hash

# How is it different from the existing PJAX plugin?

1. 1kb minified and gzipped
2. Auto-detects and loads JS and CSS from fetched pages, if needed
3. No need to set up or configure

# Tests

You should have **node** to be installed. ```cd test && npm i connect route66 && node server.js```. Navigate to http://localhost:3000 after that and play.

# License

Copyright (c) 2012 Vadim Demedes
Licensed under the MIT license.

repository: jhbao/joconut

repo_name: jhbao/joconut


text:
# Harry Potter API

## Useful links
* [Heroku](https://bme-potter-api.herokuapp.com/)
* [Swagger](https://bme-potter-api.herokuapp.com/swagger/)

Harry Potter API is a node.js library for API.

## Installation

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

```bash
npm install
```

## Usage

```bash
npm run start
npm run dev
```

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

Please make sure to update tests as appropriate.

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

## Credentials
Uses data from [JRC404/HarryPotterAPI](https://github.com/JRC404/HarryPotterAPI)

repository: amadeuszblanik/harry-potter-api

repo_name: amadeuszblanik/harry-potter-api


text:
---
layout: post
title:  "Matrices"
description: "Background to matrices"
category: Maths
tags: [maths]
---
{% include JB/setup %}

Matrices are useful for writing linear systems more compactly. Instead of writing linear systems as:

<div>
$$1x_{1} + 2x_{2} = -1$$
$$3x_{1} + 4x_{2} = 0$$
$$5x_{1} + 6x_{2} = -5$$
</div>

We could write the linear systems using matrices:

$$
\begin{pmatrix}
1 & 2 \\\\
3 & 4 \\\\
5 & 6
\end{pmatrix}
\begin{pmatrix}
x_{1} \\\\
x_{2}
\end{pmatrix} =
\begin{pmatrix}
-1 \\\\
0 \\\\
5
\end{pmatrix}
$$

### Matrix calculations

The four relevant operators are:

1. Addition
2. Subtraction
3. Scalar multiplication
4. Matrix multiplication

Addition and subtraction are straight-forward and work only with matrices that have the same dimensions. Scalar multiplication is also straight-forward; each element would be multiplied by a single number. Matrix multiplication, takes each row of the left factor and multiplies it with each column of the right factor. For example:

$$
\begin{pmatrix}
1 & 2 \\\\
3 & 4 \\\\
5 & 6
\end{pmatrix}
\begin{pmatrix}
x_{1} & y_{1} \\\\
x_{2} & y_{2}
\end{pmatrix} =
\begin{pmatrix}
1x_{1} + 2x_{2} & 1y_{1} + 2y_{2} \\\\
3x_{1} + 4x_{2} & 3y_{1} + 4y_{2} \\\\
5x_{1} + 6x_{2} & 5y_{1} + 6y_{2}
\end{pmatrix}
$$

An $m \times n$ matrix multiplied by an $n \times p$ matrix, yields an $m \times p$ matrix. In the example above, the multiplication of a 3 by 2 matrix to a 2 by 2 matrix, yielded a 3 by 2 matrix. Furthermore, changing the order of factors usually results in a completely different product and matrices can only be multiplied if the number of columns in the left factor matches the number of row in the right factor.

### Special matrices

A **zero matrix** is a matrix where all elements are equal to zero.

$$
\begin{pmatrix}
0 & 0 \\\\
0 & 0
\end{pmatrix}
$$

If we **transpose** this 2 by 3 matrix:

$$
\begin{pmatrix}
1 & 2 & 3 \\\\
4 & 5 & 6
\end{pmatrix}
$$

we get this 3 by 2 matrix:

$$
\begin{pmatrix}
1 & 4 \\\\
2 & 5 \\\\
3 & 6
\end{pmatrix}
$$

**Symmetric matrices** are square matrices that are symmetric around their main diagonals; a symmetric matrix is always equal to its transpose. For example:

$$
\begin{pmatrix}
1 & 1 & 1 & 1 \\\\
1 & 2 & 4 & 4 \\\\
1 & 4 & 3 & 9 \\\\
1 & 4 & 9 & 4
\end{pmatrix}
$$

**Triangular matrices** are square matrices in which the elements either above or below the main diagonal are all equal to zero. Here's an example of an **upper triangular matrix**:

$$
\begin{pmatrix}
1 & 1 & 1 & 1 \\\\
0 & 2 & 4 & 4 \\\\
0 & 0 & 3 & 9 \\\\
0 & 0 & 0 & 4
\end{pmatrix}
$$

Here's an example of a **lower triangular matrix**:

$$
\begin{pmatrix}
1 & 0 & 0 & 0 \\\\
1 & 2 & 0 & 0 \\\\
1 & 4 & 3 & 0 \\\\
1 & 4 & 9 & 4
\end{pmatrix}
$$

A **diagonal matrix** is a square matrix in which all elements that are not part of its main diagonal are equal to zero. For example:

$$
\begin{pmatrix}
1 & 0 & 0 & 0 \\\\
0 & 2 & 0 & 0 \\\\
0 & 0 & 3 & 0 \\\\
0 & 0 & 0 & 4
\end{pmatrix}
$$

**Identity matrices** are are square matrices with $n $ rows, where all elements on the main diagonal are equal to 1 and all other elements are 0. For example:

$$
\begin{pmatrix}
1 & 0 & 0 & 0 \\\\
0 & 1 & 0 & 0 \\\\
0 & 0 & 1 & 0 \\\\
0 & 0 & 0 & 1
\end{pmatrix}
$$

Multiplying a matrix with the identity matrix yields a product equal to the original matrix.

If the product of two square matrices is an identity matrix, then the two factor matrices are **inverses** of each other. For example:

$$
\begin{pmatrix}
1 & 2 \\\\
3 & 4
\end{pmatrix} \times
\begin{pmatrix}
x_{11} & x_{12} \\\\
x_{21} & x_{22}
\end{pmatrix} =
\begin{pmatrix}
1 & 0 \\\\
0 & 1
\end{pmatrix}
$$


text:
![EDB Logo](../images/logo.png "EDB Logo")

# EDB Reference Architectures

## Add on: load balancing and query routing with pgPool

pgPool can be used to provide pooling and load balancing over the top
of a cluster of Postgres servers. Unlike [pgBouncer](../pgbouncer/), pgPool is
able to route queries based on whether or not they are part of read or
read/write transactions, making pgPool useful in situations where the application
cannot do this itself.

It is important to note that pgPool parses queries to understand whether or not
they are going to cause writes to the database or not. This may not work
correctly if the writes are hidden inside stored procedures, views or similar
objects that may actually be called through a SELECT query. You should ensure
your application will not be affected by this behaviour before using pgPool to
handle read vs. read/write query routing.

### When should this architecture be used?

When any or all of the following are true, pgPool should be considered:

* When the application cannot manage routing of read or read/write queries to
the appropriate database itself.
* When load balancing across a number of read-only servers, and you want to be
able to add/remove servers on the fly without having to update DNS zonefiles or
similar.

### Architectural diagrams

![Architecture Diagrams](images/architecture.png "Architecture Diagrams")

### What hardware is required?

pgPool may be installed on a dedicated node (or nodes), or colocated with the
database server instances. If using multiple instances of pgPool for high
availibility, consider using a virtual IP address, DNS, or other techniques to
ensure connections are only routed to the active instances.

### What software is required?

* Any Linux distribution
[supported by EDB products](https://www.enterprisedb.com/product-compatibility).
* pgPool

### How is this architecture implemented?

1. Decide where you wish to install pgPool.

2. If installing with EDB Postgres Advanced Server on Linux, visit the
[EDB Repos](https://repos.enterprisedb.com/) website to configure the EDB
repository and install pgPool.

3. If installing with PostgreSQL on Linux, visit the
[PostgreSQL Download](https://www.postgresql.org/download/linux/) page
to configure the PostgreSQL repository and install pgPool.

4. Follow the [pgPool documentation](https://www.pgpool.net/)
to configure pgPool to connect to the backend database servers as required,
and to authenticate incoming connections.

### Summary

pgPool may be used as a connection pooler to minimise backend startup cost
and the number of connections to a Postgres server, and to provide
load balancing with automatic query routing over a number of Postgres servers.

license: PostgreSQL

repository: EnterpriseDB/edb-ref-archs

repo_name: EnterpriseDB/edb-ref-archs