text:
Here we support extraction for the Coq-ified version of the containers
library.

The extraction process is specified in the file `extracted-src/Extract.v`

NOTE: you must use stack to make sure that you use the right version of
GHC (8.4.3), the base libraries (<IP_ADDRESS>) and containers (<IP_ADDRESS>).

# install and run

- make sure that `base/` and `containers/lib/` is up to date

- type `make` in the `containers/extraction/extracted-src/` directory
  This will extract Haskell modules from the containers/lib .v files.

  Use fixcode.pl script to add missing imports to a few extracted files.
  (Ascii.hs,QArith_base.hs,Real.hs)

      perl -i examples/containers/extraction/extracted-src/fixcode.pl examples/containers/extraction/extracted-src/*.hs

- `stack build`

- `stack test`

- `stack bench`

# The shim

The file `src/ExtractedSet.hs` is a "shim" file that restores the original
interface of the library.

- provides explicit type class dictionaries when
  necessary (Coq's extraction process compiles these away).
- create instances Eq, Ord, Semigroup, Monoid, Foldable from
  Coq definitions
- add instances that were not translated (`NFData` and `Show`) that are
  needed for benchmarking and testing.
- convert between `Int` and `BinNums.Z`

# The tests/benchmarks

The benchmarks and test suite come directly from containers, with slight
modification (i.e. using ExtractedSet, `Bin` to `bin`, removing tests &
benchmarks for the untranslated functions).

   SetProperties.hs  is derived from `../containers/tests/set-properties.hs`
   Bench.hs is derived from `../containers/benchmarks/Set.hs`

repository: antalsz/hs-to-coq

gha_language: Coq

repo_name: antalsz/hs-to-coq


text:
---
title: Swedbank Pay Payments Mobile Pay
sidebar:
  navigation:
  - title: MobilePay Payments
    items:
    - url: /payments/mobile-pay
      title: Introduction
    - url: /payments/mobile-pay/redirect
      title: Redirect
    - url: /payments/mobile-pay/after-payment
      title: After Payment
    - url: /payments/mobile-pay/other-features
      title: Other Features
---

{% include alert-development-section.md %}

>Add MobilePay Online to your Swedbank Pay payment instruments and take advantage
of [Swedbank Pay Settlement Service][payex-reconciliation-and-settlement] to
get consolidated payments and reporting, for all your payment instruments.

## MobilePay Online Payments

Read our documentation on [MobilePay Redirect](/payments/mobile-pay/redirect)
to learn how to implement MobilePay in the redirect scenario.

## Payment Link

>The implementation sequence for this scenario is a variant of the purchase
 sequence in a
 [hosted payment page redirect scenario][redirect-implementation].
 The consumer is not redirected to the Payments directly but will
 instead receive a payment link via mail/SMS.
 When the consumer clicks on the link a payment window opens.

## Introduction

* The Payment Link can be implemented for payment instruments listed below,
  using the Redirect platform and hosted payment page.
  * [Credit card][credit-card]
  * [MobilePay][mobile-pay]
  * [Swish m-commerce][swish-m-commerce] and [Swish e-commerce][swish-e-commerce]
  * [Vipps][vipps]
* When the consumer/end-user starts the purchase process in your
  merchant/wehshop site, you need to make a `POST` request towards Swedbank Pay
  with your Purchase information.
  You receive a Payment Link (same as redirect URL) in response.
* You have to distribute the Payment Link to the customer through your order
  system, using channels like e-mail or SMS.
  * NOTE: When sending information in e-mail/SMS, it is strongly recommended
   that you add information about your terms and conditions, including
   purchase information and price.
    **See recommendations in the next paragraph.**
* When the consumer clicks on the Payment Link, the Swedbank Pay payment page
  will open, letting the consumer enter the payment details (varying depending
  on payment instrument) in a secure Swedbank Pay hosted environment.
  When paying with credit card and if required, Swedbank Pay will handle
  3-D Secure authentication
* After completion, Swedbank Pay will redirect the browser back to your
  merchant/webshop site.
* If [CallbackURL][technical-reference-callback] is set the merchant system
  will receive a callback from PayEx, enabling you to make a `GET` request
  towards Swedbank Pay with the paymentID received in the first step,
  which will return the purchase result.

## Recommendations regarding Payment Link in E-mail/SMS

When you as a merchant sends an e-mail or SMS to the consumer about the
Payment Link, it is recommended to include contextual information that help
the consumer understand what will happen when clicking on the Payment Link.
We recommend that you include following information:

* The name of the merchant/shop that initiates the payment
* An understandable product description, describing what kind of service the
  consumer will pay for.
* Some order-id (or similar) that exists in the merchant order system.
* The price and currency.
* Details about shipping method and expected delivery
  (if physical goods will be sent  to the consumer).
* Directions to (a link to a page) the merchant's terms and conditions
  (such as return policy) and information of how the consumer can contact the
  merchant.
* Details informing the consumer that he or she accepts the Terms & Conditions
  when clicking on the Payment Link.

## Recommendations about receipt

We recommend that you send an e-mail or SMS confirmation with a receipt to
the consumer when the payment has been fulfilled.

## API requests

The API requests depend on the payment instrument you are using when implementing
the Payment Link scenario, see [purchase flow](#purchase-flow).
One-phase payment metods will not implement capture, cancellation or reversal.
The options you can choose from when creating a payment with key operation set
to Value Purchase are listed below.

## Screenshots

When clicking the payment link, the consumer will be directed to a payment
page, similar to the examples below, where payment information can be entered.

![Payex payment menu][paymentMethodsScreenshot]

### Options

All valid options when posting in a payment with operation Purchase,
are described in each payment instrument's respective API reference.
Please see the general sequence diagrams for more information about payments
in one-phase (e.g. [Swish][swish-m-commerce] and credit card with autocapture)
and two-phase (e.g. [Credit card][credit-card],
[MobilePay][mobile-pay], [Vipps][vipps]).

#### Authorization

* PreAuthorization (Credit card):
  * If you specify that the _intent_ of the _purchase_ is PreAuthorize,
   it's almost the same as an authorization,
    **except that no money will be reserved** from the consumers credit card,
   [before you make a finalize on this transaction (using the PATCH on
   the Autorization)][tecnical-reference-finalize].

* Authorize (two-phase):
  * When using two-phase flows you reserve the amount with an authorization,
   you will have to specify that the intent of the purchaseis Authorize.
   The amount will be reserved but not charged.
   You will later (i.e. when you are ready to ship the purchased products)
   have to make a `Capture` or `Cancel` request.

#### Capture

*Autocapture (one-phase credit card)*:
If you want the credit card to be charged right away, you will have to specify
that the intent of the purchaseis Autocapture.
The credit card will be charged and you don't need to do any more financial
operations to this purchase.

#### General

When implementing the Payment Link scenario, it is optional to set a
[CallbackURL][technical-reference-callback] in the `POST` request.
If callbackURL is set Swedbank Pay will send a postback request to this URL
when the consumer as fulfilled the payment.

## Purchase flow

The sequence diagrams display the high level process of the purchase,
from generating a Payment Link to receving a Callback.
This in a generalized flow as well as a specific 3-D Secure enabled credit
card scenario.

{% include alert.html type="neutral" icon="info" body="
Please note that the the callback may come either before, after or in the same
moment as the consumer are being redirected to the status page at the merchant
site when the purchase is fulfilled." %}

When dealing with credit card payments, 3-D Secure authentication of the
cardholder is an essential topic.
There are two alternative outcome of a credit card payment:

* 3-D Secure enabled - by default, 3-D Secure should be enabled, and Swedbank
  Pay will check if the card is enrolled with 3-D Secure.
  This depends on the issuer of the card.
  If the card is not enrolled with 3-D Secure, no authentication
  of the cardholder is done.
* Card supports 3-D Secure - if the card is enrolled with 3-D Secure,
  Swedbank Pay will redirect the cardholder to the autentication mechanism
  that is decided by the issuing bank.
  Normally this will be done using BankID or Mobile BankID.

```mermaid
sequenceDiagram
  Consumer->>MerchantOrderSystem: consumer starts purchase
  Activate MerchantOrderSystem
  MerchantOrderSystem->>Merchant: start purchase process
  Activate Merchant
  Merchant->>PayEx: POST [payment] (operation=PURCHASE)
  note left of Merchant: First API request
  Activate PayEx
  PayEx-->>Merchant: payment resource with payment URL
  Deactivate PayEx
  Merchant-->>MerchantOrderSystem: Payment URL sent to order system
  Deactivate Merchant
  MerchantOrderSystem-->>Consumer: Distribute Payment URL through e-mail/SMS
  Deactivate MerchantOrderSystem

  note left of Consumer: Payment Link in e-mail/SMS
  Consumer->>PayEx: Open link and enter payment information
  Activate PayEx

  opt Card supports 3-D Secure
  PayEx-->>Consumer: redirect to IssuingBank
  Deactivate PayEx
  Consumer->>IssuingBank: 3-D Secure authentication process
  Consumer->>PayEx: access authentication page
  Activate PayEx
  end

  PayEx-->>Consumer: redirect to merchant site
  note left of PayEx: redirect back to merchant
  Deactivate PayEx

  Consumer->>Merchant: access merchant page
  Activate Merchant
  Merchant->>PayEx: GET [payment]
  note left of Merchant: Second API request
  Activate PayEx
  PayEx-->>Merchant: payment resource
  Deactivate PayEx
  Merchant-->>Consumer: display purchase result
  Deactivate Merchant
```

{% include iterator.html
                         next_href="redirect"
                         next_title="Next: Redirect" %}

[paymentMethodsScreenshot]: /assets/img/checkout/payment_methods.PNG
[credit-card]: /payments/card/
[mobile-pay]: /payments/mobile-pay/
[payex-reconciliation-and-settlement]: /payments/mobile-pay/other-features#settlement-and-reconcilliation
[redirect-implementation]: /payments/mobile-pay/redirect
[swish-e-commerce]: /payments/swish#swish-e-commerce-redirect-to-payment-pages
[swish-m-commerce]: /payments/swish#swish-m-commerce-redirect-to-payment-pages
[technical-reference-callback]: /payments/mobile-pay/other-features#callback
[tecnical-reference-finalize]: /payments/mobile-pay/after-payment#finalize
[vipps]: /payments/vipps/

license: MIT

branch_name: refs/heads/master

extension: md

gha_license_id: MIT

license_type: permissive


text:
# Fellowship Prediction
## GitHub Profile Comparative Analysis Tool Built with BentoML

![Fellowship Prediction Header Logo](https://socialify.git.ci/dtemir/fellowship-prediction/image?description=1&descriptionEditable=Comparative%20Analysis%20Tool%20for%20Future%20MLH%20Fellows&font=Rokkitt&forks=1&issues=1&language=1&logo=https%3A%2F%2Fi.imgur.com%2FJXjVwDA.png&pattern=Circuit%20Board&pulls=1&stargazers=1&theme=Light)

Table of Contents:
* [Features](#features)
* [Disclaimer](#disclaimer)
* [Technologies Used](#technologies-used)
* [Contributing](#contributing)
* [Demo](#demo)
* [Motivation](#motivation)
* [Team](#team)
  * [Damir](#damir-temir)
  * [Aymen](#aymen-bennabi)
  * [Tasha](#tasha-kim)
  * [Mofe](#eyimofe-ogunbiyi)
* [License](#license)

## Winner

This project won the [MLH Fellowship Orientation Hackathon - Batch 4](https://fellowship-orientation-batch-4.devpost.com/) along with other great projects by MLH Fellows. We highly suggest you check them out.

## Features

**Analyzes your GitHub Profile and presents you with a report on how likely you are to become the next MLH Fellow!**

[Try it now!](https://fellowship-prediction.web.app/)

[![Demo Git](img/demo.gif)](https://fellowship-prediction.web.app/)

Provides you with an **extensive analysis** on the following features of your profile:

| Feature | Description |
| :---- | :---- |
| Commits | Number of total commits the user made |
| Contributions | Number of repositories where the user made contributions |
| Followers | Number of followers the user has |
| Forks | Number of forks the user has in their repositories |
| Issues | Number of issues the user has raised |
| Organizations | Number of organizations the user is a part of |
| Repos |  Number of repositories the user has |
| Stars | Number of stars the user has on their repositories |

And gives you a comprehensive score of how similar your GitHub Profile is to an **average MLH Fellow's GitHub**.

It also shows your statistics in a **user-friendly data visualization** format for you to **gauge the range of your skills**
and **become the next MLH Fellow!**

## Disclaimer

Dear user, building this application, we were trying our best to provide with data insights into things you can improve through your GitHub Profile.
This is a hackakthon project that is built by Open Source Fellows and is not directly affiliated with MLH in any capacity.
**The positive score in your application does not guarantee your chances of becoming a fellow** because there are external things apart from GitHub that affect the decision process.

We also hope that you understand that your **GitHub Stats do not affect your value to the community as a developer**.
We all have different paths to success in our lives, and they do not necessarily involve high scores.
Regardless of your numbers, you are going to succeed in your journey.

## Technologies Used

![Tech Stack Used](img/tech-stack.png)

We used the following technologies:
* **BentoML** along with **Heroku** to build an API endpoint that calculates the comprehensive score for the user based on a simple query.
* **Flask** deployed to **Heroku** to setup a bridge between the frameworks and collect the input data.
* **React.js** served on **Firebase** to provide user-friendly UI for future MLH fellows to use.

## Contributing

To contribute to this open-source project, follow these steps:

1. Fork the repository.
2. Create a branch: `git checkout -b <branch_name>`.
3.
4. Push to your branch: `git push origin <project_name>/<location>`.
5. Create a pull request.

To work on BentoML:
1. Go to [_model/bento_deploy_](https://github.com/dtemir/fellowship-prediction/tree/main/model/bento_deploy) to find necessary files.
2. Read [BentoML Start Guide](https://docs.bentoml.org/en/latest/quickstart.html) to learn more about the files.
3. Improve the BentoML Interface to provide our users with a more accurate score.
4. Create the BentoML prediction service with `python bento_packer.py` and commit the saved class from `bentoml get IrisClassifier:latest --print-location --quiet`.

To work on the Back-End:
1. Consult [_scr/server_](https://github.com/dtemir/fellowship-prediction/tree/main/src/server) and its README.
2. Make contributions.

_Alternatively:_ Reach out to one of the [Project Contributors](https://github.com/dtemir/fellowship-prediction/graphs/contributors) for questions.

## Demo

[![YouTube Logo that Leads to our demo](img/youtube.png)](https://www.youtube.com/watch?v=gBtMHzwInAQ&ab_channel=DamirTemir)

## Motivation

We built this project because we wanted to **help prospective MLH Fellows** with their progress toward a better GitHub profile
with solid projects and a record of active work.
We also wanted to **give them some insights** into what an average fellow at MLH looks like.

When we were just aspiring to become MLH Fellows, we would look for different sources of information to know what
MLH is looking for in their fellows and better ways to prepare.
So we tried to address this issue and hopefully support future fellows on their way to success.

However, we make an important notion that **your GitHub Profile does not define you as a developer**.
Our tool is simply to let you see into the data for areas of potential improvement and keep working toward your goals.
We do not consider things like:
* Personal communication levels
* Spot availability
* Match in project interests

The mentioned points affect your chances on becoming a fellow.
Unfortunately, there is no way to take them into consideration.

## Team

Damir Tamir

Aymen Bennabi

Tasha Kim

Eyimofe Ogunbiy

### Damir Temir

Working on the project, I learned the basics of BentoML and deploying the server model to the cloud like Heroku.
I also gained some experience in Data Mining and Processing, which is an invaluable skill toward my journey to Machine Learning Engineering.

The contributions I made are:
* Wrote Jupyter Notebooks where we showcase our work with the GitHub API.
* Set up a Git repository with active GitHub Projects and proper infrastructure.
* Mined data on more than 650 fellows in the MLH Fellowship organization.
* Created a BentoML API node deployed to Heroku for querying.

### Aymen Bennabi

During the hackathon I majorly worked on the Front-End part of the project. I created a friendly UI/UX to collect data and visualize the results.
Also, I helped a little bit with the Back-End by creating a facade API to make working with GitHub easier. The new interface adds a level of abstraction that mainly focuses on quantitative data that we needed to do the statistical analysis.

I really enjoyed the Orientation Hackathon. I now feel more confident working with Git/GitHub. I also started learning about functional programming base API (OCamal/dream).

### Tasha Kim

Utilizing BentoML gave us a flexible, high-performance framework to serve, manage, and deploy our model to predict MLH fellowship status using user's GitHub profiles. In particular, I enjoyed working with ML frameworks like Matplotlib, Seaborn, and Pandas, as well as Cloud native deployment services, and API serving that were all packaged into a single service.

Some of my contributions were:
- Implemented the ANNOVA model as an alternative improved statiscal comparison to the one we are using now. Our current one works fine, but we can use this in the case we want a more rigorous and detailed comparison (multiple pairwise comparison (post hoc comparison) analysis for all unplanned comparison using Tukey’s honestly significantly differenced (HSD) test).
- Built a CI (continuous integration) pipeline for build, run, and testing of our node app as well as python app using github actions.
- Implemented method to compute average statistics for aggregated mlh fellow data.

Shout out to everyone in our team!

### Eyimofe Ogunbiyi

I worked on the Back-End Server for the project and the deployment pipeline on Heroku. I was able to use the Flask Rest Framework for the Back-End which was a new experience for me.

## License

This project is served under the MIT License.

    MIT License

    Copyright (c) 2021 Damir Temir

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

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

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

repository: dtemir/fellowship-prediction

branch_name: refs/heads/main

gha_language: Jupyter Notebook

repo_name: dtemir/fellowship-prediction


text:
Golang CRUD Booster

#### Running Locally

First, install the dependencies
`go get`

The web app requires Postgres DB. If you have docker installed, you can run the
following command to start a new Postgres container

`docker run -e POSTGRESQL_ADMIN_PASSWORD=mysecretpassword -d -p 5432:5432 centos/postgresql-96-centos7`

In this example, the database user is `postgres`, the password is `mysecretpassword` and the database is `postgres`

You can then start the application like this:

`go build && ./golang-http-crud`

Then go to http://localhost:8080

repository: golang-starters/golang-http-crud

gha_language: Go

repo_name: golang-starters/golang-http-crud


text:
# Analysis of the SAMPLing challenge

Preliminary analysis of the SAMPLing challenge.

Another set of reference calculations has been performed, and we are currently trying to resolve differences in the
final free energies on the order of 1-1.5 kcal/mol. We'll update the analysis once we understand the cause of the
discrepancies.

## Manifest

- `PaperImages/`: Images generated by the scripts in `../Scripts/` for the journal article.
- `Data/`: CSV and JSON data for the reference calculations and submission analysis.
  - `submission_id.csv/json`: contain the mean free energy, the 95% t-based confidence interval, and the difference
     with the reference calculation in time for all three systems. The values of the confidence interval (`DG_CI`) have
     to be interpreted as `mean-DG +- DG_CI`
  - `reference_free_energies.csv/json`: contain the free energies of all 5 replicates, number of energy evaluations,
     CPU time, mean free energy, and 95% t-based confidence interval in time for all the three systems.

gha_language: Python


text:
---
layout: default
---

# 1996-08-13 - Re: National Socio-Economic Security Need for Encryption Technology

## Header Data

From: "Perry E. Metzger"<EMAIL_ADDRESS>To: Bart Croughs<EMAIL_ADDRESS>Message Hash: 39d259c6de8210afaa648aa1eee7968341779401086fa731f7976cc702b6c175

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1996-08-13 07:20:52 UTC

Raw Date: Tue, 13 Aug 1996 15:20:52 +0800

## Raw message

```
{% raw  %}From: "Perry E. Metzger"<EMAIL_ADDRESS>Date: Tue, 13 Aug 1996 15:20:52 +0800
To: Bart Croughs<EMAIL_ADDRESS>Subject: Re: National Socio-Economic Security Need for Encryption Technology
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

Bart Croughs writes:
> Perry Metzger wrote:
>
> >Bart Croughs writes:
> >> 	 But there is another axiom of economics which the
> >>nationalist/socialist can use for his case against the free movement of
> >> capital. This axiom states that the wages of workers depend on the
> >> amount of capital invested. The more capital invested, the higher the
> >> wages are.
>
> >This must be some new axiom of economics that I had not heard of.
>
> It's not a sin to be ignorant, but to boast about it...  I recommend
> you read the great libertarian /austrian economists: Murray
> Rothbard, Henry Hazlitt, etc.

Perhaps I should start being more vicious when I'm using sarcasm.

Nowhere in the writings of any Austrian economist will you find anything
claiming that the wages for a given job are linked to capital
investment by the employer.

Perry

{% endraw %}
```

## Thread

+ Return to [August 1996](/archive/1996/08)

+ Return to "[Bart  Croughs <bart.croughs@tip.nl>](/authors/bart_croughs_bart_croughs_at_tip_nl_)"
+ Return to "["Perry E. Metzger" <perry@piermont.com>](/authors/perry_e_metzger_perry_at_piermont_com_)"

+ 1996-08-13 (Tue, 13 Aug 1996 09:11:59 +0800) - [re: National Socio-Economic Security Need for Encryption Technology](/archive/1996/08/9f31ef4dc4e49a8685638a0d9895216c893984ebfc275f96d35651daed7515e2) - _Bart  Croughs<EMAIL_ADDRESS>  + 1996-08-13 (Tue, 13 Aug 1996 15:20:52 +0800) - Re: National Socio-Economic Security Need for Encryption Technology - _"Perry E. Metzger"<EMAIL_ADDRESS>


text:
# Apache Flink™ Training

This repository contains material for [Apache Flink™](http://flink.apache.org) training from [Ververica](http://www.ververica.com).

The training is available at [https://training.ververica.com](https://training.ververica.com).

The gh-pages branch of this repository is the one that gets deployed.

-------

Copyright © 2020 Ververica GmbH. All Rights Reserved.

Apache Flink, Apache, and the Apache feather logo are trademarks of The Apache Software Foundation.

repository: alpinegizmo/flink-training-web

repo_name: alpinegizmo/flink-training-web


text:
# lookerapi.ApiAuthApi

All URIs are relative to *https://demo.looker.com:19999/api/3.0*

Method | HTTP request | Description
------------- | ------------- | -------------
[**login**](ApiAuthApi.md#login) | **POST** /login | Login
[**login_user**](ApiAuthApi.md#login_user) | **POST** /login/{user_id} | Login user
[**logout**](ApiAuthApi.md#logout) | **DELETE** /logout | Logout

# **login**
> AccessToken login(client_id=client_id, client_secret=client_secret)

Login

### Present client credentials to obtain an authorization token  Looker API implements the OAuth2 [Resource Owner Password Credentials Grant](https://looker.com/docs/r/api/outh2_resource_owner_pc) pattern. The client credentials required for this login must be obtained by creating an API3 key on a user account in the Looker Admin console. The API3 key consists of a public `client_id` and a private `client_secret`.  The access token returned by `login` must be used in the HTTP Authorization header of subsequent API requests, like this: ``` Authorization: token 4QDkCyCtZzYgj4C2p2cj3csJH7zqS5RzKs2kTnG4 ``` Replace \"4QDkCy...\" with the `access_token` value returned by `login`. The word 'token' is a string literal and must be included exactly as shown.  For more information and detailed examples of Looker API authorization, see [How to Authenticate to Looker API3](https://github.com/looker/looker-sdk-ruby/blob/master/authentication.md).

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.ApiAuthApi()
client_id = 'client_id_example' # str | client_id part of API3 Key. (optional)
client_secret = 'client_secret_example' # str | client_secret part of API3 Key. (optional)

try:
    # Login
    api_response = api_instance.login(client_id=client_id, client_secret=client_secret)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ApiAuthApi->login: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **client_id** | **str**| client_id part of API3 Key. | [optional]
 **client_secret** | **str**| client_secret part of API3 Key. | [optional]

### Return type

[**AccessToken**](AccessToken.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/x-www-form-urlencoded
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **login_user**
> AccessToken login_user(user_id)

Login user

### Create an access token for a given user.  This can only be called by an authenticated admin user. It allows that admin to generate a new authentication token for the user with the given user id. That token can then be used for subsequent API calls - which are then performed *as* that target user.  The target user does *not* need to have a pre-existing API client_id/client_secret pair. And, no such credentials are created by this call.  This allows for building systems where api user authentication for an arbitrary number of users is done outside of Looker and funneled through a single 'service account' with admin permissions. Note that a new access token is generated on each call. If target users are going to be making numerous API calls in a short period then it is wise to cache this authentication token rather than call this before each of those API calls.  See 'login' for more detail on the access token and how to use it.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.ApiAuthApi()
user_id = 789 # int | Id of user.

try:
    # Login user
    api_response = api_instance.login_user(user_id)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ApiAuthApi->login_user: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **user_id** | **int**| Id of user. |

### Return type

[**AccessToken**](AccessToken.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **logout**
> str logout()

Logout

### Logout of the API and invalidate the current access token.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.ApiAuthApi()

try:
    # Logout
    api_response = api_instance.logout()
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ApiAuthApi->logout: %s\n" % e)
```

### Parameters
This endpoint does not need any parameter.

### Return type

**str**

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)


text:
# One Equall Musick - Front Page

A [Jekyll](https://jekyllrb.com/) site for Montreal-based early music collective One Equall Musick, built using [Sleek](https://janczizikow.github.io/sleek/)

## License

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

repository: oneequallmusick/oem

gha_language: CSS

repo_name: oneequallmusick/oem


text:
---
layout: post
title:  "Visualizing Baby Sleep Times in Python"
date:   2020-05-26
categories: r python
comments: true
---

![how does babby sleep](/figs/2020-05-26-baby-viz/lineplot_python.png)

*This is part of a series on visualizing baby sleep data with Python and R. All code is in [this repository.](https://github.com/dodger487/snoo_plots)*

- *[Visualizing Baby Sleep Times in Python]({% post_url 2020-05-26-visualizing-baby-sleep %})*
- *[Recreating the 'Most Beautiful Data Visualization of All Time']({% post_url 2020-06-01-baby-sleep-radial %})*
- *[Night and Day, Python and R: Baby Sleep Data Analysis with Siuba]({% post_url 2020-06-10-baby-sleep-night-day %})*

# Baby Sleep Data

My baby sleeps in a fancy bassinet that records her sleep times.
I wanted to see how her sleep patterns have trended over time, going from soul-crushing randomness to the more pleasant actually-sleeping-most-of-the-night schedule.
Additionally, I wanted to take the [plotnine](https://plotnine.readthedocs.io/en/stable/) plotting library for a spin.

All of the code is [this repository.](https://github.com/dodger487/snoo_plots/blob/master/snoo_viz.py)

## Preliminaries

First we have some imports.
I always break my imports into built-ins, installed packages, and local modules.
In this case I am using no local modules, just the built-in `datetime` and the installed pandas and plotnine.
{% highlight python %}
import datetime

import pandas as pd
from plotnine import *
{% endhighlight %}
Generally, using `from [package] import *` is frowned upon, but this is a quick analysis, not production code, and it makes our plotting code way cleaner.

## Data Download and Load

Next up, a bash command to get the data out of the fancy bassinet, followed by reading it into a pandas DataFrame.
{% highlight python %}
# first, run
# pip install snoo
# snoo sessions --start START_DATE --end END_DATE > all_snoo_sessions.csv
df = pd.read_csv("all_snoo_sessions.csv")
{% endhighlight %}

## Data Processing

Out data looks like this:
{% highlight bash %}
In [207]: !head all_snoo_sessions.csv
start_time,end_time,duration,asleep,soothing
2019-11-21T18:30:38,2019-11-21T18:31:58,80,80,0
2019-11-22T04:03:32,2019-11-22T05:07:27,3835,2422,1413
2019-11-22T05:53:04,2019-11-22T05:54:07,63,36,27
{% endhighlight %}
Let's turn that into something a little more sensible.

I decided I wanted to plot date on the x-axis and the time of day on the y-axis.
I'll have a vertical line with end points for the start and end of a sleep session.
The datetimes include both dates and times (wow, dates and times in a datetime!) so we'll have to break them apart.
Pandas `.dt` accessor is great here-- it allows you to use the standard library datetime methods on a Pandas series in parallel.
{% highlight python %}
# Break out dates and times.
df["start_datetime"] = pd.to_datetime(df["start_time"])
df["end_datetime"] = pd.to_datetime(df["end_time"])
df["start_time"] = df["start_datetime"].dt.time
df["end_time"] = df["end_datetime"].dt.time
df["start_date"] = df["start_datetime"].dt.date
{% endhighlight %}

Now we run into a tricky issue: what about sleep sessions that span days?
There might be some plotting magic that can handle that, but I decided to simply break into two any sleep session that crossed a day boundary.
I did this a few ways, but I think the following approach is easiest to understand and code.

First, I separate out sessions into those that cross midnight and those that don't.
We don't need to do anything about the former and can set that data aside.

For sessions that do cross midnight, we make two copies.
For the first, we set the end date to just before midnight.
For the second, we set the start time to midnight, and increment the date to be the next day.
If this doesn't make sense, I encourage you to take a few data points and try it out.
Finally, we combine these dataframes into one new dataframe, which we'll use for plotting.

{% highlight python %}
# Deal with sessions that cross day boundaries.
df_no_cross = df[df["start_datetime"].dt.day == df["end_datetime"].dt.day].copy()
df_cross = df[df["start_datetime"].dt.day != df["end_datetime"].dt.day]
df_cross_1 = df_cross.copy()
df_cross_2 = df_cross.copy()
df_cross_1["end_time"] = datetime.time(hour=23, minute=59, second=59)
df_cross_2["start_date"] = df_cross_2["start_date"] + datetime.timedelta(days=1)
df_cross_2["start_time"] = datetime.time(hour=0, minute=0, second=0)

# Combine dataframes
rows_no_cross = df_no_cross[["start_date", "start_time", "end_time"]]
rows_cross_1 = df_cross_1[["start_date", "start_time", "end_time"]]
rows_cross_2 = df_cross_2[["start_date", "start_time", "end_time"]]
rows = pd.concat([rows_no_cross, rows_cross_1, rows_cross_2])
{% endhighlight %}

## Plotting with plotnine
I'm a huge fan of ggplot2, a graphing library for R.
Whenever I do any plotting in Python, I'm always just sad that I'm not using ggplot2.
People have tried to clone it before and I've found those clones lacking.
I gave it another whirl with `plotnine`, a new ggplot2 clone.
So far, I'm really pleased.
Everything has Just Worked™!
The plotting code will be very clear for ggplot2 fans... if you don't understand it, it's out of scope for this post, but I Strongly Encourage you to look up ggplot2 and play with it!

{% highlight python %}
# Convert back to datetime so plotnine can understand it
rows["start_time"] = pd.to_datetime(rows["start_time"], format='%H:%M:%S')
rows["end_time"] = pd.to_datetime(rows["end_time"], format='%H:%M:%S')

# Make the plot.
plot = (ggplot(aes(x="start_date",), data=rows)
  + geom_linerange(aes(ymin = "start_time", ymax = "end_time"))
  + scale_x_date(name="", date_labels="%b", expand=(0, 0))
  + scale_y_datetime(date_labels="%H:%M",
                     expand=(0, 0, 0, 0.0001))  # remove the margins
  + ggtitle("Baby Sleep Times")
  + theme_minimal()
  + theme(plot_background=element_rect(color="white"))  # white, not transparent
)

# Save it!
ggsave(plot, "fig/lineplot_python.png", width=6.96, height=5.51, units="in", dpi=300)
{% endhighlight %}

## Summary and Comments
I should note that there's clearly some missing data in the image.
We didn't track lots of naps, and a few days have no data at all.
That said, some clear patterns emerge.
During the first few days, sleep is all over the place, but gradually settles into a routine.
Later, nighttime wake-ups become fewer and shorter.

In terms of the coding work, plotnine worked great, and I look forward to using it in more projects.
As with most things in life, some small tweaks took the most time.
In particular, I messed around with the timestamp formatting a lot and spent LOTS of time Googling to figure out how to remove some margins, which I found particularly ugly.

gha_license_id: NOASSERTION


text:
# Photo-Gallery-App

## Code and Live demo

[snack code](https://snack.expo.io/@roukiasalahi/0dcba1)

## About the App

If you are a photographer and you love to see different quality images and ideas from time to time this application is the right one for you!

Instead of opening google and just see random images that takes much time to look for and might not be as your expectation as a photographer, don't worry anymore you can now easily open this application and have easy access to a huge collection of photos that you can view and get inspiration from for your future photo sessions also you can share anything easily with your clients and give them some ideas how to pose in pictures or you can just share anything you like with your friends that have the same taste and passion.

## How do I use this application ?

- Download Expo Application

   - [App Stpre](https://apps.apple.com/us/app/expo-client/id982107779)
   - [Google Play](https://play.google.com/store/apps/details?id=host.exp.exponent)

- Open the app and scan the QR code

![](./QRcode.png)

- Swip right and left between images to see a collection of photes.
- Press the share icone to share the link of the image with your friends
- Press the reffresh icon to get a new collection!

![](./p3.JPG)
![](./share1.JPG)


text:
---
title: Use RadFileExplorer with physical and shared folder paths
description: Use RadFileExplorer and RadEditor with physical and shared folder paths. Check it now!
type: how-to
page_title: Use RadFileExplorer with physical and shared folder paths
slug: editor-use-radfileexplorer-with-physical-and-shared-folder-s-paths
res_type: kb
---

## HOW-TO

The basic steps needed to implement a custom provider, that works with files and folders from a physical (or shared) file system are shown in the attached demos. A *GenericHandler.ashx* is used in the examples in order to serve the files to the browser. The different file types should be handled in this .ASHX file in order to force the browser to download or open a file.

## UPDATE
The provider supports shared folder's paths like "\\server.name\Path\Folder" as well. The mapping is done in the *MappingFile.mapping* file as shown in the attached demo.

## THE MAIN PROBLEM

The main problem in this case is that we are working with physical paths that we do not want to pass (show) to the client. In the address bar of the **RadFileExplorer** we need to show custom paths, which uniquely identify the items in the FileExplorer (and on the server). In this case, a strong mapping between the physical path and the virtual path (that will be shown in the address bar) is necessary.
In the example, which you can download from [here](files/fileexplorer-PhysicalpathFilesystemProvider.zip), the mapping is specified in the *MappingFile* sfile. You can add another mapping in the .*mapping*file and then use the mapped physical paths in the *ViewPath*, *DeletePath* or *UploadPath* collections of the FileExplorer. In the demo, the *GetPhysicalFromVirtualPath* function is widely used, and this function gets the mapped physical path from the passed virtual path.

This is an example configuration using *CustomFileSystemProvider*:

````C#
protected void Page_Load(object sender, EventArgs e)
{
string[] viewPaths = new string[]
{
   @"C:\PhysicalSource\ROOT",
   @"\\Telerik.com\Path\SharedDir"
};

string[] uploadPaths = new string[]
{
   @"C:\PhysicalSource\ROOT\CanUpload",
   @"\\Telerik.com\Path\SharedDir\ROOT\CanUpload"
};

string[] deletePaths = new string[]
{
   @"C:\PhysicalSource\ROOT\Folder_1\CanDelete",
   @"\\Telerik.com\Path\SharedDir\ROOT\Folder_1\CanDelete"
};

    RadFileExplorer1.Configuration.ViewPaths = viewPaths;
    RadFileExplorer1.Configuration.UploadPaths = uploadPaths;
    RadFileExplorer1.Configuration.DeletePaths = deletePaths;
    RadFileExplorer1.Configuration.SearchPatterns = new []{"*.*"};
    RadFileExplorer1.Configuration.ContentProviderTypeName = typeof(CustomFileSystemProvider).AssemblyQualifiedName;
}
````

 When a custom provider is used, the security part needs to be implemented as well - for example : the upload and delete logic depending from the path set.

## FORCE THE BROWSER TO DOWNLOAD THE FILES

 A GenericHandler is used in order to serve the files to the browser. Please note that the different browsers handle the file types in a different manner. You can control browsers' action, specifying the *Response.ContentType* and adding a header with the *Response.AddHeader* method before writing the file to the browser. This is a common programming task and needs to be done in the used GenericHandler. The implemented code in the demo, forces the browser to download files with *.jpg* and *.docx* extensions.

## USEFUL LINKS

* [Using custom FileBrowserContentProvider](https://docs.telerik.com/devtools/aspnet-ajax/controls/fileexplorer/server-side-programming/use-custom-filebrowsercontentprovider)
* More details about the MIME types can be found on [this site](http://www.iana.org/assignments/media-types/media-types.xhtml).
* [This is a full demo](http://demos.telerik.com/aspnet-ajax/fileexplorer/examples/applicationscenarios/filteranddownloadfiles/defaultcs.aspx) that shows how can cancel the default "Preview" window and force the browsers to download  specific files
* [This is a full demo](https://demos.telerik.com/aspnet-ajax/fileexplorer/examples/server-sideapi/dbfilebrowsercontentprovider/defaultcs.aspx)that shows an implementation of the FileBrowserContentProvider for working with database.

## NOTE
Please, read the comment in the beginning of the *MoveDirectory*function. Also, in the earlier versions of the control the *CheckDeletePermissions*method does not exist and needs to be removed. Also, a new method is added in the FileBrowserContentProvider - *CheckReadPermissions* (starting from version *2010.2.286*) and It should be overridden as well in order to ensure that the content provider will work properly.

You can download the sample files from [here](files/fileexplorer-PhysicalpathFilesystemProvider.zip). There are both C# and VB.NET versions inside the archive.

repository: telerik/ajax-docs

gha_language: C#

repo_name: telerik/ajax-docs


text:
# DaoCasinoICO

When compiling with Solidity 0.4.11, the following warnings are displayed:

```
DaoCasinoICO.sol:466:30: Warning: Unused local variable
    function receiveApproval(address _from, uint256 _value,
                             ^-----------^
DaoCasinoICO.sol:466:45: Warning: Unused local variable
    function receiveApproval(address _from, uint256 _value,
                                            ^------------^
DaoCasinoICO.sol:467:30: Warning: Unused local variable
                             ERC20 _token, bytes _extraData)
                             ^----------^
DaoCasinoICO.sol:467:44: Warning: Unused local variable
                             ERC20 _token, bytes _extraData)
                                           ^--------------^
```

Notes:

* The overall code is very neatly formatted and readable. The relationship between the contracts are a bit convoluted, as the **TokenEmission** must have the `owner` and `hammer` set to the **DaoCasinoICO** contract.

```javascript
// BK Ok
pragma solidity ^0.4.11;
/* compiled from  https://github.com/airalab/dao.casino/blob/master/contracts/DaoCasinoICO.sol */
/**
 * @title Contract for object that have an owner
 */
