text:
# `OptionBuilder`

In this first tutorial, we'll create a computation expression to remove the arrowhead pattern from working with `option` types.

In order to understand what we want to accomplish, we should also be familiar with how to do the task without a computation expression.

## Without a Computation Expression

1. Remove `Sample.fs`.
2. Create a new file, `OptionBuilder.fs`.
3. Add the file to your `.fsproj` with `<Compile Include="OptionBuilder.fs" />` above `Program.fs`.
4. Add the following lines of code to `OptionBuilder.fs`:
``` fsharp
module Options

open Expecto

let opt1 = Some 1
let opt2 = Some 2
let opt3 = Some 3
let opt4 = Some 4
let sum4 w x y z = w + x + y + z

let nested =
    match opt1 with
    | Some w ->
        match opt2 with
        | Some x ->
            match opt3 with
            | Some y ->
                match opt4 with
                | Some z ->
                    let result = sum4 w x y z
                    printfn "Nested: %d" result
                    Some result
                | None -> None
            | None -> None
        | None -> None
    | None -> None

let composed =
    opt1
    |> Option.bind (fun w ->
        opt2
        |> Option.bind (fun x ->
            opt3
            |> Option.bind (fun y ->
                opt4
                |> Option.map (fun z ->
                    let result = sum4 w x y z
                    printfn "Composed: %d" result
                    result
                )
            )
        )
    )

[<Tests>]
let tests =
    testList "OptionBuilder" [
        test "nested = composed" {
            Expect.equal nested composed "Expected nested to equal composed"
        }
    ]
```
5. Build and run the program with `dotnet test`.

> **NOTE:** if you run into problems, notably an error regarding `EntryPointAttribute`, try the following:
Rename `Main.fs` to `Program.fs` and make the same change in the `fsproj`. You may also remove
the `module` declaration in the `Program.fs` file, but that should not have any material impact.

## Objective

We will build an `OptionBuilder` to flatten the code we wrote above in `nested` and `composed` into the following:

``` fsharp
let actual = maybe {
    let! w = opt1
    let! x = opt2
    let! y = opt3
    let! z = opt4
    let result = sum4 w x y z
    printfn "Result: %d" result
    return result
}
```

## Empty builder

1. Add a new type, `type OptionBuilder() = class end`
2. Create an instance of the builder: `let maybe = OptionBuilder()`
3. Add a test to validate the maybe builder exists. We'll assert that it should support `return`, which we'll implement next, and that it should return the value provided.
``` fsharp
type OptionBuilder() = class end

let maybe = OptionBuilder()

[<Tests>]
let tests =
    testList "OptionBuilder" [
        // ...
        // previous tests
        // ...

        test "OptionBuilder returns value" {
            let expected = 1
            let actual = maybe { return expected }
            Expect.equal actual (Some expected) "Expected Some 1"
        }
    ]
```
4. Build and run the program with `dotnet test`. Your program should fail to compile with the following error:
```
/Users/ryan/Code/computation-expressions-workshop/solution/OptionBuilder.fs(53,34): error FS0708: This control construct may only be used if the computation expression builder defines a 'Return' method
```

## `Return` a Value

The compiler informs us that in order to use the `return` keyword, we must implement the `Return` method on our builder.

Replace:
``` fsharp
type OptionBuilder() = class end
```
with
```fsharp
type OptionBuilder() =
    member __.Return(value) = Some value
```

Build and run the program with `dotnet test`. Your tests should pass.

## Composing `'a option` Values

`let` bindings binds a value to a name. Computation expressions provide a `let!` binding that can bind a value according
to rules specified by the computation expression. This facilitates several possibilities:

* making a decision as to whether to continue or halt a computation
* side effects, e.g. printing to the screen or making a network call
* transform a result into another form

To find out how to implement `let!`, add a test:

``` fsharp
        test "OptionBuilder can bind option values" {
            let actual = maybe {
                let! w = opt1
                let! x = opt2
                let! y = opt3
                let! z = opt4
                let result = sum4 w x y z
                printfn "Result: %d" result
                return result
            }
            Expect.equal actual nested "Actual should sum to the same value as nested."
        }
```

Build and run the program with `dotnet test`. Your program should fail to compile with the following error:

```
/Users/ryan/Code/computation-expressions-workshop/solutions/OptionBuilder.fs(61,17): error FS0708: This control construct may only be used if the computation expression builder defines a 'Bind' method
```

The compiler informs us that in order to use the `let!` keyword, we must implement the `Bind` method on our builder.

The F# Language Specification indicates that the `Bind` member should have the following signature (specialized
for our immediate use case):

``` fsharp
member __.Bind : 'a option * ('a -> 'b option) -> 'b option
```

As you either know or expect, this matches very closely with the signature of `Option.bind`:

``` fsharp
module Option =
    val bind : ('a -> 'b option) -> 'a option -> 'b option
```

We can therefore implement `Bind` as follows:
``` fsharp
    member _.Bind(m, f) = Option.bind f m // notice the parameter orientation
```

We could also implement `Bind` like this:
``` fsharp
    member _.Bind(m: 'a option, f: 'a -> 'b option) =
        match m with
        | Some x -> f x
        | None -> None
```

Build and run the program with `dotnet test`. Your tests should pass.

## Expansion

It's worthwhile to pause here to understand what's happening. When the F# compiler encounters an
instance of an object followed by `{}`, in this case `maybe`, it will attempt to expand it based
on the computation expression rules. In our example above, the expansion ends up looking very
similar to the `composed` value we expressed above:

``` fsharp
let actual =
    maybe.Bind(opt1, fun w ->
        maybe.Bind(opt2, fun x ->
            maybe.Bind(opt3, fun y ->
                maybe.Bind(opt4, fun z ->
                    let result = sum4 w x y z
                    printfn "Result: %d" result
                    maybe.Return(result)
                )
            )
        )
    )
```

You can add a test to show that you could write this explicitly yourself:

``` fsharp
        test "OptionBuilder instance can be used directly" {
            let actual =
                maybe.Bind(opt1, fun w ->
                    maybe.Bind(opt2, fun x ->
                        maybe.Bind(opt3, fun y ->
                            maybe.Bind(opt4, fun z ->
                                let result = sum4 w x y z
                                printfn "Result: %d" result
                                maybe.Return(result)
                            )
                        )
                    )
                )
            Expect.equal actual composed "Actual should sum to the same value as nested."
        }
```

Aside from reading the specification, it can be useful to add traces or `printfn` statements
into your CE builder definition while developing it. Let's do that now:

``` fsharp
type OptionBuilder() =
    member __.Return(value) =
        printfn "maybe.Return(%A)" value
        Some value
    member __.Bind(m, f) =
        printfn "maybe.Bind(%A, %A)" m f
        Option.bind f m
```

Running the computation again should produce output that shows the calls made, and their order:

```
maybe.Bind(Some 1, <fun:actual@281-27>)
maybe.Bind(Some 2, <fun:actual@282-28>)
maybe.Bind(Some 3, <fun:actual@283-29>)
maybe.Bind(Some 4, <fun:actual@284-30>)
maybe.Return(10)
val actual : int option = Some 10
```

> **Observation:** the `maybe` instance is an object instance. While F# is a functional-first language,
>it also supports the .NET object model. Computation Expressions leverage this object model, and this can
>lead to some interesting possibilities we'll investigate later in the workshop.

## Executing without Returning

F# is not a pure functional language, meaning you can perform side-effects like writing to the file system
without returning a value indicating something like that happened. We looked briefly at `Async` earlier and
we will look at another CE that can make this explicit, but you may not want or need that.

Let's look at a case where you want to write a file to the file system if a path was provided and the path directory exists:

``` fsharp
        test "OptionBuilder can exit without returning a value" {
            let fullyQualified path =
                let fileInfo = System.IO.FileInfo(path)
                let fileName = fileInfo.Name
                let pathDir = fileInfo.Directory.FullName.TrimEnd('~')
                if System.IO.Directory.Exists(pathDir) then
                    Some (System.IO.Path.Combine(pathDir, fileName))
                else None

            let maybePath = Some "~/test.txt"

            let actual =
                maybe {
                    let! path = maybePath
                    let! fullPath = fullyQualified path
                    System.IO.File.WriteAllText(fullPath, "Test succeeded")
                }

            Expect.equal actual (Some ()) "Actual should be Some unit"
        }
```

Once again, the project fails to compile:

```
/Users/ryan/Code/computation-expressions-workshop/solutions/OptionBuilder.fs(120,21): error FS0708: This control construct may only be used if the computation expression builder defines a 'Zero' method
```

`Zero` provides us with several conveniences and is one of the first examples of why you cannot always write a
canonical computation expression for a given type. `Zero` allows you to return from the computation expression without
explicitly returning a value. The most typical implementation for our `OptionBuilder` would be to return `Some ()`, as
this indicates "success" with no value:

``` fsharp
    member __.Zero() =
        printfn "maybe.Zero()"
        Some ()
```

Running `dotnet test` with this definition will now complete successfully, and you should see the following printed out:

```
maybe.Bind(Some "~/test.txt", <fun:actual@455-41>)
maybe.Bind(Some "/Users/ryan/Code/computation-expressions-workshop/test.txt", <fun:actual@456-42>)
maybe.Zero()
```

`Zero` will also allow an `if ... then` without an `else`:

``` fsharp
        test "OptionBuilder supports if then without an else" {
            let maybePath = Some "~/test.txt"

            let actual =
                maybe {
                    let! path = maybePath
                    let pathDir = System.IO.Path.GetDirectoryName(path)
                    if not(System.IO.Directory.Exists(pathDir)) then
                        return "Select a valid path."
                }

            Expect.equal actual (Some "Select a valid path.") "Actual should return Some(\"Select a valid path.\")"
        }
```

Unfortunately, the compiler doesn't like what we've done here:

```
/Users/ryan/Code/computation-expressions-workshop/solutions/OptionBuilder.fs(465,21): error FS0001: Type mismatch. Expecting a
    'string option'
but given a
    'unit option'
The type 'string' does not match the type 'unit'
```

