text:
# Parser package

## Installing

Simply add `parser` to your config.php `always_loaded.packages` config option.

## Included Parsers

* Markdown - A PHP version of Markdown by Michel Fortin.

Simply add the libraries to your project's `composer.json` then run `php composer.phar install`:

```json
{
    "require": {
        "dwoo/dwoo" : "*",
        "mustache/mustache" : "*",
        "smarty/smarty" : "*",
        "twig/twig" : "2.*",
        "mthaml/mthaml": "*",
        "pyrocms/lex": "*",
        "zordius/lightncandy" : "dev-master"
    }
}
```

Note that the  Markdown parser is installed by default, as it is also used by the FuelPHP core class `Markdown`.

Libraries that can not be installed through composer are expected to be installed in in `APPPATH/vendor/lib_name` (capitalize lib_name),
and you'll have to download them yourself. Don't change the casing or anything, keep it as much original as possible within the `vendor/lib_name`
dir to keep updating easy (also because some come with their own autoloader).

You can configure them to be loaded from other locations by copying the parser.php config file to your app and editing it.

## Config and runtime config

Currently the drivers still lack a lot of config options they should probably accept. They are currently all configured to work with one instance of their parser library, which is available to config:

```php
// Clear the cache for a specific Smarty template
$view = View::forge('example.smarty');
$view->parser()->clearCache('example.smarty');

// Example static usage
View_Smarty::parser()->clearCache('example.smarty');
```

repository: isael/EvaluadorVirtual

repo_name: isael/EvaluadorVirtual


text:
# RegXMania - Test App for Regular Expressions

Testing app for regular expressions, using React.js.

Demo: https://nlharri.github.io/thecodinghype/regxmania/index.html

license: MIT

repository: nlharri/the-coding-hype

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: nlharri/the-coding-hype


text:
# rpi-golang

Docker image containing GOLANG that is compatible to the Raspberry Pi.

### Build the Docker Image
```bash
make build
```

### Run the Docker Image and get version of installed GOLANG
```bash
make version
```

### Push Docker Image to Docker Hub
* First, use a `docker login` with username, password and email address
* Second, push Docker Image to the official Docker Hub
```bash
make push
```

repository: axeldeau/rpi-golang

repo_name: axeldeau/rpi-golang


text:
---
layout: post-layout.njk
title: 'Voting Systems'
description: "Voting in politics and in software applications isn't as simple as it may seem. Here I discuss designing some basic voting systems and analyze their intricacies, pros, and cons."
headerBackground: '#EDE7F6'
headerColor: '#000000'
titleColor: '#5C4B75'
headerImage: /stuff/posts/voting-systems/cover.jpg
headerImageWidth: 400
headerImageHeight: 413
socialImage: /stuff/posts/voting-systems/social.jpg
imageWidth: 1280
imageHeight: 670
date: 2020-11-10
tags: ['posts']
---

## Introduction

We encounter voting in some form around us all the time. We rate our Uber drivers, they rate us back. We up-vote and down-vote posts and trolls on Reddit. We give stars to movies and restaurants. We vote on who gets kicked out of our favorite reality television show. We vote for Presidents.

All these voting systems seem a bit different from one another, but one thing that's definitely common among them — we will find ways to complain about them. The way a voting system is designed can make an *election* trivial or really complicated in nature. In fact, sometimes, the winner of an election may be determined by the rules of the voting system and not the intent of the voters (electoral college anyone?). In this post I try to explore the core of different voting systems and wonder if there is a perfect voting system.

Here I am going to use the word *election* to define an event or a goal that requires voting. An election doesn't have to be political in nature.

*Note and Acknowledgement: This blog post is influenced by the chapter on voting systems in video games in the book Power-Up by Matthew Lane.*

## Plurality Voting

This is the simplest form of voting. Most political elections in the United States are done using this form of voting. It's quite simple — every voter casts a vote for their favorite candidate. The candidate with the most number of votes wins.

Let's look at an example that we will continue to use in this post. We ask 100 people to vote for their favorite flavor of ice cream. The candidates are *Vanilla*, *Chocolate*, and *Strawberry*. Here's the result:

| Flavor         | Votes  |
| :------------- | -----: |
| Vanilla        | 45     |
| Chocolate      | 40     |
| Strawberry     | 15     |

Vanilla has won! Now if you stare at the numbers a bit, you will find some downsides in declaring Vanilla the winner in this election of the flavors.

An obvious one is that more votes were cast for a flavor that is not the winning flavor. You could also argue that no flavor should win because none of them reached a majority.

Here Strawberry is acting as a **spoiler** — similar to how third-party candidates in US elections can be considered spoilers. Maybe we should have a **_run-off election_** where only Vanilla and Chocolate are considered. Perhaps more people favor Chocolate over Vanilla when Strawberry is out of the picture. (The US state of Georgia has rules akin to this. In the 2020 elections for the senate seats in Georgia, none of the candidates achieved a majority. So run-off elections will be held in January of 2021 with the top two candidates).

The essence of the Plurality voting system is that it does not capture the full spectrum of voters' preferences. If someone voted for Strawberry, it does not tell us how they feel about Vanilla or Chocolate.

This system does not truly determine the *'will of the people'*, unless.... there are only two candidates. One of the candidates is guaranteed to receive a majority, barring a tie. So if it were truly a *two-party system* some of the flaws of this system do not matter any more.

## Ranked Choice Voting

Since the Plurality based system does not capture the full spectrum of the voter's preferences, we should probably ask for more information from the voters. What if we asked the voters to rank all the candidates, rather than cast a ballot for their favorite?

Let's look at the example we've been working with. We asked the 100 people to rank the candidate flavors. Here's the result:

| 1st            | 2nd            | 3rd            | Votes  |
| :------------- | :------------- | :------------- | -----: |
| Vanilla        | Strawberry     | Chocolate      | 45     |
| Strawberry     | Chocolate      | Vanilla        | 15     |
| Chocolate      | Strawberry     | Vanilla        | 30     |
| Chocolate      | Vanilla        | Strawberry     | 10     |

All of the 45 people who voted for Vanilla had Strawberry as the second choice. All 15 people who voted for Strawberry, had Chocolate as their second choice. Of the 40 people who voted for Chocolate, 30 preferred Strawberry over Vanilla, and 10 preferred Vanilla. So, which flavor won? There are multiple ways to interpret this data. Let's look at a couple 👇

## Borda Count

In this system for `n` candidates, each first-place vote receives `n` points. Second-place receives `n-1` points, and so on. The candidate with the most points wins.

Let's compute the points in our example. Vanilla received 45 first places, 10 second places, and 45 third places. So the score for Vanilla is `45n + 10(n-1) + 45(n-2)`. Here, `n` is `3`, giving Vanilla a score of `200`. Here's the final tally:

| Flavor         | Points  |
| :------------- | ------: |
| Vanilla        | 200     |
| Chocolate      | 195     |
| Strawberry     | 205     |

