text:
# particles-awscode

[![condensation-image][condensation-image]][condensation-url]

[![NPM][npm-image]][npm-url]
[![Gitter][gitter-image]][gitter-url]

## Summary

[Condensation][condensation-url] particles AWS CodeCommit, CodeBuild, and CodePipeline.

## Particles
* cftemplates
* metadata
* parameters
* partials
* resources
* sets

## cftemplates

### Buckets

Creates source code and artifict buckets for AWS CodeBuild and AWS
CodePipeline

|region|launch|
|------|------|
|us-east-1|[![Launch Stack][launch-stack-image]][buckets-stack-us-east-1-url]|
|us-east-2|[![Launch Stack][launch-stack-image]][buckets-stack-us-east-2-url]|
|us-west-1|[![Launch Stack][launch-stack-image]][buckets-stack-us-west-1-url]|
|us-west-2|[![Launch Stack][launch-stack-image]][buckets-stack-us-west-2-url]|
|ap-northeast-1|[![Launch Stack][launch-stack-image]][buckets-stack-ap-northeast-1-url]|
|ap-southeast-1|[![Launch Stack][launch-stack-image]][buckets-stack-ap-southeast-1-url]|
|ap-southeast-2|[![Launch Stack][launch-stack-image]][buckets-stack-ap-southeast-2-url]|
|eu-central-1|[![Launch Stack][launch-stack-image]][buckets-stack-eu-central-1-url]|
|eu-west-1|[![Launch Stack][launch-stack-image]][buckets-stack-eu-west-1-url]|
|eu-west-2|[![Launch Stack][launch-stack-image]][buckets-stack-eu-west-2-url]|
|ca-central-1|[![Launch Stack][launch-stack-image]][buckets-stack-ca-central-1-url]|

### CodeBuild S3

Create a CodeBuild Project that uses S3 as the source

|region|launch|
|------|------|
|us-east-1|[![Launch Stack][launch-stack-image]][codebuilds3-stack-us-east-1-url]|
|us-east-2|[![Launch Stack][launch-stack-image]][codebuilds3-stack-us-east-2-url]|

---

## License
Apache-2.0 ©

[condensation-image]: https://raw.githubusercontent.com/SungardAS/condensation/master/docs/images/condensation_logo.png
[condensation-url]: https://github.com/SungardAS/condensation
[npm-image]: https://badge.fury.io/js/particles-awscode.svg
[npm-url]: https://npmjs.org/package/particles-awscode
[gitter-image]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/SungardAS/condensation?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge

[launch-stack-image]: https://s3.amazonaws.com/cloudformation-examples/cloudformation-launch-stack.png
[buckets-stack-us-east-1-url]: https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.us-east-1/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-us-east-2-url]: https://console.aws.amazon.com/cloudformation/home?region=us-east-2#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.us-east-2/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-us-west-1-url]: https://console.aws.amazon.com/cloudformation/home?region=us-west-1#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.us-west-1/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-us-west-2-url]: https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.us-west-2/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-ap-northeast-1-url]: https://console.aws.amazon.com/cloudformation/home?region=ap-northeast-1#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.ap-northeast-1/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-ap-southeast-1-url]: https://console.aws.amazon.com/cloudformation/home?region=ap-southeast-1#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.ap-southeast-1/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-ap-southeast-2-url]: https://console.aws.amazon.com/cloudformation/home?region=ap-southeast-2#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.ap-southeast-2/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-eu-central-1-url]: https://console.aws.amazon.com/cloudformation/home?region=eu-central-1#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.eu-central-1/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-eu-west-1-url]: https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.eu-west-1/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-eu-west-2-url]: https://console.aws.amazon.com/cloudformation/home?region=eu-west-2#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.eu-west-2/particles-awscode/master/particles/cftemplates/buckets.template.json
[buckets-stack-ca-central-1-url]: https://console.aws.amazon.com/cloudformation/home?region=ca-central-1#/stacks/new?stackName=awscode-buckets&templateURL=https://s3.amazonaws.com/condensation-particles.eu-central-1/particles-awscode/master/particles/cftemplates/buckets.template.json
[codebuilds3-stack-us-east-1-url]: https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/new?stackName=codebuild&templateURL=https://s3.amazonaws.com/condensation-particles.us-east-1/particles-awscode/master/particles/cftemplates/codebuild_s3.template.json
[codebuilds3-stack-us-east-2-url]: https://console.aws.amazon.com/cloudformation/home?region=us-east-2#/stacks/new?stackName=codebuild&templateURL=https://s3.amazonaws.com/condensation-particles.us-east-2/particles-awscode/master/particles/cftemplates/codebuild_s3.template.json


text:
---
layout: post
category: blog
title: Muhammara
excerpt:
modified: 2022-08-07
tags: [dip, spread, middleeast]
comments: false
---

- 3-4 Tbsp Aleppo pepper soaked in some water
- 2 Tbsp bread crumbs
- 1 cup chopped walnuts
- 1-2 tsp ground cumin
- 2-3 tsp pomegranate syrup or 1Tbsp lemon juice +1/2 tsp sugar
- some salt

put all the ingredients in a food processor and pulse while drizzling up to 1/2 cup of water, until a soft paste forms.

spread in a dish and drizzle with some olive oil. you can add 1/2 tsp or more cayenne pepper if you like it spicier.
good side dish with chips, and sublime with roasted chicken.
hope you and Sally are well, and maybe will see you on our next visit the end of July.

#### Source
Abdallah Zamaria

#### Notes

license: MIT

branch_name: refs/heads/master

extension: md

gha_language: HTML

gha_license_id: MIT

license_type: permissive


text:
# ExecutionPolicy

Have you ever wondered what would happen if you would execute `Action` very fast 1 after another?
For example:

```kotlin
spec {
    inState<FooState> {
        on<BarAction> { action, state : State<FooState> ->
            delay(5000) // wait for 5 seconds
            state.override { OtherState() }
        }
    }
}
```