You can probably see the issue: `Zero` currently returns `Some ()`, but our `return` expression returns a `string`.
A better solution for this case is to have `Zero` return `None`:

``` fsharp
    member __.Zero() = None
```

Running `dotnet test` now compiles and runs with one test failure b/c our previous test expected to return `Some ()`.
Change that to `None`, and your tests will pass.

> **Observation:** computation expressions are not always one-size-fits-all. Our tests pass, but you can no longer use the result from the previous test in a continuing chain of computations, as it will return `None`, which will currently cause our `maybe` computations to propogate the `None`. You may find you need multiple `OptionBuilder` CEs for different use cases.

## Returning a Computation

Before moving on to our next exercise, let's consider how you might escape a `maybe` computation early.
Let's say that based on a condition, you want to immediately get a `None` and avoid any further computation.
How might you do this? In order to return an `'a option` from our computation, we need to use `return!`.
This is similar to `return` in the same way `let` and `let!` are similar. `return!` handles `'a option` just
like `let!` handles an `'a option`, where as their `!`-less counterparts deal with `'a` values.

``` fsharp
        test "OptionBuilder allows for early escape with return!" {
            let actual =
                maybe {
                    if true then
                        return! None
                    else
                        let! w = opt1
                        let! x = opt2
                        let! y = opt3
                        let! z = opt4
                        let result = sum4 w x y z
                        printfn "Result: %d" result // print if a result was computed.
                        return result
                }
            Expect.equal actual None "Should return None immediately"
        }
```

Add the test above and run `dotnet test`. The build will fail with the following:

```
/Users/ryan/Code/computation-expressions-workshop/solutions/OptionBuilder.fs(146,25): error FS0708: This control construct may only be used if the computation expression builder defines a 'ReturnFrom' method
```

`ReturnFrom` is a very simple method to implement:

``` fsharp
    member __.ReturnFrom(m) = m
```

or to be a bit more precise and add our tracing print statements while we are building this up:

``` fsharp
    member __.ReturnFrom(m:'a option) =
        printfn "maybe.ReturnFrom(%A)" m
        m
```

Adding this method and running `dotnet test` should result in a successful test run.

## Review

We implemented the following builder methods for `OptionBuilder`:
* `Return`
* `Bind`
* `Zero`
* `ReturnFrom`

We also observed that a given method, e.g. `Zero`, does not necessarily have a canonical implementation.

In the next exercise, we'll look at how we might be able to overcome our choice of `None` as a result for `Zero`
to continue, rather than cancel, execution of a computation involving `'a option`.

repository: maxild/computation-expressions-workshop

repo_name: maxild/computation-expressions-workshop


text:
# `useFacet`

## Features

`useFacet` composition function can be used to fetch data related to:

* products,
* categories,
* breadcrumbs.
* facets

## API

`useFacet` contains the following properties:

* `search` - function for searching and classifying records, allowing users to browse the catalog data. It accepts a single object as a parameter with following signature:

<https://www.vendure.io/docs/graphql-api/shop/input-types/#searchinput>

* `result` - reactive data object containing the response from the backend.

<https://www.vendure.io/docs/graphql-api/shop/object-types/#searchresponse>

* `loading` - reactive object containing information about the loading state of `search`.

* `error` - reactive object containing the error message, if `search` failed for any reason.

```ts
interface UseFacetErrors {
  search: Error;
}
```

## Getters

* `getGrouped` - returns grouped facets by facet name.

* `getSortOptions` - returns available and currently selected sorting options.

* `getProducts` - returns products matching current filters.

* `getPagination` - returns pagination information.

* `getTree` - returns current category tree.

* `getBreadcrumbsFromSlug` - returns breadcrumbs from current slug.

* `getAgnosticSearchResult` - returns agnostic search result.

* `getCategoryTree` - return the tree of nested categories (not used in favor of `getTree`).

* `getBreadcrumbs` - returns breadcrumbs information (not used in favor of `getBreadcrumbsFromSlug`).

* `getAll` - TBD.

```ts
interface FacetsGetters {
  getAll: (searchData: FacetSearchResult<AgnosticSearchResult>, criteria?: string[]) => AgnosticFacet[];
  getGrouped: (searchData: FacetSearchResult<AgnosticSearchResult>, criteria?: string[]) => AgnosticGroupedFacet[];
  getCategoryTree: (searchData: FacetSearchResult<AgnosticSearchResult>) => AgnosticCategoryTree;
  getSortOptions: (searchData: FacetSearchResult<AgnosticSearchResult>) => AgnosticSort;
  getProducts: (searchData: FacetSearchResult<AgnosticSearchResult>) => ProductVariant[];
  getPagination: (searchData: FacetSearchResult<AgnosticSearchResult>) => AgnosticPagination;
  getBreadcrumbs: (searchData: FacetSearchResult<AgnosticSearchResult>) => AgnosticBreadcrumb[];
  getTree: (category: Collection) => AgnosticCategoryTree | null;
  getBreadcrumbsFromSlug: (searchResult: FacetSearchResult<AgnosticSearchResult>, slug: string) => AgnosticBreadcrumb[]
  getAgnosticSearchResult: (searchResultValue: SearchResultValue<SearchResponse, SearchInput>) => FacetSearchResult<AgnosticSearchResult>;
}

interface AgnosticFacet {
  type: string;
  id: string;
  value: any;
  attrName?: string;
  count?: number;
  selected?: boolean;
  metadata?: any;
}

interface AgnosticGroupedFacet {
  id: string;
  label: string;
  count?: number;
  options: AgnosticFacet[];
}

interface AgnosticCategoryTree {
  label: string;
  slug?: string;
  items: AgnosticCategoryTree[];
  isCurrent: boolean;
  count?: number;
  [x: string]: unknown;
}

interface AgnosticSort {
  options: AgnosticFacet[];
  selected: string;
}

interface FacetSearchResult {
  data;
  input: AgnosticFacetSearchParams;
}

interface AgnosticFacetSearchParams {
  categorySlug?: string;
  rootCatSlug?: string;
  term?: string;
  page?: number;
  itemsPerPage?: number;
  sort?: string;
  filters?: Record<string, string[]>;
  metadata?: any;
  [x: string]: any;
}

interface AgnosticPagination {
  currentPage: number;
  totalPages: number;
  totalItems: number;
  itemsPerPage: number;
  pageOptions: number[];
}

interface AgnosticBreadcrumb {
  text: string;
  link: string;
}

type AgnosticSearchResult = {
  products: SearchResult[];
  categories: CollectionResult[];
  facets: FacetValueResult[];
  total: number;
  perPageOptions: number[];
  itemsPerPage: number;
}

type SearchResultValue<SEARCH_DATA, SEARCH_INPUT> = {
  data?: SEARCH_DATA;
  input?: SEARCH_INPUT;
}
```

<https://www.vendure.io/docs/graphql-api/shop/object-types/#searchresponse>

## Example

```js
import { useFacet, facetGetters } from '@vsf-enterprise/commercetools';

setup(props, context) {
  const { result, search, loading } = useFacet();

  onSSR(async () => {
    await search({
      collectionSlug: 'clothing',
      sort: { price: 'ASC'},
      take: 10,
      groupByProduct: true, // To return only master variant
    });
  });

    // Will be refactored to data mapper in theme folder
    const searchResult = computed(() => facetGetters.getAgnosticSearchResult(result.value)); // Convert raw result to agnostic search result

    const sortBy = computed(() => facetGetters.getSortOptions(searchResult.value));
    const facets = computed(() => facetGetters.getGrouped(searchResult.value));
    const products = computed(() => facetGetters.getProducts(searchResult.value));

  return {
    sortBy,
    facets,
    products,
    loading
  }
}
```

license: MIT

branch_name: refs/heads/main

extension: md

license_type: permissive