// BK Ok - Recommended to add the `acceptOwnership` function to reduce the chance of changing ownership of the contracts to an invalid address. See
//    https://github.com/openanx/OpenANXToken/blob/master/contracts/Owned.sol#L48-L55
contract Owned {
    /**
     * Contract owner address
     */
    // BK Ok
    address public owner;

    /**
     * @dev Delegate contract to another person
     * @param _owner New owner address
     */
    // BK Ok
    function setOwner(address _owner) onlyOwner
    { owner = _owner; }

    /**
     * @dev Owner check modifier
     */
    // BK Ok
    modifier onlyOwner { if (msg.sender != owner) throw; _; }
}

/**
 * @title Common pattern for destroyable contracts
 */
contract Destroyable {
    address public hammer;

    /**
     * @dev Hammer setter
     * @param _hammer New hammer address
     */
    function setHammer(address _hammer) onlyHammer
    { hammer = _hammer; }

    /**
     * @dev Destroy contract and scrub a data
     * @notice Only hammer can call it
     */
    function destroy() onlyHammer
    { suicide(msg.sender); }

    /**
     * @dev Hammer check modifier
     */
    modifier onlyHammer { if (msg.sender != hammer) throw; _; }
}

/**
 * @title Generic owned destroyable contract
 */
// BK Ok
contract Object is Owned, Destroyable {
    function Object() {
        owner  = msg.sender;
        hammer = msg.sender;
    }
}

