text:
datahub
====

A tiny data layer for any frontend project.

Datahub suggests you to only manipulate data to make your application logic clearer and more easy to read. All you need to do is to listen&invoke data change by config each component. And each component should totally unaware others' existance.

Install
------

```
npm install datahubjs
```

Or you can use the file in `dist`, a global variable named `DataHub` is provided.

Data Flow
=====

```
 _______                               ______________               ------------
|       |  hub.set("any-prop", val)   |              |   _digest() |            |
| state |  -------------------------> |   trasient   | ----------->|   updated  |
|       |                             |     state    |             |    state   |
|_______|                             |______________|             |____________|
                                          ^      |                       |
                                          |      |                       |   invoke callbacks
                                          |_ _ _ |                       V
                                    hub.set('any-prop', val)    |------------------|
                                                                | update component |
                                                                |------------------|
```

API
====

####set(propName, value)

Update a specified propName as the passed-in value.

*Notice*: the prop will update after a digest cycle, not update immediately.

####get(propName, value)

Get a specifed propName value;

###on(props, callback)

Listen to any number of prop changes.
The callback will invoke after a digest cycle only if any listened props were changed
and arguments will be map to the listened props.

If props is not provided, the callback will register as a global callback. It means
the callback will be invoked after each digest.

```javascript
var hub = datahub.getInstance();
hub.on('hello', function(val) {
  console.log('hello is: ' + val);
});
hub.on(['hello', 'world'], function(hello, world) {
  console.log('composite: '+ hello + " , " world);
});
hub.set('hello', 1);
hub.set('world', 2)

=>

hello is: 1
composite: 1 , 2

```

###watch(expression, callback)

Listen to an expression and campare the newVal with the old value every digest cycle.
It will invoke the callback once detect the newVal is different with the oldVal.

```javascript

var hub = datahub.getInstance();
hub.watch('hello + world', function(val) {
  console.log(val);
});
hub.set('hello', 10);
hub.set('world', 3);

=>

output: 13

```

License
====
MIT

repository: ssnau/datahub

repo_name: ssnau/datahub


text:
# Load vector data

This topic describes how to load a vector data file to Ganos by using shp2pgsql, ogr2gr, or QGIS.

## Preparations

Before you load a vector data file, the following command is run on your RDS instance to create the ganos\_raster extension:

```
CREATE EXTENSION Ganos_Raster CASCADE
```

## Load vector data by using shp2pgsql

