text:
project_path: /web/_project.yaml
book_path: /web/updates/_book.yaml
description: Trusted Web activities are a new way to integrate your web-app content such as your PWA with your Android app using a similar protocol to Chrome Custom Tabs.

{# wf_updated_on: 2017-12-18 #}
{# wf_published_on: 2017-10-24 #}
{# wf_tags: trusted-web-activity #}
{# wf_featured_image: /web/updates/images/generic/devices.png #}
{# wf_featured_snippet: Trusted Web activities are a new way to integrate your web-app content such as your PWA with your Android app using a similar protocol to Chrome Custom Tabs. #}
{# wf_blink_components: N/A #}

# Using Trusted Web Activity {: .page-title }

_Looking for the code?_

* [TrustedWebUtils Android Support Library API
  reference](https://developer.android.com/reference/android/support/customtabs/TrustedWebUtils.html)
* [Sample using
  TrustedWebUtils](https://github.com/GoogleChrome/custom-tabs-client/tree/master/svgomg)

There are many different ways to integrate web content on Android, each having
their own benefits and drawbacks. Developers have frequently asked for a simple
way to launch content fullscreen like a WebView, which is run using the latest
and preferred browser of the user.

At the Chrome Developer Summit 2017 (October 2017) we announced a new technology
called Trusted Web activities which are now available in [Chrome's
Canary](https://play.google.com/store/apps/details?id=com.chrome.canary) and
[Dev](https://play.google.com/store/apps/details?id=com.chrome.dev) channels.
Trusted Web activities are a new way to integrate _your_ web-app content such as
_your_ PWA with _your_ Android app using a protocol based on Custom Tabs.

There are a few things that make Trusted Web activities different from other
ways to integrate web content with your app:

1. Content in a Trusted Web activity is **trusted** -- the app and the site it
   opens are expected to come from the same developer. (This is verified using
   [Digital Asset Links](/digital-asset-links/v1/getting-started).)
1. Trusted Web activities come from the **web**: they're rendered by the user's
   browser, in exactly the same way as a user would see it in their browser
   except they are run fullscreen. Web content should be accessible and useful
   in the browser first.
1. Browsers are also updated independent of Android and your app -- Chrome, for
   example, is available back to Android Jelly Bean. That saves on APK size and
   ensures you can use a modern web runtime. (Note that since Lollipop, WebView
   has also been updated independent of Android, but there are a [significant
   number](https://developer.android.com/about/dashboards/index.html) of
   pre-Lollipop Android users.)
1. The host app doesn't have direct access to web content in a Trusted Web
   activity or any other kind of web state, like cookies and `localStorage`.
   Nevertheless, you can coordinate with the web content by passing data to and
   from the page in URLs (e.g. through query parameters, custom HTTP headers,
   and [intent URIs](https://developer.chrome.com/multidevice/android/intents).)
1. Transitions between web and native content are between **activities**. Each
   activity (i.e. screen) of your app is either completely provided by the web,
   or by an Android activity

To make it easier to test, there are currently no qualifications for content
opened in the preview of Trusted Web activities. You can expect, however, that
Trusted Web activities will ultimately need to meet [requirements similar to
improved Add to Home
screen](/web/fundamentals/app-install-banners/#what_are_the_criteria),
which is designed to be a baseline of interactivity and performance. You can
audit your site for these requirements using the
[Lighthouse](/web/tools/lighthouse/) "user can be
prompted to Add to Home screen" audit.

Today, if the user's version of Chrome doesn't support Trusted Web activities,
we'll fall back to a simple toolbar like the one you'd see in a Custom Tab. It
is also possible for other browsers to implement the same protocol that Trusted
Web activities use. While the host app has the final say on what browser gets
opened, we recommend the same policy as for Custom Tabs: use the user's default
browser, so long as that browser provides the required capabilities.

We hope that you can experiment with this API and give us feedback at
@[ChromiumDev](https://twitter.com/ChromiumDev)

## Getting started

You can quickly build an app that launches a Trusted Web activity in three
simple steps.

1. Set up Digital Asset Links in an Android app
1. Deploy your `assetlinks.json` to prove ownership of the domain
1. Create an activity that launches the Trusted Web Activity (you can use the
   Chrome Custom Tabs support library v27 or above to simplify the process)

[This sample](https://github.com/GoogleChrome/custom-tabs-client/tree/master/svgomg)
allows you to open an SVG in the [SVGOMG](https://svgomg.firebaseapp.com) PWA.

### Set up Digital Asset Links in an Android app

The basis of Trusted Web activities is the developer-defined trust relationship
between the Android app and the web content it launches established via [Digital
Asset Links](/digital-asset-links/v1/getting-started). This assures the browser
that the app opening a site is controlled by the same developer. In Chrome,
attempting to launch a URL that you can't prove ownership over will fall back to
opening a Custom Tab.

By setting `autoVerify="true"` in any intent filters you add to your app, links
will also open by default on devices higher than API level 23.

First, add a statement to your
[AndroidManifest.xml](https://github.com/GoogleChrome/custom-tabs-client/blob/master/svgomg/src/main/AndroidManifest.xml):

```
<manifest>
  <application>
    ...
    <meta-data android:name="asset_statements"
android:resource="@string/asset_statements" />
    ...
  </application>
</manifest>;
```

And in
[res/values/strings.xml](https://github.com/GoogleChrome/custom-tabs-client/blob/master/svgomg/src/main/res/values/strings.xml)
you'll need to update the statement and the configuration to point to your
website:

```
<resources>
    <string name="app_name">SVGOMG</string>
    <string name="asset_statements">
        [{
            \"relation\": [\"delegate_permission/common.handle_all_urls\"],
            \"target\": {
                \"namespace\": \"web\",
                \"site\": \"https://svgomg.firebaseapp.com\"}
        }]
    </string>
</resources>
```

Note: the backslashes are intentional!

### Deploy your assetlinks.json to prove ownership of the domain

To launch [the
site](https://svgomg.firebaseapp.com/.well-known/assetlinks.json), you'll need
to add a "statement" to the `.well-known/assetlinks.json` file with the package
name and hash of your app's certificate. This allows Digital Asset Links to
establish a bidirectional relationship between your site content and the app
opening it in a Trusted Web activity (only you can generate the cert fingerprint
and only you can host this file).

Note: you can get the hash of your app's certificate with the following command:
`keytool -exportcert -list -v -alias androiddebugkey -keystore
~/.android/debug.keystore`

Creating a statement is documented
[here](/digital-asset-links/v1/create-statement). An example statement for the
sample app is:

```
[{
  "relation": ["delegate_permission/common.handle_all_urls"],
  "target": {
    "namespace": "android_app",
    "package_name": "org.chromium.twa.svgomg",
    "sha256_cert_fingerprints":
["82:04:C5:DB:19:A8:B9:8A:27:14:F0:3E:F5:23:2C:6B:B6:B9:63:10:F2:F9:CD:44:72:AA:C6:7E:09:E1:1C:47","91:45:8F:34:E3:13:E4:58:1C:12:21:7A:FD:1E:BD:5C:BE:9B:DE:2C:1E:57:DC:0D:2B:0E:91:1D:A6:36:CA:E8"]}
}]
```

You can verify the assertion on your site with [the
validator](/digital-asset-links/tools/generator).

Troubleshooting:

* "Invalid input field(s)"
    * Specify the domain only (no https:// or path after the domain name)
    * Test only one signature at a time (the SHA256 hash should contain 32
      octets, or pairs of hexadecimals, in uppercase and separated by colons.)
* "No app deep linking permission found": your site's
  `.well-known/assetlinks.json` file is inaccessible (try navigating to it to make
  sure you see the statements you wrote.)

### Create an Activity that launches the Trusted Web activity

You can use
[TwaSessionHelper](https://github.com/GoogleChrome/custom-tabs-client/blob/master/svgomg/src/main/java/org/chromium/twa/svgomg/TwaSessionHelper.java)
to instantiate and launch a Trusted Web activity from a new activity of your
own, following
[TwaLauncherActivity](https://github.com/GoogleChrome/custom-tabs-client/blob/master/svgomg/src/main/java/org/chromium/twa/svgomg/TwaLauncherActivity.java)
in the sample.

Inside the `TwaLauncherActivity`, we use the `onCreate` event to ask the
`TwaSessionHelper` to establish a connection to the `CustomTabsService` behind the
scenes by calling the `bindService` method.

We also set the `TwaLauncherActivity` as a listener for the session events, so we
can control what to do once a connection to the browser is established.

The first parameter for `bindService` is the `Context` to which the service will be
bound to. The second parameter is an `URI` to the origin that we want to validate
for the Trusted Web activity.

```
Uri originUri = Uri.parse(TWA_ORIGIN);
TwaSessionHelper twaSessionHelper = TwaSessionHelper.getInstance();
twaSessionHelper.setTwaSessionCallback(this);
twaSessionHelper.bindService(this, originUri);
```

When the relationship has been validated and the browser has been warmed up,
`onTwaSessionReady` is invoked, to allow the `TwaLauncherActivity` to know that the
Trusted Web activity is ready to be opened.

```
TwaSessionCallback twaSessionCallback = mTwaSessionCallback.get();
if (twaSessionCallback != null) twaSessionCallback.onTwaSessionReady();
```

The `onTwaSessionReady` callback tells us that the we are ready to open the page.
In the context of this sample, we want to open it as soon as the session is
ready, but other applications may want to open the Trusted Web activity as a
result of a user action, and this event can be used to enable that action (eg:
enable a button.)

Opening the Trusted Web activity is implemented in the `openTwa` method. The API
allows us to pass our own `CustomTabsIntent` so we can change start and exit
animations. Customising animations is mostly relevant for applications opening
Trusted Web activities from an existing activity.

```
// Set an empty transition from TwaLauncherActivity to the splash screen.
CustomTabsIntent customTabsIntent = twaSessionHelper.createIntentBuilder()
        .setStartAnimations(this, 0, 0)
        .build();
Uri openUri = Uri.parse(TARGET_URL);
twaSessionHelper.openTwa(this, customTabsIntent, openUri);
```

At this point, you should be able to load your app and open your test site!

We hope that you can experiment with this API and give us feedback at
[@ChromiumDev](https://twitter.com/ChromiumDev)

{% include "comment-widget.html" %}

repository: shanselman/WebFundamentals

repo_name: shanselman/WebFundamentals


text:
---
title: PagerDuty
category: Connectors
connector_type: Alerting & Monitoring
status: incomplete
logo: https://raw.githubusercontent.com/factor-io/connector-pagerduty/master/logo.png
---
# Authentication
As an administrative user of [PagerDuty](http://www.pagerduty.com/), you can access your service key by replacing your information in the link below.

`https://<your_subdomain>.pagerduty.com/services`

Your access key can be found in the same way.

`https://<your_subdomain>.pagerduty.com/api_keys`

# pagerduty::create

## Input
ID | Default | Description
--- | ------- | -----------
service_key | |
incident_key | |
client | |
client_url | |
description | |

# pagerduty::get

## Input
ID | Default | Description
--- | ------- | -----------
service_key | |
incident_key | |

# pagerduty::acknowledge

## Input
ID | Default | Description
--- | ------- | -----------
service_key | |
incident_key | |

# pagerduty::resolve

## Input
ID | Default | Description
--- | ------- | -----------
service_key | |
incident_key | |

# pagerduty::list

license: MIT

repository: factor-io/docs

branch_name: refs/heads/master

extension: md

gha_language: JavaScript

license_type: permissive

repo_name: factor-io/docs


text:
## Double ssh tunnel

A developer in my team who worked from his place once needed to connect to one
of our servers to see logs. But the only way for him to reach it was to do a ssh
connection from the develoment server to the production server, and then from
there, a second connection to the log server.

But as a developer, he didn't have access to the production servers.
So I shared a Tmux session with him, from there I did my double connection
to the log server through the production server, and then I let him do what he
needed.

I could have done a first ssh connection to the first server, and then a second
one to the second server, but the issue here is if the second connection was
closed, the developer would have been on the production server, which wasn't
good. So I needed a double connection as below, so closing the connection would
close all of them.

### The command

	ssh -t -t -Lport:localhost:port login@server1 'ssh -Lport:localhost:port login@server2'

repository: padawin/site

gha_license_id: MIT

repo_name: padawin/site


text:
# OpenCensus Stackdriver Stats Exporter

The *OpenCensus Stackdriver Stats Exporter* is a stats exporter that exports data to
Stackdriver Monitoring. [Stackdriver Monitoring][stackdriver-monitoring] provides visibility into
the performance, uptime, and overall health of cloud-powered applications. Stackdriver ingests that
data and generates insights via dashboards, charts, and alerts.

## Quickstart

### Prerequisites

To use this exporter, you must have an application that you'd like to monitor. The app can be on
Google Cloud Platform, on-premise, or another cloud platform.

In order to be able to push your stats to [Stackdriver Monitoring][stackdriver-monitoring], you must:

1. [Create a Cloud project](https://support.google.com/cloud/answer/6251787?hl=en).
2. [Enable billing](https://support.google.com/cloud/answer/6288653#new-billing).
3. [Enable the Stackdriver Monitoring API](https://console.cloud.google.com/apis/dashboard).

These steps enable the API but don't require that your app is hosted on Google Cloud Platform.

### Hello "Stackdriver Stats"

#### Add the dependencies to your project

For Maven add to your `pom.xml`:
```xml
<dependencies>
  <dependency>
    <groupId>io.opencensus</groupId>
    <artifactId>opencensus-api</artifactId>
    <version>0.25.0</version>
  </dependency>
  <dependency>
    <groupId>io.opencensus</groupId>
    <artifactId>opencensus-exporter-stats-stackdriver</artifactId>
    <version>0.25.0</version>
  </dependency>
  <dependency>
    <groupId>io.opencensus</groupId>
    <artifactId>opencensus-impl</artifactId>
    <version>0.25.0</version>
    <scope>runtime</scope>
  </dependency>
</dependencies>
```

For Gradle add to your dependencies:
```groovy
compile 'io.opencensus:opencensus-api:0.25.0'
compile 'io.opencensus:opencensus-exporter-stats-stackdriver:0.25.0'
runtime 'io.opencensus:opencensus-impl:0.25.0'
```

#### Register the exporter

This uses the default configuration for authentication and a given project ID.

```java
public class MyMainClass {
  public static void main(String[] args) {
    StackdriverStatsExporter.createAndRegister(
        StackdriverStatsConfiguration.builder().build());
  }
}
```

#### Set Monitored Resource for exporter

By default, Stackdriver Stats Exporter will try to automatically detect the environment if your
application is running on GCE, GKE or AWS EC2, and generate a corresponding Stackdriver GCE/GKE/EC2
monitored resource. For GKE particularly, you may want to set up some environment variables so that
Exporter can correctly identify your pod, cluster and container. Follow the Kubernetes instruction
[here](https://cloud.google.com/kubernetes-engine/docs/tutorials/custom-metrics-autoscaling#exporting_metrics_from_the_application)
and [here](https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/).

Otherwise, Exporter will use [a global Stackdriver monitored resource with a project_id label](https://cloud.google.com/monitoring/api/resources#tag_global),
and it works fine when you have only one exporter running.

If you want to have multiple processes exporting stats for the same metric concurrently, and your
application is running on some different environment than GCE, GKE or AWS EC2 (for example DataFlow),
please associate a unique monitored resource with each exporter if possible.
Please note that there is also an "opencensus_task" metric label that uniquely identifies the
uploaded stats.

To set a custom MonitoredResource:

```java
public class MyMainClass {
  public static void main(String[] args) {
    // A sample DataFlow monitored resource.
    MonitoredResource myResource = MonitoredResource.newBuilder()
                                               .setType("dataflow_job")
                                               .putLabels("project_id", "my_project")
                                               .putLabels("job_name", "my_job")
                                               .putLabels("region", "us-east1")
                                               .build();

    // Set a custom MonitoredResource. Please make sure each Stackdriver Stats Exporter has a
    // unique MonitoredResource.
    StackdriverStatsExporter.createAndRegister(
        StackdriverStatsConfiguration.builder().setMonitoredResource(myResource).build());
  }
}
```

For a complete list of valid Stackdriver monitored resources, please refer to [Stackdriver
Documentation](https://cloud.google.com/monitoring/custom-metrics/creating-metrics#which-resource).
Please also note that although there are a lot of monitored resources available on [Stackdriver](https://cloud.google.com/monitoring/api/resources),
only [a small subset of them](https://cloud.google.com/monitoring/custom-metrics/creating-metrics#which-resource)
are compatible with the Opencensus Stackdriver Stats Exporter.

#### Authentication

This exporter uses [google-cloud-java](https://github.com/GoogleCloudPlatform/google-cloud-java),
for details about how to configure the authentication see [here](https://github.com/GoogleCloudPlatform/google-cloud-java#authentication).

If you prefer to manually set the credentials use:
```
StackdriverStatsExporter.createAndRegister(
    StackdriverStatsConfiguration.builder()
        .setCredentials(new GoogleCredentials(new AccessToken(accessToken, expirationTime)))
        .setProjectId("MyStackdriverProjectId")
        .setExportInterval(Duration.create(60, 0))
        .build());
```

#### Specifying a Project ID

This exporter uses [google-cloud-java](https://github.com/GoogleCloudPlatform/google-cloud-java),
for details about how to configure the project ID see [here](https://github.com/GoogleCloudPlatform/google-cloud-java#specifying-a-project-id).

If you prefer to manually set the project ID use:
```
StackdriverStatsExporter.createAndRegister(
    StackdriverStatsConfiguration.builder().setProjectId("MyStackdriverProjectId").build());
```

#### Java Versions

Java 7 or above is required for using this exporter.

## FAQ
### Why did I get a PERMISSION_DENIED error from Stackdriver when using this exporter?
To use our Stackdriver Stats exporter, you need to set up billing for your cloud project, since
creating and uploading custom metrics to Stackdriver Monitoring is
[not free](https://cloud.google.com/stackdriver/pricing_v2#monitoring-costs).

To enable billing, follow the instructions [here](https://support.google.com/cloud/answer/6288653#new-billing).

### What is "opencensus_task" metric label ?
Stackdriver requires that each Timeseries to be updated only by one task at a time. A
`Timeseries` is uniquely identified by the `MonitoredResource` and the `Metric`'s labels.
Stackdriver exporter adds a new `Metric` label for each custom `Metric` to ensure the uniqueness
of the `Timeseries`. The format of the label is: `{LANGUAGE}-{PID}@{HOSTNAME}`, if `{PID}` is not
available a random number will be used.

You have the option to override the "opencensus_task" metric label with custom constant labels using
`StackdriverStatsConfiguration.Builder.setConstantLabels()`. If you do so, make sure that the
monitored resource together with these labels is unique to the current process. This is to ensure
that there is only a single writer to each time series in Stackdriver.

You can also set `StackdriverStatsConfiguration.Builder.setConstantLabels()` to an empty map to
avoid getting the default "opencensus_task" label. You should only do this if you know that the
monitored resource uniquely identifies this process.

### Why did I get an error "java.lang.NoSuchMethodError: com.google.common...", like "java.lang.NoSuchMethodError:com.google.common.base.Throwables.throwIfInstanceOf"?
This is probably because there is a version conflict on Guava in the dependency tree.

For example, `com.google.common.base.Throwables.throwIfInstanceOf` is introduced to Guava 20.0.
If your application has a dependency that bundles a Guava with version 19.0 or below
(for example, gRPC 1.10.0), it might cause a `NoSuchMethodError` since
`com.google.common.base.Throwables.throwIfInstanceOf` doesn't exist before Guava 20.0.

In this case, please either add an explicit dependency on a newer version of Guava that has the
new method (20.0 in the previous example), or if possible, upgrade the dependency that depends on
Guava to a newer version that depends on the newer Guava (for example, upgrade to gRPC 1.12.0).

[stackdriver-monitoring]: https://cloud.google.com/monitoring/

repository: augustjanse/opencensus-java

branch_name: refs/heads/report-and-coverage

gha_language: Java

repo_name: augustjanse/opencensus-java


text:
---
title: OOP
layout: page
exclude: true
---
### Just the Data
The fundamental idea behind Object Oriented Programming is the unification of methods and data. When dealing with data in an OO manner it should never be uncoupled from the object which gives it meaning.

 It has no context. Is it color? A name? A identifying code? Without coupling this value to an object, such as `car.color` the data is meaningless.

### Data Abstraction
When creating a class to represent a real world object we can use **data abstraction** to the model that real object more effectively. This means creating classes so that their data is structured in such a way that it *matches* the real world object's structure.

For example if we have a `Bird` object we can create a generalised blueprint that matches the structure of how information about a bird might be represented.
```ruby
class Bird
  GRAVITY = 9.8
  def initialize(wing_span, weight)
    @wing_span = wing_span
    @weight = weight
    @position = { x: 0, y: 0 }
  end

  public
  def fly
    # use flying speed to move the bird and make it fly
  end

  private
  def flying_speed
    # code using gravity, weight and wing span
  end
end
```
Here the `Bird` class represents a bird with a `position`, `wing_span` and `weight`, everything need to calculate the bird's `flying_speed`. We then include a `fly` to change the bird's position.

### Encapsulation
**Encapsulation** means structuring objects so that only the properties that are required to interact with the object are *exposed* to the rest of the program giving your code a standard interface with which to interact with a class. With encapsulation we hide all of the implementation details from the rest of code keeping it as a contained object.

In the above example `GRAVITY` is a constant that can be accessed for the `Bird` class using `Bird::GRAVITY` but not changed, this is useful if we were perhaps modelling an entire woodland and wanted to get a consistent gravity across the entire model.

The `@position`,`@wing_span` and `@weight` instance variables cannot be accessed from outside the `Bird` class because the rest of program does not need to change these directly. Furthermore the `flying_speed` method is kept private so that only a particular instance of the `Bird` class can calculate its flying speed because the rest of our code doesn't need to interact with this method.

The `fly` method however *is* exposed to the rest of our code so that we have an interface for interacting with our `Bird` instances to make them fly!

Because our code has clearly defined channels for interacting with our `Bird` class it means we can easily change the implementation of the class without effecting the rest of our code. For example if we wanted to completely rewrite the `fly` method to changed how we calculating flying we can do that without in any way changing how the rest of our code outside of the `Bird` class works.

### Single Responsibility Principle
**SRP** means structuring our program so that each individual part of its functionality is encapsulated as a distinct entity (or class) capable of handling that responsibility without outside assistance. Each class should have one logical thing that is responsible for.

This also means that if changes are required to your code they should only effect *one* component class in your system. If you find that writing a change into your system is propagating out to multiple classes in then you have probably violated SRP.

The code below describes a class `Body` which has several different methods for things like thinking, moving and looking around. Currently the `Body` class violates SRP because it is responsible for multiple components and behaviours in our system. Furthermore, if we want to make a change to "thinking" or "moving" then both of those changes require use to change the body class, rather than a single component in our system further violating SRP.
```ruby
class Body
  def think
    # has thoughts
  end

  def move
    # moves around
  end

  def look
    # looks around
  end
end
```
Here is another version of the body's functionality refactored to adhere to SRP. In this version the body class has been changed to function simply as a container for the new classes which function as logical units to contain the functionality that was originally in the `Body` class. Now, if we need to make changes to "thinking", "moving" or "seeing" we only need to change one part of our code that is logical separated from the other elements of our program.
```ruby
class Body
   def initialize
     @muscles = Muscles.new
     @brain = Brain.new
     @eyes = Eyes.new
   end
end

class Muscles
  def move
    # move around
  end
end

class Brain
  def think
    # thinks thoughts
  end
end

class Eyes
  def look
    # looks around
  end
end
```
We could go further with this principle. For example, what if we want to distinguish between different parts of movement such as moving the legs to walk, or moving the arms to wave? We don't want to put the code for the walking and waving into the `Muscles` class directly because if we wanted to change our walking or waving code it would mean having more than one reason to change the `Muscles` class, thus violating SRP. Instead we should spin out this functionality into `Legs` and `Arms` classes that are simply managed by inherit from the `Muscles` class. That way if we need to change the way muscles work in general we can refactor the `Muscles` class - a single responsibility - but if we need to change the way our `Body` "walks" or "waves" we can change the `Legs` and `Arms` classes respsectively.
```ruby
class Body
   def initialize
     @muscles = Muscles.new
     @brain = Brain.new
     @eyes = Eyes.new
   end
end

class Muscles
end

class Legs < Muscles
  def walk
    # walks around
  end
end

class Arms < Muscles
  def wave
    # waves at friends
  end
end

class Brain
  def think
    # thinks thoughts
  end
end

class Eyes
  def look
    # looks around
  end
end
```
You can also conceptualise SRP further as being **method specific** if you have a method *within* a class that has more than one responsibility then this also violates SRP and should be refactored into multiple methods.

### Cohesion
**Cohesion** is similar to both encapsulation and SRP, it simply refers to grouping code in a way that is self contained and executes singular tasks well as opposed to spreading out the functionality of your code base.

### Forwarding and Delegation
**Forwarding** and **delegation** are very similar. They both involve passing messages that are passed to a class down to other objects and using the methods on those objects instead. The main difference is that when you **forward** the class receiving the message is has its own entirely separate context and interface from the class sending the method. Whereas when you **delegate** the receiving class is *wrapped* inside the class calling it, so that the context of code remains consistent with the calling object.

One analogy used is that of receiving an email asking you to donate to a charity. If you **forward** the email you might send it to a friend who would be able to donate that amount. It's not a personally responsibility. However, if you **delegate** the task of donating to your accountant then its still ultimately your responsibility to pay the money to the charity.

But, **what does this actually look like?**

The essential difference is how classes interact. The example below shows how **delegation** works. In this example the `Phone` class delegates the act of displaying things on the screen to the `Screen` class by storing an instance of it in the `@screen` instance variable. It has an essentially private relationship with the screen which it **delegates** responsibilities to. This is delegation because it is never exposed the context of `@screen` is never exposed publicly, it is all mediated through the `display` method in the phone object.
```ruby
class Phone
  def initialize
    @screen = Screen.new
  end

  def display
    @screen.display
  end
end

class Screen
  def display
    # display stuff
  end
end
```
On the other hand **forwarding** is when the interface and context of the object that is handling things is exposed.
```ruby
class Client
  def initialize(server)
    @server = server
  end
end

class Server
  def data
    # return server data
  end
end
```
In the code above the `Client` class takes in a `Server` object when created. This means that `Server` object exists in its own right even before the `Client` is first initialized. Then if our `Client` wants to get `data` it will **forward** that request to the server object. An example in the `irb` might be:
```
server = Server.new
client = Client.new(server)
client.server.data
```
Here we are calling the namespace of the `server` object directly and **forwarding** the request for data onto that object. It's this distinction that is the primary difference between these two methods of object communication. In essence however they are both about extracting functionality and organising code.

### Polymorphism
**Polymorphism** is the method of presenting the same interface on different objects, so that, even though the objects have different functionality the way code interacts with them is kept consistent meaning that we can use only a few lines of code to produce wildly different results simply by calling on different objects with the same interface.
```ruby
class Taster
  def taste(food)
    puts food.flavor
  end
end

class Cabbage
  def flavor
    "Tastes like old socks"
  end
end

class Rice
  def flavor
    "Has the flavor of cardboard"
  end
end

class Almond
  def flavor
    "Like a nut party in my mouth"
  end
end

taster = Taster.new
taster.taste(Cabbage.new) # => "Tastes like old socks"
taster.taste(Rice.new) # => "Has the flavor of cardboard"
taster.taste(Almond.new) # => "Like a nut party in my mouth"
```
In the above example we can see the `Taster` class calls the the functionality on the different types of food in exactly the same way with the line `food.flavor` to produce wildly different outputs. This is because each of the food classes have a **polymorphic** relationship in which they all implement the same method `flavor` but with different outputs. Thus we only need one line of code in the `Taster` class to interact with all of these classes.

### Inheritance
**Inheritance** is the method of defining multiple objects based on common sets of functionality that would be implemented on those objects. In the last example we created a set of polymorphic classes however its clear that there is a category relationship between all of these objects. They are all food. Which means they can *inherit* from a `Food` class.

```ruby
class Food
  def initialize(type, color)
    @type = type
    @color = color
    @edible = true
  end

  def flavor
    "It tastes like something"
  end
end

class Cabbage < Food
  def flavor
    "Tastes like old socks"
  end
end

class Rice < Food
  def flavor
    "Has the flavor of cardboard"
  end
end

class Almond < Food
  def flavor
    "Like a nut party in my mouth"
  end

  def crunch
    puts "Crunchy nuts"
  end
end
```
 We have now created a shared `initialize` method for each of foods that records their type and color as well as a boolean that describes them as edible. Furthermore each food sub class (`Cabbage`, `Rice`, `Almond`) overloads the `flavor` method defined in the `Food` class. This allows us to organise our code and centralise changes to the parent class of these items. For example, if we wanted to change how the `initialize` method on each of these classes *without* them inheriting from `Food` we would need to change three different constructors - not very dry or efficient. By letting our classes inherit the constructor we only have to change one piece of code to update all the subclasses.

### Composition over Inheritance
**Composition** is process of **designing the different parts of your code based on what they do or what they have** *rather than* by what they are. In a traditional inheritance in object oriented programming, we manage classes based on classifying them as objects that *are* something.

| Inheritance | Composition |
| --- | ---
| What something is - a computer is a type of machine | What something does - A computer displays stuff
| | What it has - a computer has a screen component that displasys stuff

Considering the  inheritance and class chart below, imagine that we were asked to make a "robot muder dog" that can `drive`, `murder` and `bark` but not `poop` because it is a robot. We would be in a very bad situation because there is no way we can redefine this inheritance structure to include this functionality without bundling a lot of functionality that we don't want - by creating a common inheritor for everything -  or confusing our types. This is sometimes called the **gorilla and banana problem** because when ask for a banana - i.e. a small piece of added functionality - we instead get a gorilla holding a banana - i.e. implementing that small piece of functionality means we need to include a lot of unnecessary functionality in that class.
```ruby
Animal
| .poop()
|
| Dog
| | .bark()
|
| Cat
| | .meow()

Robot
| .drive()
|
| Cleaner
| | .clean()
|
| Murderer
| | .murder()
```
We can solve the above problem using **composition** by extracting the different pieces of functionality into their own classes. Essentially separating these pieces of functionality in an almost modular fashion.
```ruby
class Drive
  def drive
    "drives recklessly"
  end
end

class Clean
  def clean
    "cleans carefully"
  end
end

class Murder
  def kill
    "kills indiscriminately"
  end
end

class Poop
  def poop
    "poops violently"
  end
end

class Bark
  def bark
    "barks loudly"
  end
end

class Meow
  def meow
    "meows gently"
  end
end
```
Now our original classes and desired features can be created by simply slotting together the different pieces of functionality we have created in a "has a" relationship where the larger class structures contain these smaller functional classes and then use them to do things.
```ruby
class Cat
  def initialize
    @meower = Meow.new
    @pooper = Poop.new
  end

  def meow
    @meower.meow
  end

  def poop
    @pooper.poop
  end
end

class RobotMurderDog
  def initialize
    @murderer = Murder.new
    @barker = Bark.new
    @driver = Drive.new
  end

  def murder
    @murderer.murder
  end

  def bark
    @barker.bark
  end

  def drive
    @driver.drive
  end
end
```
Now we can easily create our `RobotMurderDog` without introducing any unnecessary code into the class. We have kept our code try by extracting actions like barking and pooping into their own classes and can **compose** them in any way that we want.

### Tell, Don't Ask
"Tell, Don't Ask" means telling an object what you want and letting it handle how to accomplish that *as opposed to* querying the state of an object and then calling methods based on the results of that test.
```ruby
# Not so good
if user.admin?
  puts user.admin_message
else
  puts user.user_message
end
```
In the above example, this code queries whether the object is an `admin?` and then calls different `user` or `admin` specific message methods based on the result of that. This is a **clear violation of TDA**. As a caller we simply want to tell the `user` object to return the appropriate message. **It is the responsibility of the called object** to manage what is the correct output for that call. So instead we can refactor the `User` class to run a conditional inside a method called `message` that does this logic itself. Then when we call the `.message` method from outside the class it is clear and declarative.
```ruby
# better
puts user.message
```
The Pragmatic Programmer describes this way of coding as "Think[ing] declaratively not procedurally." and that it arises naturally if you design classes based on their responsibilities not their function.
> Written with [StackEdit](https://stackedit.io/).
<!--stackedit_data:
eyJoaXN0b3J5IjpbLTEzODQyODYxNDBdfQ==
-->

gha_language: HTML


text:
# Speedtest Implementation for .NET
This is a very simple implementation for testing users newtork speeds. It uses [speedtest.net](http://www.speedtest.net/)'s servers and logic.
There is no official API for [speedtest.net](http://www.speedtest.net/) but i've extracted some information from developer console.

[Speedtest.net](http://www.speedtest.net/) has a list of ISP's test servers. You can access via this url. When you send a POST request to this url, it returns a serverlist as json array that nearest to you.
I think it locates you by your IP address.
```
http://www.speedtest.net/api/js/servers?engine=js
```

You can select a server from the list for testing. I've selected first item, you can see in code. [Speedtest.net](http://www.speedtest.net/) may select server by preffered parameter or randomizely.
There is an example json object that contains server properties.
```
{
  "url": "http://hiztesti.isimkayit.com/speedtest/upload.php",
  "lat": "40.8520",
  "lon": "29.8780",
  "distance": 16,
  "name": "Kocaeli",
  "country": "Turkey",
  "cc": "TR",
  "sponsor": "IsimKayit.com",
  "id": "6297",
  "preferred": 0,
  "host": "hiztesti.isimkayit.com:8080"
}
```

## Calculating Download Speed
You must combine host parameter and url parameters in below for calculating download speed. First parameter should be a GUID string. Second parameters should be chunksize in bytes for your download.
The server will send a octet-stream that sized by your preferred size. [Speedtest.net](http://www.speedtest.net/) prefers 25000000 (approximately 23,4MB).

Note : GUID should be different for each request.
```
download?nocache={0}&size={1}
````

Then you should have an url lik below for example. This means, when you send a GET request to this url, server will send you 25 million bytes.
```
http://hiztesti.isimkayit.com:8080/download?nocache=ef43485f-1bbc-4507-88a7-eb4ef8e536cb&size=25000000
```

You can use stopwatch for counting download time. For example; if download finished in 15 seconds and your download size is 25000000. You can use this formula to calculate your speed in MB/s.
```
speed = (25000000 / 15) / (1024 * 1024) // get speed in MB/s
```

I prefer Mbits to show download and upload speed. For this you should multiply your result with 8. Because 1 Byte = 8 bits.

## Calculating Upload Speed
This is almost same with upper logic. You must combine host parameter and url parameters in below for calculating upload speed. There is one parameter. It should be GUID string.

Note : GUID should be different for each request.
```
upload?nocache={0}
```

Then you should have an url like below for example.
```
http://hiztesti.isimkayit.com:8080/upload?nocache=ef43485f-1bbc-4507-88a7-eb4ef8e536cb
```

You can send POST request to this url but before, you must add some parameters to your request.
```
Content-Length = 4000000 // Length is in bytes. You can increase or decrease it. I prefer 4MB, so 4000000. It is enough.
Content-Type = application/octet-stream
```

You can use stopwatch for counting upload time. For example; if upload finished in 100 seconds and your upload size is 4000000. You can use this formula to calculate your speed in MB/s.
```
speed = (4000000 / 100) / (1024 * 1024) // get speed in MB/s
```

I prefer Mbits to show download and upload speed. For this you should multiply your result with 8. Because 1 Byte = 8 bits.

# License
MIT © [Hasan Cemre Ok](https://github.com/hasancemreok)


text:
# How to data bind a Polygon’s Points to a data source – Part II

In my last blog post, I talked about one solution to data bind a Polygon's Points to a collection such that:
- Changes in the source are propagated to the UI.
- There is a clean separation between the UI and data layers.

This solution is good for scenarios where big changes to the collection happen each time we want to refresh the UI, but not so good when we need to frequently add or remove one point only. The reason for this is that every time we raise a collection change notification, a new PointCollection instance is created.

Today I will explain to you my thought process of coming up with a solution with the advantages of the previous one but without the drawback.

I will start by showing you the data source I use in this blog post:

	public class PolygonItem
	{
		private double angleIncrement = Math.PI / Math.Sqrt(2);
		private int initialCount = 249;

		private ObservableCollection<Point> points = new ObservableCollection<Point>();

		public ReadOnlyObservableCollection<Point> Points
		{
			get { return new ReadOnlyObservableCollection<Point>(this.points); }
		}

		public void AddPoint()
		{
			double angle = this.points.Count * this.angleIncrement;
			double x = 250 + 250 * Math.Cos(angle);
			double y = 250 + 250 * Math.Sin(angle);
			this.points.Add(new Point(x, y));
		}

		public PolygonItem()
		{
			while (this.points.Count < this.initialCount)
			{
				this.AddPoint();
			}
		}
	}

As you can see, every time the AddPoint method is called, a single point is added to the source collection (unlike the sample in the previous post, where every time you click on a button, the whole source collection is redone.) The fact that a very small change happens to the collection each time provides the motivation we need to find a solution different from the one in my last post.

In this post, I will explain how we can write a custom MarkupExtension that changes the target PointCollection when the source collection changes. My idea was that if Binding (which is a MarkupExtension too) doesn't provide this functionality, I could write my own simple specialized Binding that does what I want.

To create the MarkupExtension, I started by thinking about which properties are needed to allow the user to specify the source collection. I got some inspiration from the Binding object and decided to pick two properties: "Source" and "PropertyName". "Source" holds a source object, of any type, and "PropertyName" holds the name of a property of that object, of type IEnumerable<Point>. This is basically a very trimmed down version of Binding.

	[MarkupExtensionReturnType(typeof(PointCollection))]
	public class PointCollectionConnectorExtension : MarkupExtension
	{
		private object source;
		private string propertyName;
		private PointCollection pointCollection;

		public object Source
		{
			get { return this.source; }
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				this.source = value;
			}
		}

		public string PropertyName
		{
			get { return this.propertyName; }
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				this.propertyName = value;
			}
		}

		(...)
	}

Next I had to override the ProvideValue abstract method from MarkupExtension. This method is where you can find all the logic necessary to calculate the value provided by a MarkupExtension. In this particular scenario, I want to start listening to source collection change notifications and to modify the provided PointCollection everytime the source changes. Here is what my ProvideValue method looks like:

	public override object ProvideValue(IServiceProvider serviceProvider)
	{
		if (this.source == null || this.propertyName == null)
		{
			throw new InvalidOperationException("Cannot use PointCollectionConnector extension without setting Source and PropertyName.");
		}

		// Get the value of the property with name PropertyName from the source object.
		Type sourceType = this.source.GetType();
		PropertyInfo propertyInfo = sourceType.GetProperty(propertyName);
		if (propertyInfo == null)
		{
			throw new InvalidOperationException(String.Format("Source object of type {0} does not have a property named {1}.", sourceType.Name, propertyName));
		}
		object propertyValue = propertyInfo.GetValue(this.source, null);

		// See if the value is an enumerable collection of points.
		IEnumerable<Point> enumerable = propertyValue as IEnumerable<Point>;
		if (enumerable == null)
		{
			throw new InvalidOperationException(String.Format("Source object of type {0} has a property named {1}, but its value (of type {2}) doesn't implement IEnumerable<Point>.", sourceType.Name, propertyName, propertyValue.GetType().Name));
		}

		// Construct the initial point collection by copying points from the enumerable collection.
		this.pointCollection = new PointCollection(enumerable);

		// Listen for collection changed events coming from the source, if possible.
		INotifyCollectionChanged notifyCollectionChanged = propertyValue as INotifyCollectionChanged;
		if (notifyCollectionChanged != null)
		{
			notifyCollectionChanged.CollectionChanged += this.Source_CollectionChanged;
		}

		return this.pointCollection;
	}

As you can see, I use the Source and PropertyName properties to grab the source collection through reflection. The value provided by the MarkupExtension to the target DP is a new PointCollection created here, which contains the same points as the source collection. The most important part of this code, however, is where I hook up a listener for collection change notifications in the source collection. In that event handler, I have some code that replicates in the PointCollection any changes made to the source collection:

	private void Source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
	{
		switch (e.Action)
		{
			case NotifyCollectionChangedAction.Add:
				for (int i = 0; i < e.NewItems.Count; i++)
				{
					this.pointCollection.Insert(e.NewStartingIndex + i, (Point)e.NewItems[i]);
				}
				break;

			case NotifyCollectionChangedAction.Move:
				for (int i = 0; i < e.NewItems.Count; i++)
				{
					this.pointCollection.RemoveAt(e.OldStartingIndex);
					this.pointCollection.Insert(e.NewStartingIndex + i, (Point)e.NewItems[i]);
				}
				break;

			case NotifyCollectionChangedAction.Remove:
				for (int i = 0; i < e.OldItems.Count; i++)
				{
					this.pointCollection.RemoveAt(e.OldStartingIndex);
				}
				break;

			case NotifyCollectionChangedAction.Replace:
				for (int i = 0; i < e.NewItems.Count; i++)
				{
					this.pointCollection[e.NewStartingIndex + i] = (Point)e.NewItems[i];
				}
				break;

			case NotifyCollectionChangedAction.Reset:
				this.pointCollection.Clear();
				break;
		}
	}

Here is the XAML that uses this MarkupExtension:

	<Window.Resources>
		<local:PolygonItem x:Key="src"/>
	</Window.Resources>

	<Polygon Name="polygonElement" Width="500" Height="500" Margin="10" Fill="#CD5C5C">
		<Polygon.Points>
			<local:PointCollectionConnector Source="{StaticResource src}" PropertyName="Points"/>
		</Polygon.Points>
	</Polygon>

I am using property-element syntax to add the MarkupExtension in this case. Unfortunately there is a bug that prevents me from using attribute syntax with a custom MarkupExtension:

	<Polygon Points="{PointCollectionConnector Source={StaticResource src}, PropertyName=Points}" />

Next I supplied a Button with an event handler that adds a point to the source collection each time the Button is pressed.

	<Button Click="ChangeSource" Margin="10" HorizontalAlignment="Center">Change data source</Button>

	private void ChangeSource(object sender, RoutedEventArgs e)
	{
		PolygonItem polygonItem = this.Resources["src"] as PolygonItem;
		polygonItem.AddPoint();

		// Unfortunately, the Polygon element won't update unless we call InvalidateMeasure and InvalidateVisual.
		this.polygonElement.InvalidateMeasure();
		this.polygonElement.InvalidateVisual();
	}

Unfortunately there is a bug here too: the UI will not reflect changes in the PointCollection. To work around it, we need to call InvalidateMeasure followed by InvalidateVisual, as shown above.

If you now click on the Button, you will see that a new Point is added to the collection, and the pattern in the UI changes. This solution sounds pretty good, but it has a drawback: you can not use this MarkupExtension in a Style because the PointCollection, which is a Freezable, freezes (meaning, it can not be changed). Freezables become frozen when used in Styles because it's the only way they can be used across threads. It's very common for Styles (particularly those in the theme files) to be used in multiple threads.

I like this solution, but of course I couldn't stop thinking about this until I was able to find a solution with all the advantages of this one, and without the drawback. I will talk about a third solution in my next blog post, so stay tuned.

Here is a screenshot of this application:

![](Images/33PolygonBinding2.png)

repository: mindball/old-wpf-blog

repo_name: mindball/old-wpf-blog


text:
The Star Wars API

Query the Star Wars API for people, planets, vehicles, films and much more!

[![license](https://img.shields.io/github/license/mashm3ll0w/starWars-Swapi.svg)](tps://github.com/mashm3ll0w/starWars-Swapi/blob/master/LICENSE.md) ![learning.code](https://img.shields.io/badge/code-robot-success.svg)  ![mash.mellow](https://img.shields.io/badge/%3C%2F%3E%20with%20%E2%99%A5%20by-mash.mellow-%23e30000.svg)

The project is live at https://mashm3ll0w.github.io/starWars-Swapi/

## Description
The following technologies were used;
>**HTML**
>
>**CSS - ( SCSS )**
>
>**Javascript**
>
>The Star Wars API which you can find at **https://swapi.dev/**

### Documentation
For more information using the Star Wars API, have a look at this [Docs](https://swapi.dev/documentation) page.

## AUTHOR
Karl Mash

## LICENSE
This software is licensed under the [MIT](https://github.com/mashm3ll0w/starWars-Swapi/blob/master/LICENSE.md) License ©

branch_name: refs/heads/develop

gha_language: CSS


text:
+++
title = "Self service"
weight = 400
+++
---

## What are we going to do?

We have now removed the default networking resources, created a VPC and two subnets.

As we build out a multi account environment we may want to allow our end user to decide how many subnets they need,
what sizes they are or which VPC they should be attached to.  AWS Service Catalog is a great way to achieve this.  You
can create a product, add it to a portfolio and then allow your users to provision the product with limited options.

The following steps will show you how to make a product and share it with an account:

{{% children depth="1" showhidden="false" %}}


text:
---
layout: post
title:  "TIC-80 Cheatsheet"
description: "A compressed reference for current version of TIC-80 fantasy console"
category: gamedev
tags: [gamedev,tic80]
published: true
---

{% include JB/setup %}

[tic80refpng]: {{site.baseurl}}assets/documents/tic-80_cheatsheet.png
[tic80refpdf]: {{site.baseurl}}assets/documents/tic-80_cheatsheet.pdf

This a self-contained cheatsheet I created for TIC-80:

[Here's the PDF]({{site.baseurl}}assets/documents/tic-80_cheatsheet.pdf)

And a hi-quality PNG:

![tic80refpng]


text:
---
id: lecture2
title: Lecture 2
---

Homework: Assignment 1: JS, TS, and Basic React, is due 3/11 by 11:59pm

Slides: [Here](https://docs.google.com/presentation/d/1jv8itKRUyCkyRJCdipxk8znlYjsHsk5c78OdkP7UQaQ/edit?usp=sharing)

Explore more:

- [tRPC](https://trpc.io/): End-to-end type safety for a full-stack TypeScript app
- [Turborepo](https://turborepo.com/): A monorepo tool for TypeScript, to keep all libraries, backend, and frontend code in one place

# Today's Lecture 2/27

By the end of today, you should be able to:

- Understand the evolution of web development
- Understand how websites work under the hood
- Understand the difference between Node.js and Browser JS
- Understand the ecosystem of modern web development tools (Yarn, JS Frameworks, Linting, etc.), how each tool fits into the development process, why each is present, and how to use them.

## How to build a web app

_Intro to Node.js and Yarn_

### How do websites work?

There are two main models of websites: static and dynamic. The difference between the two is how the content is generated.

#### Static websites

When we originally conceived of the "website", it was a static little bundle of HTML, CSS, and JavaScript. In essence, when you access a URL, your browser asks the server at the other end for that bundle via an HTTP request. The server then sends back the bundle, and your browser renders it.

This is the traditional _static website_, and it adheres cleanly to the server-client model. However, as webpages got more complex, we needed a way to make them more dynamic. We needed a way to store data, and to send it back to the client when they requested it. This is where the _dynamic website_ comes in.

#### Dynamic websites

Dynamic websites are websites that are generated on the fly. They are not static bundles of HTML, CSS, and JavaScript. Instead, they are generated by a server-side language, such as PHP, Python, or Ruby. When a user requests a page, the server runs the code to generate the page, and then sends it back to the client.

#### In reality...

In reality, most websites are a mix of static and dynamic content. The static content is the HTML, CSS, and JavaScript that is sent to the client. The dynamic content is the data that is sent to the client when they request it.

This led to the rise of all kinds of rendering models and JavaScript frameworks, which we'll cover shortly. First, however, you need to know Node and Yarn.

## Node.js

> Node.js is an open source, cross platform JavaScript V8 runtime environment using a single-threaded event loop.

Let's break it down...

#### Open Source

All of the code is available to you to view on [Github](https://github.com/nodejs/node)! Anyone can contribute-- this democratizes the development process!

#### Cross Platform JavaScript Runtime Environment

- Historically you were only able to run JavaScript on the browser or client
- Node.js takes the V8 JavaScript engine powering Google Chrome outside of the browser allowing you to run Node.js **anywhere**
  - V8 JavaScript engine is a fast JavaScript engine created by Google. Learn more about it [here](https://v8.dev/)!
- Can run Node.js on your terminal as well
- Now, we can use JavaScript as a **universal language**!

#### Single-threaded

- Threads are a separate line of execution and can be ran in parallel - i.e. several at
  the same time.
- However, Node.js uses a single-threaded event loop
  - Run in a single process
  - Requests do not spawn new threads
- Non-blocking

#### How does Node.js handle multiple requests?

- Node.js is **asynchronous**
- When a request is sent, it is dispatched to the server
- Instead of blocking the thread and wasting CPU cycles waiting for the request to finish, Node.js continues its operations
- Once the request is complete, a callback is triggered and information is sent back

#### Event Loop

- Client can send requests into the event loop
- We can register callbacks to server when doing things that might take time (ie. search, query, intensive computation)
- After operation completes, callback will fire and return to requests

:::info
A callback is a function that you can pass to another function to be executed
later. This is a common pattern in web development, since lots of data goes
from the client to the server, and we want to implement certain behavior that fires
after the data is received.
:::

#### Why Node.js?

- Unites front-end and back-end in one language/framework
  - TypeScript/JavaScript
  - Frontend and backend in the same language
- Extremely performant
- Asynchronous and non-blocking
- NPM (Node Package Manager)
  - a directory of many libraries and packages
  - access to huge libraries to use in projects and build upon
  - similar to `pip` in Python, Gradle/Maven in Java, etc (it's okay if you've never heard of these!)

### Conceptual Overview: Node.js vs Browser JS

Node.js runs on the server (aka not in your browser), while browser JS runs on the client (in your browser). They are both JavaScript, but since JavaScript is a standard, not a single unified language, there are differences between the two (some native functions that exist in a browser, such as accessing a window's URL, obviously have no meaning in Node.js).

Keep this in mind! If you install a package meant for Node.js and try to use it in the browser, it might behave unexpectedly. If you install a package meant for the browser and try to use it in Node.js, it might not behave unexpectedly. These are two entirely separate runtime environments!

#### Node Package Manager (NPM)

NPM is a dependency manager, like pip for python or maven for java. Think of node packages as recipes made by other people you want to use in your site.
Also part of the open sourced community!

#### package.json

The `package.json` is kind of like a directory for your Node project. It contains
various metadata and information about it, as well as details on what it depends
on, so others can reproduce the behavior of your project.

- Tracks which node packages you use
- **Dependencies**: packages needed at run-time

```
npm install --save <pkg_name>
yarn add <pkg_name>
```

- **devDependencies**: packages used during development (before pushing to production).
  When a "production" or real version gets built prior to deployment, these dependencies
  will not be included. Only install certain tools that ease development in this manner.

```
npm install --save-dev <pkg_name>
yarn add --dev <pkg_name>
```

#### We will use Yarn!

- Faster at installing dependencies in practice
- More optimized

#### NPM vs Yarn commands

- NPM

```
npm init
npm install <pkg_name>
npm uninstall <pkg_name>
npm update <pkg_name>
npm audit
```

- Yarn

```
yarn init
yarn add <pkg_name>
yarn remove <pkg_name>
yarn upgrade <pkg_name>
yarn audit
```

- Very similar
- Audit: checks for vulnerabilities in dependencies

## JavaScript Frameworks, Rendering Models, and more.

Because of the rise of Node.js, there has been a rise in JavaScript frameworks and rendering models. These frameworks are either client-side or full-stack frameworks, and they are used to make the development process easier. Now, JS can run in your client's browser and on your server, meaning we have unified the front-end and back-end in one language! With this power comes ... more power, as we can manipulate how the user renders a website in different ways. This led to the rise of correpsonding JavaScript Frameworks, each of which embraces a slightly different rendering model. Here's a brief overview of all the main ways:

    Static websites are pre-built and served to the client without the need for any server-side processing. They are fast and simple, but lack dynamic functionality. We covered this above.

    Progressive Web Apps (PWAs) are web applications that can be "installed" on a user's device and run offline. They can be built using a variety of technologies, including **React.js**. These are entirely client-side frameworks that run in the browser, and are in reality singular empty HTML shells with a massive JS bundle that pushes in all the content on-the-fly as the user navigates the site.

    Server-side rendering with hydration is a technique where the initial render of a web application is done on the server, and then "hydrated" on the client with JavaScript to add dynamic functionality. This improves the initial load time and SEO of the application, while still allowing the application to be dynamic. The most famous framework in this category, and the one we'll be using, is **Next.js**.

    Incremental static regeneration is a technique where a web application is rendered statically, but certain parts of the application are periodically re-rendered on the server to ensure that the content is up-to-date (we check if the content has turned "stale" and then refresh from the server when that happens). This is a technique used by Next.js to improve the performance of certain parts of the interface, as well as by other frameworks.

    Partial hydration is a technique where only certain parts of a web application are hydrated, rather than the entire application. This can improve the performance of the application by reducing the amount of JavaScript that needs to be executed on the client. Unlike the previous rendering models, this is less of the basis of an existing framework, and more of a technique that different frameworks can use.

    Islands is a technique where a web application is divided into "islands" of functionality, each with its own hydration and JavaScript execution, isolated in a sea of very-performant and lightweight, but static HTML. This can improve the performance of the application by reducing the amount of JavaScript that needs to be executed on the client. The team behind this architecture is the **Astro.js** framework.

    Streaming SSR is a technique where the server sends the initial HTML of a web application to the client in chunks, allowing the browser to start rendering the application before all of the JavaScript has been loaded. Like...a lot of this list, Vercel's **Next.js** framework is pioneering this technique, with their newly released Next.js 13 (beta).

    Resumability is a technique where a web application serializes all of its JavaScript into HTML, and then loads JS in in as tiny of chunks as possible, allowing the browser to start rendering the application before all of the JavaScript has been loaded. This is the fastest and most performant framework, being pioneered by the team at Qwik. I won't pretend to understand exactly how this works.

Then, at the end of the day, all of this fancy code has to be compiled down into bundles that the browser can understand anyway. Towards this end, the industry heavyweight is **Webpack**, which is a bundler written in JS that can be used to compile all of your code into a single file that can be served to the client. Recent challengers, however, include Vercel's **Turbopack**, which is written in Rust and offers a much faster build time. **Vite** also exists -- an extremely lightweight and performant bundler, normally used in development environments.

# Other stuff (linting, resources, etc.)

## Why Linters Are Necessary

Remember all the weird quirks of JavaScript from last lesson? Unfortunately, we're stuck with JS because
it's the only language that can be understood by browser (for now). To mitigate the
problem, people wrote _linters_ that try to automatically find common problems in written JS.
They are well integrated with editors so you can directly see the warnings. If
you follow the 'Setup your editor' section, you are good to go. You will see
warnings when you accidentally write some wrong code.

## Resources

I recommend the _You Don't Know JS_ series by Kyle Simpson. The ebooks are
available [for free on GitHub](https://github.com/getify/You-Dont-Know-JS/tree/1st-ed).
The series is comprehensive and will teach you everything you want to know.

Additionally, the [MDN Web Docs](https://developer.mozilla.org/en-US/) are a great
resource for quickly looking up the documentation for various features in Javascript, complete with examples.

### JavaScript

We mentioned Mozilla Developer Network as a site for documentation about the JavaScript language, but it's also a great way to get familiar with the language.

Here is their JavaScript guide: [JavaScript Guide - JavaScript | MDN (mozilla.org)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)

It's a bit long, so I recommend skimming through the first few parts, up to and including the Objects section ([Working with objects - JavaScript | MDN (mozilla.org)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects)).

JavaScript objects will show up a good amount in this course, so make sure you understand the basics!

### TypeScript

The official TypeScript website is a great resource to get familiar with the language. There are different guides that assume different programming backgrounds. Choose the article that best suits your background.

Take a look at the Get Started section here: [TypeScript: The starting point for learning TypeScript (typescriptlang.org)](https://www.typescriptlang.org/docs/)

If you've gone through the MDN JavaScript guide, fill in your TypeScript knowledge with this: [TypeScript: Documentation - TypeScript for JavaScript Programmers (typescriptlang.org)](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)

There is also a Handbook that you can chug through if interested (not necessary at all): [TypeScript: Handbook - The TypeScript Handbook (typescriptlang.org)](https://www.typescriptlang.org/docs/handbook/intro.html)

Hope this is helpful for you all! This will be the language you'll be working with all-semester, so being comfortable with the language will pay off.

## In-Class Demo 1: Executing Javascript in `node` and in the browser

TODO: @daniel

- Walk them through using node to execute javascript line by line, as well as using the console to execute javascript line-by-line.
- Specifically,

repository: cornell-dti/trends-in-web-dev-website

branch_name: refs/heads/main

gha_language: TypeScript

repo_name: cornell-dti/trends-in-web-dev-website


text:
# Technology

We have settled upon the following technology choices for the project.

 - GatsbyJS
 - TypeScript (This is optional as people wish to use it)
 - Storybook
 - Jest
 - Prettier / TSLint
 - Reach Router
 - Imagemin
 - Popmotion
 - AWS S3 hosting, CloudFront distribution, Lambda processing

## Technology To Review / Research / Agree upon

 - Styled Components
 - Forms
 - Browserstack testing
 - PWA config
 - CSP and SRI
 - Google Hire integration
 - Google Docs integration
 - AWS API Gateway, Lambda and Codepush
 - S3 Media and delivery
 - Content Arrangement and sourcing
 - Draft mode


text:
---eonx_docs---
title: Installation
weight: 1000
---eonx_docs---

# Installation

## Using Composer

To install this package, we recommend using [Composer][https://getcomposer.org/]:

```bash
$ composer require eonx-com/easy-api-platform
```

## Integrating with Symfony

### Registering the Bundle

If you're using [Symfony Flex][https://flex.symfony.com/], the bundle registration step has already been done for you automatically. If not, follow these simple steps to register the bundle manually:

1. Open the `config/bundles.php` file in your Symfony project.

2. Add the following line to the file:

   ```php
   // config/bundles.php

   return [
       // Other bundles ...

       EonX\EasyApiPlatform\Bridge\Symfony\EasyApiPlatformSymfonyBundle::class => ['all' => true],
   ];
   ```

That's it! You have now successfully installed and registered the EasyApiPlatform bundle for use in your Symfony application. Happy coding!

repository: eonx-com/easy-monorepo

gha_language: PHP

repo_name: eonx-com/easy-monorepo


text:
# Changelog

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

v0.9.0
------------------------------
*September 01, 2021*

### Changed
- Generate and output source maps

v0.8.1
------------------------------
*August 11, 2021*

### Fixed
- Issue where f-http wasn't building for Storybook.

v0.8.0
------------------------------
*August 09, 2021*

### Changed
- Converted from vue-cli-service to vite

v0.7.0
------------------------------
*August 05, 2021*

### Added
- Mock Factory: Now supports passing through of requests

### Changed
- Mock Factory: Setup Mock Response does not require request data to be provided

### Fixed
- Correctly point the main entry point at the dist folder

v0.6.1
------------------------------
*August 03, 2021*

### Added
- Support for resetting mocks between tests

### Changed
- Updated and simplfiied documentation

### Fixed
- Corrections to a few class names
- Removed async from the Mock Factory

v0.6.0
------------------------------
*July 26, 2021*

### Changed
- Accept an instance of f-statistics when initialising a client, doing so means that interceptors record response timings and publish a statistic with the details.
- Several files were changed to objects with constructors because not doing so means that configuration can bleed when more than one instance is initiaised.

v0.5.0
------------------------------
*May 18, 2021*

### Added
- Injected a request/response interceptor to capture and report api timings/details

v0.4.1
------------------------------
*May 11, 2021*

### Changed
- Return status code to support PACT tests further down the stack

v0.4.0
------------------------------
*May 6, 2021*

### Added
- Expose HTTPVerbs for PUT, PATCH, DELETE
- Expose methods for PUT, PATCH, DELETE on client
- Expose a method for setting authorisation token for all requests from a client
- Ability to name a client - useful when we can push stats and logs by API or grouping name

v0.3.0
------------------------------
*April 30, 2021*

### Added
- Support for content type option
- Implemented createMockClient to make integration testing easier
- Ability to setup mock API responses
- Exposed HTTPVerbs as constants

v0.2.0
------------------------------
*April 26, 2021*

### Added
- Support for configuration merging
- Support for basic GET and POST requests

### Changed
- Updated Readme documentation

v0.1.0
------------------------------
*April 26, 2021*

### Added
- Created package


text:
# rikimaru

**rikimaru** is the VS Code extension that lets you search files in the [OpenGenus/cosmos](https://github.com/OpenGenus/cosmos) repository right from the VS Code editor. The extension uses GitHub's code search API.

## Features

Search [cosmos](https://github.com/OpenGenus/cosmos) right from your editor :D

Following is the demo GIF:

![](https://thumbs.gfycat.com/EnviousYellowishEmperorpenguin-max-14mb.gif)

## Requirements

You'll need to have a GitHub `username` and `personal access token`.

## Extension Settings
The command for `rikimaru` is `rikimaru.search`. You could bind a key combination for easy access. You could also invoke the command from the command palette - default keybinding is `CMD + SHIFT + P` on Mac OSX.

This extension contributes the following settings:

* `rikimaru.user.github.name`: Your GitHub username
* `rikimaru.user.github.personal-token`: Your GitHub personal access token

## Known Issues

None so far. If you find any please report or send in a PR! :D

## Release Notes

### v0.0.1:
* Initial release.

-----------------------------------------------------------------------------------------------------------

`-Sid`

repository: OpenGenus/rikimaru

repo_name: OpenGenus/rikimaru


text:
# linux_speedtweaks
make linux faster, at expense of crash reliability & security

disables aslr, kaslr, page table isolation, cpu vulnerability mitigations (SPECTRE, Meltdown, l1tf, etcetc) and for filesystems ext2/3/4 and btrfs, it adds stuff like nobarrier,relatime,data=writeback,journal_async_commit,compress=lzo,nodatasum

and installs libeatmydata in /etc/ld.so.preload (provided multiarch is not enabled)

and adjust vm.dirty_{ratio|expire_centisecs} to make the filesystem utilize much more of the available ram (up to 60% of total ram) for asynchronous disk writes.

if there's any more tricks you think the script should perform, or if you find any issues, please report it at https://github.com/divinity76/linux_speedtweaks/issues

# usage

```
wget 'https://raw.githubusercontent.com/divinity76/linux_speedtweaks/master/linux_speedtweaks.php';
php linux_speedtweaks.php --no-test;
```

license: Unlicense


text:
# Cortinarius olivaceoniger (E. Horak) G. Garnier, 1991 SPECIES

#### Status
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bibliographie des Cortinaires (France), D-O 256 (1991)

#### Original name
Dermocybe olivaceonigra E. Horak, 1988

### Remarks
null

repository: mdoering/backbone

path: /life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Dermocybe/Dermocybe olivaceonigra/ Syn. Cortinarius olivaceoniger/README.md

repo_name: mdoering/backbone


text:
# IMU_3DViewer
Python client to visualize absolute orientation from a BNO055 by means of an Arduino Nano with Adafruit libraries

## Details

It read from the the serial port connected to an Arduino Nano. The Arduino
Nano has been burned with the Examples/Adafruit BNO055/sensorapi sketch.
The sketch sends over the serial port the absolute orientation in the form of:
<code>
X: 328.8750 Y: 3.1875 Z: -1.0000
</code>
Values are in degrees

## Environment
Windows 10
Anaconda

## Dependencies
Python 3
pyserial (pip install pyserial)
vpython (pip install vpython) [vpython.org]


text:
# TERRA 10 Serverless labs

## Lab 000 - Preparing your stuff

* Make sure you are in the root of /terra10-labs-serverless on your filesystem
* check whether your Node version is 8+ with `node --version`
* check whether your NPM version is 6+ with `npm -version`
* check your AWS CLI version with `aws --version`

### unique id
To run the labs with multiple people simultaneously we use an unique number which is used in your account and component naming.
So every time you read T10* please replace this with your own unique ID (like T10a, T10b, etc)


text:
# DDing-Fnv
Fowler–Noll–Vo Hash Function ,Versions contains FNV-1 hash and FNV-1a hash.

## Concept
Fowler–Noll–Vo is a non-cryptographic hash function.

The basis of the FNV hash algorithm was taken from an idea sent as reviewer comments to the IEEE POSIX P1003.2 committee by Glenn Fowler and Phong Vo in 1991. In a subsequent ballot round, Landon Curt Noll improved on their algorithm. In an email message to Landon, they named it the Fowler/Noll/Vo or FNV hash.

#### FNV-1 hash
The FNV-1 hash algorithm is as follows:

```bash
  hash = FNV_offset_basis
  for each byte_of_data to be hashed
       hash = hash × FNV_prime
       hash = hash XOR byte_of_data
  return hash
```

In the above pseudocode, all variables are unsigned integers. All variables, except for byte_of_data, have the same number of bits as the FNV hash. The variable, byte_of_data, is an 8 bit unsigned integer.

#### FNV-1a hash
The FNV-1a hash differs from the FNV-1 hash by only the order in which the multiply and XOR is performed:

```bash
  hash = FNV_offset_basis
  for each byte_of_data to be hashed
       hash = hash XOR byte_of_data
       hash = hash × FNV_prime
  return hash
```

The above pseudocode has the same assumptions that were noted for the FNV-1 pseudocode. The small change in order leads to slightly better avalanche characteristics.

As an example, consider the 64-bit FNV hash:

* All variables, except for byte_of_data, are 64-bit unsigned integers.
* The variable, byte_of_data, is an 8-bit unsigned integer.
* The FNV_offset_basis is the 64-bit FNV offset basis value:<PHONE_NUMBER>9346656037 (in hex, 0xcbf29ce484222325).
* The FNV_prime is the 64-bit FNV prime value:<PHONE_NUMBER>211 (in hex, 0x100000001b3).
* The multiply returns the lower 64-bits of the product.
* The XOR is an 8-bit operation that modifies only the lower 8-bits of the hash value.
* The hash value returned is a 64-bit unsigned integer.

## Installation
Install from NPM.

```bash
  $ npm install dding-fnv --save
```

## Usage
### Hash32
##### version: fnv-1, Examples:

```javascript
var Fnv = require('dding-fnv');
var hashValue = Fnv.hash32('testString', '1');
console.log('String:', hashValue.toStr());
console.log('Decimal: ', hashValue.toDec());
console.log('Hexadecimal: ', hashValue.toHex());
```
##### version: fnv-1a, Examples:

```javascript
var Fnv = require('dding-fnv');
var hashValue = Fnv.hash32('testString', '1a');
console.log('String:', hashValue.toStr());
console.log('Decimal: ', hashValue.toDec());
console.log('Hexadecimal: ', hashValue.toHex());
```

### Hash64
##### version: fnv-1, Examples:

```javascript
var Fnv = require('dding-fnv');
var hashValue = Fnv.hash64('testString', '1');
console.log('String:', hashValue.toStr());
console.log('Decimal: ', hashValue.toDec());
console.log('Hexadecimal: ', hashValue.toHex());
```
##### version: fnv-1a, Examples:

```javascript
var Fnv = require('dding-fnv');
var hashValue = Fnv.hash64('testString', '1a');
console.log('String:', hashValue.toStr());
console.log('Decimal: ', hashValue.toDec());
console.log('Hexadecimal: ', hashValue.toHex());
```

## License
[MIT](http://sailsjs.com/license). Copyright © 2012-2017 Linan Design & The Yunding-network Company


text:
### Indexer access
By default if access to an indexer fails the indexer is disabled for a certain amount of time (for a short while first, then
increasingly longer if the problems persist). You can select to disable this and always try these indexers.

Raw search engines like Binsearch don't support searches based on IDs (e.g. for a movie using an IMDB id). You can enable query
generation for these. Hydra will then try to retrieve the movie's or show's title and generate a query, for example "showname s01e01".
In some cases an ID based search will not provide any results. You can enable a fallback so that in such a case the search will be
repeated with a query using the title of the show or movie.

Some indexers don't seem to like Hydra and disable access based on the user agent. You can change it here if you want. Please leave
it as it is if you have no problems. This allows indexers to gather better statistics on how their API services are used.

### Result filters
This section allows you to define global filters which will be applied to all search results. You can define words and regexes
which must or must not be matched for a search result to be matched. You can also exclude certain usenet posters and groups which are known for spamming.

One forbidden word in a result title dismisses the result. If any of the required words is not found anywhere in a result title it's also dismissed.
You can define forbidden and required words for categories in the next tab.
Usually required or forbidden words are applied on a word base, so they must form a complete word in a title. Only if they contain a
dash or a dot they may appear anywhere in the title. Example: "ea" matches "something.from.ea" but not "release.from.other". "web-dl"
matches "title.web-dl" and "someweb-dl".

Some indexers provide information if a release is passworded. If you select to ignore these releases only those will be ignored
of which I know for sure that they're actually passworded.

### Result processing
In (hopefully) rare cases Hydra may crash when processing an API search request. You can enable to return an empty search page in these cases (if Hydra hasn't
crashed altogether ). This means that the calling tool (e.g. Sonarr) will think that the indexer (Hydra) is fine but just didn't return a result. That way Hydra
won't be disabled as indexer but on the downside you may not be directly notified that an error occurred.

Hydra tries to find duplicate results from different indexers using heuristics. You can control some parameters for that but usually the default values work quite well.

Hydra contains a predefined list of words which will be removed if a search result title ends with them. This allows better duplicate detection and cleans up the titles.

Hydra attempts to parse the provided newznab category IDs for results and map them to the configured categories. In some cases this may lead to category names
which are not quite correct. You can select to use the original category name used by the indexer. This will only affect which category name is shown in the results.

NZB downloads from Hydra can either be achieved by redirecting the requester to the original indexer or by downloading the NZB from the
indexer and serving this. Redirecting has the advantage that it causes the least load on Hydra but also the disadvantage that the requester
might be forwarded to an indexer link that contains the indexer's API key. To prevent that select to proxy NZBs.

By default all found results are stored in the database for 14 days until they're deleted. After that any links to Hydra results still
stored elsewhere become invalid. You can increase the limit if you want, the disc space needed is negligible (about 75 MB for 7 days on
my server).

gha_license_id: NOASSERTION


text:
---
title: Getting Started
position: 1
---

Welcome to the Magic: The Gathering API! You can use the API to access Magic: The Gathering API endpoints, which can get information on cards and sets. All API access is performed over HTTPS and accessed from the `https://api.magicthegathering.io` domain.

To use the API endpoints, the format is as follows:

`https://api.magicthegathering.io/<version>/<resource>`

For example:

`https://api.magicthegathering.io/v1/cards`

There are multiple SDKs available to make it even easier to consume the API.
To chat with other developers and discuss the API and SDKs, check out the [Discord Server](https://discord.gg/qwGJNnP)!

[![mtg-developers on discord](https://img.shields.io/badge/discord-mtg%20developers-738bd7.svg)](https://discord.gg/qwGJNnP)

repository: MagicTheGathering/mtg-docs

repo_name: MagicTheGathering/mtg-docs


text:
---
layout: default
---

# 1996-04-22 - Re: Bad news from Judge Richey

## Header Data

From<EMAIL_ADDRESS>(Anonymous)

To<EMAIL_ADDRESS>Message Hash: a215bf30df9374e3ba662ed061776c79a14d112e09a250fea8a7c8c7a14d73a4

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1996-04-22 14:51:22 UTC

Raw Date: Mon, 22 Apr 1996 22:51:22 +0800

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(Anonymous)
Date: Mon, 22 Apr 1996 22:51:22 +0800
To<EMAIL_ADDRESS>Subject: Re: Bad news from Judge Richey
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

At 11:33 PM 3/25/96 tcmay wrote:
-------------------

jim bell: >talk to Jim Bell about implementing a program using
encryption that doesn't
>_need_ to be exported...legally anyway.

tcmay: You're coming perilously close to actually calling for
the killing of a  federal judge. My recollection is that a
couple of folks have been arrested  and charged for calling for
the killing of judges.

-------------------

Any half-wit falling for agent provocateur Bell's rap will do
hard time, or maybe get popped "in self-defense" by his TLA
watchers.

The son-of-a-bitch's baiting pigeon traps, no question. He's
too myopic to see how he's luring falcons for attack by
high-circling eagles. Bell's going down blind-sided with his
gulls.

{% endraw %}
```

## Thread

+ Return to [April 1996](/archive/1996/04)

+ Return to<EMAIL_ADDRESS>(Anonymous)](/authors/nobody_at_tjava_com_anonymous_)"

+ 1996-04-22 (Mon, 22 Apr 1996 22:51:22 +0800) - Re: Bad news from Judge Richey -<EMAIL_ADDRESS>(Anonymous)_


text:
# discourse-custom-trust-level
Custom Trust Level
This plugin allows you to add a few custom trust levels capabilities in Discourse.

- This plugin allows you to add/revoke a few capabilities of users of some trust levels.

- These capabilities can be added/revoked using the site settings.

- These capabilities can be added/revoked to/from all the users of that trust level.

Get the code

:raising_hand_man: You can request a feature or report a bug in a reply below or message a maintainer.

## Setup
- All site settings of this plugin have a prefix 'csl_'

- Not sure how to install a plugin? Follow the steps here

## Features
-  Define the minimum trust level to create a post on the topic.

- Specify whether TL3 (trust level 3) can edit posts or not.

- Specify whether TL0 (trust level 0) can reply as a new topic or not.

- Specify whether TL0 (trust level 0) can have actual links in the ‘about me’ field of the user's profile
- Define the minimum trust level to invite users to the topic.

## Maintainers
Github: Ahmedgagan, Github: fzngagan

**Note: Test the plugin before adding it to a live website**

repository: Ahmedgagan/discourse-custom-trust-level

gha_language: Ruby

repo_name: Ahmedgagan/discourse-custom-trust-level


text:
# Web APP

> uses the Nuxt.js and Express.js projects
>
> **Note:** This is only the WebApp part of Human-Connection, you have to also checkout the [API](https://github.com/Human-Connection/API) which is used by this WebApp.

This is the nuxt + express version of our WebApp as nuxt.js seams to be more stable and we have better options for keeping it updated.

repository: Toverto/Documentation

repo_name: Toverto/Documentation


text:
# MakeCode Package for 4tronix Cube:Bit Magical RGB Cubes of Awesome

Helper routines for using the neopixels in the Cube:Bit range of Cubes https://4tronix.co.uk/cubebit/.

## Defining the Cube
The first thing you should do is create a Cube object with the required dimensions per side. Use the block:
```blocks
create cube:bit on pin0 with side <3/4/5/6/7/8>
```

Then set the brightness to be used from 0 to 255. If this block is not used, then the brightness is set to 40. We strongly recommend keeping this at less than 100. All values sent to the LEDs after this command will be scaled down to fit in this maximum brightness level.
```blocks
set cube:bit brightness to <0..255>
```

## Using Cube:Bit Pixels
Each pixel can be addressed by using the pixel ID which is a number from 0 to the number of pixels in the cube minus one. eg. a 3x3x3 cube has 27 pixels so the ID can be 0 to 26, 4x4x4 has 64 (ID 0 to 63) and 5x5x5 has 125 (ID 0 to 124)
```blocks
set pixel color at ID to <colour>
```
The colour value is a number. There are some pre-define colours (eg. Red, Yellow, etc) or you can put in a simple number, or you can define separate Red, Green and Blue values using the map colour block
```blocks
convert from red, green, blue
```

If you want to specify the x,y,z position of the pixel then use the mapping block to create the pixel ID
```blocks
map from x y z
```

If you have set the Manual update mode, then whenever changing the colour of pixels or clearing them, or rotating them, you will need to display the result afterwards. Use the show changes block for this. The default update mode is automatic so any changes to the LED values will immediately appear on the LEDs
```blocks
show Cube:Bit changes
```

You can also set a whole plane of pixels to the same colour. eg. set the top slice to blue, or the left side to green. Use the set plane block:
```blocks
set plane <number> on axis <xy, xz, yz> to <colour>
```

## Supported targets

* for PXT/microbit

## License

MIT

repository: veryalien/CubeBit

repo_name: veryalien/CubeBit


text:
# photo-gal
Photo manager and gallery made of Vanilla JS, Bash scripts, and PHP

# DSLR 🔌 Raspberry-Pi 📡 Web-Server
![Screenshot](https://raw.githubusercontent.com/zvakanaka/photo-gal/master/img/photo-gal.png)
## Usage
1. Plug DSLR into Raspberry-Pi (or any computer with this set up)
2. Open web browser and go to the ip-address/photo-gal
3. Log into an admin account (after making a user an admin in the setup)
4. Use the UI to download photos from DSLR (creates thumbs and lightbox-sized images too)
5. Optionally upload galleries to a server

## Setup
```sh
$ bash setup.sh
```

[Further Setup](docs.md)

---
## Local Development
[Sng](https://www.npmjs.com/package/sng) can be used to serve PHP from somewhere in your home folder. Nginx, PHP, and MySQL are required. Sng requires npm, the neatest way to install that is with [nvm](nvm.sh) (Node Version Manager).

1. Place a file named `.sng.conf` in the parent directory of the project. Place these contents in `.sng.conf`:
```
# pass the PHP scripts to FastCGI server listening on the php-fpm socket
location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
}
```

2. Run `sng` from that parent directory.

3. Upload albums without a password (mandatory for UI uploads)
```sh
$ ssh-keygen
$ ssh-copy-id<EMAIL_ADDRESS>-P 22
```

repository: zvakanaka/photo-gal

repo_name: zvakanaka/photo-gal


text:
# Deploy on Docker host server using Jenkins
# *Jenkins Job name:* `Deploy_on_Docker_Host`

### Pre-requisites

1. Jenkins server
1. Docker-host Server

### Integration between Docker-host and Jenkins

Install "publish Over SSH"
 - `Manage Jenkins` > `Manage Plugins` > `Available` > `Publish over SSH`

Enable connection between Docker-host and Jenkins

- `Manage Jenkins` > `Configure System` > `Publish Over SSH` > `SSH Servers`

	- SSH Servers:
                - Name: `docker-host`
		- Hostname:`<ServerIP>`
		- username: `dockeradmin`

       -  `Advanced` > chose `Use password authentication, or use a different key`
		 - password: `*******`

### Steps to create "Deploy_on_Docker_Host" Jenkin job
 #### From Jenkins home page select "New Item"
   - Enter an item name: `Deploy_on_Docker_Host`
     - Copy from: `Deploy_on_Tomcat_Server`

   - *Source Code Management:*
      - Repository: `https://github.com/moderohan97/Devops-Project.git`
      - Branches to build : `*/master`
   - *Poll SCM* :      - `* * * *`

   - *Build:*
     - Root POM:`pom.xml`
     - Goals and options: `clean install package`

 - *Post-build Actions*
   - Send build artifacts over SSH
     - *SSH Publishers*
      - SSH Server Name: `docker-host`
       - `Transfers` >  `Transfer set`
            - Source files: `webapp/target/*.war`
	       - Remove prefix: `webapp/target`
	       - Remote directory: `//home//ansadmin` or `.`

Save and run the job now.


text:
---
layout: page
title: About
permalink: /about/
feature-img: "img/sphere.png"
---

I'm graduated from [ENSEIRB-MATMECA](http://www.enseirb-matmeca.fr/en) (in Bordeaux - France) as Finite Element Analysis Engineer.
After working with [EDF](https://www.edf.fr/en/the-edf-group), I looked for a new job.
During this time I improved my English proficiency by taking courses and traveling. I learned then a new language, German, in order to move in Germany (where I currently live).

As a hobby I discovered my interest in Artificial Intelligence and learned to code. That was my firsts steps in JavaScript.
And I enjoyed it so much that I decided to learn web-development to make a work of this new passion.
I started to follow on-line tutorials or courses (like [codeschool](https://www.codeschool.com/) or [codecademy](https://www.codecademy.com/))
but wasn't plainly satisfied of what I learned until starting my apprenticeship at [Bloc.io](https://www.bloc.io/).
There I received personal coaching from an experienced mentor and could learn good coding practices.

During my Apprenticeship with Bloc.io, I gained a wide range of skills in Front-end development (HTML, CSS, JavaScript, jQuery, Bootstrap and AngularJS).
I’m familiar with modern development tools such as: Git, Github, npm, Grunt, Heroku.

repository: amizony/portfolio

repo_name: amizony/portfolio


text:
README for rho.c
Puyan Lotfi
Math 3012: Ravi Montenegro

https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
https://math.gatech.edu/courses/math/3012

- To compile rho.c just "make".
- If you want to see the prompt
  that comes up when running
  "make prompt".
- To run, enter "./rho.bin n"
  or "./rho.bin n c x_0", entering
  just n is the same entering
  "./rho.bin n 1 2".
- For debug output "make debug".

The random 10 were a result of me pecking
randomly at the numpad until I had 90 digits
then I just made newlines and got rid of
the leading zeros.

The next 2 sets (products of primes) were
just a result of me randomly picking
primes from the list provided.

10 random 9 digit numbers:

   n           Steps    Factor

135824683        4       23
579985629        1        3
560702715        1        3
957290567        4       23
252106708        1        7
290672595        1        3
179593002        1        3
890509820        2        4
658295002        2        2
800592905        1        7

average number of steps:  2 (1.8 was the mean)

10 9 digits number which are the
product of 3 3-4 digit primes:

    n             primes             Steps      Factor

343775741 =   883 *  617 *  631        26         631
191362879 =  1031 *  313 *  593         5         313
709666267 =   769 *  911 * 1013        17      922843 *
587050549 =   983 *  599 *  997         9         983
414973483 =  1039 *  347 * 1151        16        1151
723192959 =  1201 *  701 *  859        20         701
401919487 =   587 * 1039 *  659        22         659
513379333 =   967 *  521 * 1019        16        1019
866938019 =  1033 *  977 *  859         9        1033
504731189 =   563 * 1051 *  853         5         563

average number of steps:

                           mean: 92989.60
            without the outliers:   784    (783.66 mean)
          911 instead of 922843:   796    (796.40 mean)

* note: These are the same result as rho.exe (Red Hat)
        which was posted on the project website. I
        actually found another implementation which
        I planned on using for testing my results along
        which rho.exe that gave me different factors.
        For example for the noted n, I got the factor
        911. I am not too sure why at this moment, but
        my results are in line with the posted rho.exe
        so I will leave it be. The site with the other
        implementation is

http://www.math.umbc.edu/~campbell/NumbThy/Class/
Programming/JavaScript.html

IN NO WAY WAS THIS IMPLEMENTATION USED FOR THE MAKING
OF THIS PROGRAM!!!

10 9 digit numbers which are the
product of 2 4-5 digit primes:

    n          primes          Steps         Factor

140946259 = 12253 * 11503        19           12253
112684927 =  9973 * 11299       150           11299
114433733 = 11161 * 10253        39           11161
111110557 = 11177 *  9941       125           11177
122167139 = 11393 * 10723        77           10723
120095057 = 10891 * 11027       168           10891
134424203 = 11897 * 11299       150           11299
131215319 = 11119 * 11801        94           11119
131053679 = 11503 * 11393        40           11503
141214349 = 12421 * 11369        70           11369

average number of steps: 93 (93.2 mean)

Most of the cases I tried, the number of steps was smaller than
1.2 * sqrt(p) (even the smaller factor). For example
1.2*sqrt(631) = ~30 and the number of steps was 26. Usually
it would be close to a smaller factor p, but less.

For<PHONE_NUMBER>89118539 Brent's Rho doesn't seem too much quicker
that Pollard's Rho on the Redhat machine hensinki (coc machine,
dual P4 Xeons) at first run. But timing them you see:

helsinki% time ./brentrho.exe<PHONE_NUMBER>89118539 1 2
It took 12664 steps to find a factor.
Required 0.17000 seconds.
A factor of<PHONE_NUMBER>89118539 is 44680463.
0.170u 0.000s 0:00.17 100.0%    0+0k 0+0io 216pf+0w
helsinki% time ./rho.exe<PHONE_NUMBER>89118539 1 2
It took 8944 steps to find a factor.
Required 0.29000 seconds.
A factor of<PHONE_NUMBER>89118539 is 44680463.
0.290u 0.000s 0:00.30 96.6%     0+0k 0+0io 216pf+0w
helsinki%

So now we see that Brent's Rho is nearly twice as fast as
Pollard's Rho.

repository: plotfi/pollards-rho

repo_name: plotfi/pollards-rho


text:
### Signal Middleware example

Download example and run in examples directory:

```
yarn install
yarn start
```

or just look example in https://xnimorz.github.io/signal-middleware

In this example:

* `areas` model use a real server request
* `comments` model use a setTimeout to emulate async logic
* `switcher` use a plain redux actions, without signals

repository: xnimorz/signal-middleware

repo_name: xnimorz/signal-middleware


text:
# FlightSRPAssignment

FlightSRP Assignment

Problem statement Fetch data from "https://www.ixigo.com/sampleFlightData" and show them in list

Install and Run - As no pods are used so download and run it

Architecture

Code structure has been divided like Three folders - Core , Network Layer, Presentation Layer
Followed MVVM Architecture along with object oriented along with Solid principles:
DomesticFlightSRPViewController- Contains all UI stuff related code.
FlightSRPResponseModel - Conforms codable protocol
Network Layer - Tried to use of generics and singleton pattern
Applied all possible sorting logics and applied animations

Unit Testing
 Cover all possible test cases in the project

FlightSRPResponseModelTests.swift - Tested initialization of FlightSRPResponseModel
 -  testViewModelIntialisation()
NetworkLayerTest.swift -  Tested the api call for both success and failure cases
testFetchFlightServiceSuccess()
testFetchFlightServiceFailure()

3. DomesticFlightCellModelTests - testGetTripDurationSuccess() and testGetTripDurationFailure()


text:
---
layout: post
title: When There's Something Bad, and It Dont Look Good...
subtitle: Who you gonna call?
tags: [assignments]
---
Ghost busters!!
 Anyway....

 For this assignment we were supposed to have our Arduiono board flash all of its red lights whenever it was both cold and dark. For this assignment I considered cold anything under 60 degrees.

![picture of red lights](https://raw.githubusercontent.com/Katelyn-H/Katelyn-H.github.io/master/img/IMG_20191104_224547.jpg)

Tips for past self:
#1. You need three alligator clips for the temperature sensor. So. That's why it was being weird the first time.

Also, my temperature sensor started acting wonky after I returned to my room from the TA session and tried to get a solid reading. I'm not sure why this could be, because I had all the wires connected properly and my code hadn't changed.