text:
---
layout: post
title: Passing TemplateRefs Around in Angular
---

In our Angular apps, we pass data from one component to another all the time. We can facilitate the exchange through a shared service or just use simple input/output bindings if the components are in a direct parent-child relationship. Most often, the data are just plain JavaScript primitives/objects.

But there are interesting use cases when we might want to pass a template/chunk of HTML from one component to another. This is a pretty powerful pattern: we can define the general structure of a common UI component and switch in/out dynamic content based on our app's logic.

Let's explore an example built with the [ng-bootstrap package](https://ng-bootstrap.github.io/). We have a set of reusable modal components to display warnings, prompts etc. and any component in the app can launch one of these modals and insert their custom content into the modal body.

<iframe style="width:100%; height:400px" src="https://stackblitz.com/edit/angular-passing-templaterefs?embed=1&file=src/app/app.component.html&hidedevtools=1"></iframe>

Here's the general pattern. The template is defined in a component with the `ng-template` tag. For example, in `Example1Component`, we have:
```html {% raw %}
<!-- Example1Component -->
<button (click)="warn(tmpl)">Display Simple Warning</button>
...
<ng-template #tmpl>
  <p>This is a simple warning from {{ cmpName }}</p>
</ng-template>
{% endraw %}```

We pass a reference to this template to the click handler of the button. Note that we can treat this templateRef like any other variable. The templateRef is passed to the `displayWarningModal` method in the `ModalService` and then on to the `WarningModalComponent`.
```ts
// ModalService
displayWarningModal(tmpl: TemplateRef<any>) {
    const modalRef = this.modalService.open(WarningModalComponent);
    modalRef.componentInstance.tmpl = tmpl;
}
```
In the `WarningModalComponent`, we can embed this templateRef with the convenient [`*ngTemplateOutlet` directive](https://angular.io/api/common/NgTemplateOutlet). Dealing with the templateRefs in this way keeps our component class clean of `ViewChild` annotations to get access to the templateRef or to the view container in which to insert them.
```html
<!-- WarningModalComponent -->
<ng-container *ngTemplateOutlet="tmpl"></ng-container>
```

Now, the templateRefs keep all our bindings intact. The bindings are evaluated in the context of the original component instance, where they are defined. For example, the string interpolation {% raw %}`{{ cmpName }}`{% endraw %} in `Example1Component`'s template evaluates to _'example1'_ and not _'warning modal'_ as defined in the `WarningModalComponent`. Note that the styling defined in `Example2Component` (`.special { color: orange }`) is applied to its template even though it is instantiated in the `WarningModalComponent`.

The fact that the template maintains a connection to the original component state can be leveraged in interesting ways. In `Example3Component`, we set up two-way binding to the `fontSize` and `fontColor` properties. We can now bring up the settings modal, adjust the options there and instantly see the changes applied to the text.

***

Also check out:
* [Ng-Bootstrap's Modal Component](https://ng-bootstrap.github.io/#/components/modal/examples)
* [Minko Gechev's article, 'Understanding Dynamic Scoping and TemplateRef' ](https://blog.mgechev.com/2017/10/01/angular-template-ref-dynamic-scoping-custom-templates/)
This demonstrates a really nice way to use `ng-template` with content projection.
* [Alex Rickabaugh's AngularMIX talk, 'Advanced Angular Concepts' (HIGHLY RECOMMENDED!)](https://www.youtube.com/watch?v=rKbY1t39dHU)
The first part of the video covers this topic in the context of building a left nav, a portion of which depends on the currently loaded route.


text:
# About

phxDoctrineClassFieldsPlugin adds the concept of "class" fields to Doctrine 1.2,
  allowing you to implement database-backed dependency injection for controlling
  the behavior of containers at runtime.

Doctrine 1.2 does not support custom field types, so this is not a "true" custom
  field type, but it is a good imitation.

# Usage

Once the plugin has been enabled in your Symfony project configuration, you can
  add the behavior to any of your models in `schema.yml`:

    # sf_config_dir/doctrine/schema.yml

    MyModel:
      actAs:
        ClassFields:
          fields:
            plugin:
              interface:  IMyPlugin

Store class names as normal:

    # .../actions.class.php

    public function executeAwesome( sfWebRequest $request )
    {
      ...

      /* @var $mymodel MyModel */
      $mymodel->setPlugin('MyPluginClass');
    }

To instantiate DI class instances, use `getInstance` or `get*Instance`:

    # .../actions.class.php

    public function executeExcellence( sfWebRequest $request )
    {
      ...

      /* @var $myplugin MyPluginClass */
      $myplugin = $mymodel->getInstance('plugin');

      /* This does the same thing: */
      $myplugin = $mymodel->getPluginInstance();
    }

You can also customize the initialization of the DI instance by overriding the
  `postGetInstance()` method in your model:

    # sf_lib_dir/model/doctrine/MyModel.php

    class MyModel extends BaseMyModel
    {
      ...

      public function postGetInstance( $instance )
      {
        $instance->setFoo($this->getBar());
      }
    }

Because of the way Doctrine_Template works, `postGetInstance()` must be public.

## Options

The `ClassFields` behavior accepts the following options:

- `fields`: array of fields that will have the `class` "type".
  - `index`:  name of the index for the class field.  If blank, the field is unindexed (default: `""`).
  - `interface`:  interface that a stored classname must implement to be valid (default: `null`).
  - `length`:  maximum length of class names (default: `200`).
  - `magic`:  whether to create magic methods for instantiating the class (default: `true`).
    If set to a string value, it will override the name of the magic method for this column.
  - `notnull`:  whether the classname must not be empty (default: `false`).
  - `default`:  the default value for the field (default: `null`)
  - `unique`: whether the classname must be unique (default: `false`).
- `magic`: whether to allow creating magic methods for any column (default: `true`).
  If set to a string value, it will override the magic method naming pattern for the table.

Note that `magic` only controls the creation of `get*Instance()` methods.  The
  `getInstance()` method will always be available.

Both the table's `magic` option and the individual column's `magic` option must
  be set to `true`, or else magic methods will not be created for that column.

Fully-loaded example:

    # sf_config_dir/doctrine/schema.yml

    MyModel:
      actAs:
        ClassFields:
          magic:  instantiate*Object
          fields:
            transport:
              interface:  ITransport
              notnull:    true
              default:    GenericTransport
            adapter:
              interface:  IMyModelAdapter
              magic:      getAdapterObject  # For compatiblity with legacy code.
              length:     300               # These names tend to get lengthy.
              index:      adapter_classname_idx
              unique:     true
      columns:
        ...

Note that `ClassFields` will define the class columns and indexes for you
  automatically; there is no need to add them to your model's `columns` and
  `indexes` definitions, respectively.

# Known Issues

- Magic methods for instantiating from relations are not supported... yet.

# Changelog

## 1.0.0

- Initial release.

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
You guild guards the banishment crystals on the isle of
hunters since the last demon war thousands of years ago.  Every hunter is
trained here to be sent out into the world to banish the remaining lesser
demons that haunt the lands of man. During the winter time they come back to
the island to rest, to learn in the halls of wisdom and to record their
experiences in new tomes for the next generations.

You have done this for years, but this time it is different. When you came back
the isle is overrun with lesser demons and greater demons that you never have
seen and that have been banished for hundreds of years.

## Gameplay

There are no loot drops. Every defeated demon gives "Demonshards". They are
used to buy skills when resting.

Weapons, Armor, Talismans, etc. are grabbed from other fallen hunters that
where overwhelmed by the demons.

Potions, Oils, etc. are crafted from materials and herbs that you find on the
island.

## Enemies

### Lesser Demons

Same Stats, Abilities every game. Already in the bestiary from the start. The
type you have been hunting your whole life so far.

### Greater Demons

Stats, Resistance, Abilities are randomly generated every new game. Need to
find books, inscriptions, etc. to get a bestiary entry.

### Archdemons

Stats, Resistance, Abilities are randomly generated every new game. Need to
find books, inscriptions, etc. to get a bestiary entry.  Very powerful.

repository: bnadland/demonshards

repo_name: bnadland/demonshards


text:
---
title: OpenStack
menu:
  docs:
    parent: drivers
    weight: 15
---

kitchen-openstack is a Test Kitchen *driver* for OpenStack.

## Minimum Configuration

```yaml
driver:
  name: openstack
  openstack_username: [YOUR OPENSTACK USERNAME]
  openstack_api_key: [YOUR OPENSTACK API KEY] # AKA your OpenStack Password
  openstack_auth_url: [YOUR OPENSTACK AUTH URL] # if you are using v3, API_URL/v3/auth/tokens
  openstack_domain_id: [default is 'default'; otherwise YOUR OPENSTACK DOMAIN ID]
  require_chef_omnibus: [e.g. 'true' or a version number if you need Chef]
  image_ref: [SERVER IMAGE ID]
  flavor_ref: [SERVER FLAVOR ID]
transport:
  username: ubuntu # For a Ubuntu Box
```

The `image_ref` and `flavor_ref` options can be specified as an exact id,
an exact name, or as a regular expression matching the name of the image or flavor.

All of Fog's `openstack` options (`openstack_domain_name`, `openstack_project_name`,
...) are supported. This includes support for the OpenStack Identity v3 API.

## General Configuration

### name

**Required** Tell test-kitchen what driver to use. ;)

### openstack_username

**Required** Your OpenStack username.

### openstack_api_key

**Required** Your OpenStack API Key, aka your OpenStack password.

### openstack_auth_url

**Required** Your OpenStack auth url. If you are using ID v3, you'll need to use `API_URL/v3/auth/tokens`.

### require_chef_omnibus

**Required** Set to `true` otherwise the specific version of Chef omnibus you want installed.

### image_ref

**image_ref or image_id required** Server Image Name or ID.

### image_id

**image_ref or image_id required** Server Image ID.  Specifying the ID instead of reference results in a faster create time.

**Note** If the image UUID changes this value will need to be updated.

### flavor_ref

**flavor_ref or flavor_id required** Server Flavor Name or ID.

### flavor_id

**flavor_ref or flavor_id required** Specifying the ID instead of reference results in a faster create time.

**Note** If the flavor UUID changes this value will need to be updated.

### server_name

If a `server_name_prefix` is specified then this prefix will be used when
generating random names of the form `<NAME PREFIX>-<RANDOM STRING>` e.g.
`myproject-asdfghjk`. If both `server_name_prefix` and `server_name` are
specified then the `server_name` takes precedence.

### server_name_prefix

If you want to have a static prefix for a random server name.

### port

Set the SSH port for the remote access.

### openstack_tenant

Your OpenStack tenant id.

### openstack_region

Your OpenStack region id.

### availability_zone

Your OpenStack availablity zone.

### openstack_service_name

Your OpenStack compute service name.

### openstack_network_name

Your OpenStack network name used to connect to, if you have only private network
connections you want declare this.

### glance_cache_wait_timeout

When OpenStack downloads the image into cache, it takes extra time to provision.  Timeout controls maximum amount of time to wait for machine to move from the Build/Spawn phase to Active.

### connect_timeout

Connect timeout controls maximum amount of time to wait for machine to respond to ssh login request.

### read_timeout

### write_timeout

Expose read/write timeout parameters passed down to HTTP connection created via [excon](https://github.com/excon/excon). Default timeouts (from excon) are 60 seconds.

### server_wait

`server_wait` is a workaround to deal with how some VMs with `cloud-init`.
Some clouds need this some, most OpenStack instances don't. This is a stop gap
wait makes sure that the machine is in a good state to work with. Ideally the
transport layer in Test-Kitchen will have a more intelligent way to deal with this.
There will be a dot that appears every 10 seconds as the timer counts down.
You may want to add this for **WinRM** instances due to the multiple restarts that
happen on creation and boot. A good default is `300` seconds to make sure it's
in a good state.

The default is `0`.

### security_groups

A list of `security_groups` to join:

```yaml
security_groups:
   - [A LIST OF...]
   - [...SECURITY GROUPS TO JOIN]
   ```

### user_data

If your VMs have `cloud-init` enabled you can use the `user_data` in your
kitchen.yml to inject commands at boot time.

```yaml
    driver_config:
      user_data: userdata.txt
```

Then create a `userdata.txt` in the same directory as your .kitchen.yml,
for example:

```shell
#!/bin/sh
echo "do whatever you want to pre-configure your machine"
```

### cloud_config

If your VMs have `cloud-init` enabled you can use `cloud_config` to generate userdata for use by cloud-init in the [cloud-config format](https://cloudinit.readthedocs.io/en/latest/topics/format.html#cloud-config-data). This provides a convenient way to specify cloud-init config inline. As the cloud-config format uses YAML the resulting userdata is essentially a copy+paste of `cloud_config` with the header line '#cloud-config'

```yaml
    driver_config:
      cloud_config:
        hostname: my-hostname
```

This will pass the following user data to OpenStack:

```text
#cloud-config
hostname: my-hostname
```

The `cloud_config` and `user_data` options are mutually exclusive.

### config_drive

If your VMs require config drive.

```yaml
    config_drive: true
```

### network_ref

**Deprecated** A list of network names to create instances with.

```yaml
network_ref:
   - [OPENSTACK NETWORK NAMES]
   - [CREATE INSTANCE WITH]
```

### network_id

A list of network ids to create instances with.  Specifying the id instead of reference results in a faster create time.

**Note** If the network UUID changes this value will need to be updated.

```yaml
network_ref:
   - [OPENSTACK NETWORK UUIDs]
   - [TO CREATE INSTANCE WITH]
```

### no_ssh_tcp_check

**Deprecated** You should be using transport now. This will skip the ssh check to automatically connect.

The default is `false`.

### no_ssh_tcp_check_sleep

**Deprecated** You should be using transport now. This will sleep for so many seconds. `no_ssh_tcp_check` needs
to be set to `true`.

### private_key_path

**Deprecated** You should be using transport now. The guest image should use `cloud-init` or some other method to fetch key from meta-data service.

### public_key_path

**Deprecated** You should be using transport now. The guest image should use `cloud-init` or some other method to fetch key from meta-data service.

## Disk Configuration

### block_device_mapping

#### make_volume

Makes a new volume when set to `true`.

The default is `false`.

#### snapshot_id

When set, will make a volume from that snapshot id.

#### volume_id

When set, will attach the volume id.

#### device_name

Set this to `vda` unless you really know what you are doing.

#### availability_zone

The block storage availability zone.

The default is `nova`.

#### volume_type

The volume type, this is optional.

#### delete_on_termination

This will delete the volume on the instance when `destroy` happens, if set to true.
Otherwise set this to `false`.

#### creation_timeout

Timeout to wait for volume to become available.  If a large volume is provisioned, it might take time to provision it on the backend.  Maximum amount of time to wait for volume to be created and be available.

#### attach_timeout

If using a customized version of Openstack such a VMWare Integrated OPenstack (VIO), it may mark a volume active even though it is still performing some actions which may cause test kitchen to attach the volume to early which results in errors. Specify in seconds the amount of time to delay attaching the volume after its been marked active. Default timeout is 0.

#### Example

```yaml
block_device_mapping:
  make_volume: true
  snapshot_id: 00000-111111-0000222-000
  device_name: vda
  availability_zone: nova
  delete_on_termination: false
  creation_timeout: 120
  attach_timeout: 240
```

## Network and Communication Configuration

### floating_ip

A specific `floating_ip` can be provided to bind a floating IP to the node.
Any floating IP will be the IP used for Test Kitchen's Remote calls to the node.

### floating_ip_pool

A `floating_ip_pool` can be provided to allocate a floating IP from
the pool to the instance. If `allocate_floating_ip` is true, the IP will be allocated,
otherwise the first free floating IP will be used.  It will be the IP used for
Test Kitchen's Remote calls to the node. If allocated, the floating IP will be
released once the instance is destroyed.

### allocate_floating_ip

If true, allocate a new IP from the specified `floating_ip_pool` and release is afterwards.
Otherwise, if false (the default), an existing allocated IP.

### \[public\|private\]_ip_order

In some complex network scenarios you can have several IP addresses designated
as public or private. Use `public_ip_order` or `private_ip_order` to control
which one to use for further SSH connection. Default is 0 (first one)

For example if you have openstack istance that has network with several IPs assigned like

```text
+--------------------------------------+------------+--------+------------+-------------+----------------------------------+
| ID                                   | Name       | Status | Task State | Power State | Networks                         |
+--------------------------------------+------------+--------+------------+-------------+----------------------------------+
| 31c98de4-026f-4d12-b03f-a8a35c6e730b | kitchen    | ACTIVE | None       | Running     | test=<IP_ADDRESS>, <IP_ADDRESS>   |

```

to use second `<IP_ADDRESS>` IP address you need to specify

```yaml
  private_ip_order: 1
```

assuming that test network is configured as private.

### use_ipv6

If true use IPv6 addresses to for SSH connections. If false, the default, use
IPv4 addresses for SSH connections.

### network_ref

The `network_ref` option can be specified as an exact id, an exact name,
or as a regular expression matching the name of the network. You can pass one

```yaml
  network_ref: MYNET1
```

or many networks

```yaml
network_ref:
  - MYNET1
  - MYNET2
```

The `openstack_network_name` is used to select IP address for SSH connection.
It's recommended to specify this option in case of multiple networks used for
instance to provide more control over network connectivity.

Please note that `network_ref` relies on Network Services (`Fog::Network`) and
it can be unavailable in your OpenStack installation.

### disable_ssl_validation

```yaml
  disable_ssl_validation: true
```

Only disable SSL cert validation if you absolutely know what you are doing,
but are stuck with an OpenStack deployment without valid SSL certs.

## Example **kitchen.yml**

```yaml
---
driver:
  name: openstack
  openstack_username: [YOUR OPENSTACK USERNAME]
  openstack_api_key: [YOUR OPENSTACK API KEY] # AKA your OPENSTACK PASSWORD
  openstack_auth_url: [YOUR OPENSTACK AUTH URL]
  openstack_domain_id: [default is 'default'; otherwise YOUR OPENSTACK DOMAIN ID]
  require_chef_omnibus: [e.g. 'true' or a version number if you need Chef]
  image_ref: [SERVER IMAGE ID]
  flavor_ref: [SERVER FLAVOR ID]
  key_name: [KEY NAME]
  read_timeout: 180
  write_timeout: 180
  connect_timeout: 180

provisioner:
  name: chef_infra

verifier:
  name: inspec

transport:
  ssh_key: /path/to/id_rsa #Path to private key that matches the above openstack key_name
  connection_timeout: 10
  connection_retries: 5
  username: ubuntu
  password: mysecreatpassword

platforms:
  - name: ubuntu-18.04
  - name: ubuntu-20.04
  - name: centos-8
    transport:
      username: centos
  - name: windows-2022
    transport:
      password: myadministratorpassword

suites:
  - name: default
    run_list:
      - recipe[my_cookbook::default]
    attributes:
```

repository: mailchannels/test-kitchen

gha_language: Ruby

gha_license_id: NOASSERTION

repo_name: mailchannels/test-kitchen


text:
# galaxytopper
:tophat: Firmware and associated goodies for my space-tastic top hat!

* The firmware itself is galaxytopper.ino
* Python script that uses astropy to create plots of astronomical data is
  grb_plotter.py
* Astronomical data to plot is in grbs[_trunc].votable.xml
  * this is an export from http://www.asdc.asi.it/grbgbm/
  * plotted astronomy data are in plots/
* .gitignore includes "shiftbrite" and "ticker" because I have those two
  libraries symlinked in from elsewhere:
  * https://github.com/kylemarsh/shiftbrite
  * https://github.com/kylemarsh/rgb_ticker@fc4638a3bab55e2259d5e120f80a0b4b6e69e16d
    * (NB: I'm pretty sure rgb_ticker used this way leaks memory;
      the memory management in kylemarsh/rgb_ticker@c4c391f7c31f5d3c864bb9a9a88f033d1a1bc00b
      is bugged and I haven't gone back to figure out what's wrong yet. just
      roll back a commit from there and it'll work (albeit leakily))

Inspiration for the Galaxy Topper is Chris Knight's
[instructable](http://www.instructables.com/id/My-hat-its-full-of-stars/).

repository: kylemarsh/galaxytopper

repo_name: kylemarsh/galaxytopper


text:
# Curly

This package wraps [Perfect-CURL](https://github.com/PerfectlySoft/Perfect-CURL) into a Vapor 3 `Client`. If you are running into issues with URLSession on Linux, or you want cookies or proxy support, this might be the way out.

## Usage

### 1. Add this package as a dependency to your Vapor 3 project

```swift
// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "VaporApp",
    dependencies: [
        // 💧 A server-side Swift web framework.
        .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"),
        .package(url: "https://github.com/vzsg/Curly.git", from: "0.4.0"),
        // ... other dependencies ...
    ],
    targets: [
        .target(name: "App", dependencies: ["Vapor", "...", "CurlyClient"]),
        // ... other targets ...
    ]
)
```

### 2. Register the CurlyProvider

```swift
// Typically, this is part of configure.swift
import Vapor
import CurlyClient
// ... other imports ...

public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
    try services.register(CurlyProvider())
    config.prefer(CurlyClient.self, for: Client.self)

    // ... other configuration ...
}
```

### 3. Profit!

Your Vapor app now uses curl directly instead of URLSession.

### 4. Extra profit: CurlyOptions

From 0.3.0, Curly exposes a few useful options from cURL that are otherwise not available via the Client interface, or even URLSession. To use them, you _must_ register Curly via the `CurlyProvider` as seen in step 2.

With that in place, you can call `Request.addCurlyOption` in either the `beforeSend` closure when using the convenience functions of Client, or on the Request instance itself when using `Client.send()` and a self-built Request object.
See the tests for examples of both methods.

> **Warning**: Calling `Request.addCurlyOption` without the Provider will result in a fatal error in debug builds, and a warning print in release builds.

#### Available options

- **proxy(String)**

    Equivalent to the [`-x`/`--proxy`](https://curl.haxx.se/docs/manpage.html#-x) parameter of curl, which enables proxying via a HTTP, HTTPS or SOCKS proxy.

- **proxyAuth(user: String, password: String)**

    Equivalent to the [`-U`/`--proxy-user`](https://curl.haxx.se/docs/manpage.html#-U) parameter of curl, which allows specifying the username and password to use when authenticating to the proxy server.

- **timeout(seconds: Int)**

    Equivalent to the [`-m`/`--max-time`](https://curl.haxx.se/docs/manpage.html#-m) parameter of curl, which allows specifying the maximum time allowed to service the request.

- **connectTimeout(seconds: Int)**

    Equivalent to the [`--connect-timeout`](https://curl.haxx.se/docs/manpage.html#--connect-timeout) parameter of curl, which allows specifying the maximum time allowed for the connection to the server.

- **cookieJar(String)**

  Equivalent to the **both** the [`-b`/`--cookie`](ttps://curl.haxx.se/docs/manpage.html#-b) **and** [`-c`/`--cookie-jar`](ttps://curl.haxx.se/docs/manpage.html#-c) parameters of curl. The file name provided with the option will be used as a cookie storage – reading and writing – for this request. See the tests for an example.

- **followRedirects(Bool)**

    Equivalent to the [`-L`/`--location`](https://curl.haxx.se/docs/manpage.html#-L) parameter of curl, which enables following redirects automatically.

- **insecure(Bool)**

    Equivalent to the [`-k`/`--insecure`](https://curl.haxx.se/docs/manpage.html#-k) parameter of curl, which can disable verification of the certificates received from the remote server.

repository: tjshae/Curly

repo_name: tjshae/Curly


text:
---
layout: page
order: 2
title: "Stunting & USAID Programs"
---
1. Maps
2. Friction
  - cross-sectoral
3. So: what did you want to know?
  - Fertility rates are stagnating.  Why?
  - GDP is growing, but malnutrition is still high.  Why?
4. What did we learn?
  - Geography matters.
  * stunting has dramatically improved in the Eastern half of the country.
  * the northwestern section (especially in high altitude locations) lags behind the rest of the country.
- Everything is loopy.  These are all cross-disciplinary problems, interrelated.

* stunting is a cross-disciplinary problem. influenced by:
  * toilets / san
  * health/wealth
  * education
  * family planning
* CHAIN works in reasonable locations but is over-represented in Kigali/East (?)
* stunting changes in the NW
* changes in sanitation.

repository: flaneuse/Rwanda-results

repo_name: flaneuse/Rwanda-results


text:
python-gerrit
=============
[![Build Status](https://travis-ci.org/gillarkod/python-gerrit.svg?branch=master)](https://travis-ci.org/gillarkod/python-gerrit)
[![Coverage Status](https://coveralls.io/repos/github/gillarkod/python-gerrit/badge.svg?branch=master&bust=1)](https://coveralls.io/github/gillarkod/python-gerrit?branch=master)
[![python-gerrit on discord](https://img.shields.io/badge/discord-general@python--gerrit-738bd7.svg?style=flat)](https://discord.gg/012Ch20uOuaAtn5su)

Python module that uses the Gerrit REST API as an interface to manage changes, users, groups, and more.

# Scope
The scope of this library is to code stuff when people have a need for it.
PR's and issues are welcome if they come with unittests and 10/10 pylint.

# Usage

## Examples

# Structure
This lib will try to follow the structure the Gerrit API is structured.
For example:
```
/changes/
  change
  change edit
  reviewer
  revision
  ids
  json entities
/groups/
  group
  group member
  group include
  ids
  json entities
```

## API Reference

# Developing
Are you interested in helping out with the development of python-gerrit?

## Coding standards
We try to follow PEP8 standards to the best of our ability. All python files should pass pylint, check with

`pylint gerrit tests *.py`

## Testing
You should be standing in the root directory of the git repository.
You will need to install the required python modules for testing.

`pip install -r test-requirements.txt`

You will also need to install a web driver for the functional tests. Put either firefox or chrome webdrivers in your path and specify it in the test-config.yaml file.

Use nosetests to run all tests. This will run both unit and function tests. It is recommended to run tests-setup.sh before this to set up your gerrit environment, please note that this requires docker.
```
./tests-setup.sh && nosetests
```

### Coverage
We like tests, to check the coverage locally you can use nose.

`nosetests --with-coverage --cover-package=gerrit,tests --cover-tests`


text:
# Prisoner's Dilemma Simulation

## References

* [Prisoner's Dilemma](https://www.investopedia.com/terms/p/prisoners-dilemma.asp#:~:text=The%20prisoner's%20dilemma%20is%20a,expense%20of%20the%20other%20participant.)
> The prisoner's dilemma is a paradox in decision analysis in which two individuals
> acting in their own self-interests do not produce the optimal outcome. The typical
> prisoner's dilemma is set up in such a way that both parties choose to protect
> themselves at the expense of the other participant. As a result, both participants
> find themselves in a worse state than if they had cooperated with each other in the
> decision-making process. The prisoner's dilemma is one of the most well-known concepts in
> modern game theory.
* [Generous Tit For Tat: A Winning Strategy](https://www.forbes.com/sites/rogerkay/2011/12/19/generous-tit-for-tat-a-winning-strategy/#1eb99df466eb)

## Overview

This software simulates opponents (players) competing with each other for 100 days.
Each day each player must decide to either Attack or Defend. The players have
health points added or taken away depending on their decision and the decision
of the opposing player, as follows:
* If both Defend:  No Change in health points.
* If both Attack:  Both lose 5 health points.
* If one Attacks and Other Defends: Attacker gains 2, and Defender loses 10 health points.

To run the simulation:
* ./ctlr \<player\> \<player\> \<player\> ...
* Or, use the 'run_all' script to run ctlr for all of the players provided

The ctlr program selects 2 players (opponents) to compete over 100 days period.
Each day the 2 players are faced with prisoner's dilemma, to Attack or Defend. The player's
health scores are updated by the ctlr program at the end of each day.
When 100 days of competitions have been completed, the final health score for each
player is displayed.

The ctlr program repeats selecting 2 players to compete, for all player combinations.

The ctlr program is written in C. The player programs can be written in most any
language.  The ctlr program executes the player programs and communicates with
them using standard input and output

The player programs receive the following inputs from ctlr:
* "YESTERDAY_YOUR_OPPONENT ATTACK|DEFEND": This input to the player is provided
  to the player at the beginning of each day. Players will often base their
  decision of whether to Attack or Defend today on what happened yesterday.
* "WHAT_WILL_YOU_DO_TODAY?": This input to the player requires a response back
  to ctlr of either "ATTACK" or "DEFEND".
* "TERM": The player program must terminate.

## Players Provided

The player programs provided are described below. Most are written in python,
except for jesus which is written in bash, and lucifer which is written in C.
* jesus: always defends
* lucifer: always attacks
* tft (tit-for-tat): always responds to an attack with a counter-attack
* gtft (generous-tit-for-tat): almost always responds to an attack with a counter-attack
* mrs (massive retaliatory strike): defends until attacked, once attacked
  will always respond with attack
* mrs20 (massive retaliatory strike): defends until attacked, once attacked
  will respond with attack for 20 days
* tester: will occasionally attack, and continue attacking until other player attacks
* tft_tester: combined tft and tester
* gtft_tester: combined gtft and tester

## Some Other Uses

Other than simulating the prisoner's dilemma this software provides:
* A fun way to begin learning a new computer language.
* Code which creates a child process, and communicates to it using pipes for stdin and stdout.


text:
---
layout: "docs_api"
version: "1.3.3"
versionHref: "/docs/v1"
path: "api/directive/ionSpinner/"

title: "ion-spinner"
header_sub_title: "Directive in module ionic"
doc: "ionSpinner"
docType: "directive"
---

View Source

Improve this doc

ion-spinner

The `ionSpinner` directive provides a variety of animated spinners.
Spinners enables you to give your users feedback that the app is
processing/thinking/waiting/chillin' out, or whatever you'd like it to indicate.
By default, the ionRefresher feature uses this spinner, rather
than rotating font icons (previously included in [ionicons](https://ionicons.com/)).
While font icons are great for simple or stationary graphics, they're not suited to
provide great animations, which is why Ionic uses SVG instead.

Ionic offers ten spinners out of the box, and by default, it will use the appropriate spinner
for the platform on which it's running. Under the hood, the `ionSpinner` directive dynamically
builds the required SVG element, which allows Ionic to provide all ten of the animated SVGs
within 3KB.

     android

     <ion-spinner icon="android"></ion-spinner>

     ios

     <ion-spinner icon="ios"></ion-spinner>

     ios-small

     <ion-spinner icon="ios-small"></ion-spinner>

     bubbles

     <ion-spinner icon="bubbles"></ion-spinner>

     circles

     <ion-spinner icon="circles"></ion-spinner>

     crescent

     <ion-spinner icon="crescent"></ion-spinner>

     dots

     <ion-spinner icon="dots"></ion-spinner>

     lines

     <ion-spinner icon="lines"></ion-spinner>

     ripple

     <ion-spinner icon="ripple"></ion-spinner>

     spiral

     <ion-spinner icon="spiral"></ion-spinner>

Each spinner uses SVG with SMIL animations, however, the Android spinner also uses JavaScript
so it also works on Android 4.0-4.3. Additionally, each spinner can be styled with CSS,
and scaled to any size.

Usage

The following code would use the default spinner for the platform it's running from. If it's neither
iOS or Android, it'll default to use `ios`.

```html
<ion-spinner></ion-spinner>
```

By setting the `icon` attribute, you can specify which spinner to use, no matter what
the platform is.

```html
<ion-spinner icon="spiral"></ion-spinner>
```

## Spinner Colors
Like with most of Ionic's other components, spinners can also be styled using
Ionic's standard color naming convention. For example:

```html
<ion-spinner class="spinner-energized"></ion-spinner>
```

## Styling SVG with CSS
One cool thing about SVG is its ability to be styled with CSS! Some of the properties
have different names, for example, SVG uses the term `stroke` instead of `border`, and
`fill` instead of `background-color`.

```css
.spinner svg {
  width: 28px;
  height: 28px;
  stroke: #444;
  fill: #444;
}
```

repository: ionic-team/ionic-legacy-docs

gha_language: JavaScript

repo_name: ionic-team/ionic-legacy-docs


text:
wp-cli/extension-command
========================

Manage WordPress plugins and themes.

[![Build Status](https://travis-ci.org/wp-cli/extension-command.svg?branch=master)](https://travis-ci.org/wp-cli/extension-command)

Quick links: [Using](#using) | [Installing](#installing) | [Contributing](#contributing)

## Using

This package implements the following commands:

### wp plugin

Manage plugins.

~~~
wp plugin
~~~

**EXAMPLES**

    # Activate plugin
    $ wp plugin activate hello-dolly
    Plugin 'hello-dolly' activated.
    Success: Activated 1 of 1 plugins.

    # Deactivate plugin
    $ wp plugin deactivate hello-dolly
    Plugin 'hello-dolly' deactivated.
    Success: Deactivated 1 of 1 plugins.

    # Delete plugin
    $ wp plugin delete hello-dolly
    Deleted 'hello-dolly' plugin.
    Success: Deleted 1 of 1 plugins.

    # Install the latest version from wordpress.org and activate
    $ wp plugin install bbpress --activate
    Installing bbPress (2.5.9)
    Downloading install package from https://downloads.wordpress.org/plugin/bbpress.2.5.9.zip...
    Using cached file '/home/vagrant/.wp-cli/cache/plugin/bbpress-2.5.9.zip'...
    Unpacking the package...
    Installing the plugin...
    Plugin installed successfully.
    Activating 'bbpress'...
    Plugin 'bbpress' activated.
    Success: Installed 1 of 1 plugins.

### wp theme

Manage themes.

~~~
wp theme
~~~

**EXAMPLES**

    # Install the latest version of a theme from wordpress.org and activate
    $ wp theme install twentysixteen --activate
    Installing Twenty Sixteen (1.2)
    Downloading install package from http://downloads.wordpress.org/theme/twentysixteen.1.2.zip...
    Unpacking the package...
    Installing the theme...
    Theme installed successfully.
    Activating 'twentysixteen'...
    Success: Switched to 'Twenty Sixteen' theme.

    # Get details of an installed theme
    $ wp theme get twentysixteen --fields=name,title,version
    +---------+----------------+
    | Field   | Value          |
    +---------+----------------+
    | name    | Twenty Sixteen |
    | title   | Twenty Sixteen |
    | version | 1.2            |
    +---------+----------------+

    # Get status of theme
    $ wp theme status twentysixteen
    Theme twentysixteen details:
    		Name: Twenty Sixteen
    		Status: Active
    		Version: 1.2
    		Author: the WordPress team

### wp theme mod

Manage theme mods.

~~~
wp theme mod
~~~

**EXAMPLES**

    # Set the 'background_color' theme mod to '000000'.
    $ wp theme mod set background_color 000000
    Success: Theme mod background_color set to 000000

    # Get single theme mod in JSON format.
    $ wp theme mod get background_color --format=json
    [{"key":"background_color","value":"dd3333"}]

    # Remove all theme mods.
    $ wp theme mod remove --all
    Success: Theme mods removed.

## Installing

Installing this package requires WP-CLI v0.23.0 or greater. Update to the latest stable release with `wp cli update`.

Once you've done so, you can install this package with `wp package install wp-cli/extension-command`.

## Contributing

We appreciate you taking the initiative to contribute to this project.

Contributing isn’t limited to just code. We encourage you to contribute in the way that best fits your abilities, by writing tutorials, giving a demo at your local meetup, helping other users with their support questions, or revising our documentation.

### Reporting a bug

Think you’ve found a bug? We’d love for you to help us get it fixed.

Before you create a new issue, you should [search existing issues](https://github.com/wp-cli/extension-command/issues?q=label%3Abug%20) to see if there’s an existing resolution to it, or if it’s already been fixed in a newer version.

Once you’ve done a bit of searching and discovered there isn’t an open or fixed issue for your bug, please [create a new issue](https://github.com/wp-cli/extension-command/issues/new) with the following:

1. What you were doing (e.g. "When I run `wp post list`").
2. What you saw (e.g. "I see a fatal about a class being undefined.").
3. What you expected to see (e.g. "I expected to see the list of posts.")

Include as much detail as you can, and clear steps to reproduce if possible.

### Creating a pull request

Want to contribute a new feature? Please first [open a new issue](https://github.com/wp-cli/extension-command/issues/new) to discuss whether the feature is a good fit for the project.

Once you've decided to commit the time to seeing your pull request through, please follow our guidelines for creating a pull request to make sure it's a pleasant experience:

1. Create a feature branch for each contribution.
2. Submit your pull request early for feedback.
3. Include functional tests with your changes. [Read the WP-CLI documentation](https://wp-cli.org/docs/pull-requests/#functional-tests) for an introduction.
4. Follow the [WordPress Coding Standards](http://make.wordpress.org/core/handbook/coding-standards/).

*This README.md is generated dynamically from the project's codebase using `wp scaffold package-readme` ([doc](https://github.com/wp-cli/scaffold-package-command#wp-scaffold-package-readme)). To suggest changes, please submit a pull request against the corresponding part of the codebase.*

repository: dnmvisser/extension-command

repo_name: dnmvisser/extension-command


text:
## Playbook: Scheduled Task/Job

### MITRE

| Tactic | Technique ID | Technique Name | Sub-Technique Name | Platforms | Permissions Required |
| ------ | ------------ | -------------- | ------------------ |---------- |--------------------- |
| Execution, Persistence, Privilege Escalation | T1053 | Scheduled Task/Job |  | Containers, Linux, Windows, macOS | Administrator, SYSTEM, User  |

**Investigate, remediate (contain, eradicate), and communicate in parallel!**

Assign steps to individuals or teams to work concurrently, when possible; this playbook is not purely sequential. Use your best judgment.

--------------

### Investigate

1. **Scope of the attack**
    * gather IOCs on the task and see, if there are multiple assets affected.
    * analyze log files to get a better understanding, how the task was created and clarify attack vector.
    * analyze if the user, which created the task, did other actions on assets
2. **Analyze task creation**
    * creation timestamp of the task
    * user that created the task
    * rights of the user
3. **Analyze the task**
    * called binaries
    * provided parameters
    * frequency in which the task is called
    * more IOCs for analyzing the scope of the attack
4. **Determine Severity**
    * number of affected assets
    * indicators of users compromised
    * data at risk
    * clear path of attack

--------------

### Remediate

* **Plan remediation events** where these steps are launched together (or in coordinated fashion), with appropriate teams ready to respond to any disruption.
* **Consider the timing and trade-offs** of remediation actions: your response has consequences.

#### Contain

1. **Originating account**
    * lock the account which created the task
    * change the password of the account and in all locations, where the same password was used
2. **Disable the task and prevent re-creation**
    * disable the task
    * block other ways of task creation identified by the investigation
3. **Automated blocking**
    * if in an highly controlled environment with good baseline-images, consider blocking unknown services on creation

#### Eradicate

1. **Remove task**
    * if it is clear how the task was created and what it did, you can remove it
2. **Reset asset to an clean state**
    * as an alternative, consider restoring an old image or re-imaging the asset

#### Reference: Remediation Resources

1. Resources need strongly depend on the complexity of the task and the overall attack.

--------------

### Communicate

In addition to the general steps and guidance in the incident response plan:
1. **Should be covered in default response plan**

--------------

### Recover

In addition to the general steps and guidance in the incident response plan:
1. **Monitoring**
    * monitor the environment more closely for the creation of tasks over the upcoming weeks.

--------------

### Lessons Learned

1. Follow default lessons learned procedures

--------------

### Resources

#### Additional Information

1. [MITRE T1053]("https://attack.mitre.org/techniques/T1053/")

branch_name: refs/heads/main

gha_license_id: MIT


text:
# Aesthetic

[![Build Status](https://travis-ci.org/benpickles/aesthetic.svg?branch=master)](https://travis-ci.org/benpickles/aesthetic)

Aesthetic is a tool to help you regression-test your site's aesthetic and ensure that tiny CSS changes don't have unintentional side effects in other areas of your site. Aesthetic helps you identify visual changes throughout your site to give you the confidence to freely refactor your CSS from the ground up instead of building up layers of hacks that you'll find time to fix one day.

## Usage

```ruby
aesthetic do
  # A screenshot is taken for each breakpoint.
  breakpoint :tablet, 768
  breakpoint :desktop, 1024

  # The `screenshot` method visits a URL and saves a screenshot.
  screenshot :homepage, 'http://example.com'

  # You can utilise the full Capybara DSL in example blocks.
  example 'My Account' do
    visit 'http://example.com'
    click_link 'My Account'

    # Use the `screenshot` method to save a screenshot.
    screenshot :my_account
  end
end
```

repository: sergii/aesthetic

repo_name: sergii/aesthetic


text:
# Usage with an existing Route53 hosted zone

If you already have a Route53 hosted zone for the domain, the `aws_route53_zone` data source should be used to find the zone ID.

```hcl
data "aws_route53_zone" "zone" {
    name = "example.com."
}

module "route53_o365" {
    source = "mccanney/route53-o365/aws"

    domain     = "example.com"
    zone_id    = "${data.aws_route53_zone.zone.zone_id}"
    ms_txt     = "ms12345678"
    enable_sfb = false
    enable_mdm = false
}
```

This example also disables creating the DNS records for Skype for Business and Mobile Device Management.


text:
# Nodejs + Babel + Webpack app starter
## Quick Overview

This is a minimalistic starter app to benefit of the flexibility of Babel and of ES6, ES7+, if you you want to use the latest ECMAscript features (e.g. ES6 modules) without waiting for nodejs to support them natively, already configured with a custom .vscode to allow debugging inside Visual studio code IDE
see also [node typescript webpack starter](https://github.com/madChill/nodejs-started-typescript.git)

## Usage

clone the repository then:

`npm install` or `yarn install`

`npm run dev` (to start the server development mode)

`npm run build` (to build the code)

`npm runstart` (to run the code production after build)

## Features

- **babel**: transpiling from ES6, ES7+ to ES5
- **webpack**: compile typescript with ts-loader and bundling the source to a bundle.js
- **live compiling**: as well as live reload

repository: madChill/nodejs-started-typescript

repo_name: madChill/nodejs-started-typescript


text:
# DaggerApp
Application demonstrating how to leverage Dagger and MVP to build and test an android app.

#Preface
 - To run the app in live mode, run the devDebug flavor
 - To run the app using 100% mocked data (never makes a network call thanks to dependency dnjection tricks),
 run the tddDebug flavor. Following TDD, we can write our tests, and modules which provide mocks, and run the app
 without ever needing to make a network call, or talk to a local database. This enable for not only fast manual testing,
 but the ability to have regression tests in place, IE: when you make changes, you can run your tests and know if something broke :)

##TODO Complete a matching blog post about TDD, Dagger, and clean architecure

- create another screen, maybe with different data
- create POJO test module to provide dummy data inside of tests
- write android tests and implement jacoco test coverage
- write junit/roboelctric tests
- process requires some boiler blate code in android tests. Describe how to create live templates to create boiler plate code
- make sure to note that if you are writing a test and extending your component, when you annotate that interface with @Component, make sure its importing dagger.component and not the one from espresso!!!


text:
---
title: The Prologue to Prolog
layout: post
summary: How I used Python to automate another project during my junior year at Clemson University.
---

The third and final project that I was assigned during my Spring 2015 Programming Languages class at Clemson University was not quite as exciting as its predecessors: my class was told to re-create a [certain previous project][ocaml] in Prolog. Prolog is a declarative, faintly magical language; nothing to be afraid of until you ask anyone what a cut is[^2].

[ocaml]:{% post_url 2015-06-19-ocaml-and-python %}
[^2]: [Something like advanced horticulture.](https://en.wikibooks.org/wiki/Prolog/Cuts_and_Negation)

Essentially, my assignment was to design a collection of Prolog rules that dealt with lists of lists of numbers. Along with some example data, the assignment contained a specification-complete log of resolution results[^1] involving those examples. As with all previous class projects, I had to turn in a log file, much like the one provided, proving that either my program worked or I was bored enough to fake it.

[^1]: That was *horrendously obnoxious* to extract from the project PDF.

Here's a snippet of the log file from the project specification. Queries to the SWI-Prolog interpreter start with `?- `, and Prolog's answers are suffixed by a period.

```
?- ['sde3_example_data.pro'].
true.

?- startup.
true.

?- image_tgr11(A),printImage(A).
0 0 0 20 0
0 10 10 0 0
0 10 10 0 0
0 0 0 0 0
0 0 0 0 0
A = [[0, 0, 0, 20, 0], [0, 10, 10, 0, 0], [0, 10, 10, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0|...]].

?- image_tgr11(A),image_tgr12(B),diffIm(A,B,C).
A = [[0, 0, 0, 20, 0], [0, 10, 10, 0, 0], [0, 10, 10, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0|...]],
B = [[0, 0, 0, 0, 0], [0, 10, 10, 0, 0], [0, 10, 10, 0, 0], [0, 20, 0, 0, 0], [0, 0, 0, 0|...]],
C = [[0, 0, 0, -20, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 20, 0, 0, 0], [0, 0, 0, 0|...]].
```

Thanks to my previous work on the class's OCaml project, I already had a solution to the logging problem close at hand -- that is, I already knew how to use Python to feed queries one-at-a-time into an interpreter and combine the results into my own log. Thanks to my instructor, I also had a near-complete test suite in the "correct" log, so I figured that if I could extract the queries from his sample log, then I could use them to build my own log. Then I could diff the two logs to check my program for correctness.

Why not take the time [like before][ocaml] to unit test my rules? Easy answer: writing unit tests took *forever*[^3] when I did them last, and I really only wanted the tests to help me understand the assignment. They'd do me little good here, if I could figure out another way to test overall correctness.

[^3]: A couple hours, but hey.

Let's jump right in and take a look at the Python script that I wrote. I haven't cleaned up my code at all since I wrote it, but I added some comments for clarity.

```python
#!/usr/bin/env python

import subprocess
import sys

# Extract the queries from the correct log, cutting off
# the prompt's query indicator ( ?- )
qs = sys.stdin.readlines()
in_lines = [ x[3:] for x in filter(lambda l: '?-' in l, qs) ]

# Dump the queries into a quiet version of the prolog interpreter.
pipe = subprocess.Popen(["swipl", "-q"],
        universal_newlines=True,
        stderr=subprocess.STDOUT,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE)
(o, _) = pipe.communicate("".join(in_lines))

# Save all the output lines into a list, without removing newline
# characters from each line. An isolated newline character ends
# up as a delimiter between the output for a query and the next
# query; we'll be using that later to insert the missing queries
# into our log, so we'll prepend our list of output lines with
# another newline.
real_lines = o.splitlines(keepends=True)
real_lines.insert(0, '\n')

# Replace each isolated newline with one of the input queries.
for i, l in enumerate(real_lines):
    if l == "\n" and len(in_lines) > 0:
        real_lines[i] = '\n?- ' + in_lines.pop(0)

# Print the now-complete log!
print("".join(real_lines).strip())
```

Running something like `logger.py < sample.log | tee real.log` effectively duplicated the sample log (as long as I did a decent job coding up the Prolog rules) while I would skim for immediately obvious errors. Then, `colordiff -ZbwBbd sample.log real.log` [checked for whitespace-independent differences](http://linux.die.net/man/1/diff) (I ended up trimming empty the lines out from `sample.log` for some reason, so the real log had empty lines and the sample one didn't).

I slammed all that into a Makefile that handled everything short of project submission[^4]. All I had to do to check to see if I was done coding was type `make`, and that'd fail if the log it generated was incorrect.  Automating this project was a lot easier than previous ones!

I earned full marks on this assignment, rounding out my semester at three perfect project scores. Great!

[^4]: Our course projects were submitted through BlackBoard, an automation-unfriendly web-based class management system. I *bet* I could submit automatically with Selenium and PhantomJS, but I haven't tried that yet. I may run into trouble with those projects that don't allow multiple submissions...

repository: ProtractorNinja/protractor-blog

repo_name: ProtractorNinja/protractor-blog


text:
node-red-node-pusher
====================

A Node-RED node to send and receive messages using Pusher.com.

Pre-requisites
--------------

You need a valid Pusher App key, secret and id from [http://pusher.com](http://pusher.com)

Install
-------

Run the following command in your Node-RED user directory - typically `~/.node-red`

        npm install node-red-node-pusher

Usage
-----

### Input

Pusher input mode. Use this node to subscribe to a Pusher channel/event.
You need a valid Pusher App key.

The node will set `msg.payload` to the message that arrives, and `msg.topic` to the eventname.

### Output

Pusher output node for sending messages to a specific channel/event.
You need an App key, secret and ID of a Pusher app.

The node will send the `msg.payload` of the incoming message.

repository: hixio-mh/node-red-nodes

repo_name: hixio-mh/node-red-nodes


text:
---
title: Securing PostHog
sidebar: Docs
showTitle: true
---

## Restrict access by IP

You can restrict access to PostHog by IP by passing `ALLOWED_IP_BLOCKS`. This is a comma separated list, and can either be individual IP addresses or subnets. For example:

```bash
ALLOWED_IP_BLOCKS=<IP_ADDRESS>/31,<IP_ADDRESS>/25,<IP_ADDRESS>
```

If you try to access your PostHog instance with a different IP, you will get an error message.

This restriction does not apply to the endpoints used to send events, like `batch`, `capture` etc.

If you're behind a proxy, you need to either set trusted proxies
```bash
TRUSTED_PROXIES=ip1,ip2
```

Or you can implicitely trust all proxies.

```bash
TRUST_ALL_PROXIES=True
```

!> When using `TRUST_ALL_PROXIES`, make sure your proxy (like nginx) is setting X-Forwarded-For, like in the example above. If not, it would still be possible to spoof your IP address

> If you're on Heroku, you are behind a proxy so you'll need to add `IS_BEHIND_PROXY=True`. Heroku automatically overrides X-Forwarded-For, so you can use `TRUST_ALL_PROXIES=True`.

## Secret key

Secret keys are used to encrypt cookies, password reset emails [and other things](https://docs.djangoproject.com/en/3.0/ref/settings/#secret-key). To generate a secret key, run:

```bash
openssl rand -hex 32
```


text:
---
layout: post
title: Sharypic benefits from Algolia Search!
author:
  login: nicolas
  email<EMAIL_ADDRESS>  display_name: nicolas
  first_name: Nicolas
  last_name: Dessaigne
---

Demonstrating how Algolia Search functions in the wild, in this post we will
discuss a recent integration with [sharypic][1], another
Paris-based startup focussed on photo sharing at events.

Sharypic is a [web][2] and [mobile
app][3] dedicated to collaborative photo sharing, focused on
enabling users to easily gather photos from attendees during and after an
event. The platform allows users to collect and share photos from all devices,
including mobiles (via Twitter and Instagram), cameras, and computers, and
from already existing albums on Facebook, Picassa, and Flickr. One of their
killer features is the ability to stream photos to a live PhotoWall at the
venue and to an embeddable slideshow widget. This increases engagement both
with event attendees and with an online audience. On sharypic one of the
primary ways that users discover events is via a search bar, in addition to
pages highlighting recent and popular events.

[![Sharypic][4]](http://blog.algolia.com/sharypic-benefits-
from-algolia-search/sharypic/)The existing mobile search function relied on
users accurately typing an event's name into the search field, which limited
the results (especially on smartphones where typos are common). By integrating
Algolia Search into the mobile app, sharypic users can now type just a few
letters of a search term, or enter it incorrectly ('pqris' instead of
'Paris'), and the results will display the corrected term within event names,
locations, descriptions, or hashtags.

Martin Fourcade, one of sharypic's co-founders, said "For our users, it's
exactly what we needed. They can show the best photos of their events to
friends without bugging their smartphone and whining about the internet
connection. I'm lazy when it comes to typing on my smartphone, impatient when
it comes to waiting for server responses... now everything is done with a few
keystrokes!"

Sharypic's other co-founder François-Joseph Grimault hopes that this new
intelligent search will enable users to find specific content more easily,
possibly leading to increased exploration on the platform. Time will tell how
the new search feature affects user behaviour, but reducing user frustration
through quick and efficient search is a step in the right direction.

_[Download][5] the latest version of the sharypic app, including
integrated Algolia Search, and have fun with photo sharing at your next
event!_

[1]: http://sharypic.com
[2]: http://www.sharypic.com/
[3]: https://itunes.apple.com/us/app/sharypic-event-photo-sharing/id490922939?mt=8
[4]: /algoliasearch-jekyll-hyde/assets/Sharypic.png
[5]: https://itunes.apple.com/us/app/sharypic-event-photo-sharing/id490922939?mt=8

repository: jorgeponto/hyde

repo_name: jorgeponto/hyde


text:
[![alt tag](https://raw.githubusercontent.com/fabian7593/MagicalCamera/master/Images/cameraHighQ.png)](https://github.com/fabian7593/MagicalCamera)

A Magic library to take photos and select pictures in Android. In a simple way and if you need it also save the pictures in device, and facial recognition, get the real uri path or the photo or obtain the private information of the picture.

[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-MagicalCamera-green.svg?style=true)](https://android-arsenal.com/details/1/3623)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/a64cbf5369e14c3d98f8722c4ad3fad7)](https://www.codacy.com/app/fabian7593/MagicalCamera?utm_source=github.com&utm_medium=referral&utm_content=fabian7593/MagicalCamera&utm_campaign=Badge_Grade)
[![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html)

# Contents

### Features
- - -
- [Features MagicalCamera](#features-magicalcamera)
- [Other Features](#other-features)

### Buy me a Coffee (Donate)
- [Donate](#donate)

### How to Start
- - -
- [Getting Started](#getting-started)
  - [Download Sources](#download-sources)
- [Setup](#setup)
  - [Add dependecies](#add-dependecies)
- [How To use](#how-to-use)
  - [Import library](#import-library)
  - [Extends Application Class](#extends-application-class)

### Photo Features and permissions
- - -
- [Permissions on real time](#permissions-on-real-time)
- [Photo](#photo)
  - [Declare variable to resize photo](#declare-variable-to-resize-photo)
  - [Instance Class MagicalCamera](#instance-class-magicalcamera)
  - [Activities Methods](#activities-methods)
  - [Fragments Methods](#fragments-methods)
  - [Override the event onActivityResult](#override-the-event-onactivityresult)
  - [Save Photo in Memory Devices](#save-photo-in-memory-devices)
  - [Get Uri path](#get-uri-path)
  - [Types of Formats for save photos](#types-of-formats-for-save-photos)

  - [Resize photo in real time](#resize-photo-in-real-time)
  - [Conversion Methods](#conversion-methods)
  - [Rotate picture](#rotate-picture)
  - [Facial Recognition](#facial-recognition)
  - [Private information Photo](#private-information-photo)

### Footer Docs
- - -
- [Footer Document](#footer-document)
  - [Internal documentation](#internal-documentation)
  - [Preview of Example](#preview-of-example)
  - [Application that use MagicalCamera](#application-that-use-magicalcamera)
  - [Suggestions](#suggestions)
- [Credits and contributors](#credits-and-contributors)
  - [Contributors are welcome](#contributors-are-welcome)
- [Video Explanation](#video)
- [Apache License](#license)

## Features MagicalCamera.
* **Take picture** with camera device.
* **Select pictures in gallery** device (read in devices).
* **Write the pictures** that you taken in device, in your own directory.
* Return the **path of your photo** in device. (This issue is solved for [@arthursz](https://github.com/arthursz))
* **RealTime Permissions** Magical camera offers a simple integration of realtime permissions. (This functionallity is created by [@cutiko](https://github.com/cutiko))

* Working in **android 6.0** (We have a class to request the user permission).
* Create yours **standards of name of pictures**, or use our standard, like "photoname_YYYYmmddHHmmss"
* Posibility of shown the **private info photography**, like latitude, longitude, ISO or others with Exif Class.
* Posibility of **rotate picture** when it's required.
* Select the **quality of the photo** with a percentage, when 1 is the worst and 100 is the better.
* Obtain the LandMark and return a bitmap with a **facial recognition** that you need.
* **Return the Bitmap**Photo if you need to save this in internal DB of your application.
* **Convert your bitmap** in array bytes or string64, if you need to send by Json or XML.
* **Type of photo formats:** PNG, JPEG and WEBP.

#### Other Features
* A library completely OpenSource.
* Use best practice in POO
* Minimun SDK 14+ API.
* Support library
* Compile with Gradle
* License Under Apache 2.0
* The easiest possible integration
* Integrate in less than 5 minutes
* Quick and simple API
* A good Internal Documentation

### Donate

[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=L25MKCRPR7TWY)

## Getting Started

### Download Sources
use git (sourcetree or others)
Remember Download the example for understand better the process

```bash
git clone https://github.com/TalebRafiepour/MagicalCamera.git
```

Download from [Here](https://github.com/fabian7593/MagicalCamera/zipball/master)

Another type download by Bintray from    [ ![Download](https://api.bintray.com/packages/fabian7593/maven/MagicalCamera/images/download.svg) ](https://bintray.com/fabian7593/maven/MagicalCamera/_latestVersion)

## Setup
#### Add dependecies
If you need to take photo or select picture, this is your solution.
This library give a magical solution for take a picture,write and red in device, return your uri real path and obtain yhe private info of the photo and facial recognition, you only need to download this and integrate this in your project, maybe downloading it or import in your gradle, like this.

```gradle
allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

dependencies {
    implementation 'com.github.TalebRafiepour:MagicalCamera:6.0.1'
}
```

If you have any problem with this dependence, because the library override any styles, colors or others, please change the last line for this code:

```bash
 implementation ('com.github.TalebRafiepour:MagicalCamera:6.0.1@aar') {
        transitive = false;
    }
```

## How To use

### Import library
You need to import the library
```bash
import com.frosquivel.magicalcamera.MagicalCamera;
import com.frosquivel.magicalcamera.Functionallities.PermissionGranted;

//and maybe you need in some ocations
import com.frosquivel.magicalcamera.Objects.MagicalCameraObject;
```

### Extends Application Class
You need to extends MagicalCamera application

```bash
public class MyApplicationClass extends MagicalCameraApplication {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    //IF YOU NEED MULTIDEX, SET HERE, NOT ON APPLICATION TAG ON MANIFEAST, LIKE THIS
    @Override
    protected void attachBaseContext(Context base) {
      super.attachBaseContext(base);
      MultiDex.install(this);
    }
}

```

On manifest, change the name, for the name of your Application class, like this:

```bash
  <application
        android:name=".MyApplicationClass">
```

### Permissions on real time
With the MagicalPermissions class you can ask for permissions in a Activity or in an Fragment. This class will take care of validating the device API level, what permissions the user haven't granted yet, ask for thoose permissions, deliver the result and together with MagicalCamera will take the photo or select it from the gallery.

Requesting permissions on real time to the user is a 2 part process. First permissions most be requested, then the result is delivered. So you need a field variable to later call it again on the permissions result:

```
private MagicalPermissions magicalPermissions;
```

MagicalPermissions constructor accept two params, the first is the Activity or Fragment and the second is a String array of the permissions you **need** `String[]`. MagicalPermissions use the Activity or Fragment to later deliver the result of the permission, and the array to ask for thoose permissions.

```
magicalPermissions = new MagicalPermissions(this, permissions);
```

Inside MagicalPermissions it will be solved if the API level of the device requiere to ask permissions or not. If permissions must be asked to the user then MagicalPermissions will validate which permissions are already granted and only asked for the needed. **This is why is very important you only ask for the permissions you need, taking the photo or selecting it will only happen if every permission you have asked is granted**.

 - By example, if you only need to take the photo then:

```
String[] permissions = new String[] {
                Manifest.permission.CAMERA
        };
magicalPermissions = new MagicalPermissions(this, permissions);
```

- MagicalCamera take care of saving the photo commonly you will need:

```
String[] permissions = new String[] {
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
magicalPermissions = new MagicalPermissions(this, permissions);
```

 - Or maybe you want to use more potential of MagicalCamera and also ask for location related info, then you need:

```
String[] permissions = new String[] {
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
magicalPermissions = new MagicalPermissions(this, permissions);
```

You can also ask for other permissions in other places of your app, even unrelated to MagicalCamera using MagicalPermissions separatedly. So if getting location information is not requiered for the photo, but is a plus, you should consider separating thoose permissions from the absolutely needed to your feature. MagicalPermissions use a `Runnable` to do whatever you want after checking the permissions. When is used along with MagicalCamera you don't have to be aware of that, is automatic, but in this case we are considering asking for other permissions:

```
String[] location = new String[] {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
locationPermissions = new MagicalPermissions(this, location);

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //TODO location permissions are granted code here your feature
        Toast.makeText(context, "Thanks for granting location permissions", Toast.LENGTH_LONG).show();
    }
};
locationPermissions.askPermissions(runnable);
```

Then the second part of the process come into play: receiving the permissions result. You have to **always override** the `onRequestPermissionsResult` method in the Activity or Fragment. Inside of it, call your instance of MagicalPermissions and give it the result to the `permissionResult()` method (this is why must be a field). The `permissionResult()` method is a `Map<String, Boolean>` in case you need to know what happened and do something about it:

```
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    Map<String, Boolean> map = magicalPermissions.permissionResult(requestCode, permissions, grantResults);
    for (String permission : map.keySet()) {
        Log.d("PERMISSIONS", permission + " was: " + map.get(permission));
    }
    //Following the example you could also
    //locationPermissions(requestCode, permissions, grantResults);
}
```

# Photo

### Declare variable to resize photo
**( with pixels percentage )**
You need to declare and constant or a simple int variable for the quality of the photo, while greater be, greater be the quality, and otherwise, worst be the quality, like this
```bash
//The pixel percentage is declare like an percentage of 100, if your value is 50, the photo will have the middle quality of your camera.
// this value could be only 1 to 100.
private int RESIZE_PHOTO_PIXELS_PERCENTAGE = 80;
```

### Instance Class MagicalCamera
###### *YOU NEED TO INSTANCE THIS, AFTER THAT PERMISSION GRANTED INSTANCE.*
You need to instance the MagicalCamera Class, like this:
The fisrt param is the current Activity, and the second the resize percentage photo, and the third param is the Permission Granted
```bash
 MagicalCamera magicalCamera = new MagicalCamera(this,RESIZE_PHOTO_PIXELS_PERCENTAGE, magicalPermissions);

```

### Activities Methods
You need to call the methods for take or select pictures in activities that this form:

```bash
//take photo
magicalCamera.takePhoto();

//select picture
magicalCamera.selectedPicture("my_header_name");
```

### Fragments Methods
You need to call these methods for take or select pictures in fragments:

```bash
//take photo
magicalCamera.takeFragmentPhoto(FragmentSample.this);

 //select picture
magicalCamera.selectedFragmentPicture(FragmentSample.this, "My Header Example");
```

As you can see MagicalCamera is working together MagicalPermissions so you don't need to pass a `Runnable` the camera or photo selection will be triggered once permissions are solved.

### Override the event onActivityResult
**Remember**, you **need to override** the method onActivityResult in your activity or fragment like this
```bash
 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //CALL THIS METHOD EVER
        magicalCamera.resultPhoto(requestCode, resultCode, data);

        //this is for rotate picture in this method
        //magicalCamera.resultPhoto(requestCode, resultCode, data, MagicalCamera.ORIENTATION_ROTATE_180);

        //with this form you obtain the bitmap (in this example set this bitmap in image view)
        imageView.setImageBitmap(magicalCamera.getPhoto());

        //if you need save your bitmap in device use this method and return the path if you need this
        //You need to send, the bitmap picture, the photo name, the directory name, the picture type, and autoincrement photo name if           //you need this send true, else you have the posibility or realize your standard name for your pictures.
        String path = magicalCamera.savePhotoInMemoryDevice(magicalCamera.getPhoto(),"myPhotoName","myDirectoryName", MagicalCamera.JPEG, true);

       if(path != null){
           Toast.makeText(MainActivity.this, "The photo is save in device, please check this path: " + path, Toast.LENGTH_SHORT).show();
       }else{
           Toast.makeText(MainActivity.this, "Sorry your photo dont write in devide, please contact with fabian7593@gmail and say this error", Toast.LENGTH_SHORT).show();
       }
    }
```

### Get Uri path
You only could use
```bash
magicalCamera.getRealPath()
```

### Save Photo in Memory Devices
This method save your bitmap in internal memory device or if the internal memory is full this library save in sdcard (if you have anything)
This method have a lot of params that you can need to use the library:
* **Bitmap:** This is the bitmap that you need to save in memory device.
* **PhotoName:** The name of the photo
* **DirectoryName:** The name of directory that you need to save the image
* **Format:** the format of the photo, maybe png, jpeg or webp. Depends of that you need.
* **AutoIncrementNameByDate:** This variable save the photo with the photo name and the current date and hour. (Only if is true).

For example: myTestMagicalCameraPhoto_20160520131344 -> This is the year 2016, month 5, day 20, hour 13, minute 13 and second 44.

The method:
```bash
 public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, String directoryName,
 Bitmap.CompressFormat format, boolean autoIncrementNameByDate)
```

Example:
```bash
 String path = magicalCamera.savePhotoInMemoryDevice(magicalCamera.getPhoto(), "myTestPhotoName", MagicalCamera.JPEG, true);
```

### Types of Formats for save photos
You have any type of formats for save the pictures and the bitmaps.
You can use, the static variables of the library MagicalCamera.
```bash
 Bitmap.CompressFormat jpeg = MagicalCamera.JPEG;
 Bitmap.CompressFormat png = MagicalCamera.PNG;
 Bitmap.CompressFormat webp = MagicalCamera.WEBP;
```

### Resize photo in real time
You can resize the photo in any moment with this:
```bash
   magicalCamera.setResizePhoto(newResizeInteger);
```

### Conversion Methods
The library have any methods to convert the bitmap in other formats that you need.
All of this methods are public statics, I mean that you dont have to instance the library for usage this.
You need to call the class * ConvertSimpleImage * And the respective params.
* **bitmapToBytes:** Convert the bitmap to array bytes, only need the bitmap param and the compress format, return array bytes.
* **bytesToBitmap:** Convert the array bytes to bitmap, only need the array bytes in param, return bitmap.
* **bytesToStringBase64:** Convert the array bytes to String base 64, only need the array bytes format in param, return String.
* **stringBase64ToBytes:** Convert string to array bytes, only need the String in param, return array bytes.

Example:
```bash
  //convert the bitmap to bytes
  byte[] bytesArray =  ConvertSimpleImage.bitmapToBytes(magicalCamera.getPhoto(), MagicalCamera.PNG);

   //convert the bytes to string 64, with this form is easly to send by web service or store data in DB
   String imageBase64 = ConvertSimpleImage.bytesToStringBase64(bytesArray);

   //if you need to revert the process
   byte[] anotherArrayBytes = ConvertSimpleImage.stringBase64ToBytes(imageBase64);

  //again deserialize the image
  Bitmap myImageAgain = ConvertSimpleImage.bytesToBitmap(anotherArrayBytes);
```

### Rotate picture
You have the posibility of rotate picture because some devices have the camera in landscape, and the picture is shown upside down.
If you need to rotate image use in event onActivityResult the method with the last param:
```bash
  magicalCamera.resultPhoto(requestCode, resultCode, data, MagicalCamera.ORIENTATION_ROTATE_180);
```
or if you rotate manually in another part of code use method:
```bash
//rotate any image
Bitmap myImage = magicalCamera.rotatePicture(magicalCamera.getPhoto(),  MagicalCamera.ORIENTATION_ROTATE_90);

//rotate the getPhoto in magicalCamera Object
Bitmap myImage = magicalCamera.rotatePicture(MagicalCamera.ORIENTATION_ROTATE_NORMAL);
```

You have this posibillities of rotate image:
```bash
MagicalCamera.ORIENTATION_ROTATE_NORMAL
MagicalCamera.ORIENTATION_ROTATE_90
MagicalCamera.ORIENTATION_ROTATE_180
MagicalCamera.ORIENTATION_ROTATE_270
```

### Facial Recognition:

This is a method to return your bitmap (magicalCamera.getPhoto()) like another bitmap with a square draws arround the face of the photo, with the posibillity of modify the color and the stroke of the square. And this is not all, you have the posibility of call the List<Landmark> of the photo with facial recognitions, for save data of all faces, for example the distance between eyes, the nose position and mounth position, all of this is important information for facials recognitions.

You need to write for example:
```bash
if(magicalCamera != null){
    if(magicalCamera.getPhoto() != null){
         //this comment line is the strok 5 and color red for default
         //imageView.setImageBitmap(magicalCamera.faceDetector());
         //you can the posibility of send the square color and the respective stroke
         imageView.setImageBitmap(magicalCamera.faceDetector(50, Color.GREEN));

         List<Landmark> listMark = magicalCamera.getListLandMarkPhoto();
     }else{
         Toast.makeText(MainActivity.this,
                 "Your image is null, please select or take one",
                 Toast.LENGTH_SHORT).show();
     }
 }else{
     Toast.makeText(MainActivity.this,
             "Please initialized magical camera, maybe in static context for use in all activity",
             Toast.LENGTH_SHORT).show();
 }
```

The photo and bitmap converted is like to:

![alt tag](https://raw.githubusercontent.com/fabian7593/MagicalCamera/master/Images/faceDetection2.png)

### Private information Photo:
This method show you the private information photo if the photo is saved in device or not...
For view all information the device need to activate GPS locations (and maybe internet), else not show all information :(.

You need to write this code for example:
```bash
 //verify if the bitmap of image have data
 if(magicalCamera.getPhoto()!=null) {
   //verify if this photo is save in device, and if has private information to show and return true if have information, or false is not
   if(magicalCamera.initImageInformation()) {

         StringBuilder builderInformation = new StringBuilder();

         if (notNullNotFill(magicalCamera.getPrivateInformation().getLatitude() + ""))
             builderInformation.append("Latitude: " + magicalCamera.getPrivateInformation().getLatitude() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getLatitudeReference()))
             builderInformation.append("Latitude Reference: " + magicalCamera.getPrivateInformation().getLatitudeReference() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getLongitude() + ""))
             builderInformation.append("Longitude: " + magicalCamera.getPrivateInformation().getLongitude() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getLongitudeReference()))
             builderInformation.append("Longitude Reference: " + magicalCamera.getPrivateInformation().getLongitudeReference() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getDateTimeTakePhoto()))
             builderInformation.append("Date time to photo: " + magicalCamera.getPrivateInformation().getDateTimeTakePhoto() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getDateStamp()))
             builderInformation.append("Date stamp to photo: " + magicalCamera.getPrivateInformation().getDateStamp() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getIso()))
             builderInformation.append("ISO: " + magicalCamera.getPrivateInformation().getIso() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getOrientation()))
             builderInformation.append("Orientation photo: " + magicalCamera.getPrivateInformation().getOrientation() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getImageLength()))
             builderInformation.append("Image lenght: " + magicalCamera.getPrivateInformation().getImageLength() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getImageWidth()))
             builderInformation.append("Image Width: " + magicalCamera.getPrivateInformation().getImageWidth() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getModelDevice()))
             builderInformation.append("Model Device: " + magicalCamera.getPrivateInformation().getModelDevice() + "\n");

         if (notNullNotFill(magicalCamera.getPrivateInformation().getMakeCompany()))
             builderInformation.append("Make company: " + magicalCamera.getPrivateInformation().getMakeCompany() + "\n");

         new MaterialDialog.Builder(MainActivity.this)
                 .title("See photo information")
                 .content(builderInformation.toString())
                 .positiveText("ok")
                 .show();
   }else{
   Toast.makeText(MainActivity.this,
           "This photo donte have ifnormation, remember, for obtain the info you need to save the picture in device before",
           Toast.LENGTH_SHORT).show();
   }
 }else{
   Toast.makeText(MainActivity.this,
           "You dont have data to show because the photo is null (your photo isn't in memory device)",
           Toast.LENGTH_SHORT).show();
 }

 and the method that I use in the example is for validate not null or empty
    private boolean notNullNotFill(String validate){
        if(validate != null){
            if(!validate.trim().equals("")){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
```

See the example of this infomartion return:

![alt tag](https://raw.githubusercontent.com/fabian7593/MagicalCamera/master/Images/information2.png)

# Footer Document

## Internal documentation
All the code has a internal documentation for more explanation of this example.

## Preview of Example

![alt tag](https://raw.githubusercontent.com/fabian7593/MagicalCamera/master/Images/magicalcamera.gif)

## Application that use MagicalCamera
UTNCources

ExampleMagicalCamera

Feel free to contact me to add yours apps to this list.

## Suggestions
MagicalCamera was created to make Android Devoloper's life easy. If you have any feedback please let us know in the issues by creating an issue with this format:

 - Write what your feedback is about and add the next "tag" including the square brackets [FEEDBACK]

Suggestions about how to improve the library or new features are welcome. Thanks for choosing us.

## Credits and Contributors

**Author**
### [Fabián Rosales - Frosquivel Developer](https://github.com/fabian7593) :
A magical camera author, I do the take camera, select photo, rotate picture, convert bitmap, facial recognition, save picture, get information and others...

[![alt tag](https://raw.githubusercontent.com/fabian7593/CountryAPI/master/Files/imgsReadme/github-logo.png)](https://github.com/fabian7593)
[![alt tag](https://raw.githubusercontent.com/fabian7593/CountryAPI/master/Files/imgsReadme/facebook.png)](https://www.facebook.com/fabian.rosales.509)
[![alt tag](https://raw.githubusercontent.com/fabian7593/CountryAPI/master/Files/imgsReadme/linkedin.png)](https://www.linkedin.com/in/fabian-rosales-esquivel-698893106/)
[![alt tag](https://raw.githubusercontent.com/fabian7593/CountryAPI/master/Files/imgsReadme/youtube.png)](https://www.youtube.com/channel/UCJnvvHb_vwMwbnZWplkHIfw)

**Contributors**
### [Erick Navarro](https://github.com/cutiko)
**MagicalCamera Contributor (Cutiko)**
Erick Add a best usage of google play library, and he develop the better usage of permissions, and an excellent code refactor for permission class and other components.

### [Arthur Zettler](https://github.com/arthursz)
**MagicalCamera Contributor (arthursz)**
Arthur create the return path of the image saved like a String.

## Contributors are welcome
The goal for MagicalCamera is to allow Android Developers care about what is important, feautures not getting worry about something that should be trivial such as taking a picture. We look forward to make this a great library to make image capture process simple and painless. There are amny features and other issues waiting. If you would like to contribute please reach to us, or maybe be bold! Getting a surprise pull request is very gratifying.

## Video
## You can see the video explication here (in spanish) This video is for MagicalCamera version 1.0
https://www.youtube.com/watch?v=U-JxaFZDSn4

# License
Copyright 2016 Fabian Rosales

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

repository: TalebRafiepour/MagicalCamera

repo_name: TalebRafiepour/MagicalCamera


text:
# Risk Indication App

## How to install this app

Before installing you will need an up to date version of [Node](https://nodejs.org/en/).

Then you can `git clone git@github.com:Maikxx/polymer.git`.
To install the dependencies, run: `yarn` or `npm install`, whatever you feel like.
Then to run the application: `yarn start` or `npm start`.

## About

This focusses on healtcare workers, that mainly have to deal with youth.
The main goal of this application is to decrease the amount of young people that need to leave their house as a result of threathening situations in and around the household.

What you can do in this current version:
* Calculate a risk indication percentage, by filling in input fields about a certain person. This percentage is immediately calculated when you change something in the application.
* Reset this percentage.

As for more features, there are none...
Read on to know why that is and what I would like to be added in this application.

## Concept

Here you can find my full concept in images. Most of the concept is, as stated above, not in the current application.

### Healtcare worker login screen

![Login screen](docs/loginScreen.jpg)
![Forgot password](docs/forgotPassword.jpg)

### User selection screen

The healtcare worker has to select the child they are working with at that moment in time. The children which the healtcare worker works with most are shown at the top.

It is important to note that every action the healthcare worker performs gets logged and shown in the logs screen. This is done for accuracy purposes.

For other occassions, like when a receives a new healthcare worker, all the filled in data will be transferred to that healthcare workers account, so he or she does not have to go through the forms again, unless when there would be reason for that.

![User selection screen](docs/userSelection.jpg)
![User selection active screen](docs/userSelectionActive.jpg)

### Home screen

This is the page the healthcare worker lands on, once they have logged in and selected a child.
Here they can reset all the filled in fields for this child and also export the data in excel or pdf format.

![Home screen](docs/homeScreen.jpg)
![Reset modal](docs/resetModal.jpg)
![Storage modal](docs/storageModal.jpg)
![Storage modal active](docs/storageModalActive.jpg)

### Form screens

The input fields are located on these screens.
They are seperated by category and do not require the user to press a button to recalculate the risk percentage.
Navigation between these pages can be found in the menu at the top of the screen.

![General form screen](docs/formScreen.jpg)

### Indication calculation overview screen

On this screen you can view the way the percentage is calculated.
The form fields are shown by category (tab) and shows a indication of the filled in value from `none` to `extreme`.

![Calculation screen](docs/calculationScreen.jpg)

### Log screen

On this screen the user can find all system logs, which may be important to them.
This can include the exporting of data, the changing of fields etc.

![Log screen](docs/logScreen.jpg)

## Progress

### Week 1

In the first week I attended four days of full-day-study colleges.

I went to the guest speakers talks, this tuesday, where my boss (Peter Peerdeman from Lifely) was talking about React.

When I had to choose three frameworks, which I would like to learn, I chose:
* Vue
* React
* Polymer

When the three spokesmen this tuesday spoke about their personal favorite frameworks, I immediately wanted to learn Vue. It looked really fun to learn and since I already know React, I decided to go with that as a first choice.

The next day, me and three others had decided for us that we needed to do Polymer.
This was a big bummer, because I would have liked to learn Vue more.

What also was not great, was the fact that Polymer has terrible docs and barely any community support.
We got the framework to work in about a day, which was not terrible, but understanding still has to be gained.

When I finally got the support talk with Laurens, I knew what the excersise was about.
I decided to make a risk indication application for the healtcare workers, so that they would get an easier job.

In this first week I mainly focussed on getting Polymer to work, which took way longer than expected.
What I finished after week one, was mainly the structure of the application.
I had **routing**, **components**, **views** and and some general content.

There was pretty much no custom styling in the application at this point.

I did get to appreciate framework writers their work more right now. For the most part, they do not have any guidance in to writing their own framework.

What I also did in this week, was mainly figuring out a way in which styling could be seperated from the JS.
Unfortunately, I could not find anything of relevance about this subject, so I decided to give up on that part.

### Week 2

In this week I mainly focussed on getting the application to actually give a risk and save the answers users put into the forms.

This took way more time than expected, because Polymer doesn't just simply have a concept for managing states like, for example, React does have.
What Polymer also lacks, is a well-defined way of passing functions by properties, which caused a lot more trouble.

The way I built all of this **now**, is with a lot of functions, that sit in the *utils* folder.
I did manage to create a new understanding about localStorage and functional programming.
I found myself wanting to write clean code, so I abstracted **a lot** of code into more readable bits and pieces.

The [startup](src/utils/startup.js) file, for example, contains logic that runs once the page is loaded.
What this does (in short), is that the localStorage of a new user gets filled with all values required to run the application.

Existing users are noticed here as well, which causes the localStorage data to be parsed to JSON and then put into variables that can be used by the applications forms.

The bussiness logic for generating the percentage at the top of the screen in real-time can be found [here](src/utils/generatePercentage.js). This function takes the array of factorCombinations, that is found in the users localStorage and loops over the values, inserting them in the function that calculates the percentage.

As for the other utils, they are simply functions that do exactly the same, as their name implies.

The [getLocalStorageValue](src/utils/getLocalstorageValue.js) function simply gets the value for a specific input by that inputs name and it's subclass in the data structure and returns it.

The [setFactorValue](src/utils/setFactorValue.js) function sets the factor value of a specific input to the value that is required, i.e. 0 or the factor.

The [setNewLocalstorageValue](src/utils/setNewLocalstorageValue.js) function is used by the application to set the selected value of an input to the localStorage of a user.

One more note about the [triggerRegenerateEvent](src/utils/triggerRegenerateEvent.js) code.
As you might see this is not normal code... This had to be done in order for the [index](src/index.js) to be notified when a child component two levels down would want the percentage to recalculate.

What I also did this week, was mainly help [Chelsea](https://github.com/chelseadoeleman), Jessie and Linda with their applications, which took up a lot of my time, but was fun to do and learned me understand my own code better, while helping them understand all of the complicated stuff above.

#### The less fun stuff

*If you don't want to hear me rant, skip this!*

Why I did it with the Event API and not something native to Polymer... Polymer does not have great documentation, hence the reason I could not find a way to get this to work (with callbacks for example).

As you might be able to read, I am a little bit frustrated by this so called *framework*.
If they would want to compete as a framework with React, Vue and Angular, they do really need to get their documentation and API straight.

The documentation and answers you find on Google are mainly about older versions of Polymer, which are (like anything Google makes), for some reason really different from the newest version.

Polymer feels like it is a *framework* that is missing a ton of essential features, which causes the user (i.e. me) to get creative, which is in itself not a problem.
However, when there is a deadline, this becomes a major problem.

## What is Missing?

* A checked build proces
* TypeScript support
* Seperation of Concerns (structure - styling - interaction)
* Mobile / Tablet modes
* Quite a few factors and inputs, since they aren't available
* A way to keep multiple filled in forms (for example of a specific user) and switch between them
* Some form fields, like location, an image input.

## What would be added in future versions?

Aside from all of the above (if possible), things that would be added are:

* A page where the user can see at a glance what he or she filled in, and what factor that answer contains. This could bring more understanding at the person that is using the application
* A more thought out routing structure, in order for the user to navigate the application more easily
* User signup
* A better concepting result (for example, better images of the designs)
* Helped person selection menu.
* Exporting data of a person.

## PDX (Polymer Developer Experience)

As mentioned before, Polymer has a poor developer experience.
However, I used the following links to make some sense up about Polymer:

* [Polymer 3 Starter Kit](https://github.com/Polymer/polymer-starter-kit)
* [Polymer 3 Docs](https://www.polymer-project.org/3.0/docs/devguide/feature-overview)

## License

This repository is licensed as [MIT](LICENSE) by [Maikel van Veen](https://github.com/maikxx), 2018.

repository: Maikxx/frontend-applications

repo_name: Maikxx/frontend-applications


text:
[![Release State](https://img.shields.io/badge/state-pre--alpha-red.svg)](https://img.shields.io/badge/state-pre--alpha-red.svg)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](./LICENSE)
[![Build Status](https://travis-ci.org/dfst/deepforge.svg?branch=master)](https://travis-ci.org/dfst/deepforge)
[![Stories in Ready](https://badge.waffle.io/dfst/deepforge.png?label=ready&title=Ready)](https://waffle.io/dfst/deepforge)
# DeepForge
DeepForge is an open-source visual development environment for deep learning. Currently, it supports Convolutional Neural Networks but we are planning on supporting additional deep learning classifiers such as RNNs and LSTMs. Additional features include real-time collaborative editing and version control.

## Quick Setup
After cloning the repo, run

```
npm install && npm start
```

Now, navigate to `localhost:8888` in a browser and create a new project. Select `nn` as the seed and start creating your neural nets!

## Caffe Support?
DeepForge uses Torch to perform the actual training and testing of the models. If you are interested in DeepForge using Caffe for actual training and testing, check out [DeepForge-Caffe](https://github.com/dfst/deepforge-caffe).

## Interested in contributing?
Contributions are welcome! Either fork the project and submit some PR's or shoot me an email about getting more involved!


text:
---
Title: exdownstream
Description:
Author: Deon Poncini

---
exdownstream
===============

Developed by Deon Poncini<EMAIL_ADDRESS>
Downloads
---------

Description
-----------
Example downstream consumer executable that uses the scripts build system.
Take note of how find\_package is used inside the CMakeLists.txt

Building
--------

Usage
-----

License
-------
Copyright (c) 2014 Deon Poncini.
See the LICENSE file for license rights and limitations (MIT)

repository: DeonPoncini/exdownstream

repo_name: DeonPoncini/exdownstream