The shp2pgsql command line tool is used to convert Esri shapefiles into SQL files. For more information, see [shp2pgsql](https://postgis.net/docs/using_postgis_dbmanagement.html#idm2274). Then, you can load the SQL files into Ganos.

-   Syntax

    ```
    shp2pgsql -s <srid> -c -W <charset> <path_to_shpfile> <schema>.<table_name> | psql -d <dbname> -h <host> -U <user_name> -p <port>
    ```

-   Parameters

    |Parameter|Description|Example|
    |---------|-----------|-------|
    |-s <srid\>|Specifies the spatial reference system identifier \(SRID\) of the vector data file.|4490|
    |-c|Specifies to create a table.You can also use the following parameters:

    -   -a: appends data to a table.
    -   -d: deletes a table before data is loaded.
    -   -p: creates a schema in SQL without writing spatial data.
|None|
    |-W <charset\>|The character set that is used by the shapefile.|GBK \| UTF8|
    |<path\_to\_shpfile\>|The save path of the shapefile. The save path must be accessible to the shp2pgsql command line tool.|/home/roads.shp|
    |<schema\>.<table\_name\>|The name of the geometry table that you created.|public.roads|
    |-d <dbname\>|The name of the database.|mydb|
    |-h <host\>|The host that houses the RDS instance on which the database is created.|pgm-xxxxxxx.pg.rds.aliyuncs.com|
    |-U <user\_name\>|The username that is used to connect to the database.|my\_name|
    |-p <port\>|The port number that is used to connect to the database.|3433|

-   Examples

    ```
    shp2pgsql -s 4490 -c -W "GBK" /home/roads.shp public.roads | psql -d mydb -h pgm-xxxxxxx.pg.rds.aliyuncs.com -U my_name -p 3433
    ```

    **Note:** If you want to import more than one vector data file at a time by using a script, run the `export PGPASSWORD=my_pass` command to set the PGPASSWORD environment variable to my\_pass.

## Load vector data by using ogr2ogr

The ogr2ogr command line tool is provided by GDAL/OGR to convert data. It supports common vector data types, such as Esri ShapFile, MapInfo, and FileGDB. For more information, see [ogr2ogr](https://postgis.net/docs/using_postgis_dbmanagement.html#idm2274). For more information, visit [Vector drivers](https://gdal.org/drivers/vector/index.html).

**Note:** Before you load vector data by using the ogr2ogr command line tool, make sure that GDAL supports the PostGIS vector driver.

-   Syntax

    ```
    ogr2ogr -nln <table_name> -f PostgreSQL PG:"dbname='<dbname>' host='<host>' port='<port>' user='<user_name>' password='<password>'" -lco SPATIAL_INDEX=GIST -lco FID=<FID_NAME> -overwrite "<PATH_TO_FILE>" -nlt GEOMETRY
    ```

-   Parameters

    |Parameter|Description|Example|
    |---------|-----------|-------|
    |-nln <table\_name\>|The name of the vector data file.|roads|
    |-f PostgreSQL PG:"dbname='<dbname\>' host='<host\>' port='<port\>' user='<user\_name\>' password='<password\>'"|The information that is used to connect to the ApsaraDB RDS for PostgreSQL instance on which the database is connected.|dbname='mydb' host='pgm-xxxxxxx.pg.rds.aliyuncs.com' port='3433' user='my\_name' password='my\_pass'|
    |-lco SPATIAL\_INDEX=GIST|The GiST spatial index that you want to create.|None|
    |-lco FID=<FID\_NAME\>|The ID of the specified feature.|fid|
    |-overwrite|The rewrite mode that you want to use.You can also select the -append mode.

|None|
    |<PATH\_TO\_FILE\>|The save path of the vector data file. Make sure that the save path is accessible to the ogr2gr command line tool.|/home/roads.shp /home/land.tab |
    |-nlt GEOMETRY|Specifies the geometry data type. If the vector data file contains polygon data, we recommend that you specify this parameter. This allows you to avoid errors that occur if the vector data file contains not only data of the MultiPolygon type but also data of other types.|None|

-   Examples

    ```
    ogr2ogr -nln roads -f PostgreSQL PG:"dbname='mydb' host='pgm-xxxxxxx.pg.rds.aliyuncs.com' port='3433' user='my_name' password='my_pass'" -lco SPATIAL_INDEX=GIST -lco FID=fid -overwrite "/home/roads.shp" -nlt GEOMETRY
    ```

## Load vector data by using QGIS

QGIS was known as Quantum GIS. It is a user-friendly, open-source desktop tool that supports various vector and raster formats. It allows you to use databases as data sources. In addition, it allows you to visualize, manage, and analyze data and to prepare maps. For more information, see [QGIS](https://www.qgis.org/en/site/).

1.  Establish a connection to Ganos.

    1.  In the right-side **Browser** pane, create a PostGIS connection.

    2.  Configure the required parameters.

        ![Load vector data into Ganos — QGIS— Connect to Ganos](https://static-aliyun-doc.oss-cn-hangzhou.aliyuncs.com/assets/img/en-US/5125911061/p148423.png)

        The following table describes the parameters.

        |Parameter|Description|
        |---------|-----------|
        |**Name**|The name of the connection.|
        |**Host**|The IP address of your ECS instance or the public endpoint of your RDS instance or PolarDB cluster. You can obtain this information from the Alibaba Cloud Management Console.|
        |**Port**|The port number of your ECS instance, RDS instance, or PolarDB cluster. You can obtain this information from the Alibaba Cloud Management Console.|
        |**Database**|The name of the database.|
        |**SSL Mode**|Specifies whether to establish an encrypted connection based on SSL.|

    3.  Click **Test Connection**. Then, wait until the connection is established.

2.  Load the vector data file.

    1.  In the menu bar, choose **Database** \> **DB Manager**.

    2.  In the dialog box that appears, select the data source from which you want to import the vector data file, and click **Import Layer/File**.

    3.  In the dialog box that appears, click the vector data file, configure the required parameters, and then click **OK**.

license: MIT

path: /intl.en-US/Spatio-temporal Database/FAQ/Load vector data.md

branch_name: refs/heads/master

extension: md

filename: Load vector data.md

license_type: permissive


text:
# TouHou Player

[![Build status](https://ci.appveyor.com/api/projects/status/3hnd8quh22grg4gv/branch/master?svg=true)](https://ci.appveyor.com/project/BLumia/thplayer/branch/master)

[Website](https://bearkidsteam.github.io/thplayer/)

TouHou BGM player for all platform.

## Usage

No need for config. Drag the TouHou game program into `thplayer` main window, or click the **Load** button and choose the game folder. `thplayer` will automatically load songs and then it's ready for use!

## Supported game versions

The Touhou game versions we support are:

``` plain
th07, th08, th09, th10, th11, th12, th13, th14, th15, th16, th17, th18
th095, th125, th128, th143, th165
```

Future TouHou releases should also supported as long as ZUN doesn't change the data format.

This is all made possible by the [thpatch/thtk](https://github.com/thpatch/thtk/) project. Thanks!

## Build

In order to build, you should get the source code first. We are using [thpatch/thtk](https://github.com/thpatch/thtk/) as a git submodule, since the *download as zip* option will **not** pack the submodules inside the zip file, you should use `git clone --recurse-submodules https://github.com/BearKidsTeam/thplayer.git` instead.

### Build using `qmake`

You can choose to build TouHou Player using `qmake` normally.

``` shell
# Clone the repo
git clone --recurse-submodules https://github.com/BearKidsTeam/thplayer.git
# Create a build folder
mkdir ./thplayer/build && cd $_
# Build it
qmake ../thplayer.pro && make && make clean
```

(Tip: If you forget to use `--recurse-submodules` when you clone this repo, you need do `git submodule update --init --recursive` then)

After that, you'll get the runnable binary inside the build folder. Enjoy!

### Build manually

To build it manually, get Qt open-source version from [qt.io](https://www.qt.io/download-open-source/) or from your package manager, install it and open `thplayer.pro` using QtCreator, and build it as you wish!

## License

### BSD 2-Clause License

``` plain
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the
following conditions are met:

1. Redistributions of source code must retain this list
   of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce this
   list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.

repository: Watch-Later/thplayer

repo_name: Watch-Later/thplayer


text:
# react-text-editor

## Cloning and starting the editor
```javascript
git clone https://github.com/bertrandmc/react-text-editor.git && cd react-text-editor
npm i
npm start
```

repository: bertrandmc/react-text-editor

branch_name: refs/heads/main

repo_name: bertrandmc/react-text-editor


text:
# MuJoCo OpenAI Gym Ubuntu
Short description of installation process for MuJoCo-Py on MuJoCo 1.50 with OpenAI Gym on Ubuntu 16.04
**Note**: This is a compilation of my experiences and useful resources I found. Hope this can be a helpful little *how to guide*!

Author: Gabriel Fernandez
GitHub: https://github.com/gabriel80808

## Ubuntu
Make sure to have [Ubuntu 16.04](https://www.ubuntu.com/download/desktop) installed. You can try with another version, but this is the one I am using.

## Anaconda
1. Download the latest version of [Anaconda](https://www.anaconda.com/download/#linux) with Python 3.6 version. My version of Anaconda is 4.5.1. You can probably use any other type of virtual environment. This allows us to isolate the environment we are setting up just incase it breaks.
2. Create a virtual envinronment with Anaconda:
```bash
foo@bar:~$ conda create -n NameOfYourEnvironment python=3.6 anaconda
```
3. Start your virtual environment:
```bash
foo@bar:~$ conda activate EnvName
```
**Note**: You can stay within your virtual environment throughout this process. Where you see `(MyEnv)` in this tutorial it is generally okay to be within your virtual environment. When you modify your python environment you want to be inside your virtual environment. Otherwise it's optional. If you're not sure, it's generally fine throughout this tutorial.

## MuJoCo
1. Go to [Mujoco](https://www.roboti.us/index.html) and follow directions to obtain a license. They have free licenses for students and a 30-free trial version.
2. Download MuJoCo 1.50 binaries for Linux. Right click on the file and go to properties to make sure that the file is executable before running it.
3. Unzip `mjpro1.50` to `~/.mujoco/mjpro150`
4. Place your license key, `mjkey.txt`, from step 2 to ~/.mujoco/mjkey.txt
**Note**: This setup is primarily for [MuJoCo-Py](https://github.com/openai/mujoco-py#obtaining-the-binaries-and-license-key)

## Docker
1. See the [Dockerfile](https://github.com/openai/mujoco-py/blob/master/Dockerfile) for the list of canonical dependencies. If you already know how to run docker files you can go to the next section.
2. See this [tutorial](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-16-04) for a practical instillation guide of docker. Keep in mind that you will have to run `sudo` evertime you run docker unless you change your settings which is also explained in the link.

## MuJoCo-Py
1. Git clone the MuJoCo-Py repository in your hidden `.mujoco` directory:
```bash
(MyEnv)foo@bar:~/.mujoco$ git clone https://github.com/openai/mujoco-py.git
```
2. Copy your MuJoCo license key, `mjkey.txt`, into your recently downloaded repository directory:
```bash
(MyEnv)foo@bar:~/.mujoco$ cp mjkey.txt mujoco-py
```
3. Change your directory to the repository directory.
4. Now you can build your docker file:
```bash
(MyEnv)foo@bar:~/.mujoco/mujoco-py$ sudo docker build -t mujoco_doc .
```
**Note**: `-t` is just tagging the build with a name. Also there is a period at the very end to indicate the directory in which it will build. Take a look at this [simple tutorial](https://deis.com/blog/2015/creating-sharing-first-docker-image/) here.

## OpenAI Gym
1.  Keep in mind if you do a minimal instillation, you need to additionally download and install another package: `pip install -e '.[robotics]`. I will run through the full installation.
2. Make sure all of the necessary dependencies are there or installed:
```bash
(MyEnv)foo@bar:~/.mujoco/mujoco-py$ sudo apt-get install -y python-numpy python-dev cmake zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev python-opengl libboost-all-dev libsdl2-dev swig
```
3. Now we can install the full package:
```bash
(MyEnv)foo@bar:~/.mujoco/mujoco-py$ pip install 'gym[all]'
```

## Sanity Checks
**Note**: If you are not too familiar with how to debug some of the errors, read a little bit of the next section and come back here. It will be an iterative process. Good luck!
1. Start your virtual environment if you haven't done so:
```bash
foo@bar:~/.mujoco/mujoco-py$ conda activate YourEnvironmentName
```
2. Let's start off easy and pull up python and import mujoco_py:
```bash
(MyEnv)foo@bar:~/.mujoco/mujoco-py$ python

```
```python
>>> import mujoco_py
>>>
```
**Note**: If you see any errors or warnings, that means we got a lot of debugging to do. See the next section.

3. Run a slightly modified example from MuJoCo-Py:
**Note**: You should get the same results here unlike the next one. Remember when you load the model you will have to change `foo` to your directory name.
```python
>>> import mujoco_py
>>> model = mujoco_py.load_model_from_path("/home/foo/.mujoco/mujoco-py/xmls/claw.xml")
>>> sim = mujoco_py.MjSim(model)
>>> print(sim.data.qpos)
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>>> sim.step()
>>> print(sim.data.qpos)
[  2.09217903e-06  -1.82329050e-12  -1.16711384e-07  -4.69613872e-11
  -1.43931860e-05   4.73350204e-10  -3.23749942e-05  -1.19854057e-13
  -2.39251380e-08  -4.46750545e-07   1.78771599e-09  -1.04232280e-08]
```
4. Now we can run a more involved check:
```python
>>> import mujoco_py
>>> import gym
>>> import numpy as np
>>> env = gym.make('HalfCheetah-v2')
WARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.
WARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.
```
**Note**: Don't worry about the warning. It's a bug as far as I can tell. There's no way to fix the error without going into the code and basically removing it or initializing it in a function. Additionally, for this example you will get different values from me, so there's no need to freak out. Let's continue.
```python
>>> print(env.action_space)
Box(6,)
>>> print(env.observation_space)
Box(17,)
>>> init_observation = env.reset()
>>> init_observation
array([-0.09592622, -0.00758505,  0.04018139, -0.04553654, -0.03117339,
       -0.0567909 , -0.05794625,  0.01240102,  0.00091251,  0.10259654,
        0.03697612, -0.09892215, -0.00347502,  0.06516283,  0.03751707,
        0.15983774, -0.00057076])
>>> action = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1], dtype='float32')
>>> env.render()
Creating window glfw
>>> obs, reward, done, info = env.step(action)
>>> obs
array([-0.09596615,  0.00432398,  0.01885579,  0.05236691, -0.02897269,
       -0.00611233, -0.00573494,  0.01972231,  0.27388623, -0.15326082,
        0.24379943, -0.05508176,  1.60848039,  1.13358126,  1.53246801,
        1.44243414,  0.29057963])
>>> reward
0.17909146134763032
>>> done
False
>>> env.render()
```

## Misc. Debugging Trickery
**Note**: You're almost there! This section will cover how to deal with a few errors I've come across: missing modules, GLFW3, GLEW, libOpenGL.so.0 & other lib errors associated with GPU CUDAs.

### Missing Modules
As far as python modules go, you will usually get errors that say some module is missing. Simply `pip install` the missing module. If you receive longer compiling errors, especially those with the term `lib` in it, that usually means the GPU libraries are set up incorrectly. See the following sections.

### Modifying `.bashrc` for GLEW, GLFW3 Errors, and More
**Note**: `.bashrc` is a shell script that Bash runs when it starts. That means if you modify it, you have to open a new terminal to run the updated shell script. You can just append these lines to the bottom of your `.bashrc` file. It's a hidden file, so to see it you will need to type in `ls -al` into your terminal. You will need to also open `.bashrc` with an editor such as Sublime or you probably can just type `gedit`. You can probably do the following to get to the file:
```bash
(MyEnv)foo@bar:~$ gedit .bashrc
```
1. Add this line in `.bashrc` to fix MuJoCo-Py GLFW3 error:
```bash
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.mujoco/mjpro150/bin
```
2. Add this line in `.bashrc` to fix MuJoCo-Py GLEW error:
```bash
export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libGLEW.so:/usr/lib/nvidia-390/libGL.so
```
**Note**: The original thread on this error is [here](https://github.com/openai/mujoco-py/pull/145). Check what Nvidia driver you have installed on your system by following the directory path. Mine is `nvidia-390`. Change your number to match your driver. This also applies to the next step, 3.

3. Add this line in `.bashrc` for the MuJoCo-Py environment variable:
```bash
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/nvidia-390
```
### GPU CUDA Related Errors: libOpenGL.so.0, lib*, OpenGL*, Etc
**Note**: This does not go into the setup for CUDAs in Tensorflow. See Tensorflow's [guide](https://www.tensorflow.org/install/install_linux#NVIDIARequirements) and this useful [tutorial](http://www.python36.com/install-tensorflow141-gpu/) for that. I found that majority of the difficult errors arise from having an outdated driver or somehow the wrong one. In particular it was an Nvidia card for me. Later on I will mention how on an older version of MuJoCo-Py I avoided this by simply running it off of my Intel Core i7. I possibly may do a CUDA setup installation guide in the future. Cross my fingers.
1. Find and keep note of GPU and other system information:
```bash
foo@bar:~$ lspci | grep -i vga
00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)
01:00.0 VGA compatible controller: NVIDIA Corporation GK107M [GeForce GT 640M] (rev a1)
foo@bar:~$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
```
**Note**: `lscpu` will produce a much longer list of information but we just want the first two lines. From the first command we typed, we found out that: My product type is GeForce, and my product series is GeForce 600M series. We are on Linux 16.04 if you forgot. The second command now tells us that my system can run 32-bit and 64-bit, and the architechture is set up for 64-bit. In the next step, 2, I want to fill in Linux 64-bit. If your system runs both, you probably want 64-bit for better performance.

2. Go to the [Nvidia Driver Search Page](https://linuxconfig.org/how-to-install-the-latest-nvidia-drivers-on-ubuntu-16-04-xenial-xerus) and fill out the fields with the information we collected from step 1. The version number for mine reads 390.48. Don't worry about what comes after the decimal. You can build from source, but I decided to just use `apt-get`. For now just take note of the driver number you need and don't worry what comes after the decimal place.

3. Assuming you already have a Nvidia driver installed. Restart your computer. On the start up GRUB boot menu make sure to highlight the Ubuntu entry and press the `E` key. It should bring you to a page you can edit. Don't delete anything. Just at the very end add `nouveau.modeset=0` and then press the `F10` key to continue booting.

4. On the login screen enter the keys `Ctrl` + `Alt` + `F1`. Then proceed to login with your normal credentials as if you were at your normal login screen.

5. Now we will delete everything related to Nvidia to start from fresh:
```bash
foo@bar:~$ sudo apt-get purge nvidia*
foo@bar:~$ sudo reboot
```

6. On the reboot repeat steps 3 and 4.

7. Once we are logged back in, we can install the Nvidia drivers from the proprietary GPU drivers' PPA:
```bash
foo@bar:~$ sudo add-apt-repository ppa:graphics-drivers/ppa
foo@bar:~$ sudo apt-get update
foo@bar:~$ sudo apt-get install nvidia-390 nvidia-prime
foo@bar:~$ sudo reboot
```
**Note**: Please remember to change the nvidia driver to the correct number in step 2. I additionally installed `nvidia-prime`. `nvidia-prime` allows the user to switch from the Nvidia card to Intel's. This came in handy in an older version of MuJoCo-Py. If things are really buggy, and you don't need the optimization using Intel's card might save a lot of headaches. To switch cards simply go to the Ubuntu Unity Dash (the search function) and type in Nvidia to pull up NVIDIA X Server Settings. Go to PRIME Profiles and you should see a little option to switch.

## Finished!
Hopefully, this was somewhat helpful. I am very new to the community. This is one of the ways I am trying to give back. Please leave comments or suggestions so that I can modify this to be better. I know how stressful it is getting this set up.

repository: jinparksj/MuJoCo-OpenAI-Gym-Ubuntu

gha_license_id: MIT

repo_name: jinparksj/MuJoCo-OpenAI-Gym-Ubuntu


text:
# TOUCH

> TOUGH integrates a 2-inch resistive touch screen on the front side of the product with an internal NS2009 driver chip. In the M5Tough library, we provide a series of APIs that can be used for touch interaction detection.

## Touch Class

>In the initialization of `M5.begin()`, an instance of `touch` has been created and initialized. You can use the API in this instance to obtain touch interaction information.

- **Function: Initialize the touch screen, this function will be called by default in M5.begin to initialize the touch screen**

- `void begin(bool EEPROMEnabled = true);`

- **Function: Perform screen touch calibration (calibration data will be saved to EEPROM), return to True if it has been calibrated, otherwise enter the calibration page, the user needs to touch the specified location according to the screen prompts**

- `bool calibrationTouch(TFT_eSPI *fb);`

**Routine:**

```clike
#include <M5Tough.h>

void setup()
{
    M5.begin(true, true, true, true);
    while (!M5.touch.calibrationTouch(&M5.Lcd));
    M5.Lcd.fillScreen(TFT_BLACK);
    M5.Lcd.print("Calibration Successfully");
}

void loop()
{

}

```

- **Function: Read touch data**
- `void read();`

- **Function: Read the X coordinate of the touch finger**
- `int GetTouchX();`

- **Function: Read Y coordinate of touch finger**
- `int GetTouchY();`

- **Function: Detect touch finger pressing**
- `bool isPressed();`

- **Function: Detection of touch finger release**
- `bool isRelease();`

- **Function: Detect the movement of the touch finger**
- `bool isMoving();`

- **Function: Wait for the touch finger to release**
- `bool WaitRelease();`

- **Function: Wait for the touch finger to be released and set the timeout period**
- `bool WaitRelease(uint64_t AutoReleseTime);`

- **Function: Read the touch point information, return a TouchPoint structure, which contains X, Y coordinate information, and implement operator overloading internally, support direct assignment and comparison of TouchPoint type structures**
- `TouchPoint getPoint();`

## TouchPoint

>By calling the getPoint method, a TouchPoint structure type data can be obtained. Its internal members and methods are as follows.

```clike
class TouchPoint
{
public:
    TouchPoint(int16_t x_ = -1, int16_t y_ = -1);
    bool operator==(const TouchPoint &p);
    bool operator!=(const TouchPoint &p);
    bool operator=(const TouchPoint &p);

    bool Equals(const TouchPoint &p);

    void set(int16_t x_ = -1, int16_t y_ = -1);
    bool vaild();

    int16_t x, y;
};

```

>Users can create a screen area by creating an instance of the TouchZone structure, using the built-in `contains` method to determine whether TouchPoint is contained in the area.

## TouchZone

```clike
typedef struct TouchZone
{
    uint16_t x;
    uint16_t y;
    uint16_t w;
    uint16_t h;
    TouchZone(): x(-1), y(-1), w(0), h(0) {}
    TouchZone(uint16_t _x, uint16_t _y, uint16_t _w, uint16_t _h): x(_x), y(_y), w(_w), h(_h)();
    bool contains(const TouchPoint &p)
    {
        if ((this->x == -1) || (this->y == -1) || (this->w == 0) || (this->h == 0))
            return false;
        if ((p.x >= this->x) && (p.x <= (this->x + this->w)) &&
            (p.y >= this->y) && (p.y <= (this->y + this->h)))
        {
            return true;
        }
        return false;
    }
} TouchZone_t;

```

> When dynamically reading touch data, you need to add `void update();` to the loop to refresh the touch data.

**Routine:**

```clike
#include <M5Tough.h>

TouchZone clearBtn(0,0,50,50);

void setup()
{
    M5.begin(true, true, true, true);
    while (!M5.touch.calibrationTouch(&M5.Lcd));
    M5.lcd.drawString("CLEAR",5,5,3);
}

void loop()
{
    M5.update();
    if(M5.touch.isPressed()){
        TouchPoint Point = M5.touch.getPoint();
        if(M5.touch.isMoving()){
            char buffer[24];
            sprintf(buffer, "X: %3d, Y: %3d", Point.x, Point.y);
            M5.Lcd.drawPixel(Point.x, Point.y ,TFT_GREEN);
            Serial.println(buffer);
        }
        if(clearBtn.contains(Point)){
            M5.lcd.fillScreen(TFT_BLACK);
            M5.lcd.drawString("CLEAR",5,5,3);
        }
    }
}

```

- For more information about Touch API, please refer to [M5Tough-Github source code](https://github.com/m5stack/M5Tough/tree/master/src)

gha_language: JavaScript


text:
# Powershell Azure Function Mashup - Dad Jokes and Cat Pics

[![Deploy to Azure](https://azuredeploy.net/deploybutton.svg)](https://azuredeploy.net/?repository=https://github.com/dfinke/powershell-azure-function-mashup-dad-jokes-cat-pics/tree/master)

Check out [Awesome Powershell Azure Functions](https://github.com/dfinke/awesome-powershell-azure-functions)

## This PowerShell Serverless Function Inspired by

https://itnext.io/serverless-from-the-beginning-part-ii-getting-to-know-your-portal-ide-eff3bffed4e3

Then added more jokes and dog pics.

## Try an already deployed version

Give it a moment to warmup, it's using the free consumption plan.

- https://powershell-joke-page.azurewebsites.net/api/JokePage

# Some Prerequisites

- [Install .NET Core SDK 2.2+](https://dotnet.microsoft.com/download) (required by Azure Functions Core Tools and available on all supported platforms).
- Install version 2.x of the [Azure Functions Core Tools](https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local#v2).

# How To Run

1. `git clone https://github.com/dfinke/powershell-azure-function-mashup-dad-jokes-cat-pics.git`
1. cd `powershell-azure-function-mashup-dad-jokes-cat-pics`
1. `func start`
1. Paste into a browser `http://localhost:7071/api/JokePage`


text:
# kafka-connect-zeebe

[Kafka Connect](https://docs.confluent.io/2.0.0/connect/)or for [Zeebe.io](http://zeebe.io/)

**This is a prototype for a POC - it is not production ready!**

See this blog post for an introduction: https://zeebe.io/blog/2018/12/writing-an-apache-kafka-connector-for-zeebe/

Features:
* Correlate messages from a Kafka topic with Zeebe workflows. This uses the [Zeebe Message Correlation](https://docs.zeebe.io/reference/message-correlation.html) features. So for example if no matching workflow instance is found, the message is buffered for its time-to-live (TTL) and then discarded. You could simply ingest all messages from a Kafka topic and check if they correlate to something in Zeebe.
* Send messages from a workflow in Zeebe to a Kafka topic.

![Overview](overview.png)

# How to use the connector

* Build via mvn package
* Put the resulting UBER jar into KAFKA_HOME/plugins
* Run Kafka Connect using the Connector pointing to the property files listed below: connect-standalone connect-standalone.properties zeebe-sink.properties zeebe-source.properties

## Sink (Kafka => Zeebe)

The sink will forward all records on a Kafka topic to Zeebe (see [sample-sink.properties](blob/master/src/test/resources/zeebe-test-sink.properties)):

```
name=ZeebeSinkConnector
connector.class=...ZeebeSinkConnector

correlationJsonPath=$.orderId
messageNameJsonPath=$.eventType

zeebeBrokerAddress=localhost:26500

topics=flowing-retail
...
```

In a workflow model you can wait for certain events by name (extracted from the payload by messageNameJsonPath):

![Overview](bpmn1.png)

## Source (Zeebe => Kafka)

The source can send records to Kafka if a workflow instance flows through a certain activity ([sample-source.properties](blob/master/src/test/resources/zeebe-test-source.properties)):

```
name=ZeebeSourceConnector

connector.class=...ZeebeSourceConnector
zeebeBrokerAddress=localhost:26500

topics=flowing-retail
```

In a workflow you can then add a Service Task with the task type "sendMessage" which will create a record on the Kafka topic configured:

![Overview](bpmn2.png)

## Filtering Variables

You can filter the variables being sent to Kafka by adding a custom header to the "sendMessage" task with the key "variablesToSendToKafka".

Set the value of this key to a comma-separated list of variables to pass to Kafka.

If this custom header is not present, then all variables in the scope will be sent to Kafka by default.

![Filter Variables](variables-custom-header.png)

repository: smartlgt/kafka-connect-zeebe

repo_name: smartlgt/kafka-connect-zeebe


text:
<img src="https://github.com/helpdeveloper/githubers/blob/master/app/src/main/ic_launcher-web.png" width="128">

# Githubers
 ### Project under development (Projeto em desenvolvimento) ...

[pt]
 Githubers é um aplicativo que utiliza a [API do GitHub](https://developer.github.com/v3/) para realizar
 consultas e favoritar usuários ou repositórios.

 A idéia desse projeto é documentar e desenvolver de maneira simples quase todos os novos recursos do JetPack
e outras dependências essenciais no desenvolvimento de uma aplicação bem arquitetada seguindo os passos do
próprio
guia de arquitetura do Google.

[en]
 Githubers is an application that uses the [GitHub API](https://developer.github.com/v3/) to perform queries
 and favor users or repositories.

 The idea behind this project is to document and develop in a simple way almost all new JetPack features and
 other essential dependencies in developing a well-designed application following the steps of Google's own
 architectural guide.

 ------

  Technologies / Resources:

   JetPack, Navigation, Room, Glide, Coroutines, Retrofit, Data Binding, LiveData, ViewModel, Dagger2, Worker,
   Gson, ContentProvider, SearchableView, Category Browsable etc.

 Functionalities:

 - List of favorite users;
 - Generic list of users returned by the API
 - List of user repositories;
 - List of user repositories;
 - Repository details;
 - List of favorite repositories;
 - Search of users;
 - Search of repositories;
 - Open in-app external links from github.com
 - Share user link
 - Share repo link

## Dependencies / Libraries:

   - [JetPack](https://developer.android.com/jetpack/docs/guide)
   - [Navigation](https://developer.android.com/topic/libraries/architecture/navigation/)
   - [Data Binding](https://developer.android.com/topic/libraries/data-binding/)
   - [LiveData](https://developer.android.com/topic/libraries/architecture/livedata)
   - [ViewModel](https://developer.android.com/topic/libraries/architecture/viewmodel)
   - [Worker Manager](https://developer.android.com/topic/libraries/architecture/workmanager/)
   - [Paging](https://developer.android.com/topic/libraries/architecture/paging/)
   - [Room](https://developer.android.com/topic/libraries/architecture/room)

   - [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html)
   - [Dagger](https://google.github.io/dagger/)
   - [Glide](https://bumptech.github.io/glide/)
   - [Retrofit](https://square.github.io/retrofit/)

   See the dependencies used: [build.gradle](/app/build.gradle)

## Tutorials and guides

### Android guides / architecture / Projects (github)

 - [Android guide](https://developer.android.com/guide/)
 - [GitHub - android-architecture-components](https://github.com/googlesamples/android-architecture-components)
 - [GitHub - android-sunflower](https://github.com/googlesamples/android-sunflower)
 - [CodeLabs - android-paging](https://codelabs.developers.google.com/codelabs/android-paging)
 - [Search Interface](https://developer.android.com/guide/topics/search/search-dialog)

### Coroutines

 - https://proandroiddev.com/kotlin-coroutines-patterns-anti-patterns-f9d12984c68e
 - https://proandroiddev.com/coroutines-for-android-6f9b9f966056

 - Coroutine Adapter para Retrofit2:
     - https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter
     - https://android.jlelse.eu/kotlin-coroutines-and-retrofit-e0702d0b8e8f

### Room - Object relation map (ORM)

 - https://medium.com/androiddevelopers/7-pro-tips-for-room-fbadea4bfbd1

### Dagger - Dependency injector (DI)

 - https://github.com/googlesamples/android-architecture-components/tree/88747993139224a4bb6dbe985adf652d557de621/GithubBrowserSample/app/src/main/java/com/android/example/github/di
 - Dagger com Worker:
     - https://stackoverflow.com/questions/52434165/dagger2-unable-to-inject-dependencies-in-workmanager
     - https://gist.github.com/gbzarelli/5012ecd63268e26d8ef63c36ed2ee643

## License

[Apache-2.0](https://choosealicense.com/licenses/apache-2.0/)

repository: gbzarelli/githubers

repo_name: gbzarelli/githubers


text:
---
layout: post
title:  "A trip into Kotlin Multiplatform Projects, Part 1"
author: me
categories: [ Kotlin, Multiplatform, Android, iOS, Bluetooth ]
image: /assets/images/kotlin-multiplatform-pt1.jpg
featured: false
hidden: false
---
We at **MOLO17** are always looking for **new technologies** that can boost our productivity
and allow us to deliver software at its best. Since 2017 we started adopting **Kotlin** with profit
as the main language for developing **Android** applications. After we wrote a huge project with
**JetBrains** language, I personally started believing that this new technology is going to
introduce a breeze of innovation in modern software development.
Recently, I invested my time studying the **Kotlin Multiplatform** Feature.

## Kotlin Multiplatform

**Kotlin Multiplatform** (or MPP, Multi Platform Project) is a powerful tool that combines
**Kotlin/JVM** (which compiles into JVM bytecode), **Kotlin/JS** (which compiles into Javascript)
and **Kotlin/Native** (which compiles into low-level binaries) together allowing a developer
to write a common codebase entirely in Kotlin, specialize it with some platform-dependent
implementations, and ship a software which runs on the JVM (or Android), on the web and, why not,
in your iPhone. And when I say that runs, I mean that runs absolutely well.

## Cool, isn’t it?

Some of you may argue that this is yet another way to write a cross-platform mobile app,
like the Cordova or Ionic frameworks using JS, or Xamarin using C#.

But this is not what the people behind Kotlin Multiplatform MPP meant when designing this technology.

Just by looking on how the project will be structured by following the JetBrains’ guidelines,
we can state that the principle behind this kind of multiplatform concept is **code sharing**.
It’s made possible by defining in a common module the Kotlin pure definitions and implementations
of entities and classes. In this module, all your business logic, presentation logic
and – with the right libraries – data-access logic will take place. The rule of thumb is
always to be **framework-agnostic**.

The [Kotlin Academy Portal application](https://github.com/MarcinMoskala/KtAcademyPortal) developed
by Marcin Moskala is just one of the proofs of the feasibility of these intentions.

As a Software Engineer with a main focus on the Android platform,
I started some projects for mastering the **Kotlin Multiplatform**.

## The Kotlin Multiplatform project

The first project I developed was a simple Bluetooth mobile library, for the Android and iOS platforms.
The goal was to write a common API for both the environments, for a simplified access to the Bluetooth framework.

I started by creating the project following the documentation at Kotlin’s website.
Pretty easy to setup and get running. The cool thing I really appreciated is that we can create
a MPP directly from Android Studio! So no need to install **IntelliJ**.
The first-step expectation was an API that allowed the developer to start the discovery of BLE peripherals.
So I started defining the common interface for this class, something like this:

```kotlin
expect class BluetoothAdapter {
    fun discoverDevices(callback: (BluetoothDevice) -> Unit)
    fun stopScan()
}
```

## The expect keyword in Kotlin Multiplatform

Notice the `expect` keyword at the beginning of the class declaration.
In the Kotlin Multiplatform context, the `expect` keyword defines an entity
(a class, a method, a property, or even a constructor) that the developer is declaring
in the common module and is expected to be present in the target platforms. By “expecting”
such entity, the developer needs also to “actualize” it in the platform-dependent module,
using the `actual` keyword. A sort of interface-implementation paradigm, but more dynamic.
And here comes the sugar.

## Kotlin Multiplatform – Android Target

When targeting in Kotlin Multiplatform the Android platform, nothing’s different with
the implementation you’ll do with a standard project approach. You need our lovely god `Context`
object, from which you get a `BluetoothManager` and then you can access to the system
`BluetoothAdapter` instance.

A powerful feature on the `expect`/`actual` paradigm is that *if you expect a class,
you’re not required to expect also the constructor of that class*. So in my case,
I was able to create the actual definition that required a `Context` instance in the constructor,
which allowed me to implement the definition as I wanted to.

```kotlin
actual class BluetoothAdapter(
    private val context: Context
) : ScanCallback() {
    // ...

    actual fun discoverDevices(callback: (BluetoothDevice) -> Unit) {
        this.callback = callback
        bluetoothAdapter.bluetoothLeScanner.startScan(this)
    }
    actual fun stopScan() {
        bluetoothAdapter.bluetoothLeScanner.stopScan(this)
        callback = null
    }
}
```

## Kotlin Multiplatform – iOS Target

More sugar comes when targetting the iOS platform. Apart from the benefits you get by not using **Xcode**,
you get other advantages by using **Kotlin as iOS programming language**. The Kotlin lib offers
bridges classes which translates the **Objective-C** system APIs (like `CoreBluetooth` in our case)
in Kotlin classes. That allowed me to implement the iOS “actualization” of my Bluetooth class
using `CoreBluetooth`, writing in Kotlin. Awesome.

I instantiated the `CBCentralManager` as usual, I set a `CBCentralManagerDelegate` instance to it
and started receiving the discovered peripherals. Notice also that when translating protocol to Kotlin,
the compiler adds the `Protocol` suffix to the base name.

At first, I wanted to make my actual class named `BluetoothAdapter` implement the delegate protocol
directly. Hence, I did it. But since the `CBCentralManagerDelegate` implements the `NSObjectProtocol`,
I was required to let my actual class implement also the methods defined by this protocol.
To avoid to implement them, I let the class extend from `NSObject`, for having the required methods
already implemented. All went well until I tried to use my class definition into a **Swift** project.

The compiler failed with the following error:

```
'BluetoothAdapter' is unavailable: Kotlin subclass of Objective-C class can’t be imported
```

![Xcode compiler error due to unavailability of BluetoothAdapter](https://blog.molo17.com/wp-content/uploads/2019/02/Schermata-2019-02-02-alle-16.47.59.png)

### Objective-C headers

By looking into the **Objective-C** generated headers, I saw that my `BluetoothAdapter` class
was correctly compiled but marked as unavailable with the above message. So I was not able to
instantiate a new one or even define it as property type.

After some *googling*, I figured out that this behavior is a wanted limitation for avoiding
potentially complex inheritance trees with the `Foundation` classes on the Kotlin side.
Obtaining an instance of my class then was not possible. I declared in Kotlin a function that
returned and instance of my type, and when compiled the return type became `NSObject`.
Hence I wrote down my two cents.

In a nutshell:
> We can use a class which inherits from **Foundation** objects only from the Kotlin side.
If we need to create an instance of it from Swift code, we need to create a builder function in Kotlin.

That's because Kotlin knows how it’s defined and how to create it. Something like this:

```kotlin
fun makeBluetoothAdapter() = BluetoothAdapter()

actual class BluetoothAdapter: NSObject() { ... }
```

And then in the Swift implementation:

```swift
private let myClass = ConsumerClass(
    bluetoothAdapter: BluetoothAdapterKt.makeBluetoothAdapter()
)
```

Our Kotlin codebase of our **Kotlin Multiplatform** project will know the type of the instance
we pass with the `bluetoothAdapter` label, and all will work correctly.

Now, let’s go back to my original purpose. I left my actual class without any extension,
and I eventually created an `object` property subclassing `NSObject` and implementing
the `CBCentralManagerDelegate` protocol.

```kotlin
actual class BluetoothAdapter {
    // ...
    private val delegateImpl = object : NSObject(), CBCentralManagerDelegateProtocol {
        override fun centralManager(
            central: CBCentralManager,
            didDiscoverPeripheral: CBPeripheral,
            advertisementData: Map<Any?, *>,
            RSSI: NSNumber
        ) {
            // ...
        }
    }
    private val manager = CBCentralManager().apply { delegate = delegateImpl }
    actual fun discoverDevices(callback: (BluetoothDevice) -> Unit) {
        // ...
        manager.scanForPeripheralsWithServices(null, null)
        onDeviceReceived = callback
    }
    actual fun stopScan() {
        manager.stopScan()
        onDeviceReceived = null
    }
}
```

## Conclusion

And here we go! A common class and the platform-specific implementations.

Following the **JetBrains** guidelines, I was able to add as *Build Phase* a script that launches
the Gradle task for producing the **Cocoa framework** file, embeddable into an **Xcode** project.

I developed two simple apps, **Android** with Kotlin and **iOS** with Swift. They show a list of
the discovered devices using the common module. The result was great. The Bluetooth discovery worked
flawlessy as if it was implemented in the standard way thanks to **Kotlin Multiplatform**.

The following step was the integration of a standard BLE communication… But that's may be a next post!

Thanks for reading!

Cover image credits: blog.jetbrains.com

> Originally posted in [MOLO17 Blog](https://blog.molo17.com/2019/02/a-trip-into-kotlin-native-multiplatform-projects-part-1/)


text:
mfp-gitignore
=============

This is an unofficial repository providing an initial/template `.gitignore`
file for an [IBM MobileFirst Platform
Foundation](http://www-03.ibm.com/software/products/en/mobilefirstfoundation)
Project. There is **no** official IBM support for these artifacts.
We are attempting to follow the same principles as GitHub's own
[gitignore project](https://github.com/github/gitignore). We will gladly
accept any pull request with corrections or clarifications (especially
explanatory comments).

Usage
-----

1. Include the contents of the appropriate `<VERSION>.gitignore` file in your `.gitignore` file, located at the root of your MFP project.
1. Create an empty file named `.gitkeep` in the `server/java` directory.  MFP requires the `server/java` directory to be present, but Git does not check in empty directories.  The `.gitkeep` file ensures this directory is present when developers clone the Git repository.

*Note*: Prior to version 6.3, IBM MobileFirst Platform Foundation was known as
[IBM Worklight
Foundation](http://www-03.ibm.com/software/products/en/worklight-foundation),
so there are equivalent `.gitignore` files here for versions 6.1 and 6.2. This
repository was formerly known as `worklight-gitignore`.

repository: csantanapr/mfp-gitignore

repo_name: csantanapr/mfp-gitignore


text:
#singa-incubating-0.3.0 Release Notes

---

SINGA is a general distributed deep learning platform for training big deep
learning models over large datasets. It is designed with an intuitive
programming model based on the layer abstraction. SINGA supports a wide variety
of popular deep learning models.

This release includes following features:

  * GPU Support
    * [SINGA-131] Implement and optimize hybrid training using both CPU and GPU
    * [SINGA-136] Support cuDNN v4
    * [SINGA-134] Extend SINGA to run over a GPU cluster
    * [Singa-157] Change the priority of cudnn library and install libsingagpu.so

  * Remove Dependences
    * [SINGA-156] Remove the dependency on ZMQ for single process training
    * [SINGA-155] Remove zookeeper for single-process training

  * Python Binding
    * [SINGA-126] Python Binding for Interactive Training

  * Other Improvements
    * [SINGA-80] New Blob Level and Address Level Math Operation Interface
    * [SINGA-130] Data Prefetching
    * [SINGA-145] New SGD based optimization Updaters: AdaDelta, Adam, AdamMax

  * Bugs Fixed
    * [SINGA-148] Race condition between Worker threads and Driver
    * [SINGA-150] Mesos Docker container failed
    * [SIGNA-141] Undesired Hash collision when locating process id to worker…
    * [SINGA-149] Docker build fail
    * [Singa-143] The compilation cannot detect libsingagpu.so file

repository: nusdbsystem/singa-docs

gha_language: CSS

repo_name: nusdbsystem/singa-docs


text:
---
title: Icon
description: Inkline provides you with an awesome universal icon component that you can use with your favorite icon library.
---

<script setup>
import IntegrationsTable from '../examples/integrations.vue';
import * as examples from '../examples';
</script>

# Icon

## Inkline provides you with an awesome universal icon component that you can use with your favorite icon library.

### Integrations

Inkline provides integrations with the most popular free icon packs, out of the box. Here's why we chose this approach:
- You have one simple component for all icon packs
- The icons are rendered as SVGs and can be scaled up to any size
- Small file size, natively tree-shakeable

<integrations-table></integrations-table>

### Basic Example

Here’s an example of the basic icons included with the `<i-icon>` component.

<example type="icon" :component="examples.IIconBasicExample" :html="examples.IIconBasicExampleHTML"></example>

### Color Variants
You can use text color utility classes to set the color of Inkline's icons.

<example type="icon" :component="examples.IIconColorVariantsExample" :html="examples.IIconColorVariantsExampleHTML"></example>

### Size Variants
You're able to use the `size` modifier to control the size of your icon, using one of the available sizes: `sm`, `md`, and `lg`. The default size is set to `md`.

You can also use text size utility classes to set the size of Inkline's icons.

<example type="icon" :component="examples.IIconSizeVariantsExample" :html="examples.IIconSizeVariantsExampleHTML"></example>

repository: kfern/inkline

repo_name: kfern/inkline


text:
# ex_wwdc19_language_core-polymorphism
This demo implements a REST web service that provides an example of polymorphism using INTERFACE, DICTIONARY, Function Methods and "call by reference".

Using the Genero sample officestore database, the demo creates interface "objects" for the category, supplier and country tables.  A factory defines an INTERFACE to implement C.R.U.D. functions and a DICTIONARY loads the interface objects by a "reference" name derived of the REST request resource.  Then, the C.R.U.D. functions are called by the REST resource name based on the REST method(GET, PUT, POST, DELETE).

Requires: Genero BDL with Web Services(FGLWS) v3.20 of greater to compile and execute.


text:
# E-Commerce Back End
![Badge](https://img.shields.io/badge/license-MIT-orange)
## Description

  This application is developed as a backend for an e-commerce site. The application uses Express.js for the server, MySQL for the database and Sequelize as the ORM to run MySQL models and queries. The user can view various products, their categories, tags and edit them. Insomnia was used to run various API routes. The database is accessed and updated by RESTful API routes and then joined through Sequelize queries.

## Table of Contents

  1. [Installation](#installation)

  2. [Usage](#usage)

  3. [Contributing](#contributing)

  4. [Tests](#tests)

  5. [Links](#links)

  6. [Questions](#questions)

  7. [License](#license)

## Installation

  - Clone the application repository from: https://github.com/SamGTR/E-Commerce-BackEnd.git
  - Install `Node.js` and `MySQL`.
  - Install required dependencies.

## Usage

 Run the following commands at the root of your project:

`mysql -u root -p`

Enter Password when promted

`source db/schema.sql`

`quit`

`npm run seed`

`npm start`

Please refer to the walkthrough [video link](#links) for detailed instructions on application usage.

## Contributing

  Contributions are accepted for improving the application.

## Tests

  There are no tests for this application.

## Links

  Following is the link to the Github repository for E-Commerce Back End application:
  https://github.com/SamGTR/E-Commerce-BackEnd

  Following is the video link for creating schema, seeding database and starting the server using comman line:
  https://drive.google.com/file/d/130Ba8M2PXKh3odcRRaBqadjz1TFlP-lx/view?usp=sharing

  Following is the video link for all API routes using Insomnia:
  https://drive.google.com/file/d/1tNuaoGWdK2oFSUhqsAmVus_g4GoMWSML/view?usp=sharing

## Questions

  Follow me on Github [@SamGTR](https://github.com/SamGTR)

  For any questions, reach out to<EMAIL_ADDRESS>
## License

  This app is licensed under the MIT license.

repository: SamGTR/E-Commerce-BackEnd

repo_name: SamGTR/E-Commerce-BackEnd


text:
# Signing an Android APK within Azure Pipelines

This process is somewhat tedious, but you will only ever have to do it once for each App you develop.
First, we need to create a keystore which contains a key to be used for signing through the `keytool` command line tool which should be available if you installed any recent JDK.

Before executing the tool, however, you need to think about two passwords which you should store in a personal password manager or another safe place: A password for accessing the keystore, and another password for accessing the key which will be used for signing.
[Tips on safe passwords](https://www.google.com/search?q=tips+on+safe+passwords]) (We never want to change these two, however)

## Creating the keystore file
Once that's done, execute the `keytool` in a command line, but replace `<storePassword>` and `<keyPassword>` by your two keys. `<filename>` can be anything you want, in this example, it could be `MonoGameTutorial.keystore`.

    keytool -genkey -v -keystore <filename> -alias uploadkey -storepass <storePassword> -keypass <keyPassword> -keyalg RSA -validity 10000

Fill in the information you are being asked, then type "Yes" (in your language) to confirm.
This will generate a key (unknown to you) which is protected by your `<keyPassword>` and place it into a `<filename>` keystore which is protected by `<storePassword>`. As long as you always use this key for all versions of your app, you will be able to update it in Play Store with maximum security. The key will be valid for 10.000 days which is more than 27 years.
Speaking of security: It would be very unsafe to upload the keystore to GitHub, since people could try to hack it. Fortunately, Azure Pipelines offers a free way for storing it with an additional encryption on their servers, then download and decrypt them within the build.

## Securing the keystore file and passwords
In order to do that, go back to your Azure Pipelines project and within the `Pipelines` section,  click on `Library`->`Secure Files`, then upload your Keystore file there. Once uploaded, click the file in the overview, check the `Authorize for use in all pipelines` setting and click the `Save` button.
Make sure you **do not** accidentally add this file to GitHub.

In order to be able to safely decrypt the file during the build, you need to additionally store your passwords as encrypted variables. The best place to do this is in the configuration of your pipeline. Click the `Pipelines` section again, click the `Edit` button in the top-right corner, then click the three dots, then `Variables`.
Add three variables `keystore.pass`, `keystore.alias` and `keystore.aliaspass`. The alias is `uploadkey` if you did not change it. It would not require encryption, but why not manage it in the same place as the passwords.
Click the lock symbols for each of the variables to store them as secrets.

## Signing the APK with the encrypted keystore and variables
Edit your `azure-pipelines.yml` and add the following section before the publishing one:

    # Sign the app using the decrypted keystore and the passwords stored in the Azure Pipeline
    - task: AndroidSigning@3
      inputs:
        apkFiles: '**/*.apk'
        apksign: true
        apksignerKeystoreFile: 'MonoGameTutorial.keystore'
        apksignerKeystorePassword: '$(keystore.pass)'
        apksignerKeystoreAlias: '$(keystore.alias)'
        apksignerKeyPassword: '$(keystore.aliaspass)'
        zipalign: true

The `apksignerKeystoreFile` parameter is the name of your keystore file. We are being lazy and search any apk in any subfolder with `'**/*.apk'`. Commit and push the changes, you should know how to do that by now.

Congratulations, you signed your first APK with your own key. However, you can not download it or anything, so you need to publish it somewhere.

[Continue with the guide](5_publishing_a_build.md)


text:
---
title: "Neural Network Classifiers"
date: 2019-11-03
tags:
 - Python
 - Jupyter Notebook
 - Text Classification
 - Image Classification
 - Neural Networks
 - Keras
excerpt: "How Build Neural Network Classifiers for Text and Images with Keras"
header:
  overlay_image: "/assets/NeuralBackground.png"
  overlay_filter: 0.3 # same as adding an opacity of 0.3 to a black background
  teaser: "/assets/NeuralBackground.png"
  actions:
    - label: "Go to GitHub Repository"
      url: "https://github.com/xanderhieken/NeuralNetworkClassifier"
---
# Building Neural Network Classifiers for Text and Images with Keras

**This notebook shows how build neural networks using Keras to classify text and images**

## Author

**Xander Hieken** - *Additional Work* - [xanderhieken](https://github.com/xanderhieken)


text:
---
title: Upgrade Notes
description: Important changes to consider when upgrading to Istio 1.7.
weight: 20
---

When you upgrade from Istio 1.6.x to Istio 1.7.x, you need to consider the changes on this page.
These notes detail the changes which purposefully break backwards compatibility with Istio 1.6.x.
The notes also mention changes which preserve backwards compatibility while introducing new behavior.
Changes are only included if the new behavior would be unexpected to a user of Istio 1.6.x.

## Require Kubernetes 1.16+

Kubernetes 1.16+ is now required for installation.

## Installation

- `istioctl manifest apply` is removed, please use `istioctl install` instead.
- Installation of telemetry addons by istioctl is deprecated, please use these [addons integration instructions](/docs/ops/integrations/).

## Gateways run as non-root

Gateways will now run without root permissions by default. As a result, they will no longer be able to bind to ports below 1024.
By default, we will bind to valid ports. However, if you are explicitly declaring ports on the gateway, you may need to modify your installation. For example, if you previously had the following configuration:

{{< text yaml >}}
    ingressGateways:
    - name: istio-ingressgateway
      enabled: true
      k8s:
        service:
          ports:
            - port: 15021
              targetPort: 15021
              name: status-port
            - port: 80
              name: http2
            - port: 443
              name: https
{{< /text >}}

It should be changed to specify a valid `targetPort` that can be bound to:

{{< text yaml >}}
    ingressGateways:
    - name: istio-ingressgateway
      enabled: true
      k8s:
        service:
          ports:
            - port: 15021
              targetPort: 15021
              name: status-port
            - port: 80
              name: http2
              targetPort: 8080
            - port: 443
              name: https
              targetPort: 8443
{{< /text >}}

Note: the `targetPort` only modifies which port the gateway binds to. Clients will still connect to the port defined by `port` (generally 80 and 443), so this change should be transparent.

If you need to run as root, this option can be enabled with `--set values.gateways.istio-ingressgateway.runAsRoot=true`.


text:
# Pierre-Etienne Soury Apply
## COLLECTING METRICS
### Add Tags to your Agent

> ![picture](screenshots/agent_tags.png)
On this picture you can see the tags I added to the agent thanks to the configuration files

### Install your DB Agent
> ![picture](screenshots/db_integrated_ok.png)
On this picture You can see that the db (PostgreSQL) is correctly integrated

### Create a Custom Agent Submitting values at random between 1-1000
> ![picture](screenshots/my_first_metric.png)
On this picture you can this that I'm correctly reporting a metrics with the Agent

### Bonus Question: Change the collection interval to 45s without modifying the Python checkfile

Yes, It's possible to do so without modifying the Python Checkfile,I did it in the [hello.yaml](hello.yaml) configuration File.
```
  init_config:

instances:
  - min_collection_interval: 45

```

## VISUALIZING DATA

### Create a custom timeboard with Datadog API

I used a custom script for that.
[Here](create_timeboard_via_api.rb)
 is the script I used to create the
timeboard.

> ![picture](screenshots/my_api_timeboard.png)
On this picture you can see the result of my script, creating a Timeboard through Datadog API.

> ![picture](screenshots/5min-screen.png)
On this picture you can see the last 5min of my metrics reporting, as I'm sending the snapshot to myself

### Bonus Question: What is the Anomaly graph displaying

The anomaly graph is displaying a metrics, with a grey overlay for the Anomaly function used on this metrics. It is useful to determine if a metrics is reporting normaly or anormal values, thanks to an algorithm based on previous values. On my timeboard, it just overlays a bit my metrics values because It is mostly constant.

## MONITORING DATA

### Create a monitor for the custom metrics with 500 & 800 thresholds

> ![picture](screenshots/my_monitor.png)
On this picture you can see how I have defined my monitor to receive notifications

### And notifications to get customs messages by mail
> ![picture](screenshots/alert-monitor-email.png)
On this picture you can see a typical email I receive when my metrics goes above 800, thanks to the monitoring.

> ![picture](screenshots/warning_email.png)
On this picture you can see a typical email I receive when my metrics goes above 500, thanks to the monitoring.

### Bonus Question: Set up downtimes for weekend and not-working time
> ![picture](screenshots/downtime_notif.png)
On this picture, you can see that I've setup the downtime for my application, to not be notified outside of worktime.

> ![picture](screenshots/no-notifications-outside-workingtime.png)
And here it's the the details of this downtime setup

## COLLECTING APM DATA

### Implement APM

> ![picture](screenshots/final_dashboard.png)
Here is a picture of the result

And [Here](https://p.datadoghq.com/sb/e3173ed8a-a7d8b4026550bb06b28c901b59e9a884) is a link of a Dashboard, with both APM and Infrastructure Metrics

The App I used is a small website I'm currently developping, it's a Ruby on Rails Project. I just added the gem 'dd-trace', and a datadog.rb initializer.

 It is for me mostly data, a memory location, a way to access it and the according permissions. A Service is more of a controller, allowing execution of desired operations, without regards toward the data type.

## FINAL QUESTION:

### Is there anything creative you would use Datadog for?

I see some other applications for the datadog app. It could be used in online games for examples, like in popular esport games, who are live, multiplayer and statistic-intensive. It could mesure effectiveness of a player compared to the other, to the overall state of the game, and produce analytics to help coaches understand what are the best strategies, or which player struggles with it.

It could also be used, in a reduced version, as a way to determine the optimal settings for a game/application on a specific configuration, allowing a player to get the more of his/her computer to play in the best conditions, in running a few tests in the background or at first launch for exemple. Some driver/CG provider try to do that (NVIDIA GeForce Exp for exemple) with mixed results.

## CONCLUSION

Thank you for your attention, this project took me more time than expected, but I had fun discovering the Datadog App, which is very useful. I hope my submission will be appreciated, and that I've been explicit enough in the different exercises.

repository: JeFaisLeCafe/hiring-engineers

repo_name: JeFaisLeCafe/hiring-engineers


text:
---
lesson-example: "https://carpentries.github.io/lesson-example/"
layout: default
title: "Learning how to build websites with Jekyll"
---

## Description
{{ site.description }}

{% assign lead = site.team_members | where:"role", "project lead" | first %}
The project is lead by {{ lead.name }}.
[See our full team](about#team).

## About
More details about the project can be found in the [About](about.md) page.

Have any questions about what we do? [We'd love to hear from you!](mailto:{{ site.email }})

## Time
{{ site.time }}

See some [examples of our work]({{ page.lesson-example }})

{% include post_list.html %}

repository: aromanowski/group-website

repo_name: aromanowski/group-website


text:
# Outdated
I stopped developing this version due to it's limitations when using py2app and it being only useful for OSX. The appearance of PySimpleGUI has inspired me to remake this app as a completely standalone app with no need for connecting to a web server at all.

Check the new 2020 version here https://github.com/antonvino/preciousapp

# About
Precious Mac OS X app is the standalone part of the hour logging app that I've called Precious. It comes from a quote of a cool french guy who said to me once "I'm sorry but I work and my time is precious".
It is a side project that I'm working on to learn Python and also to help my discipline.
The hours are logged via this app. It is made with PyObjC wrappers using XCode to create the interface.
There is a web app that outputs the data that is pushed to it via this app. The web app is here: https://github.com/antonvino/precious_web

# How to contribute
Feel free to contribute to the app and do a pull request if you want to work on bugs or implement new features. I'm trying to keep the Mac OS X app minimal, so will not approve any fancy upgrades. Feel free to create your own app based on my code and if it works well we can figure out the syncing to the web side as well.

# py2app commands
Alias build:
python setup.py py2app -A

Launch to test:
dist/Precious.app/Contents/MacOS/Precious

Dist build:
python setup.py py2app


text:
#Change Log
This project adheres to [Semantic Versioning](http://semver.org/).

This CHANGELOG follows the format listed at [Keep A Changelog](http://keepachangelog.com/)

## [Unreleased]
- Enhaced history metrics: outputs all history metrics into a single measurement, adding subscribers and check name as tags

### Added
- Proxy_mode
- Basic auth authentication option.
- Filters
- Measurement templating mechanism
- Append check and client tags to metrics

### Fixed
- strip_key was not working

## 0.0.2 - 2017-05-18
### Added
- Add rubocop checks and fixes the code to pass them (@luisdavim)
- Add option to configure strip_metric from the check definition (@luisdavim)

## 0.0.1 - 2017-04-19
### Added
- Change sensu-influxdb-extension into a gem (@stevenviola)


text:
# @textile/testing

**Info**

This is not a supported developer library.
Do not use as a direct dependency in your projects.

**Install**

Only available within monorepo

**Usage**

```js
import { createUsername } from '@textile/testing'
```

[Read the docs](https://textileio.github.io/js-textile/).

repository: textileio/js-textile

gha_language: TypeScript

repo_name: textileio/js-textile


text:
# [![](./resources/icon-small.png)]() Leve1Up

## [ discontinued ]
This repo is not likely to get any more commitments.

## Leve1Up
**A Graphical User Interface for NoSQL ( CouchDB, LevelDB ) database management**

* Shows up in Modern Browsers (doesn't need atom-shell, etc.)
* Developed on top of NodeJs, ExpressJs, PouchDB ...

### Getting Started
Make sure NodeJs and NPM are installed (Requirements .)
Download this repository (git) and install it with dependencies (npm .)
*These steps depend on your OS. Debian  e.g.*
```
$ git clone https://github.com/mhgolkar/Leve1Up.git ~/Leve1Up
$ cd ~/Leve1Up
$ npm install
```
Now you can run it as a NodeJS app (Debian e.g.):
```
$ node ./main.js
```
or perhaps `$ node ~/Leve1Up/main.js` from any other working directory.

That's it all.
The Leve1Up server side will run ( by default on `http://localhost:1234` ) and salutes you in the terminal.
*Open the given address in your browser to use it.*
To change host, port  or any other settings, you can edit `configs.js` file.

[![](./resources/screenshot-editor.png)](#)

[![](./resources/screenshot-connection.png)](#)

#### Notes
* you can **turn off the server side** by sending any request to a path specified in `configs.js` ( by default browsing `http://localhost:1234/turn-off` does the job.)
* There is a very small **sample LevelDB database** in `./little_movie_db` shipped with the repository, which can be used locally to discover what Leve1Up can do.
* If the port `1234` is being used by another app or service, you'll get an error. Simply change the port as mentioned.
* It's generally safer to use absolute path for local dbs. A relative path is normally relative to the current working directory (the directory from which you invoked the node command).

Have a nice time .


text:
# Demo Program using the Python PubSub gRPC Client Library

## Usage
To use Cloud Pub/Sub, requires you to have authentication setup.
Refer to the [Authentication Getting Started Guide](https://cloud.google.com/docs/authentication/getting-started)
for instructions on setting up credentials.

If you have a service account you can configure on a environment:
```
export GOOGLE_APPLICATION_CREDENTIALS=path/to/your/service_account.json
```

To install in a virtual environment:
```
virtualenv .env
. .env/bin/activate
pip install -r requirements.txt
```

(Optional)To connect on a Pub/Sub emulator:
```
export PUBSUB_EMULATOR_HOST=<host>:<port>
```

## Publishing

Then, to publish to a Cloud PubSub topic, issue the following command where
**<project>** is the name of your GCP project, **<topic>** is the topic
you wish to publish to, **<data>** is the message content.

`python main.py <project> publish <topic> <data>`

## Subscribing

To Pull messages from a Cloud PubSub subscription, issue the following command
where **<project>** is the name of your GCP project, and **<subscription>** is
the subscription you wish to pull from.

`python main.py <project> subscribe <subscription>`

gha_language: Java


text:
# Vera-Plugin-RulesEngine

A rules engine for for [getVera](http://getvera.com/) Home Controller (VeraEdge, Vera3, VeraLite)

**Compatible with UI5 & UI7. Rules are editable only with [AltUI](http://forum.micasaverde.com/index.php/board,78.0.html)**

More informations here :
- http://forum.micasaverde.com/index.php/topic,34489.0.html

repository: digideskio/Vera-Plugin-RulesEngine

repo_name: digideskio/Vera-Plugin-RulesEngine


text:
# react-native-aws-freertos

React native aws freertos bridge

## Installation

```sh
npm install react-native-aws-freertos
cd ios && pod install
```
Open the ios project with xcode and run from there to a physical device, since npx react-native-run ios will open in the simulator and it wont connect to any bt device.

- Android
Add this to your manifest file under android/app/src/main/AndroidManifest.xml
```
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <!-- initiate device discovery and manipulate bluetooth settings -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <!-- allow scan BLE -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```

- IOS
Add this to your Podfile
```
  use_frameworks! :linkage => :static
  pod 'AmazonFreeRTOS'
  pod 'AWSAuthUI'
  pod 'AWSMobileClient','~> 2.17.0'
  pod 'AWSUserPoolsSignIn'
  pod 'react-native-aws-freertos', :path => '../node_modules/react-native-aws-freertos'
```

Make sure you add bt permissions keys to your Info.plist

	<key>NSBluetoothPeripheralUsageDescription</key>
	<string>The app needs access to Bluetooth</string>
	<key>NSBluetoothAlwaysUsageDescription</key>
	<string>We need to acces BLE to update the device</string>

## Usage

```js
import AwsFreertos from "react-native-aws-freertos";

// ...
AwsFreertos.getConnectedDeviceAvailableNetworks(deviceMacAddress);
const eventEmitter = new NativeEventEmitter(NativeModules.AwsFreertos);

const wifiListEvent = eventEmitter.addListener(
    eventKeys.DID_LIST_NETWORK,
    (network: WifiInfo) => {
      console.log(network)
    }
);
```

## Available methods
```ts
type AwsFreertosType = {
  startScanBtDevices(): void;
  stopScanBtDevices(): void;
  setAdvertisingServiceUUIDs(uuids: string[]): void;
  requestBtPermissions(): Promise<any>;
  connectDevice(macAddress: string): Promise<any>;
  disconnectDevice(macAddress: string): Promise<any>;
  disconnectNetworkOnConnectedDevice(macAddress: string, index: number): Promise<any>;
  saveNetworkOnConnectedDevice(
    macAddress: string,
    bssid: string,
    pw: string
  ): Promise<any>;
  getConnectedDeviceAvailableNetworks(macAddress: string): Promise<WifiInfo[]>;
  getConnectedDeviceSavedNetworks(macAddress: string): Promise<WifiInfo[]>;
  getGattCharacteristicsFromServer(
    macAddress: string,
    serviceUuidString: string
  ): void;
};
```

## Events
```js
export const events = {
  // Bluetooth events
  DID_UPDATE_BLE_POWER_STATE: 'DID_UPDATE_BLE_POWER_STATE',
  DID_DISCONNECT_DEVICE: 'DID_DISCONNECT_DEVICE',
  DID_DISCOVERED_DEVICE: 'DID_DISCOVERED_DEVICE',
  DID_CONNECT_DEVICE: 'DID_CONNECT_DEVICE',
  DID_FAIL_TO_CONNECT_DEVICE: 'DID_FAIL_TO_CONNECT_DEVICE',
  DID_READ_CHARACTERISTIC_FROM_SERVICE: 'DID_READ_CHARACTERISTIC_FROM_SERVICE',

  // Wifi events of paired up device
  DID_LIST_NETWORK: 'DID_LIST_NETWORK',
  DID_SAVE_NETWORK: 'DID_SAVE_NETWORK',
  ERROR_SAVE_NETWORK: 'ERROR_SAVE_NETWORK',
  DID_EDIT_NETWORK: 'DID_EDIT_NETWORK',
  DID_DELETE_NETWORK: 'DID_DELETE_NETWORK',
};
```

## Contributing

See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.

## License

MIT


text:
Debugging:
  I used the following two links to help set up debugging on a jailbroken iOS 10.1 device.
  https://kov4l3nko.github.io/blog/2016-04-27-debugging-ios-binaries-with-lldb/
  https://blog.securityevaluators.com/debugging-ios-applications-a-guide-to-debug-other-developers-apps-c041311498eb

My current test set of daemons is from iOS 10.1, but I can easily change this by modifying the version number in:
runBaseIDAAnalysisOnAllExecsWithSelectorString.sh
We will eventually need to run our scripts on iOS 11 or whatever version we use class-dump on to extract our nsxpc protocols.


text:
## 4.2.0
  - Fix incorrect parsing in some cases
  - fix validate length as it was incorrectly validating with pattern

## 4.1.0
  - only modify national number to its international version when it is valid
  - resolve issue where phone number were incorrectly parsed if national number started with country code (it happens)

## 4.0.1

  - reexport deprecated public api for backward comp

## 4.0.0 Consolidating Public API

This release removes the LightPhoneParser because it was not working perfectly and the cost of maintaining
two parsers is too high.

Removing that parser allowed to revert to a more succint public API, where methods should be accessed
solely via the PhoneNumber class.

PhoneParser,  PhoneNumberFormatter and the likes are still exported for backward compatibility but it is advised
to switch to PhoneNumber's methods instead

- [Breaking]: LightPhoneParser has been removed as it was imperfect and added complexity in maintaining two parsers.
- [Deprecated]: PhoneParser methods have been deprecated in favor of the methods on PhoneNumber class

## 3.0.2
- fix formatter error when empty input

## 3.0.1
- added [parseNational]

## 3.0.0
- added localized formatter to format a phone number in an human readable way
- added PhoneNumberRanges and utility operators on PhoneNumber (thanks @bsutton)
- renamed [dialCode] to [countryCode] as dialCode was semantically incorrect

## 2.0.1
- rename base class for parsers to BasePhoneParser, as parser was too broad.
- export BasePhoneParser

## 2.0.0
- Resolve issue #1 where it was possible to significantly increase memory foothprint by importing both parsers. Thanks @xvrh
- Deplaced validate method from PhoneNumber to PhoneParser and LightPhoneParser to
  make it more obvious that one is
- Light parser can now parseWithDialCode and parseRaw, although less accurate than the full parser

## 1.0.5
- Minor doc change

## 1.0.4
- Added metadata property runtime type to toString to make it more obvious when two instances are not equals

## 1.0.3
- Made toString more readable

## 1.0.2
- Add toString to PhoneNumber

## 1.0.1
- validate method on PhoneNumber

## 1.0.0
- There are now two parsers:
   - PhoneParser: Heavy, more accurate and more computationally intensive (relies on pattern matching)
   - LightPhoneParser: Light, somewhat accurate and less computationally intensive (relies on length)
   If a light validation based on length suffice, LightPhoneParser can be used, assuming you don't import
   the other parser, that will decrease the library size footprint.

  With this change a few breaking changes had to be made
- [Breaking]: PhoneNumber creation is now made with parsers:

  before:
  ```dart
  final frPhone = PhoneNumber.fromRaw('+33 655 5705 76');
  final frPhone1 = PhoneNumber.fromIsoCode('FR', '655 5705 76');
  ```

  after:
  ```dart
  final frPhone = PhoneParser.fromRaw('+33 655 5705 76')
  final frPhone1 = LightPhoneParser.fromIsoCode('FR', '655 5705 76');
  ```

- [Breaking]: removed country class and country list, which are now in a separate library

## 0.2.0
* extracted country data files to another library dart_countries as it can be used in other scenarios
* [Breaking]: Country.getDisplayDialCode is now a getter Country.displayIsoCode.

## 0.1.4
* upgrade dependencies

## 0.1.3
* deprecate valid property on phone number
* make phone number type in validate method nullable to validate against general type

## 0.1.2
* rename example so it shows in pub.dev

## 0.1.1
* Add example

## 0.1.0

- fix substantial bug where validity would be true for longer numbers
- added validity check on phone number to further check validity for a given phone number type (mobile, fixedLine)
- added more tests

## 0.0.5

- Breaking: remove getters for leading digits as it sometimes contains patterns
- Put space in American Samoa's name

## 0.0.4

- changed displayDialCode getter into method to allow for different syntax

## 0.0.3

- added toString to PhoneNumber
- added leading digits getter to country
- added displayDialCode on country which is a mix of country code and leading digits
- added copyWithIsoCode as instance method on phone number to make it
  easy to switch between countries in a phone number input
- added toString to exception

## 0.0.2

- added some doc, by Cedvdb

## 0.0.1

- Initial version, created by Cedvdb


text:
---
title: "Episode #3 - From Foragers to Farmers"
layout: post
permalink: "from-foragers-to-farmers"
date: 2016-04-26 7:00
tag:
- episode
- previkingage
- vikingagepod
blog: true
---

## From Foragers to Farmers

Hello, my name is Lee and this is Episode #3 - From Foragers to Farmers!

In this episode we explore the transition from Hunting and Gathering to Agriculture in Scandinavia. Along the way we encounter conflicting hypotheses, meager evidence and a story about Status and Reputation.

The Agricultural revolution has been called the most important invention in Human history, so it feels only fair that we spend an episode exploring the potential causes in Scandinavia.

For all this and more, checkout the episode below, or subscribe on iTunes. Happy listening :)

<iframe style="border: none" src="//html5-player.libsyn.com/embed/episode/id/4320366/height/360/width/640/theme/standard/autoplay/no/autonext/no/thumbnail/yes/preload/no/no_addthis/no/direction/backward/no-cache/true/" height="360" width="640" scrolling="no"  allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>

## Like what you hear?
If you like this episode you could do a huge solid for all of us here at the Viking Age Podcast and spread the word on social media with the links below!

extension: markdown


text:
---
topic: "Rational: ex09"
desc: "== vs. .equals, hashCode()"
indent: true
code_repo: https://github.com/UCSB-CS56-pconrad/cs56-rational-ex09
p86 : 4dot-methods-use-instance-variables-how-objects-behave/comparing_variables_open_parenthesis_pri
---

On website: https://ucsb-cs56-pconrad.github.io/tutorials/rational_ex09/

Part of a [series of tutorial articles about a Rational class](/tutorials/rational/).

{% include code_examples.md %}

# == vs .equals, and hashCode()

The next part of this tutorial concerns the difference between `==` and `.equals` and the implementation of the hashCode() function.

Please first, read through the following:

* [== vs .equals, and hashCode()](/topics/java_double_equals_vs_dot_equals/)
* p. 86 in Chapter 4 of Head First Java, 2nd Edition
  [on-campus]({{site.on_campus}}/{{site.hfj_url}}/{{page.p86}})
  [off-campus]({{site.off_campus}}/{{site.hfj_url}}/{{page.p86}})

The big picture take away is that we need to implement `.equals()` and `.hashCode()` properly for each class
we implement.

Here's a way to do it.

# First, we write tests

That's the essence of test-driven development.  Always start with your tests

Here are some tests for the .equals() method from the file `RationalTest.java`.

In coming up with these tests, we mostly make tests that we expect to be true
(and which fail when the `.equals()` method is still implementing `==`).

However, it is helpful to add *at least one test* where we expect
.equals() to return false.  Otherwise, simply writing a version of
`.equals()` that would return `true`, *always*, would satisfy the
tests.  That would be bad.

```java
    @Test
    public void test_equals_1() {
	Rational a = new Rational(2,3);
	Rational b = new Rational(2,3);
	assertTrue(a.equals(b));
    }

    @Test
    public void test_equals_2() {
	Rational a = new Rational(2,3);
	Rational b = new Rational(-2,-3);
	assertTrue(a.equals(b));
    }

    @Test
    public void test_equals_3() {
	Rational a = new Rational(1,3);
	Rational b = new Rational(3,9);
	assertTrue(a.equals(b));
    }

    @Test
    public void test_equals_4() {
	Rational a = new Rational(-1,3);
	Rational b = new Rational(1,-3);
	assertTrue(a.equals(b));
    }

    @Test
    public void test_equals_5() {
	Rational a = new Rational(2,3);
	Rational b = new Rational(4,5);
	assertFalse(a.equals(b));
    }

```

Here are some tests for the .hashCode() method from the file `RationalTest.java`.

Here, you might notice that we only wrote tests where we expect the hashCode values returned to be equal.

It is a bit tougher to write a test where we should guarantee that the hashCode values should *not* be equal.  In fact, arguably, we cannot do that without knowing details about how the hashCode should be implemented, since there is no guarantee in the contract of `hashCode()` that unequal values will have unequal `hashCode()` values.

It is important to keep in mind that the extent of our testing is an "engineering design decision", a "tradeoff", not something where we aim for "perfection".  Don't get so bogged down in the quest for test perfection that you burn out on testing and fail to do any testing at all.

```java
    @Test
    public void test_hashCode_1() {
	Rational a = new Rational(2,3);
	Rational b = new Rational(2,3);
	assertTrue(a.hashCode()==b.hashCode());
    }

    @Test
    public void test_hashCode_2() {
	Rational a = new Rational(2,3);
	Rational b = new Rational(-2,-3);
	assertTrue(a.hashCode()==b.hashCode());
    }

    @Test
    public void test_hashCode_3() {
	Rational a = new Rational(1,3);
	Rational b = new Rational(3,9);
	assertTrue(a.hashCode()==b.hashCode());
    }

    @Test
    public void test_hashCode_4() {
	Rational a = new Rational(-1,3);
	Rational b = new Rational(1,-3);
	assertTrue(a.hashCode()==b.hashCode());
    }
```

With these tests in place, we run, initially *without* adding an overridden `equals()` and `hashCode()` method, and we see that we have only eight test failures.  That's to be expected, since `test_equals_5()` is likely to "pass", though for the "wrong reason" .

```
UCSB-CS56-pconrad/UCSB-CS56-pconrad.github.io/_tutorials/rational_ex09.md
Phillips-Mac-mini:cs56-rational-ex09 pconrad$ ant test
Buildfile: /Users/pconrad/github/UCSB-CS56-pconrad/cs56-rational-ex09/build.xml

compile:

test:
    [junit] Testsuite: RationalTest
    [junit] Tests run: 34, Failures: 8, Errors: 0, Skipped: 0, Time elapsed: 0.043 sec
    [junit]
    [junit] Testcase: test_equals_1(RationalTest):	FAILED
    [junit]
    [junit] junit.framework.AssertionFailedError:
    [junit]	at RationalTest.test_equals_1(RationalTest.java:170)
    [junit]
    [junit]
    [junit] Testcase: test_equals_2(RationalTest):	FAILED
    [junit]
    [junit] junit.framework.AssertionFailedError:
    [junit]	at RationalTest.test_equals_2(RationalTest.java:177)
    [junit]
    [junit]
    [junit] Testcase: test_equals_3(RationalTest):	FAILED
    [junit]
    [junit] junit.framework.AssertionFailedError:
    [junit]	at RationalTest.test_equals_3(RationalTest.java:185)
    [junit]
    [junit]
    [junit] Testcase: test_equals_4(RationalTest):	FAILED
    [junit]
    [junit] junit.framework.AssertionFailedError:
    [junit]	at RationalTest.test_equals_4(RationalTest.java:193)
    [junit]
    [junit]
    [junit] Testcase: test_hashCode_1(RationalTest):	FAILED
    [junit]
    [junit] junit.framework.AssertionFailedError:
    [junit]	at RationalTest.test_hashCode_1(RationalTest.java:208)
    [junit]
    [junit]
    [junit] Testcase: test_hashCode_2(RationalTest):	FAILED
    [junit]
    [junit] junit.framework.AssertionFailedError:
    [junit]	at RationalTest.test_hashCode_2(RationalTest.java:215)
    [junit]
    [junit]
    [junit] Testcase: test_hashCode_3(RationalTest):	FAILED
    [junit]
    [junit] junit.framework.AssertionFailedError:
    [junit]	at RationalTest.test_hashCode_3(RationalTest.java:223)
    [junit]
    [junit]
    [junit] Testcase: test_hashCode_4(RationalTest):	FAILED
    [junit]
    [junit] junit.framework.AssertionFailedError:
    [junit]	at RationalTest.test_hashCode_4(RationalTest.java:231)
    [junit]
    [junit]
    [junit] Test RationalTest FAILED

BUILD SUCCESSFUL
Total time: 0 seconds
Phillips-Mac-mini:cs56-rational-ex09 pconrad$
```

So, now let's try to write some code so that our tests pass.

First an implementation of .equals().  This is the easy part.

For the most part, checking whether `this` instance of `Rational`
is equal to some other object is a matter of checking whether this numerators
are equal and the denominators are equal.    This, of course, depends
on two assumptions, namely that:

* (a) our constructor is taking care of reducing fractions, and normalizing where the minus sign goes (always in the numerator), and
* (b) that our Rational object is immutable

Also, there is a bit of "boiler plate code" that we always need for a
.equals method to take care of the fact that:

* (a) the parameter is of type Object, meaning we can pass in literally *any* kind of java reference, even one to some other class.
* (b) the parameter could be null, and we need to make sure we don't end up throwing a `NullPointerException` in that case.

So, here's the final method, boilerplate and all:

```java
    /**
	return true if and only if numerators and denominators are equal
     */
    @Override
    public boolean equals(Object o) {

	// Start: boilerplate code for .equals

	if (this == o) return true;
	if (o == null) return false;
	if (getClass() != o.getClass()) return false;
	Rational r = (Rational) o;

	// End boilerplate

	return this.num == r.num && this.denom == r.denom;
    }
```

Note that the line of boilerplate code that reads

```java
  if (getClass() != o.getClass()) return false;
```

Used to be written this way prior to Java 7:

```
  if (! o instanceof Rational) return false;
```

The new syntax is supposedly more efficient, and also avoids having to
mention the class by name, making it easier to copy and paste the boilerplate
from one function to another.    The class name still appears on the next line
of boilerplate code though, where we have a typecast to convert the parameter
`o` to a Rational.

```
   Rational r = (Rational) o;
```

# Implementing `hashCode`

We have a bit of a dilemma here.  The space of hashCodes is the space of the
type `int`.   The number of values we have is twice as big.

If we use either numerator alone, or denonminator alone, we are likely to
get quite a few hash collisions.

* One might expect that when working with rationals, we might be working with a set of numbers that contains 1/7, 3/7, 22/7, etc, so hashing based on denominator alone is probably not a good idea.

* Similarly, if we are working with a set of numbers 1/2, 1/3, 1/4, 1/5, etc. we would not want to use numerator alone to hash.

It might be tempting to simply use a bitwise xor to combine the values together.  This ignores the fact, though, that might expect, for many applications, that the numerator and denominator would be more likely to be small integers than large integers.   To use the bits wisely, we might do better to take the least significant bits from both numerator and denominator, and combine them together.

So, here is a function that does that.

```java
    /**
       hashCode for Rational class.  Concatenate least significant
       16 bits of the 32 bit int values for num and denom.

       Can you think of cases where this might be a poor choice?
       Can you think of a better choice?
     */

    @Override
    public int hashCode() {
	int numLowerBitsOnly   = this.num   & 0x0000FFFF;
	int denomLowerBitsOnly = this.denom & 0x0000FFFF;
	return (numLowerBitsOnly << 16) | denomLowerBitsOnly;
    }

```

We've also added some code into our main to illustrate what is happening.

```java
    /**
	For testing getters.
	@param args unused
     */

    public static void main (String [] args) {
	Rational r = new Rational(5,7);
	System.out.println("r.getNumerator()=" + r.getNumerator());
	System.out.println("r.getDenominator()=" + r.getDenominator());
	System.out.println("Integer.toHexString(r.hashCode())=" +
			   Integer.toHexString(r.hashCode()));
	Rational r2 = new Rational(0x01234567,0x89ABCDEF);
	System.out.println("Integer.toHexString(r2.getNumerator())=" +
			   Integer.toHexString(r2.getNumerator()));
	System.out.println("Integer.toHexString(r2.getDenominator())=" +
			   Integer.toHexString(r2.getDenominator()));
	System.out.println("Integer.toHexString(r2.hashCode())=" +
			   Integer.toHexString(r2.hashCode()));

	Rational r3 = new Rational(0x89ABCDEF,0x01234567);
	System.out.println("Integer.toHexString(r3.getNumerator())=" +
			   Integer.toHexString(r3.getNumerator()));
	System.out.println("Integer.toHexString(r3.getDenominator())=" +
			   Integer.toHexString(r3.getDenominator()));
	System.out.println("Integer.toHexString(r3.hashCode())=" +
			   Integer.toHexString(r3.hashCode()));
    }

```

Here's a run of that code:

```
Phillips-Mac-mini:cs56-rational-ex09 pconrad$ ant run
Buildfile: /Users/pconrad/github/UCSB-CS56-pconrad/cs56-rational-ex09/build.xml

run:
    [java] r.getNumerator()=5
    [java] r.getDenominator()=7
    [java] Integer.toHexString(r.hashCode())=50007
    [java] Integer.toHexString(r2.getNumerator())=1234567
    [java] Integer.toHexString(r2.getDenominator())=89abcdef
    [java] Integer.toHexString(r2.hashCode())=4567cdef
    [java] Integer.toHexString(r3.getNumerator())=89abcdef
    [java] Integer.toHexString(r3.getDenominator())=1234567
    [java] Integer.toHexString(r3.hashCode())=cdef4567

BUILD SUCCESSFUL
Total time: 0 seconds
Phillips-Mac-mini:cs56-rational-ex09 pconrad$
```

gha_language: Ruby