text:
# Upgrade

At the moment clusters of the versions from v1.12.x to v1.14.x are supported.
If you upgrade within a major version, for example from v1.12.3 to v1.12.7, it
is fine to skip the intermediate versions. The major versions should be upgraded
one by one (i.e. v1.12.x → v1.13.x → v1.14.x).

## Preparation

If you upgrade from v1.12.x to v1.13.x, remove the "etcd" section from the
"kubeadm-config" ConfigMap completely. To edit the ConfigMap:

```
$ kubectl -n kube-system edit cm kubeadm-config
```

## Master Upgrade

On each master node:

* [download] the master node components of the desired version
* perform the upgrade operation:

  ```
  $ kube node <Host SSH> master upgrade
  ```

* wait for the node related Kubernetes core components pods are restarted before
  proceeding with the next node. The pods are:

  - API server
  - scheduler
  - controller manager
  - kube-proxy (usually get restarted after the first master upgrade only).

## Worker Upgrade

On each worker node:

* [download] the worker node components of the desired version
* restart Kubelet:

  ```
  $ kube node <Host SSH> restart
  ```

<!-- Links -->

[download]: setup.md#download

repository: travelping/cennsonic

gha_language: Shell

repo_name: travelping/cennsonic


text:
# tspsa (Traveling Salesman Problem: Simulated Annealing)

## Description
Implementation of the Traveling Salesman Problem (TSP) using the Simulated Annealing (SA) Algorithm written in GO.

## Contributors
- Spencer Bull (bullapse) [sgb695]

## Usage
The following will return a path of Nodes in the shortest distance as a splice of Nodes ([]Node) containing *x* and *y* corridinates
- `RunSARandom(itterations (int), temperature (float64), Mintemp (float64), coolrate (float64), max x cordinate (int), max y cordinate (int), number of locations (int), verbose (bool))`
- TODO: `RunSAFromFile(itterations (int), temperature (float64), Mintemp (float64), coolrate (float64), filename (string))`

## Testing
- `go build; go test` will run a few tests in the `tspsa_test.go` file

 #### Citation
 - http://katrinaeg.com/simulated-annealing.html

repository: spencerbull/tspsa

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: spencerbull/tspsa


text:
# Howl Ctags