text:
# Swift-Slide-Menu (Material Design Inspired)
[![Platform](http://img.shields.io/badge/platform-ios-blue.svg?style=flat
)](https://developer.apple.com/iphone/index.action)
[![Language](http://img.shields.io/badge/language-swift-brightgreen.svg?style=flat
)](https://developer.apple.com/swift)
[![License](http://img.shields.io/badge/license-MIT-lightgrey.svg?style=flat
)](http://mit-license.org)

A Slide Menu, written in Swift 2, inspired by Navigation Drawer on Material Design (inspired by [Google Material Design](https://www.google.com/design/spec/patterns/navigation-drawer.html)) for iOS written in Swift 2.0

Please feel free to make pull requests :)

![alt tag](https://github.com/PhilippeBoisney/Swift-Slide-Menu/raw/master/SlideMenu.gif)

## USAGE
1. **Add those 5 files** on your project : BaseViewController.swift, ChildViewController.swift, MenuTableViewCell.swift, TableViewMenuController.swift and ZFRippleButton.swift. Don't forget to also add "background.jpg" on your asset directory.
2. **Add your own mini icons** for menu on your asset directory
3. Create **ViewControllers** Swift files for your **ChildView**, subclass with ChildViewController.
4. Create on **Storyboard** (Interface Builder) your **ChildViews** (Just drag UIViewController)then **set "Storyboard ID" AND "CustomClass"**
5. **Subclass** your main ViewController with BaseViewController and on Storyboard(Interface Builder), select your main ViewController, then **add a Navigation Controller** (Editor => Embed In => Navigation Controller).
6. Finally, Add on your main ViewController:
```swift
//Add the childViews
addChildView("HomeScreenID", titleOfChildren: "HOME", iconName: "home")
addChildView("ContactScreenID", titleOfChildren: "CONTACT", iconName: "contact")

//Show the first childScreen
showFirstChild()
```

## Version
1.2

## Features

- Multi-Device Full Support
- Rotation Support
- Material Design Effect

## Thanks
This library use a modified version of this awesome project: [ZFRippleButton](https://github.com/zoonooz/ZFRippleButton)

## Author

Philippe BOISNEY (phil.boisney(@)gmail.com)

repository: SatcomInt/apple-samples

branch_name: refs/heads/master

repo_name: SatcomInt/apple-samples


text:
# messenger_launcher

A new flutter plugin project for launching messenger.

## Installation

First, add messenger_launcher as a dependency in your pubspec.yaml file.

## iOS

Add the following entry to your Info.plist file, located in <project root>/ios/Runner/Info.plist:

````xml
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>fb-messenger</string>
</array>
````

## Example

````dart
import 'package:flutter/material.dart';
import 'package:messenger_launcher/messenger_launcher.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  initState() {
    super.initState();
  }

  void openMessenger() async {
    await MessengerLauncher.launchMessenger("messengerId");
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Plugin example app'),
        ),
        body: new Center(
          child: FlatButton(
            child: Text("Open Messenger"),
            onPressed: () {
              openMessenger();
            },
          )
        ),
      ),
    );
  }
}

````

repository: coder-Aayush/messenger-launcher

repo_name: coder-Aayush/messenger-launcher


text:
# 🐛 COVID-19 Puerto Rico Data

*Data provided by the [Puerto Rico Institute of Statistics](https://estadisticas.pr/en/covid-19), based on official data provided by the Puerto Rico Department of Health.*

---

## Current Test Results
*Quantity and Percentage Distribution*

- [x] **Folder Name**: *datos_en_general*
- [x] **Data Format**:  *CSV*

## Positive results
*According to the Reported Sex*

- [X] **Folder**: *datos_por_sexo*
- [x] **Data Format**:  *CSV*

## Positive results
*Distribution by Health Region*

- [X] **Folder**: *datos_por_region*
- [x] **Data Format**:  *CSV*

### Sources

- *Office of Communications and Public Affairs, Department of Health of Puerto Rico.*
- *La Fortaleza, Government of Puerto Rico.*
- *Department of Biostatistics and Epidemiology, Graduate School of Public Health, Campus of Medical Sciences, University of Puerto Rico.*

*[More information about COVID-19 in Puerto Rico](http://www.salud.gov.pr/Pages/coronavirus.aspx)*

gha_language: JavaScript

gha_license_id: MIT


text:
# DMusic

# Privacy Policy

This privacy policy document is to provide information on what, how, and why personal data or information is collected, used, and disclosed, when this software is utilized, and the choices you have associated with that data. The objective of this policy document is to provide an open environment between developer and users of this software by openly stating what information the developer collects or not. By utilizing this software, it means you accept all the terms and conditions of the developer peculiar to only DMusic software. This Policy applies to this software only, and the developer would not be held responsible for the content or privacy practices on any third party app not operated by the developer to which this software links or that links to this software, therefore it is advisable to read up the privacy policies of third party services that may be linked to this software.

## Permission and Access

For better and enhanced utilization of DMusic, the software is designed to request the provision of certain personally identifiable information. This permission needs to be enabled for the software to work properly on the device on which the software's services are intended.

The permission is;

- Storage

With the storage permission enabled, the app can;

- modify or delete the contents of your SD card.
- read the contents of your SD card.

DMusic has some other capabilities, which are functions the software can remotely effect on its own. They include;

- **close other apps**: This allows the app to end background processes of other apps.
- **have full network access**: The app is capable of creating network sockets and can use customized network protocols. This capability does not require the software to send data to the internet.
- **view network connections**: This is the capability of the app to view information about network connections such as which networks exist and are connected.
- **change network connectivity**: Allows the app to change the state of network connectivity.
- **view Wi-Fi connections**: This capability allows the app to view information about wifi networking such as whether wifi is enabled and the name of connected wifi devices.
- **connect and disconnect from Wi-Fi**: Allows the app to connect to and disconnect from Wi-Fi access points and to make changes to device configuration for Wi-Fi networks.
- **prevent phone from sleeping**: Allows the app to prevent the phone from going to sleep.

The information that may be collected with these permissions are stored locally on the device and the developer has no access to that information. These permissions can be revoked when they are not needed, this is privy to only devices running Android 6.0 upward.

## Types of Data Collected

### Personal Data
The developer doesn't collect personally identifiable data. Only except when you send crash logs.

### Usage Data
The developer doesn't collect usage data.

### Installation Data
The developer distributes this software via google play store where download counts are maintained. But, the developer has no knowledge or way to acquire knowledge about a user that has installed or is using this software.

## Crash reports
The developer is unable to get crash reports automatically when the app crashes. If you encounter a bug that caused the app to crash, please report it to the developer.
DMusic is a project under active development and the developer needs to get information when it doesn't work, to make it work. If you encounter any error while using the software, please open an [issue](https://github.com/Dsiner/DMusic/issues/new) on GitHub and it will be fixed. In a case where the app crashes, try to include logcats in your reports, when possible.

## Service Providers

DMusic depends on the services of third-party libraries to facilitate its utilization, and to perform service-related services, or, to assist in analyzing how the services of the software are used. These third parties don't have access to your Personal Data but are used only to perform some tasks on the developer's behalf.

## Transfer Of Data
With these third-party libraries contained in the software, your information, including personal data, may be transferred to computers located outside of your state, province, country or other governmental jurisdiction where the data protection laws may differ than those from your jurisdiction. Your consent to this Privacy Policy followed by your submission of such information represents your agreement to that transfer.

## Links To Other Sites

DMusic contains links to other services that are not directly operated by the developer. If you click on a third party library webpage or license URL, you will be directed to that third party's site. The developer has no control over and assumes no responsibility for the content, privacy policies or practices of any third party sites or services.

## Children's policy

This software is intended for general use and has no restrictions on utilization by children except otherwise stated in a law governing that locale.

## Security Of Data

The security of your data is important, but remember that no method of transmission over the Internet or method of electronic storage is 100% secure therefore the developer doesn't guarantee its absolute security.

## Changes To This Privacy Policy

The developer may update this policy as there will be further development of the software and these developments may not be consistent with this current policy. It is advisable to check this policy occasionally for any changes. Changes to this Privacy Policy are effective when they are made on this document.

## Disclaimer

DMusic is developed in good faith and for general use. The developer will not be held accountable for how you decide to use this software and will not be liable for any losses and/or damages in connection with the use of the software.

## Contact

Contributions to this project are welcomed. Contributions, suggestions or bug reports and fixes can be made by opening an issue or creating pull requests. Read our contributor's guidelines [here]() to get started.
If you have any questions about this Privacy Policy, or any other issue relating to DMusic, please contact us [here](https://github.com/Dsiner/DMusic) by opening an [issue](https://github.com/Dsiner/DMusic/issues/new).

repository: Dsiner/DMusic

path: /Privacy policy.md

filename: Privacy policy.md

gha_language: Java

repo_name: Dsiner/DMusic


text:
Please read the "Showoff User Manual" document for more information.

Tools & Technologies Used:
PHP 5.6.40
CSS 3
JS ES5
HTML5
BS4
WAMP Server
Codeigniter 3
Github
Heroku

Github Source code Link:
https://github.com/tarakantnayak/Showoff.git

Heroku:
Staging: https://damp-wildwood-56440.herokuapp.com/
Production: https://showtarak.herokuapp.com/
	Environment variables are set-up so that, there is no dependency on the code. It can be seamlessly deployed into any environment.

repository: tarakantnayak/Showoff

repo_name: tarakantnayak/Showoff


text:
TrackMyMoney
============

TrackMyMoney is a simple web application for managing personal outgoings, developed with Tornado.
I decided to make public this old project of mine: it was one of my first steps in writing web application using Python as backend programming language.

In this project I have used:
* [Cosmo](http://bootswatch.com/cosmo/): free theme built with [Bootstrap](http://bootstrapdocs.com/v2.2.2/docs/)
* [jQuery](http://jquery.com/download/)
* [jqPlot](http://www.jqplot.com/) for plotting graphs
* [jQuery Validation Plugin](http://jqueryvalidation.org/) for validating forms
* [Bootbox](http://bootboxjs.com/) for a unified style with dialog boxes.
* MySQL

Installation and Configuration
------------------------------

Tornado can be installed with `pip` or `easy_install`:

    pip install tornado

Create a MySQL database, database user and password and import generic dump:

    mysql -u user -ppassword database < trackmymoney.db.sql

Apply correct configuration in `config.py` and launch the server with command:

    python main.py

Open your browser at `http://localhost:port` and access with (admin, admin).
Password are stored clear. If you want to change then you can manually edit `trackmymoney.db.sql`

repository: mr--dev/trackmymoney

repo_name: mr--dev/trackmymoney


text:
---
title: "The Interlocked class"
date: 2007-09-05 22:50
author: saguiitay
categories: [Development]
tags: [.Net]
redirect_from:
 - /2007-09-05-the-interlocked-class/
 - /development/the-interlocked-class/
---
Working with threads and counters can because a really pain if you do not take care.
Fortunetly for us, .Net supplies us with a couple of methods that can make our life a little bit easier.
The class `Interlocked`, which can be found in `System.Thread` allows you to increment, decrement, and set the
value of an int or long as an atomic action, thus preventing race conditions where multiple threads update the
same counter at the same time.

The first methods are of course, `Increment()` and `Decrement()`, both accepting an int or long variable and
update it as requested. The next method is the `Exchange()`, which allow you to set the value of either an int,
a long or object variable, by passing it the variable by reference, and the next requested value.

Another interesting method in the `CompareExchange()`. This method checks if the value of the variable is as
expected, and only then update it. The methos returns the current value of the variable, whether it was updated
or not, allowing you to redo you calculations if the value changed while you were calculating the new value.

Below is an example take from [MSDN](http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemthreadinginterlockedclasscompareexchangetopic.asp):

{% highlight csharp %}
public int AddToTotal(int addend)
{
    int initialValue, computedValue;
    do
    {
        initialValue = totalValue;
        computedValue = initialValue + addend;
    }
    while (initialValue != Interlocked.CompareExchange(ref totalValue, computedValue, initialValue));
    return computedValue;
}
{% endhighlight %}


text:
This is not yet ready for release.

This is a port of Caffeine originally written for Java by Ben Manes. (https://github.com/ben-manes/caffeine)
This version of Caffeine.NET has been written for .NET Core 2.1 (https://github.com/dotnet/core/releases)

This is still in development. A good bulk of the code has been written, but there remains a lot of debugging and testing to be done. If you're interested in helping let us know. We're looking for committers.

We ommitted Weak References for this version. In Java there is something known as a ReferenceQueue. When a weak reference is collected it's added to that queue. This allows removing the collected weak references by simply iterating that queue. There is no equivalent in .NET., making it problematic for knowing when to remove an item from the cache.

The underlying cache can be accessed as a concurrent dictionary by the function AsConcurrentDictionary() from the ICache interface. The only ConcurrentDictionary functions that have been implemented are
- IsEmpty
- Count
- Clear
- ContainsKey
- TryGetValue
- Remove
- TryRemove

We have not implemented the Loading caches yet nor the Async caches. While some of the code exists there remains work to finish these features.


text:
# Incremental Analysis

Incremental aggregation allows you to obtain aggregates in an
incremental manner for a specified set of time periods.

This not only allows you to calculate aggregations with varied time
granularity, but also allows you to access them in an interactive manner
for reports, dashboards, and for further processing. Its schema is
defined via the aggregation definition.

-   [Configuring aggregation
    queries](#IncrementalAnalysis-Configuringaggregationqueries)
-   [Incremental aggregation in single-node deployments and HA
    deployments](#IncrementalAnalysis-Incrementalaggregationinsingle-nodedeploymentsandHAdeployments)
-   [Scaling through distributed
    aggregations](#IncrementalAnalysis-ScalingthroughdistributedaggregationsPartitionAggregation)

## Configuring aggregation queries

This section explains how to calculate aggregates in an incremental
manner for different sets of time periods, store the calculated values
in a data store and then retrieve that information.

To demonstrate this, consider a scenario where a business that sells
multiple brands stores its sales data in a physicaldatabase for the
purpose of retrieving them later to perform sales analysis. Each sales
transaction is received with the following details:

-   `          symbol         ` : The symbol that represents the brand
    of the items sold.
-   `          price         ` : the price at which each item was sold.
-   `          amount         ` : The number of items sold.

The Sales Analyst needs to retrieve the total number of items sold of
each brand per month, per week, per day etc., and then retrieve these
totals for specific time durations to prepare sales analysis reports.

To address the above use case, Siddhi queries need to be designed in two
steps as follows:

-   [Step 1: Calculate and persist time-based aggregate
    values](#IncrementalAnalysis-Step1:Calculateandpersisttime-basedaggregatevalues)
-   [Step 2: Retrieve calculated and persisted aggregate
    values](#IncrementalAnalysis-Step2:RetrievecalculatedandpersistedaggregatevaluesRetrieveAggregations)

### Step 1: Calculate and persist time-based aggregate values

!!! tip

Before you begin:

Before creating queries to calculate and persist aggregate values, the
following prerequisites need to be completed:

-   When you are defining a physical store to store aggregate values,
    you need to first download, install and set up the required database
    type. For more information about setting up the database, see
    [Defining Tables for Physical
    Stores](_Defining_Tables_for_Physical_Stores_) .
-   If the aggregation query included in the Siddhi application is only
    for read-only purposes, disable data purging.

To write the required Siddhi queries to calculate and persist aggregate
values required for the scenario outlined above, follow the steps below:

1.  To capture the input events based on which the aggregations are
    calculated, define an input stream as follows. The stream definition
    includes attributes named symbol, price and amount to capture the
    details described above.

    `             define stream TradeStream (symbol string, price double, quantity long, timestamp long);            `

    The stream definition includes attributes named
    `           symbol          ` , `           price          ` and
    `           amount          ` to capture the details described
    above. In addition, it has an attribute named
    `           timestamp          ` to capture the time at which the
    sales transaction occurs. The aggregations are executed based on
    this time.

        !!! info

        This attribute's value could either be a long value (reflecting the
        Unix timestamp in milliseconds), or a string value adhering to one
        of the following formats.

        -   **`             <yyyy>-<MM>-<dd> <HH>:<mm>:<ss> <Z>            `**
            : This format can be used if the timezone needs to be specified
            explicitly. Here the ISO 8601 UTC offset must be provided for
            \<Z\> . e.g., +05:30 reflects the India Time Zone. If time is
            not in GMT, this value must be provided.)
        -   **`             <yyyy>-<MM>-<dd> <HH>:<mm>:<ss>            `** :
            This format can be used if the timezone is in GMT.

2.  To persist the aggregates that are calculated via your Siddhi
    application, include a store definition as follows, if not the data
    is stored in-memory and lost when siddhi app is stopped.

    `             define stream TradeStream (symbol string, price double, quantity long, timestamp long);            `

    **`              @store(type='rdbms', jdbc.url="jdbc:                             mysql://localhost:3306/TestDB                            ", username="root", password="root" ,                             jdbc.driver.name                            ="com.mysql.jdbc.Driver")             `**

3.  Define an aggregation as follows. You can name it
    `           TradeAggregation          ` .

        !!! info

        When you save aggregate values in a store, the system uses the
        aggregation name you define here as part of the database table name.
        Table name is
        `           <Aggregation_Name>_<Granularity>          ` . Some
        database types have length limitations for table names (e.g., for
        Oracle, it is 30 characters). Therefore, you need to check whether
        the database type you have used for the store has such table name
        length limitation, and make sure that the aggregation name does not
        exceed that maximum length.

        define aggregation TradeAggregation

4.  To calculate aggregations, include a query as follows:
    1.  To get input `             events            ` from the
        `             TradeStream            ` stream that you
        previously defined, add a `             from            ` clause
        as follows.

        `               define aggregation TradeAggregation              `

        **`                 from TradeStream                `**

    2.  To select attributes to be included in the output event, add a
        `             select            ` clause as follows.

        `               define aggregation TradeAggregation              `

        `                from TradeStream               `
        **`                 select symbol, avg(price) as avgPrice, sum(quantity) as total                `**

        Based on this, each output event has the following attributes.

        | Attribute                                   | Description                                                                                |
        |---------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
        | `                 symbol                `   | The symbol representing the product sold is included in each output event.                                                                                |
        | `                 avgPrice                ` | The average price at which the brand is sold. This is derived by applying the `                 avg()                ` function to the `                 price                ` attribute with each input event. |
        | `                 total                `    | The total number of items sold for each product. This is derived by applying the `                 sum()                ` function to the quantity attribute with each input event.                              |

        The average price and the total number of items are the
        aggregates calculated in this scenario.

    3.  To group the output by the symbol, add a
        `             group by            ` clause as follows.

        `               define aggregation TradeAggregation              `

        `                from TradeStream               `
        `                select symbol, avg(price) as avgPrice, sum(quantity) as total               `

        **`                group by symbol               `**

        The group by clause is optional in incremental aggregations. If
        it is not provided, all the events are aggregated together for
        each duration.

    4.  The timestamp included in each input event allows you to
        calculate aggregates for the range of time granularities
        seconds-years. Therefore, to calculate aggregates for each time
        granularity within this range, add the
        `             aggregate by            ` clause to this aggregate
        query as follows.

        `               define aggregation TradeAggregation              `

        `                from TradeStream               `
        `                select symbol, avg(price) as avgPrice, sum(quantity) as total               `

        `               group by symbol              `

        **`                aggregate by timestamp every sec ... year;               `**

        This results in the average price and the total number of items
        sold being calculated per second, minute, hour, day, month and
        year. These time-based calculations are saved in the MySQL store
        you defined.

                !!! warning

                If you exclude one or more time granularities from this range,
                you cannot later retrieve aggregates for them. e.g., You cannot
                aggregate by timestamp every
                `             sec ... day            ` in the aggregate
                definition, and then attempt to retrieve per
                `             months            ` . This is because monthly
                values are not calculated and persisted.

                !!! info

                You can also provide comma-separated values such as
                `             every day, month,            ` ...

        The complete Siddhi application with all the definitions and
        queries added looks as follows.

        ``` sql
                @App:name('TradeApp')

                define stream TradeStream (symbol string, price double, quantity long, timestamp long);

                @store(type='rdbms', jdbc.url="jdbc:mysql://localhost:3306/TestDB", username="root", password="root" , jdbc.driver.name="com.mysql.jdbc.Driver")

                define aggregation TradeAggregation
                from TradeStream
                select symbol, avg(price) as avgPrice, sum(quantity) as total
                group by symbol
                aggregate by timestamp every sec ... year;
        ```

The following is a list of optional annotations supported for
incremental aggregation.

-   **`            @store(type=<store type>, ...)           `**
    The aggregated results are stored in the database defined via this
    annotation in tables corresponding to each aggregate duration. For
    more information on how to define a store, see [Defining Tables for
    Physical Stores](_Defining_Tables_for_Physical_Stores_) .

        !!! info

        When these database entries are created, the primary key is defined
        internally. Therefore, you must not include an
        `           @PrimaryKey          ` annotation within this
        `           @store          ` annotation in the aggregation
        definition.

    If a store is not defined via this annotation, the aggregated
    results are stored in in-memory tables by default. Adding a specific
    store definition is useful in a production environment. This is
    because the aggregations stored in in-memory tables can be lost if a
    system failure occurs.

    The names of the tables are created in the
    `           <AGGREGATION_NAME>_<DURATION>          ` format. In this
    scenario, the following tables are created:

    -   `             TradeAggregation_SECONDS            `

    -   `             TradeAggregation_MINUTES            `

    -   `             TradeAggregation_HOURS            `

    -   `             TradeAggregation_DAYS            `

    -   `             TradeAggregation_MONTHS            `

    -   `             TradeAggregation_YEARS            `

    The primary keys of these tables are determined as follows:
    ![](attachments/112390719/112390725.png){width="500"}

    `           AGG_TIMESTAMP          ` and
    `           AGG_EVENT_TIMESTAMP          ` are internally calculated
    values that reflect the time bucket of an aggregation for a
    particular duration. e.g. for the `           day          `
    aggregations, `           AGG_TIMESTAMP =<PHONE_NUMBER>000          `
    reflects that it is the aggregation for the 5th of January 2018 (
    `<PHONE_NUMBER>000          ` is the Unix time for
    `           2018-01-05 00:00:00          ` ). All aggregations are
    based on GMT timezone.

    The other values stored in the table would be aggregations and other
    function calculations done in the aggregate definition. If any such
    function calculation is not an aggregation, the output value
    corresponds with the function calculation for the latest event of
    that time bucket. e.g., If a multiplication is carried out, the
    multiplication value corresponds with the latest event's
    multiplication as per the duration.

    Certain aggregations are internally stored as a collection of other
    aggregations. e.g., the average aggregation is internally calculated
    as a function of sum and count. Hence, the table only reflects a sum
    and a count. The actual average is returned when the user retrieves
    the aggregate values as described in [Step 2: Retrieve calculated
    and persisted aggregate
    values](#IncrementalAnalysis-RetrieveAggregations) .

    The other values stored in the database table are aggregations and
    other function calculations carried out via the aggregation
    definition.

    In the scenario described in this section, a timestamp is assigned
    to each input event via the `           timestamp          `
    attribute, and `           symbol          ` is the
    `           group by          ` key. Therefore, the
    `           TestDB          ` store defined via the
    `           @store          ` annotation uses the
    `           AGG_EVENT_TIMESTAMP          ` and
    `           symbol          ` attributes as primary keys. Each
    record . in this store must have a unique combination of values for
    these two attributes.

-   **`           @purge          `**

    This specifies whether automatic data purging is enabled or not. If
    automatic data purging is enabled, you need to specify the time
    interval at which the data purging should be carried out. In
    addition, you need to specify the time period for which the data
    should be retained based on the granularity by including the
    `           @retentionPeriod          ` annotation (described
    below). If this annotation is not included in an incremental
    aggregation query, the data purging is carried out every 15 minutes
    based on the default retention periods mentioned in the description
    of the `           @retentionPeriod          ` annotation.

        !!! tip

        If you want to disable automatic data purging, you can use this
        annotation as follows:

        `           @purge(enable="false")          `

        You should disable data purging if the aggregation query is included
        in the Siddhi application for read-only purposes.

    <colgroup>
    <col style="width: 100%" />
    </colgroup>

-   **`           @retentionPeriod          `**

    This specifies the time period for which data needs to be retained
    before it is purged, based on the granularity. The retention period
    defined for each granularity should be greater than, or equal to the
    minimum retention period as given below:

    -   `            second           ` : 120 seconds
    -   `            minute           ` : 120 minutes
    -   `            hour           ` : 25 hours
    -   `            day           ` : 32 days
    -   `            month           ` : 13 months
    -   `            year           ` : none

    If the retention period is not specified, the default retention
    period for each granularity is applied as given below:

    -   `            second           ` : 120 seconds
    -   `            minute           ` : 24 hours
    -   `            hour           ` : 30 days
    -   `            day           ` : 1 year
    -   `            month           ` : All
    -   `            year           ` : All

### Step 2: Retrieve calculated and persisted aggregate values

This step involves retrieving the aggregate values that you calculated
and persisted in Step 1. To do this, let's add the Siddhi definitions
and queries required for retrieval to the `         TradeApp        `
Siddhi application that you have already started creating for this
scenario.

!!! info

Retrieval logic for the same aggregation can be defined in different
Siddhi app. However, only one aggregation should carry out the
processing (i.e. the aggregation input stream should only feed events to
one aggregation definition).

For this scenario, let's assume that the Sales Analyst needs to retrieve
the sales totals for the time duration between 15th February 2014 and
16th March 2014.

1.  To retrieve aggregations, you need to make retrieval requests. To
    capture these requests as events, let's define a stream as follows.

    `             @App:name('TradeApp')                          define stream TradeStream (symbol string, price double, quantity long, timestamp long);                         `

    **`              define stream TradeSummaryRetrievalStream (symbol string);             `**

    `             @store(type='rdbms', jdbc.url="jdbc:mysql://localhost:3306/TestDB", username="root", password="root" , jdbc.driver.name="com.mysql.jdbc.Driver")                          define aggregation TradeAggregation                          from TradeStream select symbol, avg(price) as avgPrice, sum(quantity) as total group by symbol aggregate by timestamp every sec ... year;            `

2.  To process the events captured via the
    `           TradeSummaryRetrievalStream          ` stream you
    defined, add a new query as follows.

        from TradeSummaryRetrievalStream as b join TradeAggregation as a
        on a.symbol == b.symbol
        within "2014-02-15 00:00:00 +05:30", "2014-03-16 00:00:00 +05:30"
        per "days"
        select a.symbol, a.total, a.avgPrice
        insert into TradeSummaryStream;

    This query matches events in the
    `           TradeSummaryRetrievalStream          ` stream and the
    `           TradeAggregation          ` aggregation that was defined
    in step 1 based on the value for the `           symbol          `
    attribute, and performs a join for each matching pair. Based on that
    join, it produces an output event(s) with the
    `           symbo          ` l, `           total          ` and
    `           avgPrice          ` attributes for the day granularity
    within the time range `           2014-02-15 00:00:00          ` to
    `           2014-03-16 00:00:00          ` . The time zone is
    represented by `           +05:30          ` .

    Note the following about the query given above:

    -   The **`             on            `** condition is optional for
        retrieval.
    -   You can provide the **`             within            `**
        duration in two ways as follows:
        -   **`               within <start_time>, <end_time>              `**
            : The `              <start_time>             ` and
            `              <end_time>             ` can be
            `              STRING             ` or
            `              LONG             ` values. If it is a string
            value, the format needs to be
            `              <yyyy>-<MM>-<dd> <HH>:<mm>:<ss> <Z>             `
            ( `              <Z>             ` represents the timezone.
            It can be omitted if the time is in GMT).  You can provide
            long values if you need to specify the times as Unix
            timestamps (in milliseconds). In the above query, you are
            specifying the time duration via this method in the
            `              STRING             ` format.
        -   **`               within <within_duration>              `**
            : This method allows you to enter the time duration only as
            a STRING value. The format can be one of the following:
            -   `                <yyyy>-**-** **:**:** <Z>               `
            -   `                <yyyy>-<MM>-** **:**:** <Z>               `
            -   `                <yyyy>-<MM>-<dd> **:**:** <Z>               `
            -   `                <yyyy>-<MM>-<dd> <HH>:**:** <Z>               `
            -   `                <yyyy>-<MM>-<dd> <HH>:<mm>:** <Z>               `
            -   `                <yyyy>-<MM>-<dd> <HH>:<mm>:<ss> <Z>                                               `

            e.g., If the duration is specified as
            `              2018-01-** **:**:**             ` , it means
            within the first month of 2018. This is equal to the
            `              2018-01-01 00:00:00", "2018-02-01 00:00:00             `
            clause provided as per the previous method.

            You do not need to specify the timezone via
            `              <Z>             ` if the time is in GMT.
    -   The `            per           ` clause specifies the time
        granularity for which the aggregations need to be retrieved. The
        value for this clause can be `            seconds           ` ,
        `            minutes           ` ,
        `            hours           ` , `            days           ` ,
        `            months           ` , or
        `            years           ` . The time granularity for which
        you want to retrieve values must have been included in the time
        range you specified when calculating and persisting aggregates.
        For more information, see [Calculating and persisting time-based
        aggregate values - Step 4, substep
        d](#IncrementalAnalysis-SelectTimeRange) .
    -   The output contains the `            total           ` and
        `            avgPrice           ` per
        `            symbol           ` for all the days falling within
        the given time range.

!!! tip

The following are other ways in which you can construct the query to
retrieve aggregate values:

-   Instead of providing the within and per values as constants in the
    query itself, you can retrieve them via attributes in the input
    stream definition as shown below.
    1.  Define the input stream as follows.

            define stream TradeSummaryRetrievalStream (symbol string, startTime long, endTime long, perDuration string);

        The above schema allows you to enter the start time and the end
        time of the time duration for which you want to retrieve
        aggregates in the aggregate retrieval request by including
        values for the `             startTime            ` and
        `             endTime            ` attributes. The time
        granularity for which the aggregations need to be retrieved can
        be specified as the value for the
        `             perDuration            ` attribute.

    2.  Then add the query as follows.

        `               from TradeSummaryRetrievalStream as b join TradeAggregation as a on a.symbol == b.symbol                               within b.startTime, b.endTime per b.perDuration                              select a.symbol, a.total, a.avgPrice  insert into TradeSummaryStream;              `

        Here, the `             within            ` and
        `             per            ` clauses refer to the attributes
        in the input stream that specify the time duration and the per
        duration.

-   If you want the retrieved aggregates to be sorted in the ascending
    order based on time, include the
    `           AGG_TIMESTAMP          ` in the
    `           select          ` clause as shown below. Once it is
    included in the `           select          ` clause, you can add
    the `           order by AGG_TIMESTAMP          ` clause.

    `             from TradeSummaryRetrievalStream as b join TradeAggregation as a on a.symbol == b.symbol  within "2014-02-15 00:00:00 +05:30", "2014-03-16 00:00:00 +05:30"  per "days"  select                           AGG_TIMESTAMP                          , a.symbol, a.total, a.avgPrice                           order by AGG_TIMESTAMP                          insert into TradeSummaryStream;            `

## Incremental aggregation in single-node deployments and HA deployments

In order to understand how incremental aggregation is carried out in
different deployment, consider the following example that explains how
the aggregation is executed internally.

Assume that six events arrive in the following sequence, with the given
timestamps.

-   event 0 → 2018-01-01 05:59:58
-   event 1 → 2018-01-01 05:59:58
-   event 2 → 2018-01-01 05:59:59
-   event 3 → 2018-01-01 06:00:00
-   event 4 → 2018-01-01 06:00:01
-   event 5 → 2018-01-01 06:00:02

In this scenario, the aggregation is done for second, minute and hour
durations. Therefore, based on the above timestamps, the second, minute,
and hour during which each event occured is as follows.

![](attachments/112390719/112390724.png){width="500"}

As mentioned before, when storing, time based aggregatesa table is
created for each time granularity in the
`         <AGGREGATE_NAME>_<TIME_GRANUARITY>        ` format. Assuming
that the name of the aggregation in `         TradeAggregation        `
, three tables are created as follows.

-   `          TradeAggregation_SECONDS         `
-   `          TradeAggregation_MINUTES         `
-   `          TradeAggregation_HOURS         `

The incremental analysis related execution that is carried out by the
system with the arrival of each event is described in the table below.

<colgroup>
<col style="width: 5%" />
<col style="width: 94%" />
</colgroup>

Arriving Event
Execution

0
The system initially processes event 0 at the              SECOND             executor level. The aggregation is retained in memory until the 58th second elapses.

1
This event also occurs during the 58th second (same as event 0). Therefore, the system aggregates events 0 and 1 together.

2

Event 2 arrives during the 59th second. The 58th second has elapsed at the time of this event arrival. Therefore, the system does the following:

Writes the aggregation for the 58th second (i.e., the total aggregation for events 0 and 1) to the                TradeAggregation_SECONDS               table and then forwards the aggregation to be processed at the                MINUTE               executor level.

Processes event 2 in the in-memory table at t he                SECOND               executor level for the 59th second.

3

Event 3 arrives during the second 0 of 06.00 minute. With this arrival, the aggregations for the 59th second and 59th minute expire. Therefore, the system does the following:

Writes the aggregation for the 59th second (i.e., aggregation of event 2) to the                TradeAggregation_SECONDS               table, and forwards the aggregation to be processed at the                MINUTE               executor level .

Writes the aggregation for the 59th minute to the                TradeAggregation_MINUTES               table, and forwards the aggregation to be processed at the                HOUR               execution level. The                HOUR               executor processes this for the 5th hour.

Processes event 3 in the in-memory table at the                SECOND               executor level.

4

At the time event 4 arrives during the 1st second of the 06.00 minute, second 0 of the same minute has elapsed. Therefore, the system does the following:

Writes the aggregation for second 0 to the                TradeAggregation_SECONDS               table, and forwards the aggregation to be processed at the                MINUTE               executor level.

Processes event 4 in the in-memory table at the                SECOND               executor level.

5

Event 5 arrives during the 2nd second. At this time, the 1st second has elapsed. Therefore, the system does the following:

Writes the aggregation for the 1st second (i.e., aggregation for event 4) to the                TradeAggregation_SECONDS               table, and forwards the aggregation to be processed at the                MINUTE               executor level. Once the aggregation for event 4 is forwarded to the                MINUTE               executor level, events 3 and 4 are aggregated together because they occured during the same minute.

Processes event 5 in the in-memory table at the                SECOND               executor level.

The following is the aggregation status after all six events have
arrrived.

In-memory Table
Available Aggregation Records
Processing In-Memory

             TradeAggregation_SECONDS

Aggregation for                2018-01-01 05:59:58               (Aggregation of event 0 and 1)

Aggregation for                2018-01-01 05:59:59               (event 2)

Aggregation for                2018-01-01 06:00:00               (event 3)

Aggregation for                2018-01-01 06:00:01               (event 4)

Aggregation for               2018-01-01 06:00:02              (event 5)

             TradeAggregation_MINUTES

Aggregation for               2018-01-01 05:59:00              (Aggregation of event 0, 1 and 2)

Aggregation for 2018-01-01 06:00:00 (i.e., minute 0 of the 6th hour. Here, event 3 and 4 are aggregated together.)

             TradeAggregation_HOURS
None
Aggregation for 2018-01-01 05:00:00 (i.e., the 5th hour. Here, events 0,1, and 2 are aggregated together.)

Now let's consider how the scenario described above works in a single
node deployment and an HA deployment.

-   **Single node deployment**
    If the `          @store         ` configurtation is not provided,
    the  system stores older aggregations (i.e., aggregations that are
    already completed for a particular second, minute etc., and
    therefore not running in-memory) in in-memory tables. In such a
    situation, a server failure results in all these aggregations done
    up to the time of the failure being lost.

    If a database configuration is provided via the
    `          @store         ` annotation, the older aggregations are
    stored in the external database. Therefore, if the node fails, the
    system recreates the in-memory running aggregations from this stored
    data once you restart the server. In the given scenario, in-memory
    aggregations for the `          MINUTE         ` execution level can
    be recreated with data in the
    `          TradeAggregation_SECONDS         ` table (i.e., points 3
    and 4 in the above aggregation status summary table). Similarly,
    in-memory aggregations for the `          HOUR         ` execution
    level can be recreated from the
    `          TradeAggregation_MINUTES         ` table.

    However, the recreation described above cannot be done for the most
    granular duration for which aggregation done. e.g., In the given
    scenario, the system cannot recreate  the in-memory aggregations for
    the `          SECOND         ` execution level because there is no
    database table for a prior duration.

    Assume that in the given scenario, a server failure occurs after all
    five events have arrived. Once you restart the server, only event 5
    is lost because that was the only aggregation being executed for the
    `          SECOND         ` execution level in the in-memory tables
    at that time.
-   **HA deployment**

        !!! info

        To understand how WSO2 SP runs as a minimum HA cluster, see [Minimum
        High Availability (HA)
        Deployment](https://docs.wso2.com/display/SP400/Minimum+High+Availability+%2528HA%2529+Deployment)
        .

    In a minimum HA setup, one runs as an active node and the other is
    passive. No events are lost even if the
    `           @store          ` configuration is not provided due to
    snapshoting the current state of SP. When a snapshot iof the SP
    state is created, the system does not recreate aggregations from
    tables because it is not required. The newly active node (which was
    previously passive) continues to process the new events that arrive
    after the failure of the other node as in a situation where no
    server failura has occured.

The following is a summary of the retrievability of aggregates based on
how they are stored and how WSO2 SP is deployed.

<colgroup>
<col style="width: 100%" />
</colgroup>

## Scaling through distributed aggregations

Distributed aggregations partially process aggregations in different
nodes. This allows you to assign one node to process only a part of an
aggregation (regional scaling, etc.). In order to do this all the
aggregations must have a physical database and must be linked to the
same database.

#### Syntax

The `         @PartitionById        ` annotation must be added before
the aggregation definition as shown below.

`           @store(type="<store type>", ...)                                `

**`            @PartitionById(enable='true')           `**

`           define aggregation <aggregator name>          `
`           from <input stream>          `

`           select <attribute name>, <aggregate function>(<attribute name>) as <attribute name>, ...          `

`           group by <attribute name>          `

`           aggregate by <timestamp attribute> every <time periods> ;          `

You can enable all Siddhi applications to partition aggregations in this
manner by adding the following system parameters in the
`         <SP_HOME>/conf/<PROFILE/deployment.yaml        ` file under
`         siddhi        ` .

``` xml
    siddhi:
      properties
        partitionById: true
        shardId: wso2-sp
```

A unique ID must be provided for each node via a system parameter named
`         shardId        ` . This parameter is required when
partitioning aggregations is enabled for a single Siddhi application as
well as when it is enabled for all Siddhi applications.

!!! tip

To maintain data consistency, do not change the shard IDs after the
first configuration.

When you enable the aggregation partitioning feature, a new column ID
named `         SHARD_ID        ` is introduced to the aggregation
tables. Therefore, you need to do one of the following options after
enabling this feature to avoid errors occuring due to the differences in
the table schema.

-   Delete all the aggregation tables for `          SECONDS         ` ,
    `          MINUTES         ` , `          HOURS         ` ,
    `          DAYS         ` , `          MONTHS         ` ,
    `          YEARS         ` .
-   Edit the aggregation tables by adding a new column named
    `          SHARD_ID         ` , and specify it as a primary key.

#### Example

The following query can be included in two Siddhi applications in two
different nodes that are connected to the same database. Separate input
events are generated for both nodes. Each node performs the aggregations
and stores the results in the database. When the aggregations are
retrieved, the collective result of both nodes are considered.

``` sql
    define stream TradeStream (symbol string, price double, quantity long, timestamp long);

    @store(type='rdbms', jdbc.url="jdbc:mysql://localhost:3306/TestDB", username="root", password="root" , jdbc.driver.name="com.mysql.jdbc.Driver")
    @PartitionById(enable='true')
    define aggregation TradeAggregation
    from TradeStream
    select symbol, avg(price) as avgPrice, sum(quantity) as total
    group by symbol
    aggregate by timestamp every sec ... year;
```

Let's assume that the following input events were generated for the two
nodes during a specific hour.

**Node 1**

| Event | symbol | price | quantity |
|-------|--------|-------|----------|
| 1     | wso2   | 100   | 10       |
| 2     | wso2   | 100   | 20       |

**Node 2**

| Event | symbol | price | quantity |
|-------|--------|-------|----------|
| 1     | wso2   | 100   | 10       |
| 2     | wso2   | 100   | 30       |

Here, node 1 calculates an hourly total of 30, and node 2 calculates an
hourly total of 40. When you retrieve the total for this hour via a
retrieval query, the result is 70.

!!! info

For more information about incremental aggregation, see [Siddhi Query
Guide - Incremental
Aggregation](https://siddhi-io.github.io/siddhi/documentation/siddhi-4.x/query-guide-4.x/#incremental-aggregation)
.


text:
---
id: adding-image-watermarks
url: watermark/net/adding-image-watermarks
title: Adding image watermarks
weight: 1
description: ""
keywords:
productName: GroupDocs.Watermark for .NET
hideChildren: True
---
GroupDocs.Watermar API supports adding the following image file types as image watermark:

* Bmp;
* Png;
* Gif;
* Jpeg.

## Add image watermark from local file

Following code snippet shows how to add [ImageWatermark](https://apireference.groupdocs.com/net/watermark/groupdocs.watermark.watermarks/imagewatermark) to a document. If the document consists of multiple parts (pages, worksheets, slides, frames etc), the watermark will be added to all of them.

**AdvancedUsage.AddingImageWatermarks.AddImageWatermark**

```csharp
// Constants.InPresentationPptx is an absolute or relative path to your document. Ex: @"C:\Docs\presentation.pptx"
using (Watermarker watermarker = new Watermarker(Constants.InPresentationPptx))
{
    // Use path to the image as constructor parameter
    using (ImageWatermark watermark = new ImageWatermark(Constants.WatermarkJpg))
    {
        // Add watermark to the document
        watermarker.Add(watermark);

        watermarker.Save(Constants.OutPresentationPptx);
    }
}
```

## Add image watermark from stream

You can also use a stream of the image to initialize [ImageWatermark](https://apireference.groupdocs.com/net/watermark/groupdocs.watermark.watermarks/imagewatermark) instance as shown in below example.

**AdvancedUsage.AddingImageWatermarks.AddImageWatermarkUsingStream**

```csharp
// Constants.WatermarkJpg is an absolute or relative path to your document. Ex: @"C:\Docs\watermark.jpg"
using (Stream watermarkStream = File.OpenRead(Constants.WatermarkJpg))
{
    using (Watermarker watermarker = new Watermarker(Constants.InImagePng))
    {
        // Use stream containing an image as constructor parameter
        using (ImageWatermark watermark = new ImageWatermark(watermarkStream))
        {
            // Add watermark to the document
            watermarker.Add(watermark);

            watermarker.Save(Constants.OutImagePng);
        }
    }
}
```

{{< alert style="warning" >}}
[ImageWatermark](https://apireference.groupdocs.com/net/watermark/groupdocs.watermark.watermarks/imagewatermark) class implements [IDisposable](https://docs.microsoft.com/en-us/dotnet/api/system.idisposable) interface. Therefore, it is necessary to call [Dispose](https://docs.microsoft.com/en-us/dotnet/api/system.idisposable.dispose) method when you are done working with the watermark. Alternatively, you can use [using](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement) statement.
{{< /alert >}}

For the advanced use of image watermark properties please check the following article about text watermarks, however same techniques will work for image watermark as well:

* [Adding Text Watermarks]({{< ref "watermark/net/developer-guide/advanced-usage/adding-watermarks/adding-text-watermarks.md" >}})

## More resources

### GitHub examples

You may easily run the code above and see the feature in action in our GitHub examples:

* [GroupDocs.Watermark for .NET examples](https://github.com/groupdocs-watermark/GroupDocs.Watermark-for-.NET)
* [GroupDocs.Watermark for Java examples](https://github.com/groupdocs-watermark/GroupDocs.Watermark-for-Java)

### Free online document watermarking App

Along with full featured .NET library we provide simple, but powerful free Apps.

You are welcome to add watermark to PDF, DOC, DOCX, PPT, PPTX, XLS, XLSX, Emails and more with our free online [Free Online Document Watermarking App](https://products.groupdocs.app/watermark).


text:
## Laravel OTA (Over-The-Air) Distribution for iOS

[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
<!-- [![Build Status][ico-travis]][link-travis]
[![Total Downloads][ico-downloads]][link-downloads]-->

The package creates the necessary files and routes on your server to cater for the upload of iOS .ipa files and provision the installation of those builds on iOS devices.

### Great, how does it work?

The package allows an integration tool to submit an iOS build to your server - where you can act as the host - the package’s service provider creates the routes that 1) handle the submission of the build which in turn create the necessary manifest files, views, and the download page required for over the air distribution for ios devices, and routes to download the build using those generated files.

Note, since iOS 9, over-the-air distribution requires the https protocol or installation will fail.

## Installation

Require this package with composer:

```shell
composer require "pavankataria/laravel-ota-distribution-ios":"dev-master"
```

After updating composer, add the ServiceProvider to the providers array in config/app.php

### Laravel 5.x:

```php
PavanKataria\OtaDistributionIos\ServiceProvider::class,
```

Run the publish command to finish with the installation, copy the views to the views vendor directory. The routes that serve the build use these views.

```shell
php artisan vendor:publish --provider="PavanKataria\OtaDistributionIos\ServiceProvider"
```

### Lumen:

For Lumen, register a different Provider in `bootstrap/app.php`:

### License

The Laravel OTA Distribution for iOS package is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)

[ico-version]: https://img.shields.io/packagist/v/pavankataria/laravel-ota-distribution-ios.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/pavankataria/laravel-ota-distribution-ios/master.svg?style=flat-square
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/pavankataria/laravel-ota-distribution-ios.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/pavankataria/laravel-ota-distribution-ios.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/pavankataria/laravel-ota-distribution-ios.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/pavankataria/laravel-ota-distribution-ios
[link-travis]: https://travis-ci.org/pavankataria/laravel-ota-distribution-ios
[link-scrutinizer]: https://scrutinizer-ci.com/g/pavankataria/laravel-ota-distribution-ios
[link-code-quality]: https://scrutinizer-ci.com/g/pavankataria/laravel-ota-distribution-ios
[link-downloads]: https://packagist.org/packages/pavankataria/laravel-ota-distribution-ios
[link-author]: https://github.com/pavankataria
[link-contributors]: ../../contributors


text:
---
layout: post
title:  "HTTP Client"
date:   2018-09-01 12:11:10 -0500
categories: java
image: /assets/images/banners/HTTP_Client.png
author: pradeep
featured: false
---

In this article I will give a simple introduction of HttpClient class and then will use this class to develop a small HTTP program. This program will hit a HTTP end point at [http://numbersapi.com/](http://numbersapi.com/) This end point will take a number and returns an interesting fact about the given number.

In Java 11 HttpClient has moved from incubator module to base module under the java.net.http package. This package provides a high-level interfaces to HTTP and low-level interfaces to Websockets. This package provides all the required classes and interfaces to make a HTTP request.

We need to do below three actions to complete a full HTTP request

* Create HTTP request
* Create HTTP client
* Get HTTP response

Lets go through each of this action in below sections

## Create HTTP request

HttpRequest class represents the request object. This class contains all the functionality to handle HTTP requests some of them are like request URL, request headers, HTTP protocol version and request types (GET, POST, PUT).

{% highlight java %}
HttpRequest request = HttpRequest
                .newBuilder(URI.create("http://numbersapi.com/5"))
                .build();
{% endhighlight %}

newBuilder is a static method which will take a URI of the HTTP request and creates a Builder object. We called build on it to get HttpRequest object. If needed this request object can be cached to use multiple times.

## Create HTTP Client

Once we have request then we can pass it to HTTPClient. HTTPClient class is used to send and get the request and responses from the HTTP server. Below code snippet will send the request and returns the HTTPResponse.

{% highlight java %}
HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());
{% endhighlight %}

newHttpClient is a static method which will return an instance of HttpClient and we called send method on it. send method will take request and body handler instances. We will discuss about body handlers in the next section below. send is a synchronous call means this method will block the thread until the response receives from the server. We can make an asynchronous call by using sendAsync method like below

{% highlight java %}
HttpClient.newHttpClient()
        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .join();
{% endhighlight %}

sendAsync returns CompletableFuture<HttpResponse<String>>. Both send and sendAsync methods we return HttpResponse object. We will use this object in the below section.

## Get HTTP response

send and sendAsync methods in the HttpClient takes the request and Body handlers. Body handlers are used to indicate the response type from the HTTP server, for example response can be a simple string, byte stream or it can be a file to download so BodyHandlers builds the instance of HttpResponse, this is the reason HttpResponse is an interface and BodyHandler will create its instance based on the response type.

Below contains two code snippets to handle response with send and sendAsync;

{% highlight java %}
HttpRequest request = HttpRequest
                .newBuilder(URI.create("http://numbersapi.com/5"))
                .build();
//sync call
HttpResponse response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

//async call
HttpClient.newHttpClient()
        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .join();
{% endhighlight %}

Output
{% highlight bash %}
5 is the number of dots in a quincunx.
5 is the number of permanent members with veto power on the United Nations Security Council.
{% endhighlight %}

[http://numbersapi.com/](http://numbersapi.com/) responds with a random interesting fact about the provided number. In the above code snippet I made two HTTP calls (sync and async) for number 5 so there are two lines.

Now we have completed all three actions for a HTTP transaction now lets enhance this using Java streams. Lets make five HttpRequests with random numbers.

{% highlight java %}
new Random().ints(5, 1, 100)
        .mapToObj(number -> String.format("http://numbersapi.com/%d", number))
        .map(url -> HttpRequest.newBuilder(URI.create(url))
                .build())
        .map(request -> HttpClient.newHttpClient()
                .sendAsync(request, HttpResponse.BodyHandlers.ofString()))
        .forEach(response ->
                response.thenApply(HttpResponse::body)
                        .thenAccept(System.out::println)
                        .join()
        );
{% endhighlight %}

Output
{% highlight bash %}
91 is the atomic number of protactinium.
33 is the temperature at which water boils according to the Newton scale.
58 is the minimum wind speed (mph) needed to issue a Severe Thunderstorm Warning.
17 is the number of flames emanating from the grenade cap-badge of the Grenadier Guards.
8 is the number of principles of Yong in Chinese calligraphy.
{% endhighlight %}
We are generating five random numbers between 1 and 100 and mapping them to URL's and then creating HttpRequest for each URL and making requests with HttpClient, finally displaying the body content in the console.

## Conclusion

We went through different classes and interfaces in java.net.http package and created some sample HTTP requests.

gha_language: HTML


text:
---
title: Proxy-Normalizing Activations to Match Batch Normalization while Removing Batch Dependence
collection: talks
type: "Talk and Poster"
permalink: /talks/2021-12-07-NeurIPS
venue: NeurIPS 2021
date: 2021-12-07
location: "Online"
tag: recent
---

Presentation of my research on Proxy Norm at NeurIPS 2021.

[[Slides]](/files/2021-12-07-NeurIPS-talk.pdf) [[Poster]](/files/2021-12-07-NeurIPS-poster.pdf)


text:
# Colby Hill Portfolio

[![MIT license](https://img.shields.io/badge/License-MIT-blue.svg)](https://lbesson.mit-license.org/)
[![Actions Status](https://github.com/colbyhill21/PersonalWebsite/workflows/CI/badge.svg)](https://github.com/colbyhill21/PersonalWebsite/actions)

This is the repository for my website. Hosted at `https://www.colby-hill.com`

## Tools and Technologies

I designed the website using Adobe XD and developed it using Angular, HTML5, and CSS3. I leveraged numerous AWS services including S3, Route 53, Cloudfront, ACM, CodeBuild, CodePipeline, and CloudTrail to handle the website's storage, hosting, content delivery, certificate management, and CI/CD.

## Continuous Integration and Deployment

This repository is currently configured to automatically run testing and deploy to my S3 bucket upon each commit. This is handled using AWS's CodeBuild and CodePipeline services.

## Getting  started

First, run `npm install` in the project root directory to install all dependencies.
Then run `ng serve -o` which will build and then launch a server that will automatically open your default browser

## How to add a component

Since there are multiple modules in this project, you have to use the `--module` tag for the Angular-CLI to add a component.
`ng g c component-name --module app`

## License

This software is licensed under the MIT License.
See the [License](./LICENSE.md) for more information.


text:
In this section, we evaluate the following principles

1) Architectural Design Principles
We list three examples of architectural design principle violations in OpenMRS. Where possible, we will provide test cases for each example. If there's not an associated test case, we will describe the design principle violation and how we would fix it in a few paragraphs.

2) Usable Security Principles
We list three examples of usable security principle violations in OpenMRS. Where possible, we will write test cases for each example. If there's not an associated test case, we will describe the usability principle violation and how we would fix it in a few paragraphs.

3) Protection Poker
We recommend new functional requirements for OpenMRS to add functionality that is not in the system yet and rank security risk for each table and requirement.

4) Bug Fixes
We will submit bug fixes to OpenMRS

repository: genterist/openMRS-Security

repo_name: genterist/openMRS-Security


text:
# Symmetric Travelling Salesman Problem using Simulated Annealing

View paper [here](https://drive.google.com/open?id=18x4r-5cMFL3lseziqZBCMLisbarDMp1X).

***

The travelling salesman problem (TSP) is one of the most studied optimisation problems and has numerous applications, ranging from the drilling of printed circuit boards to route planning and logistics. This paper applies simulated annealing (SA), a heuristic method for approximating global optimums, to the TSP. A sequential implementation is provided as a benchmark, on which a number of optimisations are made. A parallel approach is implemented and its performance overheads investigated.


text:
## About

Challenge

## Installation

```bash
# clone repository
git clone https://github.com/rogerfernandezv/challenges2it.git

# Access the folder
cd challenges2it

# install components
composer install

# copy env
cp .env.example .env

# key generate
php artisan key:generate

# configure database on .env here simple example
DB_CONNECTION=mysql
DB_HOST=<IP_ADDRESS>
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

# migrate
php artisan migrate

# storage link
php artisan storage:link

# to testing using php builtin server
php artisan serve

# go to http://localhost:8000

# for unit test
composer test

```

## How to use

To test you can use Postman:
https://www.getpostman.com/

|      						| Method 	| Body 	| Description
| ---      					| ---       | ---	| ---
| /api/people  				| GET       | 		| list all peoples
| /api/people/{id}  		| GET       | 		| people detail with id = {id}
| /api/order  				| GET    	| 		| list all orders
| /api/order/{id}  			| GET    	| 		| order detail with id = {id}

## License

The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).


text:
---
title: Components
description: Components Guide for the OriginPHP Framework
extends: _layouts.documentation
section: content
---
# Components

`Components` are objects that you can share between `Controllers`. When you create a `Component`, you can use other `Components` within the `Component` and access the current `Controller`. If you are just looking to share code between `Controllers` then you should use [Concerns](/docs/controller/concerns) instead.

## Creating a Component

`Components` are stored in the `App/Http/Controller/Component` folder.

You can run the following command

```linux
$ bin/console generate component Math
```

This will create the `Component` and its test file.

For more information on code generation see the [code generation guide](/docs/development/code-generation).

```php
namespace App\Http\Controller\Component;
use Origin\Http\Controller\Component\Component;

class MathComponent extends Component
{
  public function sum(int $x,int $y): int
  {
    return $x+$y;
  }

  public function doSomethingWithControler(): void
  {
    $controller = $this->controller(); // get current controller
    $result = $controller->method('xyz');
  }
}
```

After a component is created the component `initialize` method will be called, this is where you can put any code that you need to be executed when a component is created. This is a hook so you don't need to override the `___construct()`.

## Loading Components

To load a component in the controller, you call `loadComponent` from within the `initialize` method so the the callbacks can be executed.

```php
class WidgetsController extends ApplicationController
{
  protected function initialize(array $config): void
  {
      parent::initialize($config);
      $this->loadComponent('Math');
  }
}
```

## Using Components

 To use a component, you call it from within your controller methods.

```php
class WidgetsController extends ApplicationController
{
  public function doSomething(): int
  {
    return $this->Math->sum(1,2);
  }
}
```

If you want to use a component within a component then you call the `loadComponent` method, the component will then be lazy loaded when you next call it. When you load a component within a component, this component will not have callbacks executed unless the component is already loaded in a controller.

```php
class MathComponent extends Component
{
   protected function initialize(array $config): void
    {
      $this->loadComponent('Math',$config);
    }
}
```

## Callbacks

There are two callbacks which Components use `startup` and `shutdown`. To use the callbacks, just create a method in your component with the callback name. Both these callbacks must be public since the `Controller` will call these.

### Startup callback

This called after the controller `startup` but before the controller action.

```php
public function startup()
{

}
```

### Shutdown callback

This is called after the controller action but before the controller `shutdown`.

```php
public function shutdown()
{

}
```

## Accessing the request object

If you need to access the request object from within the component.

```php
$request = $this->request();
```

## Accessing the response object

If you need to access the response object from within the component.

```php
$response = $this->response();
```

## Accessing the controller

When working with components, you may need to access the controller, this can be easily done by calling the controller method.

```php
$controller = $this->controller();
```

## Component Configuration

Components work with the `Configurable` package, standardizing and simplifying how you work with configuration. See the [ConfigTrait guide](/docs/configurable) for more information.

repository: originphp/website

gha_language: CSS

repo_name: originphp/website


text:
# Security reviewer

Reviewers seek to understand the system and probe its security.
Design level issues should be considered as well as any high
level problems with the project’s setup and operation. The [process](./)
is intended to provide an independent analysis based primarily on documents
provided by the project itself.

Reviewers may look at code, but aren't required to do so. Review of
documents includes asking questions to understand if there are hidden
assumptions, underestimated risk, or design issues that harm or risk
the security of the project.

Reviewers are encouraged to reach out to community members to resolve
some questions, especially involving deployment scenarios and the impact
of attacks.

## Qualifications

### Required

Unless approved by SIG-Security chairs, at least one of the reviewers will have previously performed a CNCF security assessment.  Exemptions to this are reviewed case by case upon established need by the CNCF SIG-Security chairs in order to bootstrap the process as appropriate.

### Preferred

It is preferred reviewers have previous experience performing formal or informal software or security audits or assessments for a variety of organizations.  An ideal reviewer should also have been the recipient of CNCF project security assessments for a software project they manage.

Note: Participation through shadowing is encouraged from members who are not qualified for security reviews, to facilitate their development of the necessary skills to be a reviewer in the future.

## Time and effort

The level of effort for the reviewers is expected to be 10 hours per review. Correspondance, project availability, and clarification of a project's scope or other details in the ticketed request for project security assessment may require additional time. However, analysis is expected to be concluded in a few weeks.  Effort is expected to include and may not be limited to:
* reviewing existing security documentation
* reviewing ticketed request for project security assessment
* analysis of security assertions and assumptions
* attending project presentation with Q&A
* discussion via Slack or additional live Q&A sessions

## Expectations

GitHub issues are assigned to security reviewers. Security reviewers are
expected to conduct an in-depth review described in the [Security Assessment
Guide](./).

## Conflict of interest

There is a possibility of a conflict of interest that can arise between a security reviewer and
the project being reviewed due to the closely-knit nature of the community. Having clear
guidelines for conflict of interest situations are important to prevent:

- Individuals from intentionally or unintentionally promote their own company's project
- SIG-Security chairs and assessment leads could intentionally or unintentionally limit the participation of an individual unfairly by asserting conflict of interest
- Security reviews being stalled while groups belabor on who should be allowed to participate

The conflicts of interest lie on a spectrum, and are classified into hard and soft conflicts.
Hard conflicts makes a reviewer ineligible to review a project.
A soft conflict allows a reviewer to review a project, but not as a [project lead](./project-lead.md).
A reviewer with a soft conflict is required to document the nature of the conflict in the
security assessment documentation. It is the responsibility of the security reviewer
to make known his/her own conflict of interests.

For each project, 2 SIG-Security chairs must sign off on the conflicts presented to them that the assessment lead has no conflicts, and reviewers have no hard conflicts. Reasons for accepting and rejecting conflicts should be documented.

Below are classifications of hard/soft conflicts.

Hard conflicts:
- Reviewer is a maintainer of the project
- Reviewer is a direct report of/to a maintainer of the project
- Reviewer is paid to work on the project
- Reviewer has significant financial interest directly tied to success of the project

Soft conflicts:
- Reviewer belongs to the same company/organization of the project, but does not work on the project
- Reviewer uses the project in his/her work
- Reviewer has contributed to the project.
- Reviewer has a personal stake in the project (personal relationships, etc.)

repository: unclepieman/sig-security

repo_name: unclepieman/sig-security