text:
# azmi

![GitHub](https://img.shields.io/github/license/sre-prg/azmitool)
![GitHub release (latest by date)](https://img.shields.io/github/v/release/SRE-PRG/azmitool?style=plastic)
![GitHub Release Date](https://img.shields.io/github/release-date/sre-prg/azmitool)

## Description

Azure Managed Identity tool -  **azmi** - is application designed to run at Command-line interface (CLI) inside Azure Linux Virtual Machines (VM) which simplifies authentication to Azure resources.

Using VM with assigned Managed Identity and azmi installed you can easily authenticate against Azure services like Key Vault (download secrets to VM), Storage Account (download/upload files from VM into Azure container = become blobs), etc.

## Examples

```bash
# get token from Azure infrastructure
azmi gettoken

# list all blobs in a container
azmi listblobs --container $CONTAINER_URL

# download blob from a storage account container and save to a file
azmi getblob --blob $BLOB_URL --file $FILE

# download blobs from a storage account container and save them to folder
azmi getblobs --container $CONTAINER_URL --directory ./downloadBlobsHere

# upload file by specifying blob url and identity
azmi setblob --file ~/info.txt --blob $CONTAINER_URL/myhostname/info.txt --identity 117dc05c-4d12-4ac2-b5f8-5e239dc8bc54

# fetch latest or specific version of a secret from Azure Key Vault
azmi getsecret --secret $SECRET_URL
azmi getsecret --secret $SECRET_URL/$VERSION

# fetch latest or specific version of a certificate(s) and private key bundle from Azure Key Vault
azmi getcertificate --certificate $CERTIFICATE_URL
azmi getcertificate --certificate $CERTIFICATE_URL/$VERSION
```

For more explanations, see detailed [commands overview](./Commands.md).

For more examples, see detailed [examples page](./Examples.md).

## Download

To download executable / package, use following commands:

- executable
```bash
wget https://azmi.blob.core.windows.net/release/azmi
chmod +x azmi
ls azmi -l
./azmi --version
```
P.S. Running azmi executable does not require root privilege.

- Debian package
```bash
wget https://azmi.blob.core.windows.net/release/azmi.deb
ls azmi.deb -l
sudo dpkg -i ./azmi.deb
azmi --version
```

- Windows

Tool `azmi` is built on top of cross-platform dotnet core.
Therefore, there are versions of `azmi` also for Windows.
Read more [here](Windows.md).

## How it works

All Azure authentication is completely transparent for VM user or for a running script.
Authentication is not attached for a user running the command, but actually to VM and its managed identity.
There is no need to keep any secrets in the code or on the system, or to rotate and distribute them.

Azmi is utilizing managed identities to authenticate against Azure AD and obtain access token.
This token is then sent to specified resource together with request for specific action (read/write data).

![azmi - how it works](img/azmi-explanation.png)

For other azmi commands (i.e. setblob) authentication works the same way. The only difference is with request being sent to target resource.

Azmi is not working across different AAD tenants.

Read more:
- [Managed identities for Azure resources](https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview)

## Performance

Because `azmi` is written in c# / dotnet, its performance are dependant on your VM size. On Basic VM sizes, performance will be slower than native Linux commands or tools, like `curl` or `rclone`. We recommend Standard or Compute optimized VM sizes (like F2 or larger) where `azmi` performs better than `curl` tool for example.

`azmi` currently supports only serial communication (sequential). Should you need simultaneous usage consider using multiple instances of `azmi` binary.

## Common errors

By default, `azmi` will display simple, Linux style errors. To discard the error, you can redirect the error stream to null.
To get more verbose error output, use `--verbose` or `-v` switch in command.

### `Missing identity argument`

If your VM has exactly one managed identity, you can omit `--identity` parameter. If it has more than one identity, you must specify it using the same argument.

### `No managed identity endpoint found`

If you run `azmi` on non-Azure VM, you will get the error above.

### `Identity not found`

If you used `--identity` argument, please verify if you used correct client / application ID

### `Failure processing application bundle...`
Full text of an error:
`Failure processing application bundle.
Failed to create directory [/var/tmp/.net/azmi/] for extracting bundled files
A fatal error was encountered. Could not extract contents of the bundle`

You ran `azmi` as a different user in past at your host than current user. Cache for .NET bundle has been created for previous user and can not be re-used.
Either remove cache directory (e.g. `rm -rf /var/tmp/.net/azmi`) or set specific cache directory for your current user like `export DOTNET_BUNDLE_EXTRACT_BASE_DIR="$HOME/cache_dotnet_bundle_extract"`.
For more info, see [github issue at .NET project](https://github.com/dotnet/runtime/issues/3846) which was resolved in .Net Core 3.1.4.

## Support

You can chat about **azmi** or get support for your issues via [Skype](https://www.skype.com) _(no account registration/Skype ID required)_, by clicking a link below.

[![chat on Skype](https://img.shields.io/badge/chat-on%20Skype-blue.svg?style=flat)](https://join.skype.com/bSUkedMmCPwq)

Or, if you want, feel free to [open a new issue](https://github.com/SRE-PRG/azmitool/issues/new/choose).

## Pipeline statuses

| Pipeline | Status | Tests |
|---|---|---|
| Package build | [![Build status](https://skype.visualstudio.com/SCC/_apis/build/status/SE-UP/azmi/build%20-%20azmi)](https://skype.visualstudio.com/SCC/_build/latest?definitionId=8166) |   |
| Integration tests | [![Build status](https://dev.azure.com/iiric/azmi/_apis/build/status/azmi-CI)](https://dev.azure.com/iiric/azmi/_build/latest?definitionId=28) | [![Build details](https://img.shields.io/azure-devops/tests/iiric/azmi/28?label=integration%20tests)](https://dev.azure.com/iiric/azmi/_build/latest?definitionId=28) |
| Unit tests | [![Build Status](https://dev.azure.com/iiric/azmi/_apis/build/status/Unit%20Testing)](https://dev.azure.com/iiric/azmi/_build/latest?definitionId=32) | [![Build details](https://img.shields.io/azure-devops/tests/iiric/azmi/32?label=unit%20tests)](https://dev.azure.com/iiric/azmi/_build/latest?definitionId=32) |
| Performance test | [![Build Status](https://dev.azure.com/iiric/azmi/_apis/build/status/azmi-performance%20test?branchName=master)](https://dev.azure.com/iiric/azmi/_build/latest?definitionId=29&branchName=master) |

See [testing overview here](./Testing.md).

## Other repository statistics

![GitHub commits since latest release (by date)](https://img.shields.io/github/commits-since/sre-prg/azmitool/latest)
![GitHub last commit](https://img.shields.io/github/last-commit/sre-prg/azmitool)
![GitHub issues](https://img.shields.io/github/issues-raw/sre-prg/azmitool)
![GitHub pull requests](https://img.shields.io/github/issues-pr/sre-prg/azmitool)

![GitHub stars](https://img.shields.io/github/stars/sre-prg/azmitool?style=plastic)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/sre-prg/azmitool)
![GitHub repo size](https://img.shields.io/github/repo-size/sre-prg/azmitool)
![GitHub language count](https://img.shields.io/github/languages/count/sre-prg/azmitool)
![GitHub top language](https://img.shields.io/github/languages/top/sre-prg/azmitool)

repository: urtabajev/azmitool

repo_name: urtabajev/azmitool


text:
This is a basic UDP network tester I wrote to learn some go.
It ping-pongs UDP packets, where packet size, packet count
and number of threads can be specified on the command line.

Run as a server (server port is the final option):

server options:
 -s            enable server mode
 -k <number>   server key

phantom -s (random key and port are chosen)
phantom -k 1969 -s (server key 1969, random port)
phantom -k 1969 -s 2929 (server key 1969, port 2929)

Run as a client (server ip:port is the final option):

client options:
 -n <number>   number of threads (default 1)
 -c <number>   packets per thread (default 1k)
 -b <number>   packet size (default 512 bytes)
 -k <number>   server key
 -r <number>   ramp-up mode (see below)

phantom -k 1969 <IP_ADDRESS>:2929 (key 1969 server <IP_ADDRESS>:2929)
phantom -k 1969 -n 10 -c 1000000 -b 288 <IP_ADDRESS>:2929 (10 threads, 100k packets per thread, 288 byte packets)

Set -c 0 to get a client that runs for a very long time, or til interrupted.

Client in ramp-up mode:

In ramp-up mode the client will add a thread at the interval specified until packet loss is detected.
The option -r overrides the -n and -c options.

phantom -k 1969 -r 5 <IP_ADDRESS>:2929 (key 1969, ramp-up 5s, server <IP_ADDRESS>:2929)

license: ISC

repository: solidposter/phantom

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: solidposter/phantom


text:
---
layout: post
title: "ViewCompat.canScrollVertically()"
date: 2014-06-22 19:56:29 +0800
comments: true
categories: android
---

Due to watching world cup evey night through out the week, I spent most of my time these two weekends sleeping. Even not able to do some serious coding, I tried to clean up my long pending reading list, and I just took a look of [SwipeRefreshLayout](http://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html).

Saw this class a while ago, just from the name of this class, I expected it to be a ViewGroup that handles the pull gesture of the Android style pull to refresh. I was not very interested in this class because there is no plan to touch the refresh UI in work, but it is always good to know it is in the support library.

What really caught my attention is the canChildScrollUp() method in SwipeRefreshLayout. It used ViewCompat.canScrollVertically and special handled pre-ICS.

[Source line 348](https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v4/java/android/support/v4/widget/SwipeRefreshLayout.java)

``` java

public boolean canChildScrollUp() {
    if (android.os.Build.VERSION.SDK_INT < 14) {
        if (mTarget instanceof AbsListView) {
            final AbsListView absListView = (AbsListView) mTarget;
            return absListView.getChildCount() > 0
                    && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
                            .getTop() < absListView.getPaddingTop());
        } else {
            return mTarget.getScrollY() > 0;
        }
    } else {
        return ViewCompat.canScrollVertically(mTarget, -1);
    }
}

```

(Well I don't understand why the ViewCompat method cannot(?) handle pre-ICS... then what's the point of Compat?)

I wasn't aware there is a canScrollVertically() method in View since ICS, and the ViewCompat also provides some interesting method that could simplify some custom ViewGroup implementation. Should put more time to review what's new in those commonly used classes as I believe there is no need to support pre-ICS soon.

Refrerence: http://antonioleiva.com/swiperefreshlayout/

license: MIT

repository: billynyh/random-coding

extension: markdown

repo_name: billynyh/random-coding


text:
# Editor Scripts

### ClickEditorWindow.cs

_Overview:_

GUIWindow template for an editor window which responds to clicks in the scene.

_Usage:_

Place script in Assets/Editor then navigate to Window > Click Tracking Window from the menubar.

### ObjectArrayGenerator.cs

_Overview:_

GUIWindow which allows user to quickly generate arrays objects.
The editor supports 2D and 3D array generation.
It also supports parenting to existing objects, or it can generate an empty object which will become the parent for all generated objects.

_Usage:_

Place script in Assets/Editor then navigate to Window > Click Tracking Window from the menubar.

repository: SalvatoreTosti/unity-scripts

repo_name: SalvatoreTosti/unity-scripts


text:
# parcel-optimizer-imagemin
> Parcel optimizer plugin to minify images seamlessly.

## Installation
1. `$ npm install parcel-optimizer-imagemin --save-dev`
2. Update your `.parcelrc` with the entry below.
   ```
   "optimizers": {
     "*.{gif,jpeg,jpg,png,svg,webp}": ["parcel-optimizer-imagemin", "..."]
   }
   ```

*Important:* the three dots indicate to Parcel to run their default optimizers on any bundles that haven't been optimized yet.

## Configuration
Plugin configuration lives in your `package.json`, as `parcel-optimizer-imagemin` object prop:
- Keys should be [imagemin plugins](https://www.npmjs.com/search?q=keywords:imageminplugin).
- Values should be a plugin options object, or `false` to disable the plugin.

### Preset Plugins
By default, this optimizer includes the following imagemin configuration:
```
{
  "imagemin-gifsicle": { "optimizationLevel": 3 },
  "imagemin-mozjpeg": { "quality": 80 },
  "imagemin-pngquant": { "speed": 1, "strip": true },
  "imagemin-svgo": {},
  "imagemin-webp": {}
}
```

### Examples
The example below shows how to use optipng instead of pngquant.
```
// package.json
"parcel-optimizer-imagemin": {
  "imagemin-optipng": {},
  "imagemin-pngquant": false
}
```

*Important:* optipng is not installed by default, and you should add this dependency to your `package.json`.

## Debugging
Run Parcel with `--log-level info` to see what and how bundles are optimized.

## Changelog
See the [Changelog](./CHANGELOG.md) for a list of changes.

## License
    The MIT License (MIT)

    Copyright (c) 2020 Mark van Seventer

    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: vseventer/parcel-optimizer-imagemin

repo_name: vseventer/parcel-optimizer-imagemin


text:
Google Image Search
===========

This is a simple utility to search for images using the [`Google Images API`](https://developers.google.com/image-search/v1/jsondevguide).

Demonstrates Pinterest-esque layout, hiding navigation bar on scroll, recent searches, and auto-complete.

## Demo
![Google Image Search Demo](http://i.imgur.com/D3QL0pd.gif)

## Restrictions
You are restricted to 64 results without an API key and 1000 results with an API key.

### Auto Complete Delay
Google seems to be rate limiting the endpoint, so we are delaying auto-complete requests by 0.4 seconds by default to help cull excessive requests

## Libraries
*  AFNetworking
*  AMScrollingNavbar
*  CHTCollectionViewWaterfallLayout
*  PureLayout

## License
GIS for iOS is released under a slightly modified [Simplified BSD License](https://github.com/nmock/artisan-ios/blob/master/LICENSE).

Please don't upload this code directly to the App Store as is without making subsantial improvements.

## Known Bugs / Possible improvements
*  allow user to view full image, image details, etc.
*  allow user to change search options (grayscale images, faces, clip art, safe search, etc.)
*  better error handling
*  create plist to handle all constants / tweakable values for easy tweaking for stakeholders
*  show loading inline by way of custom uicollectionviewcell footer / headers
*  better error/state handling (reachability, network errors, API errors, end of results, no results, etc.)

repository: nmock/GIS

repo_name: nmock/GIS


text:
---
layout: extension
name: datapreview
title: Data preview for ckan from local resource cache
author: Data.Gov.UK - Cabinet Office
homepage: https://github.com/datagovuk/ckanext-datapreview
github_user: datagovuk
github_repo: ckanext-datapreview
category: Extension
featured:
permalink: /extension/datapreview/
---

# ckanext-datapreview

This extension is a modified, but local implementation of the [OKFN dataproxy](https://github.com/okfn/dataproxy) that runs as a CKAN extension rather than on [Google AppEngine](http://jsonpdataproxy.appspot.com). This has been written to improve the performance on [data.gov.uk](data.gov.uk) and increase the maximum file size processed.

The interface to the extension::

    /data/preview/<resource_id>?max-results=N&encoding=utf-8

is not exactly the same - dataproxy requires the URL instead of the resource id - the data returned is identical. Rather than always fetching the data from the remote site the new controller at the above route will first attempt to find the data in the [ckanext-archiver](https://github.com/okfn/ckanext-archiver)'s local archive.

## Installation

The most straightforward method of installation is::

    git clone git://github.com/datagovuk/ckanext-datapreview.git
    cd ckanext-datapreview
    python setup.py develop

Or alternatively install directly using pip:

    pip install -e git+https://github.com/datagovuk/ckanext-datapreview.git#egg=ckanext-datapreview

Once complete the datapreview should be added to your ckan.plugins property in the appropriate .ini file.

## Requirements

* __ckanext-archiver__ - for the resource cache
* __messytables__ - (in setup.py)

## Problems

Currently when previewing this data with [recline.js](reclinejs.com) the dataproxy backend has a hard-coded URL to http://jsonpdataproxy.appspot.com which means it is unable to be used with this extension.

On data.gov.uk we have patched a local copy of recline to use the new datapreview, however a patch to the recline dataproxy backend should be feasible.

## Improvements

* Increases the limit on download size (doesn't have the appengine download limit)
* Uses the local archive cache if it exists rather than hitting the remote site (only if ckanext-archiver has retrieved the file).


text:
# PGP Verify Jar

Docker container to verify jars PGP signatures.

[![ShellCheck](https://github.com/thomasleplus/docker-pgp-verify-jar/workflows/ShellCheck/badge.svg)](https://github.com/thomasleplus/docker-pgp-verify-jar/actions?query=workflow:"ShellCheck")
[![Docker Build](https://github.com/thomasleplus/docker-pgp-verify-jar/workflows/Docker/badge.svg)](https://github.com/thomasleplus/docker-pgp-verify-jar/actions?query=workflow:"Docker")
[![Docker Stars](https://img.shields.io/docker/stars/thomasleplus/pgp-verify-jar)](https://hub.docker.com/r/thomasleplus/pgp-verify-jar)
[![Docker Pulls](https://img.shields.io/docker/pulls/thomasleplus/pgp-verify-jar)](https://hub.docker.com/r/thomasleplus/pgp-verify-jar)
[![Docker Automated](https://img.shields.io/docker/cloud/automated/thomasleplus/pgp-verify-jar)](https://hub.docker.com/r/thomasleplus/pgp-verify-jar)
[![Docker Build](https://img.shields.io/docker/cloud/build/thomasleplus/pgp-verify-jar)](https://hub.docker.com/r/thomasleplus/pgp-verify-jar)
[![Docker Version](https://img.shields.io/docker/v/thomasleplus/pgp-verify-jar?sort=semver)](https://hub.docker.com/r/thomasleplus/pgp-verify-jar)

## Examples

Assuming that you want to see the signature of a jar with coordinates 'org.leplus:ristretto:1.0.0':

```
docker run --rm thomasleplus/pgp-verify-jar org.leplus:ristretto:1.0.0
```

You can put several sets in coordinates in arguments to verify
multiple artifacts. You can also use the `KEYSERVER` environment
variable to choose a different keyserver (default is keyserver.ubuntu.com):

```
docker run --rm -e KEYSERVER=pgp.mit.edu thomasleplus/pgp-verify-jar org.leplus:ristretto:1.0.0
```

Alternatively you can use the `--keyserver` option to achieve the same
result:

```
docker run --rm thomasleplus/pgp-verify-jar --keyserver=pgp.mit.edu org.leplus:ristretto:1.0.0
```

Note that this will show you the jar's signature information but if
you use a public keyserver, it doesn't provide any guarantee since
anybody can upload a key to a public keyserver and claim that it is
owned by anyone (neither the name nor the email address associated
with the key are verified).

There are several solutions to this issue. If you have access to
private keyserver hosting only trusted keys, you can simply use the
`KEYSERVER` environment variable or the `--keyserver` option described
above.

Otherwise, you can use the `ONLINE_KEYS` environment variable to restrict the
keys to be trusted from the server (private or public). `ONLINE_KEYS`
should contain a coma-separated list of public key IDs:

```
docker run --rm -e ONLINE_KEYS=6B1B9BE54C155617,85911F425EC61B51 thomasleplus/pgp-verify-jar org.leplus:ristretto:1.0.0 junit:junit:4.13.1
```

Alternatively you can use the `--online-keys` option to achieve the
same result:

```
docker run --rm thomasleplus/pgp-verify-jar --online-keys=6B1B9BE54C155617,85911F425EC61B51 org.leplus:ristretto:1.0.0 junit:junit:4.13.1
```

If the keys downloaded from the server are themselves signed by other
keys, you can import these key-signing keys first using the
`BOOTSTRAP_ONLINE_KEYS` environment variable or the
`--bootstrap-online-keys` option (again a coma-separated list of
public key IDs in both cases).

Otherwise you will see the following warning from `gpg`:
`gpg: WARNING: This key is not certified with a trusted signature!`

Finally, if you prefer to verify signatures entirely offline, you can
mount a local GnuPG folder of your choice into the docker container
and setting the `VERIFICATION_MODE` environment variable to `offline`
(default value is `online`):

```
docker run --rm -e VERIFICATION_MODE=offline -v "/path/to/.gnupg:/root/.gnupg" thomasleplus/pgp-verify-jar org.leplus:ristretto:1.0.0
```

Alternatively you can use the `--verification-mode` option to achieve
the same result:

```
docker run --rm -v "/path/to/.gnupg:/root/.gnupg" thomasleplus/pgp-verify-jar --verification-mode=offline org.leplus:ristretto:1.0.0
```

In `offline` mode, all the keys present in the keyring can be used to
check the signatures. The keys cannot be restricted as with the
`ONLINE_KEYS` environment variable or the `--online-keys` option. But
the key ID used to verify each signature will be displayed in the
output so you can review them if needed. Or you can pass a keyring
containing only the acceptable keys.

In `offline` mode, you are also responsible for putting in the keyring
any key-signing key if needed.

repository: ruageek/docker-pgp-verify-jar

branch_name: refs/heads/main

repo_name: ruageek/docker-pgp-verify-jar


text:
# Pareto Gamuts: Exploring Optimal Designs Across Varying Contexts

Liane Makatura, Minghao Guo, Adriana Schulz, Justin Solomon, and Wojciech Matusik

SIGGRAPH 2021

This repository contains the code to accompany our SIGGRAPH 2021 paper,
[Pareto Gamuts: Exploring Optimal Designs Across Varying Contexts](http://paretogamuts.csail.mit.edu).
For more details, please refer to the paper.

## Overview

This folder contains (1) our discovery algorithm, (2) problem setups for all examples scenarios included in the paper, and (3) code for running comparisons against two state-of-the-art fixed context approaches (termed "NSGA" and "Schulz" -- see paper for details.)

## Pareto Gamut Discovery code

All Pareto gamut code is in the folder `ParetoGamuts_discovery`.
You must change the working directory in `AppDiscover.m`, line 12. Be sure to include the final `/` in the path.

While developing the code, we used the term "application variable" to describe what is known in the paper as the "context variable"; they should be treated interchangably here.

### Running the examples

All examples from Section 6.1 (ZDT1-6, Fourier benchmark) can be run from `examplesAnalytic.m`

All examples from Section 6.2 (turbine, bicycle, solar roof/gridshell, lamp, bicopter) can be run from `examplesMeshBased.m`

## Comparisons with NSGA

All code for NSGA is in the folder `NSGA_comparisons`.

### Running the examples

Turbine and Lamp:  run `python comparison_stats.py`

To switch between the two problems, you will need to make some small changes within the file:
- line 53: change the nadir point for HV to 2 (Turbine) or 3(Lamp) dimensions
- line 165: change the problem class to Turbine or Lamp

Bikerocker: run `python runBike.py`

Bicopter: run `python runBicopter.py`

Solar Roof: run `python runGridShell.py`

## Comparisons with Schulz

All code for Schulz is in the folder `ParetoGamuts_discovery`.
You must change the working directory in `MappingFunction.m`, line 51. Be sure to include the final `/` in the path.

### Running examples

All examples can be run from `compareGamutSingleContext.m`. You will need to specify `scFunc_list` according to the descriptions in `MappingFunction.m`.

repository: LianeMakatura/ParetoGamuts

repo_name: LianeMakatura/ParetoGamuts


text:
| |
:-|:-:|-:
__Version: 0.1.12__ | [Home](Home.md) | [Versions Index](https://bitbucket.org/cicci/node-postgres-orm/src/master/doc/Index.md)

- [Syntax](#markdown-header-syntax)
- [Database](#markdown-header-database)
- [Access](#markdown-header-access)
- [Example](#markdown-header-example)

[comment]: <> (doc begin)
For detaild about _foreign keys_, please refer to PostreSQL documentation.

The __FKEY__ pseudo type is used to instruct __pgo__ to create a _foreign key_ on database.

# Syntax

```javascript
var Pgo = require('pgo');
var db  = new Pgo("postgres://username:password@localhost/database");

db.model('foo', {
  bar: db.VARCHAR,
});

db.model('baz', {
  bar: db.FKEY('foo'),
  foo: db.FKEY('foo', 'bar'),
});
```

In the example above, table __baz__ has two _foreign keys_ on the table __foo__.

The first one on field __id__ (_as default_), and the second one on field __bar__.

# Database

Whith this simple syntax __pgo__ will create:
* a filed of the same type of the referred one
* the __FOREIGN KEY__ constraint
* the __INDEX__ required to enforce the constraint

# Access

In the example above, the two attributes __bar__ and __foo__ of a _record_ of type __baz__ will be repectively of type __INT8__ and __VARCHAR__ and they will have the value the record has in database.

To access the relative __foo__ record, the standard __pgo__._<table_name>_._load()_ function can be used. More than this a quick method is added to the _record_: __record__._<field_name>Load()_ wich expects in input a _callback_ function.

# Example

```javascript
db.baz.load({id: 1}, fnction(err, res) {
  if(err || ! res.length)
    return;

  res[0].barLoad(function(err, res) {
    if(err || ! res.length)
      return;

    // res[0] is the referenced foo record
  });
});
```
[comment]: <> (doc end)

 | |
:-|:-:|-:
__Version: 0.1.12__ | [Home](Home.md) | [Versions Index](https://bitbucket.org/cicci/node-postgres-orm/src/master/doc/Index.md)

repository: iccicci/node-postgres-orm

gha_language: JavaScript

gha_license_id: MIT

repo_name: iccicci/node-postgres-orm


text:
---
layout: project
type: project
image: images/geoquizcode.png
title: GeoQuiz
permalink: projects/geoquiz
date: 2016
labels:
  - Android App Development
  - Android Studio
  - Java
summary: I coded a simple True/False quiz app for Android for an Android Application Development class I taught over the summer.
---

  <img class="ui image" src="../images/geoquizcode.png">

GeoQuiz is a simple Android app that uses textviews, buttons, toasts, and menus to present a question about geography to the user. The user answers the question by pressing a "True" or "False" button and a toast appears indicating if they were correct or not. They must press another button to view the next question. While this app may seem simple, coding it definitely wasn't. I used the Android Studio IDE with Java and XML to create the app. Android Studio isn't easy to use, and requires intermediate to advanced Java and XML knowledge, as well as knowledge on the Android API and how apps work.

I made this app in preparation for an Android App Development course I taught at Punahou School. My role was one of the two instructors, and both of us collaborated on the preparation. However, I made the GeoQuiz app on my own while she made the slides and prepped what would happen during class for the beginning. Punahou contracted DevLeague to teach a few classes for their summer school. Our class was designed for high school students, and we used this app as a skeleton for the students to use Android Studio and design their own app for Android.

I definitely learned quite a bit from this project. Android Studio is surprisingly difficult and having the experience of using it, even briefly for such a simple project, makes me feel more confident in my ability to make apps in the future. Mobile app development is booming in the programming business, and the knowledge of the IDE is incredibly important, especially with app-specific funcitonalities that this project required me to use, including toasts, buttons, textviews, and layouts. I also learned a few things about Java, such as anonymous & local inner classes and event listeners. The interaction with XML was another new thing for me, as I had never worked with markup languages prior to this app.

[Here is my source code for GeoQuiz.](https://github.com/JHeadland/GeoQuizAndroidApp) It's uploaded as a tar.gz archive because GitHub wouldn't let me upload the source files individually (it was too big).


text:
# OptimPack.jl

| **Documentation**               | **License**                     | **Build Status**                                                | **Code Coverage**                                                   |
|:--------------------------------|:--------------------------------|:----------------------------------------------------------------|:--------------------------------------------------------------------|
| [![][doc-dev-img]][doc-dev-url] | [![][license-img]][license-url] | [![][travis-img]][travis-url] [![][appveyor-img]][appveyor-url] | [![][coveralls-img]][coveralls-url] [![][codecov-img]][codecov-url] |

OptimPack.jl is the Julia interface to [OptimPack][lib-optimpack-url], a C
library for solving large scale optimization problems.

## Installation

### Installation using pre-compiled libraries

From a Julia session, press `]` to enter the Pkg REPL and type the following commands:

```julia
(...) pkg> add https://github.com/emmt/OptimPack.jl
```

to install and build the package.  This just has to be done once.

To use the package in your code:

```julia
using OptimPack
```

### Installation with your own compiled libraries

By default, the package manager will attend to download precompiled OptimPack
libraries for your architecture so that you have nothing to compile.  These
libraries are provided by the
[OptimPackBuilder](https://github.com/emmt/OptimPackBuilder) project.  If your
system is not part of the supported platforms or if you want to use
OptimPack libraries compiled and installed by yourself (see intructions at
[official OptimPack repository][lib-optimpack-url]) then you have to define 4
environment variables **before** building `OptimPack.jl` package.  Each of
these environment variables specifies the full path to one of the OptimPack
dynamic libraries. These environment variables can be set before starting Julia
or at Julia REPL, for instance by:

```julia
ENV["OPTIMPACK_OPK_LIB"] = "/usr/local/lib/libopk.so"
ENV["OPTIMPACK_COBYLA_LIB"] = "/usr/local/lib/libcobyla.so"
ENV["OPTIMPACK_BOBYQA_LIB"] = "/usr/local/lib/libbobyqa.so"
ENV["OPTIMPACK_NEWUOA_LIB"] = "/usr/local/lib/libnewuoa.so"
```

Then proceed as for the other installation method: press `]` to enter the Pkg
REPL and type the following commands:

```julia
(...) pkg> add https://github.com/emmt/OptimPack.jl
```

You may use URL `git@github.com:emmt/OptimPack.jl` if you want to use SSH
instead of HTTPS.

If you define the environment variables after adding `OptimPack.jl` package,
just re-build the package:

```julia
(...) pkg> build OptimPack
```

## Unconstrained Minimization of a Nonlinear Smooth Function

There are two methods in OptimPack to minimize a nonlinear smooth multivariate
function without constraints: non-linear conjugate gradient (NLCG) implemented
by `nlcg` and limited memory variable metric method (VMLM) implemented by
`vmlm`.  In general, `vmlm` is more efficient than `nlcg` but may require more
memory.

The easiest way to use these minimizers is to provide a Julia function, say
`fg!`, which is in charge of computing the value of the function and its
gradient for given variables.  This function must have the form:
```julia
function fg!(x, g)
   g[...] = ... # store the gradient of the function
   f = ...      # compute the function value
   return f     # return the function value
end
```
where the arguments `x` and `g` are Julia arrays (same types and
dimensions) with, on entry, `x` storing the variables and, on exit, `g`
storing the gradient.  The user defined function shall return the function
value.

## Nonlinear Conjugate Gradient (NLCG)

The solution `x` can be computed by one of the implemented nonlinear
conjugate gradient methods with:
```julia
x = nlcg(fg!, x0, method)
```
where `x0` gives the initial value of the variables (as well as the data
type and dimensions of the solution).  `x0` is a Julia dense array with any
dimensions and with elements of type `Float64` or `Float32`.  Argument
`method` is optional and can be used to choose among the different implemented
methods (see below).

The keyword `verb` can be set true to print information at each iteration.
Other keywords are described in the following sub-sections.

### Method Settings

The different nonlinear conjugate gradient methods mainly differ by the way
they compute the search direction.  The conjugate gradient iteration
writes:
```julia
x_{k+1} = x_{k} + alpha_{k} * d_{k}
```
with `alpha_{k}` the step length and where the search direction `d_{k}` is
derived from the gradient `g(x_{k})` of the objective function at the
current point `x_{k}` and from the previous search direction `d_{k-1}` by
an *update rule* which depends on the specific method.  Typically:
```julia
d_{k} = -g(x_{k}) + beta_{k} * d_{k-1}
```
where `beta_{k}` is computed following different recipes.  To choose which
recipe to use, the value of the `method` argument can be set to one of the
following values:

- `OptimPack.NLCG_FLETCHER_REEVES` for Fletcher & Reeve method;
- `OptimPack.NLCG_HESTENES_STIEFEL` for Hestenes & Stiefel method;
- `OptimPack.NLCG_POLAK_RIBIERE_POLYAK` for Polak, Ribière & Polyak method;
- `OptimPack.NLCG_FLETCHER` for Fletcher "*Conjugate Descent*" method;
- `OptimPack.NLCG_LIU_STOREY` for Liu & Storey method;
- `OptimPack.NLCG_DAI_YUAN` for Dai & Yuan method;
- `OptimPack.NLCG_PERRY_SHANNO` for Perry & Shanno update rule;
- `OptimPack.NLCG_HAGER_ZHANG` for Hager & Zhang method.

The above values can be bitwise or'ed with the following bits:

- `OptimPack.NLCG_POWELL` to force parameter `beta` to be nonnegative;
- `OptimPack.NLCG_SHANNO_PHUA` to guess the step length following the
  prescription of Shanno & Phua.

For instance:
```julia
method = OptimPack.NLCG_POLAK_RIBIERE_POLYAK | OptimPack.NLCG_POWELL
```
merely corresponds to PRP+ algorithm by Polak, Ribière & Polyak; while:
```julia
method = OptimPack.NLCG_PERRY_SHANNO | OptimPack.NLCG_SHANNO_PHUA
```
merely corresponds to the nonlinear conjugate gradient method implemented
in CONMIN (Shanno & Phua, 1980).

The default settings for nonlinear conjugate gradient is:
```julia
const OptimPack.NLCG_DEFAULT = (OptimPack.NLCG_HAGER_ZHANG | OptimPack.NLCG_SHANNO_PHUA)
```

### Stopping Criteria

The nonlinear conjugate gradient methods are iterative algorithms, the
convergence is assumed to be achieved when the Euclidean norm of the
gradient is smaller than a threshold.  In pseudo-code, the criterion is:
```julia
||g(x)|| <= max(0, gatol, grtol*||g(x0)||)
```
where `||g(x)||` is the Euclidean norm of the gradient at the current
solution `x`, `||g(x0)||` is the Euclidean norm of the initial gradient at
`x0`, `gatol` is an absolute threshold parameter and `grtol` is a relative
threshold parameter.  The keywords `gatol` and `grtol` can be used to
specify other values for these parameters than the default ones which are
`gatol = 0.0` and `grtol = 1E-6`.

It may be desirable to limit the time spent by the algorithm.  To that end,
the keywords `maxiter` and `maxeval` are available to specify the maximum
number of iterations and evaluations of the algorithm respectively.  Their
default values is `-1` which means that there are no restrictions.  For now,
the algorithm can only be safely stopped at an acceptable iterate, thus the
maximum number of allowed function evaluations may slightly exceed the
value of `maxeval`.

### Line Search Settings

The keyword `lnsrch` can be used to specify another line search method than
the default one:
```julia
x = nlcg(fg!, x0, method, lnsrch=ls)
```
where `ls` is one of the implemented line search methods:
```julia
ls = OptimPack.ArmijoLineSearch(ftol=...)
ls = OptimPack.MoreThuenteLineSearch(ftol=..., gtol=..., xtol=...)
ls = OptimPack.NonmonotoneLineSearch(mem=..., ftol=..., amin=..., amax=...)
```
with `ftol` the tolerance on the function reduction for the Armijo or first
Wolfe condition, `gtol` the tolerance on the gradient for the second
(strong) Wolfe condition, `xtol` the relative precision for the step length
(set to the machine relative precision by default), `mem` the number of
previous steps to remember for the nonmonotone line search, keywords `amin`
and `amax` set the lower steplength bound and the upper steplength relative
bound to trigger bissection in nonmonotone line search.  By default, the
values used in SPG2 are used for the nonmonotone line search: `mem = 10`,
`ftol = 1E-4`, `amin = 0.1` and `amax = 0.9`.

The line search is safeguarded by imposing lower and upper bounds on the
step.  In `nlcg` and `vmlm`, keywords `stpmin` and `stpmax` can be used to
specify the step bounds relatively to the size of the first step for each
line search.  Their default values are: `stpmin = 1E-20` and `stpmax =
1E+20`; if specified, they must be such that: `0 <= stpmin < stpmax`.

## Variable Metric with Limited Memory (VMLM)

Alternatively, the solution `x` can be computed by a limited memory version
of the variable metric method (implementing BFGS updates) with:
```julia
x = vmlm(fg!, x0, m)
```
where the optional argument `m` is the number of previous steps to memorize
(by default `m = 3`) while other arguments have the same meaning as for
`nlcg`.

Keywords `verb`, `gatol`, `grtol`, `lnsrch`, `stpmin` and `stpmax` can also
be specified for `vmlm` and have the same meaning as for `nlcg`.

In addition to these keywords, you can specify how to scale the inverse
Hessian in variable metric method via the `scaling` keyword:
```julia
scaling = OptimPack.SCALING_NONE             # to use a unit scaling (no scaling)
scaling = OptimPack.SCALING_OREN_SPEDICATO   # to scale by: gamma1 = <s,y>/<y,y>
scaling = OptimPack.SCALING_BARZILAI_BORWEIN # to scale by: gamma2 = <s,s>/<s,y>
```
where `<s,y>` denotes the inner product between the previous step `s` and
gradient difference `y`.

## Spectral Projected Gradient Method

The spectral projected gradient (SPG2) method of Birgin, Martinez & Raydan
can be used for solving large constrained optimization problems.  The usage
of the SPG2 method is documented [here](doc/spg2.md).

## Low-level Interface

### Operations on Vectors

To create a vector space for vectors of dimensions `dims` and element type
`T`:
```julia
space = OptimPack.DenseVectorSpace(T, dims)
```
where `T` is `Float32` or `Float64` (or any type alias of these,
e.g. `Cfloat` or `Cdouble`) and `dims` is a tuple of the dimensions.

It is also possible to *wrap* a vector around a specific Julia array:
```julia
vect = OptimPack.wrap(space, arr)
```
where `space` is an OptimPack *shaped* vector space and `arr` is a Julia
array.  The element type and dimension list of the array must match those
of the vector space.  A method is available to change the contents of such
a vector:
```julia
OptimPack.wrap!(vect, arr2)
```
where `arr2` is another Julia array (the same constraints on the element
type and dimensions apply).

Note that `arr` must be a **dense array** (of type `DenseArray`) as the
elements of *shaped* vectors are supposed to be stored contiguously in
memory.  OptimPack offers the possibility to create custom vector spaces
and this will be exploited in a near future to allow for other flavors of
Julia arrays.

### Error Management

Run-time errors throw Julia exception.

[doc-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[doc-stable-url]: https://emmt.github.io/OptimPack.jl/stable

[doc-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[doc-dev-url]: https://emmt.github.io/OptimPack.jl/dev

[license-url]: ./LICENSE.md
[license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat

[travis-img]: https://travis-ci.com/emmt/OptimPack.jl.svg?branch=master
[travis-url]: https://travis-ci.com/emmt/OptimPack.jl

[appveyor-img]: https://ci.appveyor.com/api/projects/status/github/emmt/OptimPack.jl?branch=master
[appveyor-url]: https://ci.appveyor.com/project/emmt/OptimPack-jl/branch/master

[coveralls-img]: https://coveralls.io/repos/emmt/OptimPack.jl/badge.svg?branch=master&service=github
[coveralls-url]: https://coveralls.io/github/emmt/OptimPack.jl?branch=master

[codecov-img]: http://codecov.io/github/emmt/OptimPack.jl/coverage.svg?branch=master
[codecov-url]: http://codecov.io/github/emmt/OptimPack.jl?branch=master

[julia-url]: https://pkg.julialang.org/

[lib-optimpack-url]: https://github.com/emmt/OptimPack

gha_language: Julia

gha_license_id: NOASSERTION


text:
# Lovely.IO Show E007

In [this episode](http://lovely.io/show/how-to-participate) I'm showing the
internals of the lovely.io project itself and explain how one can participate
and make changes to the code base.

## License & Copyright

All source code in this show is released under the terms of the MIT license

Copyright (C) 2012 Nikolay Nemshilov


text:
# How To Git

Use this repo to play with basic git operations.

## Requirements
- A GitHub account
- Git for Windows or Mac
- VS Code (optional)

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

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

repository: hugo-valdez-ext/how-to-git-java-example

repo_name: hugo-valdez-ext/how-to-git-java-example


text:
# Marasmius epodius var. epodius VARIETY

#### Status
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fung. trident. 1: 88 (1881)

#### Original name
Marasmius epodius var. epodius

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
# UnityHue
Small library that lets you manipulate Philips Hue lamps from within the editor. Uses unity webrequests to communicate with
the hue bridge so it should be pretty crossplatform but will only work in Unity 5.2+ ([More on platform support](https://docs.unity3d.com/Manual/UnityWebRequest.html)).

## Functionality:

- Discover bridges in network
- Authenticate app with bridge (after pressing the link button on the bridge)
- Retrieve list of available lights and light groups
- Rename light, change light state (on/off, color, transition time, alert, effect etc. (pretty much all the api allows)),
get light state and delete light
- Create groups, rename groups and change associated lights, delete groups and change group state (like with lamps but affecting all the lamps in the group)

## License:
MIT

repository: j-bbr/UnityHue

repo_name: j-bbr/UnityHue


text:
# bubbles
This is an algorithm to display bubbles like the Apple Watch UI

This is an experiment to see if I can use Javascript to replicate the look and feel of Apple watch UI "bubbles".

I'm trying to this UI for a project I'm working on, but could not find ready Javascript plug in. All the existing bubbles-like JS plugins are for bubble charts, which isn't what I'm looking for.

What makes this unique and different from the available plugins are:

1) There's a "central" bubble from which all other bubbles radiate out from
2) Each non-central bubble is defined by a distance from the center, and a size
3) Bubbles should not overlap with each other if possible

In the end, I used a combination of trignometry and pythagorean theorem, coupled with loop and recursion to accomplish this.

Hopefully I can turn this into a ready-to-use plugin for other people at some point. If anyone has the skillset to do so, feel free to fork and change the code as necessary.


text:
# Monitoring GPS and Location Permission checks using LiveData

## Background:

In Android apps, users need to allow specific permissions so that app can use that particular resource. All location tracking apps need “GPS to be enabled” and want users to allow “Location Permission” so that app can start receiving location coordinates. For our usecase, it was critically needed to ensure both of these requirements are fulfilled. If not, user should be alerted and informed on UI level during or after *Onboarding* and also when Location Tracking is started/running in background.

This is a sample app to demonstrate the usecase.

## Motivation to publish my solution:

There are already native android ways to implement both of these checks but we tried to do it using LiveData which is a newly introduced API from Android to handle asynchronous operations using Subscribe/Publish mechanism. We faced our fair share of challenges and there was limited help available as not many have tried for this usecase. Solutions which are challenging are the best candidate to be shared with public because it means many others out there will face the same problems and it could save their time. At the end of the day, it’s basically giving back to the community.

## What is this project about:

1) UI (app is active): Checking for both elements, displaying state and showing dialogs for user to react accordingly

    Medium Article: [Read Here](https://medium.com/ki-labs-engineering/monitoring-gps-and-location-permission-checks-using-livedata-part-1-278907344b77)

2) Background (app is not active): Check for both elements as part of Service whenever it is started by System and inform user via notification so that user can enable them for us. Otherwise, location tracking won’t succeed at all.

    Medium Article: [Read Here](https://medium.com/ki-labs-engineering/monitoring-gps-and-location-permission-checks-using-livedata-part-2-d8822ab951a6)

## How sample app looks like or behaves


text:
# Flask-Bcrypt

Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for
your application.

Due to the recent increased prevelance of powerful hardware, such as modern
GPUs, hashes have become increasingly easy to crack. A proactive solution to
this is to use a hash that was designed to be "de-optimized". Bcrypt is such
a hashing facility; unlike hashing algorithms such as MD5 and SHA1, which are
optimized for speed, bcrypt is intentionally structured to be slow.

For sensitive data that must be protected, such as passwords, bcrypt is an
advisable choice.

## Installation

Install the extension with one of the following commands:

    $ easy_install flask-bcrypt

of alternatively if you have pip installed:

    $ pip install flask-bcrypt

## Usage

To use the extension simply import the class wrapper and pass the Flask app
object back to here. Do so like this:

    from flask import Flask
    from flask.ext.bcrypt import Bcrypt

    app = Flask(__name__)
    bcrypt = Bcrypt(app)

Two primary hashing methods are now exposed by way of the bcrypt object. Use
them like so:

    pw_hash = bcrypt.generate_password_hash('hunter2')
    bcrypt.check_password_hash(pw_hash, 'hunter2') # returns True

## Documentation

The Sphinx-compiled documentation is available here: http://packages.python.org/Flask-Bcrypt/

repository: RobertYYF/InfoWebsite

repo_name: RobertYYF/InfoWebsite


text:
1. [About This Package](#about-this-package)
2. [Usage of Account](#usage-of-account)
   1. [Dependencies](#dependencies)
   2. [Examples](#examples)
      1. [Create a random account](#create-a-random-account)
      2. [Import an existing privateKey to create Account](#import-an-existing-privatekey-to-create-account)
      3. [Encrypt/Export keyStore file, Decrypt/Import keyStore file](#encryptexport-keystore-file-decryptimport-keystore-file)
      4. [Address format getter](#address-format-getter)
      5. [Sign a transaction](#sign-a-transaction)
3. [Usage of Wallet](#usage-of-wallet)
   1. [Dependencies](#dependencies-1)

# About This Package

`@harmony-js/account` is dealing with account related features.

Developers can use this packages to:
* create `Account` instance
* create `Wallet` instance
* sign `Transaction`
* convert address format
* manage `privateKey` or `mnemonic phrases` and do the `encrypt` and `decrypt` job

There are 2 main classes in this package, `Account` and `Wallet`.

The `Account` class is basic instance that contains most features mentioned above.
The `Wallet` class is class that stores all `Account` instance, you can do CRUD on it.

# Usage of Account

## Dependencies
  * "@harmony-js/network",
  * "@harmony-js/staking",
  * "@harmony-js/transaction",
  * "@harmony-js/utils"

## Examples

### Create a random account
```typescript

    // import the Account class
    import {Account} from '@harmony-js/account'

    // Messenger is optional, by default, we have a defaultMessenger
    // If you like to change, you will import related package here.
    import { HttpProvider, Messenger } from '@harmony-js/network';
    import { ChainType, ChainID } from '@harmony-js/utils';

    // create a custom messenger
    const customMessenger = new Messenger(
        new HttpProvider('http://localhost:9500'),
        ChainType.Harmony, // if you are connected to Harmony's blockchain
        ChainID.HmyLocal, // check if the chainId is correct
    )

    // to create an Account with random privateKey
    // and you can setMessenger later
    const randomAccount = new Account()
    randomAccount.setMessenger(customMessenger)

    // or you can set messenger on `new`
    const randomAccountWithCustomMessenger = new Account(undefined, customMessenger)

    // you can display the account
    console.log({randomAccount,randomAccountWithCustomMessenger})

    // or you can use static method to create an Account
    const staticCreatedAccount = Account.new()
    // but you have to set messenger manually after
    staticCreatedAccount.setMessenger(customMessenger)

    console.log({staticCreatedAccount})

```

### Import an existing privateKey to create Account

```typescript

    // import the Account class
    import {Account} from '@harmony-js/account'

    // NOTED: Key with or without `0x` are accepted, makes no different
    // NOTED: DO NOT import `mnemonic phrase` using `Account` class, use `Wallet` instead
    const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930'

    const myAccountWithMyPrivateKey = new Account(myPrivateKey)

    // you can also import privateKey use static method
    const myAccountWithMyPrivateKeyUsingStatic = Account.add(myPrivateKey)

    console.log({ myAccountWithMyPrivateKey, myAccountWithMyPrivateKeyUsingStatic })

```

### Encrypt/Export keyStore file, Decrypt/Import keyStore file

```typescript

    // import the Account class
    import {Account} from '@harmony-js/account'

    // suppose we have an account
    const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930'
    const myAccountWithMyPrivateKey = new Account(myPrivateKey)

    // suppose we have a password, and we want to encrypt the account above
    const myStrongPassword = '123'

    async function encryptAndDecrypt(password) {
        // we get the privateKey before encrypted as comparison
        const unencryptedPrivateKey = myAccountWithMyPrivateKey.privateKey

        // export the account to keyStore string, which will make the privateKey encrpyted
        const keyStoreFile = await myAccountWithMyPrivateKey.toFile(password)
        // exported keyStoreFile
        console.log({ keyStoreFile })
        // see if the account is encrypted
        console.log(`Is this account encrypted? \n ${myAccountWithMyPrivateKey.encrypted}`)
        // keystore file should be equal to encrypted privateKey
        console.log(
            `Is privateKey equal to keyStore string? \n ${keyStoreFile ===
            myAccountWithMyPrivateKey.privateKey}`,
        )
    }

    encryptAndDecrypt(myStrongPassword)

    // suppose we have keyStorefile, in this example, we just use same password and keystore string encrypted above
    const someKeyStoreFile =
    '{"version":3,"id":"62326332-3139-4839-b534-656134623066","address":"1fe3da351d9fc0c4f02de5412ad7def8aee956c5","Crypto":{"ciphertext":"b86ab81682c9f5a35738ad9bd38cd9b46c1b852ef33f16dd83068f79e20d5531","cipherparams":{"iv":"44efb5a514f34968e92cafad80566487"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"salt":"d70ae1f311601562113f98c8ebe382f52a332dca1588886e5ea91e2f8a647134","n":8192,"r":8,"p":1,"dklen":32},"mac":"7b63e4e31a75a22b7091291bb58302655b738539ef3e30b30a7a7f170f6163ef"}}'

    async function importKeyStoreFileAndDecrypt(keyStoreFile, password) {
        // import keyStore string and provide the password, remember to make a new Account first
        const importedAccount = await Account.new().fromFile(keyStoreFile, password)
        // the account should decypted which `Account.encrypted` is false
        console.log(`Is this account encrypted? \n ${importedAccount.encrypted}`)
        // see if the privatekey is equal to unencrypted one?
        console.log(
            `Is the account recovered from keystore? \n ${importedAccount.privateKey === myPrivateKey}`,
        )
    }

    importKeyStoreFileAndDecrypt(someKeyStoreFile, myStrongPassword)

```

### Address format getter

```typescript

    // import the Account class
    import {Account} from '@harmony-js/account'

    // suppose we have an account
    const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930'
    const myAccountWithMyPrivateKey = new Account(myPrivateKey)

    // Account.address is bytes20/base16 address
    console.log(myAccountWithMyPrivateKey.address)
    // Account.bech32Address is bech32 format address, in Harmony, it's `one1` prefixed
    console.log(myAccountWithMyPrivateKey.bech32Address)
    // Account.bech32TestNetAddress is bech32 format address, in Harmony, it's `tone1` prefixed, used in testnet
    console.log(myAccountWithMyPrivateKey.bech32TestNetAddress)
    // Account.checksumAddress is checksumed address from base16
    console.log(myAccountWithMyPrivateKey.checksumAddress)

```

### Sign a transaction

```typescript

    // import the Account class
    import {Account} from '@harmony-js/account'

    // import Transaction class from '@harmony-js/transaction'
    import {Transaction} from '@harmony-js/transaction'

     // Messenger is optional, by default, we have a defaultMessenger
    // If you like to change, you will import related package here.
    import { HttpProvider, Messenger } from '@harmony-js/network';
    import { ChainType, ChainID, Unit } from '@harmony-js/utils';

    // create a custom messenger
    const customMessenger = new Messenger(
        new HttpProvider('http://localhost:9500'),
        ChainType.Harmony, // if you are connected to Harmony's blockchain
        ChainID.HmyLocal, // check if the chainId is correct
    )
    // suppose we have an account
    const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930'
    const myAccountWithMyPrivateKey = new Account(myPrivateKey)

    const txnObject = {
        //  token send to
        to: 'one166axnkjmghkf3df7xfvd0hn4dft8kemrza4cd2',
        // amount to send
        value: '1000000000000000000000',
        // gas limit, you can use string or use BN value
        gasLimit: '210000',
        // send token from shardID
        shardID: 0,
        // send token to toShardID
        toShardID: 0,
        // gas Price, you can use Unit class, and use Gwei, then remember to use toWei(), which will be transformed to BN
        gasPrice: new Unit('100').asGwei().toWei(),
        // if you set nonce manually here, and remember, the `updateNonce` of `Account.signTransaction` should be set to false
        nonce: 0,
    };

    const txn = new Transaction(txnObject, customMessenger);

    async function signTheTxn() {
        // Account.signTransaction(transaction: Transaction, updateNonce?: boolean, encodeMode?: string, blockNumber?: string): Promise<Transaction>
        // If the 2nd parameter `updateNonce` is set to true, it will query and update account's nonce before it signs
        const signedTxn = await myAccountWithMyPrivateKey.signTransaction(txn, false, 'rlp', 'latest');

        // see if the transaction is signed
        console.log(`\n see if transaction is signed: \n ${signedTxn.isSigned()} \n`);

        // get the tranaction bytes
        console.log(`\n the signed bytes is: \n ${signedTxn.getRawTransaction()} \n`);

        return signTheTxn;
    }

    signTheTxn();
```

# Usage of Wallet

## Dependencies
  * "@harmony-js/crypto",
  * "@harmony-js/network",
  * "@harmony-js/staking",
  * "@harmony-js/transaction",
  * "@harmony-js/utils"

```typescript

    import {Wallet} from '@harmony-js/account'

    const wallet=new Wallet()

```

repository: FireStack-Lab/Harmony-sdk-core

gha_language: TypeScript

repo_name: FireStack-Lab/Harmony-sdk-core


text:
# element-boilerplate
A boilerplate to create bel or yo-yo element

### Why

To start write code quickly.

### Intall

```sh
$ npm i element-boilerplate -g
```

### Usage

To create a markdown component for example:

```sh
eb element-markdown
```

### What's in there

```
.
├── LICENSE
├── README.md
├── example
│   ├── index.css
│   └── index.js
├── index.html
├── index.js
├── package.json
└── test
    └── index.js
```

To start the server with wzrd from the example directory so that you can test your code while developing.

```sh
$ npm start
```

To run test

This project has the basic settings to make your repo running test on Travis CI.

Using `standard` to run lint for now.

```sh
$ npm test
```

repository: fraserxu/element-boilerplate

repo_name: fraserxu/element-boilerplate


text:
# OctaveConv_pytorch
## Pytorch implementation of Octave convolution with other similar operation
  This is **third parity** implementation(un-official) of Following Paper which are talked in
  1. Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks with Octave Convolution(ICCV 2019).
  [paper](https://arxiv.org/pdf/1904.05049)
  ![](fig/octave_conv.png)
  2. Adaptively Connected Neural Networks.(CVPR 2019)
  [paper](https://arxiv.org/abs/1904.03579)
  ![](fig/adaptive_conv.png)
  3. Res2net:A New Multi-scale Backbone Architecture
  [paper](https://arxiv.org/abs/1904.01169)
  ![](fig/res2net.png)
  4. ScaleNet:Data-Driven Neuron Allocation for Scale Aggregation Networks
  [paper](https://arxiv.org/pdf/1904.09460)
  ![](fig/sablock.png)
  5. SRM : A Style-based Recalibration Module for Convolutional Neural Networks
  [paper](https://arxiv.org/abs/1903.10829)
  ![](fig/srm.png)

### Plan
1. add Res2Net bolock with SE-layer (done)
2. add Adaptive-Convolution: both pixel-aware and dataset-aware (done)
3. Train code on Imagenet. (done)
4. Support more models. ()

### Usage
   check model files under the fig/nn floder.

```python
from lib.nn.OCtaveResnet import resnet50
from lib.nn.res2net import se_resnet50
from lib.nn.AdaptiveConvResnet import PixelAwareResnet50, DataSetAwareResnet50

model = resnet50().cuda()
model = se_resnet50().cuda()
model = PixelAwareResnet50().cuda()
model = DataSetAwareResnet50().cuda()

```

## Reference:
  1. OctaveConv: MXNet implementation [here](https://github.com/terrychenism/OctaveConv)
  2. AdaptiveCov: Offical tensorflow implementation [here](https://github.com/wanggrun/Adaptively-Connected-Neural-Networks)
  3. ScaleNet: [here](https://github.com/Eli-YiLi/ScaleNet)
  4. SGENet:[here](https://github.com/implus/PytorchInsight)
## License
    MIT License


text:
# Writing Complex Unreal functions in C++

A lot of languages have embarked on the coroutine model using async/await. Unreal is not different. But here, they are called Latent Functions. There is no easy way to write Latent Functions using Blueprint, so we must jump to C++.

Their complexity is justified because they allow you to have very elegant Blueprints, allowing non-developers to orchestrate complex behaviour and tune the game the way they see fit.

To arrive at our desired aim, we will need four steps.

- Simple Function in C++
- Function with multiple Exec pins
- Simple Latent Function
- Latent Function with Multiple Exec pins

# Creating our project

We don't need much here. So we are going to create a simple blank project. Create a useless cube actor.

All our reactions to our new Blueprint nodes will just print strings.

So head up to "New Project" and create a new Blank project.

![Screenshot015.jpg](./Screenshot001.jpg)

![Screenshot015.jpg](./Screenshot002.jpg)

The vital step here is to change from "Blueprint" project to "C++" project. Which actually allow us to use both.

![Screenshot015.jpg](./Screenshot003.jpg)

I have previously selected VSCode as the editor. If you haven't, Visual Studio will pop up instead.

There is no difference. Just choose whatever best suits you.

![Screenshot015.jpg](./Screenshot004.jpg)

If you go back to Unreal and hit "Compile", you will hear two noises. One signal compilation start, and the other compilation ended.

![Screenshot015.jpg](./Screenshot005.jpg)

The compilation result will appear at "Message Log -> Compiler Log". You can double click on errors here, and it will open VSCode/Visual Studio on that particular file and line. That's nice!

![Screenshot015.jpg](./Screenshot006.jpg)

Before we jump into code, let us create out actor.

![Screenshot015.jpg](./Screenshot007.jpg)

![Screenshot015.jpg](./Screenshot008.jpg)

![Screenshot015.jpg](./Screenshot009.jpg)

Any actor will do, so let us just create a simple and useless Cube actor.

![Screenshot015.jpg](./Screenshot0010.jpg)

![Screenshot015.jpg](./Screenshot0011.jpg)

![Screenshot015.jpg](./Screenshot0012.jpg)

The important part is that we will be reacting to our new Blueprint nodes here. For now, let us just print something.

![Screenshot015.jpg](./Screenshot0013.jpg)

And let us not forget to place the actor in the world.

![Screenshot015.jpg](./Screenshot0014.jpg)

Hit "Play" and verify everything is working.

![Screenshot015.jpg](./Screenshot0015.jpg)

![Screenshot015.jpg](./Screenshot0016.jpg)

We are ready to start.

# Create a function in C++

Our first example is going to be a simple Blueprint node. Nothing fancy. You pass a parameter, and the function print the string you passed.

We will create all our nodes inside a "Blueprint Function Library".

The code is as simple as that.

![Screenshot015.jpg](./Screenshot0017.jpg)

Implementation is also straightforward.

![Screenshot015.jpg](./Screenshot0018.jpg)

After compiling, we should be able to see and use our new node.

The nice thing is that the node's name came from our Function name. Realize how Unreal split the Pascal case from the function name into words.

We can also control de category. See how the "Hello Lib" category we see below is actually on the function metadata above. Also nice!

![Screenshot015.jpg](./Screenshot0019.jpg)

![Screenshot015.jpg](./Screenshot0020.jpg)

And if we hit Play.

![Screenshot015.jpg](./Screenshot0021.jpg)

# Create a function with multiple Exec pins

Now we will create something a little bit more complex. A node with multiple output execution pins.

The actual code is still relatively simple.

We first need to define an enum that will represent all pins. If you need dynamic pins, this approach will not work.

Second, you ask Unreal to create multiple pins with "ExpandEnumAsExecs". Its value is the parameter name.

![Screenshot015.jpg](./Screenshot0022.jpg)

Inside the implementation, you just need to assign a value to this parameter, and Unreal will propagate the correct output pin.

![Screenshot015.jpg](./Screenshot0023.jpg)

This is our new fancy node inside Blueprint.

![Screenshot015.jpg](./Screenshot0024.jpg)

# Create a Latent Function

Now we can jump to more exciting nodes.

When we use "Delay", we realize that the output pin is not called immediately. It takes how long we asked. These kinds of nodes are called "Latent Functions" inside the engine.

They are a little bit more complex. But we can still create them very easily.

First, we need to define the function as being latent with a bunch of metadata.

HidePin and DefaultToSelf are not required but are excellent additions. If you are curious about what they do, just comment them.

Another essential part is the last parameter.

![Screenshot015.jpg](./Screenshot0025.jpg)

Inside the implementation is clear that this parameter contains all the need context information to schedule our latent function.

In our case, here, we will implement something similar to the Delay node.

All the first two "if"s do is checking if our latent function is already scheduled or not.

That is why you can call the delay function multiple times, but it triggers only once. Another option is, instead of ignoring subsequent executions, we can reset the trigger. That is what "Retriggable Delay" does.

Here, we just ignore them.

The core of this function is on the AddNewAction function—specifically the FDelayAction.

![Screenshot015.jpg](./Screenshot0026.jpg)

This is a custom class we created that allow us to store some state and easily react to ticks and do whatever we want.

Screenshot015.jpg](./Screenshot0027.jpg)

From time to time, the engine will call us at "UpdateOperation".

Here we just subtract RemainingTime, and if it hit zero or below, we complete the action. This is done by "FinishAndTriggerIf".

![Screenshot015.jpg](./Screenshot0028.jpg)

This is our brand new latent node in action. The clock on the top right flag the node as being latent.

![Screenshot015.jpg](./Screenshot0029.jpg)

# Create Latent Function with Multiple Exec pins

If we want to go even further and we want our node to have multiple output pins. We can use another approach to create latent function.

In this example, we will create a simple countdown that signal when a "whole second" passed. It can allow us to do a countdown to a racing game, for example: 5...4...3...2...1...go!

We can implement a class that inherits from UBlueprintAsyncActionBase.

One of the important parts here is the DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam. This mouthful macro creates a type that will define our output pin and its parameters.

In this case, we will generate one integer named "Seconds".

Our output pins are defined inside the "private" section, and they are simple field using this type. In this case, we have "Updated" and "Completed".

Another vital thing to notice is the static function that will create the node.

![Screenshot015.jpg](./Screenshot0030.jpg)

This function is quite simple. Create your class. Init all variables and return it.

![Screenshot015.jpg](./Screenshot0031.jpg)

Just after this function is called, the engine will call the "Activate" method of this class.

This is the place to start doing whatever this node does.

Here we will start a timer that will call us every 100ms.

![Screenshot015.jpg](./Screenshot0032.jpg)

Here we do our job.
We decrement the remaining time. And if a whole second has passed, we call the "Updated" pin. Passing how many seconds we still have.

If we reach zero, we call "Completed".

![Screenshot015.jpg](./Screenshot0033.jpg)

And we can use our adorable node in Blueprint now.

Imagine how hard and ugly would it be in pure Blueprint.

![Screenshot015.jpg](./Screenshot0034.jpg)

# Code

HelloLib.h

```
#pragma once

#include "Engine/EngineTypes.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "SayHelloLib.generated.h"

UENUM(BlueprintType)
enum ESayHello2OutcomePins
{
    PrintName1,
    PrintName2,
};

UCLASS()
class LATENTFUNCTION_API UBPFuncLib : public UBlueprintFunctionLibrary
{
    GENERATED_BODY()
public:
    virtual ~UBPFuncLib();

    UFUNCTION(BlueprintCallable, Category = "Hello Lib")
    static void SayHello1(FString name);

    UFUNCTION(BlueprintCallable, Category = "Hello Lib",
        meta = (ExpandEnumAsExecs = "OutputPins"))
    static void SayHello2(FString name1, FString name2,
        TEnumAsByte<ESayHello2OutcomePins>& OutputPins);

    UFUNCTION(BlueprintCallable, Category = "Hello Lib",
        meta = (Latent, LatentInfo = "LatentInfo", HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject"))
    static void SayHello3(UObject *WorldContextObject, FString name, FLatentActionInfo LatentInfo);
};

DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FBPAsyncCountdownOutputPin, int32, Seconds);

UCLASS()
class LATENTFUNCTION_API UBPAsyncCountdown : public UBlueprintAsyncActionBase
{
GENERATED_BODY()

private:
    UPROPERTY(BlueprintAssignable)
    FBPAsyncCountdownOutputPin Updated;

    UPROPERTY(BlueprintAssignable)
    FBPAsyncCountdownOutputPin Completed;

    const UObject* WorldContext;
    float RemainingSeconds;
    FTimerHandle TimerHandle;

    UFUNCTION(BlueprintCallable, meta = (HidePin = "WorldContextObject", WorldContext = "WorldContextObject"), Category = "Hello Lib")
    static UBPAsyncCountdown* AsyncCountdown(const UObject* WorldContextObject, int32 Seconds);

    void InternalTick();
public:

    virtual void Activate() override;
};
```

HelloLib.cpp
```
#include "SayHelloLib.h"

#include <algorithm>
#include "LatentActions.h"
#include "TimerManager.h"

UBPFuncLib::~UBPFuncLib()
{

}

void UBPFuncLib::SayHello1(FString name)
{
    auto msg = FString::Printf(TEXT("Hello, %s!"), *name);
    UE_LOG(LogTemp, Warning, TEXT("%s"), *msg);
    GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, msg);
}

void UBPFuncLib::SayHello2(FString name1, FString name2,
    TEnumAsByte<ESayHello2OutcomePins>& OutputPins)
{
    auto which = FMath::RandRange(0, 1);

    FString* name;
    if (which == 0) {
        name = &name1;
        OutputPins = ESayHello2OutcomePins::PrintName1;
    } else {
        name = &name2;
        OutputPins = ESayHello2OutcomePins::PrintName2;
    }

    if (name)
    {
        auto msg = FString::Printf(TEXT("Hello, %s!"), **name);
        GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, msg);
    }
}

class FDelayAction : public FPendingLatentAction
{
public:
    float TimeRemaining;
    FName ExecutionFunction;
    int32 OutputLink;
    FWeakObjectPtr CallbackTarget;

    FString Name;

    FDelayAction(FString name, float Duration, const FLatentActionInfo &LatentInfo)
        : TimeRemaining(Duration),
        ExecutionFunction(LatentInfo.ExecutionFunction),
        OutputLink(LatentInfo.Linkage),
        CallbackTarget(LatentInfo.CallbackTarget),
        Name(name)
    {
    }

    virtual void UpdateOperation(FLatentResponse &Response) override
    {
        TimeRemaining -= Response.ElapsedTime();

        if (TimeRemaining <= 0.0f) {
            auto msg = FString::Printf(TEXT("Hello, %s!"), *Name);
            GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, msg);
        }

        Response.FinishAndTriggerIf(TimeRemaining <= 0.0f, ExecutionFunction, OutputLink, CallbackTarget);
    }
};

void UBPFuncLib::SayHello3(UObject *WorldContextObject, FString name, FLatentActionInfo LatentInfo)
{
    GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("Before"));

    if (UWorld *World = GEngine->GetWorldFromContextObjectChecked(WorldContextObject))
    {
        FLatentActionManager &LatentActionManager = World->GetLatentActionManager();
        if (LatentActionManager.FindExistingAction<FDelayAction>(LatentInfo.CallbackTarget, LatentInfo.UUID) == NULL)
        {
            LatentActionManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, new FDelayAction(name, 1.0, LatentInfo));
        }
    }
}

UBPAsyncCountdown* UBPAsyncCountdown::AsyncCountdown(const UObject* WorldContextObj, int32 Seconds)
{
    UBPAsyncCountdown* Node = NewObject<UBPAsyncCountdown>();
    if (Node)
    {
        Node->WorldContext = WorldContextObj;
        Node->RemainingSeconds = (float)Seconds;
    }
    return Node;
}

void UBPAsyncCountdown::Activate()
{
    if (WorldContext)
    {
        FTimerDelegate TimerDelegate;
        TimerDelegate.BindUObject(this, &UBPAsyncCountdown::InternalTick);
        WorldContext->GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDelegate, 0.1f, true);
    }
}

void UBPAsyncCountdown::InternalTick()
{
    auto& t = WorldContext->GetWorld()->GetTimerManager();
    auto dt = t.GetTimerElapsed(TimerHandle);

    int oldseconds = (int)this->RemainingSeconds;
    this->RemainingSeconds -= dt;
    int newseconds = std::max(0, (int)this->RemainingSeconds);

    if (this->RemainingSeconds <= 0.0) {
        t.ClearTimer(TimerHandle);
        Completed.Broadcast(newseconds);
        return;
    }

    if (newseconds != oldseconds) {
        Updated.Broadcast(newseconds + 1);
    }
}
```

repository: xunilrj/sandbox

repo_name: xunilrj/sandbox


text:
# First Project - Data Analysis

This project analyses the King County House prices to discover unknown insights and train a regression model to predict house prices.

## To go through this notebook please setup your environment as follows:

```BASH
pyenv local 3.8.5
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```


text:
DynamicFusion
============
Implementation of [Newcombe et al. 2015 DynamicFusion paper](http://grail.cs.washington.edu/projects/dynamicfusion/papers/DynamicFusion.pdf).

#### This project is still in active development and does not yet reproduce the results of the paper accurately.

The code is based on this [KinectFusion implemenation](https://github.com/Nerei/kinfu_remake)

Dependencies:
* CUDA 5.0 or higher
* OpenCV 2.4.8 or higher (modules opencv_core, opencv_highgui, opencv_calib3d, opencv_imgproc, opencv_viz). Make sure that WITH_VTK flag is enabled in CMake during OpenCV configuration.
* Nanoflann (included in the repository)
* Boost (libraries system, filesystem and program options. Only used in the demo. Tested with [1.64.0](http://www.boost.org/users/history/version_1_64_0.html))
* Ceres solver (Tested with version [1.13.0](http://ceres-solver.org/ceres-solver-1.13.0.tar.gz))

Implicit dependency (needed by opencv_viz):
* VTK 5.8.0 or higher
* SuiteSparse, BLAS and LAPACK for ceres
Optional dependencies:
* GTest for testing
* Doxygen for documentation
* OpenNI v1.5.4 for getting input straight from a kinect device.

## Building instructions:

### Linux
Install NVIDIA drivers.A good tutorial with some common issues covered can be found [here](
https://askubuntu.com/a/61433/167689).

Download and install CUDA from the [NVIDIA website](https://developer.nvidia.com/cuda-downloads).

Install VTK, SuiteSparse, BLAS and LAPACK
```
sudo apt-get install libvtk5-dev libsuitesparse-dev liblapack-dev libblas-dev
```

Clone Ceres Solver `git clone https://ceres-solver.googlesource.com/ceres-solver`, then build and install using `cmake` and `make`.

Clone and install opencv. The project should work with any version above 2.4.8
```
git clone https://github.com/opencv/opencv
cd opencv
git checkout 3.2.0
mkdir build
cd build
cmake .. -DWITH_VTK=ON -DBUILD_opencv_calib3d=ON -DBUILD_opencv_imgproc=ON
make -j4
sudo make install
```
Get [Boost 1.64.0](http://www.boost.org/users/download/) or above. Don't install it through apt-get as it sometimes results in linking errors on Ubuntu 16.04.

Optionals:
Doxygen can be installed through apt-get: `sudo apt-get install doxygen`.
Clone and install [GTest](https://github.com/google/googletest)
Clone and install [OpenNI](https://github.com/OpenNI/OpenNI)

Now clone the repository and build:
```
git clone https://github.com/mihaibujanca/dynamicfusion
mkdir build
cd build
cmake ..
make -j4
```

If you want to build the tests as well, make sure you pass `-DBUILD_TESTS=ON` to the cmake command.

To build documentation, go to the project root directory and execute
```
doxygen -g
doxygen Doxyfile
```
### Windows
* [Install NVIDIA drivers](https://www.geforce.com/drivers) and [CUDA](https://developer.nvidia.com/cuda-downloads)
* [Install LAPACK](http://icl.cs.utk.edu/lapack-for-windows/lapack/).
* [Install VTK](http://www.vtk.org/download/) (download and build from source)
* [Install OpenCV](http://docs.opencv.org/3.2.0/d3/d52/tutorial_windows_install.html).
* [Install Boost](http://www.boost.org/users/download/)

Optionals:
* [Doxygen](http://www.stack.nl/~dimitri/doxygen/download.html)
* [GTest](https://github.com/google/googletest)
* [OpenNI]( http://pointclouds.org/downloads/windows.html)

## Run instructions
### Unix
Download an example dataset using `./download_data`.
To run the project, use `./build/bin/dynamicfusion <project_root>/data/umbrella`

### Windows
[Download the dataset](http://lgdv.cs.fau.de/uploads/publications/data/innmann2016deform/umbrella_data.zip).\
Create a `data` folder inside the project root directory. \
Unzip the archive into `data` and remove any files that are not .png. \
Inside `data`, create directories `color` and `depth`, and move color and depth frames to their corresponding folders.

To use with .oni captures or straight from a kinect device, use `./build/bin/dynamicfusion_kinect <path-to-oni>` or `./build/bin/dynamicfusion_kinect <device_id>`

---
Note: currently, the frame rate is too low (5-6fps) to be able to cope with live inputs, so it is advisable that you capture your input first.

## References
[DynamicFusion project page](http://grail.cs.washington.edu/projects/dynamicfusion/)

```
@InProceedings{Newcombe_2015_CVPR,
author = {Newcombe, Richard A. and Fox, Dieter and Seitz, Steven M.},
title = {DynamicFusion: Reconstruction and Tracking of Non-Rigid Scenes in Real-Time},
booktitle = {The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
month = {June},
year = {2015}
}
```

The example dataset is taken from the [VolumeDeform project](http://lgdv.cs.fau.de/publications/publication/Pub.2016.tech.IMMD.IMMD9.volume_6/).
```
@inbook{innmann2016volume,
author = "Innmann, Matthias and Zollh{\"o}fer, Michael and Nie{\ss}ner, Matthias and Theobalt, Christian
         and Stamminger, Marc",
editor = "Leibe, Bastian and Matas, Jiri and Sebe, Nicu and Welling, Max",
title = "VolumeDeform: Real-Time Volumetric Non-rigid Reconstruction",
bookTitle = "Computer Vision -- ECCV 2016: 14th European Conference, Amsterdam, The Netherlands,
            October 11-14, 2016, Proceedings, Part VIII",
year = "2016",
publisher = "Springer International Publishing",
address = "Cham",
pages = "362--379",
isbn = "978-3-319-46484-8",
doi = "10.1007/978-3-319-46484-8_22",
url = "http://dx.doi.org/10.1007/978-3-319-46484-8_22"
}
```


text:
---
layout: post
title: Search Graph Nodes
tags: algorithm jiuzhang array bfs revisit apple
date: 2017-05-07 18:01:00 -0400
comments: true
---
>Q: Given an undirected graph, a node and a target, return the node mapping to the target value nearest to the given node, return NULL if you can't find.

Note: it's guaranteed that there is only one available solution.

Example:

    2------3  5
     \     |  |
      \    |  |
       \   |  |
        \  |  |
          1 --4

There a hash named values which is [3,4,10,50,50], representing:
Value of node 1 is 3
Value of node 2 is 4
Value of node 3 is 10
Value of node 4 is 50
Value of node 5 is 50

Give a node 1, target is 50, return node 4

### Sample solution

```java
/**
 * Definition for graph node.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) {
 *         label = x; neighbors = new ArrayList<UndirectedGraphNode>();
 *     }
 * };
 */
public class Solution {
    public UndirectedGraphNode searchNode(ArrayList<UndirectedGraphNode> graph,
                                          Map<UndirectedGraphNode, Integer> values,
                                          UndirectedGraphNode node,
                                          int target) {
        if (graph == null || graph.size() == 0){
            return null;
        }

        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        Set<UndirectedGraphNode> hash = new HashSet<UndirectedGraphNode>();

        queue.offer(node);
        hash.add(node);

        while (!queue.isEmpty()){
            UndirectedGraphNode head = queue.poll();
            if (values.get(head) == target){
                return head;
            }
            for (UndirectedGraphNode n : head.neighbors){
                if (!hash.contains(n)){
                    queue.offer(n);
                    hash.add(n);
                }
            }
        }
        return null;
    }
}
```

Reference:

http://www.lintcode.com/en/problem/search-graph-nodes/

repository: Yunhan-Zheng/codingBlog

repo_name: Yunhan-Zheng/codingBlog


text:
[![GitHub issues](https://img.shields.io/github/issues/miykael/parcellation_fragmenter.svg)](https://github.com/miykael/parcellation_fragmenter/issues/)
[![GitHub pull-requests](https://img.shields.io/github/issues-pr/miykael/parcellation_fragmenter.svg)](https://github.com/miykael/parcellation_fragmenter/pulls/)
[![GitHub contributors](https://img.shields.io/github/contributors/miykael/parcellation_fragmenter.svg)](https://GitHub.com/miykael/parcellation_fragmenter/graphs/contributors/)
[![GitHub Commits](https://github-basic-badges.herokuapp.com/commits/miykael/parcellation_fragmenter.svg)](https://github.com/miykael/parcellation_fragmenter/commits/master)
[![GitHub size](https://github-size-badge.herokuapp.com/miykael/parcellation_fragmenter.svg)](https://github.com/miykael/parcellation_fragmenter/archive/master.zip)
[![GitHub HitCount](http://hits.dwyl.io/miykael/parcellation_fragmenter.svg)](http://hits.dwyl.io/miykael/parcellation_fragmenter)

# Parcellation Fragmenter

Fragments FreeSurfer parcellation annotation in N-equal sized parcels. Besides looking beautiful, such surface parcellation could be used as feature extract for machine learning approaches or similar.

The current version takes either the whole FreeSurfer surface and devides it into N equal sized parcels or it takes a predefined region of interest (ROI), specified by FreeSurfer's `aparc.annot` file and fragments this region in N equal sized parcels.

The parcellation can be done by using a Gaussian Mixed Model, a Ward or a K-Means approach.

The following figure shows an example of a whole surface fragmentation for 16, 64, 256, 1024, 4096 parcels using a Gaussian Mixed Models approach:

The following figure shows an example of a fragmentation of the primary auditory cortex for 4, 16, 64, 256, 1024 using a K-Means approach:

# How to install it

Eventually via pip... It requires the following python packages: `numpy`, `nibabel`, `nilearn`, `sklearn`

# How to run it

Simple, open the `fragmenter.py` script and change the values at the bottom accordingly.

# How to help with it

There are still many things that can be changed/adapted/added. So please feel free to check-out the [issues section](https://github.com/miykael/parcellation_fragmenter/issues) for what can be done, fork the project, send me a PR or give us a feedback!


text:
---
layout: default
title: "Documentation"
---
# postgres-queries

Utility to generate and execute postgresql queries with ease.

## Install

`npm install --save postgres-queries`

## Introduction
Creating query and executing them are two separate concerns. And thus postgres-queries is divided in two parts:
- [The Pool](pool), that allows to connect to the postgres database and execute query.
- [The query builders](queryBuilder.html) (insertOne, selectOne, etc..) that allows to generate sql, and the corresponding parameters.

## Pool
Extend [node-pg-pool](https://github.com/brianc/node-pg-pool)
Allow to connect to postgresql and execute query
It adds:
- namedQuery
- a link helper to link a query builder to the client.

## Query Builder
The main idea behind the query builder is to be able to just give a configuration object:
- the name of a table
- its primary key(s)
- the columns we want to read
- the columns we want to write

And get a function asking for the query parameter:
- id
- data object

And returning queryData that can be directly passed to the `client.namedQuery` method.

Some builder even allows to create several builder at once.

repository: qibinlin/postgres-queries

repo_name: qibinlin/postgres-queries


text:
# Canvas Bitfield Drawer

Creates an animation using a bit formula to draw colors on a canvas.

Based on the original source code by Martin Kleepe (@aemkei) in [original tweet](https://twitter.com/aemkei/status/1378106731386040322).

repository: johnsbuck/Bitfield-Canvas-Drawer

repo_name: johnsbuck/Bitfield-Canvas-Drawer


text:
#notebookscripts [![Picture](https://raw.github.com/janelia-flyem/janelia-flyem.github.com/master/images/gray_janelia_logo.png)](http://janelia.org/)
================

Ipython notebook files for FlyEM.

These files are mainly designed for internal FlyEM use.  Simple or interactive python scripts should be documented and saved into an ipython notebook file.  One can view these files http://nbviewer.ipython.org/github/janelia-flyem/notebookscripts/#notebookname# (example: http://nbviewer.ipython.org/github/janelia-flyem/notebookscripts/blob/master/missing_synapses/parse_debug_assignments.ipynb).

## Potential Use Cases

* Documentation of small scripts that would otherwise not be versioned or monitored
* Keeping track of how a script was called
* Keeping track of a set of experiments that leverage the same script
* Tutorial for calling a module or package such as Gala

repository: janelia-flyem/notebookscripts

repo_name: janelia-flyem/notebookscripts


text:
# Design

The Honeycomb agent is an observability tool that continuously observes
the log files of an application (_e.g._, nginx, MySQL, _etc_.), parses
them, and sends them to the [Honeycomb API][1].

This document describes the core abstractions of the Honeycomb agent,
and how to use it in your Kubernetes cluster. Specifically:

1. What happens when the Honeycomb agent is deployed on a Kubernetes
   cluster
1. How to deploy the Honeycomb agent to a Kubernetes cluster
1. How to configure the agent to consume up logs of different types
   running in your cluster

You will need:

* [Jsonnet][5] v0.9.4
* The [hausdorff:honeycomb][4] branch of ksonnet-lib
* A deployed Kubernetes environment, such as a cluster or minikube.

## Deploying the Honeycomb agent to a Kubernetes cluster (and what happens when you do)

After you have set up a Kubernetes environment (_e.g._, minikube, or a
[cluster on AWS][2]), run the following command.

```shell
kubectl apply -f honeycomb-agent-ds.json
```

This deploys Honeycomb agent is deployed to Kubernetes as a
[`DaemonSet`][3], which means that Kubernetes will try to have the
Honeycomb agent run on every node in the cluster.

When a Honeycomb agent starts, in the general case, it needs to know:

1. Which logs to `tail`
1. Which parsers to use on which logs

The way this works in Kubernetes is: the user annotates some set of
pods with a _label_ (_e.g._, `{app: nginx}`, and then specifies which
parsers to use on pods whose labels match a pattern (specified with
[_label selectors_][7]).

This behavior is specified using a YAML config file, an example of
which is below. An important note about this code is that for the MVP,
this code (which you can see [here][6]) comes _hard-coded_ into the
Honeycomb agent container. This will change to be pluggable as this
project matures.

Here is the example YAML config file:

```yaml
apiHost: https://api.honeycomb.io
writekey: "YOUR_WRITE_KEY_HERE"
watchers:
- dataset: kubernetestest
  parser: json
  sampleRate: 22
  labelSelector: "app=nginx"
- dataset: mysql
  labelSelector: "app=mysql"
  parser: mysql
```

The `watchers` field defines label patterns (called "label selectors")
that tell the Honeycomb agent which pods to read `stdout` of, as well
as which parser to use when it reads the data.

For example, the data set `"kubernetestest"` requires the JSON parser,
and we want Honeycomb to parse the `stdout` of any pod with a label
matching `app=nginx`.

Once the agent boots up, it reads this file to configure itself, and
begins parsing the logs and sending data to Honeycomb. As soon as
there are events to consume, they will begin appearing in the
dashboard.

## Customizing the Honeycomb agent for different applications

When the agents are deployed to the cluster, they need to be
configured so that they have the resources they need to actually get
to the logs of different pods (_e.g._, volume mounts, and so on).

This is typically done by writing a YAML file specifying (_e.g._) a
`DaemonSet`, with all the resources declared, and then `kubectl` this
to the cluster.

But, this is a burden on consumers. Because YAML is purely
declarative, it means that the user must either template the YAML
somehow, or else each configuration of the agent requires a completely
different YAML file to be written.

To reduce this burden, the Honeycomb agent uses [ksonnet][9].

Let's look at an example of how the base Honeycomb agent `DaemonSet`
can be customized to read the container logs for different pods. In
[`honeycomb-agent-ds-app.jsonnet`][8], we see code like the following:

```c++
local honeycomb = import "honeycomb-agent-ds-base.libsonnet";
local custom = import "honeycomb-agent-ds-custom.libsonnet";

// Import Honeycomb agent DaemonSet, append volume to it. The output
// of this equivalent to `honeycomb-agent-ds-custom.json`.
honeycomb.base("honeycomb-agent-v1.1", "kube-system") +
custom.daemonSet.addHostMountedPodLogs("varlog", "varlibdockercontainers")
```

One way to read this code is as saying "take `honeycomb.base`, the
default `DaemonSet` for the Honeycomb agent, and use
`addHostMountedPodLogs` to mount a pods's container logs inside all
the containers in that `DaemonSet`.

Breaking it down, this code is doing three important things:

1. Imports `honeycomb.base`, which will define the most basic
   Honeycomb agent daemonset
1. Imports `custom.daemonSet.addHostMountedPodLogs`, which will
   mount the path to the Pod container logs into a (customizable) subset of the containers in a `DaemonSet`
1. Combining these two things with the Jsonnet `+` ("mixin") operator.

As we can see, this approach allows users to decouple the "base" logic
that all configurations have in common, and customize it as necessary.

Now let's look at how `addHostMountedPodLogs` works.

```c++
    // addhostMountedPodLogs takes a two volume names and produces a
    // mixin that will mount the Kubernetes pod logs into a set of
    // containers specified by `containerSelector`.
    addHostMountedPodLogs(
      varlogVolName, podLogVolName, containerSelector=function(c) true
    )::
      // Pod logs are located on the host at
      // `/var/lib/docker/containers`. Define volumes and mounts for
      // these paths, so the Honeytailer can access them.
      local varlogVol = volume.fromHostPath(varlogVolName, "/var/log");
      local varlogMount =
        volumeMount.new(varlogVol.name, varlogVol.hostPath.path);
      local podLogsVol =
        volume.fromHostPath(
          podLogVolName,
          "/var/lib/docker/containers");
      local podLogMount =
        volumeMount.new(podLogsVol.name, podLogsVol.hostPath.path, true);

      // Add volume to DaemonSet, and attach mounts to every
      // container for which `containerSelector` is true.
      ds.mixin.spec.template.spec.volumes([varlogVol, podLogsVol]) +

      // Add volume mount to every container in the DaemonSet.
      ds.mapContainers(
        function (c)
          if containerSelector(c)
          then c + container.volumeMounts([varlogMount, podLogMount])
          else c),
  }
```

This code is a bit more complicated, but it's essentially doing four
things:

1. Creating a volume that exposes `/var/lib` and
   `/var/lib/docker/containers` from the host. These directories
   contain logs for applications and pod containers. Because they are
   exposed from the host, the Honeycomb agent can simply read from
   those files to get logs for a pod.

   ```c++
   local varlogVol = volume.fromHostPath(varlogVolName, "/var/log");
    local podLogsVol =
      volume.fromHostPath(
        podLogVolName,
        "/var/lib/docker/containers");
   ```
1. Creating volume mounts for both of those volumes, which can be
   embedded in the Honeycomb agent container.

   ```c++
   local varlogMount =
     volumeMount.new(varlogVol.name, varlogVol.hostPath.path);
   local podLogMount =
     volumeMount.new(podLogsVol.name, podLogsVol.hostPath.path, true);
   ```
1. Adding the volumes to the Honeycomb agent pod.
   ```c++
      ds.mixin.spec.template.spec.volumes([varlogVol, podLogsVol]) +
   ```
1. Adding these volume mounts to every container in the Honeycomb agent pod.
   ```c++
   ds.mapContainers(
     function (c)
       if containerSelector(c)
       then c + container.volumeMounts([varlogMount, podLogMount])
       else c),
   ```

## Limitations

* The Honeycomb agent can currently only read `stdout` for container
  logs, but eventually we will expand this to support reading from
  (_e.g._) arbitrary files on a persistent volume.

[1]: https://honeycomb.io/
[2]: https://aws.amazon.com/quickstart/architecture/heptio-kubernetes/
[3]: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
[4]: https://github.com/hausdorff/ksonnet-lib/tree/honeycomb
[5]: http://jsonnet.org/
[6]: https://github.com/honeycombio/honeycomb-kubernetes-agent/blob/devel/config.yaml
[7]: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
[8]: https://github.com/honeycombio/honeycomb-kubernetes-agent/blob/devel/jsonnet/honeycomb-agent-ds-app.jsonnet
[9]: https://github.com/ksonnet/ksonnet-lib

repository: honeycombio/honeycomb-kubernetes-agent

gha_language: Go

repo_name: honeycombio/honeycomb-kubernetes-agent


text:
## Doozer

[![PyPI version](https://badge.fury.io/py/rh-doozer.svg)](https://badge.fury.io/py/rh-doozer)
[![codecov](https://codecov.io/gh/openshift/doozer/branch/master/graph/badge.svg)](https://codecov.io/gh/openshift/doozer)

Doozer is a build management utility that currently has the capability to build RPMs and Container Images via OSBS/Brew

## Deployment

_**Note**: This is for running the full, local python `doozer` client, not the containerized version. This requires other dependencies discussed in the [Installation doc](Installation.md)._

For local development pull the code and run:

`python setup.py develop`

For new releases, Jenkins is already setup and deployment to PyPi is easy:

- Bump the version in `./doozerlib/VERSION`
- Push the change to `master`
- Create a new GitHub release: https://github.com/openshift/doozer/releases/new

That's it. Jenkins will do the rest automatically.

## Installation

If you just want to use `doozer` checkout the [container usage doc](Container.md).

If you need to develop for doozer checkout the full [installation doc](Installation.md).

## Usage

Checkout the [Usage doc](Usage.md)

repository: jupierce/doozer

repo_name: jupierce/doozer


text:
# swpt_lib

**NOTE: THIS REPO IS NO LONGER RELEVANT!**

A library of tools shared by all swaptacular micro-services

You can read the docs [here](https://swpt-lib.readthedocs.io/en/latest/).


text:
---
_id: 5e17fa23fb0ecc0036c351e1
title: "Memory Leak C#"
url: 'https://codewithshadman.com/memory-leak-c'
category: articles
slug: 'memory-leak-c'
user_id: 5a83ce59d6eb0005c4ecda2c
username: 'bill-s'
createdOn: '2020-01-10T04:14:27.266Z'
tags: [.net]
---

Many of us were taught that .NET manages memory automatically. There is no need to explicitly free memory. It just kind of goes away with the garbage collector. Though, It doesn’t mean we can’t have memory leaks. In this tutorial we will learn what is a memory leak in C# and how to measure .NET application performance with a variety of tools to diagnose memory issues.

repository: dotnetweekly/dnw-gatsby

repo_name: dotnetweekly/dnw-gatsby


text:
---
title: "DOM Interfaces"
keywords: dom interface
sidebar: api_sidebar
permalink: dom-interfaces.html
toc: false
comments: false
---
Each node created by `xmlbuilder2` is a DOM node. If required, DOM interfaces can be accessed with the `node` property of the builder object. For example:

```js
const { create } = require('xmlbuilder2');

const child = create().ele('root').ele('child');
const tagName = child.node.tagName;
```
The `node` property exposes the DOM [Node](https://dom.spec.whatwg.org/#interface-node) interface.


text:
---
title: 'Weekly Links #141'
date: '2018-12-22'
---

**Top 10 Links For 14-20/12**

1.  [Performance is a Marathon: Successful tactics for web page performance](https://calendar.perfplanet.com/2018/performance-marathon-successful-tactics/)
2.  [There’s no reason to use pointer-events for HTML elements](https://bitsofco.de/theres-no-reason-to-use-pointer-events-for-html-elements/)
3.  [React v16.7: No, This Is Not The One With Hooks](https://reactjs.org/blog/2018/12/19/react-v-16-7.html)
4.  [Researching a Property in the CSS Specifications](https://24ways.org/2018/researching-a-property-in-the-css-specifications/)
5.  [A one-line solution to highlighting search matches](https://bitsofco.de/a-one-line-solution-to-highlighting-search-matches/)
6.  [ECMAScript - A Taste from ES2019 (ES10)](https://nitayneeman.com/posts/a-taste-from-ecmascript-2019/)
7.  [JavaScript Getter-Setter Pyramid](https://staltz.com/javascript-getter-setter-pyramid.html)
8.  [Let's talk JS : documentation](https://areknawo.com/lets-talk-js-documentation/)
9.  [Clip Paths Know No Bounds](https://24ways.org/2018/clip-paths-know-no-bounds/)
10. [I Threw Away my Mouse](https://www.24a11y.com/2018/i-threw-away-my-mouse/)