text:
# Spring Boot Thymeleaf Starter

Starter project based on Spring Boot and Thymeleaf.

## Tech Stack

| Component | Tech |
| --- | --- |
| Build & Deploy | [Gradle](https://gradle.org/), [Docker](https://www.docker.com/), [Docker Compose](https://docs.docker.com/compose/), [AWS Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/) |
| Languages | [Kotlin](https://kotlinlang.org/), [Java](https://www.java.com/), [HTML](https://www.w3schools.com/html/), [CSS](https://www.w3schools.com/css/), [JavaScript](https://www.javascript.com/) |
| Frameworks | [Spring Boot](http://spring.io/projects/spring-boot), [Thymeleaf](https://www.thymeleaf.org/), [Bootstrap](https://getbootstrap.com/) |
| Databases | [MySQL](https://www.mysql.com/), [H2](http://www.h2database.com/), [Flyway](https://flywaydb.org) |

## File Structure

The overall file structure is as follows:

```text
thymeleaf-starter/
├── .elasticbeanstalk/
│   └── config.yml
├── ebextensions/
│   └── *.config
├── gradle/wrapper/
│   └── gradle.*.[jar|properties]
├── flyway/
│   ├── credentials/
│   |   └── local.pass
│   └── local.conf
├── src/main/
│   ├── kotlin/
│   |   └── com/jahnelgroup/
│   |       └── *.[kt|java]
│   └── resources/
│       ├── db/
│       |   ├── devdata/*.sql
│       |   └── migration/*.sql
│       ├── static/
│       |   └── *.[css|images|js]
│       ├── templates/
│       |   └── *.html
│       └── application.[properties|yml]
├── src/test/
│   └── (testing framework)
├── Dockerfile
├── build.gradle
├── docker-compose.full.yml
├── docker-compose.yml
└── settings.gradle
```

## Getting Started

Gradle is the build and dependency management tool used by this service. Most actions can be accomplished through Gradle tasks described in the sections below. Most of the requirements needed will be provided through Gradle but you'll still need to install Gradle itself. I suggest using [SDKMAN!](https://sdkman.io/install) because it's referenced in the [Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-installing-spring-boot.html#getting-started-sdkman-cli-installation) or use any equivalent tool of your choosing.

### SDKMAN!

If you've opted for SDKMAN! after [installing it](https://sdkman.io/install) then proceed with these installations as well.

```bash
$ sdk install gradle
$ sdk install java
```

### Gradle

Gradle commands can be run one at a time like `gradle clean` as well as combined like `gradle clean build`. Here is a cheat sheet for important Gradle tasks.

#### List Tasks

| Command | Description |
| --- | --- |
| gradle tasks | List all tasks |

#### Clean/Test/Build

| Command | Description |
| --- | --- |
| gradle clean build | Deletes build artifacts and runs a fresh build. |
| gradle test  | Run tests. |

#### How does Gradle build the Spring Boot JAR?

If you inspect the [build.gradle](build.gradle) file you'll notice plugins related to Spring. These will effectively run a normal build process but with further processing to make the JAR executable. Read more about this process [Appendix E. The Executable Jar Format](https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html).

The only difference in this starter is the addition of the [.ebextensions](.ebextensions) directory for Elastic Beanstalk support. Review the `bootJar` task definition in [build.gradle](build.gradle) for how this is accomplished.

![gradleBuild.png](docs/diagrams/gradleBuild.png)

To start this application from the command line:

```bash
$ java -jar build/libs/app.jar
...
2019-04-25 20:27:58.558  INFO 1 --- [           main] com.jahnelgroup.App                   : Started App in 27.344 seconds (JVM running for 28.325)
```

### Docker

[Docker](https://en.wikipedia.org/wiki/Docker_(software)) is a computer program that performs operating-system-level virtualization, also known as "containerization". It makes the installation and management of software easier to handle. Docker can assist in the local development process by making it easy to start dependencies like your database.

Follow these steps for [installing docker](https://docs.docker.com/install/) and [installing docker-compose](https://docs.docker.com/compose/install/). This application also leverages two Gradle plugin's to assist with working with docker. [palantir/gradle-docker](https://github.com/palantir/gradle-docker) is used to build the image from the [Dockerfile](./Dockerfile) and [avast/gradle-docker-compose-plugin](https://github.com/avast/gradle-docker-compose-plugin) is used to help start/stop the stacks described in [docker-compose.yml](./docker-compose.yml) and other compose files.

| Command | Description |
| --- | --- |
| gradle clean build docker | Clean, fresh build, then build docker image. |
| gradle fullComposeUp | Start everything including the app (must have built the container first) |
| gradle fullComposeDown | ^ Stops the full stack |
| gradle depsComposeUp | Start only the app dependencies |
| gradle depsComposeDown | ^ Stops the dependency stack |

All of these tasks have their origins as pure docker commands but bringing them into the Gradle ecosystem allows for a more uniform experience. Additionally it provides a platform for more interesting task combinations in the future.

#### How does Gradle build the docker container?

This application uses the [palantir/gradle-docker](https://github.com/palantir/gradle-docker) Gradle plugin for building docker images. The library is powerful but we're just using it as a wrapping around invoking the [Dockerfile](Dockerfile). The architecture of this process was taken from the [Spring Boot with Docker](https://spring.io/guides/gs/spring-boot-docker/) guide.

![gradleDocker.png](docs/diagrams/gradleDocker.png)

#### Docker for Local Development

When you're actively developing an application it's useful to be able to run it from within an IDE. You can launch only the dependencies in docker containers leaving it up to you for how you'd like to launch the app, preferably from something like IntellIJ where it's easy to debug.

Run only the dependencies (i.e., just the database) in docker with `gradle depsComposeUp`.

![gradleDepsComposeUp.png](docs/diagrams/gradleDepsComposeUp.png)

Then to stop the dependencies stack run `gradle depsComposeDown`.

Sometimes you just want to launch the entire stack locally without an IDE, perhaps a demo or showcase. You can do this with a variation of compose by running `gradle fullComposeUp`.

![gradleFullComposeUp.png](docs/diagrams/gradleFullComposeUp.png)

Then to stop the full stack run `gradle fullComposeDown`.

#### Native Docker Commands

Refer to the [Docker Documentation](https://docs.docker.com/) for a detailed treatment on the available commands. Please note that you should use the Gradle docker plugin commands shown above for building the image.

Show here are a few native common commands that you'll still need.

List your docker images:

```bash
$ docker images
REPOSITORY                                          TAG                 IMAGE ID            CREATED             SIZE
com.jahnelgroup/thymeleaf-starter                   latest              b86ac0cb2daa        25 minutes ago      151MB
```

List your running containers:

```bash
$ docker ps -a
CONTAINER ID        IMAGE                              COMMAND                  CREATED             STATUS              PORTS                               NAMES
0383023e5aea        mysql:8                                    "docker-entrypoint..."   25 minutes ago      Up 25 minutes       <IP_ADDRESS>:3306->3306/tcp, 33060/tcp   db
557a8d58bb70        adminer:4                                  "entrypoint.sh doc..."   25 minutes ago      Up 25 minutes       <IP_ADDRESS>:8081->8080/tcp              adminer
165f4026652c        com.jahnelgroup/thymeleaf-starter:latest   "/bin/sh -c 'exec ..."   25 minutes ago      Up 25 minutes       <IP_ADDRESS>:8080->8080/tcp              thymeleaf-starter
```

Tail the logs of a particular container:

```bash
$ docker logs -f thymeleaf-starter
...
2019-04-25 20:27:58.556  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-25 20:27:58.558  INFO 1 --- [           main] com.jahnelgroup.App                      : Started App in 27.344 seconds (JVM running for 28.325)
```

### Flyway

[Flyway](https://flywaydb.org) is an open-source database migration tool. It strongly favors simplicity and convention over configuration. It is based around just a few basic commands that help you with the iterative development of a database. Being a Spring application it's very natural for us to leverage JPA/Hibernate for data persistence but it is important to note that **Hibernate is not generating the DDL for us and rather we create them manually by hand** and are they located in [src/main/resources/db/migration](./src/main/resources/db/migration). The properties that disable Hibernate DDL generation are located in [src/main/resources/application.yml](./src/main/resources/application.yml).

| Command | Description |
| --- | --- |
| gradle [flywayMigrate](https://flywaydb.org/documentation/gradle/migrate) | Migrates the database |
| gradle [flywayClean](https://flywaydb.org/documentation/gradle/clean) | Drops all objects in the configured schemas |
| gradle [flywayInfo](https://flywaydb.org/documentation/gradle/info) | Prints the details and status information about all the migrations |
| gradle [flywayValidate](https://flywaydb.org/documentation/gradle/validate) | Validates the applied migrations against the ones available on the classpath |
| gradle [flywayBaseline](https://flywaydb.org/documentation/gradle/baseline) | Baselines an existing database, excluding all migrations up to and including baselineVersion |
| gradle [flywayRepair](https://flywaydb.org/documentation/gradle/repair) | Repairs the schema history table |

By default these Flyway commands are pointing to the local instance per the configuration found in `build.gradle`.

```groovy
flyway {
	configFiles = [
		'flyway/local.conf', 'flyway/credentials/local.pass'
	]
}
```

#### Database Seed Data

If you need seed data it can easily be separated out from the Flyway DDL migrations by specifying it as an additional Flyway location. For example you can leverage Flyway callbacks to run the seed data as described in this article [How to create database test data for Spring Boot applications with Flyway DB](https://medium.com/@jonashavers/how-to-create-database-test-data-for-spring-boot-applications-with-flyway-db-294a436db7ee). It's important to note that the seed data must be idempotent, more specifically it should not produce errors if run multiple times. An example of this is to use `insert ignore into` as opposed to `insert into`.

To leverage this simply create more folders under the src/main/resources/db folder. Using Spring Profiles change the list of migrations to reflect the way you want to seed environments differently.

```text
src/main/
└── resources/
    ├── db/
    |   ├── devdata/*.sql
    |   └── migration/*.sql
```

#### Running Flyway against a remote database.

This application will use an embedded Flyway dependency to automatically migrate your database upon startup. However, sometimes you'll still want to inspect the Flyway status of a database yourself. In order to do this you'll use a Gradle Flyway plugin from the command line.

You'll need two configuration files in place to achieve this - one for the database URL and location of migrations, and the other for the database credentials. **You will not commit the database credentials file to version control because it will be ignored by .gitignore**.

Here is the base structure of the [flyway](./flyway) directory.

```text
thymeleaf-starter/
└── flyway/
    ├── credentials/
    |   ├── .gitignore    // this will ignore your other *.pass files
    |   └── local.pass
    └── local.conf
```

Now let's add the ability to connect to a remote database by adding two additional files.

```text
thymeleaf-starter/
└── flyway/
    ├── credentials/
    |   ├── .gitignore
    |   ├── aws-dev.pass   // secret credentials
    |   └── local.pass
    ├── aws-dev.conf       // db url and migrations
    └── local.conf
```

Here would be the contents of these files, replace the variables with your own values:

**flyway/aws-dev.conf**
```text
flyway.url=jdbc:mysql://${DB_URL}:${DB_PORT}/${DB_SCHEMA}?useSSL=false
flyway.locations=classpath:db/migration
```

**flyway/credentials/dev.pass**
```text
flyway.user=${DB_USER}
flyway.password=${DB_PASS}
```

To run the Gradle Flyway plugin commands against this database pass this argument in:

```bash
$ gradle -Dflyway.configFiles=flyway/aws-dev.conf,flyway/credentials/aws-dev.pass flywayInfo
```

**Note:** If you're running this against a remote environment behind a Firewall (i.e., AWS) you'll need to expose the port and whitelist your IP address to have access to it.

### HTTP/REST Testing Tools

Here are a few useful HTTP testing tools:

* [curl](https://curl.haxx.se/docs/manpage.html)
* [HTTPie](https://httpie.org/)
* [Postman](https://www.getpostman.com/)

## Quick Start - Run Locally

Ensure you have Gradle, Java, and Docker installed based on the instructure above. Invoke the `gradle fullComposeUp` command to initiate the entire which includes the application and the database.

```
$ gradle fullComposeUp

> Task :fullComposeUp
adminer uses an image, skipping
db uses an image, skipping
app uses an image, skipping
Creating network "e786c2c2a0474a08129fcf4561ff7928_thymeleaf-starter_full_frontend" with the default driver
Creating network "e786c2c2a0474a08129fcf4561ff7928_thymeleaf-starter_full_backend" with the default driver
Creating thymeleaf-starter ...
Creating db                ...
Creating e786c2c2a0474a08129fcf4561ff7928_thymeleaf-starter_full_adminer_1_5beb9ccaa3e6 ...
Creating thymeleaf-starter                                                              ... done
Creating e786c2c2a0474a08129fcf4561ff7928_thymeleaf-starter_full_adminer_1_5beb9ccaa3e6 ... done
Creating db                                                                             ... done
Will use <IP_ADDRESS> (network e786c2c2a0474a08129fcf4561ff7928_thymeleaf-starter_full_backend) as host of adminer
Will use <IP_ADDRESS> (network e786c2c2a0474a08129fcf4561ff7928_thymeleaf-starter_full_backend) as host of app
Will use <IP_ADDRESS> (network e786c2c2a0474a08129fcf4561ff7928_thymeleaf-starter_full_backend) as host of db
Probing TCP socket on <IP_ADDRESS>:8081 of service 'adminer_1'
TCP socket on <IP_ADDRESS>:8081 of service 'adminer_1' is ready
Probing TCP socket on <IP_ADDRESS>:8080 of service 'thymeleaf-starter'
Waiting for TCP socket on <IP_ADDRESS>:8080 of service 'thymeleaf-starter' (Connection refused (Connection refused))
Waiting for TCP socket on <IP_ADDRESS>:8080 of service 'thymeleaf-starter' (Connection refused (Connection refused))
Waiting for TCP socket on <IP_ADDRESS>:8080 of service 'thymeleaf-starter' (Connection refused (Connection refused))
TCP socket on <IP_ADDRESS>:8080 of service 'thymeleaf-starter' is ready
Probing TCP socket on <IP_ADDRESS>:3306 of service 'db'
TCP socket on <IP_ADDRESS>:3306 of service 'db' is ready

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 50s
12 actionable tasks: 9 executed, 3 up-to-date

```

Verify that the docker image was generated:

```bash
$ docker images
REPOSITORY                                          TAG                 IMAGE ID            CREATED              SIZE
com.jahnelgroup/thymeleaf-starter                   latest              b18d953e2ff5        About a minute ago   151MB
```

Verify that the docker containers are running:

```bash
$ docker ps -a
CONTAINER ID        IMAGE                              COMMAND                  CREATED             STATUS              PORTS                               NAMES
0383023e5aea        mysql:8                                    "docker-entrypoint..."   25 minutes ago      Up 25 minutes       <IP_ADDRESS>:3306->3306/tcp, 33060/tcp   db
557a8d58bb70        adminer:4                                  "entrypoint.sh doc..."   25 minutes ago      Up 25 minutes       <IP_ADDRESS>:8081->8080/tcp              adminer
165f4026652c        com.jahnelgroup/thymeleaf-starter:latest   "/bin/sh -c 'exec ..."   25 minutes ago      Up 25 minutes       <IP_ADDRESS>:8080->8080/tcp              thymeleaf-starter
```

Connect the MySQL database and verify that the schema and tables were created _(root/rootpassword)_:

```bash
$ mysql -uroot -p -h<IP_ADDRESS>
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.14 MySQL Community Server - GPL

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| jg_starter         |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> use jg_starter;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+------------------------+
| Tables_in_jg_starter   |
+------------------------+
| authorities            |
| flyway_schema_history  |
| task_lists             |
| tasks                  |
| user_group_authorities |
| user_group_members     |
| user_groups            |
| users                  |
+------------------------+
8 rows in set (0.00 sec)
```

Navigate to http://localhost:8080 and login with _steven / pass_.

## AWS Elastic Beanstalk

[AWS Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/) is an easy-to-use service for deploying and scaling web applications and services developed with various technologies like Java and Docker.

### AWS/EB Command Line Setup

The [EB CLI](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3.html) is a command line interface for Elastic Beanstalk that provides interactive commands that simplify creating, updating and monitoring environments from a local repository. Use the EB CLI as part of your everyday development and testing cycle as an alternative to the AWS Management Console.

To use AWS Elastic Beanstalk you must have:

* An aws account with an *aws_access_key_id* and *aws_access_key_id*
* Your account must be privileged enough to use the Elastic Beanstalk service
* You must have installed and configured the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)
* You must have installed and configured the [AWS Elastic Beanstalk CLI](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3.html)

If you're using multiple AWS accounts it's helpful to manage them with [named profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html).

**~/.aws/credentials**

```bash
[jahnelgroup]
aws_access_key_id=YOUR_KEY
aws_secret_access_key=YOUR_SECRET
```

**~/.aws/config**

```bash
[profile jahnelgroup]
region = us-east-1
output = json
role_arn = arn:aws:iam::<your_account_id>:role/<your_role>
source_profile = jahnelgroup
```

Validate that you're configured correctly by checking your identity with the named profile:

```bash
$ aws sts get-caller-identity --profile jahnelgroup
{
    "Account": "<your_account_id>",
    "UserId": "<your_user_id>",
    "Arn": "<your_arn>"
}
```

Type `eb` to make sure it's installed:

```bash
$ eb
usage: eb (sub-commands ...) [options ...] {arguments ...}
...
```

### AWS/EB Configuration Files (ebextensions)

We can use [ebextensions](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions-optionsettings.html) to advise Elasitc Beanstalk on how to create an environment. You can have an arbitrary number of config files, here we've broken them up base on resource type and one for the environment variables.

```text
thymeleaf-starter/
├── .elasticbeanstalk/
│   └── config.yml
├── ebextensions/
    ├── db-instance-options.config
    ├── ec2-instance-options.config
    └── env.config
```

### Creating an AWS/EB Environment

Make sure that you're using the named profile of **--profile jahnelgroup** or whatever you decided to call it. Read about the [eb create](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-create.html) to become familiar with it's options.

Make sure your application is built with the latest with `gradle clean build`.

```bash
$ gradle clean build
$ eb create --database
Enter Environment Name
(default is thymeleaf-starter-dev):
Enter DNS CNAME prefix
(default is thymeleaf-starter-dev):

Enter an RDS DB username (default is "ebroot"):
Enter an RDS DB master password:
Retype password to confirm:
2019-02-22 21:14:33    INFO    createEnvironment is starting.
2019-02-22 21:14:34    INFO    Using elasticbeanstalk-us-east-1-12321471834 as Amazon S3 storage bucket for environment data.
2019-02-22 21:14:59    INFO    Created security group named: awseb-e-fa2fszffed-stack-AWSEBSecurityGroup-13R271AAHRC7J
2019-02-22 21:15:15    INFO    Created EIP: <IP_ADDRESS>
2019-02-22 21:15:15    INFO    Creating RDS database named: bb2czfhgfe6e1pzu. This may take a few minutes.
 -- Events -- (safe to Ctrl+C)
```

> Note that by databases created via Elastic Beanstalk will be permanently tied to this environment. If you delete the environment then the database will be destroyed. Also note that AWS will automatically inject your new database information (URL, DB name and credentials) for you which will be picked up by Spring with [application-beanstalk.yml](src/main/resources/application-beanstalk.yml)

You can launch the application from the terminal with:

```bash
$ eb open
```

### List AWS/EB Environments and switching between them

List available environments:

```bash
$ eb list
* thymeleaf-starter-dev
thymeleaf-starter-prod
```

Switch between them:

```bash
$ eb use thymeleaf-starter-prod
```

### Redeploy new version to an existing AWS/EB Environment

Make sure your application is built with the latest with `gradle clean build`.

Make sure you're using the correct Elastic Beanstalk environment with `eb list` then redeploy:

```bash
$ eb deploy
```

### Delete an AWS/EB Environment

```bash
$ eb terminate
The environment "thymeleaf-starter-dev" and all associated instances will be terminated.
To confirm, type the environment name: thymeleaf-starter-dev
2019-02-22 21:27:36    INFO    terminateEnvironment is starting.
2019-02-22 21:27:53    INFO    Waiting for EC2 instances to terminate. This may take a few minutes.
2019-02-22 21:31:26    INFO    Deleted EIP: <IP_ADDRESS>
```

### Getting quick health statistics of an AWS/EB Environment

You can easily get quick health statics about your application by running `eb health`

![ebHealth.png](docs/diagrams/ebHealth.png)

## Spring Boot Dev Tools

[Spring Boot Dev Tools](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html) includes an additional set of tools that can make the application development experience a little more pleasant.

### Live Reload within IntelliJ

IDE's are fantastic but introduce complexity when it comes to watching file changes. As such Spring Boot Dev Tools can't easily automatically detect if files have changed within IntelliJ.

If you want changes to take effect then triggering a build within IntelliJ will cause Spring Boot to reload:

* \[Build\] then \[Rebuild Project]
* Or use short cut `Ctrl + F9`

#### Fully Automatic

If you really want every change to trigger a reload then follow additional steps described in [this article](https://www.romaniancoder.com/spring-boot-live-reload-with-intellij/).

* \[Ctrl + Shift + A] then select Registry
* Enable "compiler.automake.allow.when.app.running" then close
* \[File Menu] then \[Settings]
* Expand \[Build, Execution, Deployment] then select Compiler
* Enable "Build project automatically" then Apply then Ok
* Restart IntelliJ

repository: JahnelGroup/thymeleaf-starter

gha_language: HTML

repo_name: JahnelGroup/thymeleaf-starter


text:
---
name: Bug report
about: Open a bug report
title: ''
labels: bug
assignees: ''

---

I'm trying to...

### What's happening

When I do ... then this happens: ...

### What should be happening

I expect this would happen instead: ...

### My setup

StatiCrypt version:
Node version:
Any additional relevant context, if any:

license: MIT

repository: lwd-temp/staticrypt

branch_name: refs/heads/master

extension: md

gha_license_id: MIT

license_type: permissive

repo_name: lwd-temp/staticrypt


text:
# [2038. Remove Colored Pieces if Both Neighbors are the Same Color](https://leetcode-cn.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/)

![](https://img.shields.io/badge/Difficulty-Medium-F8AF40.svg)

Topics

* [`Greedy`](https://leetcode.com/tag/greedy/)
* [`Math`](https://leetcode.com/tag/math/)
* [`String`](https://leetcode.com/tag/string/)

There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.

Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice moves **first**.

 + Alice is only allowed to remove a piece colored `'A'` if **both its neighbors** are also colored `'A'`. She is **not allowed** to remove pieces that are colored `'B'`.
 + Bob is only allowed to remove a piece colored 'B' if **both its neighbors** are also colored `'B'`. He is **not allowed to** remove pieces that are colored `'A'`.
 + Alice and Bob **cannot** remove pieces from the edge of the line.
 + If a player cannot make a move on their turn, that player **loses** and the other player **wins**.

Assuming Alice and Bob play optimally, return *`true` if Alice wins, or return `false` if Bob wins*.

**Example 1:**

```
Input: colors = "AAABABB"
Output: true
Explanation:
AAABABB -> AABABB
Alice moves first.
She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.

Now it's Bob's turn.
Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
Thus, Alice wins, so return true.
```

**Example 2:**

```
Input: colors = "AA"
Output: false
Explanation:
Alice has her turn first.
There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.
Thus, Bob wins, so return false.
```

**Example 3:**

```
Input: colors = "ABBBBBBBAAA"
Output: false
Explanation:
ABBBBBBBAAA -> ABBBBBBBAA
Alice moves first.
Her only option is to remove the second to last 'A' from the right.

ABBBBBBBAA -> ABBBBBBAA
Next is Bob's turn.
He has many options for which 'B' piece to remove. He can pick any.

On Alice's second turn, she has no more pieces that she can remove.
Thus, Bob wins, so return false.
```

**Constraints:**

 + `1 <= colors.length <= 10^5`
 + `colors` consists of only the letters `'A'` and `'B'`

url: https://raw.githubusercontent.com/InnoFang/algo-set/2419a7d720bea1fd6ff3b75c38342a0ace18b205/LeetCode/2038. Remove Colored Pieces if Both Neighbors are the Same Color/README.md

repository: InnoFang/algo-set

repo_name: InnoFang/algo-set


text:
# DarkskyRain

Simple "is it going to rain?" visualisation using the Apple [WeatherKit API](https://developer.apple.com/documentation/weatherkitrestapi) (formerly the Dark Sky API) and [Highcharts](https://www.highcharts.com/). Shows probablity charts for the next hour and the next 24 hours. Rain intensity is indicated by bubble size.

![Screenshot](screenshot.png)

## Acknowledgements

Thanks to Adam Russell for the WeatherKit API implementation <https://github.com/adam-russell/weatherkit-net-example>

repository: drybones/DarkskyRain

gha_language: JavaScript

repo_name: drybones/DarkskyRain


text:
---
slug: control-a-synth-with-your-voice-and-a-gate-in-ableton-live
title: Control a Synth With Your Voice and a Gate in Ableton Live
date: 2020-05-29 21:05
published: true
category: ['music']
---

Sometimes you have a rythym in your head that you're having a hard
time laying down using a keyboard or pads. Whenever that happens,
just record an audio track using your voice or clapping then sidechain
the audio track into a "Gate". This video will walk you through the process:

<YoutubeEmbed slug="nBnkmLNsv2c"/>

gha_language: CSS


text:
# Installation
Move this folder into home folder.
'''$ mv ../rpi_capture_cam ~/spectrometer'''

The folder tree should look like
/home/pi/spectrometer
    cam.py
    light.py
    samples/

Enter the directory
'''$ cd $HOME/spectrometer'''

move the capture command to /bin
'''$ sudo mv capture /bin'''

The folder tree should look like

/bin
    capture

to make sure it is copied in the right directory
'''$ sudo ls /bin | grep capture''' should result:
"capture"

then source the terminal.
'''$ source ~/.bashrc'''

# Usage
To run:
'''$ capture FILE_NAME'''

# Simple Documentation
    The capture script simply runs few lines of code to first
activate the light wait few sec and run camera capturing and turn light off.
The file will be generated in /samples


text:
---
published: true
title: Consulting Answers
layout: post
summary: This week on our podcast we talked about my now defunct consulting business, which in it's last year of operation made me hundreds of thousands of dollars at rates north of $200/hour. I got some follow up questions, I'm collecting my answers here.
---

This week on our [podcast](http://shavua.net) (careful, Hebrew) we talked about my now defunct consulting business, which in it's last year of operation made me hundreds of thousands of dollars at rates north of $200/hour. I got some follow up questions, I'm collecting my answers here.

### How do you explain your high rates to customers?

I solve problems for free until there's nothing to explain and it's clear to all sides that my cost is much less than their gain. For this method to work, two things are necessary:

1. The right pipeline brings in potential clients that (a) have large problems I can solve big time and (b) have enough money to easily spend $50k if it makes sense to them.
2. A method which lets me deliver value fast to that pipeline. The key here is *deliver* not *explain*. The fast part enables the pipeline's economics. If it wasn't fast I couldn't do it for free, if I couldn't do it for free, sales would be a lot tougher.

When it works, after one or two meetings the client sees how my work is changing significant outcomes for their business. At that point cost is not an issue as long as they have the money available.

The harder questions are (1) how do you develop the skills to do work that is genuinely worth say $30k/month (2) how do you put yourself in front of people who can use your help and deliver solutions so obviously that hiring you for more solutions is a no brainer.

### How do you manage conflicts with clients?

The important thing is understanding that if you have a conflict you've already lost, you're now in damage control mode. When things go well conflict almost never happens. I haven't had a client conflict in years, and I used to have them often.

If you do have a conflict optimise for ending it. These things can be a real drag and there's basically no limit on how bad it can get. You'll also want an agreement structure that makes the option of "hey this isn't working out, let's just call it a day" feasible. This means as much time based billing as possible and as little fixed deliverables as possible.

You sit them down, explain transparently why you don't want to continue the work and because you're not a douche you give them as much control over the wind down process as possible.

The best thing you can do is have clients that crazy appreciate your work (first step: do work that is worth crazy appreciating). That dynamic changes everything, you'll get no pressure from your clients and how you manage your work life balance will be entirely up to you.

If you find yourself thinking "sure, that's easy for someone who is already established", I can see why you'd think that but I'd disagree. One always reliable way to do work that is crazy appreciated is really caring about your output. That almost always works and never requires experience or connections.

### How do you source customers? Blogging? Talks? High profile projects? Free meetings?

Find ways to deliver as much value as possible to as many people as possible. Nothing sells your services better than actually delivering small portions of it to the right people.

High profile projects are useful, but ideally you want your clients to hire you because *you've already helped them*. They've already learned from you, you already solved problems for them through a blog, a talk, a meeting, whatever. At that point, your skills are not under examination. You can't fake solving someone's problems.

extension: markdown


text:
# RTreeSharp

Implementation of an RTree in C# using .net core.

## Getting Started

### Prerequisites

Open with VS 2019 and build.

### Installing

## Running the tests

### Break down into end to end tests

### And coding style tests

## Deployment

## Built With

## Contributing

## Versioning

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags).

## License

This project is licensed under the Apache License 2.0 - see the [LICENSE.md](LICENSE.md) file for details

## Acknowledgments

repository: Sprunth/RTreeSharp

gha_language: C#

repo_name: Sprunth/RTreeSharp


text:
# OBJ-File-Renderer
Renders OBJ file formats to a 2D display, uses Python and Pygame

I have started work on a more clean version of this code ([py3D](https://github.com/hamolicious/py3d)) therefore I have archived this repository.

Images

repository: rishideepc/OBJ-File-Renderer

repo_name: rishideepc/OBJ-File-Renderer


text:
---
date: '2016-09-26'
layout: rafaga
rafagas:
- desc: Several resolutions and formats terrain tiles on Amazon by Mapzen
  keyw: terrain
  link: https://aws.amazon.com/blogs/publicsector/announcing-terrain-tiles-on-aws-a-qa-with-mapzen/
  microlink:
    desc: We are excited to announce Terrain Tiles on AWS, a new AWS Public Dataset
      that makes global digital elevation models (DEMs) available for anyone to access
      from Amazon Simple Storage Service (Amazon S3). DEMs provide a way to examine
      the elevation of the Earth’s surface and are available as terrain r…
    image: https://d2908q01vomqb2.cloudfront.net/827bfc458708f0b442009c9c9836f7e4b65557fb/2020/06/03/Blog-Post_thumbnail.png
    logo: https://logo.clearbit.com/amazon.com
    title: 'Announcing Terrain Tiles on AWS: A Q&A with Mapzen | Amazon Web Services'
- desc: Barcelona subway network with the real itineraries and way more data
  keyw: subway
  link: http://carto.metro.free.fr/cartes/metro-tram-barcelona/
  microlink:
    desc: Site consacré aux métros, tramways et RER (Paris, Lyon, Lille, Bordeaux,
      Strasbourg, Nantes, Clermont-Ferrand, Dijon, Marseille, Montpellier, Mulhouse,
      Nice, Orléans, Genève, Lausanne, Turin, Milan). Vous y trouverez des cartes
      très détaillées de ces différents réseaux.
    image: http://cartometro.com/images/logo.png
    logo: http://cartometro.com/favicon.gif
    title: Carte détaillée du métro et tramway de Barcelona (voies, ateliers)
- desc: A visual editor for GL vector styles, open source and looking for funding
  invalid: true
  keyw: styles
  link: http://maputnik.com/demo/
- desc: Contextualized study with 2015 MediaMarkt economic results
  keyw: results
  link: http://www.arcgis.com/apps/MapSeries/index.html?appid=8ebf08730b034f1199bee15f9f08cbd5
  microlink:
    desc: This story map was created with the Story Map Series application in ArcGIS
      Online.
    image: https://www.arcgis.com/apps/MapSeries/resources/common/icons/esri-globe.png
    logo: https://www.arcgis.com/apps/MapSeries/resources/tpl/viewer/icons/favicon.ico
    title: Story Map Series
- desc: Geological maps, remote sensing and the Chilean copper mine example
  keyw: copper
  link: https://www.linkedin.com/pulse/rsg-key-mineral-exploration-giant-porphyry-copper-example-d%C3%ADaz
  microlink:
    desc: 'Dear colleagues and connections, here goes the pending second part of the
      article: “Remote Spectral Geology (#RSG) Concept: its Origin and Evolution”
      (direct link below). The new article is going deeper to explain the reasons
      why is important for #MineralExploration companies to apply this concept.'
    image: https://media-exp1.licdn.com/dms/image/C5612AQFNmWlU0Q1O1w/article-cover_image-shrink_600_2000/0/1520175807526?e=1628121600&v=beta&t=egRIoqMGFVP4JgQ7XXVv3hQ_d1ty33M9Xqx7rWMsc7U
    logo: https://logo.clearbit.com/linkedin.com
    title: 'RSG: Key for Mineral Exploration - Giant Porphyry Copper example, Chile'
rid: 443
---

repository: geoinquiets/rafagas

branch_name: refs/heads/gh-pages

gha_language: SCSS

gha_license_id: NOASSERTION

repo_name: geoinquiets/rafagas


text:
---
name: Usage Question
about: Ask a question about AWS Amplify CLI usage
title: ''
labels: ''
assignees: ''

---

>**Note**: If your question is regarding the AWS Amplify Console service, please log it in the
[official AWS Amplify Console forum](https://forums.aws.amazon.com/forum.jspa?forumID=314&start=0)

** Which Category is your question related to? **

** What AWS Services are you utilizing? **

** Provide additional details e.g. code snippets **

repository: awslabs/amplify-video

repo_name: awslabs/amplify-video


text:
# 367. Valid Perfect Square
**Difficulty:** Easy

## URL

https://leetcode.com/problems/valid-perfect-square/

## Solution

### Approach 1: Binary Seach

To my sense, this is the most intuitive solution I can think of. The idea of binary search to this problem is very simple, each time we take the average (integer) of two boundary values, one of which is the lower search bound, the other is the upper search bound. Then we square this median and compare the result with our target value, recursively, if to some step they are equal, then our target is a perfect square, otherwise it's not.

The reason for binary search is also intuitive, for time efficiency and space efficiency. Overall, this algorithm can run in $O(log n)$ time and $O(log n)$ space (depends on the recursion depth).

There is one issue we should notice: the data type `int` may not work for the square operation so we need to use `long long int` instead. Program with `int` actually will report runtime error.

The code is shown below:

```c++
// Valid Perfect Square
// 53.63% time, 76.19% space
// Accepted

#include <iostream>
#include <math.h>

using namespace std;

class Solution {
public:
    // This helper function evaluate whether the square of the average of low and high equals the target
    bool evaluate(int low, int high, int target) {
        // base case
        int median = (low+high) / 2;
        if (low == high || median == low || median == high)    return false;
        if (median*median == target)    return true;
        else if (target > median*median)    return evaluate(median, high, target);
        else    return evaluate(low, median, target);
    }

    bool isPerfectSquare(int num) {
        if (num < 0)
            return false;
        else if (num == num*num)
            return true;

        return evaluate(0, num, num);
    }
};

int main() {
    Solution test;
    int res1 = test.isPerfectSquare(16);
    int res2 = test.isPerfectSquare(14);
    cout << res1 << endl;
    cout << res2 << endl;

    return 0;
}
```

## Approach 2

```python
class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        left = 1
        right = num
        while left <= right:
            mid = (left + right) // 2
            temp = mid * mid
            if temp == num:
                return True
            elif temp < num:
                left = mid + 1
            else:
                right = mid - 1
        return False
```

repository: Aden-Q/LeetCode

repo_name: Aden-Q/LeetCode


text:
+++
title = "Native & Components"
date = 2020-10-20T18:13:41+02:00
weight = 2
pre = "<b>2. </b>"
draft = false
+++

`react-native` is different from the WebView based approaches for app development. In `react-native` the components are
converted to actual native components and that is why the components are not web, but a specific set of components that
can map to the specific native corresponding components.

#### Component mapping for primitive components
{{< lazy-image image="rn_to_native.png" lightbox=false />}}

Usually the transition from `react` for the web to `react-native` is quite intuitive as the only thing that changes is
the tags that are used. The semantics of `<View />` is a reference to the native part in `react-native` as mobile app
frameworks have the view as the central primitive. What this means in practice is that any UI can be built as a
hierarchy of `<View />`s.

repository: adaschevici/react-native-ac

branch_name: refs/heads/main

repo_name: adaschevici/react-native-ac


text:
---
layout: page
title: Opportunities
---

While the CNL does not currently have any openings, we are always open to internships and short projects with undergraduate students, graduate students, and volunteers.

Please email [cameron.craddock<EMAIL_ADDRESS>to apply.


text:
Example DeepOps configuration
=============================

This directory provides an example configuration for NVIDIA DeepOps.
The files in this directory will help determine the behavior of the Ansible playbooks and other scripts that DeepOps uses to set up your systems.

For more details on how this works, see [how to configure DeepOps](../docs/deepops/configuration.md).

repository: NVIDIA/deepops

gha_language: Shell

repo_name: NVIDIA/deepops


text:
# Get The First Item For Every Top-Level Key

Let's say we have a JSON object where each key in that object is tied to a
large array of values. To get a better idea of what the data looks like, we
want to trim down the JSON a bit. Essentially, we want to tie each key to the
first value in each of their respective arrays.

We can do this by reducing the object into a new object where each top-level
key is tied to the first item in its array.

```bash
$ jq '. as $object | reduce keys[] as $k ({}; .[$k] = $object[$k][0])' data.json
```

This uses variables (`$object` and `$k`) and the [`reduce`
function](https://stedolan.github.io/jq/manual/#Reduce) to iterate over the
incoming JSON object and produce a new object with the trimmed down data.

JSON like this:

```json
{
  "key1": ["a", "b", "c"],
  "key2": [1, 2, 3],
  "key3": ["x", "y", "z"]
}
```

will be turned into this:

```json
{
  "key1": "a",
  "key2": 1,
  "key3": "x"
}
```

repository: jbranchaud/til

gha_language: Vim Script

repo_name: jbranchaud/til


text:
# App-All-O-Gizer
### (ə-pŏlˈə-jīz ə(r))

## Never be sorry you weren't sorry again!

Sometimes we hurt people, sometimes people are hurt by us and we don't know it. With this app, you don't have to worry about forgetting to say your sorry to the ones you love. Schedule apologies to be sent automatically once a month, once a week, or every day!

### Never be sorry you weren't sorry again!

### You can see App-All-O-Gizer in action [here](http://www.appallogizer.com/)

![appallogizer](https://cloud.githubusercontent.com/assets/4650739/22124056/4d18bb72-de32-11e6-82ed-a89134d6c22c.gif)

## Getting Started
1. Fork and clone
1. Run `npm install`
1. Add your gmail email address and password to enviornmental variables. IN your terminal run:
  1. `export<EMAIL_ADDRESS>and
  1. `export pass=YOUR_EMAIL_PASWORD`
1. Run `npm start`
1. Open your browser to `http://localhost:3000/`
1. Never be sorry you weren't sorry again!

## Contributing
1. Fork it!
1. Create your feature branch: ```git checkout -b my-new-feature```
1.  Push to the branch: ````git push origin my-new-feature````
1. Submit a pull request :D

repository: JoeKarlsson/app-all-o-gizer

repo_name: JoeKarlsson/app-all-o-gizer


text:
---
title: Monitoring Jaeger
navtitle: Monitoring
weight: 8
---

Jaeger itself is a distributed, microservices based system. If you run it in production, you will likely want to setup adequate monitoring for different components, e.g. to ensure that the backend is not saturated by too much tracing data.

## Metrics

By default Jaeger microservices expose metrics in Prometheus format. It is controlled by the following command line options:

* `--admin-http-port` the port number where the HTTP admin server is running
* `--metrics-backend` controls how the measurements are exposed. The default value is `prometheus`, another option is `expvar`, the Go standard mechanism for exposing process level statistics.
* `--metrics-http-route` specifies the name of the HTTP endpoint used to scrape the metrics (`/metrics` by default).

Each Jaeger component exposes the metrics scraping endpoint on the admin port:

Component             | Port
--------------------- | ---
**jaeger-agent**      | 14271
**jaeger-collector**  | 14269
**jaeger-query**      | 16687
**jaeger-ingester**   | 14270
**all-in-one**        | 14269

### Prometheus monitoring mixin for Jaeger

The Prometheus monitoring mixin for Jaeger provides a starting point for people wanting to monitor Jaeger using Prometheus, Alertmanager, and Grafana. This includes a prebuilt [dashboard](https://github.com/jaegertracing/jaeger/blob/master/monitoring/jaeger-mixin/dashboard-for-grafana.json). For more information, see [the documentation](https://github.com/jaegertracing/jaeger/tree/master/monitoring/jaeger-mixin).

## Logging

Jaeger components only log to standard out, using structured logging library [go.uber.org/zap](https://github.com/uber-go/zap) configured to write log lines as JSON encoded strings, for example:

```json
{"level":"info","ts":1517621222.261759,"caller":"healthcheck/handler.go:99","msg":"Health Check server started","http-port":14269,"status":"unavailable"}
```

The log level can be adjusted via `--log-level` command line switch; default level is `info`.

## Traces

Jaeger has the ability to trace some of its own components, namely the requests to the Query service. For example, if you start `all-in-one` as described in [Getting Started](../getting-started), and refresh the UI screen a few times, you will see `jaeger-query` populated in the Services dropdown. If you prefer not to see these traces in the Jaeger UI, you can disable them by running Jaeger backend components with `JAEGER_DISABLED=true` environment variable, for example:

```
docker run -e JAEGER_DISABLED=true -p 16686:16686 jaegertracing/all-in-one:{{< currentVersion >}}
```

repository: jaegertracing/documentation

repo_name: jaegertracing/documentation


text:
TaskRunner is what AsyncTasks or Loaders would be like if they were designed around the way the Android runtime actually works.

# Introduction

Most Android apps suffer from couple fundamental problems:

1. **Losing work or crashing during screen rotations**: Android makes it very difficult to manage asynchronous work across device rotations or configuration changes.
2. **I/O on the main thread**: this results in slow screen loads, chunky scrolling, and in extreme cases, "Application Not Responding" dialogs which, to the end user, appear to be crashes.
3. **Memory leaks**: usually caused by performing asynchronous operations with callbacks that are implicitly bound to their containing Activity via closure. That means that Activities (including all their Fragments and Views) are retained until the operation complete. In many cases this is no longer than a few seconds, but in some cases it can be as long as minutes. In the case of programmer error, they may leak indefinitely. As the user navigates around the app, these leaks begin to pile up, and can eventually lead to OutOfMemoryExceptions.
4. **Modifying paused, destroyed components**: depending on timing, the callbacks described in (2) may be invoked while the UI component is in one of the following 'invalid' states:
    * *Paused*: modifying UI components while they are in the paused state leads to buggy behavior, especially for Fragments. The UI updates may be reverted by the platform automatically during the resume cycle.
    * *Destroyed*: the runtime will generally throw an exception if UI components are modified after they have been destroyed.

**TaskRunner** is a small library that helps address of these problems.

# What does TaskRunner do?

TaskRunner does the following:

1. Keeps track of its respective component's lifecycle and ensures completion events are not raised unless the component is in a valid (i.e. active) state.
2. Ensures work is tracked/cached across screen rotations and other configuration changes
3. Is designed to discourage implicit binding via closure to Activity instances
3. Adds an easy facility to do simple I/O bound tasks in the background, safely

# How does TaskRunner work?

TaskRunner requires cooperation with the component (Activity or Fragment) it is bound to. The hosting component must notify its Runner instance about certain changes to its lifecycle. It follows a couple very simple rules:

1. A Runner may be *paused* or *resumed*, and *attached* or *detached*.
2. *Attached* instances are bound to a component, and may be either paused or resumed.
3. Instances are considered *paused* when their containing component is paused. Paused Runners may accept new Tasks, however:
    * These Tasks will not be started until the Runner is resumed.
    * Work that was started while resumed, but finished while paused, will be cached but not relayed to the containing component until the Runner is resumed.
4. Instances are considered *resumed* when their containing component is resumed. Resumed instances are allowed to accept and start work, and also delivered results.
5. Instances become *detached* when their containing component is destroyed. Upon detach, the instance is added to a global cache with a short TTL. If not re-attached within a short period of time, the Runner will be removed from the cache and all work (pending and completed) will be forgotten. The short TTL allows the library to automatically clean up resources for orphaned Runners/Tasks in a predicable manner, and ensures that work is almost never restarted.

The following sequence diagram explains common behavior visually:

Note: in this diagram Activity could instead be a Fragment, Service, or any other construct that needs a Runner.

![sequence diagram 1](https://github.com/underarmour/android-taskrunner/blob/master/static/img/sequence_diagram_1.png?raw=true)

# Integrating TaskRunner with your app

If you read the previous section you'll notice an emphasis on using Activities and Fragments to drive Runners. This may seem slightly unintuitive at first, but it can actually help reduce tight coupling between components. It's best to think of Tasks as light-weight, reliable asynchronous wrappers around existing synchronous operations. This paradigm works well with service-oriented architectures. In a nutshell, the idea is this:

1. Use a micro-service oriented architecture for your Android app. Services house business logic for things not strictly related to UI interaction – communicating with the backend, querying the database, etc. Note that services do not necessarily need to be subclasses of Android's Service base class. Rather, they are components within an Android application that perform I/O bound operations on behalf of the user interface.
2. Remove all AsyncTasks and Loaders from your UI. TaskRunner will handle this for you. Service methods should simply return their result on the calling thread, throwing an exception if necessary.
3. Write Tasks that wrap the synchronous methods as required.

A sequence diagram for this approach looks like the following:

![sequence diagram 2](https://github.com/underarmour/android-taskrunner/blob/master/static/img/sequence_diagram_2.png?raw=true)

Interaction using an event bus library (e.g. Otto) may look like the following:

![sequence diagram 3](https://github.com/underarmour/android-taskrunner/blob/master/static/img/sequence_diagram_3.png?raw=true)

Following this approach has the these benefits:

1. **Services become easier to write** – no need to worry about multi-threading in most cases. All public methods can be synchronous.
2. **Synchronous methods make the service layer easier to test**. You won't be required to create CountDownLatches with timeouts, or spin waiting for results.
3. **Tasks are easily reusable**, and can be integrated into ViewModels easily.

# Usage

## Lifecycle Integration

The best way to integrate with TaskRunner is to create an instance of `com.uacf.taskrunner.LifecycleDelegate` in your Activity or Fragment and forward the relevant lifecycle events to it: `onCreate`, `onSaveInstanceState`, `onPause`, `onResume`, and `onDestroy`. Make sure you instantiate the `LifecycleDelegate` in `onCreate`.

Your Activity will also need to implement `com.uacf.taskrunner.Runner.TaskCallbacks` (or create an inner class that implements it) to receive results.

Here's an example:

```java
class TaskRunnerActivity extends AppCompatActivity implements Runner.TaskCallbacks {
    private final LifecycleDelegate delegate;

    public void onCreate() {
        super.onCreate();
        delegate = new LifecycleDelegate(this, this, getClass(), null);
        delegate.onCreate();
    }

    public void onDestroy() {
        super.onDestroy();
        delegate.onDestroy();
    }

    public void onPause() {
        super.onPause();
        delegate.onPause();
    }

    public void onRersume() {
        super.onResume();
        delegate.onResume();
    }

    public void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);
        delegate.onSaveInstanceState(state);
    }

    public void onTaskCompleted(String name, long id, Task task, Object result) {
        /* process results here */
    }

    public void onTaskError(String name, long id, Task task, Throwable error) {
        /* process errors here */
    }

    protected Runner getRunner() {
        return delegate.runner();
    }
}
```

## Defining a Task

Tasks should either be defined as static inner classes, or regular outer classes. That is, you don't want your Task to have an implicit binding to whatever Activity/Fragment is instantaiting it.

```java
private static class MyTask extends Tasks.Blocking<MyResultType, MyErrorType> {
    public MyTask(...) {
    }

    @Override
    protected MyResultType exec(final Context context) throws MyErrorType {
        final MyResultType result = ...;
        ...
        return result;
    }
}
```

Some important notes:

* Tasks are parameterized by two types: the `ResultType`, and an `ErrorType`.
* All long-running work should be performed in the `ResultType exec(final Context context) throws MyErrorType` method.
* You may pass data via constructor, but you should not retain anything that is implicitly (or explicitly) bound to the host Activity or Fragment.
* Generally you should use `Tasks.Blocking` as your base class. This type of task will be run on a background thread, but will block waiting for a result. `Tasks.AsyncWait` is also provided and can be used to wrap existing asynchronous operations.
* If your operation does not throw an explicit exception, you can use `Tasks.Blocking.Unchecked<ResultType>` to omit specifying an `ErrorType`.

## Starting a Task

Once your Activity has been integrated with `LifecycleDelegate` and you have a Task defined, you're ready to go:

```java
class MyActivity extends TaskRunnerActivity {
    private long myTaskId = -1;

    public void onUserAction() {
        taskId = getRunner().run(new MyTask(argument));
    }

    void onTaskCompleted(String name, long id, Task task, Object result) {
        if (id == myTaskId) {
            /* done! */
        }
    }

    void onTaskError(String name, long id, Task task, Throwable error) {
        if (id == myTaskId) {
            /* error! */
        }
    }

    ...
}
```

Note that this example matches task completion by `id`. Users may also compare tasks by `name` by using the `Runner.run(String name, Task task)` method.

When running by name the caller can opt in to caching. If a Task is run to completion, and another Task is enqueued with the same name, this operation can be de-duped and the result from the first Task can be return immediately. Note that cached results are only available to the same Activity/Fragment that instantiated the Task. That is, if two Activities define Tasks with the same name, one will not get cached results from the other. Here's an example:

```java
getRunner().run("MyNamedTask", new MyTask(...), Runner.CacheMode.CacheOnSuccess);
```

Similarly, if two name Tasks are enqueued at the same time, the user can specify the preferred de-duplication method:

```java
getRunner().run("MyNamedTask", new MyTask(...), Runner.DedupeMode.UseExisting);
```

The default cache mode is `CacheMode.None` (don't cache anything) and the default dedupe method is `DedupeMode.Throw` (throws an exception if two tasks with the same name are enqueued simultaenously). The default modes may be tweaked by calling `runner.setDefaultCacheMode()` and `runner.setDefaultDedupeMode()`.

# Task best practices

When writing tasks always do the following:

1. Task subclasses that are inner classes should always be declared as static, as to not leak implicit references of their containing type
2. Task subclasses should be extremely judicious about their inputs, and not accept anything that that explicitly, or implicitly references large objects (e.g. Views, Fragments, Activities, Bitmaps, etc).

# Critique and future

Although TaskRunner helps solve a couple fundamental issues with Android app development, it can certainly be better.

Perhaps the biggest problem with TaskRunner is the proliferation of small wrapper classes that exist just to call through to service methods. While Tasks are generally easy to write, they do take time and are not exactly elegant. In the future we'd like to figure out a way to dynamically create Tasks at compile-time, perhaps leveraging some clever use of annotations.

Additionally, TaskRunner provides no facility for composing or chaining Tasks. This, however, may be addressed by using something like RxJava's Observers synchronously within a Task's work method.

repository: clangen/android-taskrunner

repo_name: clangen/android-taskrunner


text:
# Authentication

Uceem's API uses an `auth_token` for authentication, every request made to the Uceem API will require one.  These tokens are managed on a per-user level, so you will need to authenticate to the Uceem API with a `POST` that contains your valid Uceem email and password.

## Retrieving the token

A successful request would be similar to the following:

```bash
$ curl -X POST -d<EMAIL_ADDRESS>\
               -d "password=password" \
               https://uceem.com/api/login.json
```

With the response:

```json
{
  "auth_token": "<YOUR_TOKEN>"
}
```

A valid response will have the status 200, and an `auth_token` key in the response body. Now that you've secured your token, you will be able to make other requests to the Uceem API. Just be sure to include `auth_token=my_token` as a parameter, otherwise we don't know it's you.

## Using the ruby gem

The Uceem gem can take care of all of this for you, with one simple call that takes the email and password as parameters:

```ruby
require 'uceem'

<EMAIL_ADDRESS>'password')
# => 'your_secret_auth_token'
```

The `begin_session` call retrieves the `auth_token`, so you can make all the API calls you'd like with the Uceem gem during that session. When you're done:

```ruby
Uceem::Authentication.end_session
```

repository: uceem/uceem-ruby

repo_name: uceem/uceem-ruby


text:
# Virgil Core SDK & Crypto Stack Java/Android

[![Build Status](https://api.travis-ci.org/VirgilSecurity/virgil-sdk-java-android.svg?branch=master)](https://travis-ci.org/VirgilSecurity/virgil-sdk-java-android)
[![Maven](https://img.shields.io/maven-central/v/com.virgilsecurity.sdk/sdk.svg)](https://search.maven.org/artifact/com.virgilsecurity.sdk/sdk)
[![GitHub license](https://img.shields.io/badge/license-BSD%203--Clause-blue.svg)](https://github.com/VirgilSecurity/virgil/blob/master/LICENSE)

[Introduction](#introduction) | [SDK Features](#sdk-features) | [Installation](#installation) | [Configure SDK](#configure-sdk) | [Usage Examples](#usage-examples) | [Docs](#docs) | [Support](#support)

## Introduction

 [Virgil Security](https://virgilsecurity.com) provides a set of APIs for adding security to any application. In a few simple steps you can encrypt communications, securely store data, and ensure data integrity. Virgil Security products are available for desktop, embedded (IoT), mobile, cloud, and web applications in a variety of modern programming languages.

The Virgil Core SDK is a low-level library that allows developers to get up and running with [Virgil Cards Service API](https://developer.virgilsecurity.com/docs/platform/api-reference/cards-service/) quickly and add end-to-end security to their new or existing digital solutions.

In case you need additional security functionality for multi-device support, group chats and more, try our high-level [Virgil E3Kit framework](https://github.com/VirgilSecurity/awesome-virgil#E3Kit).

## SDK Features
- Communicate with [Virgil Cards Service](https://developer.virgilsecurity.com/docs/platform/api-reference/cards-service/)
- Manage users' public keys
- Encrypt, sign, decrypt and verify data
- Store private keys in secure local storage
- Use [Virgil Crypto Library](https://github.com/VirgilSecurity/virgil-crypto-java)

## Installation

The Virgil Core SDK is provided as set of packages named *com.virgilsecurity.sdk*. Packages are distributed via Maven repository. In this guide you'll also find one more package - Virgil Crypto Library, that is used by the SDK to perform cryptographic operations.

### Target

* Java 7+.
* Android API 16+.

### Prerequisites

* Java Development Kit (JDK) 7+
* Maven 3+

### Installing the package

You can easily add SDK dependency to your project, just follow the examples below:

#### Maven

Use this packages for Java projects:

```
<dependencies>
    <dependency>
        <groupId>com.virgilsecurity.sdk</groupId>
        <artifactId>sdk</artifactId>
        <version><latest-version></version>
    </dependency>
</dependencies>
```

#### Gradle

Add jcenter() repository if missing:

```
repositories {
    jcenter()
}
```

Use this packages for Android projects:

```
    implementation "com.virgilsecurity.sdk:sdk-android:<latest-version>"
```

The **\<latest-version>** of the SDK can be found in the [Maven Central Repository](https://mvnrepository.com/artifact/com.virgilsecurity.sdk/sdk) or in the header of current readme.

## Configure SDK

This section contains guides on how to set up Virgil Core SDK modules for authenticating users, managing Virgil Cards and storing private keys.

### Set up authentication

Set up user authentication with tokens that are based on the [JSON Web Token standard](https://jwt.io/) with some Virgil modifications.

In order to make calls to Virgil Services (for example, to publish user's Card on Virgil Cards Service), you need to have a JSON Web Token ("JWT") that contains the user's `identity`, which is a string that uniquely identifies each user in your application.

Credentials that you'll need:

|Parameter|Description|
|--- |--- |
|App ID|ID of your Application at [Virgil Dashboard](https://dashboard.virgilsecurity.com)|
|App Key ID|A unique string value that identifies your account at the Virgil developer portal|
|App Key|A Private Key that is used to sign API calls to Virgil Services. For security, you will only be shown the App Key when the key is created. Don't forget to save it in a secure location for the next step|

#### Set up JWT provider on Client side

Use these lines of code to specify which JWT generation source you prefer to use in your project:

```java
// Get generated token from server-side
final String authenticatedQueryToServerSide =
        "eyJraWQiOiI3MGI0NDdlMzIxZjNhMGZkIiwidHlwIjoiSldUIiwiYWxnIjoiVkVEUzUxMiIsImN0eSI6InZpcmdpbC1qd3Q7dj0xIn0.eyJleHAiOjE1MTg2OTg5MTcsImlzcyI6InZpcmdpbC1iZTAwZTEwZTRlMWY0YmY1OGY5YjRkYzg1ZDc5Yzc3YSIsInN1YiI6ImlkZW50aXR5LUFsaWNlIiwiaWF0IjoxNTE4NjEyNTE3fQ.MFEwDQYJYIZIAWUDBAIDBQAEQP4Yo3yjmt8WWJ5mqs3Yrqc_VzG6nBtrW2KIjP-kxiIJL_7Wv0pqty7PDbDoGhkX8CJa6UOdyn3rBWRvMK7p7Ak";

// Setup AccessTokenProvider
CallbackJwtProvider.GetTokenCallback getTokenCallback = new CallbackJwtProvider.GetTokenCallback() {

        @Override
        public String onGetToken(TokenContext tokenContext) {
                return authenticatedQueryToServerSide;
        }
};
// initialize JWT provider
AccessTokenProvider accessTokenProvider =
        new CallbackJwtProvider(getTokenCallback);
```

#### Generate JWT on Server side

Next, you'll need to set up the `JwtGenerator` and generate a JWT using the Virgil SDK.

Here is an example of how to generate a JWT:

```java
// App Key (you got this Key at Virgil Dashboard)
String appKeyBase64 = "MC4CAQAwBQYDK2VwBCIEINlK4BhgsijAbNmUqU6us0ZU9MGi+HxdYCA6TdZeHjR4";
byte[] appKeyData = ConvertionUtils.base64ToBytes(appKeyBase64);

// Crypto library imports a private key into a necessary format
VirgilCrypto crypto = new VirgilCrypto();
PrivateKey appKey = crypto.importPrivateKey(appKeyData);

// initialize accessTokenSigner that signs users JWTs
AccessTokenSigner accessTokenSigner = new VirgilAccessTokenSigner();

// use your App Credentials you got at Virgil Dashboard:
String appId = "be00e10e4e1f4bf58f9b4dc85d79c77a"; // App ID
String appKeyId = "70b447e321f3a0fd"; // App Key ID
TimeSpan ttl = TimeSpan.fromTime(1, TimeUnit.HOURS); // 1 hour (JWT's lifetime)

// setup JWT generator with necessary parameters:
JwtGenerator jwtGenerator = new JwtGenerator(appId, appKey, appKeyId, ttl, accessTokenSigner);

// generate JWT for a user
// remember that you must provide each user with his unique JWT
// each JWT contains unique user's identity (in this case - Alice)
// identity can be any value: name, email, some id etc.
String identity = "Alice";
Jwt aliceJwt = jwtGenerator.generateToken(identity);

// as result you get users JWT, it looks like this: "eyJraWQiOiI3MGI0NDdlMzIxZjNhMGZkIiwidHlwIjoiSldUIiwiYWxnIjoiVkVEUzUxMiIsImN0eSI6InZpcmdpbC1qd3Q7dj0xIn0.eyJleHAiOjE1MTg2OTg5MTcsImlzcyI6InZpcmdpbC1iZTAwZTEwZTRlMWY0YmY1OGY5YjRkYzg1ZDc5Yzc3YSIsInN1YiI6ImlkZW50aXR5LUFsaWNlIiwiaWF0IjoxNTE4NjEyNTE3fQ.MFEwDQYJYIZIAWUDBAIDBQAEQP4Yo3yjmt8WWJ5mqs3Yrqc_VzG6nBtrW2KIjP-kxiIJL_7Wv0pqty7PDbDoGhkX8CJa6UOdyn3rBWRvMK7p7Ak"
// you can provide users with JWT at registration or authorization steps
// Send a JWT to client-side
String jwtString = aliceJwt.stringRepresentation();
```

For this subsection we've created a sample backend that demonstrates how you can set up your backend to generate the JWTs. To set up and run the sample backend locally, head over to your GitHub repo of choice:

[Node.js](https://github.com/VirgilSecurity/sample-backend-nodejs) | [Golang](https://github.com/VirgilSecurity/sample-backend-go) | [PHP](https://github.com/VirgilSecurity/sample-backend-php) | [Java](https://github.com/VirgilSecurity/sample-backend-java) | [Python](https://github.com/VirgilSecurity/virgil-sdk-python/tree/master#sample-backend-for-jwt-generation)
 and follow the instructions in README.

### Set up Card Verifier

Virgil Card Verifier helps you automatically verify signatures of a user's Card, for example when you get a Card from Virgil Cards Service.

By default, `VirgilCardVerifier` verifies only two signatures - those of a Card owner and Virgil Cards Service.

Set up `VirgilCardVerifier` with the following lines of code:

```java
// initialize Crypto library
CardCrypto cardCrypto = new VirgilCardCrypto();

VerifierCredentials yourBackendVerifierCredentials =
        new VerifierCredentials("YOUR_BACKEND",
                ConvertionUtils.base64ToBytes(PUBLIC_KEY_STR));

Whitelist yourBackendWhiteList =
        new Whitelist(Arrays.asList(yourBackendVerifierCredentials));

CardVerifier cardVerifier = new VirgilCardVerifier(cardCrypto,
        Arrays.asList(yourBackendWhiteList));
```

### Set up Card Manager

This subsection shows how to set up a Card Manager module to help you manage users' public keys.

With Card Manager you can:
- specify an access Token (JWT) Provider.
- specify a Card Verifier used to verify signatures of your users, your App Server, Virgil Services (optional).

Use the following lines of code to set up the Card Manager:

```java
// initialize cardManager and specify accessTokenProvider, cardVerifier
CardManager cardManager = new CardManager(cardCrypto, accessTokenProvider, cardVerifier);
```

## Usage Examples

Before you start practicing with the usage examples, make sure that the SDK is configured. See the [Configure SDK](#configure-sdk) section for more information.

### Generate and publish Virgil Cards at Cards Service

Use the following lines of code to create a user's Card with a public key inside and publish it at Virgil Cards Service:

```java
import com.virgilsecurity.crypto.VirgilCrypto;

VirgilCrypto crypto = new VirgilCrypto();

// generate a key pair
VirgilKeyPair keyPair = crypto.generateKeyPair();

// save a private key into key storage
privateKeyStorage.store(keyPair.getPrivateKey(), "Alice", null);

// publish user's card on the Cards Service
try {
    Card card = cardManager.publishCard(keyPair.getPrivateKey(), keyPair.getPublicKey(), "Alice");
    // Card is created
} catch (Exception e) {
    // Error occured
}
```

### Sign then encrypt data

Virgil Core SDK allows you to use a user's private key and their Virgil Cards to sign and encrypt any kind of data.

In the following example, we load a private key from a customized key storage and get recipient's Card from the Virgil Cards Service. Recipient's Card contains a public key which we will use to encrypt the data and verify a signature.

```java
import com.virgilsecurity.crypto.VirgilCrypto;

VirgilCrypto crypto = new VirgilCrypto();

// prepare a message
String messageToEncrypt = "Hello, Bob!";
byte[] dataToEncrypt = ConvertionUtils.toBytes(messageToEncrypt);

// prepare a user's private key
Tuple<PrivateKey, Map<String, String>> alicePrivateKeyEntry =
        privateKeyStorage.load("Alice");
VirgilPrivateKey alicePrivateKey =
        (VirgilPrivateKey) alicePrivateKeyEntry.getLeft();

// using cardManager search for user's cards on Cards Service
try {
    List<Card> cards = cardManager.searchCards("Bob");
    // Cards are obtained
    List<VirgilPublicKey> bobRelevantCardsPublicKeys = new ArrayList<>();
    for (Card card : cards) {
        if (!card.isOutdated()) {
            bobRelevantCardsPublicKeys.add(
                    (VirgilPublicKey) card.getPublicKey());
        }
    }
    // sign a message with a private key then encrypt on a public key
    byte[] encryptedData = crypto.signThenEncrypt(dataToEncrypt,
            alicePrivateKey, bobRelevantCardsPublicKeys);
} catch (CryptoException | VirgilServiceException e) {
    // Error occured
}
```

### Decrypt data and verify signature

Once the user receives the signed and encrypted message, they can decrypt it with their own private key and verify the signature with the sender's Card:

```java
import com.virgilsecurity.crypto.VirgilCrypto;

VirgilCrypto crypto = new VirgilCrypto();

// prepare a user's private key
Tuple<PrivateKey, Map<String, String>> bobPrivateKeyEntry =
        privateKeyStorage.load("Bob");
VirgilPrivateKey bobPrivateKey =
        (VirgilPrivateKey) bobPrivateKeyEntry.getLeft();

try {
    // using cardManager search for user's cards on Cards Service
    List<Card> cards = cardManager.searchCards("Alice");
    // Cards are obtained
    List<VirgilPublicKey> aliceRelevantCardsPublicKeys = new ArrayList<>();
    for (Card card : cards) {
        if (!card.isOutdated()) {
            aliceRelevantCardsPublicKeys.add(
                    (VirgilPublicKey) card.getPublicKey());
        }
    }

    // decrypt with a private key and verify using a public key
    byte[] decryptedData = crypto.decryptThenVerify(encryptedData,
            bobPrivateKey, aliceRelevantCardsPublicKeys);
} catch (CryptoException | VirgilServiceException e) {
    // Error occured
}
```

### Get Card by its ID

Use the following lines of code to get a user's card from Virgil Cloud by its ID:

```java
// using cardManager get a user's card from the Cards Service
try {
    Card card = cardManager.getCard("f4bf9f7fcbedaba0392f108c59d8f4a38b3838efb64877380171b54475c2ade8");
    // Card is obtained
} catch (CryptoException | VirgilServiceException e) {
    // Error occured
}
```

### Get Card by user's identity

For a single user, use the following lines of code to get a user's Card by a user's `identity`:

```java
try {
    List<Card> cards = cardManager.searchCards("Bob");
    // Cards are obtained
} catch (CryptoException | VirgilServiceException e) {
    // Error occured
}
```

## Run benchmarks

Build artifacts with a command
```bash
mvn clean install -DskipTests
```

A JAR file with benchmarks and all dependencies will be build. You can find it at `/benchmark/target/benchmark.jar`.
You can copy this JAR file to any other machine with install JRE and run with a command
```bash
java -jar <path_to_jar>
```

## Docs

Virgil Security has a powerful set of APIs, and the [Developer Documentation](https://developer.virgilsecurity.com/) can get you started today.

## License

This library is released under the [3-clause BSD License](LICENSE).

## Support

Our developer support team is here to help you. Find out more information on our [Help Center](https://help.virgilsecurity.com/).

You can find us on [Twitter](https://twitter.com/VirgilSecurity) or send us email<EMAIL_ADDRESS>
Also, get extra help from our support team on [Slack](https://virgilsecurity.com/join-community).

repository: VirgilSecurity/virgil-sdk-java-android

gha_language: Java

repo_name: VirgilSecurity/virgil-sdk-java-android


text:
Static Analysis Algorithms with Haskell
----

The code is written for practice purpose during the author's learning of *Principles of Program Analysis* [[1]](#ppa).

Honestly speaking, this book is not very good for learning something about program analysis, esp. for newbies. Actually, I went through the [CMU's course](https://www.cs.cmu.edu/~aldrich/courses/15-819O-13sp/) sometime earlier. But I also believe that, there is no easy way to learn, just easier a bit maybe if you got right.

Although it is just for practice, I will try to make the library as modular as possible and the code quality as high as possible.

Why Haskell? First, I have been programming with it for almost a year and will be less distracted when implementing something complex with it. Second, the polymorphism and type class can make things as abstract as possible, while reducing the pain of programming.

### Modules
* Data Flow Analaysis: `Language.DFA`
    + Monotone Framework: `Language.DFA.Core.Mono`
    + Intra-procedural Analysis:
        + Reaching Definition Analysis: `Language.DFA.Packages.RDA`
        + Available Expressions Analysis: `Language.DFA.Packages.AEA`
        + Very Busy Expressions Analysis: `Language.DFA.Packages.VBEA`
        + Live Variable Analysis: `Language.DFA.Packages.LVA`
    + Inter-procedural Analysis:
        + Detection of Sign Analysis: `Language.DFA.Packages.DSA`

## TODOs
1. Test inter-procedural analysis with the recursive function
2. Abstract 0-CFA Analysis

### References
1.

Flemming Nielson, Hanne R. Nielson, and Chris Hankin. 1999. Principles of Program Analysis. Springer-Verlag New York, Inc., Secaucus, NJ, USA.

repository: izgzhen/static-hs

repo_name: izgzhen/static-hs


text:
---
layout: post
status: publish
published: true
title: how to make apache scream (like a school girl)
author:
  display_name: stevecrozz
  login: stevecrozz
  email<EMAIL_ADDRESS>  url: http://lithostech.com
author_login: stevecrozz
author_email<EMAIL_ADDRESS>author_url: http://lithostech.com
wordpress_id: 35
date: '2008-08-15 20:46:21 -0700'
date_gmt: '2008-08-16 04:46:21 -0700'
categories:
- Uncategorized
tags:
- network adminstration
comments:
- id: 1
  author: ''
  author_email: ''
  author_url: ''
  date: '2008-08-22 18:21:38 -0700'
  date_gmt: ''
  content: This is really great writing.  Easy to keep in your head what is going
    on, what the big takeaway points are, etc.  Nice job!
---
{% responsive_image path: static/img/full/2008/school-girl.jpg alt:
"Young cheerleader screaming with hands in the air" class:
"img-float-left" %} I was investigating some web site slowness for a
friend the other day.  His company uses SugarCRM over https. He had been
complaining about slowness for over a year and I finally decided to give
it a thorough look. Since the sugar application makes heavy use of its
database backend, I decided to start there.  Unfortunately mySQL's slow
query log turned up nothing, except that the database was running about
as fast as you could possibly expect with the whole database buffered in
memory. I honestly didn't think to check the web server itself because
I've never really had a measurable problem with that before, default web
server settings have always suited me fine in the past. Apparently all
bets are off when running under SSL...

On a whim, I downloaded [YSlow](http://developer.yahoo.com/yslow/), a
firefox plugin developed by Yahoo! which I had heard about from a fellow
developer a few months ago. It gives your site a letter grade based on a
number of factors that contribute to site slowness. I had two major
improvements I could easily make, plus a number of small ones that I'd
like to do, but I'm not about to dive into sugar and restructure it.

<!--more-->

This web server runs some version of CentOS which has somehow become
very popular among hosting providers and apache 2.x with mod_php. Since
this was my first major stab at apache performance tuning, I decided to
fire up the [official documentation](http://httpd.apache.org/docs/2.0/)
which incidentally has a section on performance tuning. With the
documentation open in one window and httpd.conf open in another, I
started systematically disabling modules that I didn't think were being
used. After disabling a handful of modules, I'd force-reload apache and
check to see if anything had broken. This is what I ended up with:

~~~
LoadModule access_module modules/mod_access.so
#LoadModule auth_module modules/mod_auth.so
#LoadModule auth_anon_module modules/mod_auth_anon.so
#LoadModule auth_dbm_module modules/mod_auth_dbm.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule ldap_module modules/mod_ldap.so
#LoadModule auth_ldap_module modules/mod_auth_ldap.so
#LoadModule include_module modules/mod_include.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
#LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
#LoadModule usertrack_module modules/mod_usertrack.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule mime_module modules/mod_mime.so
#LoadModule dav_module modules/mod_dav.so
#LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule asis_module modules/mod_asis.so
#LoadModule info_module modules/mod_info.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
#LoadModule imap_module modules/mod_imap.so
#LoadModule actions_module modules/mod_actions.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule cache_module modules/mod_cache.so
#LoadModule suexec_module modules/mod_suexec.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule cgi_module modules/mod_cgi.so
~~~

I might be able to trim these run-time modules even further, but I was
already feeling satisfied here since I cut it down by about 50%, at
least in terms of sheer number of loaded modules. That was a good start,
and improved the memory footprint on each spawned apache process, but
didn't seem to make a noticeable performance difference which makes
sense because the server wasn't ever low on memory.

Just for the sake of comparison I hard-refreshed the front page a number
of times before running through the YSlow checklist. The page
consistently took 15-25 seconds to load.

YSlow revealed the big problems. The first suggestion was excellent.

### Make fewer HTTP requests

- This page has 19 external JavaScript files.
- This page has 7 external StyleSheets.
- The problem is, sugarCRM handles all this internally. Best case
  scenario, this should really be done in only two requests, but
  we're making 26 separate HTTP requests just for local javascripts
  and stylesheets. Of course, this is nowhere near as bad as [some
  sites I've seen](http://www.fresnobee.com). So I skipped that one
  because it'll be hard for me to implement in this instance, hoping
  I could still make a major difference.
### Use a CDN

Good idea, but my friend's company is cheap, really cheap. There's no
way they're about to shell out an extra dime for a good content delivery
network.

### Add an expires header

Now that's a practical and very easy thing to do. It turns out that many
web browsers are not as liberal with their caching policy over the https
schema. I added this snippet to the virtual host which informs the web
browser that it can hold onto a cached copy of these files for a little
while rather than requesting new ones on every page load. I decided on 7
days for javascript and stylesheets, and a month for images.

~~~ bash
ExpiresActive On
ExpiresByType text/css "access plus 7 days"
ExpiresByType text/javascript "access plus 7 days"
ExpiresByType application/x-javascript "access plus 7 days"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 month"
~~~

That one change made a drastic difference. After logging in, the
application home page used to weigh in at 704.8KiB in all. Most of this
stuff was being loaded on every single page view. Now (after priming the
cache), its only 199.7. That's a 353% decrease in the amount of data
that must be loaded. That number alone is huge, but the performance
increases are far beyond that because of the way browsers handle
concurrent downloads, and especially concurrent javascript loading.

### Gzip components

This is one that really suprised me. I had no idea that gzipping
components could make such a drastic difference. I had always thought
that gzipping site components was only for trying to squeeze every last
ounce of performance out of low-bandwidth connections. It turns out that
enabling gzip compression on a few key files took their effective sizes
down by about an order of magnitude. Take for example the actual front
html page which was 199.7KiB during testing. Gzip was able to take it
down to 19.2KiB. Here are some magical statements straight from the
apache documentation:

~~~ bash
# Insert filter
SetOutputFilter DEFLATE
# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
# Don't compress images
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
~~~

This basically instructs apache to gzip everything except images while
respecting certain browser quirkiness. I don't care to research exactly
what all that Netscape 4.x quirkiness is about; I think I'll just trust
the apache doc writers. Maybe I'll just take that out actually because
seriously, who's using Netscape 4.x anyway?

Now cache-primed 19.2KiB front page loads are minuscule in when compared
with the former 704.8KiB behemoths, and let me tell you, this web site
is screaming now. The front page loads take anywhere from 0.5-4 seconds.
I'm not sure why that range is so large, but I am sure that the CRM
users will be much happier the next time they log in.

gha_language: Ruby


text:
# iam-service release checklist

* Make sure all changes are committed and pushed.
* Make sure the documentation is up-to date.
* Make sure all tests are passing.
* ``NEW_RELEASE_VERSION=1.2.0-SNAPSHOT``
* Upgrade component version in script below.
  ```
  ./version-upgrade.sh
  ```
* Test all iam-service components locally.
  ```
  cd release
  ./create-release.sh
  cd ..
  ```
* Commit changes related to version upgrade.
* Create release tag and push the tag to origin.
  ```
  git tag -l
  git tag RELEASE_<NEW_RELEASE_VERSION>
  git push origin --tags
  ```
* Create new release on [github](https://github.com/jveverka/iam-service/releases)
  * Make sure Release notes are up-to-date.
  * Upload released binary
    ```
    build/iam-service-release-<NEW_RELEASE_VERSION>.zip
    ```
* Publish artefacts to as [described here](https://central.sonatype.org/pages/gradle.html).
  ```
  gradle uploadArchives
  ```

repository: GuilleOr/iam-service

repo_name: GuilleOr/iam-service


text:
# Applications

What do we do now ?

------

## Consumer Applications of Object Detection

Group photo face recognition
Convenient (and scary)

------

## Consumer Applications of Object Detection
Clipdrop, a background removal photo app

------

## Industrial Applications of Object Detection

Autonomous vehicules

------

## Industrial Applications of Object Detection

Logistics

[https://www.logivations.com/en/solutions/agv/camera_identification.php](https://www.logivations.com/en/solutions/agv/camera_identification.php)


text:
# Spirent Test Center Management Driver
This requires access to the STC Lab Server. The driver connects to an STC chassis via the lab server to discover what modules are installed and determine if the chassis is online or offline. The driver is not able to detect link on each port.
This driver requires a property called STC_Lab_Server to be present in the resource's template. The value of this property is the IP address or hostname of the STC Lab Server.

 <b>Tags:</b> Test Equipment, Traffic Generator

repository: mbarfiel/Velocity-assets

repo_name: mbarfiel/Velocity-assets


text:
# Stratified Flow over Rough Bottom Topography
Python post-processing codes for simulations reported in "Near-inertial dissipation due to stratified flow over abyssal topography" by Zemskova, V.E. and Grisouard, N.

## Post-processing example
* Found in postprocess_example.py
* Shows how to extract grid, velocity, and buoyancy fields from a Nek5000 output file (.f*)
* Shows how to compute height-above-bottom (HAB) coordinates for a given topographic height and width
* Shows how to compute kinetic energy dissipation in volume
* Shows how to average a field in HAB coordinates for Nek5000 curved grid


text:
# SocketLite - .NET Standard

[![NuGet Badge](https://buildstats.info/nuget/SocketLite.PCL)](https://www.nuget.org/packages/SocketLite.PCL)

[![.NET Standard](http://img.shields.io/badge/.NET_Standard-v2.0-red.svg)](https://docs.microsoft.com/da-dk/dotnet/articles/standard/library)

*Please star this project if you find it useful. Thank you.*

### No longer updated or supported
With the level of maturity .NET Standard have reached, I don't see the real need for this library anymore. Also, the library have turned into a bit of a mess.

If you think you need this library please consider if maybe there's a smarter way to accomplish what you need to accomplish.

### Supports Xamarin Forms on Windows 10/UWP (16299 and later), iOS, Android, and .NET Standard from 2.0

This project is a fork that build upon the fantastic work done with [Socket for PCL](https://github.com/rdavisau/sockets-for-pcl).

## Why this fork?
Two reasons:

 1. The original Socket for PCL delivers great broad cross-platform
    support. SocketLite PCL only covers .NET 4.5+, UWP, iOS and Android.

 2. SocketLite has been refactored to use Reactive Extensions (Rx).

The purpose of this PCLis to make it easy to write cross platform socket code. For example [Simple Http Listener](https://github.com/1iveowl/Simple-Http-Listener-PCL) is written using SocketLite.PCL

This library is based on "Bait and Switch" pattern. It is strongly recommend to read this short and great blog post to get an good understanding of this pattern before contributing to the SocketLite PCL code-base: [The Bait and Switch PCL Trick](http://log.paulbetts.org/the-bait-and-switch-pcl-trick/)

Get SocketLite.PCL in NuGet: ````Install-Package SocketLite.PCL````

### Version 5.0
Version 5.0 updated System.Reactive to version 4.0.0
.NET is support from version 4.6 and later.

.NET Standard 1.3 amd 1.5 is no longer part of the library, only .NET Standard 2.0 and later is supported.

### Version 4.0
Version 4.0 represents a major overhaul of this library. Version 4.0 is still backwards compatible, but many of the methods have been marked as deprecated to inspire developers to use the newer versions of this library. In previous versions you had to subscribe to an observable and then start the action. In version 4.0 you just subscribe, that's it. Much more clean and better aligned with the Rx patterns.

There is still UWP support in version 4.0, but the emphasis has been on .NET Core and it will be going forward.

### Classes
The plugin currently provides the following socket abstractions:

Class|Description|.NET|Windows 10 / UWP
-----|-----------|:--------------:|:---------------:
**TcpSocketListener** | Bind to a port and accept TCP socket connections. | TcpListener | StreamSocketListener
**TcpSocketClient** | Connect to a TCP endpoint with bi-directional communication. | TcpClient | StreamSocket
**UdpSocketReceiver** | Bind to a port and receive UDP messages. | UdpClient | DatagramSocket
**UdpSocketClient** | Send messages to arbitrary endpoints over UDP. | UdpClient | DatagramSocket
**UdpSocketMulticastClient** | Send and receive UDP messages within a multicast group. | UdpClient | DatagramSocket

### Examples Usage

#### Using

```csharp
using SocketLite.Model;
using SocketLite.Services;
```

**IMPORTANT**: Please notice that the parameter `allowMultipleBindToSamePort` will only work on Windows. On other platforms it should be set to `false`.

#### Specify Which Network Interface To Use
Defining what Network Interface to use is typically the version first step. This can be done on multiple ways. Here it is done using the IP adress of the interface:

```csharp
var communicationInterface = new CommunicationsInterface();
var allInterfaces = communicationInterface.GetAllInterfaces();
var networkInterface = allInterfaces.FirstOrDefault(x => x.IpAddress == "<IP_ADDRESS>");
```

##### A TCP Listener
```csharp
var tcpListener = new TcpSocketListener();

var observerTcpListner = await tcpListener.CreateObservableListener(
    port:8000,
    listenOn: networkInterface,
    allowMultipleBindToSamePort:false);

var subscriberTcpListener = observerTcpListner.Subscribe(
    tcpClient =>
    {
        //Insert your code here
    },
    ex =>
    {
        // Insert your exception code here
    },
    () =>
    {
        // Insert your completed code here
    });
```

##### A TCP Client
```csharp
var tcpClient = new TcpSocketClient();
await tcpClient.ConnectAsync("<IP_ADDRESS>", "1234");

var helloWorld = "Hello World!";

var bytes = Encoding.UTF8.GetBytes(helloWorld);
await tcpClient.WriteStream.WriteAsync(bytes, 0, bytes.Length);
tcpClient.Disconnect();
```
###### Tip: What About Multi Threading?
The TcpSocketClient WriteStream property is of type ```System.IO.Stream```, which does not automatically manage multi-treading.

To work around this limitation you can do something like the following example, which have been inspired by this Stack Overflow post: [SslStream.WriteAsync “The BeginWrite method cannot be called when another write operation is pending”](http://stackoverflow.com/a/12649107/4140832)

```csharp

private readonly ConcurrentQueue<byte[]> _writePendingData = new ConcurrentQueue<byte[]>();
private bool _sendingData;

private async Task SendAsync(ITcpSocketClient tcpSocketClient, byte[] frame)
{
    if (!tcpSocketClient.IsConnected)
    {
        throw new Exception("Websocket connection have been closed");
    }

    await WriteQueuedStreamAsync(tcpSocketClient, frame);
}

private async Task WriteQueuedStreamAsync(ITcpSocketClient tcpSocketClient, byte[] frame)
{
    if (frame == null)
    {
        return;
    }

    _writePendingData.Enqueue(frame);

    lock (_writePendingData)
    {
        if (_sendingData)
        {
            return;
        }
        _sendingData = true;
    }

    try
    {
        if (_writePendingData.Count > 0 && _writePendingData.TryDequeue(out byte[] buffer))
        {
            await tcpSocketClient.WriteStream.WriteAsync(buffer, 0, buffer.Length);
            await tcpSocketClient.WriteStream.FlushAsync();
        }
        else
        {
            lock (_writePendingData)
            {
                _sendingData = false;
            }
        }
    }
    catch (Exception)
    {
        // handle exception then
        lock (_writePendingData)
        {
            _sendingData = false;
        }
    }
    finally
    {
        lock (_writePendingData)
        {
            _sendingData = false;
        }
    }
}
```

##### A UDP Receiver
```csharp
var udpReceiver = new UdpSocketReceiver();

var observerUdpReceiver = await udpReceiver.ObservableUnicastListener(
    port: 1900,
    communicationInterface: networkInterface,
    allowMultipleBindToSamePort: false);

var subscriberUpdReceiver = observerUdpReceiver.Subscribe(
    udpMsg =>
    {
        System.Console.WriteLine($"Udp package received: {udpMsg.RemoteAddress}:{udpMsg.RemotePort}");
    },
    ex =>
    {
        //Inset your exception code here
    },
    () =>
    {
        //Insert your completion code here
    });
```

##### A UDP Client
```csharp
var udpReceiver = new UdpSocketReceiver();

var observerUdpReceiver = await udpReceiver.CreateObservableListener(
    port: 8000,
    communicationInterface: networkInterface,
    allowMultipleBindToSamePort: false);

var subscriberUpdReceiver = observerUdpReceiver.Subscribe(
    udpMsg =>
    {
        //Inset your code here
    },
    ex =>
    {
        //Inset your exception code here
    },
    () =>
    {
        //Insert your completion code here
    });

// Fire datagram into the great void
await udpClient.SendToAsync(bytes, bytes.Length, address:"<IP_ADDRESS>", port:1234);
```

##### A Multicast UDP Client
```csharp
var udpMulticast = new SocketLite.Services.UdpSocketMulticastClient();
await udpMulticast.JoinMulticastGroupAsync("<IP_ADDRESS>", 1900, allowMultipleBindToSamePort:true); //Listen for UPnP activity on local network.

// Listen part
var udpMulticast = new UdpSocketMulticastClient();

var observerUdpMulticast = await udpMulticast.ObservableMulticastListener(
    "<IP_ADDRESS>",
    1900,
    networkInterface,
    allowMultipleBindToSamePort: false);

var subscriberUdpMilticast = observerUdpMulticast.Subscribe(
    udpMsg =>
    {
        System.Console.WriteLine($"Udp package received: {udpMsg.RemoteAddress}:{udpMsg.RemotePort}");
    },
    ex =>
    {
        //Insert your exception code here
    },
    () =>
    {
        //Insert your completion code here
    });
```
You can also add or drop multicast addresses on the Multicast listeren using: `MulticastAddMembership(string ipLan, string mcastAddress)` and `MulticastDropMembership(string ipLan, string mcastAddress)`

Note: A UDP Multicast Client also listen to any other UDP send directly to the specified port. So if you need a UDP Client and a UDP Multicast Listener on the same port, all you need to do is to create one UDP Multicast Listener.

repository: xsjames/SocketLite

repo_name: xsjames/SocketLite


text:
# spiritdev_apps_manager
Spiritdev Apps Manager is a demo project to demonstrate the interaction between a RESTful web service and a rich client application.

The server was built with ASP.NET Core 3.1, the client with Angular 9.

The client application communicates with the server via CRUD operations (CREATE, READ, UPDATE, DELETE). DTO objects are used to exchange data between client and server.

Features of the client app: Angular 9, RxJS, NGXS, Angular Material and Angular Flex.

Features of the server app: ASP.NET Core 3.1, Entity Framework.

The client application was developed with Visual Studio code. A proxy server was used to test the communication during development. To start the demo app, open the application with Visual Studio code and start the app with the command 'npm start'. This ensures that certain remaining calls are forwarded to the ASP.NET server via the proxy server.

The server application was developed with Visual Studio 2019 (Community Edition). The server should start without problems from the IDE.

gha_language: TypeScript