Strawberry has won! Strawberry, which had the fewest votes in the Plurality voting system, has the most points in the Borda ranking system. Totally ridiculous, isn't it? Well maybe, but maybe not. Strawberry did receive the fewest third-place votes. And 75% of the people had Strawberry as their second choice.  Perhaps Strawberry does deserve to win!

## Instant Runoff Voting

Let's take a look at a different model of interpreting the ranked voting data. In an Instant Runoff, the candidate with the fewest first-place votes is eliminated, and its votes are distributed to the second choice. This is then repeated until we have one candidate left standing.

Some consider this model of iterative elimination a bit confusing and thereby not practical. But it's getting wide adoption, including in political elections (San Francisco and Oakland city elections, for example). It is also used to decide the winner of the Best Picture Academy Award.

Let's apply this to our current example.

| Flavor         | Votes  |
| :------------- | -----: |
| Vanilla        | 45     |
| Chocolate      | 40     |
| Strawberry (eliminated)     | 15     |

 Strawberry is eliminated. Since all Strawberry voters preferred Chocolate over Vanilla, Chocolate gets Strawberry's 15 votes. Chocolate now has 55 votes, a majority. Chocolate has won!

 ## Quick Recap

 We have discussed three systems so far, and in our example, we have had three different winners for the same election. You may decide subjectively that one of these systems may be better for the use case you have in mind, or you might think as I did at first: **It's all pointless!**

 ## The Impossibility

 There is a concept in decision theory called the **[Independence of Irrelevant Alternatives (IIA)](https://en.wikipedia.org/wiki/Independence_of_irrelevant_alternatives)** which states a voter's preference between two choices `x` and `y`, should not depend on any other choices.

 This seems like a simple and a good rule to live by and our election systems should live by them as well. Sadly, all the systems we have looked at so far do not abide by this rule.

 Let's look at the Plurality system - From the rankings we know that all of Strawberry voters prefer Chocolate over Vanilla. If the choice of Strawberry was not there, Chocolate would have won with 55 votes. But with Strawberry present, Vanilla wins with 45 votes.

 For the Borda system, Chocolate is the spoiler. With Chocolate in the picture, Strawberry wins. Without Chocolate, Vanilla wins 55-45.

 In the Instant Runoff, Chocolate wins when Vanilla is present but Strawberry wins 60-40 if Vanilla is not.

 ### Arrow's Impossibility Theorem

 In decision theory, here are some good things to have in an election or any voting system.

 - Independence of Irrelevant Alternatives: which we have discussed and failed to account for so far.
 - Nondictatorship: Output should not be based on one individual, the wishes of multiple voters should be taken into consideration.
 - Pareto Efficiency (Unanimity): should have a notion of [unanimity](https://en.wikipedia.org/wiki/Pareto_efficiency) — If every voter prefers candidate A over candidate B, candidate A should win.
 - Unrestricted Domain: Voting must account for all individual preferences.
 - Ordering:  Each individual should be able to order the choices in any way.

 All good rules, don't you think? Let's create the ultimate voting system! But here comes [Kenneth Arrow](https://en.wikipedia.org/wiki/Kenneth_Arrow) to shatter our hopes.

 **[Arrow's Impossibility Theorem](https://en.wikipedia.org/wiki/Arrow's_impossibility_theorem) states that in all cases where preferences are ranked, it is impossible to formulate a social ordering without violating one of these rules.**

In other words, any democracy that satisfies Unanimity and the Independence of Irrelevant Alternatives, must be a dictatorship! \*_insert dramatic sound effects_\*

So yeah, we will always find things to argue about in an election. 😒

 ## Dodging the Impossibility

 Since every system is flawed, is it the end of this essay? Unfortunately for you, I, like many of you, noticed this one clause in Arrow's impossibility theorem which provides a way for us to escape this gravity well.

 The theorem assumes that we are dealing with a ranked choice voting system. Let's just not rank our candidates. 💡

 Here I would remind you, that we're trying to look at voting systems in general, not just political elections.

 We have implemented non rank based systems in Software numerous times. Think Netflix, Yelp, Reddit, Tinder. The key as you may have guessed is rating, and not ranking (Tinder being a more specific type of rating - approval voting, which I'll discuss later). A voting system based on rating is usually called **Score Voting**.

## Score Voting

The idea behind score voting is that you give each candidate a score in one or many categories. This score is independent of the score the other candidates receive. Think Diving and Gymnastics in the Olympics. The judges rate each athlete based on form, routine, landings. One with the highest total score wins.

But is this system better? That's subjective but we know it lets us escape the impossibility mathematically, and yet conform to independence, unanimity and nondictatorship rules.

## Approval Voting

There's a simpler form or Score Voting - Approval Voting. Think of it as a binary version of the score voting. Each person can give a candidate a score of `0` or `1`. In other words one can approve or disapprove any number of candidates.

This is similar to how people vote on dating apps like Tinder. They give prospects a score of `1` by swiping right, and a score of `0` by swiping left.

## Strategizing the Ranked Vote

One key advantage for Score Voting and Approval Voting is that it never hurts to vote for your favorite candidate. It may seem obvious and trivial but it's not always satisfied by voting systems. For example, it is common in political elections for people to not vote for the third-party candidate even though the third-party candidate may be the voter's first choice; since you know your candidate is unlikely to win, so vote for one of the top two likely candidates instead.

Let's see how ranked voting could alter the elections in our ice cream flavor example. If 20 of the 45 people who voted for Vanilla strategize and vote for Strawberry over Vanilla (their favorite candidate), they can cause Chocolate to lose.

Before strategizing:

 1st            | 2nd            | 3rd            | Votes  |
| :------------- | :------------- | :------------- | -----: |
| Vanilla        | Strawberry     | Chocolate      | 45     |
| Strawberry     | Chocolate      | Vanilla        | 15     |
| Chocolate      | Strawberry     | Vanilla        | 30     |
| Chocolate      | Vanilla        | Strawberry     | 10     |

After strategizing:

 1st            | 2nd            | 3rd            | Votes  |
| :------------- | :------------- | :------------- | -----: |
| Vanilla        | Strawberry     | Chocolate      | 25     |
| Strawberry     | Vanilla        | Chocolate      | 20     |
| Strawberry     | Chocolate      | Vanilla        | 15     |
| Chocolate      | Strawberry     | Vanilla        | 30     |
| Chocolate      | Vanilla        | Strawberry     | 10     |

Score and Approval voting are not immune to strategizing but they do not fall victim to the obvious situations where voting for your favorite candidate can be detrimental for that candidate.

## Rating the Systems

We have discussed five different voting systems so far, and definitely there has to be a best one. In reality, situations often fall back to the age old trope — *it depends*. Some environments do not want to complicate it for the voters, so a score based system is not preferred. A lot of cases an Approval system could replace the Plurality system because of it's simple nature.

But to rate a voting system means to measure a rating system. How do you measure the 'goodness' of a voting system? One model for doing that is called **Bayesian Regret**.

## Bayesian Regret

The [Bayesian regret](https://en.wikipedia.org/wiki/Bayesian_regret) measures the *expected unavoidable human unhappiness* caused by a voting system. The more the unpopular candidates get elected, higher the Bayesian regret.

This value is computed using a number of factors: number of voters, number of candidates, the amount of strategizing by the voters, etc. With this, it calculates two features: how much utility society gains from the outcome, and the maximum possible utility the society could have gained from each of the candidates. The difference in these values gives the Bayesian regret. Though I do understand the concept here, I do not know the intricate details in calculating these values.

Mathematician Warren D. Smith studied different voting models, simulating various elections and estimating the Bayesian regret. A lot of it is available on his website [rangevoting.org](https://www.rangevoting.org)

Here's a rough representation of the data from the simulation:

Each bar represents the range of Bayesian regret values in the election simulations. Lower the value (closer to the left bar) the less the regret.

Here's what we can see from the chart:
- Plurality voting performs poorly regardless of strategizing (the range of values with various strategizing simulated).
- Both the ranked-choice systems (Borda and Instant Runoff) end up with a broad range of regret values, depending on how much strategizing goes on.
- Even with strategizing, Score and Approval voting offer a much smaller range of regret values.
- When voters are honest, score voting gives the lowest regret value.
- The Approval voting system offers a much lower regret value than the Plural system, and yet is equally simple in design.

## Conclusion

No voting system is perfect, but the design of the voting system has a huge impact on the winner of the election. Our most common voting system - Plurality voting has a set of serious flaws. It can create spoilers, is least expressive for voters, bad mathematically, predicts higher regret values.

Approval and Score voting add a huge value over the rank-based voting systems.

I am no expert on the topic, but this is what I have learned, found interesting, and have put into a blog post.

gha_language: HTML


text:
[@redhat-cloud-services/notifications-client](../README.md) > [AppRelationships](../interfaces/apprelationships.md)

# Interface: AppRelationships

*__export__*:

*__interface__*: AppRelationships

## Hierarchy

**AppRelationships**

## Index

### Properties

* [eventTypes](apprelationships.md#eventtypes)

---

## Properties

### `<Optional>` eventTypes

**● eventTypes**: *[Relationships](relationships.md)*

*Defined in [api.ts:149](https://github.com/RedHatInsights/javascript-clients/blob/master/packages/hooks/api.ts#L149)*

*__type__*: {Relationships}

*__memberof__*: AppRelationships

___

repository: rvsia/javascript-clients

repo_name: rvsia/javascript-clients


text:
# Alt

* Fantasy Land Specification Page: [Alt](https://github.com/fantasyland/fantasy-land/#alt)

A value that implements the Alt specification must also implement
the [Functor](#functor) specification.

1.  The
`fantasy-land/alt` method takes one argument:

    a['fantasy-land/alt'](b)

1. `b` must be a value of the same Alt

    1. If `b` is not the same Alt, behaviour of `fantasy-land/alt` is
       unspecified.
    2. `a` and `b` can contain any value of same type.
    3. No parts of `a`'s and `b`'s containing value should be checked.

2. `fantasy-land/alt` must return a value of the same Alt.

>\#100DaysOfCode

---

##### Copyright © 2020 Benjamin Vincent Kasapoglu (Luxcium)

###### Scientia is lux principium✨™

gha_language: JavaScript

gha_license_id: NOASSERTION


text:
# Project Title

This repository contains the assignments that we given for the course CS370 - Operating Systems. The course covers the book Operating System Concepts by Abraham Silberschatz, Peter Baer Galvin and Greg Gagne. All assignments are done in C on a Linux framework.

## Getting Started

If you wish to run this code, fork the repository in a Linux based system. For detailed description see the prerequisites below.

### Prerequisites/Installation

While most of the assignments can be done on on any Linux-based system, some of them require Kernels to be loaded directly onto the OS and can potentially crash your OS. Therefore it is recommended you download and install the virtual box (if you do not already have one), and [OSC-2016 Virtual Machine](http://people.westminstercollege.edu/faculty/ggagne/osc/vm/index.html).

## Running the tests

Compile the C++ code and run it.

### Break down into end to end tests

Explain what these tests test and why

```
Give an example
```

### And coding style tests

Explain what these tests test and why

```
Give an example
```
## Contributing

Please read [CONTRIBUTING.md](https://gist.github.com/PurpleBooth/b24679402957c63ec426) for details on our code of conduct, and the process for submitting pull requests to us.

## Authors

* **Billie Thompson** - *Initial work* - [PurpleBooth](https://github.com/PurpleBooth)

See also the list of [contributors](https://github.com/your/project/contributors) who participated in this project.

## License

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

## Acknowledgments

* Hat tip to anyone whose code was used
* Inspiration
* etc

gha_language: C


text:
# Deep Learning One Stop Shop

### Specs
ubuntu 16.04
cuda 10.0
python 3.6.7
pytorch 1.0.1.post2
tensorflow 1.13.1
jupyter with r kernel support
many more python packages...
many r packages...
openssh and other linux tools...

### Installation
1. make sure your host has the nvidia-docker installed and the right cuda support
2. run from inside the folder
```
docker build -t <docker_name> .
```
3. run the image using
```
nvidia-docker run ...
```

repository: YontiLevin/Dockers

repo_name: YontiLevin/Dockers


text:
# gosu-lang-ext
Provides extensions to the standard [gosu-lang](https://github.com/gosu-lang/gosu-lang "gosu-lang") libraries.

## License

Released under version 2.0 of the [Apache License](http://www.apache.org/licenses/LICENSE-2.0.txt "License").

### Validation
`Validation.require()`  is a syntactic sugar for validation code which throws exceptions (e.g. validating that the function input is correct). For example:
```
if (myParam == null) {
	throw new IllegalArgumentException("myParam cannot be null")
} else {
	//continue program flow
}
```
becomes
```
Validation.require(\ -> myParam != null, "myParam cannot be null")
```

The class also allows for construction of other exceptions or executing alternative flows if the condition does not evaluate to true.

### Run - wrapper for `gw.transaction.Transaction`

#### What
Useful abstractions which allow running functions with Guidewire bundles under
context of different users. This is particularly useful for Guidewire entity builders.

##### Note:
This class is applicable to the Guidewire platform and is not useful for
`gosu-lang` developers on the open-source version.

#### Why
Guidewire provides `gw.transaction.Transaction` class to handle programming cases
when an explicit bundle is required in the application code. These use cases are
documented extensively in the Guidewire documentation.

This class is an abstraction for the cases when a function, which requires a bundle,
also returns a value. This is typical for Guidewire entity builders, which require
a bundle but also return an entity object.

Additionally, "Run" is a bit faster to type than "Transaction". For this reason,
it is a separate class, rather than an enhancement on the existing "Transaction" type.

#### How
##### Without this class
```
import gw.transaction.Transaction

var result: A

Transaction.runWithNewBundle(\bundle -> {
  result = new XYXBuilder()
    .withA()
    .withB()
    .create(bundle)
}, user)

return result
```
##### With this class
```
import gosu.transaction.enhancements.Run

var result = Run.asUser(\bundle -> {
  new XYXBuilder()
    .withA()
    .withB()
    .create(bundle)
}, user)
```
### Algebraic Data Types (ATDs)
#### Tuples
Tuple is an ordered list of elements in which elements can be of different types. The element projections (typed values) are exposed as ElementN where N ranges from 1 to max dimension or arity.  Tuples are useful as composite type constructors which contain proper equals() and hashCode() implementations, which make them usable as composite keys in HashMaps, Sets, etc. However, caution should be exercised at high arities, as tuples inhibit understanding of code (e.g. what does Tuple10.Element10 mean?).

Tuples can be constructed either by invoking a constructor or static builder (apply) function. Static builder function is preferable, since it uses the type system to determine the type of each element:
```
var result1 = Tuple2.apply("A", 1)
print (result1.Element1)   // A
print (result1.Element2)   // 1
```
A constructor should be used when the type system cannot determine the type (usually when elements are blocks), in which case the element types should be defined explicitly:
```
var e1 = \ -> "A" // a block which returns "A"
var e2 = \ -> 1   // a block which returns 1

var result2 = new Tuple2<block(): String, block(): Integer>(e1, e2)
print (result2.Element1()) // evaluate Element1() - returns "A"
print (result2.Element2()) // evaluate Element1() - returns 1
```
Tuples (and tuple tests) are generated by a TupleGenerator which uses velocity templates. TupleGenerators allows customization of max dimension and some other parameters via `withXYZ()` calls, e.g. `withMaxArity(X)`. Sample TupleGenerator usage:
```
TupleGenerator.INSTANCE.withBasePackageName("com.abc").withMaxArity(10).run()
```
This will generate com.abc.gosu.functional.adt.Tuple2 to com.abc.gosu.functional.adt.Tuple10 classes and the corresponding tests.

After the tuple classes are generated, they may be checked-in into the source control repository. Direct editing of tuple classes is discouraged.

### Concurrency
#### ConcurrentRunner
`ConcurrentRunner` provides an implementation for parallelizing work. It allows submission of callables for execution (in separate threads). It can then optionally block the current thread until the work submitted in separate threads is completed (successfully or not (failed, time-out, etc)). `ConcurrentRunner` knows how to manage the thread pool: by default, it destroys threads after all callables are completed, but they can be set for thread re-use, if necessary.

The API is simple:
`ConcurrentRunner.run()` submits callables for execution is separate threads and returns a collection of FutureResult(s).

`ConcurrentRunner.collect()` blocks the thread until all callables are completed (either successfully or not).

`FutureResult` can be either success or failure. Success allows to retrieve the value returned by a callable. If callable failed, FutureFailure contains the throwable which aborted the execution. If not all threads are completed prior to the timeout (the default is 60 seconds but can be overwritten), a warning is logged.

Sample usage:
```
var doWork = \id: Integer, delay: long -> {
  Thread.sleep(delay)
  return id
}

fastWork = (1..1000).map(\elm -> \ -> doWork(elm, 100)) // create 1000 threads which sleep for 0.1 second

var runner = new ConcurrentRunner<Integer>()
runner.run(fastWork)
var results = runner.collect()
var resultCount = results.whereTypeIs(gosu.concurrent.result.FutureSuccess).Count
print(resultCount) // prints the count of successful results
```

#### ContextAwareConcurrentRunner
`ContextAwareConcurrentRunner` extends the functionality of `ConcurrentRunner` by providing the provisions to specify a bundle and/or a user which should be used for running callables. Notice that all callables are run in the same bundle and user context. By default, the user context is that of a current user, and the bundle is the "current" bundle, if it is writable, and a new bundle, if it is not.

Most Guidewire implementations will prefer to use ContextAwareConcurrentRunner, since callables typically create new entities or modify them.

### Logging
`Logger` contains an implementation of org.slf4j.Logger and various predefined logging categories.

Sample usage:
```
var logger = Logger.finder.DEV  // get development logger (logs at the trace level)
logger.debug(\ -> "Starting")   // use the method with a block parameter since
								// the logger evaluate the block only if the debug
								// level or above is set (more efficient)

```
Logger is also "decorated" by a block which returns a string which gets prepended to a log message. In the provided default configuration, the log is using a stack trace element decorator which prepends the class name and function name to each log message. It can be customized to include any combination of a package name, class name, function name, file name, and a line number, or an alternative custom log decorator.

In the sample usage below, a DEV category log is instantiated with a log decorator which prepends a package name, class name, function name, file name, and the file line number to each log message:
```
var customLogDecorator = \ -> {
  var stackTraceLine = StackTraceElementEnhancement
        .getWithOffset_ext(3).Decorator_ext
        .withStackTraceFormat(PACKAGE_CLASS_FUNCTION_FILE_LINE)
        .DisplayName
  return stackTraceLine != null ? stackTraceLine + " : " : ""
}

var logger = Logger.finder.DEV.withDecorator(customLogDecorator)
logger.debug(\ -> "Started")
```

### Type System
`TypeSystemUtil` allows reflective construction of objects by their class names.

The example below constructs an instance of a Tuple2 class by passing class name and parameters:
```
var params = { e1, e2 }.toArray()
var className = TypeSystemUtil.getClassNameFromType(Tuple2)
return TypeSystemUtil.getInstanceByClassName(className, params) as Tuple2
```

### Comparators
#### AssumeMatchIfTargetNotSetComparator
`AssumeMatchIfTargetNotSetComparator` is the implementation which bypasses equality checks between a criteria and a target if the target is not set; it simply returns true. However, if the target is set, then the criteria must be equal to the target. Equality is assessed via a collection of functions ranging from a simple `equals()` to more sophisticated `equalsAsCaseInsensitiveString()`, `equalsAsCaseSensitiveString()`, `equalsAsCaseInsensitiveNoWhitespaceString()`, `startsWithAsCaseSensitiveString()`, etc.

Sample usage:
```
var criteria = "a"
var matchAgainst = "Abc"

var result1 = AssumeMatchIfTargetNotSetComparator
	.buildFrom(criteria, matchAgainst).startsWithAsCaseInsensitiveString()
print (result1)  //true

var result2 = AssumeMatchIfTargetNotSetComparator
	.buildFrom(criteria, null).startsWithAsCaseInsensitiveString()
print (result2)  //true

var result3 = AssumeMatchIfTargetNotSetComparator
	.buildFrom(criteria, matchAgainst).equalsAsCaseInsensitiveString()
print (result3)  //false
```

#### Set Comparison
`SetEnhancement` compares `that` to `this` set and returns a result which contains elements which were added, removed, or unchanged as collection properties.

Sample usage:
```
var thisSet = { "D", "B", "C" }.toSet()
var thatSet = { "A", "B", "C", "D" }.toSet()

var result = thatSet.compareTo_Ext(thisSet)
print (result.Added.join(", "))           // A
print (result.Unchanged.join(", "))       // D, B, C
```

### Enhancements
#### Iterable.firstNotNull_ext()
`Iterable.firstNotNull_ext()` iterates over each element of an iterable until it finds a value which is not null. If the iterable contains blocks, evaluates blocks until it finds the one which returns a value which is not null and returns that value.

Sample usage:
```
var result1 = { null, "A", "B" }.firstNotNull_Ext()
print (result1) // A

var a = \ -> null as String
var b = \ -> "B"
var c = \ -> "C"

var result2 = { a, b, c }.firstNotNull_Ext()
print (result2) // B
```

#### java.util.Date Enhancements
`java.util.Date` is enhanced with static functions to calculate duration between two dates, as well as customizable user-friendly formatting, e.g. 1 Day 5 Hours 10 Minutes, etc.

Sample usage:
```
uses java.util.Date

var date1 = gw.api.util.DateUtil.currentDate()
var date2 = date1.addMinutes(65)
print (Date.getDurationAsString_Ext(date1, date2))
// 1 Hour 5 Minutes 0 Seconds 0 Milliseconds 0 Microseconds 0 Nanoseconds
```

### Performance Measurement
#### Stopwatch
`Stopwatch.measureExecutionDuration(runnable(): A)` allows to measure the time it takes it execute runnable and obtain its result. `Stopwatch.measureWarmedExecutionDuration(runnable(): A)` runs runnable X number of times (default is 200) to ensure that the JVM optimizations compiled it to native code and reports the results, including the speedup relative to the very first invocation.

Sample usage:
```
var doWork = \max: int -> {
  var res: int = 0
  (1..max).each(\elt -> {
    res = res + elt
  })
  return res
}

var result = Stopwatch.measureWarmedExecutionDuration(\ -> doWork(10000))
print (result.DurationDisplayValue)
// 0 Days 0 Hours 0 Minutes 0 Seconds 6 Milliseconds 120 Microseconds 0 Nanoseconds
```

#### Performance Capture
In most modern applications, ongoing performance management is of a paramount concern, but the answer is not
as easy as it may seem, especially, if the orchestrated process involves multiple (asynchronous) function calls.

The performance capturing tool allows you to place performance capturing code in some key strategic points, like so:
```
Perf.INSTANCE.measure(businessID, MyWebService, "doProcessRequest", \ -> MyWebService.doProcessRequest()
```
It is similar to a performance profiler provided by Guidewire, but it is different in its intent: profiling tools
are used to troubleshoot problems and in this capacity their impact on performance is a secondary concern.
Performance capturing tools are meant to capture statistics with minimal impact on the system performance and is
therefore useful in Production environments.

For this reason, the performance capturing tool's implementation evaluates the "measured" code paths very quickly and
off-loads the writing of statistics to the separate statistics capturing component. In the included reference
implementation, the performance capturing tool is writing collected performance statistics
to the CSV files. The CSVWriter can be swapped for any other implementation.

The back-pressure is controlled by the size of the performance buffer (implemented as a circular buffer). If the
performance events are coming in at a very high rate, or the buffered results are not processed quickly enough,
the oldest elements are simply dropped. This may be mitigated by increasing the size of the buffer (by default,
it can accommodate up to 1,000 results). The results captured in a buffer are processed by a separate background thread.

#### Tool Usage
```
Perf.INSTANCE.measure(businessID, MyWebService, "doProcessRequest", \ -> MyWebService.doProcessRequest()
```

The `measure` function returns the type returned by the `\ -> MyWebService.doProcessRequest()` block, so it is
very easy to inject this anywhere you call `MyWebService.doProcessRequest()`.

`businessID` is a business identifier used to identify an event, e.g. Quote ID. It is used as an identifier on
which the results of calling `MyWebService.doProcessRequest()` multiple times may be aggregated to calculate the
min, max, average, etc.

`MyWebService` is the class being measured.

`doProcessRequest` is usually the function name being measured, but can be anything, as it is represented by a string.

`\ -> MyWebService.doProcessRequest()` is a block which returns some result. This is the code which is being measured.
The results are reported in milliseconds.

### Stack Trace Element Decorator
`StackTraceElementEnhancement` allows the selection of a stack trace element using the offset relative to some base stack trace frame  and "decorate" it with additional properties, such as package name, class name, function name, etc. It is used in the logger implementation to customize the format of a log entry but can be used generically.

The stack trace element decorator should be used sparingly, as it has a performance penalty. Performance is not an issue in development environments where trace and debug level logging mode are used extensively. In a production setting, a performance penalty is mitigated by logging at a much higher log level (typically info, or error), so calls to the decorator are minimized.

See Logger for usage.

```
var stackTraceLine = java.lang.StackTraceElement
    .getWithOffset_Ext(1).Decorator_Ext
    .withStackTraceFormat(CLASS_FUNCTION)
    .DisplayName

print (stackTraceLine)
```

### Gosu Builder for Google Guava Cache

#### What
This package contains Gosu classes which make the use of Google Guava cache from Gosu simpler
for Gosu developers, as it is using the familiar "builder" interface. In fact, it is a wrapper for
Google Guava cache builder API, with sensible defaults and ability to overwrite cache parameters.

#### Why
Guidewire provides its own implementation of Cache in the `gw.util.concurrent.Cache` package. However,
it does not provide API for defining cache eviction strategies (e.g. expire cache after 15 minutes).

Google Guava cache implementation provides time-based eviction capabilities and therefore is more appropriate
in most cases.

#### How
For most common usage patterns, please see the tests (`gtest/gosu/cache/CacheTest`) and the cache implementation in
`SimpleCacheImpl`. You would likely want to use a singleton pattern. SimpleCacheImpl provides a reference
implementation for the Singleton pattern in Gosu (it relies on the order of static initializers on JVM).

Be careful with other Singleton patterns, such as a final static variable
`
final static var _cache: ICache = new CacheImpl()
`
as it does not work correctly in highly concurrent environments.

#### Usage Example
```
var cache = CacheBuilder
    .newBuilder<Integer, String>()
    .withExpireAfterAccess(15, TimeUnit.MINUTES)
    .withMaxSize(10)
    .withRecordCacheStatistics()
    .withCacheMissHandler(\key: Integer -> handleCacheMiss(key))
    .build()
```

`newBuilder<Integer, String>()`: the cache will have Integer as a key, and String as a value (substitute for correct
types in your use case

`withExpireAfterAccess(15, TimeUnit.MINUTES)`: will expire cache 15 minutes after last access (i.e. will evict
a key-value from the cache). There are other options for eviction strategies, such as withExpireAfterWrite,
withRefreshAfterWrite. For details, please see Google Guava cache documentation:
https://github.com/google/guava/wiki/CachesExplained

`withMaxSize(10)`: the maximum size of cache (i.e. the number of unique keys).

`withRecordCacheStatistics()`: activates the cache statistics which one can query at runtime (e.g. collects
information on cache misses, hits, etc.); if activated, it is available in `Cache.stats()`. Note: this is NOT
activated by default for performance reasons. However, in most Guidewire implementations, performance won't be
a big issue, and this should be activated if you are using cache statistics in your code.

`withCacheMissHandler`: accepts a block which takes the key as a parameter and returns the value to be cached.
It gets called every time the key is not found in cache.

`build()`: returns the instance of Cache.

### ClassLoaderUtil
Contains a variety of functions and properties to troubleshoot class loading on a JVM.

`ClassLoaderUtil.LoadedClassesByClassLoader` returns the list of classes loaded by each class loader.

`ClassLoaderUtil.getClassInterfaces(clz: Class)` returns the list of interfaces for a class.


text:
# Vagrant AWX Lab

A simple lab to spin up a working AWX install.

The lab uses vagrant to spin up a single node k3s and deploys ansible awx.

## Initial setup

What you need to get started!

- [Virtualbox](https://www.virtualbox.org/)
- [Vagrant](http://vagrantup.com)
- [Ansible >=2.10](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html)

## Use

### Starting the environment

```bash
vagrant up
```

### SSH to the k3s node

```bash
vagrant ssh k3s
```

### Checking awx pod status

Start by entering the k3s node via ssh, then

```bash
$ sudo k3s kubectl get pods --namespace awx
NAME                  READY   STATUS    RESTARTS   AGE
awx-postgres-0        1/1     Running   0          12m
awx-b5f6cf4d4-dmbm8   4/4     Running   0          12m
```

### Opening AWX Web interface

To enter the web interface you'll navigate to http://awx.k3s.test, to make this work please enter the following into your /etc/hosts file

```text
<IP_ADDRESS>  awx.k3s.test
```

### Customization

You can use variables found in ansible/host_vars/k3s.yml to easily change the default settings.
It is also possible to change the file ansible/templates/awx.yml.j2 with settings from the [awx-operator](https://github.com/ansible/awx-operator)

## Author

Author: Thorstein B. Nordby

branch_name: refs/heads/main


text:
# Starting Template

Now that we have all the folders made and starting files generated, we can start working on a base template. This template is what we will use on every single future page, so that our entire site looks cohesive and well built.

## Design

Before we can start code, we need to figure out what will be present in every single page on our website. For the purposes on this tutorial, here is what every page in our site will have:

* Navigation bar at the top
* Contents of the page
* Footer at the bottom with links

## Coding the Template

 1. Open ```template.html``` in your text editor (Sublime Text, Notepad++, etc)
 2. Copy this code:
   3. ```
  <!DOCTYPE html>
  <html>
  <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>John Doe Personal Site</title>
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
      <link rel="stylesheet" href="css/portfolio.css">
  </head>
  <body>
      <!-- This is where our page's content will go -->

      <!-- Our Javascript Files -->
      <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
      <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
      <script type="text/javascript" src="js/portfolio.js"></script>
  </body>
  </html>
  ```
   This is the absolute barebone version of our template. What we are doing here is loading the Bootstrap **CSS** and **JS** files as well as our own files from earlier.
 3. The next step is to make add the Navigation bar at the top of the page; this is where Boostrap starts to shine.
 4. Out of the box, Bootstrap comes with a Navigation bar pre configured, we just need to code it to our liking. First go [here to read up](https://getbootstrap.com/components/#navbar) on how the navigation bar works.
 5. Next, write the following before where your content will go:
   6. ```
	<nav class="navbar navbar-default">
		<div class="container-fluid">
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
					<span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
				</button>
				<a class="navbar-brand" href="#">John Doe</a>
			</div>

			<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
				<ul class="nav navbar-nav navbar-right">
					<li><a href="index.html">Home</a></li>
					<li><a href="#">About Me</a></li>
					<li><a href="#">Contact Me</a></li>
				</ul>
			</div>
		</div>
	</nav>
```
  Here we are creating a new navigation bar with three links on the right and our website's name on the left.
 7. Our website should look like this when you try and open it in a web browser:
   ![](../images/navbar.png)
 8. Next we are going to add a placeholder for our content. This can be done by adding the following code after the navigation:
   9. ```
	<div class="container">
		<!-- Page content will eventually go in here -->
	</div>
```
 10. Finally, for the footer, we will put the following code ***inside*** the container ```div``` we added in the last step
   11. ```
		<footer class="footer">
			<p class="text-muted">Copyright 2016, John Doe</p>
		</footer>
```

> #### Success::Our Website So far
>
> ![](../images/footer.png)
> ##### Not super impressive yet, but we are only getting started!


text:
# Cryptopan

[![Build Status](https://travis-ci.org/pwood/cryptopan.svg?branch=master)](https://travis-ci.org/pwood/cryptopan)

This is a ruby implementation of the Crypto-PAn function providing prefix
consistency while anonymising IP addresses. This program is based on the paper
"Prefix-Preserving IP Address Anonymization: Measurement-based
Security Evaluation and a New Cryptography-based Scheme" written by
Jun Xu, Jinliang Fan, Mostafa H. Ammar, and Sue B. Moon.  The detailed
explanation can be found in [Xu2002].

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'cryptopan'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install cryptopan

## Usage

*Note* Currently only supports IPv4 addresses.

```
2.0.0-p598 :001 > key = SecureRandom.random_bytes(32).bytes
 => [27, 8, 236, 31, 47, 181, 230, 41, 198, 24, 254, 3, 151, 151, 200, 75, 255, 197, 170, 3, 235, 236, 200, 41, 12, 10, 206, 127, 203, 162, 176, 206]
2.0.0-p598 :002 > c = CryptoPAn.new(key)
 => #<CryptoPAn:0x0000000349b350 @key="\e\b\xEC\x1F/\xB5\xE6)\xC6\x18\xFE\x03\x97\x97\xC8K", @pad=[214, 202, 47, 81, 14, 48, 182, 196, 30, 19, 88, 145, 215, 2, 249, 52]>
2.0.0-p598 :003 > c.anonymise("<IP_ADDRESS>")
 => "<IP_ADDRESS>"
2.0.0-p598 :004 > c.anonymise("<IP_ADDRESS>")
 => "<IP_ADDRESS>"
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/pwood/cryptopan.

## References

[Xu2002] Jun Xu, Jinliang Fan, Mostafa H. Ammar, and Sue B. Moon,
"Prefix-Preserving IP Address Anonymization: Measurement-based
Security Evaluation and a New Cryptography-based Scheme", in
Proceedings of the IEEE International Conference on Network Protocols,
Paris, 2002.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

## Contributors

- Keiichi SHIMA, (https://github.com/keiichishima) - README.md and some test data shamelessly appropriated.

repository: pwood/cryptopan

repo_name: pwood/cryptopan


text:
---
layout: post
title: 'notes on the four agreements'
date: '2018-03-26T07:04:00-04:00'
tags:
- the four agreements
- colab
- don miguel ruiz
---

back in jnauary, we had a colab staff meeting where the topic of the day was the four agreements. the four agreements are ancient toltec wisdom, distilled into western language. they are:

> 1. **Be Impeccable with your Word**: Speak with integrity. Say only what you mean. Avoid using the Word to speak against yourself or to gossip about others. Use the power of your Word in the direction of truth and love.
>
> 2. **Don’t Take Anything Personally**: Nothing others do is because of you. What others say and do is a projection of their own reality, their own dream. When you are immune to the opinions and actions of others, you won’t be the victim of needless suffering.
>
> 3. **Don’t Make Assumptions**: Find the courage to ask questions and to express what you really want. Communicate with others as clearly as you can to avoid misunderstandings, sadness and drama. With just this one agreement, you can completely transform your life.
>
> 4. **Always Do Your Best**: Your best is going to change from moment to moment; it will be different when you are healthy as opposed to sick. Under any circumstance, simply do your best, and you will avoid self-judgment, self-abuse, and regret.

miguel ruiz says of these words that they are simple to understand and yet it can take a whole lifetime to live them. that resonates with me, for sure.

i could dig into all of these for a long time, but it felt important back in january to write up at least the parts of them that were particularly challenging or resonant with me. it's taken me until late march to make space for this, but here we are! and, as danielle always says, "you are moving at the correct pace".

## don't make assumptions

the language of this agreement is challenging for me. as a story-based strategist, assumptions are one of our key sources of power. so the phrasing of this doesn't exactly work for me, but it's really just a technical detail. i don't actually think the agreement is to not make assumptions; i think what it's actually saying is "make explicit your assumptions and ask direct questions to understand the assumptions of others." finding "the courage to ask questions and to express what you really want" is... difficult to put it lightly.

## always do your best

i love the idea that your best changes from moment to moment. it's so real and yet i have such a hard time living like i understand that. sometimes i have a great day at volleyball. sometimes i don't. but the days that i don't, i create unnecessary suffering for myself when i say (to myself) things like "i'm better than this, i know it!" the truth is that i'm as good as i am on that day. and that day isn't all days.

---

anyway, these are such good, wise words and i really would like to integrate them more into my life. maybe they'll become a part of my rule of life as i have more conversations with angie and casper about the novitiate...

<!-- hyperlink bank -->

<!-- * = asterisk -->
<!-- ' = single quote '-->

**words / writing / post-processing**
483w / 12min / 6min


text:
# kislayphp
kislayphp 0.9  Web Programming Framework
=============================

Thank you for choosing kislayphp - a high-performance component-based PHP framework.

INSTALLATION
------------

Please make sure the release file is unpacked under a Web-accessible
directory. You shall see the following files and directories:

      app/                 App
      system/              framework source files
      www/		           Css,js,images Files
      CHANGELOG            describing changes in every kislayphp release
      LICENSE              license of kislayphp
      README               this file
      UPGRADE              upgrading instructions

REQUIREMENTS
------------

The minimum requirement by kislayphp is that your Web server supports
PHP 5.1.0 or above. kislayphp has been tested with Apache HTTP server
on Windows and Linux operating systems.

Please access the following URL to check if your Web server reaches
the requirements by kislayphp, assuming "kislayphpPath" is where kislayphp is installed:

      http://hostname/kislayphpPath/

WHAT's NEXT
-----------

Please visit the project website for tutorials, class reference
and join discussions with other kislayphp users.

The kislayphp Developer Team
http://www.skelves.com


text:
# Coders' Workshop: February 20, 2019

## Topic: Introduction to Git

## Resources

* [Download Git](https://git-scm.com/downloads)
* [Resources to learn Git](https://try.github.io/)

repository: malignantz/Coders-Workshop

gha_license_id: MIT

repo_name: malignantz/Coders-Workshop


text:
# Shared configuration state

Sometimes is is required to pass configuration values between different application parts
or implement bundles communication. In this cases usually you have to use `ThreadLocal` (direct static fields can't
be used because it will make problems for tests).

!!! attention
    This is edge cases - they are really rare and should be avoided if possible.

Guicey adds shared state support in order to replace all current and future hacks (and
so avoid unexpected side effects for tests).

Shared state is created together with `GuiceBundle` creation and destroyed with application shutdown.
Internally it is implemented as static map with value reference by application instance.

!!! note
    Shared state content is intentionally not logged (there is no report for that) because
    it is an internal state. Don't abuse it! It myst be used only for edge cases.

Guicey use it for storing `Injector` object lookup ([InjectorLookup](guice/injector.md#access-injector) is actually a shortcut).

[SPA](../extras/spa.md) and [GSP](../extras/gsp.md) bundles use it for bundles communication.

## Shared state restrictions

Internally shared state is a `Map<Class, Object>`. Class is used as key because assumed
usage scope is bundle and it will force you to use bundle class as a key. Moreover non string
key reduce dummy errors: typos (internally, values are stored by string class name to unify keys from different class loaders).

Other restrictions:

* State value can be **set just once**! This is simply to avoid hard to track problems with overridden state.
* State value can't be null! Again, to avoid problems with NPE errors.

It is assumed that state will be used not for simple values, but for shared configuration objects.

## Main bundle

It is assumed that there should be no need to access shared state from [main bundle](configuration.md#main-bundle).
So [the only state-related method](configuration.md#hooks-related) actually assumed to be used by [hooks](hooks.md):

```java
static class XHook implements GuiceyConfigurationHook {
    @Override
    void configure(GuiceBundle.Builder builder) {
        builder.withSharedState(state -> {
            state.put(XHook, new SharedObject());
        });
    }
}
```

## Guicey bundle

Shared state is assumed to be used by bundles. Bundle provides special [shortcut methods](configuration.md#guicey-bundle)
for accessing state. It is assumed that state is declared under initialization phase and
could be accessed under both phases.

For usage examples see [bundles section](bundles.md#shared-state).

## Guice modules

Shared state is not intended to be used in guice modules, but it is possible.
To simplify usage there are shortcuts available in [dropwizard aware module](guice/module-autowiring.md#shared-state) base class.

## Static access

If required, shared state could be accessed statically everywhere:

```java
SharedConfigurationState.get(application)
```

Or direct value access:

```java
SharedConfigurationState.lookup(application, XBundle.class)
```

And it is possible to use `Environment` instance for access:

```java
SharedConfigurationState.get(environment)
SharedConfigurationState.lookup(environment, XBundle.class)
```

Special shorcut methods may be used for "get or fail behaviour":

```java
SharedConfigurationState.lookupOrFail(app, XBundle.class,
        "Failed to lookup %s service", XBundle.class.getSimpleName())
```

It will throw IllegalStateException if shared context is not available or no value.
Note that message is formatted with `String.format`.

## Tests

Shared state is referenced by application instance, so there should not be any
problems with tests.

The only possible side effect is when you test many application startup error situations,
when application did not shutdown properly and so some shared contexts may not be removed.
If it (hard to imagine how) will affect your tests, you can forcefully clean all states:

```java
SharedConfigurationState.clear()
```

## Default objects

The following objects are available in shared state just in case:

* Bootstrap
* Environment
* Configuration
* [ConfigurationTree](yaml-values.md)

So any of it could be accessed statically with application or environment instance:

```java
Optional<Bootstrap> bootstrap = SharedConfigurationState
            .lookup(environment, Bootstrap.class);
```

or

```java
Bootstrap bootstrap = SharedConfigurationState
            .lookupOrFail(environment, Bootstrap.class, "No bootstrap available");
```

repository: emre-e/dropwizard-guicey

repo_name: emre-e/dropwizard-guicey


text:
---
layout: project
title:  "FTP Implementation"
bannerDescription: "A client-server Implementation of the File Transfer Protocol closely following RFC-959 and Beej's Guide."
techUsed: C++, GNU Make, TCP/IP sockets, Google Compute Engine
githubRepo: jatin69/ftp
comments: true
priority: 2
date: 2019-04-10
---

# FTP

A client-server Implementation of the File Transfer Protocol closely following [RFC-959](https://tools.ietf.org/html/rfc959) and [Beej's Guide](https://beej.us/guide/bgnet/html/multi/index.html).

## Demo

Screenshots / screencasts coming soon. In the meantime, checkout the [`logs`](logs/).

## Features

- Closely follows the official spec for FTP : `RFC-959`
- Provides basic authentication with multiuser support.
- Supports multiple client connections.
- Handles control connection (`PI`) and data connection (`DTP`) separately.
- Supports switching of data connection port with `PORT` command.
- Works over `localhost`, `local network` and over the `internet`.

## Supported commands

Checkout the list of supported commands in the
github readme.

## How to make

- `git clone` and `cd` in the folder
- make sure you have `make` installed, then run `make -s`
- it will create a bin folder with two executables `client` and `server`

## How to Run

- go to where executables live `cd ./bin`
- `server` needs to be started first. Usage is as follows.
  - `./server` This uses `port=9000` as default.
  - `./server <portNumber>` in case you want to supply custom port number.
- `client` can be started as follows.
  - `./client` This uses `host=localhost` and `port=9000` as defaults.
  - `./client <serverIP> <serverPort>` in case server is on different machine.

## Testing

The code has been tested in `all three cases` mentioned above.
The maximum file size tested is `190 MB` over the internet and `2.5 GB` over `localhost`.
In theory, it should work for even bigger file sizes.
File integrity is intact, no corruption occurs during the transfer.

### Localhost

- Both client and server are on same machine.
- Use `<IP_ADDRESS>` or `localhost` as Server IP

### LAN

- Both system are on Local Network
- use localIPs like `<IP_ADDRESS>`. You must know server's local IP for this.

### Internet

- Both systems want to transfer files over the internet.
- Internet Testing has been done with VM instances for below 2 scenarios.
  - `Scenario 1` : Server and client are both on different VMs. Both have static IP.
  - `scenario 2` : Server is on VM with static IP. Client is my machine (behind a router).
  - VM-1 on Google cloud `ssh jatin@ftp-tester-1` : acts as server
  - VM-2 on Google cloud `ssh jatin@ftp-tester-2` : acts as client
- Ensure that server has `static IP`. The easiest way to know if a machine has a `static internet IP` is :
  - Run the server program on the machine you wish to test for static IP
  - From any other machine `telnet <machineInternetIP> <portOnWhichServerIsRUnning=9000>`
  - To obtain a machine's internet IP, use `curl ifconfig.me`
  - It should ideally establish connection, because FTP is based on the telnet protocol. If however, it says `No route to Host`, then it means the machine is behind a router and NAT is your enemy.
- Things to keep in mind while creating your VMs for testing -
  - First, create some `VM instances` on google cloud. Make sure you have free credits.
  - Server needs to have a static IP. In your project, go to `VPC network` > `External IP addresses` and reserve static IP address for your machines.
  - On google cloud, all ports are blocked by default. But our ftp-server should be allowed to use ports freely. So we have to add two `Firewall rules` to allow `ingress and egress traffic` on `all ports` on `all protocols` accessible by `all IPs` i.e. `<IP_ADDRESS>/0`
  - Setup ssh login. Then login using `ssh <username>@<external-IP>`
  - If you don't want to remember external IP's you can also add custom hostnames and resolve them in your `/etc/hosts` file
  - Then `clone` the project, `make` it, and run
  - To connect to server, client needs to know server's `static internet ip`. That's a pre-requisite.

## General Questions

## How to analyse

- Monitoring system calls with `strace`
  - `strace` will allow you to monitor relevant system calls as they happen.
  - go to where executable live `cd ./bin`
  - `strace -fe trace=process,network,signal ./bin/server 9000`
  - `strace -fe trace=process,network,signal ./bin/client <IP_ADDRESS> 9000`
- Monitoring processes, their children, pid, ppid, pgid with `ps`
  - Use `ps fj` to see the tree format of all the forks, along with their pid's and ppid's.
- Generating logs with `tee`. This is very unpredictable for interactive programs.
  - `make | tee logs/makelog.txt`
  - `./bin/server | tee logs/serverlog.txt`
  - `./bin/client | tee logs/clientlog.txt`
- Hiding all the server logs with output redirection
  - To hide all output from server, send it to the null device
  - `./server &>/dev/null`

## How to Format code

- a `chromium` based, `opinionated` `.clang-format` file is present in project root.
- This has been used for all the formatting in this project.
- Set your IDE format settings to file.
- For VS Code, add these in your `setting.json`
  ```json
  "C_Cpp.clang_format_path": "/usr/bin/clang-format-3.8",
  "C_Cpp.clang_format_style": "file",
  "C_Cpp.clang_format_fallbackStyle": "Chromium",
  ```
- Build your own formatter file [here](https://zed0.co.uk/clang-format-configurator/)
- Know more about unified formatting across IDE's [here](https://xiaoyuliu.github.io/2018/03/30/20180330-clang-format/)

gha_language: CSS


text:
[![Build Status](https://dev.azure.com/chefcorp-partnerengineering/Chef%20Base%20Plans/_apis/build/status/chef-base-plans.musl?branchName=master)](https://dev.azure.com/chefcorp-partnerengineering/Chef%20Base%20Plans/_build/latest?definitionId=172&branchName=master)

# musl

musl is a new standard library to power a new generation of Linux-based devices. musl is lightweight, fast, simple, free, and strives to be correct in the sense of standards-conformance and safety.

## Maintainers

* The Core Planners<EMAIL_ADDRESS>
## Type of Package

Library package

### Use as Dependency

Library packages can be set as runtime or build time dependencies, however they are typically used as buildtime dependencies. See [Defining your dependencies](https://www.habitat.sh/docs/developing-packages/developing-packages/#sts=Define%20Your%20Dependencies) for more information.

To add core/musl as a depdendency, you can add one of the following to your plan file.

##### Buildtime Dependency

> pkg_build_deps=(core/musl)

##### Runtime Depdendency

> pkg_deps=(core/musl)

### Use as Library

#### Installation

To install this plan, you should run the following commands to install it.

`hab pkg install core/musl`

> » Installing core/musl
>
> ☁ Determining latest version of core/musl in the 'stable' channel
>
> ☛ Verifying core/musl/1.1.19/20200306011400
>
> ✓ Installed core/musl/1.1.19/20200306011400
>
> ★ Install of core/musl/1.1.19/20200306011400 complete with 1 new packages installed.

#### Viewing library files

To view the library files you must first search for them with habitat.

`hab pkg path core/musl`

> /hab/pkgs/core/musl/1.1.19/20200306011400

```bash
ls /hab/pkgs/core/musl/1.1.19/20200306011400
```
> bin/
>
> include/
>
> lib/
>
> share/

#### Notes

core/musl does binlink musl-gcc, however this binary can not be tested.

repository: habitat-sh/core-plans

gha_language: Shell

repo_name: habitat-sh/core-plans