// Standard token interface (ERC 20)
// https://github.com/ethereum/EIPs/issues/20
// BK Ok
contract ERC20
{
// Functions:
    /// @return total amount of tokens
    // BK Ok - Note that this is duplicated in Token and Token.totalSupply should be removed
    uint256 public totalSupply;

    /// @param _owner The address from which the balance will be retrieved
    /// @return The balance
    // BK Ok
    function balanceOf(address _owner) constant returns (uint256);

    /// @notice send `_value` token to `_to` from `msg.sender`
    /// @param _to The address of the recipient
    /// @param _value The amount of token to be transferred
    /// @return Whether the transfer was successful or not
    // BK Ok
    function transfer(address _to, uint256 _value) returns (bool);

    /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
    /// @param _from The address of the sender
    /// @param _to The address of the recipient
    /// @param _value The amount of token to be transferred
    /// @return Whether the transfer was successful or not
    // BK Ok
    function transferFrom(address _from, address _to, uint256 _value) returns (bool);

    /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @param _value The amount of wei to be approved for transfer
    /// @return Whether the approval was successful or not
    // BK Ok
    function approve(address _spender, uint256 _value) returns (bool);

    /// @param _owner The address of the account owning tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @return Amount of remaining tokens allowed to spent
    // BK Ok
    function allowance(address _owner, address _spender) constant returns (uint256);

// Events:
    // BK Ok
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    // BK Ok
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

/**
 * @title Token contract represents any asset in digital economy
 */
contract Token is Object, ERC20 {
    /* Short description of token */
    // BK Ok
    string public name;
    // BK Ok
    string public symbol;

    /* Total count of tokens exist */
    // BK NOTE As found by Darryl Morris, this variable will hide ERC20.totalSupply and should be removed
    uint256 public totalSupply;

    /* Fixed point position */
    // BK Ok
    uint8 public decimals;

    /* Token approvement system */
    // BK Ok
    mapping(address => uint256) balances;
    // BK Ok
    mapping(address => mapping(address => uint256)) allowances;

    /* Token constructor */
    // BK Ok
    function Token(string _name, string _symbol, uint8 _decimals, uint256 _count) {
        name        = _name;
        symbol      = _symbol;
        decimals    = _decimals;
        totalSupply = _count;
        balances[msg.sender] = _count;
    }

    /**
     * @dev Get balance of plain address
     * @param _owner is a target address
     * @return amount of tokens on balance
     */
    // BK Ok
    function balanceOf(address _owner) constant returns (uint256)
    { return balances[_owner]; }

    /**
     * @dev Take allowed tokens
     * @param _owner The address of the account owning tokens
     * @param _spender The address of the account able to transfer the tokens
     * @return Amount of remaining tokens allowed to spent
     */
    // BK Ok
    function allowance(address _owner, address _spender) constant returns (uint256)
    { return allowances[_owner][_spender]; }

    /**
     * @dev Transfer self tokens to given address
     * @param _to destination address
     * @param _value amount of token values to send
     * @notice `_value` tokens will be sended to `_to`
     * @return `true` when transfer done
     */
    // BK NOTE - The following function does not have overflow protection. In this case where total supply is way way less than 2^256 / 2, there is no ability for the user
    //    to cause an maths overflow anyway
    // BK NOTE - This function will also allow an account to transfer 0 tokens
    function transfer(address _to, uint256 _value) returns (bool) {
        // BK account's balance >= value
        if (balances[msg.sender] >= _value) {
            balances[msg.sender] -= _value;
            balances[_to]        += _value;
            Transfer(msg.sender, _to, _value);
            return true;
        }
        return false;
    }

    /**
     * @dev Transfer with approvement mechainsm
     * @param _from source address, `_value` tokens shold be approved for `sender`
     * @param _to destination address
     * @param _value amount of token values to send
     * @notice from `_from` will be sended `_value` tokens to `_to`
     * @return `true` when transfer is done
     */
    // BK NOTE - The following function does not have overflow protection. In this case where total supply is way way less than 2^256 / 2, there is no ability for the user
    //    to cause an maths overflow anyway
    // BK NOTE - This function will also allow an account to transfer 0 tokens
    function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
        var avail = allowances[_from][msg.sender]
                  > balances[_from] ? balances[_from]
                                    : allowances[_from][msg.sender];
        if (avail >= _value) {
            allowances[_from][msg.sender] -= _value;
            balances[_from] -= _value;
            balances[_to]   += _value;
            Transfer(_from, _to, _value);
            return true;
        }
        return false;
    }

    /**
     * @dev Give to target address ability for self token manipulation without sending
     * @param _spender target address (future requester)
     * @param _value amount of token values for approving
     */
    // BK NOTE - An account will have to call `unapprove(...)` below to reduce their allowance (to 0)
    // BK NOTE - This is a different behaviour to most other tokens, with the aim to mitigate the double spending attack
    // BK NOTE - User's should be made aware of this difference if they are used to the normal behaviour of `approve(...)`
    function approve(address _spender, uint256 _value) returns (bool) {
        // BK NOTE - += instead of =
        allowances[msg.sender][_spender] += _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    /**
     * @dev Reset count of tokens approved for given address
     * @param _spender target address (future requester)
     */
    // BK NOTE - This function is required as `approve(...)` has no way to reduce the allowance
    function unapprove(address _spender)
    { allowances[msg.sender][_spender] = 0; }
}

contract TokenEmission is Token {
    function TokenEmission(string _name, string _symbol, uint8 _decimals,
                           uint _start_count)
             Token(_name, _symbol, _decimals, _start_count)
    {}

    /**
     * @dev Token emission
     * @param _value amount of token values to emit
     * @notice owner balance will be increased by `_value`
     */
    // BK NOTE - Owner can create any number of tokens up to (2^256 - 1)/10^18
    // BK NOTE - The owner is set to the DaoCasinoICO contract, so this emission() functionality is controlled by the code
    function emission(uint _value) onlyOwner {
        // Overflow check
        if (_value + totalSupply < totalSupply) throw;

        totalSupply     += _value;
        balances[owner] += _value;
    }

    /**
     * @dev Burn the token values from sender balance and from total
     * @param _value amount of token values for burn
     * @notice sender balance will be decreased by `_value`
     */
    // BK NOTE - Accounts can burn their own tokens
    // BK NOTE - This function should log an event so token holders can monitor this operation
    function burn(uint _value) {
        if (balances[msg.sender] >= _value) {
            balances[msg.sender] -= _value;
            totalSupply      -= _value;
            // BK NOTE - Suggested logging of this operation
            // Transfer(msg.sender, 0x0, _value);
        }
    }
}

/**
 * @title Asset recipient interface
 */
contract Recipient {
    /**
     * @dev On received ethers
     * @param sender Ether sender
     * @param amount Ether value
     */
    event ReceivedEther(address indexed sender,
                        uint256 indexed amount);

    /**
     * @dev On received custom ERC20 tokens
     * @param from Token sender
     * @param value Token value
     * @param token Token contract address
     * @param extraData Custom additional data
     */
    event ReceivedTokens(address indexed from,
                         uint256 indexed value,
                         address indexed token,
                         bytes extraData);

    /**
     * @dev Receive approved ERC20 tokens
     * @param _from Spender address
     * @param _value Transaction value
     * @param _token ERC20 token contract address
     * @param _extraData Custom additional data
     */
    // BK TOCHECK - How will this work?
    function receiveApproval(address _from, uint256 _value,
                             ERC20 _token, bytes _extraData) {
        if (!_token.transferFrom(_from, this, _value)) throw;
        ReceivedTokens(_from, _value, _token, _extraData);
    }

    /**
     * @dev Catch sended to contract ethers
     */
    // BK TOCHECK - Does this contract have the ability to withdraw sent ETH?
    function () payable
    { ReceivedEther(msg.sender, msg.value); }
}

/**
 * @title Crowdfunding contract
 */
contract Crowdfunding is Object, Recipient {
    /**
     * @dev Target fund account address
     */
    address public fund;

    /**
     * @dev Bounty token address
     */
    TokenEmission public bounty;

    /**
     * @dev Distribution of donations
     */
    mapping(address => uint256) public donations;

    /**
     * @dev Total funded value
     */
    uint256 public totalFunded;

    /**
     * @dev Documentation reference
     */
    string public reference;

    /**
     * @dev Crowdfunding configuration
     */
    Params public config;

    struct Params {
        /* start/stop block stamps */
        uint256 startBlock;
        uint256 stopBlock;

        /* Minimal/maximal funded value */
        uint256 minValue;
        uint256 maxValue;

        /**
         * Bounty ratio equation:
         *   bountyValue = value * ratio / scale
         * where
         *   ratio = R - (block - B) / S * V
         *  R - start bounty ratio
         *  B - start block number
         *  S - bounty reduction step in blocks
         *  V - bounty reduction value
         */
        uint256 bountyScale;
        uint256 startRatio;
        uint256 reductionStep;
        uint256 reductionValue;
    }

    /**
     * @dev Calculate bounty value by reduction equation
     * @param _value Input donation value
     * @param _block Input block number
     * @return Bounty value
     */
    // BK TOCHECK - This function will be overloaded
    function bountyValue(uint256 _value, uint256 _block) constant returns (uint256) {
        if (_block < config.startBlock || _block > config.stopBlock)
            return 0;

        var R = config.startRatio;
        var B = config.startBlock;
        var S = config.reductionStep;
        var V = config.reductionValue;
        // BK NOTE - For better accuracy:
        //    uint256 ratio = R - ((_block - B) * V / S);
        uint256 ratio = R - (_block - B) / S * V;
        return _value * ratio / config.bountyScale;
    }

    /**
     * @dev Crowdfunding running checks
     */
    modifier onlyRunning {
        bool isRunning = totalFunded + msg.value <= config.maxValue
                      && block.number >= config.startBlock
                      && block.number <= config.stopBlock;
        if (!isRunning) throw;
        _;
    }

    /**
     * @dev Crowdfundung failure checks
     */
    modifier onlyFailure {
        bool isFailure = totalFunded  < config.minValue
                      && block.number > config.stopBlock;
        if (!isFailure) throw;
        _;
    }

    /**
     * @dev Crowdfunding success checks
     */
    // BK TOCHECK - This modifier will be overloaded
    modifier onlySuccess {
        bool isSuccess = totalFunded >= config.minValue
                      && block.number > config.stopBlock;
        if (!isSuccess) throw;
        _;
    }

    /**
     * @dev Crowdfunding contract initial
     * @param _fund Destination account address
     * @param _bounty Bounty token address
     * @param _reference Reference documentation link
     * @param _startBlock Funding start block number
     * @param _stopBlock Funding stop block nubmer
     * @param _minValue Minimal funded value in wei
     * @param _maxValue Maximal funded value in wei
     * @param _scale Bounty scaling factor by funded value
     * @param _startRatio Initial bounty ratio
     * @param _reductionStep Bounty reduction step in blocks
     * @param _reductionValue Bounty reduction value
     * @notice this contract should be owner of bounty token
     */
    function Crowdfunding(
        address _fund,
        address _bounty,
        string  _reference,
        uint256 _startBlock,
        uint256 _stopBlock,
        uint256 _minValue,
        uint256 _maxValue,
        uint256 _scale,
        uint256 _startRatio,
        uint256 _reductionStep,
        uint256 _reductionValue
    ) {
        fund      = _fund;
        bounty    = TokenEmission(_bounty);
        reference = _reference;

        config.startBlock     = _startBlock;
        config.stopBlock      = _stopBlock;
        config.minValue       = _minValue;
        config.maxValue       = _maxValue;
        config.bountyScale    = _scale;
        config.startRatio     = _startRatio;
        config.reductionStep  = _reductionStep;
        config.reductionValue = _reductionValue;
    }

    /**
     * @dev Receive Ether token and send bounty
     */
    // BK TOCHECK - This function is overloaded and not used
    function () payable onlyRunning {
        ReceivedEther(msg.sender, msg.value);

        totalFunded           += msg.value;
        donations[msg.sender] += msg.value;

        var bountyVal = bountyValue(msg.value, block.number);
        if (bountyVal == 0) throw;

        bounty.emission(bountyVal);
        bounty.transfer(msg.sender, bountyVal);
    }

    /**
     * @dev Withdrawal balance on successfull finish
     */
    // BK TOCHECK - This function is overloaded
    function withdraw() onlySuccess
    { if (!fund.send(this.balance)) throw; }

    /**
     * @dev Refund donations when no minimal value achieved
     */
    // BK NOTE - Investors may not be able to withdraw their refunds if the owner has withdrawn the ETH
    function refund() onlyFailure {
        var donation = donations[msg.sender];
        donations[msg.sender] = 0;
        if (!msg.sender.send(donation)) throw;
    }

    /**
     * @dev Disable receive another tokens
     */
    // BK NOTE - This will not stop the sending of ERC20 tokens that do not implement the `receiveApproval(...)` check
    function receiveApproval(address _from, uint256 _value,
                             ERC20 _token, bytes _extraData)
    { throw; }
}

contract DaoCasinoICO is Crowdfunding {
    /**
     * @dev Crowdfunding contract initial
     * @param _fund Destination account address
     * @param _bounty Bounty token address (erc20 with emission function)
     * @param _reference Reference documentation link
     * @param _startBlock Funding start block number
     * @param _stopBlock Funding stop block nubmer
     * @param _minValue Minimal funded value in wei
     * @param _maxValue Maximal funded value in wei
     * @param _scale Bounty scaling factor by funded value
     * @param _startRatio Initial bounty ratio
     * @param _reductionStep Bounty reduction step in blocks
     * @param _reductionValue Bounty reduction value
     * @notice this contract should be owner of bounty token
     */
    function DaoCasinoICO(
        address _fund,
        address _bounty,
        string  _reference,
        uint256 _startBlock,
        uint256 _stopBlock,
        uint256 _minValue,
        uint256 _maxValue,
        uint256 _scale,
        uint256 _startRatio,
        uint256 _reductionStep,
        uint256 _reductionValue,
        uint256 _minDonation
    ) Crowdfunding(_fund, _bounty, _reference, _startBlock, _stopBlock, _minValue, _maxValue, _scale, _startRatio, _reductionStep, _reductionValue) {
        minDonation = _minDonation;
    }

    /**
     * @dev Receive Ether token and charge bounty
     */
    function () payable onlyRunning {
        // Minimal donation check
        if (msg.value < minDonation) throw;

        ReceivedEther(msg.sender, msg.value);

        totalFunded           += msg.value;
        donations[msg.sender] += msg.value;

        var bountyVal = bountyValue(msg.value, block.number);
        var bountySupply = bounty.totalSupply();

        // Bounty emission for crowdfunding contract
        //   is needed for bounty totalSupply accounting
        bounty.emission(bountyVal);

        // Correct emission check, result should be more
        if (bountySupply == bounty.totalSupply()) throw;

        // Append new participant
        if (bounties[msg.sender] == 0)
            participants.push(msg.sender);

        // Charge bounties
        bounties[msg.sender] += bountyVal;
    }

    // ONLY FOR 16.44s block time
    uint256 public constant BLOCKS_IN_DAY = 5256;

    uint256 public minDonation;

    /**
     * @dev Calculate bounty value by static equation
     * @param _value Input donation value
     * @param _block Input block number
     * @return Bounty value
     */
    function bountyValue(uint256 _value, uint256 _block) constant returns (uint256) {
        uint256 ratio = 0;
        uint256 start = config.startBlock;

        // 1st day bounty
        if (_block >= start && _block < start + BLOCKS_IN_DAY)
            ratio = 2000;

        // [2; 15) day bounty
        if (_block >= start + BLOCKS_IN_DAY && _block < start + 15*BLOCKS_IN_DAY)
            ratio = 1800;

        // [15; 18) day bounty
        if (_block >= start + 15*BLOCKS_IN_DAY && _block < start + 18*BLOCKS_IN_DAY)
            ratio = 1700;

        // [18; 21) day bounty
        if (_block >= start + 18*BLOCKS_IN_DAY && _block < start + 21*BLOCKS_IN_DAY)
            ratio = 1600;

        // [21; 23) day bounty
        if (_block >= start + 21*BLOCKS_IN_DAY && _block < start + 23*BLOCKS_IN_DAY)
            ratio = 1500;

        // [23; 26) day bounty
        if (_block >= start + 23*BLOCKS_IN_DAY && _block < start + 26*BLOCKS_IN_DAY)
            ratio = 1400;

        // [26; 29) day bounty
        if (_block >= start + 26*BLOCKS_IN_DAY && _block <= config.stopBlock)
            ratio = 1300;

        return _value * ratio / config.bountyScale;
    }

    /**
     * @dev Crowdfunding success checks
     */
    modifier onlySuccess {
        bool isSuccess = totalFunded >= config.minValue
                      && block.number > config.stopBlock
                      || totalFunded == config.maxValue;
        if (!isSuccess) throw;
        _;
    }

    /**
     * @dev Withdrawal Ethereum balance
     */
    // BK NOTE - Owner will be able to withdraw ETH at any time, even if the crowdsale does not reach the minimum funding level and investors are due for refunds
    function withdrawEth() onlyOwner {
        if (!fund.send(this.balance)) throw;
    }

    /**
     * @dev 30% emission on success
     */
    function withdraw() onlySuccess {
        if (withdrawDone) throw;
        withdrawDone = true;

        var bountyVal = bounty.totalSupply() * 30 / 70;
        bounty.emission(bountyVal);
        if (!bounty.transfer(fund, bountyVal)) throw;
    }

    bool withdrawDone = false;
    mapping(address => uint256) public bounties;
    address[] public participants;

    /**
     * @dev Transfer paritication bounty for account
     * @param _participant Account address
     */
    function getBounty(address _participant) onlySuccess {
        var bountyVal = bounties[_participant];
        if (bountyVal == 0) throw;

        bounties[_participant] = 0;
        if (!bounty.transfer(_participant, bountyVal)) throw;
    }

    /**
     * @dev Simple way to get sender account bounty
     */
    function getMyBounty() { getBounty(msg.sender); }
}
```


text:
# WonderQ: Message Broker

My implementation of a message broker. Messages can be created, fetched and confirmed as processed. However if the confirmation does not happen within a specific amount of time, the message is re-entered into of the queue.

### Prerequisites

Node.js
Run `yarn`
Then `yarn dev`

## Running the tests

Run `yarn test`

## Code cleanup
Run `yarn lint:fix`

## API

## Service Endpoints

* `GET /v1/messages/`
* `POST /message/`
* `PUT /messages/confirm/`

## Docs
Run `yarn docs` to generate docs.
Then open `index.html` on the `docs/` folder that will be created in the root folder as a result of the command.

## Built With

* [Node.js](https://nodejs.org/en/)
* [TypeScript](https://www.typescriptlang.org/)

repository: IsraelGboluwaga/WQ

repo_name: IsraelGboluwaga/WQ


text:
## E 12
**pasta**
Hey, Diane, **What have you been up to**?
Well, I'm just **weighing my options**.
I think I'm having a **epiphany**.

## E 11
What do you say we go on an epic **bender**?
booing is generally **frowned upon** here.
Let's make some **amends**
That movie star has really **taken a shine to** our boy.
If by "**closure**" you mean I **lit** her **ottoman** on fire, then yes.
so we decided to do a **stakeout**
at night, she is a **high end** **call girl**, and by day, she's an international **superspy**.
It's a **rarefied breed**, man, Congratulations!
The people who **glom onto** you, because of who they think you are, and think they can sleep on your couch and eat your food.
**planetarium**
in a grand universe, we're just one tiny **speck**

## E 10
unfortunately, we have to **scale back** our staff
there is a **drought**
I'll go back to being another **cog** in the giant **Play-Doh** **spaghetti** maker that is this industry.

## E 9
It's already an **overused** **trope** now, in 2007.
can you be **wistful** a little quieter?
**bygones**
Luis Guzman said I'm too **portly** for TV?
Is there a single woman you've worked with who you haven't tried to **groggily** thrust yourself into?
Is there **any wonder** I don't want to be around you?
Please, you're such a **self-pitying** **masochist**
I'm good at driving **sober**, but I don't **relish** the opportunity.

## E 8
Rutabaga, do you think we have the **spunk** and **moxie**?
I've been telling people I didn't need the **trappings of fame**.
that's an **untapped market**
He is probably just **razzing** ya, but he's a good dog.
It's a **coming-of-age** story about a girl who likes **Jellybeans**.
The movie I want to make isn't **glamorous** or sexy.

Gonna **tie this up** tonight if it's going to happen.

That **fell apart**, too.
If things don't **perk up** the first quarter, we might be looking at **broader** layoffs.
I've been **tied up** with my studies

## E 7
He is pretty **steamed**
We do have an **infestation**, of Todds, look at that, they're getting bigger.
Did the head help to **ameliorate** your pest **peccadillo**?
Do you often **keep people at arm's length**?
So you don't feel any guilt about your **tryst** with Emily?
I knew I had to **lay low**. **Go off the grid**, disappear.

## E 6
A **streetwise** but **soulful** teen needed somewhere to live as he waited for his Juliliard **audition**.
that **takes me back**.
Just pick out something extra soft for my **tushy**.

Obviously, we'll **pre-tape** it.
I'm **making things all about me**? I'm the one who's having an abortion.
I gotta take the **high road**, go on the news and **rat those suckers out**.
Is somebody standing in my **windpipe**?
A little **queasy**, but **on the whole**, wonderful.

Let's not waste each other's time and **cut right to the chase**.

## E 4
**pantomime**
**panto**

## E2 & E 3

## E 1
**Keep it down**, buddy.
**you betcha**
we got **skunked**.
I didn't know you were such a **klepto**. I can buy you a new phone.
I'm **on the clock**, you want to chat, you need to buy me a private dance in the **Blowhole** Room.
**Thar she blows, then thar she goes**. - Shit.
Doesn't **ring the bell**, hasn't met this guy.
> A system is a **formulated** method or plan of procedure.

I will not going to **spill more beans**.
I am just trying to **get through** each day.
All those **perky**, **well-adjusted** people you see in movies and TV shows?
because to you my face is a symbol for the **opiate** of show business
this going to be a really **caper**
I turned my home into a **halfway** house for troubled addicts.
but then more **slipped through the cracks**.


text:
You can build Vitess using either [Docker](#docker-build) or a
[manual](#manual-build) build process.

If you run into issues or have questions, please post on our
[forum](https://groups.google.com/forum/#!forum/vitess).

## Docker Build

To run Vitess in Docker, use an
[Automated Build](https://registry.hub.docker.com/repos/vitess/).

* The vitess/base image contains a full development
  environment, capable of building Vitess and running integration tests.
* The vitess/lite image contains only the compiled Vitess
  binaries, excluding ZooKeeper. it can run Vitess, but lacks the
  environment needed to build Vitess or run tests.

You can also build Vitess Docker images yourself to include your
own patches or configuration data. The
[Dockerfile](https://github.com/youtube/vitess/blob/master/Dockerfile)
in the root of the Vitess tree builds the vitess/base image.
The [docker](https://github.com/youtube/vitess/tree/master/docker)
subdirectory contains scripts for building other images.

## Manual Build

The following sections explain the process for manually building
Vitess on a local server:

-    [Install Dependencies](#install-dependencies)
-    [Build Vitess](#build-vitess)
-    [Test Your Vitess Cluster](#test-your-vitess-cluster)
-    [Start a Vitess Cluster](#start-a-vitess-cluster)
-    [Run a Client Application](#run-a-client-application)
-    [Tear Down the Cluster](#tear-down-the-cluster)

### Install Dependencies

Vitess runs on either Ubuntu 14.04 (Trusty) or Debian 7.0 (Wheezy). It requires the software and libraries listed below.

1.  [Install Go 1.3+](http://golang.org/doc/install).

2.  Install [MariaDB 10.0](https://downloads.mariadb.org/) or
    [MySQL 5.6](http://dev.mysql.com/downloads/mysql). You can use any
    installation method (src/bin/rpm/deb), but be sure to include the client
    development headers (**libmariadbclient-dev** or **libmysqlclient-dev**).

    The Vitess development team currently tests against MariaDB 10.0.17
    and MySQL 5.6.24.

    If you are installing MariaDB, note that you must install version 10.0 or
    higher. If you are using apt-get, confirm that your repository
    offers an option to install that version. You can also download the source
    directly from [mariadb.org](https://downloads.mariadb.org/mariadb/10.0.16/).

3.  Select a lock service from the options listed below. It is technically
    possible to use another lock server, but plugins currently exist only
    for ZooKeeper and etcd.
    - ZooKeeper 3.3.5 is included by default.
    - [Install etcd v2.0+](https://github.com/coreos/etcd/releases).
      If you use etcd, remember to include the etcd command
      on your path.

4.  Install the following other tools needed to build and run Vitess:
    - make
    - automake
    - libtool
    - memcached
    - python-dev
    - python-virtualenv
    - python-mysqldb
    - libssl-dev
    - g++
    - mercurial
    - git
    - pkg-config
    - bison
    - curl
    - unzip

    These can be installed with the following apt-get command:

    ``` sh
sudo apt-get install make automake libtool memcached python-dev python-virtualenv python-mysqldb libssl-dev g++ mercurial git pkg-config bison curl unzip
```

5.  If you decided to use ZooKeeper in step 3, you also need to install a
    Java Runtime, such as OpenJDK.

    ``` sh
      sudo apt-get install openjdk-7-jre</pre>
```

### Build Vitess

1.  Navigate to the directory where you want to download the Vitess
    source code and clone the Vitess Github repo. After doing so,
    navigate to the **src/github.com/youtube/vitess** directory.

    ``` sh
cd $WORKSPACE
git clone https://github.com/youtube/vitess.git src/github.com/youtube/vitess
cd src/github.com/youtube/vitess
```

1.  Set the **MYSQL_FLAVOR** environment variable. Choose the appropriate
    value for your database. This value is case-sensitive.

    ``` sh
export MYSQL_FLAVOR=MariaDB
or
export MYSQL_FLAVOR=MySQL56
```

1.  If your selected database installed in a location other than **/usr/bin**,
    set the **VT_MYSQL_ROOT** variable to the root directory of your
    MariaDB installation. For example, if MariaDB is installed in
    **/usr/local/mysql**, run the following command.

    ``` sh
export VT_MYSQL_ROOT=/usr/local/mysql
```

    Note that the command indicates that the **mysql** executable should
    be found at **/usr/local/mysql/bin/mysql**.

1.  Run mysql_config --version and confirm that you
    are running the correct version of MariaDB or MySQL. The value should
    be 10 or higher for MariaDB and 5.6.x for MySQL.

1.  Build Vitess using the commands below. Note that the
    bootstrap.sh script needs to download some dependencies.
    If your machine requires a proxy to access the Internet, you will need
    to set the usual environment variables (e.g. http_proxy,
    https_proxy, no_proxy).

    ``` sh
./bootstrap.sh
# Output of bootstrap.sh is shown below
# skipping zookeeper build
# go install golang.org/x/tools/cmd/cover ...
# Found MariaDB installation in ...
# skipping bson python build
# skipping cbson python build
# creating git pre-commit hooks
#
# source dev.env in your shell before building
# Remaining commands to build Vitess
. ./dev.env
make build
```

    If you build Vitess successfully, you can proceed to
    [start a Vitess cluster](#start-a-vitess-cluster).
    If your build attempt fails, see the following section,
    [Test your Vitess Cluster](#test-your-vitess-cluster), for help
    troubleshooting the errors.

### Test your Vitess Cluster

**Note:** If you are using etcd, set the following environment variable:

``` sh
export VT_TEST_FLAGS='--topo-server-flavor=etcd'
```

The default _make_ and _make test_ targets contain a full set of tests
intended to help Vitess developers to verify code changes. Those tests
simulate a small Vitess cluster by launching many servers on the local
machine. To do so, they require a lot of resources; a minimum of 8GB RAM
and SSD is recommended to run the tests.

If you want only to check that Vitess is working in your environment,
you can run a lighter set of tests:

``` sh
make site_test
```

#### Common Test Issues

Attempts to run the full developer test suite (_make_ or _make test_)
on an underpowered machine often results in failure. If you still see
the same failures when running the lighter set of tests (*make site_test*),
please let the development team know in the
[vitess@googlegroups.com](https://groups.google.com/forum/#!forum/vitess)
discussion forum.

##### Node already exists, port in use, etc.

A failed test can leave orphaned processes. If you use the default
settings, you can use the following commands to identify and kill
those processes:

``` sh
pgrep -f -l '(vtdataroot|VTDATAROOT)' # list Vitess processes
pkill -f '(vtdataroot|VTDATAROOT)' # kill Vitess processes
```

##### Too many connections to MySQL, or other timeouts

This error often means your disk is too slow. If you don't have access
to an SSD, you can try [testing against a
ramdisk](https://github.com/youtube/vitess/blob/master/doc/TestingOnARamDisk.md).

##### Connection refused to tablet, MySQL socket not found, etc.

These errors might indicate that the machine ran out of RAM and a server
crashed when trying to allocate more RAM. Some of the heavier tests
require up to 8GB RAM.

##### Connection refused in zkctl test

This error might indicate that the machine does not have a Java Runtime
installed, which is a requirement if you are using ZooKeeper as the lock server.

##### Running out of disk space

Some of the larger tests use up to 4GB of temporary space on disk.

### Start a Vitess cluster

After completing the instructions above to [build Vitess](#build-vitess),
you can use the example scripts in the Github repo to bring up a Vitess
cluster on your local machine. These scripts use ZooKeeper as the
lock service. ZooKeeper is included in the Vitess distribution.

1.  **Check system settings**

    Some Linux distributions ship with default file descriptor limits
    that are too low for database servers. This issue could show up
    as the database crashing with the message "too many open files".

    Check the system-wide `file-max` setting as well as user-specific
    `ulimit` values. We recommend setting them above 100K to be safe.
    The exact [procedure](http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/)
     may vary depending on your Linux distribution.

1.  **Configure environment variables**

    If you are still in the same terminal window that
    you used to run the build commands, you can skip to the next
    step since the environment variables will already be set.

    Navigate to the directory where you built Vitess
    (**$WORKSPACE/src/github.com/youtube/vitess**) and run the
    following command:

    ``` sh
. ./dev.env
```

    From that directory, navigate to the directory that contains
    the example scripts:

    ``` sh
cd examples/local
```

1.  **Start ZooKeeper**

    Servers in a Vitess cluster find each other by looking for
    dynamic configuration data stored in a distributed lock
    service. The following script creates a small ZooKeeper cluster:

    ``` sh
./zk-up.sh
# Starting zk servers...
# Waiting for zk servers to be ready...
```

    After the ZooKeeper cluster is running, we only need to tell each
    Vitess process how to connect to ZooKeeper. Then, each process can
    find all of the other Vitess processes by coordinating via ZooKeeper.

    To instruct Vitess processes on how to connect to ZooKeeper, set
    the ZK_CLIENT_CONFIG environment variable to the path
    to the zk-client-conf.json file, which contains the
    ZooKeeper server addresses for each cell.

1.  **Start vtctld**

    The vtctld server provides a web interface that
    displays all of the coordination information stored in ZooKeeper.

    ``` sh
./vtctld-up.sh
# Starting vtctld
# Access vtctld at http://localhost:15000
```

    Open http://localhost:15000 to verify that
    vtctld is running. There won't be any information
    there yet, but the menu should come up, which indicates that
    vtctld is running.

    **Note:** The vtctld server accepts commands from
    the vtctlclient tool, which administers the Vitess
    cluster. The following command lists the commands that
    vtctlclient supports:

    ``` sh
$VTROOT/bin/vtctlclient -server localhost:15000
```

1.  **Start vttablets**

    The following command brings up three vttablets. Bringing up
    tablets in a previously empty keyspace effectively creates
    a new shard.

    ``` sh
./vttablet-up.sh
# Output from vttablet-up.sh is below
# Starting MySQL for tablet test-0000000100...
# Starting vttablet for test-0000000100...
# Access tablet test-0000000100 at http://localhost:15100/debug/status
# Starting MySQL for tablet test-0000000101...
# Starting vttablet for test-0000000101...
# Access tablet test-0000000101 at http://localhost:15101/debug/status
# Starting MySQL for tablet test-0000000102...
# Starting vttablet for test-0000000102...
# Access tablet test-0000000102 at http://localhost:15102/debug/status
```

    After this command completes, go back to the vtctld
    web page from the previous step and click the **Topology** link.
    You should see the three tablets listed. If you click the address
    of a tablet, you will see the coordination data stored in ZooKeeper.
    From there, if you click the **status** link at the top of the page,
    you will see the debug page generated by the tablet itself.

1.  **Initialize a keyspace for the shard**

    Perform a keyspace rebuild to initialize the keyspace for the
    new shard:

    ``` sh
$VTROOT/bin/vtctlclient -server localhost:15000 RebuildKeyspaceGraph test_keyspace
```

    **Note:** Most vtctlclient commands yield no output if
    they run successfully.

1.  **Elect a master vttablet**

    The vttablet servers are all started as replicas.
    In this step, you designate one of the vttablets to be the master.
    Vitess automatically connects the other replicas' mysqld
    instances so that they start replicating from the master
    mysqld instance.

    Since this is the first time the shard has been started, the
    vttablets are not already doing any replication. As a result,
    the following command uses the -force flag when
    calling the InitShardMaster command so that it
    accepts the change of a replica to be the master.

    ``` sh
$VTROOT/bin/vtctlclient -server localhost:15000 InitShardMaster -force test_keyspace/0 test-0000000100
```

    After running this command, go back to the **Topology** page
    in the vtctld web interface. When you refresh the
    page, you should see that one vttablet is the master
    and the other two are replicas.

    You can also run this command on the command line to see the
    same data:

    ``` sh
$VTROOT/bin/vtctlclient -server localhost:15000 ListAllTablets test
# The command's output is shown below:
# test-0000000100 test_keyspace 0 master localhost:15100 localhost:33100 []
# test-0000000101 test_keyspace 0 replica localhost:15101 localhost:33101 []
# test-0000000102 test_keyspace 0 replica localhost:15102 localhost:33102 []
```

1.  **Create a table**

    Create the database table defined in the createtesttable.sql
    file.

    ``` sh
$VTROOT/bin/vtctlclient -server localhost:15000 ApplySchema -sql "$(cat create_test_table.sql)" test_keyspace
```

    The SQL to create the table is shown below:

    ``` sh
CREATE TABLE test_table (
  id BIGINT AUTO_INCREMENT,
  msg VARCHAR(250),
  PRIMARY KEY(id)
) Engine=InnoDB
```

1.  **Start vtgate**

    Vitess uses vtgate to route each client query to
    the correct vttablet. This local example runs a
    single vtgate instance, though a real deployment
    would likely run multiple vtgate instances to share
    the load.

    ``` sh
./vtgate-up.sh
```

### Run a Client Application

The client.py file is a simple sample application
that connects to vtgate and executes some queries.
To run it, you need to either:

* Add the Vitess Python packages to your PYTHONPATH

  or
* Use the client.sh wrapper script, which temporarily
  sets up the environment and then runs client.py

    ``` sh
./client.sh --server=localhost:15001
# Output from client.sh is shown below
# Inserting into master...
# Reading from master...
# (1L, 'V is for speed')
# Reading from replica...
# (1L, 'V is for speed')
```

### Tear down the cluster

As long as your VTDATAROOT directory is only used
for this test, you can kill the processes created during this
test with the following commands:

``` sh
# Look for processes started during the test
$ pgrep -u $USER -f -l $VTDATAROOT

# If the list looks correct, kill the processes
$ pkill -u $USER -f $VTDATAROOT
```

Repeat the pgrep command to make sure all processes
have been killed and manually kill any remaining processes.

Also clear out the contents of VTDATAROOT before
starting again:

``` sh
$ cd $VTDATAROOT
$ /path/to/vtdataroot$ rm -rf *
```

repository: atyenoria/vitess

repo_name: atyenoria/vitess


text:
---
name: "\U0001F41B Bug Report"
labels: "bug"
about: Something isn't working as expected

---

## Bug Report

Please answer these questions before submitting your issue. Thanks!

1. What did you do? If possible, provide a recipe for reproducing the error.

2. What did you expect to see?

3. What did you see instead?

4. Versions of the failpoint

    - failpoint-ctl version (run `failpoint-ctl -V`):

        ```
        (paste failpoint-ctl version here)
        ```

repository: pingcap/failpoint

repo_name: pingcap/failpoint


text:
# MotionBuilderSublime
### A Sublime Text 2/3 plugin.

Send selected Python code snippets or whole files from SublimeText to MotionBuilder via telnet.

----------

### Installation

**Easy Install**

You can install this plugin directly from Sublime Package Control:

https://packagecontrol.io/packages/MotionBuilder

Note: Due to current naming policies, the listed package name is ```MotionBuilder``` - not ```MotionBuilderSublime```.

**Manual Install**

1. clone this repo into the `SublimeText2/3 -> Preference -> Browse Packages` directory:
`git clone git://github.com/matthewkapfhammer/MotionBuilderSublime.git`

2. Edit the `MotionBuilderSublime.sublime-settings` file, setting the port to match the commandPorts you have configured in MotionBuilder.

3. Optionally edit the keymap file to change the default hotkey from ctrl+alt+shift+return to something else.

Note: Ideally you would make your custom changes to the user settings and not the default settings, so that they do not get overwritten when the plugin is updated.

### Usage

To send a snippet, simply select some code in a Python script, and hit ctrl+alt+shift+return, or right click and choose "Send To MotionBuilder".
A telnet connection will be made to a running MotionBuilder instance on the configured port matching Python, and the code will be run in MotionBuilder's environment.

### Beyond The Plugin

The function that sends a Python command to MotionBuilder can also be used in any external application.

See ```MotionBuilderSublime.py``` -> ```telnet_write```

### Credits

MotionBuilderSublime is inspired by and primarily based on [MayaSublime] (https://github.com/justinfx/MayaSublime) by [Justin Israel] (https://github.com/justinfx).

Additional credit belongs to [Chris Evans] (https://github.com/chrisevans3d) for sharing how to handle a telnet connection to MotionBuilder in his blog post, [Creating Interactive MotionBuilder User Interface Tools] (http://www.chrisevans3d.com/pub_blog/creating-interactive-motionbuilder-user-interface-tools/).

repository: matthewkapfhammer/MotionBuilderSublime

repo_name: matthewkapfhammer/MotionBuilderSublime


text:
# Postmark Ruby Gem
[![Build Status](https://circleci.com/gh/wildbit/postmark-gem.svg?style=shield)](https://circleci.com/gh/wildbit/postmark-gem)
[![Code Climate](https://codeclimate.com/github/wildbit/postmark-gem/badges/gpa.svg)](https://codeclimate.com/github/wildbit/postmark-gem)
[![License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](http://www.opensource.org/licenses/MIT)
[![Gem Version](https://badge.fury.io/rb/postmark.svg)](https://badge.fury.io/rb/postmark)

Postmark allows you to send your emails with high delivery rates. It also includes detailed statistics. In addition, Postmark can parse incoming emails which are forwarded back to your application.

This gem is the official wrapper for the [Postmark HTTP API](http://postmarkapp.com).

## Usage

Please see the [wiki](https://github.com/wildbit/postmark-gem/wiki) for detailed instructions about sending email, using the bounce api and other Postmark API features.
For details about Postmark API in general, please check out [Postmark developer docs](https://postmarkapp.com/developer).

## Requirements

You will need a Postmark account, server and sender signature (or verified domain) set up to use it. For details about setup, check out [wiki pages](https://github.com/wildbit/postmark-gem/wiki/Getting-Started).

If you plan using the library in a Rails project, check out the [postmark-rails](https://github.com/wildbit/postmark-rails/) gem, which
is meant to integrate with ActionMailer. The plugin will try to use ActiveSupport JSon if it is already included. If not,
it will attempt to use the built-in Ruby JSon library.

You can also explicitly specify which one to be used, using following code:

``` ruby
Postmark.response_parser_class = :Json # :ActiveSupport or :Yajl are also supported.
```

## Installation

You can use the library with or without a Bundler.

With Bundler:

``` ruby
gem 'postmark'
```

Without Bundler:

``` bash
gem install postmark
```

## Note on Patches/Pull Requests

See [CONTRIBUTING.md](CONTRIBUTING.md) file for details.

## Issues & Comments

Feel free to contact us if you encounter any issues with the library or Postmark API.
Please leave all comments, bugs, requests and issues on the Issues page.

## License

The Postmark Ruby library is licensed under the [MIT](http://www.opensource.org/licenses/mit-license.php) license.
Refer to the [LICENSE](https://github.com/wildbit/postmark-gem/blob/master/LICENSE) file for more information.

## Copyright

Copyright © 2021 Wildbit LLC.

repository: pinklite/postmark-gem

repo_name: pinklite/postmark-gem


text:
# NikoSDK

Niko Home Control SDK for .NET Standard

## Status

| Target | Branch | Status | SonarCloud | Package version |
|--------------|------------- | --------- | --------| --------|
| Release | master |  |  |  |
| Preview | develop | |  |  |

## Usage
### Client instantiation

You can use the autodetect static method :
```
var client = NikoClient.AutoDetect();
```

Or pass the IP of the NHC :
```
var client = new NikoClient("<IP_ADDRESS>");
```
### Start client

To start the client, use :

```
client.StartClient();
```

### Stop client

To stop the client, use :

```
client.StopClient();
```

### Locations

To get the locations, use :

```
var locations = await client.GetLocations();
```

### Actions

To get the actions, use :

```
var actions = await client.GetActions();
```

### Execute Command

To execute an action, use :

```
var result = await client.ExecuteCommand(int id, int value);
```

Value is from 0 to 100, and you can get action id from the action list

### Events

To receive events like status change:

```
await client.StartEvents();
client.OnValueChanged += _nikoClient_OnValueChanged;

private void _nikoClient_OnValueChanged(object sender, IEvent e)
{
    ...
}
```

## Models

If you want to use the model for a client application, there is this nuget package :

Net.ArcanaStudio.NikoSDK.Model

## Limitations

It wasn't tested on NHC II

As I don't have alarm or energy modules, there is not command for it.
If someone can give the their json format, I will implement it.

## History

1.1.0
-Added : Unit tests
- FIXED : Bugs
- CHANGE : Refactoring

1.0.3
- FIXED : Values sometimes not well returned from server
- CHANGE : Action's Location property renamed to LocationId

1.0.2
- FIXED : Case when multiple messages received same time

1.0.1:
- FIXED : bug when sometimes NHC send extra characters at the end of json

1.0
- Initial release

## License

```
Copyright 2019 Arcana Studio

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```

repository: Guruumeditation/NikoSDK

repo_name: Guruumeditation/NikoSDK


text:
## Templates

Rendering templates is going to become a two-step process:
  1. parse the template via regexps and replace values (the way we're currently doing it)
  2. walk the node tree to setup bindings and replace values

I can't say that I exactly love the idea of essentially running through each template twice, but it's better to me than moving all the logic into HTML attributes. Plus, it seems to me that the templates should be able to be used for things other than just HTML (if one wanted to)

So, a template with bindings, logic, and interpolation might look something like this:

```html
<script id="user-template" type="leverage/bound-template">
  <div data-if="//logic goes here, maybe?">
      <span data-bind="user.fullName()"/>
      <input data-bind-value="user.firstName : onkeyup">
      <input data-bind-value="user.lastName : onkeyup">
  </div>
</script>
```

And a template that doesn't need any binding could look like this:
```html
<script id="user-template" type="leverage/template">
  <div>
    <span>{= user.fullName() =}</span>
  </div>
</script>
```

I can't decide, however, whether I like the above binding sytax better than this other option:
```html
<script id="user-template" type="leverage/bound-template">
  <div>
    <span data-bind="user.fullName()"/>
    <input data-bind-value="user.firstName:onkeyup">
    <input data-bind-value="user.lastName:onkeyup">
  </div>
</script>
```

The nice thing about that syntax is that walking the node tree could potentially be much faster. Honestly, though, it's kind of ugly, so I'm not exactly sure how I feel about that second binding option.


text:
---
layout: post
title: '812. Largest Triangle Area'
subtitle: ''
date: 2019-09-03
categories: Leetcode
tags: Leetcode Math Array
---
### [812\. Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area/)

Difficulty: **Easy**

Topics: **Math**

You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.

```
Example:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
```

![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/04/1027.png)

**Notes:**

*   `3 <= points.length <= 50`.
*   No points will be duplicated.
*   `-50 <= points[i][j] <= 50`.
*   Answers within `10^-6` of the true value will be accepted as correct.

#### Solution

Language: **Python**

```python
class Solution(object):
    def largestTriangleArea(self, points):
        """
        :type points: List[List[int]]
        :rtype: float
        """
        return max(0.5 * abs(i[0] * j[1] + j[0] * k[1] + k[0] * i[1]- j[0] * i[1] - k[0] * j[1] - i[0] * k[1]) for i, j, k in itertools.combinations(points, 3))
```

#### Notes
- brute force, time complexity: O(N^3)
![](https://s3-lc-upload.s3.amazonaws.com/users/lee215/image_1523209147.png)
![](https://s3-lc-upload.s3.amazonaws.com/users/lee215/image_1523379988.png)

gha_language: HTML