"Go to definition" for the [Howl](https://howl.io/) editor that uses ctags.

## Requirements

* [ctags](https://ctags.io/) (or any other program that can generate ctags-compatible files)

## Installation

Install the howl-ctags bundle

    cd ~/.howl/bundles
    git clone https://github.com/dgaw/howl-ctags

Add keyboard shortcuts to your `~/.howl/init.moon` file. E.g.

    bindings.push {
      editor:
        alt_enter: 'ctags-goto-definition'
        ctrl_shift_t: 'ctags-generate'
    }

## Usage

This bundle provides the following commands:

* `ctags-goto-definition` - go to the definition of the tag under the cursor. If there's no tag under the cursor, a prompt to enter a tag name will be shown. This command expects a "tags" file to be present in the project root (or in one of the parent folders of the file being edited).

* `ctags-generate` - run the ctags command line tool to generate the "tags" file. The tool is run in the project root. Use the `ctags_command` configuration variable to customise the path and arguments for the ctags tool (you can also use another tool that's compatible with ctags).

license: MIT

repository: dgaw/howl-ctags

repo_name: dgaw/howl-ctags


text:
# Inverse.js [![Build Status](https://travis-ci.org/devatwork/inverse.js.png?branch=master)](https://travis-ci.org/devatwork/inverse.js)

A DI container inspired by the AngularJS.

## Why dependency injection?

Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.

This can be used, for example, as a simple way to load plugins dynamically or to choose stubs or mock objects in test environments vs. real objects in production environments. This software design pattern injects the depended-on element (object or value, etc.) to the destination automatically by knowing the requirement of the destination. Another pattern, called dependency lookup, is a regular process and reverse process to dependency injection.

One of its core principles is the separation of behavior from dependency resolution.

## Concepts

Inverse.js is heavily inspired by the *DI Container* as implemented in [AngularJS](http://angularjs.org/), it derives most of its concepts from it as well.

The main element is the DI container itself is called the *Injector*. Its goal is to resolve values from providers.

A *Provider* is either an object or a function. Providers are, together with their declared dependencies, registered in the injector and the values they provide can be requested from the injector. If a provider is requested the injector injects its dependencies before returning it.

Providers can be grouped into *Modules*. Modules get registered in the injector.

## Example

```js
var di = require('./inversejs');

// Define a Car object which needs an engine obviously
var Car = function(engine) {
	this.start = function() {
		engine.start();
	};
};

// Define a factory which can create different type of engines
var engineFactory = function(engineType) {
	return {
		start: function() {
			console.log('Starting ' + engineType + ' engine');
		}
	};
};

// Create the drive module
var carModule = new di.Module('driving');
carModule.type('car', Car);
carModule.factory('engine', engineFactory);
carModule.constant('engineType', 'rocket');

// Create the injector
var injector = new di.Injector([carModule]);

// Execute a function using the injector, the dependencies will be injected
injector.invoke(function(car) {
	car.start();
});
```

## Annotations

Annotations are the way to declare the dependencies of a provider. There are several ways to declare them.

### Array syntax

My personal favorite, clean syntax.

```js
module.run(['car', function(carInstance) {
	carInstance.start();
}]);
```

### Method arguments

Warning: this might break when used with minifiers.

```js
module.run(function(car) {
	car.start();
});
```

### $inject

Possibly the most clean way, since it seperates the concerns.

```js
var startCar = function(car) {
	car.start();
};
startCar.$inject = ['car'];
module.run(startCar);
```

## Module API

### constant(key, value)

Registers a constant value.

```js
module.constant('engineType', 'rocket');
```

### type(key, Constructor)

If resolved, the `Constructor` will be called with the `new` operator to create an instance.

```js
module.type('car', Car);
```

### factory(key, factoryFn)

If resolved, the `factoryFn` will be invoked to produce an instance.

```js
module.factory('engine', engineFactory);
```

### decorator(key, decorateFn)

If resolved, the `decorateFn` will be invoked to decorate an produced instance identified by the `key`. The `$delegate` argument hold the instance.

```js
module.decorator('engine', ['$delegate', function($delegate) {
	// Modify the $delegate here
	return $delegate;
}];
```

### run(runFn)

Registers a `runFn` callback which will be invoked after the injector is initialized.

```js
module.run(function(car) {
	car.start(); // Lets get going!
});
```

## Injector API

### instantiate(Type, locals)

Instantiates the given `Type`, the construct arguments of the `Type` are injected. `Type` is either the constructor function or a string. If it is a string, it is assumed to be a registered type key, which is resolved first. `locals` is an optional object and if present then any argument names are read from this object first, before the $injector is consulted.

```js
var car1 = injector.instantiate(Car); // Creates an instance of the Car
var car2 = injector.instantiate('car'); // Resolves car type by key an instantiates it
```

### get(key)

Gets the value from the provider identified by key.

```js
var car = injector.get('car');
```

### invoke(fn, self, locals)

Invoke the method and supply the method arguments from this injector. `fn` is the function to invoke, its arguments are injected. `self` it the optional `this` binding of `fn`. `locals` is an optional object and if present then any argument names are read from this object first, before the $injector is consulted.

```js
injector.invoke(function(car) {
	car.start();
});
```

## Release History

* 2014-01-05   v0.0.1   Development release.

## Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).

## Copyright

Copyright (c) 2013 Bert Willems and contributors.

## License

This project is licensed under [MIT](http://www.opensource.org/licenses/mit-license.php "Read more about the MIT license form"). Refer to LICENCE for more information.


text:
---
layout: post
title:  "A circuit-like notation for lambda calculus"
date:   2015-11-08
categories: projects
hieroglyph: "𓍝"
---

Lately, I've been playing around with inventing a visual writing system for lambda calculus.

[Lambda calculus](http://en.wikipedia.org/wiki/Lambda_calculus) (λ-calculus) is a sort of proto-functional-programming, originally invented by Alonzo Church while he was trying to solve [the same problem](http://en.wikipedia.org/wiki/Entscheidungsproblem) that led Turing to invent Turing machines. It’s another way of reasoning about computation.

Python’s lambda is an idea that was borrowed from λ-calculus. In Python, you can use a [lambda expression](https://docs.python.org/2/tutorial/controlflow.html#lambda-expressions) like the following in order to define a function that returns the square of a number:

    square = lambda x: x * x

In λ-calculus, the idea is the same: we create a function by using `λ` to specify which arguments a function takes in, then we give an expression for the function's return value. Pure lambda calculus doesn't include operators of any sort – just functions being applied to other functions – so if we try to write a `square` function, we have to suppose that `multiply` is a function of two variables that has already been defined:

    square = λx. multiply x x

The `square` function, once defined, can be applied to arguments and evaluated into something simpler.

    square 4 = (λx. multiply x x) 4
             = multiply 4 4
             = 16

One of the cool things about lambda calculus is that we can represent most common programming abstractions using λ-calculus, even though it's nothing but functions: numbers, arithmetic, booleans, lists, if statements, loops, recursion... the list goes on. Before I introduce the visual writing system I've been using, let's take a detour and discuss how we can represent numbers and arithmetic using lambda calculus.

Church numerals, in lambda calculus
---
Alonzo Church figured out how to represent numbers as lambda functions; these numbers are referred to as Church numerals.

We can represent any nonnegative integer as long as we have two things: (1) a value for **zero**, and (2) a **successor** function, which returns `n + 1` for any number `n`. To represent numbers as functions, then, we require that `z` (zero) and `s` (successor) be passed in as arguments, and go from there. Each number is actually secretly a function of those two inputs.

    zero = λs. λz. z
    one = λs. λz. s z
    two = λs. λz. s (s z)
    three = λs. λz. s (s (s z))

The actual details of how to implement zero and successor should be implemented as are left as someone else’s problem — we can survive without them. All we care about is that our numbers do the right thing, given whatever zero and successor someone may provide.

What about **addition**? Addition is a function that takes in two numbers (let’s call them `x` and `y`), and produces a number representing their sum. To sum them together, we’ll want to produce a number that applies `s`, the successor function, a total of `x + y` times. For example, we could first apply it `y` times to the zero, then apply it `x` more times to that result.

    plus = λx. λy. (λs. λz. x s (y s z))

Let’s try proving that one plus one equals two. In λ-calculus, this proof looks like the following:

    one = λs. λz. s z
    two = λs. λz. s (s z)

    plus = λx. λy. (λs. λz. x s (y s z))

    plus one one = (λx. λy. (λs. λz. x s (y s z))) one one
                 = λs. λz. one s (one s z)
                 = λs. λz. (λs. λz. s z) s (one s z)
                 = λs. λz. s (one s z)
                 = λs. λz. s ((λs. λz. s z) s z)
                 = λs. λz. s (s z)
                 = two

(Long, but at least conciser than [Bertrand Russell’s](http://en.wikipedia.org/wiki/Principia_Mathematica).)

Lambda circuitry
---

There are a lot of lambdas, parentheses, and arguments being pushed around in that proof. Mentally matching up parentheses is annoying. Scope is especially annoying: which `s` am I looking at again in `λs. λz. (λs. λz. s z) s (one s z)`, the inner one or the outer one?

A linear string of lambdas and parentheses is an ineffective way to provide intuition for the computations that are taking place. This problem isn't unique to lambda calculus, either; consider trying to represent a binary tree using a linear string:

    Node(2, Node(7, Leaf(2), Node(6, Leaf(5), Leaf(11))), Node(5, None, Node(9, Leaf(4), None)))

Unambiguous, but not very intuitive. Contrast that representation with the diagram we use when we're trying to explain that same binary tree at a chalkboard, a more visual notation:

![Binary tree diagram, from Wikipedia](https://upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Binary_tree.svg/288px-Binary_tree.svg.png)

_Image from [Wikipedia](https://commons.wikimedia.org/wiki/File:Binary_tree.svg)._

I remember programming constructs better when I can reason about them visually like this: when I imagine cutting an array in half for binary search, when I imagine pointers in a linked list being shuffled around to insert a new element, and when I imagine traversing up and down the branches of a binary tree.

Why can't lambda calculus get some visual intuitions, in the same way? Lambda calculus is a dance of variables flowing through and being manipulated by functions, and I want a writing system for lambda calculus that will visually display this dance. It shouldn't look like strings of parentheses and symbols: it should create visual intuition.

After some trial and error, here is the system I came up with. I aimed for something that would resemble circuitry.

**Values** flow along wires, where they may be passed in as arguments to functions or applied as functions themselves. Some are inputs, some are outputs.

**Functions** are represented as boxes which are applied to their inputs on one side and produce a single output on the other. The notation must indicate which function is applied; this may either be drawn within the box itself, or wired in to the middle of the box from some other value.

**Arguments** are represented as inputs, coming in from the right side of the diagram; these arguments might pass through functions, or they might be functions-to-apply themselves. If an argument has not been passed in yet, it's an empty arrow beginning a wire; if an argument has been passed in, its value is attached to the wire. Arguments are always passed in from top to bottom, in order.

As an example, here's a function which takes in two functions, `f` and `g`, then a value `x`, and returns `f (g x)`:

![lambda f. lambda g. lambda x. f (g x)](/images/lambda-f-g-x.png)

As another example, here's the M combinator `M = λx. x x` (the "mockingbird" in [_To Mock a Mockingbird_](http://smile.amazon.com/gp/product/B00A1P096Y)):

![lambda x. x x](/images/m-combinator.png)

Church numerals, in lambda circuitry
---

Here's the Church numeral `four = λs. λz. s (s (s (s z)))`, drawn out in lambda circuitry:

![Four, in lambda circuitry](/images/lambda-four.png)

Let's take that proof from earlier that one plus one is two. What does it look like to draw that proof in lambda circuitry, instead?

![Proof that one plus one is two, in lambda circuitry](/images/lambda-oneplusoneistwo.png)

{:refdef: style="text-align: right;"}
∎
{: refdef}

We could also consider **multiplication**. A multiply function would take in two numbers, m and n, and computes a new number which is their product. In lambda calculus, we’d write:

    multiply = λm. λn. λs. λz. m (n s) z

In the notation of lambda circuitry, this looks like this:

![Multiplication function, in lambda circuitry](/images/lambda-multiply.png)

Using this function, we can check that `multiply 2 3` evaluates to `6`:

![Multiply(2, 3), step 1](/images/lambda-multiply-1.png)

![Multiply(2, 3), step 2](/images/lambda-multiply-2.png)

![Multiply(2, 3), step 3](/images/lambda-multiply-3.png)

![Multiply(2, 3), step 4](/images/lambda-multiply-4.png)

![Multiply(2, 3), step 5](/images/lambda-multiply-5.png)

{:refdef: style="text-align: right;"}
∎
{: refdef}

Sidenote: De Bruijn indices
---
One of the nice things about lambda circuitry is that it completely removes the need for variable names.

There's another notation for lambda calculus that does this too: [_De Bruijn indices_](https://en.wikipedia.org/wiki/De_Bruijn_index). A lambda expression written with De Bruijn indices indicates which variables are used where with a positive integer; the smaller the integer, the more recently the argument it refers to was passed in.

For example, the identity function `λx. x` may be written with De Bruijn indices like so:

    identity = λ 1

The Church numeral for two, `λs. λz. s (s z)`, may be written like so:

    two = λ λ 2 (2 1)

The addition function, `λx. λy. (λs. λz. x s (y s z))`, may be written like so:

    plus = λ λ (λ λ 4 2 (3 2 1))

An evaluation of `plus one one` looks like this:

    plus one one = (λ λ (λ λ 4 2 (3 2 1))) (λ λ 2 1) (λ λ 2 1)
                 = (λ (λ λ (λ λ 2 1) 2 (3 2 1))) (λ λ 2 1)
                 = λ λ (λ λ 2 1) 2 ((λ λ 2 1) 2 1)
                 = λ λ (λ λ 2 1) 2 (2 1)
                 = λ λ 2 (2 1)

One of the tricky things about writing a lambda calculus interpreter is getting the renaming rules right; De Bruijn indices are convenient because they remove the need for this. Lambda circuitry is similar in spirit to De Bruijn indices in that it doesn't require variable names at all, but instead indicates which variables are passed where by connecting values directly to an arrow indicating when they were passed in.

Argument-switching function, in lambda circuitry
---

I'll provide more examples just to further demonstrate how the notation works in different situations. Let’s consider the “argument-switching” function `C`, where `C f x y` returns `f y x`. (This is actually the [C combinator](https://en.wikipedia.org/wiki/B,C,K,W_system).)

    C = λf. λx. λy. f y x

![C combinator](/images/c-combinator.png)

Suppose we try applying this to a silly function `f` where `f x y` discards `y` and just returns `x`. Then, `C f` should switch around `f`‘s arguments and create a function which returns `y` instead. Let’s check:

    f = λx. λy. x

    C f = λf. λx. λy. (f y x) f
        = λx. λy. f y x
        = λx. λy. (λx. λy. x) y x
        = λx. λy. y

![f = lambda x. lambda y. x](/images/lambda-f.png)

![C(f), step 1](/images/c-combinator-of-f-1.png)

![C(f), step 2](/images/c-combinator-of-f-2.png)

![C(f), step 3](/images/c-combinator-of-f-3.png)

{:refdef: style="text-align: right;"}
∎
{: refdef}

We could also try a function `g` where `g x y` returns `x y`. Then `C g x y` should return `y x`. Let’s check:

    g = λx. λy. x y

    C g x y = λf. λx. λy. (f y x) g x y
            = g y x
            = (λx. λy. x y) y x
            = y x

![g = lambda x. lambda y. x(y)](/images/lambda-g.png)

![C(g), step 1](/images/c-combinator-of-g-1.png)

![C(g), step 2](/images/c-combinator-of-g-2.png)

![C(g), step 3](/images/c-combinator-of-g-3.png)

![C(g), step 4](/images/c-combinator-of-g-4.png)

{:refdef: style="text-align: right;"}
∎
{: refdef}

_Exercise_: Show that applying `C` twice reverses it. That is, show that `C (C f)` returns `f`, for any `f`.
(Note that `C f` is a function which takes in two arguments, `x` and `y`, and returns `f y x`. Applying `C` only to `f` like this is [partial application](http://en.wikipedia.org/wiki/Partial_application).)

Prior work
---
There are some other systems that give visual intuition to lambda calculus.

[_To Dissect a Mockingbird_](http://dkeenan.com/Lambda/) describes a notation that is actually very similar to the one I've described, and demonstrates it on various problems from _To Mock a Mockingbird_. I like the way this looks, especially how every function is enclosed by two halves of a circle which make it obvious how that function might be applied. My notation doesn't have this feature, but requires drawing fewer enclosing boxes as a result.

Visual Lambda ([code](https://code.google.com/p/visual-lambda/), [basics](http://bntr.planet.ee/lambda/visual_lambda_bubble_notation.gif), [paper](http://bntr.planet.ee/lambda/work/visual_lambda.pdf)) represents lambda expressions as colored bubbles, and provides an interface for manipulating them.

[Alligator Eggs](http://worrydream.com/AlligatorEggs/) is a description of a puzzle game based on lambda calculus, which also happens to provide a visual way of working with and evaluating lambda expressions.

These last two don't happen to satisfy the aesthetic that I personally was aiming for: they use color to represent variable names, whereas I wanted something that would be closer in spirit to De Bruijn indices, providing computational meaning by the careful placement of symbols or wires – but they are nifty nonetheless.

Further reading
---
An explanation of some of the nittier, grittier details of lambda calculus can be found at [Wikipedia: Lambda calculus](http://en.wikipedia.org/wiki/Lambda_calculus) as well as in the textbook [Types and Programming Languages](http://www.cis.upenn.edu/~bcpierce/tapl/).

[_To Mock a Mockingbird_](http://smile.amazon.com/gp/product/B00A1P096Y) is a great puzzle book, and an introduction to [combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus); I had a lot of fun reading it and writing out some of the proofs for answers to some of the problems in lambda circuitry notation.


text:
## Gino-Admin

![Gino-Admin Logo](docs/img/logo/g_logo.svg)

Docs (state: in process): [Gino-Admin docs](https://gino-admin.readthedocs.io/en/latest/ui_screens.html)

Play with Demo (current master 0.0.12) [>>>> Gino-Admin demo <<<<](http://www.xnu-im.space/gino_admin_demo/login)

![badge1](https://img.shields.io/pypi/v/gino_admin) ![badge2](https://img.shields.io/pypi/l/gino_admin) ![badge3](https://img.shields.io/pypi/pyversions/gino_admin)

Admin Panel for PostgreSQL DB with Gino ORM and Sanic

![Table view](docs/img/table_view_new.png)
![Load Presets](docs/img/db_presets.png)

### Supported features

- Auth by login/pass with cookie check
- Create(Add new) item by one for the Model
- Search/sort in tables
- [Upload/export data from/to CSV](https://gino-admin.readthedocs.io/en/latest/csv_upload.html#upload-csv-files)
- Delete all rows/per element
- Copy existed element (data table row)
- Edit existed data (table row)
- SQL-Runner (execute SQL-queries)
- [Presets: Define order and Load to DB bunch of CSV-files](https://gino-admin.readthedocs.io/en/latest/presets.html)
- Drop DB (Full clean up behavior: Drop tables & Recreate)
- Deepcopy element (recursive copy all rows/objects that depend on chosen as ForeignKey)
- [Composite CSV: Load multiple relative tables in one CSV-file](https://gino-admin.readthedocs.io/en/latest/csv_upload.html#composite-csv-to-upload)
- History logs on changes (log for admin panel actions - edit, delete, add, init_db, load presets and etc)

##### TODO:

- Select multiple for delete/copy
- Edit multiple items (?)
- Roles & User store in DB
- Filters in Table's columns
- Add possible to add new Presets from GUI
- Other staff on [Gino Project Dashboard](https://github.com/xnuinside/gino-admin/projects/1)

### How to install

```pip install gino-admin==0.1.0```

### Updates in version 0.1.0 (current master):

1. Added REST endpoint to upload data from CSV file to DB.
2. Cleaned up styles in UI.

### How to use

You can find several code examples in [examples/](examples/) folder.

#### Run Admin Panel from Command line

**Run Admin Panel from cli**

```
gino_admin run #module_name_with_models -d postgresql://%(DB_USER):%(DB_PASSWORD)@%(DB_HOST):%(DB_PORT)/%(DB)

Optional params:
    -d --db
        Expected format: postgresql://%(DB_USER):%(DB_PASSWORD)@%(DB_HOST):%(DB_PORT)/%(DB)
        Example: postgresql://gino:gino@%gino:5432/gino (based on DB settings in examples/)
        Notice: DB credentials can be set up as  env variables with 'SANIC_' prefix
    -h --host
    -p --port
    -c --config Example:  -c "presets_folder=examples/base_example/src/csv_to_upload;some_property=1"
                Notice: all fields that not supported in config will be ignored, like 'some_property' in example
    --no-auth  Run Admin Panel without Auth in UI
    -u --user Admin User login & password
        Expected format: login:password
        Example: admin:1234
        Notice: user also can be defined from env variable with 'SANIC_' prefix - check Auth section example
```

Example:

```gino-admin run examples/base_example/src/db.py postgresql://gino:gino@%gino:5432/gino -u admin:1234
```

#### Add Admin Panel to existed Sanic application as '/admin' route

Create in your project 'admin.py' file and use `add_admin_panel` from from gino_admin import add_admin_panel

Code example in:  examples/base_example
How to run example in: examples/base_example/how_to_run_example.txt

Example:

```
    from from gino_admin import add_admin_panel

    # your app code

    add_admin_panel(
        app, db, [User, Place, City, GiftCard], custom_hash_method=custom_hash_method
    )

```

Where:

* 'app': your Sanic application
* 'db' : from gino.ext.sanic import Gino; db = Gino() and
* [User, Place, City, GiftCard] - list of models that you want to add in Admin Panel to maintain
* custom_hash_method - optional parameter to define you own hash method to encrypt all '_hash' columns of your Models.

In admin panel _hash fields will be displayed without '_hash' prefix and fields values will be  hidden like '******'

#### Run Admin Panel as Standalone Sanic app (if you use different frameworks as main App)

You can use Gino Admin as stand alone web app. Does not matter what Framework used for your main App.

Code example in:  examples/use_with_any_framework_in_main_app/
How to run example in: examples/use_with_any_framework_in_main_app/how_to_run_example.txt

1. In module where you define DB add 'if block'.
We will use Fast API as main App in our example.

We have db.py where we import Gino as
```
    from gino.ext.starlette import Gino

    db = Gino(
        dsn='postgresql://gino:gino@localhost:5432/gino'
    )
```
But if we use this module in Admin Panel we need to have initialisation like this:
```
    from gino.ext.sanic import Gino
    db = Gino()
```

To get this, we will add some flag and based on this flag module will init db in needed to as way:
```

    if os.environ.get('GINO_ADMIN'):
        from gino.ext.sanic import Gino
        db = Gino()
    else:
        from gino.ext.starlette import Gino
        db = Gino(dsn='postgresql://gino:gino@localhost:5432/gino')
```
So, if now 'db' used by Gino Admin - we use init for Sanic apps, if not - we use for our Main application Framework

Now, we need to create **admin.py** to run admin panel:
```
    import os

    from gino_admin import create_admin_app

    os.environ["GINO_ADMIN"] = "1"

    # gino admin uses Sanic as a framework, so you can define most params as environment variables with 'SANIC_' prefix
    # in example used this way to define DB credentials & login-password to admin panel

    os.environ["SANIC_DB_HOST"] = "localhost"
    os.environ["SANIC_DB_DATABASE"] = "gino"
    os.environ["SANIC_DB_USER"] = "gino"
    os.environ["SANIC_DB_PASSWORD"] = "gino"

    os.environ["SANIC_ADMIN_USER"] = "admin"
    os.environ["SANIC_ADMIN_PASSWORD"] = "1234"

    if __name__ == "__main__":
        # variable GINO_ADMIN must be set up before import db module, this is why we do import under if __name__
        import db # noqa E402

        # host & port - will be used to up on them admin app
        # config - Gino Admin configuration,
        # that allow set path to presets folder or custom_hash_method, optional parameter
        # db_models - list of db.Models classes (tables) that you want to see in Admin Panel
        create_admin_app(host="<IP_ADDRESS>", port=5000, db=db.db, db_models=[db.User, db.City, db.GiftCard])
```

All environment variables you can move to define in docker or .env files as you wish, they not needed to be define in '.py', this is just for example shortness.

### Presets

Load multiple CSV to DB in order by one click.
Presets described that CSV-s files and in that order need to be loaded in DB.

Read the docs: [Presets](https://gino-admin.readthedocs.io/en/latest/presets.html)

### Composite CSV to Upload

Composite CSV - one file that contains data for several relative tables.

Read the docs: [Composite CSV to Upload](https://gino-admin.readthedocs.io/en/latest/csv_upload.html#composite-csv-to-upload)

### Config Gino Admin

Read the docs: [Config](https://gino-admin.readthedocs.io/en/latest/config.html)

### Init DB

Init DB feature used for doing full clean up DB - it drop all tables & create them after Drop for all models in Admin Panel.

### Upload from CSV

Files-samples for example project can be found here: **examples/base_example/src/csv_to_upload**

### Authorization

Read in docs: [Authorization](https://gino-admin.readthedocs.io/en/latest/authorization.html)

### Limitations

For correct work of Admin Panel all models MUST contain at least one unique and primary_key Column (field).

This column used to identify row (one element) for Copy & Edit & Delete operations.
Name of unique and primary_key column and type does not matter.

So if you define model, for example, User, you can have column **user_id** as unique and primary_key:

```
    class User(db.Model):

        __tablename__ = "users"

        user_id = db.Column(db.String(), unique=True, primary_key=True)
```

Or for model 'Country' it can be 'code'

```
    class Country(db.Model):

        __tablename__ = "countries"

        code = db.Column(db.String(8), unique=True, primary_key=True)
        name = db.Column(db.String())
```

### Screens:

Check in docs: [UI Screens](https://gino-admin.readthedocs.io/en/latest/ui_screens.html)

repository: ehborisov/gino-admin

repo_name: ehborisov/gino-admin


text:
Pattern: Malformed brace for method

Issue: -

## Description

Checks the location of the opening brace (`{`) for constructors and methods. By default, requires them on the same line, but the `sameLine` property can be set to `false` to override this.

## Further Reading

* [CodeNarc - BracesForMethod](https://codenarc.github.io/CodeNarc/codenarc-rules-formatting.html#bracesformethod-rule)

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

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


text:
# Minecraft Map Converter

## Introduction

An old project from 2019 I rediscovered, It was an attempt to show how images were distorted
when you converted then into a mincraft map colour pallet. However, it was one my first big projects and it really shows.

It's terribly commented, extremely obtuse, and missing many of the techniques I would have used today. Also it's using 8 spaces as indents... so there's that.

## Why is RGB stored as a single array?

One the things I was intrested in doing with project was using a techinque I'd heard used in Ultimate Doom(1996) of using an offset instead of multiple arrays. The RGB values are stored in a single array as [R1,R2,R3,B1,B2,B3,G1,G2,G3], so in order get the colour of 1 you'd have to refference 3 seperate points. This was terrible hard to develop for and didn't even help performance.

repository: Ben-Brady/Minecraft-Map-Art

branch_name: refs/heads/main

repo_name: Ben-Brady/Minecraft-Map-Art


text:
OS:
VSCode version:
Extension version:
Toolchain version:
Build target:
Python version:

Debug log

repository: bzarco/vscode-lldb

gha_license_id: MIT

repo_name: bzarco/vscode-lldb


text:
Document: "WebApps"

Path: "/tmp/azure-rest-api-specs/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json")

## SwiftVirtualNetwork

Swift Virtual Network Contract. This is used to enable the new Swift way of doing virtual network integration.

```puppet
azure_swift_virtual_network {
  api_version => "api_version",
  connection_envelope => "connectionEnvelope",
  kind => "kind (optional)",
  properties => "properties (optional)",
  resource_group_name => "resource_group_name",
  slot => "slot",
  subscription_id => "subscription_id",
}
```

| Name        | Type           | Required       | Description       |
| ------------- | ------------- | ------------- | ------------- |
|api_version | String | true | API Version |
|connection_envelope | Hash | true | Properties of the Virtual Network connection. See example. |
|kind | String | false | Kind of resource. |
|properties | String | false | SwiftVirtualNetwork resource specific properties |
|resource_group_name | String | true | Name of the resource group to which the resource belongs. |
|slot | String | true | Name of the deployment slot. If a slot is not specified, the API will add or update connections for the production slot. |
|subscription_id | String | true | Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). |

## CRUD operations

Here is a list of endpoints that we use to create, read, update and delete the SwiftVirtualNetwork

| Operation | Path | Verb | Description | OperationID |
| ------------- | ------------- | ------------- | ------------- | ------------- |
|Create|`/subscriptions/%{subscription_id}/resourceGroups/%{resource_group_name}/providers/Microsoft.Web/sites/%{name}/slots/%{slot}/config/virtualNetwork`|Put|Integrates this Web App with a Virtual Network. This requires that 1) "swiftSupported" is true when doing a GET against this resource, and 2) that the target Subnet has already been delegated, and is not
in use by another App Service Plan other than the one this App is in.|WebApps_CreateOrUpdateSwiftVirtualNetworkConnectionSlot|
|List - list all|``||||
|List - get one|`/subscriptions/%{subscription_id}/resourceGroups/%{resource_group_name}/providers/Microsoft.Web/sites/%{name}/slots/%{slot}/config/virtualNetwork`|Get|Gets a Swift Virtual Network connection.|WebApps_GetSwiftVirtualNetworkConnectionSlot|
|List - get list using params|``||||
|Update|`/subscriptions/%{subscription_id}/resourceGroups/%{resource_group_name}/providers/Microsoft.Web/sites/%{name}/slots/%{slot}/config/virtualNetwork`|Put|Integrates this Web App with a Virtual Network. This requires that 1) "swiftSupported" is true when doing a GET against this resource, and 2) that the target Subnet has already been delegated, and is not
in use by another App Service Plan other than the one this App is in.|WebApps_CreateOrUpdateSwiftVirtualNetworkConnectionSlot|
|Delete|`/subscriptions/%{subscription_id}/resourceGroups/%{resource_group_name}/providers/Microsoft.Web/sites/%{name}/slots/%{slot}/config/virtualNetwork`|Delete|Deletes a Swift Virtual Network connection from an app (or deployment slot).|WebApps_DeleteSwiftVirtualNetworkSlot|


text:
# PHP-Grav

### At a glance

This aproach for a lightweight Content Management System stack includes four main parts:

+ **PHP-FPM** as the FastCGI engine.
+ **Pushion** as the minimal linux container for this stack.

### Components

**Pushion** base Docker container is a minimal Ubuntu base image modified and minified to be a lightweight Docker compatible container.
The container is enhanced with key features like the ability to handle SSH access to the container and the ability to add additional daemons that run at the startup time of the container.

### Container philosophy

In theory, the use of Docker and containers encourage the one process per container approach but, from the point of view of software as a service, this new container is focused in the one service per container philosophy.

### Dockerfile

The definition for this new **PHP-Grav** container perfirm several tasks at build time:

+ Define the base image as **phusion/baseimage:0.9.19**, an excelent minified Ubuntu 16.04 LTS Docker container.
+ Install and update the core components for this new container.
+ Setup PHP-FPM service.
+ Expose Volumes and ports.

This Docker container is ready and preconfigured. Just download and use it.

### Useful shortcuts and functions

```bash
function docker_remove_all_images() {
	docker rmi $(docker images -q)
}
```

```bash
function docker_remove_all_containers() {
	docker rm $(docker ps -q)
}
```

```bash
function docker_push_image() {
	docker login && docker build -t $1 $2 && docker push $1
}
```

docker login && docker build -t <user>/<image-name>:<version> . && docker push <user>/<image-name>:<version>

### Known Issues

repository: austinrivas/php-grav

repo_name: austinrivas/php-grav


text:
# Projects

## Get all published projects

```shell
curl "http://{server}/api/v2/projects?per_page=1"
```

> The above command returns JSON structured like this:

```json
{
  "results": [
      {
        "id": 16,
        "name": "littlePiggy Bank",
        "slug": "littlepiggy-bank--3",
        "icon": "https://lb-community-staging.s3.amazonaws.com/uploads/image/asset/776/small_pig3_interaction2_highRes.jpg",
        "description": "Interactive piggy bank that RINGS frantically to thank you for feeding it, BUZZES and LIGHTS up when you pet it’s ear, and SITS quietly when you want it to!<br>",
        "comment_count": 0,
        "like_count": 1,
        "liked_by_user": true,
        "user": {
          "id": 1750,
          "image": "https://lb-community-staging.s3.amazonaws.com/uploads/user/avatar/17/small_icon-green-ohhh.png",
          "slug": "littlebits",
          "username": "littleBits"
        }
      }
    ],
    "meta": {
      "criteria": {
        "method": "GET",
        "endpoint": "/api/v1/projects",
        "params": [
          {
            "name": "page",
            "value": 1
          },
          {
            "name": "per_page",
            "value": "1"
          }
        ]
      },
      "success": true,
      "errors": null
    }
}
```

`GET http://{server}/api/v2/projects/`

This request can be optionally authenticated to receive `liked_by_user`.

### Query Parameters

Parameter | Type  | Description
--------- | ----- | -----------
page | integer | Page number of returned results. Default is 1
per_page | integer | Number of results per page. Default is 10

## Search projects

```shell
curl "http://{server}/api/v2/projects/search?kit=base-kit&per_page=1"
```

> The above command returns JSON structured like previously.

`GET http://{server}/api/v2/projects/search`

This request can be optionally authenticated to receive `liked_by_user`.

### Query Parameters

Parameter | Type  | Description
--------- | ----- | -----------
q | string | Search projects by keyword
sort | string | Sort projects by most recent or popular. Accepts either `recent` or `popular`
days_ago | integer | Return projects published some number of days ago
tags | string | Return projects with a given tag
type | string | Defaults to projects only. Use `lesson` for lessons only.
kit | string | Return projects that can be built with this kit. Use slug of a kit.
variants | integer | Return projects with these variant IDs and not any others. Should be a comma separated list.
qty | integer | Return projects with this quantity of a corresponding variant ID. Must be a comma separated list of the same size as the list of variants.
user | integer | Return projects of a given user ID
page | integer | Page number of returned results. Default is 1
per_page | integer | Number of results per page. Default is 10

## Get a project

```shell
curl "http://{server}/api/v2/projects/2055"
```

> The above command returns JSON structured like this:

```json
{
  "results":
  {
    "id": 2055,
    "name": "Sounding Box #11",
    "description": "Sounding Box #11 is the first piece to go public in a series of acoustic sculptures that allow viewers...",
    "comment_count": 1,
    "like_count": 10,
    "liked_by_user": false,
    "user": {
      "id": 47312,
      "image": "https://lb-community-staging.s3.amazonaws.com/uploads/user/avatar/small_Caselden_Studios_high_res.png",
      "slug": "caselden_studios",
      "username": "Caselden_Studios"
    },
    "credits": "God",
    "images": [
      {
        "id": 15,
        "url": "https://lb-community-staging.s3.amazonaws.com/uploads/image/asset/7755/large_filled_IMG_6771.jpg"
      }
    ],
    "embeds": [
      {
        "id": 5,
        "service": "youtube.com",
        "code": "<iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/IYJSEPD9T40\" frameborder=\"0\" allowfullscreen></iframe>"
      }
    ],
    "files": [],
    "tools": [
      {
        "id": 1,
        "name": "3D Printers"
      }
    ],
    "products": [
      {
        "product_id": 139,
        "variant_id": 133,
        "image": "https://s3.amazonaws.com/lb-spree-staging/spree/products/2046/small/arduino_withlogo.jpg?1423167635",
        "name": "Arduino",
        "quantity": 2
      }
    ],
    "materials": [
      {
        "id": 4,
        "name": "Assorted Paints and Finishing Oils",
        "quantity": 1
      }
    ],
    "steps": [
      {
        "id": 2,
        "number": 1,
        "title": "i am a jolly step title",
        "description": "<b>Make a sound box:</b><br>Design a resonating wooden chamber. We took design influence from...",
        "images": [
          {
            "id": 9896,
            "url": "https://lb-community-staging.s3.amazonaws.com/uploads/image/asset/9896/large_filled_PurpleBit.jpg",
            "caption": "Picture 1"
          }
        ]
      }
    ]
  },
  "meta": {
    "criteria": {
        "method": "GET",
        "endpoint": "/api/v1/projects/2055",
        "params": [
          {
            "name": "id",
            "value": 2055
          },
          {
            "name": "slug",
            "value": null
          }
        ]
      },
      "success": true,
      "errors": null
    }
  }

```

`GET http://{server}/api/v2/projects/{:id|:slug}`

This request can be optionally authenticated to receive `liked_by_user`.

### Examples

`GET http://{server}/api/v2/projects/16`

`GET http://{server}/api/v2/projects/robot`

repository: littlebitselectronics/web-api-docs

repo_name: littlebitselectronics/web-api-docs


text:
## Contributing

[fork]: https://github.com/actions/virtual-environments/fork
[pr]: https://github.com//actions/virtual-environments/compare
[code-of-conduct]: CODE_OF_CONDUCT.md

Hi there! We're thrilled that you'd like to contribute to this project. Your help is essential for keeping it great.

Contributions to this project are [released](https://help.github.com/articles/github-terms-of-service/#6-contributions-under-repository-license) to the public under the [MIT](LICENSE.md).

Please note that this project is released with a [Contributor Code of Conduct][code-of-conduct]. By participating in this project you agree to abide by its terms.

## Submitting a pull request

1. [Fork][fork] and clone the repository
1. Create a new branch: `git checkout -b my-branch-name`
1. Make your changes, ensure that they include steps to install and validate post-install (e.g. [kind.sh](images/linux/scripts/installers/kind.sh)).

      Adding tool for Windows images:
    - add tool installation script `Install-ToolName.ps1` (`/images/win/scripts/Installers`)
    - add tool validation script `Validate-ToolName.ps1` (the same directory)
    - add changes to document tool name and version to the software report generator: `images/win/scripts/SoftwareReport/SoftwareReport.Generator.ps1` that is used to generate software README file, e.g. [Windows2019-Readme.md](images/win/Windows2019-Readme.md)

1. Test your changes by [creating VHD and deploying a VM](help/CreateImageAndAzureResources.md).
1. Push to your fork and [submit a pull request][pr]

Here are a few things you can do that will increase the likelihood of your pull request being accepted:

- Follow the style guide for [Powershell](https://github.com/PoshCode/PowerShellPracticeAndStyle) when writing Windows scripts. There is currently no set style for the Shell scripts that run Linux installs :soon:.
- Include complete details of why this is needed in the PR description. If it's a new piece tool being installed, consider cross-platform. If the tool is available in other platforms (MacOS, Windows, Linux), make sure you include it in as many as possible.
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
- Write [good commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).

## Resources

- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
- [Using Pull Requests](https://help.github.com/articles/about-pull-requests/)
- [GitHub Help](https://help.github.com)


text:
# Halligan JS: Service Container

![NPM](https://img.shields.io/npm/l/@halliganjs/service-container)
[![Build Status](https://travis-ci.com/halliganjs/service-container.svg?branch=main)](https://travis-ci.com/halliganjs/service-container)
[![Coverage Status](https://coveralls.io/repos/github/halliganjs/service-container/badge.svg?branch=main)](https://coveralls.io/github/halliganjs/service-container?branch=main)
[![Total alerts](https://img.shields.io/lgtm/alerts/g/halliganjs/service-container.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/halliganjs/service-container/alerts/)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/halliganjs/service-container.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/halliganjs/service-container/context:javascript)
![npm](https://img.shields.io/npm/v/@halliganjs/service-container)
![npm](https://img.shields.io/npm/dm/@halliganjs/service-container)
![npm bundle size](https://img.shields.io/bundlephobia/min/@halliganjs/service-container)
![Maintenance](https://img.shields.io/maintenance/yes/2022)

The Service Container provides a very simple, centralized container that stores and resolves libraries, objects, and values to better organize code, manage dependencies, and enhance testability.

Benefits:

- Encourages up-front, centralized dependency configuration
- Configuration allows for resolving values, one-time-run factories, and multi-run factories
- Defers dependency resolution to mitigate circular references
- Allows for easy mocking during unit testing

## Table of Contents

* [Installation](#installation)
* [Usage](#usage)
    * [Creating the Container](#creating-the-container)
    * [Registering Values](#registering-values)
        * [`instance(key: any, value: any)`](#instancekey-any-value-any)
        * [`singleton(key: any, value: (container: ContainerInterface) => any)`](#singletonkey-any-value-container-containerinterface--any)
        * [`binding(key: any, value: (container: ContainerInterface) => any)`](#bindingkey-any-value-container-containerinterface--any)
    * [Retrieving Values](#retrieving-values)
        * [`make(key: any)`](#makekey-any)
            * [Type-hinting Supprt [TypeScript Only]](#type-hinting-supprt-typescript-only)
    * [Binding Fakes and Mocks for Unit Testing](#binding-fakes-and-mocks-for-unit-testing)
        * [`fake(key: any, value: any)`](#fakekey-any-value-any)
        * [`reset(hard: boolean)`](#resethard-boolean)
    * [Bundling Registrations with Providers](#bundling-registrations-with-providers)
        * [Creating a `Provider`](#creating-a-provider)
        * [Register `Provider` with `provider (provider: Provider)`](#register-provider-with-provider-provider-provider)

## Installation

The Service Container is registered on NPM and can be installed with both `npm` and `yarn`.

```sh
# Install with NPM
$ npm i @halliganjs/service-container

# Install with yarn
$ yarn add @halliganjs/service-container
```

## Usage

### Creating the Container

The Service Container is a class that needs to be instantiated. The resulting instance should be exported for use throughout your application as a singleton so that everything interacts with the same instance of the container.

```js
const { Container } = require('@halliganjs/service-container')

const container = new Container()

module.exports = container
```

### Registering Values

There are 3 methods for registering values, depending on how the value is used.

#### `instance(key: any, value: any)`

The `instance()` method is used to register a single value to a specific key. When an instance value is resolved from the container the value provided is the exact same value that will be returned. This makes `instance()` great for registering strings, numbers, and libraries that either don't need to be constructed or do not depend on other items in the container.

Since bindings are stored in a `Map`, any value can be used as a key, including library references themselves.

> Note: values such as objects, functions, and arrays are passed by reference, so be careful mutating such values when resolved from the container.

```js
const container = require('./container.js')
const axios = require('axios')

// Registers the number 3 to the key 'loginAttemptsAllowed'
container.instance('loginAttemptsAllowed', 3)

// Registers the string 'TESTING' to the key 'typeConstant'
container.instance('typeConstant', 'TESTING')

// Registers the library axios to the key that is a reference to the axios library
container.instance(axios, axios)
```

#### `singleton(key: any, value: (container: ContainerInterface) => any)`

The `singleton()` method is used to register a closure that is responsible for building a value to a specific key. The _first time_ the value is requested the closure will be run and its return value will be stored as the new value for that key as if it was registered with `instance()`. The new value will always be returned as the value for the key.

This method is perfect for when you want a singleton instance, but it has to be made from other items that may be in the container.

The container instance is provided as the only parameter to the closure.

Since bindings are stored in a `Map`, any value can be used as a key, including library references themselves.

```js
const container = require('./container.js')
const Network = require('./Network')
const axios = require('axios')

// The closure is registered to the Network key.
// When resolved for the first time, the closure will be run and its value will replace the closure as the value of the key
// The closure recieves the container as its only parameter
container.singleton(Network, (container) => {
    return new Network(container.make(axios))
})

// Registers the closure to the key 'randomNumber'.
// When the value is requested the first time the closure is run and the random number is stored
// The same number will always be returned when the key 'randomNumber' is requested because the closure is only run once
container.singleton('randomNumber', () => {
    return Math.floor(Math.random() * 10)
})
```

#### `binding(key: any, value: (container: ContainerInterface) => any)`

The `binding()` method is used to register a closure that is responsible for building a value to a specific key. Unlike `singleton()`, the closure registered with `binding()` is run _every single time the value is requested_. As a result, a new value is given every time the value is requested.

This method is perfect for when you want a new value or a new instance of a class every time you request one from the container.

The container instance is provided as the only parameter to the closure.

Since bindings are stored in a `Map`, any value can be used as a key, including library references themselves.

```js
const container = require('./container.js')
const User = require('./User')
const Network = require('./Network')

// The closure is registered to the User key.
// A new instance of User will be provided every time the key is requested
// The closure recieves the container as its only parameter
container.binding(User, (container) => {
    return new User(container.make(Network))
})

// Registers the closure to the key 'randomNumber'.
// A new number will always be returned when the key 'randomNumber' is requested
container.binding('randomNumber', () => {
    return Math.floor(Math.random() * 10)
})
```

### Retrieving Values

#### `make(key: any)`

Once values and factory functions have been registered into the container, they can be retrieved by calling `make()` with the key you wish to retrieve.

```js
const container = require('./container')
const Network = require('./Network')
const User = require('./User')

const randomNumber = container.make('randomNumber')
const network = container.make(Network)
const user = container.make(User)
```

##### Type-hinting Supprt [TypeScript Only]

When calling the `make()` method inside a TypeScript environment, you may choose to provide a generic type that will be used as the return type of the `make()` method for type-hinting purposes. If you choose not to provide a generic type, then TypeScript will assume that the returned value has a type of any.

```js
// Default behavior - value has a type of any
const value = container.make(MyClass)

// Opt-in behavior - newValue has a type of MyClass
const value = container.make<MyClass>(MyClass)
```

> Note: Be careful when defining the return type of the `make()` method. TypeScript does not check that the value returned is the correct type, it merely casts the type for type-hinting purposes.

### Binding Fakes and Mocks for Unit Testing

One of the best features of a centralized service container is that it is really easy to fake, mock, and stub dependencies when unit testing. So long as your code retrieves values from the container, you can have the container provide your mock during testing and the code under test won't know the difference.

The Service Container provides several methods that make this process easy and straightforward, from binding fake values to resetting the container so that each individual test starts with a full original container.

#### `fake(key: any, value: any)`

The `fake()` method behaves exactly like the `instance()` method, except the value provided to it is stored separately and tagged as a fake. When a fake value is registered and `make()` is called, the fake value will be provided until it is cleared with `reset()`.

For unit testing, create your mock value and register it with `fake()`. When the code you intend to test runs and requests the value for the key you have faked, the fake value will be returned. When the test is finished executing, call `reset()` and the fake value will be removed so the next test will use the real value again.

> `fakeInstance()` is an alias for `fake()` since instance binding is almost exclusively what unit testing will need. `fakeSingleton()` and `fakeBinding()` exist as well for the sake of completeness, with signatures that match their non-fake versions, but are not likely to be necessary.

```js
const container = require('./container')
const moment = require('moment')

describe('Test description', function () {
  it('should use the fake moment', function () {
    // Create the fake
    const fakeMoment = {
      normalizeUnits () {
        return 'year'
      }
    }

    // Register the fake
    container.fake(moment, fakeMoment)

    // Run your test
    const result = myCode.doSomethingWithMoment()
    assert.equal(result, 'year')

    // Reset the container (see the reset() docs for better ways to do this)
    container.reset()
  })
}
```

#### `reset(hard: boolean)`

If you are registering fakes in a unit test, odds are you don't want the fakes from one test to bleed into other tests. The `reset()` method allows you to eliminate all the fakes currently registered so that only actual bindings remain. By calling `reset()` between tests, you are guaranteed that each test only fakes what it needs and relies on actual bindings for everything else, regardless of what other tests do.

While you could call `reset()` at the end of every test, all the major test runners provide some means of running functions before each test or after each test. It is highly recommended that you reset your container in a global before-each or after-each function so that it is automatic and not reliant on developers remembering to redundantly call `reset()` in all of their tests.

> If you wish for the container to be cleaned of _ALL_ of its bindings, both fakes and actual ones, then pass `true` as the first argument to `reset()` for a hard reset that eliminates all bindings.

```js
const container = require('./container')
const moment = require('moment')

describe('Test description', function () {
  beforeEach(function () {
    // Ensure that the container is always clean before a test runs
    container.reset()
  })

  it('should use the fake moment', function () {
    // Create the fake
    const fakeMoment = {
      normalizeUnits () {
        return 'year'
      }
    }

    // Register the fake
    container.fake(moment, fakeMoment)

    // Run your test
    const result = myCode.doSomethingWithMoment()
    assert.equal(result, 'year')
  })
})
```

### Bundling Registrations with Providers

While it's fairly easy to create a container and wire it up together all at once, it is not always the most organized way. Also, if you want to reuse libraries across projects, you will need to duplicate the registrations in every project that you use that library in.

To make life easier, the container supports providers, which are just a way to bundle multiple registrations on a container into one callback. This allows you to organize multiple registrations for the same service, or the same category of services, into a single file that exports a `Provider` closure. When the closure is registered with the container, the container will extract all of the registrations automatically. This makes providers a great way to organize similar services together, or to bundle with a library you use across projects so you can just reference the bundled provider for consistent, DRY service registration.

#### Creating a `Provider`

A `Provider` is just a closure that accepts the container as its only parameter. Inside the closure you can run as many operations (such as `instance()`, `singleton()`, and `binding()`) as you like on the container. Once given to the container, the `Provider`'s registrations will all be run on the container itself.

```js
// in ./providers/dBProvider.js
const DBConnection = require('./DBConnection')
const ModelFactory = require('./ModelFactory')

// This closure is the Provider, and registers two items into the container
module.exports = function (container) {
  container.singleton(DBConnection, function () {
    return new DBConnection(
      process.env.DB_HOST,
      process.env.DB_USER,
      process.env.DB_PASS
    )
  })

  container.binding(ModelFactory, function (container) {
    return new ModelFactory(container.make(DBConnection))
  })
}
```

#### Register `Provider` with `provider (provider: Provider)`

Once you have services organized into one or more providers, they just need to be registered with the container. This is done by calling `provider()` on the container instance and passing your provider. The container will take the provider and run it, registering each item defined within the provider.

> Note: Unlike `instance()`, `singleton()`, and `binding()` registrations, providers are not stored or remembered by the container. Only the items that the provider registers by calling `instance()`, `singleton()`, and `binding()` are stored.

```js
//in ./container.js
const Container = require('@halliganjs/service-container')
const DBConnection = require('./DBConnection')
const dbProvider = require('./providers/dBProvider.js')

// Instantiate container instance
const container = new Container()

// Register the provider
container.provider(dbProvider)

// All the provider's registered items are now available in the container
const dbConnection = container.make(DBConnection)
```

---

Inspired by the [Laravel Service Container](https://github.com/illuminate/container).

repository: halliganjs/service-container

gha_language: TypeScript

repo_name: halliganjs/service-container


text:
## The RxPlayer

The RxPlayer is a media player library allowing to play DASH, Smooth streaming and other similar streaming contents in any application.

The RxPlayer does not come with an UI in itself as the idea is to let you have a full control over your application's experience.

What happens here is that you provide only a `<video>` or `<audio>` element to it (and optionally a separate element to display text tracks) an URL to the content (for example, to the DASH's MPD) and the configuration you want (the languages, control over the quality etc.) and the RxPlayer takes care of every little details to play the content inside that element:
```js
import RxPlayer from "rx-player";

// take the first video element on the page
const videoElement = document.querySelector("video");

const player = new RxPlayer({ videoElement });

player.loadVideo({
  url: "https://www.example.com/Manifest.mpd",
  transport: "dash",
  autoPlay: true,
});
```

## The documentation pages

Those pages are splitted into multiple categories:

  - You're here in the "Getting Started" category which provides tutorials and
    other resources allowing to help you with basic usage of the RxPlayer.

  - You can also dive into the [API](../api/Overview.md), which specifies the
    behavior of everything that is possible with the RxPlayer.

repository: canalplus/rx-player

repo_name: canalplus/rx-player


text:
### Movie Tracker Mobile

![Screen Shot](https://github.com/Miltonr87/Movie-Tracker-Mobile/blob/main/movieretracker.png)

[X] Mobile version

### About

Made with React and **Mobile First techniques**, the Web APP consumes an API provided by [MovieDB](https://www.themoviedb.org/). This application was used to learn how to manipulate the JSON data array with **Fetch API** and convert it into a visual model with images, note and description. To build it I used the most modern tool in React documentation called **Hooks API**.

### Getting Started

- Clone the repo (HTTP Protocol): ```git clone https://github.com/Miltonr87/Movie-Tracker-Mobile.git```
- Using NPM or Yarn to install the React APP and run the project on your computer.

### Required:

As you see, **Movie Tracker Mobile** runs on [Node.js](https://nodejs.org/), so before you can continue, please ensure that you have it installed with NPM or Yarn. Once you have Node installed, you will need the React (17.01) library. So, to start the project in your machine, open your terminal inside the Movie Tracker Mobile folder and type "NPM Install" or "Yarn Install".

### Live Demo

- [LIVE DEMO HERE](https://movie-tracker-mobile.vercel.app)

#### License

This project is licensed under the [MIT License](https://magno.mit-license.org/2018). Copyright © Milton Rodrigues


text:
---
layout: article
title: "Challenges in building Unity native plugins"
headline: ""
date: 2015-08-05T04:20:38+02:00
estimate: "10 mins"
categories: [unity3d, getsocial]
post: true
external: true
sourceName: "The GetSocial Blog"
sourceUrl: "https://www.getsocial.im/blog/challenges-in-building-unity-native-plugins/"
---

### Prehistory

Half a year ago GetSocial Mobile team had to prepare and release SDK v.3.0 with a lot of new cool features and breaking changes from 2.x version. Just in that time I've joined a company and had a chance to make a complete revamp of Unity SDK.Half a year ago GetSocial Mobile team released SDK v.3.0 with a lot of new cool features and breaking changes from 2.x version. Since then, I’ve joined GetSocial and have had an opportunity to make a complete revamp of their Unity SDK.

In this series of posts, I’ll describe what decisions we made and what challenges our team faced with developing the [GetSocial Unity SDK](https://github.com/getsocial-im/getsocial-unity-sdk).

### Approaches in building Unity SDK

First, we needed to decide which approach to go for in order to create an SDK.

At that moment, we had [Android SDK](https://github.com/getsocial-im/getsocial-android-sdk) written in Java and [iOS SDK](https://github.com/getsocial-im/getsocial-ios-sdk) in ObjectiveC, both completely native to achieve the best performance and user experience. Unity supports three scripting languages: C#, UnityScript (aka JavaScript), and Boo. We decided to expose API in C# as it's [the most widely used one](http://blogs.unity3d.com/2014/09/03/documentation-unity-scripting-languages-and-you/).

Let’s check which options we had to achieve the goal...

##### Pure C# SDK

The best approach from developer and user perspective as

- it delivers the best performance;
- it is simple to setup;
- we could make SDK available to 21 platforms supported by Unity.

Looks like an ideal solution, but there are few huge disadvantages:

- at the end we'll have a third huge codebase that should be kept in sync with iOS and Android ones;
- all UI should be reimplemented in C# that is not the easiest task as all games use different UI frameworks.

##### Cross-compilation to C\#

According Google [report](http://gmailblog.blogspot.nl/2014/11/going-under-hood-of-inbox.html), that they managed to reuse 70% of code between Android, iOS and Web Inbox clients, we were so impressed by the idea that decided to give it a try.

Because of similarity between Java and C# we digged in a direction of recompiling Android SDK to C#.

From a positive side, we found that:

- there are tools for cross-compilation like [Java Language Conversion Assistant](http://www.microsoft.com/en-us/download/details.aspx?id=14349) from Microsoft;
- in theory, in the end we get C# library, that is fast;
- and possible to use on all Unity supported platforms.

On the other hand:

- it's not possible to cross-compile presentation layer as it uses Android APIs. That means we need to replicate UI part of the SDK manually on C#;
- cross-compilation required a clear separation between business and presentation logic, which would lead to a huge refactoring in Android SDK;
- it would be hard to establish automated C# SDK regenerations when Java source is updated, as cross-compilers produce [upgrade issues](https://msdn.microsoft.com/en-us/library/5atsz094(v=vs.71).aspx) that should be fixed manually.

##### Unity native plugin

Native plugins are platform-specific native code libraries. They can access features like OS calls and third-party code libraries that would otherwise not be available to Unity.

Pros:

- very few code needed; a bridge is a thin adapter layer between API exposed in C# and native SDKs;
- 100% code reuse from native SDKs;
- UI rendering is handled by native side => no problem with variety of Unity UI frameworks.

Cons:

- we’d be able to deploy only to iOS and Android Unity games;
- native SDKs API should be in sync to avoid huge amount of adapter's code in a bridge;
- Unity Java Native Interface implementation has issues (Unity engineers fix them quickly but tend to add a new one on each release).

### Selected approach

We decided to go with Unity native plugin approach as it required the least effort, gave plenty of advantages and flexibility. Now GetSocial Unity SDK has the following architecture:
![GetSocial Unity SDK Architecture]({{ site.baseurl }}/img/posts/challenges-in-building-unity-native-plugins-intro-sdk-architecture.png)

Between C# API and native libraries, we have a bridge layer on Unity and native side. The main task for the bridge is to invoke methods between platforms and convert data to primitive types as we can’t pass objects between platforms.

To communicate between C# code and native side, Unity exposes a wide variety of APIs. On Android: Unity Messaging (the one we use to send messages between GameObjects) and wrappers around Java Native Interface. On iOS, we can invoke extern methods from ObjectiveC and use MonoPInvokeCallbackAttribute to call C# methods from the iOS world.

### Everything is simple, right?

The theory is simple: thin bridge layer, few calls between C# and native platforms, nice demo app and problem solved. But a simple solution doesn’t come without any challenges. Here are a few of my favorites:

 - **performance**: potentially bridge could become a performance-wise bottleneck, especially if calls will be made on each frame (keep in mind [16ms rule](https://www.youtube.com/watch?v=CaMTIgxCSqU));
 - **testability**: with Unity native plugin approach most of the SDK will be in the native code, that means we can test only on iOS or Android device/simulator, but not Unity player;
 - **continuous delivery**: SDK consist of 3 parts, each one has it own build process, setting up build pipeline could be complicated;
 - **version fragmentation**: Unity is a very dynamic platform, each release brings tons of cool features and ... new bugs. Unlike game developers who can select Unity version and use it during whole game life, we have to support all Unity versions starting, at least, from 4.1.

### Want to know more?

It was only a first post from the series, follow GetSocial on social networks in order not to miss updates and don't hesitate to share your thoughts and experience with building Unity plugins in comments.

repository: zasadnyy-inc/v-zasadnyy-com

extension: markdown

gha_language: HTML

repo_name: zasadnyy-inc/v-zasadnyy-com


text:
# autoMEGA - Release Mirror

> This is the latest release of autoMEGA. To submit feature requests, bug reports, or to view the development tree, go to [gitlab.com/cbray/autoMEGA](https://gitlab.com/cbray/autoMEGA)

Tool for automating MEGAlib simulations. The goal is to create a user-friendly method for running iterative simulations.

Features:
- Automatically generate modified Geomega (`*.geo.setup`) and Cosima (`*.source`) files
  - Flexible parameters
  - Unlimited configurations
- Capable of running dozens of simultaneous simulations
  - Ideal for optimizing instrument dimensions, generating plots of continuum sensitivity, or calculating Aeff
- User-Friendly
  - Convenient YAML configuration
  - Capable of notifying the user of simulation completion (or errors)
    - Email
    - Slack
- ~~Causes robot uprising~~

## Notes

The library is currently in a early release state. Bug reports and feature requests welcome!

### Dependencies:
- MEGAlib (Tested on v2.34)
- yaml-cpp (0.5 or newer)
- g++ with C++11 (Tested on 5.4.1, 7.3.0, and 8.1.1)
   - clang++ may replace g++, but may require modifications to the Makefile (tested on clang++ 6.0.1)
- sendmail (optional, required only for email functionality)
- curl (optional, required only for slack functionality)
- backward-cpp and libdw-dev (optional, required only for debug functionality. backward-cpp is automatically fetched during `make debug`)

### To compile:

```
make
```

Or, manually:
```
g++ checkGeometry.cpp -o checkGeometry -std=c++11 -pthread -lyaml-cpp -O2 -Wall $(root-config --cflags --glibs) -I$MEGALIB/include -L$MEGALIB/lib -lGeomegaGui -lGeomega -lCommonGui -lCommonMisc
g++ autoMEGA.cpp -o autoMEGA -std=c++11 -pthread -lyaml-cpp -O2 -Wall
```

Go to [Gitlab pages](https://cbray.gitlab.io/autoMEGA/autoMEGA_8cpp.html) for full documentation.

[![pipeline status](https://gitlab.com/cbray/autoMEGA/badges/master/pipeline.svg)](https://gitlab.com/cbray/autoMEGA/pipelines)

repository: ComPair/autoMEGA

repo_name: ComPair/autoMEGA


text:
This app uses Android Architecture Components with Dagger 2.

You can open the project in Android Studio 3 and press run.

## Libraries
* [Android Support Library][support-lib]
* [Android Architecture Components][arch]
* [Android Data Binding][data-binding]
* [Dagger 2][dagger2] for dependency injection
* [Firebase][realtime] for data and auth
* [Glide][glide] for image loading
* [Timber][timber] for logging
* [ChatKit][chatkit] for UI

[support-lib]: https://developer.android.com/topic/libraries/support-library/index.html
[arch]: https://developer.android.com/arch
[data-binding]: https://developer.android.com/topic/libraries/data-binding/index.html
[dagger2]: https://google.github.io/dagger
[realtime]: https://firebase.google.com/
[glide]: https://github.com/bumptech/glide
[timber]: https://github.com/JakeWharton/timber
[chatkit]: https://github.com/stfalcon-studio/ChatKit


text:
# Ranges
The `Ranges` unit contains types to iterate over ranges of numbers or elements.

## Types
This unit introduces 3 types:
* `TRange` represents a range `[Start, Stop)` (inclusive start, exclusive stop) with a given `Step` size. E.g. `Range(0, 10, 2)` is `[0, 2, 4, 6, 8]`
* `TArrayRange<T>` references a subset of an array, without copying any elements. E.g. `TArrayRange<Integer>.Create([1, 2, 3], 0, 2)` represents the values `1, 2` without having to copy that array
* `TListRange<T>` is the same as `TArrayRange` just for `TList<T>` objects

Each of these types is iterable and provides the `[]` operator to directly access an element in that range:
```pascal
for i in Range(5, 10) do
  WriteLn(i);
// same as
rng := Range(5, 10);
for i := 0 to rng.Count - 1 do
  WriteLn(rng[i]);
```
With `[]` objects can be referenced from the back, e.g. `Range(0, 10)[-1]` is the last element in that range, i.e. 9.

Also subranges can be taken, e.g. `Range(5, 10).SubRange(2, 3)` is equivalent to `Range(7, 8)`.
The step size is multiplied, e.g. `Range(0, 10, 2).SubRange(0, 10, 2)` is `[0, 4, 8]`
The constants `RangeBegin` and `RangeEnd` can be used to reference the start and Stop values for `SubRange` without needing to know the actual numbers.
Also relative ranges can be used here: `Range(0, 10).SubRange(-3)` will cover the last 3 elements of the range

### Array/List Ranges
`TArrayRange` and `TListRange` allow for accessing parts of an array/list without copying the data. The ranges also allow referencing relative to the array like subranges:
```pascal
arr := [1, 2, 3, 4, 5, 6];
// Last 3 elements of the array
for i in TArrayRange<Integer>.Create(arr, -3) do
  WriteLn(i);
```
To avoid having the lazy copy mechanism take place `TArrayRange` references the target array by pointer, i.e. if the array get's destroyed before the range does, the range will cause use after free errors.

Array- and List ranges can also be created throug an implicit cast, to cover the whole array/list:
```pascal
rng := [0, 1, 2, 3];
for i in rng.SubRange(RangeBegin, RangeEnd, -1) do
  ...
```

### Conversion to Lists and Arrays
`TRange` provides `ToArray` to create an array of all the numbers covered, `ToList` to create a `TList<SizeInt>` of them and `FillList(AList)` to add the numbers to a list.
`TArrayRange` and `TListRange` have a `Copy` function to create an array/list from that subrange.

repository: Warfley/Recutils

repo_name: Warfley/Recutils


text:
EMACS AT THE EXCHANGE

The lingua franca of this project is Lisp. Adopting Lisp means we can switch from working on one part of the tool chain to another without having to switch syntax. That makes the parts of the project more cohesive. Emacs, built with Lisp, has been around so long it is nearly organic to Lisp itself.  Thanks to Richard Stallman and the Gnu Project./p>

With Emacs, we can open a window on any part of the toolchain and work there.  It is the glue.  Let me suggest a few lines for emac's init.el file to help with that.

I use clojure-mode for working with lisp in Emacs, once that is installed, add:

(add-to-list 'auto-mode-alist '("\\.hy\\'" . clojure-mode))

to the init.el file so Hy lisp buffers also use clojure-mode.

Look at the eLisp-snippet file in this folder. The idea there is pretty straight forward: You "C-u M-x: shell" in Emacs and give the shell buffer you are creating a name you have pre-defined in Emacs as a buffer to which you will be sending Lisp commands.  So for example, in the snippet I refer to, there is a line that says:

(define-key clojure-mode-map (kbd "C-w")
      (lambda () (interactive) (repl-eval-last-expression "brepl")))

What that means is, after you setup your Client's repl environment as described here, and configured the Nginx part of the Server as decribed here you will be able to talk to the client application running in a web browser just by entering "C-w" at the end of a lisp expression in Emacs.

This basic ability of Emacs to send commands between open windows running seperate repl environments multiplies in utility as development becomes more complex.  For example, consider the following screenshot.

From window A, we can direct commands into any of three available repl environements (B, C, D) which could all be windowed into different parts of the workflow e.g., the Desktop, the Server, and the Client development environments.

So also add the eLips-snippet.el file in this folder to your emacs init.el file and visit the repl setup page here. To get your repls going.

repository: tecumsehcommunications/StarlinkViewer

repo_name: tecumsehcommunications/StarlinkViewer


text:
## Upgrading from Nock 11 to Nock 12

[Release Tag](https://github.com/nock/nock/releases/tag/v12.0.0)

### Breaking changes

1. Support for Node < 10 was dropped.
   To upgrade Nock, ensure your version of Node is also updated.
   At the time of release, Node 10.x, 12.x, and 13.x were supported.

1. [`cleanAll()`](https://github.com/nock/nock#cleanall) no longer returns the global `nock` instance ([#1872](https://github.com/nock/nock/pull/1872)).

   ```js
   // before
   nock.cleanAll().restore() // Uncaught TypeError: Cannot read property 'restore' of undefined

   // upgraded
   nock.cleanAll()
   nock.restore()
   ```

1. Support was dropped for the String constructor ([#1873](https://github.com/nock/nock/pull/1873)).
   Only string primitive are supported. All strings passed to Nock for options should not use `new String` syntax.
   [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#String_primitives_and_String_objects).

### New features for developers

1.  [`enableNetConnect()`](https://github.com/nock/nock#enabling-requests) now accepts a function.
    ```js
    nock.enableNetConnect(
      host => host.includes('amazon.com') || host.includes('github.com')
    )
    ```

repository: nock/nock

gha_language: JavaScript

repo_name: nock/nock


text:
# Answers for Interview Questions suggested by DAXX (2014)

Answers for questions suggested in the article *[How to Hire the Right Offshore Ruby on Rails Developer: Ruby on Rails Interview Questions](https://www.daxx.com/article/how-hire-offshore-ruby-on-rails-developer)*.

You may know all the answers and might have used most of these in your day to day work, but it helps to write it down again so that you may put it in words when interviewed.

Note that the article was published July 21, 2014.

## Questions

### Ruby Interview Questions

1. How do you define class, instance, and global variables?

    - Class Variables
    ```ruby
    class Song
      @@plays = 0
    end
    ```
    **Important note on this and Class Level Instance Variables [here](http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/).**
    - Instance variables
    ```ruby
    class Person
      def initialize
        @name = "Tom"
      end
    end
    ```
    Or if you want it defined with getter and setter methods
    ```ruby
    class Person
      attr_accessor :name

      def initialize
        @name = "Tom"
      end
    end
    ```

    More on [attr_accessor](http://stackoverflow.com/a/4371458/250703).
    - Global Variables
    ```ruby
    $global_variable = 10
    ```

2. What is rubygems?

    [RubyGems.org](https://rubygems.org/) is the Ruby community’s gem hosting service, where everyone can instantly publish gems and then install them.

3. What is a module?

    From [Ruby Docs](http://ruby-doc.org/core-2.2.0/Module.html).

    *A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not. Conversely, module methods may be called without creating an encapsulating object, while instance methods may not.*

    From [rubylearning.com](http://rubylearning.com/satishtalim/modules_mixins.html):
    Modules serve two purposes:
    - They act as namespace:
    ```ruby
    # p058mytrig.rb
    module Trig
      PI = 3.1416
      # class methods
      def Trig.sin(x)
        # ...
      end
      def Trig.cos(x)
        # ...
      end
    end

    # p059mymoral.rb
    module Moral
      VERY_BAD = 0
      BAD         = 1
      def Moral.sin(badness)
        # ...
      end
    end

    # p060usemodule.rb
    require_relative 'p058mytrig'
    require_relative 'p059mymoral'
    Trig.sin(Trig::PI/4)
    Moral.sin(Moral::VERY_BAD)
    ```

    - They allow you to share functionality between classes (mixins):
    ```ruby
    module Persister
      def save_to_file
        ...
      end
    end

    class WorkSheet
      include Persister

      def do_stuff
        ...
      end
    end

    worksheet = WorkSheet.new
    worksheet.do_stuff
    worksheet.save_to_file
    ```
4. What is a Range?

    From [Ruby Docs](https://ruby-doc.org/core-2.2.0/Range.html).

    *A Range represents an interval—a set of values with a beginning and an end. Ranges may be constructed using the s..e and s...e literals, or with ::new. Ranges constructed using .. run from the beginning to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence.*

    ```ruby
    (-1..-5).to_a      #=> []
    (-5..-1).to_a      #=> [-5, -4, -3, -2, -1]
    ('a'..'e').to_a    #=> ["a", "b", "c", "d", "e"]
    ('a'...'e').to_a   #=> ["a", "b", "c", "d"]
    ```

5. What is a Symbol?

    From [Ruby Docs](http://ruby-doc.org/core-2.2.0/Symbol.html).

    *Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program's execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.*

    ```ruby
    (-1..-5).to_a      #=> []
    (-5..-1).to_a      #=> [-5, -4, -3, -2, -1]
    ('a'..'e').to_a    #=> ["a", "b", "c", "d", "e"]
    ('a'...'e').to_a   #=> ["a", "b", "c", "d"]
    ```

6.

    The same Symbol object will be created for a given name or string for the duration of a program's execution. This is not true with strings.

    ```ruby
    :my_symbol.object_id  #=> 544168
    :my_symbol.object_id  #=> 544168
    :my_symbol.object_id  #=> 544168

    "my_string".object_id #=><PHONE_NUMBER>1160
    "my_string".object_id #=><PHONE_NUMBER>2940
    "my_string".object_id #=><PHONE_NUMBER>6700
    ```

7. How do “and” and “&&” operators differ?

    From [Difference between “and” and && in Ruby?](http://stackoverflow.com/a/1426835/250703).

    `and` is the same as `&&` but with [lower precedence](http://phrogz.net/ProgrammingRuby/language.html#table_18.4). They both use [short-circuit evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation).

    **WARNING:** `and` even has lower precedence than `=` so you'll want to avoid `and` always

8. How do you define a custom Exception?

    ```ruby
    class MyError < StandardError
    end
    ```

### Rails Interview Questions
1. What is Scope in Rails?

    As stated in the [Rails Guides](http://guides.rubyonrails.org/active_record_querying.html#scopes), scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method such as where, joins and includes. All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it.

    ```ruby
    class Article < ApplicationRecord
      scope :published, -> { where(published: true) }
    end
    ```

2. What is a sweeper?

    From Action Controller Sweeper in [rails-observers](https://github.com/rails/rails-observers#action-controller-sweeper).

    *Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change. They do this by being half-observers, half-filters and implementing callbacks for both roles. A Sweeper example:*

    ```ruby
    class ListSweeper < ActionController::Caching::Sweeper
      observe List, Item

      def after_save(record)
        list = record.is_a?(List) ? record : record.list
        expire_page(:controller => "lists", :action => %w( show public feed ), :id => list.id)
        expire_action(:controller => "lists", :action => "all")
        list.shares.each { |share| expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
      end
    end
    ```

    *The sweeper is assigned in the controllers that wish to have its job performed using the cache_sweeper class method:*

    ```ruby
    class ListsController < ApplicationController
      caches_action :index, :show, :public, :feed
      cache_sweeper :list_sweeper, :only => [ :edit, :destroy, :share ]
    end
    ```

3. What is an observer?

    From Action Record Observer in [rails-observers](https://github.com/rails/rails-observers).

    *Observer classes respond to life cycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn't pertain to the core responsibility of the class. Observers are put in app/models (e.g. app/models/comment_observer.rb). Example:*

    ```ruby
    class CommentObserver < ActiveRecord::Observer
      def after_save(comment)
<EMAIL_ADDRESS>"New comment was posted", comment).deliver
      end
    end
    ```

    *This Observer sends an email when a Comment#save is finished.*

4. What is a filter and when is it called?

    From [Rails Guides](http://guides.rubyonrails.org/action_controller_overview.html#filters).

    *Filters are methods that are run "before", "after" or "around" a controller action.*

    *Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.*

    ```ruby
    class ApplicationController < ActionController::Base
      before_action :require_login

      private

      def require_login
        ...
      end
    end
    ```

5. How do you implement caching in Rails?

    See [Rails Guides: Caching with Rails: An Overview](http://guides.rubyonrails.org/caching_with_rails.html).

6. How do you create a REST API for your app?

    - [Building a RESTful API in a Rails Application](https://www.airpair.com/ruby-on-rails/posts/building-a-restful-api-in-a-rails-application) by Abraham Polishchuk.

    - [APIS ON RAILS](http://apionrails.icalialabs.com/book/chapter_one) by Abraham Kuri Vargas.

    - [Rails Guides: Using Rails for **API-only** Applications](http://edgeguides.rubyonrails.org/api_app.html).

7. What is a polymorphic association and how do you implement it?

    From [Rails Guides](http://guides.rubyonrails.org/association_basics.html#polymorphic-associations).

    *With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model.*

    ```ruby
    class Picture < ApplicationRecord
      belongs_to :imageable, polymorphic: true
    end

    class Employee < ApplicationRecord
      has_many :pictures, as: :imageable
    end

    class Product < ApplicationRecord
      has_many :pictures, as: :imageable
    end
    ```

8. What is fields_for used for?

    From the [apidock Rails](http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for).

    *Creates a scope around a specific model object like form_for, but doesn’t create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form.*

    ```ruby
    <%= form_for @person do |person_form| %>
      First name: <%= person_form.text_field :first_name %>
      Last name : <%= person_form.text_field :last_name %>

      <%= fields_for :permission, @person.permission do |permission_fields| %>
        Admin?  : <%= permission_fields.check_box :admin %>
      <% end %>

      <%= person_form.submit %>
    <% end %>
    ```

### Related

1. What is the difference between functional testing and unit testing?

    From Stackoverflow ["Unit tests vs Functional tests"](http://stackoverflow.com/questions/2741832/unit-tests-vs-functional-tests).

    *Unit Test - testing an individual unit, such as a method (function) in a class, with all dependencies mocked up.*

    *Functional Test - AKA Integration Test, testing a slice of functionality in a system. This will test many methods and may interact with dependencies like Databases or Web Services.*

2. Do you have experience using a mocking framework?

    - [RSpec Mocks](https://github.com/rspec/rspec-mocks)

    - [Mocha](https://github.com/freerange/mocha)

3. Do you have any experience with BDD using RSpec or Cucumber?

    - [Applying BDD to Ruby on Rails Web Applications](https://semaphoreci.com/community/tutorials/applying-bdd-to-ruby-on-rails-web-applications)

    - [RSpec](http://rspec.info/)

    - [Cucumber](https://cucumber.io/docs)

4. What plugin would you suggest for full-text search?

    Note: Not *plugins*.

    - [Thinking Sphinx](https://github.com/pat/thinking-sphinx)

    - [Sunspot](https://github.com/sunspot/sunspot)

    - [Searchkick](https://github.com/ankane/searchkick)

    - [elasticsearch-ruby](https://github.com/elastic/elasticsearch-ruby)

5. What is your most used plugin for user authorization?

    - [CanCan](https://github.com/ryanb/cancan)

    - [CanCanCan](https://github.com/CanCanCommunity/cancancan)

    - [Pundit](https://github.com/elabs/pundit)

6. How do you create a plugin?

    See [Rails Guides](http://guides.rubyonrails.org/plugins.html).

    ```ruby
    rails plugin new yaffle
    ```


text:
---
layout: post
tag : Make switching between languages easier
category: "Python for SAS"
title: "Python R SAS Keyboard Shortcuts"
description: comparing Python, R and SAS everyday keyboard shortcuts
author: Sarah Chen
image: images/posts/photos/IMG-0685.jpg

---
![](/images/posts/photos/IMG-0685.jpg)
- [Keyboard shortcuts](#keyboard-shortcuts)
  - [VSCode](#vscode)
  - [Ipython shell commands](#ipython-shell-commands)
  - [RStudio](#rstudio)
- [Add custom snippets](#add-custom-snippets)

# Keyboard shortcuts
Keyboard shortcuts are essential because: when we are used to writing in a language, switching to another one can make use feel slow and dumb. Using keyboard shortcuts will allow us to pick up speed and feel at home.

## VSCode
Although Spyder and Ipython (notebook and shell) both are great, VSCode is especially useful when we are writing packages or modules.  I use VSCode for all three languages.  There are suggested add-ons for each of the languages.
See [keyboard shortcuts pdf](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf) for the comprehensive list.

![VSCode Keyboard Shortcuts](/images/posts/vscode_shortcuts.PNG)
![VSCode Keyboard Shortcuts](/images/posts/vscode_shortcuts.JPEG)
You can also define your own keyboard shortcut.

## Ipython shell commands
These aren't technically shortcuts, but I count them in because they are convinient.

ls cd pwd all work in Ipython shell as they do in command prompt.

%automagic on enables magic commands without having to use prefix "%".

%history -n 2-5 presents history line 2 to 5.

%run myStuff.py: runs code in this directory.

>Functions defined in myStuff.py are alive in the current Ipython session after %run myStuff.py.

And get inspired by others' [notebooks](https://nbviewer.org).

## RStudio
- Ctrl+Enter   To run a line of code from the source editor.
- Ctrl+Shift+M  is the pipe operator  %>% is or Cmd+Shift+M (Mac).
- Alt + -  is the assignment operator <-, or Option + - (Mac).
- Ctrl+L to clear all the code from your console.
- Ctrl+2  and `Ctrl+1` to move the curser back and forth the source editor.
- Ctrl + ↑  to scroll through your command history by clicking  or Cmd + ↑ (Mac).
- Search a matching subset of the history: type the first few characters and then press `Ctrl/Cmd + ↑`
- Rename all instances of a variable name: highlight one instance of the variable name and then using Code > *Rename in Scope*. This is better than using Edit > Replace and Find because it only looks for whole word matches.

# Add custom snippets
Using custom snippets helps save time.  Using 3 languages has a lot of syntax and libraries to remember.
See [how to add a snippet](https://code.visualstudio.com/docs/editor/userdefinedsnippets) for details.

1. Use [snippet generator](https://snippet-generator.app/) to easily create the snippet json code.
2. shift + command + p and type snippets, and then  Preferences: Configure User Snippets.
3. Hit New snippets, then choose language, and follow the directions.  Note, while the snippet is in json, you don't choose json.  Choose Python if the snippet is for Python code, choose markdown if it is for markdown.

gha_language: SCSS


text:
⛔ [DEPRECATED] StockportGovUk.NetStandard.Models

  :gem: :trophy: :art:

  We're the same you and I

  Shared objects used within SMBC

    External Links

      GitHub

     |

      NuGet

  Built with ❤ by
  Stockport Council and

    contributors

## Table of Contents
- [Features](#features)
- [Philosophy](#philosophy)
- [Installation](#installation)

## Features
- __Common approach:__ shared object throughout SMBC estate

## Philosophy
How many time have developers made an Address object, or Customer objects? We have had an issue with this across multiple applications and were sick of it. This package exposes shared objects that are used within the SMBC estate to ensure people use the same object throughout the process

## Installation
```bash
$ dotnet add package StockportGovUK.NetStandard.Models
```

## License
[MIT](https://tldrlegal.com/license/mit-license)

gha_language: C#