The example above shows a problem with async. state machines like FlowRedux:
If our state machine is in `FooState` and a `BarAction` got triggered, we wait for 5 seconds and then set the state to another state.
What if while waiting 5 seconds (i.e. let's say after 3 seconds of waiting) another `BarAction` gets
triggered.
That is possible, right?
With `ExecutionPolicy` you can specify what should happen in that case.
There are three options to choose from:

- `CANCEL_PREVIOUS`: **This is the default one automatically applied unless specified otherwise.** It would cancel any previous execution and just run the latest one. In the example mentioned it means the previous still running `BarAction` handler gets canceled and a new one with the laster `BarAction` starts.
- `UNORDERED`: Choosing this causes all the blocks to continue running but there are no guarantees in which order. For example:

    ```kotlin
    spec {
        inState<FooState> {
            on<BarAction>(executionPolicy = FlapMapPolicy.UNORDERED) { _, state : State<FooState> ->
                delay(randomInt()) // wait for some random time
                state.override { OtherState }
            }
        }
    }
    ```

    Let's assume that we trigger `BarAction` two times.
    We use random amount of seconds for waiting.
    Since we use `UNORDERED` as policy `on<BarAction>` the handler block gets executed 2 times without canceling the previous one (that is the difference  to `CANCEL_PREVIOUS`).
    Moreover, `UNORDERED` doesn't make any promise on order of execution of the block (see `ORDERED` if you need promises on order).
    If `on<BarAction>` gets executed two times it will run in parallel and the the second execution
    could complete before the first execution (because using a random time of waiting).

- `ORDERED`: In contrast to `UNORDERED` and `CANCEL_PREVIOUS`, `ORDERED` will not run `on<BarAction>` in parallel and will not cancel any previous execution. Instead, `ORDERED` will preserve the order.

`on<Action>` and `collectWhileInstate()` can specify an `ExecutionPolicy`:

- `on<Action>(executionPolicy = ExecutionPolicy.CANCEL_PREVIOUS) { ... }`
- `collectWhileInState(executionPolicy = ExecutionPolicy.CANCEL_PREVIOUS) { ... }`

Please note that `onEnter` doesn't have the option to specify `ExecutionPolicy`.

repository: freeletics/FlowRedux

branch_name: refs/heads/main

gha_language: Kotlin

repo_name: freeletics/FlowRedux


text:
---
slug: more-incoming-students-coming-from-the-region
title: "More incoming students coming from the region"
date: January 01 2020
---

  The number of CSUMB students from the tri-county area increased in Fall 2010.
  Residents of Monterey, Santa Cruz and San Benito counties now make up 33
  percent of enrollment, compared with 31 percent last year. Northern California
  and Southern California each supply approximately another third of students.

  Total enrollment is 4,790 this semester, including 829 freshmen and 490 new
  transfer students. This year’s incoming class has a grade-point average of
  3.25, up slightly from last year.

repository: csumb-archives/news-gatsby

gha_language: JavaScript

repo_name: csumb-archives/news-gatsby


text:
# Redis Data Types

Redis is not aplainkey-value store, it is actually adata structures server, supporting different kinds of values. What this means is that, while in traditional key-value stores you associate string keys to string values, in Redis the value is not limited to a simple string, but can also hold more complex data structures. The following is the list of all the data structures supported by Redis

- **Binary-safe strings**
- **Lists:** collections of string elements sorted according to the order of insertion. They are basicallylinked lists.
- **Sets:** collections of unique, unsorted string elements.
- **Sorted sets,** similar to Sets but where every string element is associated to a floating number value, calledscore. The elements are always taken sorted by their score, so unlike Sets it is possible to retrieve a range of elements (for example you may ask: give me the top 10, or the bottom 10).
- **Hashes,** which are maps composed of fields associated with values. Both the field and the value are strings. This is very similar to Ruby or Python hashes.
- **Bit arrays (or simply bitmaps):** it is possible, using special commands, to handle String values like an array of bits: you can set and clear individual bits, count all the bits set to 1, find the first set or unset bit, and so forth.
- **HyperLogLogs:** this is a probabilistic data structure which is used in order to estimate the cardinality of a set.
- **Streams:** append-only collections of map-like entries that provide an abstract log data type.

## Redis Lists

Redis lists are implemented via Linked Lists. This means that even if you have millions of elements inside a list, the operation of adding a new element in the head or in the tail of the list is performedin constant time. The speed of adding a new element with the [LPUSH](https://redis.io/commands/lpush) command to the head of a list with ten elements is the same as adding an element to the head of list with 10 million elements.
Redis Lists are implemented with linked lists because for a database system it is crucial to be able to add elements to a very long list in a very fast way. Redis Lists can be taken at constant length in constant time.
When fast access to the middle of a large collection of elements is important, there is a different data structure that can be used, called sorted sets. Sorted sets will be covered later in this tutorial.
The [LPUSH](https://redis.io/commands/lpush) command adds a new element into a list, on the left (at the head), while the [RPUSH](https://redis.io/commands/rpush) command adds a new element into a list, on the right (at the tail). Finally the [LRANGE](https://redis.io/commands/lrange) command extracts ranges of elements from lists:

```bash
> rpush mylist A
> lpush mylist first
> lrange mylist 0 -1
```

Note that [LRANGE](https://redis.io/commands/lrange) takes two indexes, the first and the last element of the range to return. Both the indexes can be negative, telling Redis to start counting from the end: so -1 is the last element, -2 is the penultimate element of the list, and so forth.
An important operation defined on Redis lists is the ability topop elements. Popping elements is the operation of both retrieving the element from the list, and eliminating it from the list, at the same time. You can pop elements from left and right, similarly to how you can push elements in both sides of the list:

```bash
> rpush mylist a b c
> rpop mylist
> lpop mylist
```

## Common use cases for lists

- Remember the latest updates posted by users into a social network.
- Communication between processes, using a consumer-producer pattern where the producer pushes items into a list, and a consumer (usually aworker) consumes those items and executed actions. Redis has special list commands to make this use case both more reliable and efficient.

## Capped Lists

Redis allows us to use lists as a capped collection, only remembering the latest N items and discarding all the oldest items using the [LTRIM](https://redis.io/commands/ltrim) command.
The [LTRIM](https://redis.io/commands/ltrim) command is similar to [LRANGE](https://redis.io/commands/lrange), butinstead of displaying the specified range of elementsit sets this range as the new list value. All the elements outside the given range are removed.
Note: while [LRANGE](https://redis.io/commands/lrange) is technically anO(N) command, accessing small ranges towards the head or the tail of the list is a constant time operation.

## Blocking operations on lists

Lists have a special feature that make them suitable to implement queues, and in general as a building block for inter process communication systems: blocking operations.
Imagine you want to push items into a list with one process, and use a different process in order to actually do some kind of work with those items. This is the usual producer / consumer setup, and can be implemented in the following simple way:

- To push items into the list, producers call [LPUSH](https://redis.io/commands/lpush).
- To extract / process items from the list, consumers call [RPOP](https://redis.io/commands/rpop).
However it is possible that sometimes the list is empty and there is nothing to process, so [RPOP](https://redis.io/commands/rpop) just returns NULL. In this case a consumer is forced to wait some time and retry again with [RPOP](https://redis.io/commands/rpop). This is calledpolling, and is not a good idea in this context because it has several drawbacks:

1. Forces Redis and clients to process useless commands (all the requests when the list is empty will get no actual work done, they'll just return NULL).

2. Adds a delay to the processing of items, since after a worker receives a NULL, it waits some time. To make the delay smaller, we could wait less between calls to [RPOP](https://redis.io/commands/rpop), with the effect of amplifying problem number 1, i.e. more useless calls to Redis.
So Redis implements commands called [BRPOP](https://redis.io/commands/brpop) and [BLPOP](https://redis.io/commands/blpop) which are versions of [RPOP](https://redis.io/commands/rpop) and [LPOP](https://redis.io/commands/lpop) able to block if the list is empty: they'll return to the caller only when a new element is added to the list, or when a user-specified timeout is reached.
This is an example of a [BRPOP](https://redis.io/commands/brpop) call we could use in the worker:

```bash
> brpop tasks 5

1) "tasks"
2) "do_something"
```

It means: "wait for elements in the listtasks, but return if after 5 seconds no element is available".
Note that you can use 0 as timeout to wait for elements forever, and you can also specify multiple lists and not just one, in order to wait on multiple lists at the same time, and get notified when the first list receives an element.
A few things to note about [BRPOP](https://redis.io/commands/brpop):

1. Clients are served in an ordered way: the first client that blocked waiting for a list, is served first when an element is pushed by some other client, and so forth.

2. The return value is different compared to [RPOP](https://redis.io/commands/rpop): it is a two-element array since it also includes the name of the key, because [BRPOP](https://redis.io/commands/brpop) and [BLPOP](https://redis.io/commands/blpop) are able to block waiting for elements from multiple lists.

3. If the timeout is reached, NULL is returned.
There are more things you should know about lists and blocking ops. We suggest that you read more on the following:

- It is possible to build safer queues or rotating queues using [RPOPLPUSH](https://redis.io/commands/rpoplpush).
- There is also a blocking variant of the command, called [BRPOPLPUSH](https://redis.io/commands/brpoplpush).

## Automatic creation and removal of keys

So far in our examples we never had to create empty lists before pushing elements, or removing empty lists when they no longer have elements inside. It is Redis' responsibility to delete keys when lists are left empty, or to create an empty list if the key does not exist and we are trying to add elements to it, for example, with [LPUSH](https://redis.io/commands/lpush).
This is not specific to lists, it applies to all the Redis data types composed of multiple elements -- Streams, Sets, Sorted Sets and Hashes.
Basically we can summarize the behavior with three rules:

1. When we add an element to an aggregate data type, if the target key does not exist, an empty aggregate data type is created before adding the element.

2. When we remove elements from an aggregate data type, if the value remains empty, the key is automatically destroyed. The Stream data type is the only exception to this rule.

3. Calling a read-only command such as [LLEN](https://redis.io/commands/llen)(which returns the length of the list), or a write command removing elements, with an empty key, always produces the same result as if the key is holding an empty aggregate type of the type the command expects to find.

## Redis Hashes

Redis hashes look exactly how one might expect a "hash" to look, with field-value pairs:

```bash
> hmset user:1000 username antirez birthyear 1977 verified 1
OK
> hget user:1000 username
"antirez"
> hget user:1000 birthyear
"1977"
> hgetall user:1000

1) "username"
2) "antirez"
3) "birthyear"
4) "1977"
5) "verified"
6) "1"
```

While hashes are handy to representobjects, actually the number of fields you can put inside a hash has no practical limits (other than available memory)
The command [HMSET](https://redis.io/commands/hmset) sets multiple fields of the hash, while [HGET](https://redis.io/commands/hget) retrieves a single field.[HMGET](https://redis.io/commands/hmget) is similar to [HGET](https://redis.io/commands/hget) but returns an array of values:

```bash
> hmget user:1000 username birthyear no-such-field

1) "antirez"
2) "1977"
3) (nil)
```

There are commands that are able to perform operations on individual fields as well, like [HINCRBY](https://redis.io/commands/hincrby):

```bash
> hincrby user:1000 birthyear 10
(integer) 1987
> hincrby user:1000 birthyear 10
(integer) 1997
```

It is worth noting that small hashes (i.e., a few elements with small values) are encoded in special way in memory that make them very memory efficient.

## Redis Sets

Redis Sets are unordered collections of strings. The [SADD](https://redis.io/commands/sadd) command adds new elements to a set. It's also possible to do a number of other operations against sets like testing if a given element already exists, performing the intersection, union or difference between multiple sets, and so forth.

```bash
> sadd myset 1 2 3
(integer) 3
> smembers myset
```

1. 3
2. 1
3. 2

> sscan myset 0 match f*
Here I've added three elements to my set and told Redis to return all the elements. As you can see they are not sorted -- Redis is free to return the elements in any order at every call, since there is no contract with the user about element ordering.
Redis has commands to test for membership. For example, checking if an element exists:

```bash
> sismember myset 3
(integer) 1
> sismember myset 30
(integer) 0
```

"3" is a member of the set, while "30" is not.
Sets are good for expressing relations between objects. For instance we can easily use sets in order to implement tags.
There are other non trivial operations that are still easy to implement using the right Redis commands. For instance we may want a list of all the objects with the tags 1, 2, 10, and 27 together. We can do this using the [SINTER](https://redis.io/commands/sinter) command, which performs the intersection between different sets.
In addition to intersection you can also perform unions, difference, extract a random element, and so forth.

The command to extract an element is called [SPOP](https://redis.io/commands/spop), and is handy to model certain problems.
set command that provides the number of elements inside a set. This is often called thecardinality of a setin the context of set theory, so the Redis command is called [SCARD](https://redis.io/commands/scard).
When you need to just get random elements without removing them from the set, there is the [SRANDMEMBER](https://redis.io/commands/srandmember) command suitable for the task. It also features the ability to return both repeating and non-repeating elements.
| **Command** | **Example use and description**                                                                                |
|---------------|---------------------------------------------------------|
| SADD        | SADD key-name item [item ...]--- Adds the items to the set and returns the number of items added that weren't already present                                                                                |
| SREM        | SREM key-name item [item ...]--- Removes the items and returns the number of items that were removed                                                                                |
| SISMEMBER   | SISMEMBER key-name item - Returns whether the item is in the SET                                                                                |
| SCARD       | SCARD key-name - Returns the number of items in the SET                                                                                |
| SMEMBERS    | SMEMBERS key-name - Returns all of the items in the SET as a Python set                                                                                |
| SRANDMEMBER | SRANDMEMBER key-name [count]--- Returns one or more random items from the SET. When count is positive, Redis will return count distinct randomly chosen items, and when count is negative, Redis will return count randomly chosen items that may not be distinct. |
| SPOP        | SPOP key-name - Removes and returns a random item from the SET                                                                                |
| SMOVE       | SMOVE source-key dest-key item - If the item is in the source, removes the item from the source and adds it to the destination, returning if the item was moved                                                                                |
Operations for combining and manipulatingSETs in Redis

| **Command** | **Example use and description**                                                                                |
|-------------|-----------------------------------------------------------|
| SDIFF       | SDIFF key-name [key-name ...]--- Returns the items in the first SET that weren't in any of the other SETs (mathematical set difference operation)                              |
| SDIFFSTORE  | SDIFFSTORE dest-key key-name [key-name ...]--- Stores at the dest-key the items in the first SET that weren't in any of the other SETs (mathematical set difference operation) |
| SINTER      | SINTER key-name [key-name ...]--- Returns the items that are in all of the SETs (mathematical set intersection operation)                                                      |
| SINTERSTORE | SINTERSTORE dest-key key-name [key-name ...]--- Stores at the dest-key the items that are in all of the SETs (mathematical set intersection operation)                         |
| SUNION      | SUNION key-name [key-name ...]--- Returns the items that are in at least one of the SETs (mathematical set union operation)                                                    |
| SUNIONSTORE | SUNIONSTORE dest-key key-name [key-name ...]--- Stores at the dest-key the items that are in at least one of the SETs (mathematical set union operation)                       |

## Redis Sorted sets (ZSET)

Sorted sets are a data type which is similar to a mix between a Set and a Hash. Like sets, sorted sets are composed of unique, non-repeating string elements, so in some sense a sorted set is a set as well.
However while elements inside sets are not ordered, every element in a sorted set is associated with a floating point value, calledthe score(this is why the type is also similar to a hash, since every element is mapped to a value).
Moreover, elements in a sorted sets aretaken in order(so they are not ordered on request, order is a peculiarity of the data structure used to represent sorted sets). They are ordered according to the following rule:

- If A and B are two elements with a different score, then A > B if A.score is > B.score.
- If A and B have exactly the same score, then A > B if the A string is lexicographically greater than the B string. A and B strings can't be equal since sorted sets only have unique elements.
Implementation note: Sorted sets are implemented via a dual-ported data structure containing both a skip list and a hash table, so every time we add an element Redis performs anO(log(N))operation. That's good, but when we ask for sorted elements Redis does not have to do any work at all, it's already all sorted

```bash
> zadd hackers 1940 "Alan Kay"

> zrange hackers 0 -1

> zrevrange hackers 0 -1

> zrange hackers 0 -1 withscores

> zrangebyscore hackers -inf 1950

> zremrangebyscore hackers 1940 1960

> zrank hackers "Anita Borg"

> zrevrank hackers "Anita Borg"
```

| **Command**   | **What it does**                                                   |
|------------------|------------------------------------------------------|
| ZADD          | Adds member with the given score to the ZSET                       |
| ZRANGE        | Fetches the items in the ZSET from their positions in sorted order |
| ZRANGEBYSCORE | Fetches items in the ZSET based on a range of scores               |
| ZREM          | Removes the item from the ZSET, if it exists                       |- Expire an item in list after 2 mins

- Set expire on item if no new data comes then expire the whole key
- When inserting new data remove the data before 2 mins if available

```bash
zadd test_key<PHONE_NUMBER> test_value_1 (add an item to sortedset)

zadd test_key<PHONE_NUMBER> test_value_2 (add an item to sortedset)

zrangebyscore test_key<PHONE_NUMBER><PHONE_NUMBER> (to sortedset items)

zrangebyscore test_key<PHONE_NUMBER><PHONE_NUMBER> withscores (to sortedset items with score)

zremrangebyscore test_key<PHONE_NUMBER><PHONE_NUMBER> (to remove item)
```

## Lexicographical scores

With recent versions of Redis 2.8, a new feature was introduced that allows getting ranges lexicographically, assuming elements in a sorted set are all inserted with the same identical score (elements are compared with the Cmemcmpfunction, so it is guaranteed that there is no collation, and every Redis instance will reply with the same output).
The main commands to operate with lexicographical ranges are [ZRANGEBYLEX](https://redis.io/commands/zrangebylex), [ZREVRANGEBYLEX](https://redis.io/commands/zrevrangebylex), [ZREMRANGEBYLEX](https://redis.io/commands/zremrangebylex) and [ZLEXCOUNT](https://redis.io/commands/zlexcount).

## Updating the score: leader boards

Just a final note about sorted sets before switching to the next topic. Sorted sets' scores can be updated at any time. Just calling [ZADD](https://redis.io/commands/zadd) against an element already included in the sorted set will update its score (and position) withO(log(N)) time complexity. As such, sorted sets are suitable when there are tons of updates.
Because of this characteristic a common use case is leader boards. The typical application is a Facebook game where you combine the ability to take users sorted by their high score, plus the get-rank operation, in order to show the top-N users, and the user rank in the leader board (e.g., "you are the #4932 best score here").

## Bitmaps

Bitmaps are not an actual data type, but a set of bit-oriented operations defined on the String type. Since strings are binary safe blobs and their maximum length is 512 MB, they are suitable to set up to 232different bits.

Bit operations are divided into two groups: constant-time single bit operations, like setting a bit to 1 or 0, or getting its value, and operations on groups of bits, for example counting the number of set bits in a given range of bits (e.g., population counting).
Since bitmap operations don't have a data structure of their own, there isn't a special data structure to describe. The Redis strings themselves are implemented as a binary safe string. Redis string data structure is internally called Simple Dynamic String (SDS). It is essentially a nativechar []with some additional book keeping information.
One of the biggest advantages of bitmaps is that they often provide extreme space savings when storing information. For example in a system where different users are represented by incremental user IDs, it is possible to remember a single bit information (for example, knowing whether a user wants to receive a newsletter) of 4 billion of users using just 512 MB of memory.
Bits are set and retrieved using the [SETBIT](https://redis.io/commands/setbit) and [GETBIT](https://redis.io/commands/getbit) commands:

```bash
> setbit key 10 1
(integer) 1
> getbit key 10
(integer) 1
> getbit key 11
(integer) 0
```

The [SETBIT](https://redis.io/commands/setbit) command takes as its first argument the bit number, and as its second argument the value to set the bit to, which is 1 or 0. The command automatically enlarges the string if the addressed bit is outside the current string length.
[GETBIT](https://redis.io/commands/getbit) just returns the value of the bit at the specified index. Out of range bits (addressing a bit that is outside the length of the string stored into the target key) are always considered to be zero.
There are three commands operating on group of bits:

1. [BITOP](https://redis.io/commands/bitop) performs bit-wise operations between different strings. The provided operations are AND, OR, XOR and NOT.

2. [BITCOUNT](https://redis.io/commands/bitcount) performs population counting, reporting the number of bits set to 1.

3. [BITPOS](https://redis.io/commands/bitpos) finds the first bit having the specified value of 0 or 1.
Both [BITPOS](https://redis.io/commands/bitpos) and [BITCOUNT](https://redis.io/commands/bitcount) are able to operate with byte ranges of the string, instead of running for the whole length of the string. The following is a trivial example of [BITCOUNT](https://redis.io/commands/bitcount) call:

```bash
> setbit key 0 1
(integer) 0
> setbit key 100 1
(integer) 0
> bitcount key
(integer) 2
```

Common use cases for bitmaps are:

- Real time analytics of all kinds.
- Storing space efficient but high performance boolean information associated with object IDs.
For example imagine you want to know the longest streak of daily visits of your web site users. You start counting days starting from zero, that is the day you made your web site public, and set a bit with [SETBIT](https://redis.io/commands/setbit) every time the user visits the web site. As a bit index you simply take the current unix time, subtract the initial offset, and divide by the number of seconds in a day (normally, 3600*24).
This way for each user you have a small string containing the visit information for each day. With [BITCOUNT](https://redis.io/commands/bitcount) it is possible to easily get the number of days a given user visited the web site, while with a few [BITPOS](https://redis.io/commands/bitpos) calls, or simply fetching and analyzing the bitmap client-side, it is possible to easily compute the longest streak.

```bash
BITOP AND andbc b c

bitop not nota a

BITOP OR orbc b c

BITOP XOR xorbc b c
```

Bitmaps are trivial to split into multiple keys, for example for the sake of sharding the data set and because in general it is better to avoid working with huge keys. To split a bitmap across different keys instead of setting all the bits into a key, a trivial strategy is just to store M bits per key and obtain the key name withbit-number/M and the Nth bit to address inside the key withbit-number MOD M.

## HyperLogLogs

A HyperLogLog is a probabilistic data structure used in order to count unique things (technically this is referred to estimating the cardinality of a set). Usually counting unique items requires using an amount of memory proportional to the number of items you want to count, because you need to remember the elements you have already seen in the past in order to avoid counting them multiple times. However there is a set of algorithms that trade memory for precision: you end with an estimated measure with a standard error, which in the case of the Redis implementation is less than 1%. The magic of this algorithm is that you no longer need to use an amount of memory proportional to the number of items counted, and instead can use a constant amount of memory! 12k bytes in the worst case, or a lot less if your HyperLogLog (We'll just call them HLL from now) has seen very few elements.
HLLs in Redis, while technically a different data structure, are encoded as a Redis string, so you can call [GET](https://redis.io/commands/get) to serialize a HLL, and [SET](https://redis.io/commands/set) to deserialize it back to the server.
Conceptually the HLL API is like using Sets to do the same task. You would [SADD](https://redis.io/commands/sadd) every observed element into a set, and would use [SCARD](https://redis.io/commands/scard) to check the number of elements inside the set, which are unique since [SADD](https://redis.io/commands/sadd) will not re-add an existing element.
While you don't reallyadd itemsinto an HLL, because the data structure only contains a state that does not include actual elements, the API is the same:

- Every time you see a new element, you add it to the count with [PFADD](https://redis.io/commands/pfadd).
- Every time you want to retrieve the current approximation of the unique elementsaddedwith [PFADD](https://redis.io/commands/pfadd) so far, you use the [PFCOUNT](https://redis.io/commands/pfcount).

```bash
> pfadd hll a b c d
(integer) 1
> pfcount hll
(integer) 4
```

An example of use case for this data structure is counting unique queries performed by users in a search form every day.
Redis is also able to perform the union of HLLs

## Other Features

- It is possible to [iterate the key space of a large collection incrementally](https://redis.io/commands/scan).
- It is possible to run [Lua scripts server side](https://redis.io/commands/eval) to improve latency and bandwidth.
- Redis is also a [Pub-Sub server](https://redis.io/topics/pubsub).
<https://redis.io/topics/data-types-intro>

## Redis single-‐argument commands and their corresponding multi-‐argument alternatives

| **Single-‐Argument Command** | **Single-‐Argument Description**  | **Multi-‐Argument Alternative** | **Multi-‐Argument Description**             |
|---------------|------------------------|---------------|------------------|
| **SET**                      | Set the value of a key            | MSET                            | Set multiple keys to multiple values        |
| **GET**                      | Get the value of a key            | MGET                            | Get the values of all the given keys        |
| **LSET**                     | Set value of an element in a list | LPUSH, RPUSH                    | Prepend/append multiple values to a list    |
| **LINDEX**                   | Get an element from a list        | LRANGE                          | Get a range of elements from a list         |
| **HSET**                     | Set the string value of a hash    | HMSET                           | Set multiple hash fields to multiple values |
| **HGET**                     | Get the value of a hash field     | HMGET                           | Get the values of all the given hash fields |

## Pipeline commands

Another way to reduce latency associated with high command volume is to pipeline several commands together so that you reduce latency due to network usage. Rather than sending 10 client commands to the Redis server individually and taking the network latency hit 10 times, pipelining the commands will send them all at once and pay the network latency cost only once. Pipelining commands is supported by the Redis server and by most clients. This is only beneficial if network latency is significantly larger than your instance's
![image](../../../media/Redis_Redis-Data-Types-image1.jpg)
<https://redis.io/topics/pipelining>

## Redis commands with high time complexity

| **Command**     | **Description**                                 | **Improve Performance By**                                                                   |
|--------------|------------------------------|-----------------------------|
| **ZINTERSTORE** | intersect multiple sorted sets and store result | reducing the number of sets and/or the number of elements in resulting set                   |
| **SINTERSTORE** | intersect multiple sets and store result        | reducing size of smallest set and/or the number of sets                                      |
| **SINTER**      | intersect multiple sets                         | reducing the size of smallest set and/or the number of sets                                  |
| **MIGRATE**     | transfer key from one Redis instance to another | reducing the number of objects stored as values and/or their average size                    |
| **DUMP**        | return serialized value for a given key         | reducing the number of objects stored asvalues and/or their average size                     |
| **ZREM**        | remove one or more members from sorted set      | reducing the number of elements to remove and/or the size of the sorted set                  |
| **ZUNIONSTORE** | add multiple sorted sets and store result       | reducing the total size of the sorted setsand/or the number of elements in the resulting set |
| **SORT**        | sort elements in list, set, or sorted set       | reducing the number of element to sort and/or the number of returned elements                |
| **SDIFFSTORE**  | subtract multiple sets and store result         | reducing the number of elements in all sets                                                  |
| **SDIFF**       | subtract multiple sets                          | reducing the number of elements in all sets                                                  |
| **SUNION**      | add multiple sets                               | reducing the number elements in all sets                                                     |
| **LSET**        | set value of an element in a list               | reducing the length of the list                                                              |
| **LREM**        | remove elements from a list                     | reducing the length of the list                                                              |
| **LRANGE**      | get range of elements from a list               | reduce the start offset and/or the number of elements in range                               |

![image](../../../media/redis-use-cases.jpg)


text:
# mongo-prometheus

Mongo Prometheus exporter docker-compose

Point each instance of this container to a MongoDB instance. It may be a standalone mongo, cluster router, configserver or a shard instance.

Use Prometheus to record and monitor metrics and view them in Grafana. A good Grafana dashboard for MongoDB is https://grafana.com/grafana/dashboards/2583

## Usage

* Create docker-compose.yml:

```yml
version: '3.5'
services:
  mongo-prometheus:
    image: bitnami/mongodb-exporter:0.11.0-debian-10-r75
    ports:
      - 8880:9216
    environment:
      - MONGODB_URI=mongodb://admin:admin123@mongo:27017
  mongo:
    image: mongo:4.2.8-bionic
    restart: always
    ports:
      - 27017:27017
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=admin123
      - MONGO_INITDB_DATABASE=sample
```

* Run ```docker-compose up -d```

* Run ```curl localhost:8880/metrics```
  * See some metrics

* Add this target to your own Prometheus instance
  * See /docker-compose.yml for a more comprehensive example

repository: stutzlab/mongo-prometheus

repo_name: stutzlab/mongo-prometheus


text:
# Code Quiz

## Welcome to the Code Quiz

### Purpose of this Project

This project is a website with a quiz to test your knowledge about the coding and a

a brief history about JavaScript and HTML. The user gets to go through the questions before the timer runs out

and they can save their highscore with their intials.

# Links

Deployed Link: https://leonaysmael16.github.io/coding-quiz/

GitHub Repo: https://github.com/leonaysmael16/coding-quiz

# License

This Project is under the MIT License.

# Ackowledgments

The University of Washington coding bootcamp is providing me the skills and knowledge to make this project.


text:
# Image
[![crates.io](https://img.shields.io/crates/v/image.svg)](https://crates.io/crates/image)
[![Documentation](https://docs.rs/image/badge.svg)](https://docs.rs/image)
[![Build Status](https://github.com/image-rs/image/workflows/Rust%20CI/badge.svg)](https://github.com/image-rs/image/actions)
[![Gitter](https://badges.gitter.im/image-rs/image.svg)](https://gitter.im/image-rs/image?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)

Maintainers: [@HeroicKatora](https://github.com/HeroicKatora), [@fintelia](https://github.com/fintelia)

[How to contribute](https://github.com/image-rs/organization/blob/master/CONTRIBUTING.md)

## An Image Processing Library

This crate provides basic image processing functions and methods for converting to and from various image formats.

All image processing functions provided operate on types that implement the `GenericImageView` and `GenericImage` traits and return an `ImageBuffer`.

## Supported Image Formats

`image` provides implementations of common image format encoders and decoders.

<!--- NOTE: Make sure to keep this table in sync with the one in src/lib.rs -->

| Format | Decoding | Encoding |
| ------ | -------- | -------- |
| AVIF   | Only 8-bit \*\* | Lossy |
| BMP    | Yes | Rgb8, Rgba8, Gray8, GrayA8 |
| DDS    | DXT1, DXT3, DXT5 | No |
| Farbfeld | Yes | Yes |
| GIF    | Yes | Yes |
| ICO    | Yes | Yes |
| JPEG   | Baseline and progressive | Baseline JPEG |
| OpenEXR  | Rgb32F, Rgba32F (no dwa compression) | Rgb32F, Rgba32F (no dwa compression) |
| PNG    | All supported color types | Same as decoding |
| PNM    | PBM, PGM, PPM, standard PAM | Yes |
| QOI    | Yes | Yes |
| TGA    | Yes | Rgb8, Rgba8, Bgr8, Bgra8, Gray8, GrayA8 |
| TIFF   | Baseline(no fax support) + LZW + PackBits | Rgb8, Rgba8, Gray8 |
| WebP   | Yes | Rgb8, Rgba8 \* |

- \* Requires the `webp-encoder` feature, uses the libwebp C library.
- \*\* Requires the `avif-decoder` feature, uses the libdav1d C library.

### The [`ImageDecoder`](https://docs.rs/image/*/image/trait.ImageDecoder.html) and [`ImageDecoderRect`](https://docs.rs/image/*/image/trait.ImageDecoderRect.html) Traits

All image format decoders implement the `ImageDecoder` trait which provide
basic methods for getting image metadata and decoding images. Some formats
additionally provide `ImageDecoderRect` implementations which allow for
decoding only part of an image at once.

The most important methods for decoders are...
+ **dimensions**: Return a tuple containing the width and height of the image.
+ **color_type**: Return the color type of the image data produced by this decoder.
+ **read_image**: Decode the entire image into a slice of bytes.

## Pixels

`image` provides the following pixel types:
+ **Rgb**: RGB pixel
+ **Rgba**: RGB with alpha (RGBA pixel)
+ **Luma**: Grayscale pixel
+ **LumaA**: Grayscale with alpha

All pixels are parameterised by their component type.

## Images
Individual pixels within images are indexed with (0,0) at the top left corner.
### The [`GenericImageView`](https://docs.rs/image/*/image/trait.GenericImageView.html) and [`GenericImage`](https://docs.rs/image/*/image/trait.GenericImage.html) Traits

Traits that provide methods for inspecting (`GenericImageView`) and manipulating (`GenericImage`) images, parameterised over the image's pixel type.

Some of these methods for `GenericImageView` are...
+ **dimensions**: Return a tuple containing the width and height of the image.
+ **get_pixel**: Returns the pixel located at (x, y).
+ **pixels**: Returns an Iterator over the pixels of this image.

While some of the methods for `GenericImage` are...
+ **put_pixel**: Put a pixel at location (x, y).
+ **copy_from**: Copies all of the pixels from another image into this image.

### Representation of Images
`image` provides two main ways of representing image data:

#### [`ImageBuffer`](https://docs.rs/image/*/image/struct.ImageBuffer.html)
An image parameterised by its Pixel types, represented by a width and height and a vector of pixels. It provides direct access to its pixels and implements the `GenericImageView` and `GenericImage` traits.

```rust
use image::{GenericImage, GenericImageView, ImageBuffer, RgbImage};

// Construct a new RGB ImageBuffer with the specified width and height.
let img: RgbImage = ImageBuffer::new(512, 512);

// Construct a new by repeated calls to the supplied closure.
let mut img = ImageBuffer::from_fn(512, 512, |x, y| {
    if x % 2 == 0 {
        image::Luma([0u8])
    } else {
        image::Luma([255u8])
    }
});

// Obtain the image's width and height.
let (width, height) = img.dimensions();

// Access the pixel at coordinate (100, 100).
let pixel = img[(100, 100)];

// Or use the `get_pixel` method from the `GenericImage` trait.
let pixel = *img.get_pixel(100, 100);

// Put a pixel at coordinate (100, 100).
img.put_pixel(100, 100, pixel);

// Iterate over all pixels in the image.
for pixel in img.pixels() {
    // Do something with pixel.
}
```

#### [`DynamicImage`](https://docs.rs/image/*/image/enum.DynamicImage.html)
A `DynamicImage` is an enumeration over all supported `ImageBuffer<P>` types.
Its exact image type is determined at runtime. It is the type returned when opening an image.
For convenience `DynamicImage` reimplements all image processing functions.

`DynamicImage` implement the `GenericImageView` and `GenericImage` traits for RGBA pixels.

#### [`SubImage`](https://docs.rs/image/*/image/struct.SubImage.html)
A view into another image, delimited by the coordinates of a rectangle.
The coordinates given set the position of the top left corner of the rectangle.
This is used to perform image processing functions on a subregion of an image.

```rust
use image::{GenericImageView, ImageBuffer, RgbImage, imageops};

let mut img: RgbImage = ImageBuffer::new(512, 512);
let subimg = imageops::crop(&mut img, 0, 0, 100, 100);

assert!(subimg.dimensions() == (100, 100));
```

## Image Processing Functions
These are the functions defined in the `imageops` module. All functions operate on types that implement the `GenericImage` trait.
Note that some of the functions are very slow in debug mode. Make sure to use release mode if you experience any performance issues.

+ **blur**: Performs a Gaussian blur on the supplied image.
+ **brighten**: Brighten the supplied image.
+ **huerotate**: Hue rotate the supplied image by degrees.
+ **contrast**: Adjust the contrast of the supplied image.
+ **crop**: Return a mutable view into an image.
+ **filter3x3**: Perform a 3x3 box filter on the supplied image.
+ **flip_horizontal**: Flip an image horizontally.
+ **flip_vertical**: Flip an image vertically.
+ **grayscale**: Convert the supplied image to grayscale.
+ **invert**: Invert each pixel within the supplied image This function operates in place.
+ **resize**: Resize the supplied image to the specified dimensions.
+ **rotate180**: Rotate an image 180 degrees clockwise.
+ **rotate270**: Rotate an image 270 degrees clockwise.
+ **rotate90**: Rotate an image 90 degrees clockwise.
+ **unsharpen**: Performs an unsharpen mask on the supplied image.

For more options, see the [`imageproc`](https://crates.io/crates/imageproc) crate.

## Examples
### Opening and Saving Images

`image` provides the `open` function for opening images from a path.  The image
format is determined from the path's file extension. An `io` module provides a
reader which offer some more control.

```rust,no_run
use image::GenericImageView;

fn main() {
    // Use the open function to load an image from a Path.
    // `open` returns a `DynamicImage` on success.
    let img = image::open("tests/images/jpg/progressive/cat.jpg").unwrap();

    // The dimensions method returns the images width and height.
    println!("dimensions {:?}", img.dimensions());

    // The color method returns the image's `ColorType`.
    println!("{:?}", img.color());

    // Write the contents of this image to the Writer in PNG format.
    img.save("test.png").unwrap();
}
```

### Generating Fractals

```rust,no_run
//! An example of generating julia fractals.
fn main() {
    let imgx = 800;
    let imgy = 800;

    let scalex = 3.0 / imgx as f32;
    let scaley = 3.0 / imgy as f32;

    // Create a new ImgBuf with width: imgx and height: imgy
    let mut imgbuf = image::ImageBuffer::new(imgx, imgy);

    // Iterate over the coordinates and pixels of the image
    for (x, y, pixel) in imgbuf.enumerate_pixels_mut() {
        let r = (0.3 * x as f32) as u8;
        let b = (0.3 * y as f32) as u8;
        *pixel = image::Rgb([r, 0, b]);
    }

    // A redundant loop to demonstrate reading image data
    for x in 0..imgx {
        for y in 0..imgy {
            let cx = y as f32 * scalex - 1.5;
            let cy = x as f32 * scaley - 1.5;

            let c = num_complex::Complex::new(-0.4, 0.6);
            let mut z = num_complex::Complex::new(cx, cy);

            let mut i = 0;
            while i < 255 && z.norm() <= 2.0 {
                z = z * z + c;
                i += 1;
            }

            let pixel = imgbuf.get_pixel_mut(x, y);
            let image::Rgb(data) = *pixel;
            *pixel = image::Rgb([data[0], i as u8, data[2]]);
        }
    }

    // Save the image as “fractal.png”, the format is deduced from the path
    imgbuf.save("fractal.png").unwrap();
}
```

Example output:

<img src="examples/fractal.png" alt="A Julia Fractal, c: -0.4 + 0.6i" width="500" />

### Writing raw buffers
If the high level interface is not needed because the image was obtained by other means, `image` provides the function `save_buffer` to save a buffer to a file.

```rust,no_run
fn main() {

    let buffer: &[u8] = unimplemented!(); // Generate the image data

    // Save the buffer as "image.png"
    image::save_buffer("image.png", buffer, 800, 600, image::ColorType::Rgb8).unwrap()
}
```

repository: image-rs/image

gha_language: Rust

repo_name: image-rs/image


text:
<img src="examples/maps.gif" align="right" width=300 />

# AoE3Unknown

Expect the unexpected! An Age of Empires 3 style 2D map generator using [Perlin noise](https://www.redblobgames.com/maps/terrain-from-noise/) and [Poisson<EMAIL_ADDRESS>techniques.

## Description

Generate AoE3 minimaps which aim to be (somewhat) similar to the maps included in the game. The currently supported map types are the land and island types, with snow, plains, andes, and decan as available biomes.

The Generator uses Perlin noise to generate the island and lake shapes. For placing forests, mines, hunts, and treasures, the Poisson Disk sampling method is used to ensure a minimum distance between the objects of the same type. Other familiar objects such as Town Centers, Trade Routes and Native Settlements are also randomly generated.

## Installation

Install dependencies using:

```bash
pip install -r requirements.txt
```

## Usage

To generate a map, run the program as follows:

```bash
python generate.py
```

The generated map will be automatically saved in the `out` subfolder. Additionally, the following flags can be added to the run command:

|Option | Action | Choices | Default |
| --- | --- | --- | --- |
| --size | Specify map size | int | 600 |
| --type | Specify map type | {random, island, land} | random |
| --biome | Specify map biome | {random, snow, plains, andes, decan} | random |
| --seed | Specify map seed | int | None |
| --no | How many maps to generate | int | 1 |
| --compass | Place compass graphic around maps | - | False |

repository: albertterradas/map

repo_name: albertterradas/map


text:
## Operations on process
###Process creation
- __parent process__: creating process
- __child process__: new process created
- each of these new process may in turn create other process, forming a tree fo process.
- Process Identifier (PID): an Interger number that provides a unique value for each process in the system.
-PID can be used as an index to access various attributes of a process withing the kernel.

_PPI - parent process identifier_

Parent of all the process is called the _init process_ with pid=1 | serves a the root parent process for all user process

two children of init- _kthreadd_ and _sshd_

kthreadd -> parent of all the kernel process

sshd -> responsible for managing clients that directly log onto the system

repository: ChesterChenTW/Cs-Web

repo_name: ChesterChenTW/Cs-Web


text:
# Deep Learning-based Diagnosis of Oral Cancer using Endoscopy

## Introduction
This project aims to build a deep learning-based diagnostic model of oral cancer. The convolutional neural network (EfficientNet-B3) were trained and evaluated using a total of 12,400 endoscopy of oral cavity (JPG format) acquired from six different medical centers, which will be available with restricted access. This repository includes 10-fold cross-validation, data preprocessing, and evaluation process. This study was supported by grants from the National Information Society Agency (NIA) of Korea.

## Table of Contents
1. Installation and Requirements
	- 1.1. Required Libraries
	- 1.2. Installation
2. Run
	- 2.1. Training
	- 2.2. Testing
3. Licenses

## 1. Installation and Requirements

### 1.1. Required Libraries
```
pandas==1.1.1

Pillow==7.2.0

pydicom==2.0.0

scikit-learn==0.23.2

torch==1.7.0.dev20200819+cu101

torchvision==0.8.0.dev20200828+cu101

efficientnet-pytorch==0.7.0

opencv-python-headless==<IP_ADDRESS>

matplotlib==3.3.1
```
### 1.2. Installation
Install the library by yourself or build docker image using Dockerfile.

For example, excute the following command in the path where Dockerfile locates.
```
docker build -t oral_cancer .
```
## 2. Data preprocessing
- Resizing to 300x300
- Normalization by statistics of ImageNet dataset : mean = (0.485, 0.456, 0.406), std = (0.229, 0.224, 0.225)

## 3. Run
### 3.1. Training
```
python train.py
```
### 3.2. Testing
For example,
```
python train.py --fold 0 --trained_model='model/trained-model-fold0.pth'
```
## 4. Licenses
Copyright (c) MINDs n company. All rights reserved.

Licensed under the Apache License, Version 2.0.


text:
---
layout: default
title: StridedSliceAssign
parent: array_ops
grand_parent: enuSpace-Tensorflow API
last_modified_date: now
---

# StridedSliceAssign

---

## tensorflow C++ API {#tensorflow-c-api}

[tensorflow::ops::StridedSliceAssign](https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/strided-slice-assign.html)

[Assign](https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/assign.html#classtensorflow_1_1ops_1_1_assign) `value` to the sliced l-value reference of `ref`.

---

## Summary {#summary}

The values of`value`are assigned to the positions in the variable`ref`that are selected by the slice parameters. The slice parameters`begin,`end`,`strides`, etc. work exactly as in`StridedSlice\`.

NOTE this op currently does not support broadcasting and so`value`'s shape must be exactly the shape produced by the slice of`ref`.

Arguments:

* scope: A [Scope](https://www.tensorflow.org/api_docs/cc/class/tensorflow/scope.html#classtensorflow_1_1_scope) object

Returns:

* [`Output`](https://www.tensorflow.org/api_docs/cc/class/tensorflow/output.html#classtensorflow_1_1_output): The output\_ref tensor.

---

## StridedSliceAssign block {#abs-block}

Source link :[https://github.com/EXPNUNI/enuSpaceTensorflow/blob/master/enuSpaceTensorflow/tf\_array\_ops.cpp](https://github.com/EXPNUNI/enuSpaceTensorflow/blob/master/enuSpaceTensorflow/tf_math.cpp)

![](./assets/array_ops/stridedsliceassign1.png)

Argument:

* Scope scope : A Scope object \(A scope is generated automatically each page. A scope is not connected.\)
* Input ref: A `Tensor`.
* Input begin: An `int32` or `int64 Tensor`. \`begin\[k\]\` specifies the offset into the \`k\`th range specification. The exact dimension this corresponds to will be determined by context. Out-of-bounds values will be silently clamped. If the \`k\`th bit of \`begin\_mask\` then \`begin\[k\]\` is ignored and the full range of the appropriate dimension is used instead. Negative values causes indexing to start from the highest element e.g. If \`foo==\[1,2,3\]\` then \`foo\[-1\]==3\`.
* Input end: An `int32` or `int64 Tensor`. \`end\[i\]\` is like \`begin\` with the exception that \`end\_mask\` is used to determine full ranges.
* Input strides: An `int32` or `int64 Tensor`. \`strides\[i\]\` specifies the increment in the \`i\`th specification after extracting a given element. Negative indices will reverse the original order. Out or range values are clamped to \`\[0,dim\[i\]\) if slice\[i\]>0 `or` \[-1,dim\[i\]-1\] if slice\[i\] < 0\`
* Input value: A `Tensor` . Assign to ref.
* StridedSlice::Attrs attrs:
  * begin\_mask: a bitmask where a bit i being 1 means to ignore the begin value and instead use the largest interval possible. At runtime begin\[i\] will be replaced with `[0, n-1) if` stride\[i\] > 0 `or`\[-1, n-1\] `if` stride\[i\] < 0
  * end\_mask: analogous to begin\_mask
  * shrink\_axis\_mask: a bitmask where bit i implies that the i th specification should shrink the dimensionality. begin and end must imply a slice of size 1 in the dimension. For example in python one might do foo\[:, 3, :\] which would result in shrink\_axis\_mask being 2.
  * ellipsis\_mask: a bitmask where bit i being 1 means the i\`th position is actually an ellipsis. One bit at most can be 1. If ellipsis\_mask == 0, then an implicit ellipsis mask of 1 << \(m+1\) is provided. This means that foo\[3:5\] == foo\[3:5, ...\]. An ellipsis implicitly creates as many range specifications as necessary to fully specify the sliced range for every dimension. For example for a 4-dimensional tensor foo the slice foo\[2, ..., 5:8\] implies foo\[2, :, :, 5:8\].
  * new\_axis\_mask: a bitmask where bit i being 1 means the i th specification creates a new shape 1 dimension. For example foo\[:4, tf.newaxis, :2\] would produce a shape \(4, 1, 2\) tensor.

Output:

* Output output: Output object of StridedSliceAssign class object.

Result:

* std::vector\(Tensor\) `result_output`: A `Tensor` the same type as `input`.

---

## Using Method

![](./assets/array_ops/stridedsliceassign2.png)※ value에서 특정한 부분을 잘라내어 ref의 variable에 입력하는 기능을 한다. begin은 각 차원에서 잘라낼 시작지점\(마이너스 값일 경우 reverse시키는것으로 보임\), end는 어디까지 자를것인지 입력한다. strides는 몇 스텝을 이동할 것인지 정한다\(ex: strides가 2일 경우 시작인 1에서 두칸 넘어간 3 그다음은 5 이런식이다.\).


text:
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).

- [live Demo](https://extwiii-hn.herokuapp.com/)

Features
--------
- react
- eslint
- axios
- jest
- enzym
- babel-eslint
- eslint-config-airbnb
- flow
- css grid

Prerequisites
-------------
- make sure you have npm/yarn in your computer

Getting Started
-------------

The easiest way to get started is to clone the repository:

```bash
# Get the latest snapshot
git clone https://github.com/extwiii/React-HN.git

# Change directory
cd React-HN

# Install NPM dependencies
yarn install

# Simply build your app to dist
yarn build

# Test your app
yarn test

# Then start your app
yarn start

```

### 1.0.0 (12 Feb, 2018)
- First version of React-HN

Contributing
------------

If something is unclear, confusing, or needs to be refactored, please let me know.
Pull requests are always welcome, but due to the opinionated nature of this
project, I cannot accept every pull request. Please open an issue before
submitting a pull request. This project uses
[Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) with a
few minor exceptions.

License
-------

The MIT License (MIT)

Copyright (c) 2017 Bilal Cagiran

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

### Bilal Cagiran  |<EMAIL_ADDRESS>| [Github](https://github.com/extwiii/) | [LinkedIn](https://linkedin.com/in/bilalcagiran) | [CodePen](http://codepen.io/extwiii/) | [Blog/Site](http://bilalcagiran.com) | [FreeCodeCamp](https://www.freecodecamp.com/extwiii)

repository: extwiii/React-HN

repo_name: extwiii/React-HN


text:
# I2C sniffer - RP2040 - PICO

The purpose of this project is to develop a sniffer for the I2C BUS that can capture at 400 KHZ.

For 100 Khz, it is possible to use bit-banding (IRQ or Polling) with an 8/32 bit processor, for example an AVR8, but since for 400 Khz it is necessary to react in less than 1.5 uS, a CPLD or FPGA is required.

An intermediate way is to use the processor [RP2040](https://www.raspberrypi.org/products/raspberry-pi-pico/) that has a PIO unit that  executes instructions in one cycle independent of central CPUs. The operating speed of the PIO can reach 125 Mhz.

## I2C protocol

A simplification of the i2c working principle could be that there are three conditions to detect: START DATA and STOP. And when the clock pin level (SCL) is high, the data pin transitions (SDA) indicate start or stop, but if (SDA) remains stable then it is a valid data bit.

![alt text](images/I2C_data_transfer.png)

## PIO-based sniffer working principle

Each PIO has 4 state machines that can be programmed to decode a part of the protocol and using an IRQ / WAIT scheme plus two GPIOs communicate the event.

For example, SM0 executes the program that decodes the START condition and sets the two auxiliary pins with the event code (0x01) and triggers IRQ 7 that SM3 listens, which executes the main program that is waiting for the IRQ to PUSH the event in the transmit FIFO.

![alt text](images/block_diagram_pio.png)

Excerpt from the code of the START DATA and MAIN state machine.

```assembly
.program i2c_start
.wrap_target
wait_sda_low:
    wait 0 gpio SDA_PIN     ; Wait for the sda pin to go down.
    jmp pin detected        ; If the SCL is high, the condition was detected.
    jmp wait_sda_high       ;

detected:
    set pins EV_START       ; Set the event code for START
    irq wait IRQ_EVENT      ; Fire the irq event

wait_sda_high:
    wait 1 gpio SDA_PIN     ;
.wrap

.program i2c_data
.wrap_target
    wait 1 gpio SCL_PIN     ; Wait for the scl pin to go high.
    set pins EV_DATA        ; Clear event code.
    irq wait IRQ_EVENT
    wait 0 gpio SCL_PIN     ; Wait for the scl pin to go low.
.wrap

.program i2c_main
.wrap_target
wait_irq_event:
    wait 1 irq IRQ_EVENT    ; Wait for the irq event.
    jmp pin send_event      ; If the lsb of the event code is zero, read the data bit.
    in pins, 1              ; Update the ISR register with the SDA value.
    jmp wait_irq_event      ; loads it into the FIFO when it reaches 9 bits.

send_event:
    mov isr, pins           ; Load the EV1(3), EV0(1), SDA(0).
    in NULL, 9              ; The event code starts at bit 11 and ends at 12.
.wrap
```
### Pin sequence to encode the event

    GPIO    Channel       Signal
    ---- ------------  -------------
    0   - 1 (Yellow)  - SDA
    3   - 2 (Blue)    - SCL
    1   - 3 (Violet)  - EV0
    2   - 4 (Green)   - EV1

In the graph below, you can see how the state machines (START/STOP/DATA) encode the event code before calling IRQ7 using the EV pins. When it detects the START condition it sets EV0 high and EV1 low, when it detects DATA put EV0 and EV1 in low, and for STOP condition put EV0 and EV1 in high.

![alt text](images/tek_sda_scl_ev0_ev1.png)

### Coding of sniffer events

When the main state machine inserts a 32-bit event into the FIFO, it uses the following format: the least significant nines are reserved for the address or data that is made up of 8 bits plus the ack/nack, and the 11th bits and 12 encode the event code.

![alt text](images/fifo_encode_format.png)

### Connection diagram

The sniffer connection to the I2C bus is as follows: the SDA line connects to the GPIO0, the SCL line to the GPIO3 and the GND is shared.

NOTE: the bus is 3.3V logic.

![alt text](images/sniffer_diagram.png)

## Firmware description

Although each state machine has an 8-level FIFO, for frames composed of more than 8 digits it is not enough, so it was decided to take advantage of the fact that the PICO has two CPUs, and dedicate CORE0 to wait for the i2c events of the main state machine and send them to CORE1 through the 8-level multicore FIFO to be decoded and sent through the USB serial port to a console on a PC.

To increase the level of FIFOs, one was implemented in RAM (40K events) controlled by CORE0 for buffering when the multicore FIFO is full.

![alt text](images/firmware_cores.png)

## Ascii event encoding

The ascii output is a succession of events in the sequence in which they were detected by the sniffer. It must be assumed that the slave address is the one immediately after the START event, and that after the 8 bits encoded in ascii the ack / nack bit continues.
To improve readability, a CR LF is added each time the STOP condition is detected.

`s = START CONDITION`
`p = STOP CONDITION`
`a = ACK DETECTED`
`n = NAK DETECTED`

Below is an excerpt of the command to get range from the VL530X sensor using the [Pololu Arduino library](https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp).

    Capture         Source Code
    -------         -------------
    s52a13ap    -   readReg(RESULT_INTERRUPT_STATUS)
    s53a40np    -   status = 40
    s52a13ap    -   readReg(RESULT_INTERRUPT_STATUS)
    s53a44np    -   status = 44
    s52a1Eap    -   readReg16Bit(RESULT_RANGE_STATUS + 10);
    s53a08a05np -   range = 0805
    s52a0Ba01ap -   writeReg(SYSTEM_INTERRUPT_CLEAR, 0x01);
    s52a80a01ap -   writeReg(0x80, 0x01);
    s52aFFa01ap -   writeReg(0xFF, 0x01);
    s52a00a00ap -   writeReg(0x00, 0x00);
    s52a91a3Cap -   writeReg(0x91, stop_variable);
    s52a00a01ap -   writeReg(0x00, 0x01);
    s52aFFa00ap -   writeReg(0xFF, 0x00);
    s52a80a00ap -   writeReg(0x80, 0x00);
    s52a00a01ap -   writeReg(SYSRANGE_START, 0x01);
    s52a00ap    -   readReg(SYSRANGE_START)
    s53a00np    -   answer = 00

### Download the firmware in Raspberry Pi Pico

Hold down the BOOTSEL button while plugging the board into USB. The uf2 file [i2c_sniffer_pio.uf2](https://github.com/jjsch-dev/pico_i2c_sniffer/blob/master/bin/i2c_sniffer_pio.uf2) should then be copied to the USB mass storage device that appears. Once programming of the new firmware is complete the device will automatically reset and be ready for use.

### Test scenario

To test the capture, an arduino nano was used as a master that requests the status of a VL530 TOF every 10 mS on a 400 Khz i2c BUS..

![alt text](images/test_device.png)

### Preliminary results

The following video shows the arduino monitor consulting the status, and the serial console that sends the result of the sniff of the i2c bus.
Note: Given the nature of the test, it has not been possible to check for loss of frames or data.

![](images/i2c_sniff_400khz_10mS_TOF.gif)

### TinyUSB - serial console

To make the usb port behave like a serial port (CDC) pico uses the TinyUSB library, and with the option pico_enable_stdio_usb ($ {PROJECT_NAME} 1) it is integrated into the output console (printf).

For this case, the print conversions (% c% x% s) add a lot of delay, so it was decided to do the conversion locally by nibbles.

```c
static inline char nibble_to_hex( uint8_t nibble ) {
    nibble &= 0x0F;

    if (nibble > 9) {
        nibble += 'A' - '0' - 10;
    }

    return( nibble + '0' );
}
```

To further optimize speed, MUTEX and CR and LF conversion were disabled with PUBLIC PICO_STDOUT_MUTEX = 0 PICO_STDIO_ENABLE_CRLF_SUPPORT = 0.

## Print using buffered string

When the output is via USB CDC, the data is sent in packets of maximum 64 bytes every 1mS. As the decoding of the i2c frame is composed of more than one event (Start / Stop / Data) that are separated by a few uS, to optimize the output they are stored in buffer waiting for: STOP, the buffer is full, or that elapsed more than 100 uS since the last event.

```c
void buff_print( void ) {
    if (ascii_index > 0) {
        ascii_buff[ascii_index] = '\0';
        printf(ascii_buff);
        ascii_index = 0;
    }
}

static inline void buff_putchar(char c) {
    // Reserve one byte for the NULL character.
    if (ascii_index >= sizeof(ascii_buff)-1) {
        buff_print();
    }

    ascii_buff[ascii_index++] = c;
}
```

### Led indicator

The LED is used to indicate that the board has initialized successfully (ON), flashes when there is activity on the i2c bus, and turns off when it detects a RAM overflow.


text:
![](https://d362q4tvy1elxj.cloudfront.net/header_logoheader.png)
RUBY-SDK
==========

Table of Contents
=================

  * [Table of contents](#table-of-contents)
  * [Installation](#installation)
  * [Getting Started](#getting-started)
    * [Retrieve a Specific Template](#retrieve-a-specific-template)
    * [List all Signed Waivers](#list-all-signed-waivers)
    * [Retrieve a Specific Waiver](#retrieve-a-specific-waiver)
    * [Retrieve Photos on a Waiver](#retrieve-photos-on-a-waiver)
    * [Search For Waivers](#search-for-waivers)
    * [Retrieve/Set Webhook Config](#retrieveset-webhook-configuration)
  * [Exception Handling](#exception-handling)
    * [Status Codes](#status-codes)
  * [Advanced](#advanced)
    * [Authentication](#authentication)

Installation
==========

    gem install smartwaiver-sdk

Alternatively, you may install the SDK from the github repo:

    git clone https://www.github.com/smartwaivercom/ruby-sdk

Getting Started
==========

All that is required to start using the SDK is a Smartwaiver account and the API Key for that account.
In all of the examples you will need to put the API Key into the code wherever it says: `[INSERT API KEY]`

If running the examples from the project without installing the gem, you will need to set the RUBYLIB path.

    export RUBYLIB=/Users/<user_name>/workspace/ruby-sdk/lib/smartwaiver-sdk

It's time to start making requests.
A good first request is to list all waiver templates for your account.
Here is the code to do that:

```ruby
require 'smartwaiver-sdk/template_client'
# The API Key for your account
api_key = '[INSERT API KEY]'

# Set up your Smartwaiver client using your API Key
client = SmartwaiverTemplateClient.new(api_key)

# Now request a list of all the waiver templates
results = client.list
```

That's it! You've just requested all waiver templates in your account.
But, now it's time to do something with them.
Let's loop through those templates and print out the ID and Title of each template:

```ruby
result[:templates].each do |template|
  puts "#{template[:templateId]}: #{template[:title]}"
end
```

Awesome! For more details on all the different properties a waiver template has, check out [template_properties.rb](examples/templates/template_properties.rb)

Now that you've got your first request, check out the sections below to accomplish specific actions.

Retrieve a Specific Template
---------

First let's set up the template client.
Make sure to put in your account's API Key where it says `[INSERT API KEY]`

```ruby
require 'smartwaiver-sdk/template_client'
# The API Key for your account
api_key = '[INSERT API KEY]'

# Set up your Smartwaiver client using your API Key
client = SmartwaiverTemplateClient.new(api_key)
```

Now we can request information about a specific template.
To do this we need the template ID.
If you don't know a template ID for your account, try listing all waiver templates for you account, as shown [here](#getting-started), and copying one of the ID's that is printed out.
Once we have a template ID we can execute a request to get the information about the template:

```ruby
# The unique ID of the template to be retrieved
template_id = '[INSERT TEMPLATE ID]'

# Retrieve a specific template (SmartwaiverTemplate object)
template = client.get(template_id)
```

Now let's print out some information about this template.

```ruby
# Access properties of the template
puts "List single template:"
puts "#{template[:templateId]}: #{template[:title]}"
```

To see all the different properties a waiver template has, check out [template_properties.rb](examples/templates/template_properties.rb)

List All Signed Waivers
----------

First let's set up the basic Smartwaiver waiver client. Make sure to put in your account's API Key where it says `[INSERT API KEY]`

```ruby
require 'smartwaiver-sdk/waiver_client'
# The API Key for your account
api_key = '[INSERT API KEY]'

# Set up your Smartwaiver client using your API Key
client = SmartwaiverWaiverClient.new(api_key)
```

Now we can request signed waivers from your account.

```ruby
# Get a list of summaries of waivers
waiver_summaries = client.list
```

With this done, we can iterate over the returned summaries to see what is stored.
The default limit is 20, which means if you have more than 20 in your account, only the most recent 20 will be returned

```ruby
puts "List all waivers:"
waiver_summaries[:waivers].each do |waiver|
  puts "#{waiver[:waiverId]}: #{waiver[:title]}"
end
```

To see all the different properties a waiver summary has, check out [waiver_summary_properties.rb](examples/waivers/waiver_summary_properties.rb)

Once we have a waiver summary, we can access all the detailed information about the waiver. To do that look [here](#retrieve-a-specific-waiver).

But, we can also restrict our query with some parameters.
For example, what if we only want to return 5 waivers, (the default is 20).
Here is the code to do that:

```ruby
# Set the limit
limit = 5

# Get a list of summaries of waivers
waiver_summaries = client.list(limit)
```

Or what if we only want any waivers that have not been verified (either by email or at the kiosk)?

```ruby
# Set the limit
limit = 5

# Set the verified parameter
verified = false

# Get a list of summaries of waivers
waiver_summaries = client.list(limit, verified)
```

What other parameters can you use? Here is an example using all of them:

```ruby
# An example limiting the parameters
limit = 5                                      # Limit number returned to 5
verified = true                                # Limit only to waivers that were signed at a kiosk or verified over email
template_id = '[INSERT TEMPLATE ID]'           # Limit query to waivers of this template ID
from_dts = '2016-11-01T00:00:00'               # Limit to waivers signed in November of 2016
to_dts = '2016-12-01T00:00:00'

# Get a list of summaries of waivers
waiver_summaries = client.list(limit, verified, template_id, from_dts, to_dts)
```

These examples are also available in [list_all_waivers.rb](examples/waivers/list_all_waivers.rb)

###Parameter Options

| Parameter Name | Default Value | Accepted Values   | Notes                                                                                |
| -------------- | ------------- | ----------------- | ------------------------------------------------------------------------------------- |
| limit          | 20            | 1 - 100           | Limit number of returned waivers                                                      |
| verified       | null          | true/false/null   | Limit selection to waiver that have been verified (true), not (false), or both (null) |
| templateId     |               | Valid Template ID | Limit signed waivers to only this template                                            |
| fromDts        |               | ISO 8601 Date     | Limit to signed waivers between from and to dates (requires toDts)                    |
| toDts          |               | ISO 8601 Date     | Limit to signed waivers between from and to dates (requires fromDts)                  |

Retrieve a Specific Waiver
----------

What if we want to retrieve a specific waiver?
All we need for that is a waiver ID.
If you don't have a waiver ID to use, you can get a list of signed waivers in your account [here](#list-all-signed-waivers)

First let's set up the basic Smartwaiver object. Make sure to put in your account's API Key where it says `[INSERT API KEY]`

```ruby
require 'smartwaiver-sdk/waiver_client'
# The API Key for your account
api_key = '[INSERT API KEY]'

# Set up your Smartwaiver client using your API Key
client = SmartwaiverWaiverClient.new(api_key)
```

Now, we can request the information about a specific waiver.
Make sure to put your waiver ID in where it says `[INSERT WAIVER ID]`

```ruby
# The unique ID of the signed waiver to be retrieved
waiver_id = '[INSERT WAIVER ID]'

# Get a specific waiver
result = client.get(waiver_id)
```

The waiver object has many different properties that can be accessed.
For example, we can print out the waiver ID and title of the waiver.

```ruby
# Access properties of waiver
waiver = result[:waiver]
puts "List single waiver:"
puts "#{waiver[:waiverId]}: #{waiver[:title]}"
```

To see a full list of all properties that a waiver object contains, check out [waiver_properties.rb](examples/waivers/waiver_properties.rb)

We can also request that the PDF of the signed waiver as a Base 64 Encoded string be included. Here is the request to do that:

```ruby
# The unique ID of the signed waiver to be retrieved
waiver_id = '[INSERT WAIVER ID]'

pdf = true

# Get the waiver object
result = client.get(waiver_id, pdf)
```

The code provided here is also combined in to one example in [retrieve_single_waiver.rb](examples/waivers/retrieve_single_waiver.rb)

Retrieve Photos on a Waiver
----------

We can also use the API to retrieve any photos taken when the waiver was signed or attached later with the console.
All we need is you're API key and the ID of a signed waiver, which has attached photos.

If you don't have a waiver ID to use, you can get a list of signed waivers in your account [here](#list-all-signed-waivers)

First let's set up the basic Smartwaiver object. Make sure to put in your account's API Key where it says `[INSERT API KEY]`

```ruby
require 'smartwaiver-sdk/waiver_client'

# The API Key for your account
api_key='[INSERT API KEY]'

client = SmartwaiverWaiverClient.new(api_key)
```

Now, we can request the photos on a specific waiver.
Make sure to put your waiver ID in where it says `[INSERT WAIVER ID]`

```ruby
# The unique ID of the signed waiver to be retrieved
waiver_id='[INSERT WAIVER ID]'

result = client.photos(waiver_id)

photos = result[:photos]
```

This photos object has a little meta-data we can print out:

```ruby
# Print a little header
puts "Waiver Photos for: #{photos[:title]}"

photos[:photos].each do |photo|
  puts "#{photo[:photoId]}: #{photo[:date]}"
end
```

The code provided here is also combined in to one example in [retrieve_waiver_photos.rb](examples/waivers/retrieve_waiver_photos.rb)

Search for Waivers
----------

First let's set up the basic Smartwaiver object. Make sure to put in your account's API Key where it says `[INSERT API KEY]`

```ruby
require 'smartwaiver-sdk/search_client'

# The API Key for your account
api_key='[INSERT API KEY]'

client = SmartwaiverSearchClient.new(api_key)
```

Now we can request a search for signed waivers from your account.

```ruby
# Request all waivers signed in 2018
results = client.search('', '2018-01-01 00:00:00')
```

**Note: The search route is a blocking search. Thus, a request to search for large amounts of data can take up to a few seconds.
As such, this route should not be used for anything where real-time performance is important. Instead use the Waivers route.**

This will return a search object containing metadata about the results of our search.
We can easily print out all that information:

```ruby
search = results[:search]
# Print out some information about the result of the search
puts "Search Complete:"
puts "  Search ID: #{search[:guid]}"
puts "  Waiver Count: #{search[:count]}"
puts "  #{search[:pages]} pages of size #{search[:pageSize]}"
```

The server has stored the results of our search request under the GUID given.
We can now loop through the pages and request each page, which will be a list of up to 100 waivers.
For example, if we wanted to created a list of all first names from our search, we would do that like this:

```ruby
# We're going to create a list of all the first names on all the waivers
name_list = [];

pages = search[:pages]
current_page = 0
search_guid = search[:guid]

while current_page < pages
  puts "Requesting page: #{current_page}/#{pages} ..."

  waivers = client.results(search_guid, current_page)

  puts "Processing page: #{current_page}/#{pages} ..."

  waivers[:search_results].each do |waiver|
    name_list.push(waiver[:firstName])
  end

  current_page = current_page + 1
end
```

To see all the different properties a waiver has, check out [waiver_properties.rb](examples/waivers/waiver_properties.rb)

This examples is also available in [basic_search.rb](examples/search/basic_search.rb)

### Search Parameters

We can also restrict our search with more parameters.
For example, what if we only want to return waivers for one of the templates in our account.
Here is the code to do that:

```ruby
# The unique ID of the template to search for

template_id='[INSERT TEMPLATE ID]'

# Request all waivers signed for this template
results = client.search(template_id)
```

Or what if we only want any waivers that have not been verified (either by email or at the kiosk)?

```ruby
# Request all waivers signed that not have been email verified
results = client.search(template_id, '', '', '', '', true)
```

What other parameters can you use? Here are some more examples:

```ruby
# Request all waivers signed for this template after the given date
results = client.search(template_id, '2017-01-01 00:00:00')

# Request all waivers signed for this template before the given date
results = client.search(template_id, '', '2017-01-01 00:00:00')

# Request all waivers signed for this template with a participant name Kyle
results = client.search(template_id, '', '', 'Kyle')

# Request all waivers signed for this template with a participant name Kyle Smith
results = client.search(template_id, '', '', 'Kyle', 'Smith')

# Request all waivers signed with a participant name Kyle that have been email verified
results = client.search(template_id, '', '', 'Kyle', '', true)

# Request all waivers signed in ascending sorted order
results = client.search(template_id, '', '', '', '', '', false)
```

These examples are also available in [search_params.rb](examples/search/search_params.rb)

### Parameter Options

| Parameter Name | Default Value | Accepted Values   | Notes                                                                                |
| -------------- | ------------- | ----------------- | --------------------------------------------------------------------------------------- |
| templateId     |               | Valid Template ID | Limit signed waivers to only this template                                              |
| fromDts        |               | ISO 8601 Date     | Limit to signed waivers between after this date                                         |
| toDts          |               | ISO 8601 Date     | Limit to signed waivers between before this date                                        |
| firstName      |               | Alpha-numeric     | Limit to signed waivers that have a participant with this first name (Case Insensitive) |
| lastName       |               | Alpha-numeric     | Limit to signed waivers that have a participant with this last name (Case Insensitive)  |
| verified       | null          | true/false/null   | Limit selection to waiver that have been verified (true), not (false), or both (null)   |
| sortDesc       | true          | true/false        | Sort results in descending (latest signed waiver first) order                           |

Retrieve/Set Webhook Configuration
----------

You can both retrieve and set your account's webhook configuration through this SDK with a couple simple calls.
To view your current webhook settings, we first need to set a Smartwaiver object.
Make sure to put in your account's API Key where it says `[INSERT API KEY]`

```ruby
require 'smartwaiver-sdk/webhook_client'
# The API Key for your account
api_key = '[INSERT API KEY]'

# Set up your Smartwaiver client using your API Key
client = SmartwaiverWebhookClient.new(api_key)
```

Now, it's easy to request the webhook configuration:

```ruby
# Get the current webhook settings
result = client.configuration
```

And, now we can print out the information:

```ruby
# Access the webhook config
puts "Endpoint: #{result[:webhooks][:endpoint]}"
puts "EmailValidationRequired: #{result[:webhooks][:emailValidationRequired]}"
```

The Email Validation Required is whether the webhook will fire before, after, or before and after a waiver is verified.
The endpoint is simply the endpoint URL for the webhook.

And changing your webhook configuration is just as easy.
The new configuration will be returned from the request and can be access just like the read request above.

```ruby
# The new values to set
endpoint = 'http://endpoint.example.org'
email_validation_required = SmartwaiverWebhookClient::WEBHOOK_AFTER_EMAIL_ONLY

# Set the webhook to new values
result = client.configure(end_point, send_after_email_only)

# Access the new webhook config
webhook = result[:webhooks]
puts "Successfully set new configuration."
puts "Endpoint: #{webhook[:endpoint]}"
puts "EmailValidationRequired: #{webhook[:emailValidationRequired]}"
```

This code is also provided in [retrieve_webhooks.rb](examples/webhooks/retrieve_webhooks.rb)
and [set_webhooks.rb](examples/webhooks/set_webhooks.rb)

Exception Handling
==========

There are three types of exceptions int the SDK:
 * A BadAPIKeyError occurs if the API key is incorrect or missing.
 * A BadFormatError occurs when trying to update the webhook configuration with incorrect data.
 * All other types of errors will be a RemoteServerError which is thrown by the API server.  The message returned explains the problem.

Here is an example of catching an HTTP exception. First we set up the Smartwaiver account:

```ruby
require 'waiver_client'

# The API Key for your account
api_key='[INSERT API KEY]'

# The unique ID of the signed waiver to be retrieved

client = SmartwaiverWaiverClient.new(api_key)
```

Next, we attempt to get a waiver that does not exist:

```ruby
# The Waiver ID to access
waiver_id='InvalidWaiverId'

# Try to get the waiver object
result = client.get(waiver_id)
```

This will throw an exception because a waiver with that ID does not exist. So let's change the code to catch that exception:

```ruby
begin
  # use default parameters
  result = client.get(waiver_id)

  waiver = result[:waiver]
  puts "List single waiver:"
  puts "#{waiver[:waiverId]}: #{waiver[:title]}"

  result = client.get(waiver_id, true)

  waiver = result[:waiver]
  puts "PDF:"
  puts "#{waiver[:pdf]}"

rescue SmartwaiverSDK::BadAPIKeyError=>bad
  puts "API Key error: #{bad.message}"
rescue Exception=>e
  puts "Exception thrown.  Error during waiver retrieval: #{e.message}"
end
```

But there is lot's of useful information in the exception object. Let's print some of that out too:

```ruby
# The code will be the HTTP Status Code returned
puts "Error Message: #{e.message}"

# Also included in the exception is the header information returned about
# the response.
puts "API Version: #{e.result[:version]}"
puts "UUID: #{e.result[:id]}"
puts "Timestamp: #{e.result[:ts]}"
```

Status Codes
----------

The code of the exception will match the HTTP Status Code of the response and the message will be an informative string informing on what exactly was wrong with the request.

Possible status codes and their meanings:

| Status Code | Error Name            | Description                                                                                |
| ----------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| 400         | Parameter Error       | Indicates that something was wrong with the parameters of the request (e.g. extra parameters, missing required parameters, etc.). |
| 401         | Unauthorized          | Indicates the request was missing an API Key or contained an invalid API Key.                                                     |
| 402         | Data Error            | Indicates that the parameters of the request was valid, but the data in those parameters was not.                                 |
| 404         | Not Found             | Indicates that whatever was being searched for (specific waiver, etc.) could not be found.                                        |
| 406         | Wrong Content Type    | Indicates that the Content Type of the request is inappropriate for the request.                                                   |
| 500         | Internal Server Error | Indicates that the server encountered an internal error while processing the request.                                             |

Advanced
==========

This section contains notes about several more ways to use the SDK that are slightly more low level.

Authentication
----------

If you are making custom requests you must include the proper authentication.
The Smartwaiver API expects a header called 'sw-api-key' to contain the API for the account you are accessing.

    sw-api-key: [INSERT API KEY]

If you do not have a Smartwaiver API key go [here](https://www.smartwaiver.com/p/API) to find out how to create one.

repository: smartwaivercom/ruby-sdk

gha_language: Ruby

repo_name: smartwaivercom/ruby-sdk


text:
# DEPRECATED

RSpec has a command that will perform the same features as this project. Prefer to use that instead.

    $ rspec --seed 1234 --bisect

See [their documentation](https://relishapp.com/rspec/rspec-core/docs/command-line/bisect) for more details.

# Rspec::Bisect

Detect order dependencies in rspec test suites and print a minimal list of tests required to reproduce it.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'rspec-bisect'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rspec-bisect

## Usage

So you think you have order dependencies? This tool will tell you exactly which tests are causing that dependency. It won't try to figure out if one exists or tell you why it's happening.

Have your rspec config set so that ```rspec --seed 1234``` runs your test suite with the specified seed.

Run ```rspec-bisect --seed 1234``` and rspec-bisect will tell you which tests are from an order dependency and the minimum tests required to reproduce it.

## Contributing

1. Fork it ( https://github.com/[my-github-username]/rspec-bisect/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

repository: spitsin-mercdev/rspec-bisect

repo_name: spitsin-mercdev/rspec-bisect


text:
---
title: Working Locally
date: 2018-07-07T13:49:05-07:00
weight: 1
---

Whether you are working by yourself or with others, the workflow for making
changes on your local machine stays the same. This guide is primarily aimed at
those who are new to version control, but is also useful for seasoned version
control users trying to see how gg stacks up to their current tool.

<!--more-->

## Creating a Repository

To create an empty repository, you use [`gg init`][].

```shell
gg init foo
cd foo
```

This will create a new folder `foo` with a `.git` directory inside it.

[`gg init`]: {{< relref "commands/init.md" >}}

## Adding Files

Let's say you create a file inside your new repository:

```shell
nano my-thoughts.txt
```

gg will not track `my-thoughts.txt` until you explicitly tell it to, using [`gg
add`][]:

```shell
gg add my-thoughts.txt
```

You can then save your work to the repository using [`gg commit`][].  A commit message should be a short, human-readable
summary of what you did in that commit. A quick internet search for "good commit
messages" includes advice on how to write a good commit message and why this is
important, especially when collaborating with others.

[`gg add`]: {{< relref "commands/add.md" >}}
[`gg commit`]: {{< relref "commands/commit.md" >}}
[Git commit]: https://git-scm.com/docs/gitglossary#def_commit

## Modifying Files

Let's say you add more to `my-thoughts.txt`. You can get a short summary of the
files that have changed by using [`gg status`][]:

```shell
gg status
```

This would show something like:

```
M my-thoughts.txt
```

If you want a more detailed view of your changes, you can use [`gg diff`][] (short for differences).

```shell
gg diff
```

This would show something like:

```
diff --git a/my-thoughts.txt b/my-thoughts.txt
--- a/my-thoughts.txt
+++ b/my-thoughts.txt
@@ -1,1 +1,2 @@
 Hello, World!
+I'm learning gg!
```

When you're ready to make a new commit, you run `gg commit` like before.

```shell
gg commit -m "Documented my experience in following a gg tutorial"
```

Long-time Git users will notice that we did not have to "add" the files before
committing. This is intentional: gg makes every effort to emulate Mercurial's
index-less model to reduce the number of steps in common workflows. To commit
only certain files, just pass them as arguments to `gg commit`. For more
advanced partial commits, use `git add` and `git commit` directly.

[`gg diff`]: {{< relref "commands/diff.md" >}}
[`gg status`]: {{< relref "commands/status.md" >}}

## Removing Files

Sometimes, you will want to remove a file that has been tracked by version
control.  Let's see how to use
gg to go back in time.

[`gg rm`]: {{< relref "commands/remove.md" >}}

## Examining History

The primary motivation for version control is to be able to inspect previous
revisions of files. gg includes several commands to access the repository's
data.

The first command is [`gg log`].

```shell
gg log
```

`gg log` will show you a list of all the commits you have made up to this point.
Each commit is identified by a long hexadecimal string called the [hash][]. You
can use the hash to reference the commit in other commands or when talking with
other people.

If you want to see the changes made in a single commit, you can pass the `-c`
flag to `gg diff` with a hash you found from the log.

```shell
gg diff -c a199be2
```

You can also see all the changes made since a particular commit using `-r`:

```shell
gg diff -r a199be2
```

If you want to check out what the repository looked like at a particular commit,
you can use the [`gg update`], also known as `checkout`.

```shell
gg checkout -r a199be2
```

When you're done looking, you can go back to your latest work using `checkout`.

```shell
gg checkout -r master
```

`master` is the name of the default [branch][] that was created when you ran `gg
init`. You can use the name of a branch instead of a commit hash in any gg
command that takes in a commit to indicate the latest commit on that branch.

Finally, if you realize you made a mistake (perhaps you want `my-thoughts.txt`
back), you can use `gg revert` to bring files back to their state at a given
commit, then use `gg commit` to save your work as normal.

```shell
gg revert -r a199be2 my-thoughts.txt
gg commit -m "Brought back my thoughts"
```

[branch]: https://help.github.com/articles/about-branches/
[`gg log`]: {{< relref "commands/log.md" >}}
[`gg update`]: {{< relref "commands/update.md" >}}
[hash]: https://git-scm.com/docs/gitglossary#def_hash

## Next Steps

If you are using gg just by yourself, this may be all you need to know. Version
control lets you keep track of how your files have changed over time, and lets
you bring back files you may have accidentally deleted. However, version control
is an important tool for being able to share these changes with others. Once
you've gotten used to the commands in this guide, take a look at the other
[workflows][] to see how to share your work with others. You may also want to
look at the [command reference][].

[command reference]: {{< sectionref "commands" >}}
[workflows]: {{< sectionref "workflows" >}}

repository: ijt/gg

repo_name: ijt/gg