text:
---
layout: post
title:  "The Everything Store"
authors: Brad Stone

---

This is a good starting book to get an insight on how Amazon was built by its founding team.

Second innovation

> And just when it had established itself as the Internet’s top retailer and a leading platform on which other sellers could hawk their wares, **Amazon redefined itself yet again as a versatile technology firm that sold the cloud computing infrastructure known as Amazon Web Services**

Patient investors for profits

> it actually lost money in 2012. But Wall Street hardly seems to care. With his consistent proclamations that he is building his company for the long term, Jeff Bezos has earned so much faith from his shareholders that **investors are willing to patiently wait for the day when he decides to slow his expansion and cultivate healthy profits**.

Bezos

> Bezos is a micromanager with a **limitless spring of new ideas**, and he reacts harshly to efforts that don’t meet his rigorous standards.

Conflicting wants from customers

> But at a certain point, these companies get so big that a contradiction in the public’s collective psyche reveals itself. We want things cheap, but we don’t really want anyone undercutting the mom-and-pop store down the street or the locally owned bookstore, whose business has been under assault for decades,

Bezos focus and away from media

> He **rarely speaks at conferences and gives media interviews infrequently**. Even those who admire him and closely follow the Amazon story are apt to mispronounce his surname

No slides for presentations

> Amazon’s internal customs are deeply idiosyncratic. PowerPoint decks or slide presentations are never used in meetings. Instead, **employees are required to write six-page narratives laying out their points in prose, because Bezos believes doing so fosters critical thinking**. For each new product, they craft their documents in the style of a press release. The goal is to frame a proposed initiative **in the way a customer might hear about it for the first time**.

Listening

> He devotes his full attention to the conversation, and, unlike many other CEOs, he **never gives you the sense that he is hurried or distracted** — but he is highly circumspect about deviating from well-established, very abstract talking points.

3 focus: customer, long term and innovation

> “We are genuinely customer-centric, we are genuinely long-term oriented and we genuinely like to invent. Most companies are not those things. They are focused on the competitor, rather than the customer. They want to work on things that will pay dividends in two or three years, and if they don’t work in two or three years they will move on to something else.

Acknowledge that it is complex and not that simple

> The narrative fallacy, Bezos explained, was a term coined by Nassim Nicholas Taleb in his 2007 book The Black Swan to describe how **humans are biologically inclined to turn complex realities into soothing but oversimplified stories**. Taleb argued that the limitations of the human brain resulted in our species’ tendency to squeeze unrelated facts and events into cause-and-effect equations and then convert them into easily understandable narratives. These stories, Taleb wrote, **shield humanity from the true randomness of the world, the chaos of human experience, and, to some extent, the unnerving element of luck that plays into all successes and failures**.

Avoid Narrative Fallacy

> In Taleb’s book—which, incidentally, all Amazon senior executives had to read—the author stated that the way to avoid the narrative fallacy was to **favor experimentation and clinical knowledge over storytelling and memory**. Perhaps a more practical solution, at least for the aspiring author, is to **acknowledge its potential influence and then plunge ahead anyway**.

Hiring from all background

> By design, D. E. Shaw would be a different kind of Wall Street firm. Shaw **recruited not financiers but scientists and mathematicians—big brains with unusual backgrounds, lofty academic credentials, and more than a touch of social cluelessness**. Bob Gelfond, who joined DESCO after the firm moved to a loft on Park Avenue South, says that “David wanted to see the power of technology and computers applied to finance in a scientific way” and that he “looked up to Goldman Sachs and wanted to build an iconic Wall Street firm.”

Studying other businessmen

> Between 1989 and 1990 he spent several months working in his spare time on a startup with a young Merrill Lynch employee named Halsey Minor, who would later go on to start the online news network CNET. Their fledgling venture, aimed at sending a customized newsletter to people over their fax machines, collapsed when Merrill Lynch withdrew the promised funding. But Bezos nevertheless made an impression. Minor remembers that **Bezos had closely studied several wealthy businessmen** and that he particularly admired a man named Frank Meeks, a Virginia entrepreneur who had made a fortune owning Domino’s Pizza franchises. Bezos also revered pioneering computer scientist Alan Kay and often quoted his observation that “point of view is worth 80 IQ points”—a **reminder that looking at things in new ways can enhance one’s understanding**.

Changing quickly

> At DESCO, Bezos displayed many of the idiosyncratic qualities his employees would later observe at Amazon. He was disciplined and precise, constantly recording ideas in a notebook he carried with him, as if they might float out of his mind if he didn’t jot them down. **He quickly abandoned old notions and embraced new ones when better options presented themselves.**

Analytical

> Bezos **thought analytically about everything**, including social situations.

Hiring

> Members of the firm delighted in asking these recruits random questions, such as “How many fax machines are in the United States?” **The intent was to see how candidates tried to solve difficult problems.** After the interviews, everyone who had participated in the hiring process gathered and expressed one of four opinions about each individual: strong no hire; inclined not to hire; inclined to hire; or strong hire. One holdout could sink an applicant.

Working in a company which was using the latest tools

> D. E. Shaw was ideally situated to take advantage of the Internet. Most Shaw employees had, instead of proprietary trading terminals, Sun workstations with Internet access, and they utilized early Internet tools like Gopher, Usenet, e-mail, and Mosaic, one of the first Web browsers. To write documents, they used an academic formatting tool called LaTeX, though Bezos refused to touch the program, claiming it was unnecessarily complicated. D. E. Shaw was also among the very first Wall Street firms to register its URL. Internet records show that Deshaw.com was claimed in 1992.

Internet growth

> Bezos interpolated from this that Web activity overall had gone up that year by a factor of roughly 2,300—a 230,000 percent increase. “Things just don’t grow that fast,” Bezos later said. “It’s highly unusual, and that started me thinking, **What kind of business plan might make sense in the context of that growth?**”

Compulsion for business with growth

> (Bezos also liked to say in speeches during Amazon’s early years that it was the Web’s “**2,300 percent” annual growth rate that jolted him out of complacency**. Which makes for an interesting historical footnote: Amazon began with a math error.) Bezos concluded that a true everything store would be impractical—at least at the beginning. He made a **list of twenty possible product categories, including computer software, office supplies, apparel, and music**. The category that eventually jumped out at him as the best option was books.

Making the jump

> Bezos knew it would never really be his company if he pursued the venture inside D. E. Shaw. Indeed, the firm initially owned all of Juno and FarSight, and Shaw acted as chairman of both. If Bezos wanted to be a true owner and entrepreneur, with significant equity in his creation and the potential to achieve the same kind of financial rewards that businessmen like pizza magnate Frank Meeks did, **he had to leave his lucrative and comfortable home on Wall Street**.

Not having a regret in the future

> That kind of thing just isn’t something you worry about when you’re eighty years old. At the same time, I knew that **I might sincerely regret not having participated in this thing called the Internet that I thought was going to be a revolutionizing event**. When I thought about it that way… it was incredibly easy to make the decision.”

Leaving a cushy job

> Then they drove northwest, Bezos sitting in the passenger seat, **typing revenue projections into an Excel spreadsheet—numbers that would later prove to be radically inaccurate**. They tried to check into a Motel 6 in Shamrock, Texas, but it was booked, so they settled for a road motel called the Rambler. 12 When MacKenzie saw the room, she declined to take off her shoes that night. A day later, they stopped at the Grand Canyon and watched the sunrise. He was thirty, she was twenty-four, and together they were writing an entrepreneurial origin story that would be imprinted on the collective imagination of millions of Internet users and hopeful startup founders.

Humble start

> They were now calling it Amazon.com. The site was primitive, mostly text and somewhat unimpressive.

Initial funding

> It was all done on a threadbare budget. At first Bezos backed the company himself with $10,000 in cash, and over the next sixteen months, he would finance the startup with an additional $84,000 in interest-free loans, according to public documents.

Releasing the beta site

> In the spring of 1995, Bezos and Kaphan sent links to the beta website to a few dozen friends, family members, and former colleagues. The site was bare, crammed with text and tuned to the rudimentary browsers and slowpoke Internet connections of the time. “One million titles, consistently low prices,” that first home page announced in blue underlined text.

First purchase!

> Kaphan invited a former coworker, John Wainwright, to try the service, and Wainwright is credited with making the very first purchase: Fluid Concepts and Creative Analogies, a science book by Douglas Hofstadter. His Amazon account history records the date of that inaugural order as April 3, 1995.

Ring the bell with a purchase!

> Each order during those early months brought a thrill to Amazon’s employees. When someone made a purchase, a bell would ring on Amazon’s computers, and everyone in the office would gather around to see if anyone knew the customer.

Dog fooding initially

> Bezos decided to watch reviews closely for offensive material rather than read everything before it was published. **The early employees and their friends wrote many of the initial reviews themselves.** Kaphan himself took a book off the shelf that was meant for a customer, a Chinese memoir called Bitter Winds: A Memoir of My Years in China’s Gulag. He read it cover to cover and wrote one of the first reviews.

Getting a negative feedback form a customer and taking in the feedback

> Bezos later recalled getting an angry letter from an executive at a book publisher implying that Bezos didn’t understand that his business was to sell books, not trash them. “We saw it very differently,” Bezos said. “When I read that letter, I thought, we don’t make money when we sell things. **We make money when we help customers make purchase decisions**.”

Physical vs online..

> Tom Alberg, a former executive at McCaw Cellular, met Bezos and was dubious because he loved browsing in bookstores. Then a few days later **he failed to find a business book for his son at a local shop**, and he changed his mind and decided to invest.

Hiring smart people

> Bezos felt that hiring only the best and brightest was key to Amazon’s success. For years he **interviewed all potential hires himself** and asked them for their SAT scores. “Every time we hire someone, **he or she should raise the bar for the next hire**, so that the overall talent pool is always improving,” he said, a recurring Jeffism.

Thinking

> He was unusually **confident, more stubborn** than they had originally thought, and he strangely and presumptuously assumed that they would all work tirelessly and perform constant heroics. He seemed to **keep his ambitions and plans very close to the vest**, not revealing much even to Kaphan.

Analytics and stats

> Bezos was also proving himself to be something of a spoilsport. That year the engineers rigged a database command, rwerich, to track the number of daily purchases as well as orders throughout the lifetime of the company. They **obsessively watched those numbers grow**—it was one of their pleasures amid the typically frenetic days. Bezos eventually told them to stop doing it, in part because it was putting too much strain on the servers.

Not celebrating minor wins

> its first five-thousand-dollar-order day and Lovejoy wanted to throw a party, Bezos rejected the idea. **“There are a lot of milestones coming and that’s not the way I want to run things**,” he said.

Working long, hard and smart

> In the old Bellevue house, Bezos had said to Kaphan and Davis, “You can **work long, hard, and smart**, but at Amazon.com **you can pick only two out of three**.” Now the young CEO liked to recite, “You can work long, you can work hard, you can work smart, but at Amazon you **can’t choose two out of three**.”

Energy and enthusiasm

> “I walked into the door and this guy with a **boisterous laugh who was just exuding energy comes bounding down the steps**,” says Doerr, who had backed such winners as Netscape and Intuit. “In that moment, I wanted to be in business with Jeff.”

Better financial terms

> Unlike brick-and-mortar retailers, whose inventories were spread out across hundreds or thousands of stores around the country, Amazon had one website and, at that time, a single warehouse and inventory. **Amazon’s ratio of fixed costs to revenue was considerably more favorable than that of its offline competitors**.

IPO information

> But Bezos, characteristically secretive, divulged only the legal minimum and withheld some data, like what it cost Amazon to attract a new user and how much loyal customers typically spent on the site. **He wanted capital from an IPO but didn’t want to give his rivals a road map to use to follow in his footsteps.**

Using Internet to enhance features

> This was a key part of Amazon’s early strategy: **maximizing the Internet’s ability to provide a superior selection of products** as compared to those available at traditional retail stores.

Amazon brand expansion

> Bezos now felt expansion into new categories was urgent. In customers’ minds, the Amazon brand meant books only. He wanted it to be more malleable, like Richard Branson’s Virgin, which stood for everything from music to airlines to liquor.

Under valued company?

> During that time, no one placed bigger, bolder bets on the Internet than Jeff Bezos. Bezos believed more than anyone that the Web would change the landscape for companies and customers, so he sprinted ahead without the least hesitation. **“I think our company is undervalued” became another oft-repeated Jeffism**. “The world just doesn’t understand what Amazon is going to be.”

Hiring from a complementary industry

> As the company grew, Bezos offered another sign that his ambitions were larger than anyone had suspected. He started hiring more Walmart executives. In early 1998, Amazon pursued one of Rick Dalzell’s former colleagues, a retired Walmart vice president of distribution named Jimmy Wright.

Warehouse designing...

> Wright asked Bezos what products they would be shipping. “He said, ‘I don’t know. Just design something that will handle anything,’ ” Wright recalls. “I’m going, You’re kidding me, right? And he said, ‘No, that is the mission.’ **I had to have a solution to handle everything but an aircraft carrier**.” Wright had never experienced a challenge of that magnitude.

Filling a patent for 1-Click ?!?!

> Critics charged that the idea behind 1-Click was rudimentary and that its approval by the U.S. patent office was a symptom of lazy bureaucracy and a broken patent process. Bezos didn’t altogether disagree—intellectually, **he was an advocate for patent reform—but he was determined to exploit the status quo for any possible advantage**.

Not taking failure personally

> Bezos didn’t take the defeat personally. He later cast the mistake as the first step in a series of important experiments to bring third-party sellers onto Amazon.

Operations

> ‘This is the most critical project in Amazon’s history’ is pretty close to a direct quote.” Ultimately, the project faded amid other, more pressing priorities. It is more evident in the way Amazon operates now that **Bezos became absorbed with the challenge of delivering products immediately after customers placed their orders**.

Bezos and very early Google

> On a Saturday morning, Shriram picked up Bezos and his wife at a local hotel, the Inn at Saratoga, and drove them to his home. Page and Brin met them there for breakfast and demonstrated their modest search engine. Years later, Bezos told journalist Steven Levy that **he was impressed by the Google guys’ “healthy stubbornness” as they explained why they would never put advertisements on their home page.**

Doesn't matter if you didn't know, you willing to learn

> In other words, Miller **knew nothing about toy retailing, but in a pattern that would recur over and over, Bezos didn’t care**. He was looking for versatile managers—he called them “athletes”—who could move fast and get big things done.

Frugality

> With door-desks and minimal subsidies for employee parking, he was constantly **reinforcing the value of frugality**. A coffee stand on the first floor of the Pac Med building handed out loyalty cards so a customer could get a free drink after his or her tenth purchase. Bezos, by now a multimillionaire, often made a deliberate show of getting his card punched or handing his free-drink credit to a colleague waiting in line next to him.

Be humble!

> quarterly earnings reports came out, analysts were usually so upbeat and congratulatory that Amazon executives had to prevent themselves from sounding overly arrogant. **On the tops of their earnings scripts, they wrote in giant letters Humble, humble, humble**. A few times they also added Remember, Meg is listening, a reference to the eBay CEO and a reminder to remain guarded with company information.

An idea generator

> “Most companies have priority lists of forty-five good ideas and triage is easy,” Galli says. “At Amazon there were a hundred and fifty good ideas all the time and Jeff was capable of developing a new one every day.”

Leaning out and organising things after a big growth

> At the same time, rising investor skepticism and the pleadings of nervous senior executives finally convinced Bezos to shift gears. Instead of Get Big Fast, the company adopted a new operating mantra: **Get Our House in Order**. The watchwords were discipline, efficiency, and eliminating waste. The company had exploded from 1,500 employees in 1998 to 7,600 at the beginning of 2000, and now, even Bezos agreed, it needed to take a breath. The rollout of new product categories slowed, and **Amazon shifted its infrastructure to technology based on the free operating system Linux**. It also began a concerted effort to improve efficiency in its far-flung distribution centers. “The company got creative because it had to,” says Warren Jenson.

Risk

> “The most anxiety-inducing thing about it was that the **risk was a function of the perception and not the reality**,” says Russ Grandinetti, Amazon’s treasurer at the time. Which is why Amazon’s damage-control response was unusually

Illogical thinking?

> To Bezos, Suria represented a strain of illogical thinking that had infected the broader market: the notion that the Internet revolution and all of the brash reinvention that accompanied it would just go away. According to colleagues from the time, Bezos frequently invoked Suria’s analyses in meetings. An executive in the finance group used Suria’s name to coin a term for a **significant mathematical error of a million dollars or more**; Bezos loved it and started using it himself. The word was milliravi.

Optimism despite stock price!

> In the span of three weeks in June, it dropped from $57 to $33, shedding almost half its value. Employees started to get nervous. **Bezos scrawled I am not my stock price on the whiteboard in his office and instructed everyone to ignore the mounting pessimism**. “You don’t feel thirty percent smarter when the stock goes up by thirty percent, so when the stock goes down you shouldn’t feel thirty percent dumber,” he said at an all-hands meeting.

Perfection in feedback and customer service

> Bezos didn’t care about that simple calculus. **He hated when customers called at all, seeing it as a defect in the system**, and he believed that **customers should be able to solve their problems themselves with the aid of self-help tools**.

Selling it cheaper... figure out the core of the business

> “There are two kinds of retailers: **there are those folks who work to figure how to charge more, and there are companies that work to figure how to charge less, and we are going to be the second**, full-stop,” he said in that month’s quarterly conference call with analysts, coining a new Jeffism to be repeated over and over ad nauseam for years.

Why lower prices?

> **“You’ve got to decide what you’re great at,”** he told the Amazon executives. Drawing on Collins’s concept of a flywheel, or self-reinforcing loop, Bezos and his lieutenants sketched their own virtuous cycle, which they believed powered their business. It went something like this: Lower prices led to more customer visits. **More customers increased the volume of sales and attracted more commission-paying third-party sellers to the site.**

Jeff, the marketing manager?

> “There can be only one head of marketing at Amazon, and his name is Jeff,” says Diane Lye, a British senior manager who led Amazon’s data-mining department and helped run the advertising tests. Bezos felt that word of mouth could deliver customers to Amazon. He wanted to funnel the saved marketing dollars into improving the customer experience and accelerating the flywheel.

Shopping cost hurdles

> During the 2000 and 2001 holidays, Amazon offered free shipping to customers who placed orders of a hundred dollars or more. The **promotion was expensive but clearly boosted sales**. Customer surveys showed that shipping costs were one of the biggest hurdles to ordering online.

Learning from another industry!

> Then one of his deputies, a finance vice president named Greg Greeley, mentioned how airlines had segmented their customers into two groups—business people and recreational travelers—by reducing ticket prices for those customers who were willing to stay at their destination through a Saturday night. Greeley suggested doing the equivalent at Amazon. They would make the free-shipping offer permanent, but only for customers who were willing to wait a few extra days for their order. Just like the airlines, Amazon would, in effect, **divide its customers into two groups: those whose needs were time sensitive, and everyone else.**

Employees leaving

> Over the next year, Amazon executives quit in droves. They left because their stock had been vested or because they no longer believed in the mission or because their comparatively low salaries and the depressed stock price guaranteed that they were not getting wealthy anytime soon. Some were tired and just wanted a change. Others felt Bezos didn’t listen to them and that he wasn’t about to start. Almost all figured that Amazon’s best days were behind it.

Not taking it personally

> Bezos never despaired over the mass exodus. One of his gifts, his colleagues said, was being able to drive and **motivate his employees without getting overly attached to them personally**. But he did usually make time in his calendar for **a private meeting with exiting executives**.

When computer generated reviews surpassed human editors

> An algorithm called Amabot brought about the downfall of editorial. **Amabot replaced the personable, handcrafted sections of the site with automatically generated recommendations in a standardized layout**. The system handily won a series of tests and demonstrated it could sell as many products as the human editors.

Bezos, an adopted child

> Bezos grew up in a tight-knit family, with two deeply involved and caring parents, Jackie and Mike, and two close younger siblings, Christina and Mark. Seemingly, there was nothing unusual about it. Yet for a brief period early in his life, before this ordinary childhood, Bezos lived alone with his mother and grandparents. And before that, he lived with his mother and his biological father, a man named Ted Jorgensen. Bezos himself told Wired magazine that he remembered when Jackie and Mike, who is technically his adoptive father, explained this situation to him when he was ten. He learned Mike wasn’t his biological father around the same time he learned that he needed glasses. “That made me cry,” he said.

repository: sayanee/books

gha_language: HTML

repo_name: sayanee/books


text:
---
published: true
title: Lightning-fast deployment of .NET Core app over SSH
description: Applying KISS principle in order to deploy .NET Core app over SSH as simple as possible.
layout: post
tags: [dotnet-core, ssh, linux]
comments: true
---

Once in a while, I want to try some idea to implement. Having background by developing mostly in `.NET` stack my choice is obviously `.NET Core`. I always have at hand couple of `Linux` servers: one is in `DigitalOcean`, another one is [MSI Cubi N](https://www.msi.com/Desktop/Cubi-N.html) under my TV set. Hence, my `Linux` horses will run `.NET Core` app.

My yet another brilliant idea is waiting for implementation. Wait a minute! It will not happen without a [continuous integration](https://en.wikipedia.org/wiki/Continuous_integration) server which is triggered by GitHub in order to prepare a release package. And, don't forget about a [continuous delivery](https://en.wikipedia.org/wiki/Continuous_delivery) server, how can we deploy without it? Probably, it is even better to set up [Kubernetes](https://kubernetes.io/) cluster. Right? No way! That's not for me. I would like to have something as simple as possible. [KISS principle](https://en.wikipedia.org/wiki/KISS_principle) after all!

How minimal deployment script will look like? I'm going to deploy to my `MSI Cubi N` that has `<IP_ADDRESS>`. After a couple of evenings googling and debugging the script is ready. It uses [rsync](https://en.wikipedia.org/wiki/Rsync) in order to upload only changed files, [systemd](https://en.wikipedia.org/wiki/Systemd) for running the console app as service and restarting in case of failure.

```bash
#!/bin/bash
ssh<EMAIL_ADDRESS>'bash -s' <<'ENDSSH'
printf "Stopping service...\n"
systemctl stop HelloSshDeploy
printf "Service is "
systemctl is-active HelloSshDeploy
mkdir -p /apps/HelloSshDeploy
ENDSSH
printf "Uploading new version of service...\n"
rsync -v -a ./bin/Release/netcoreapp2.2/ubuntu.16.04-x64/publish/ root@<IP_ADDRESS>:/apps/HelloSshDeploy/
ssh<EMAIL_ADDRESS>'bash -s' <<'ENDSSH'
chmod 777 /apps/HelloSshDeploy/Gaev.Blog.Examples.HelloSshDeploy
if [[ ! -e /etc/systemd/system/HelloSshDeploy.service ]]; then
    printf "Installing service...\n"
    cat > /etc/systemd/system/HelloSshDeploy.service <<'EOF'
    [Unit]
    Description=HelloSshDeploy
    After=network.target

    [Service]
    WorkingDirectory=/apps/HelloSshDeploy
    ExecStart=/apps/HelloSshDeploy/Gaev.Blog.Examples.HelloSshDeploy
    Restart=always
    KillSignal=SIGINT

    [Install]
    WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable HelloSshDeploy
fi
printf "Starting service...\n"
systemctl start HelloSshDeploy
printf "Service is "
systemctl is-active HelloSshDeploy
ENDSSH
```

My `.NET Core` console app is super small. I'm using  `Console.CancelKeyPress` here to respect `Ctrl + C` and `SIGINT` signal which is sent by `Linux` to stop the console app.

```c#
class Program
{
    static async Task Main(string[] args)
    {
        var cancellation = new CancellationTokenSource();
        Console.CancelKeyPress += (_, e) => { e.Cancel = true; cancellation.Cancel(); };
        using (var logger = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File("HelloSshDeploy.log")
            .CreateLogger())
            await RunApplication(logger, cancellation.Token);
    }
    static async Task RunApplication(Logger logger, CancellationToken cancellation)
    {
        logger.Information("Hello World!");
        try
        {
            await Task.Delay(Timeout.Infinite, cancellation);
        }
        catch (TaskCanceledException) { }
        logger.Information("Goodbye World!");
    }
}
```

### Prerequisites for deployment over SSH

* `Linux` machine itself: for instance, you can start from $5/mo machine by [DigitalOcean](https://www.digitalocean.com/);
* [ssh](https://en.wikipedia.org/wiki/Secure_Shell) & [rsync](https://en.wikipedia.org/wiki/Rsync) on your machine must be installed. For `Windows` users, the easiest way is to install `Ubuntu` for `Windows 10` via [Windows Subsystem for Linux](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux);
* password-less `SSH` login must be configured in target `Linux` machine. [ssh-copy-id](https://www.ssh.com/ssh/copy-id) to the rescue;
* [root login over SSH](https://stackoverflow.com/a/18395932/1400547) must be enabled in target `Linux` machine.

Finally, it takes 4 seconds in order to deploy. See the execution result of the following commands:

```bash
./make.sh
./deploy.sh
```

![Deployment over SSH](/img/deploy-over-ssh.png "Deployment over SSH" ){:style="max-width:1827px; width:100%;" class="block-center"}

See source code here [Gaev.Blog.Examples.HelloSshDeploy](https://github.com/gaevoy/Gaev.Blog.Examples/tree/1.8.0/Gaev.Blog.Examples.HelloSshDeploy).

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
[Go back to the main page](../../../README.md)

## Mobile Development (CM3050)

This module aims to give you the fundamental understanding and skills
needed to develop mobile applications. By studying this module, you will
learn the principles of effective mobile user interface design and how
to design and build user interfaces. You will learn about data-driven
mobile applications, and how you can integrate a mobile application to
a data source. You will learn about the mobile development ecosystem
and how you can develop, run and test your applications. You will learn
how to work with various sensors available on mobile devices using
built-in APIs. The style of the modules will be practical, with a focus
on developing functioning applications.

### Topics covered

- The mobile app ecosystem
- Mobile user interface design
- Programming user interfaces
- Advanced user interface elements
- Developing a mobile app project
- Data sources
- Integrating Cloud and web services
- Sensor programming
- Advanced APIs
- Deployment

### Assessment

Coursework only (Type III)

repository: svarlamov/REPL

gha_license_id: MIT

repo_name: svarlamov/REPL


text:
---
layout: post
title: Finding bigrams with NLTK.
tags: [Natural Language Processing, NLTK, Python, Text Processing]
use_math: true
comment: true
---
In one of my previous post we discussed how to [find bi-grams with Perl](http://jaganadhg.freeflux.net/blog/archive/2009/07/13/finding-bigrams-with-t-score-in-perl.html). Here we can see how it can be dome with Python and [NLTK](http://www.nltk.org/). NLTK is a Python based tool kit for Natural Language Programming. A [Nice book is available from O'RIELLY.](http://oreilly.com/catalog/9780596516499/), have look on it.

There is a function available in NLTK called bigrams(). Using this function we can generate bi-grams from text given in any language. Let us see how it can be used in an English text. After that I will show how it can be used to generate bi-grams in Indic Languages.

I Assumes that you have installed NLTK in your system. For installation instructions please visit the [NLTK site](http://www.nltk.org/).

Start Python interpreter. Then type the following commands in the python interpreter.

```python
    >>> from nltk import bigrams
```

Just we are importing bigrams function from NLTK

```python
    >>> a = "Jaganadh is testing this application"
```

Creating a string for generating bi-grams

```python
    >>> tokens = a.split()
```

Converting string in to tokens

```python
    >>> bigrams(tokens)
    [('Jaganadh', 'is'), ('is', 'testing'), ('testing', 'this'), ('this', 'application.')]
    >>>
```

We are passing tokens to the bigrams() function. That is all folks.

When we comes to Indic or other languages it can be done in a tricky way. Because your text will be in Unicode. So we have to use 'codecs' to open and read the Unicode contents.

Below I am giving a code for generating bigrams from a Unicode text with NLTK. Copy and paste the code to your favourite editor and save it as '`mlbigram.py`'.

```python

#!/usr/bin/env python
import codecs
import sys
from nltk import bigrams

def gen_ML_Bigram(text):
        texfbig = codecs.open(text,'r','utf8').read()
        tokens = texfbig.split()
        ml_bigram = bigrams(tokens)
        out = codecs.open("ml_bigram.txt",'w','utf8')
        for ml in ml_bigram:
                out.write(" ".join(ml))
                out.write("\n")

inp = sys.argv[1]

gen_ML_Bigram(inp)

```

Save your Unicode contents in a text file. Run `python mlbigram.py <your_unicode_text>`. After execution the output will be stored in 'ml_bigram.txt'. The code may seem slow even if you run in a small text file, because it may take time to load NLTK.

Happy hacking!!

Migrated from my [old blog jaganadhg.freeflux.net](https://web.archive.org/web/20160323193721/http://jaganadhg.freeflux.net/blog)


text:
# jigoshopAtosPlugin
Wordpress plugin that enable Atos payment for Jigoshop.

Install
-------
Depending on your web server, copy the correct binary files on your server.
If you are on Linux, and want to know if you run 32 or 64 bits, just type:

    getconf LONG_BIT

For these binaries, don't forget to add execution rights.

    chmod +x

Put your params files too on your web server.

To use the credit cards logos given with this plugin, change images path in your param/pathfile.

```
D_LOGO!/wp-content/plugins/jigoshopAtosPlugin/images/!
```

Take a look at the examples atos files provided with this plugin to put the correct values in **YOUR** param files.

**Automatic response**

Create a page that contains shortcode above and fill the automatic_response_url field in admin.

```
[jigoshop_atos_automatic_response]
```
----------

Test mode
---------
Use these values to test your installation.

Credit card success infos

    Credit card n°:<PHONE_NUMBER>497800
    Crypt key: 600
    Expiration date: anything in the future

Credit card failed infos

    Credit cart n°:<PHONE_NUMBER>497800
    Crypt key: 655
    Expiration date: anything in the future

For 3D secure test

    Valid password: 00000000
    Invalid password: anything else

Security
---------
For security purpose, the param files **must** be located somewhere outside the webroot of your site.
Example: if your wordpress installation is something like
```
/var/www/wordpress
```
Then your param files should be located in:
```
/var/atos/param/
```

repository: chtipepere/jigoshopAtosPlugin

repo_name: chtipepere/jigoshopAtosPlugin


text:
# Buildionaire
## Overview
Buildionaire is a Gamification Platform where code quality matters.
Buildionaire monitors build servers, collects application builds metrics and scores each Build.

Let the games begin.

## Getting Started
You need to setup the Buildionaire Database and TFS connections. This can be done on the web.config file. For the database edit the connection string. To configure the TFS connection edit the following keys of appSettings:

```

    <add key="SourceControlEndpoint" value="http://MYTFSENDPOINT" />

    <add key="SourceControlUserName" value="" />

    <add key="SourceControlUserPassword" value="" />

    <add key="SourceControlDomain" value="MY SOURCECONTROL DOMAIN" />

```

## Credits

Buildionaire is built using the following great open source projects:

- [ASP.NET Web API](https://aspnetwebstack.codeplex.com/)
- [Hangfire](https://github.com/HangfireIO/Hangfire)
- [Json.Net](http://james.newtonking.com/json)
- [SharpRepository](https://github.com/SharpRepository/SharpRepository)
- [Katana](https://katanaproject.codeplex.com/)

## Development
1. Fork it
2. Create your feature branch: `git checkout -b my-new-feature`
3.  Push to the branch: `git push origin my-new-feature`
5. Submit a pull request!

repository: fjsnogueira/Buildionaire

repo_name: fjsnogueira/Buildionaire


text:
# **DotaComp**  [![Codacy Badge](https://api.codacy.com/project/badge/Grade/1096164bcdc84c4ea3b9dcfc7fba86df)](https://www.codacy.com/app/festrs/DotaComp?utm_source=github.com&utm_medium=referral&utm_content=festrs/DotaComp&utm_campaign=Badge_Grade) [![Build Status](https://travis-ci.org/festrs/DotaComp.svg?branch=master)](https://travis-ci.org/festrs/DotaComp)

# Body

As a fan of the game (Dota 2) I created this project to follow and keep connected to the Dota2 tournaments. The main source is the oficial [Stream api](https://wiki.teamfortress.com/wiki/WebAPI), starting from that I created a [web server](http://watcherd2.herokuapp.com/livegames) to manage the requests and included that [upcoming games](http://watcherd2.herokuapp.com/upcoming) and the done games, not present in the Stream api yet.
The goal of provide an app for a quick look of the games on going of dota 2.

This project use Carthage for manage the dependencies.

If you wanna contribute fell free to concat and fork the project

# Autor

Felipe Pereira [festrs](https://github.com/festrs)

# License

**DotaComp** is available under the MIT license. See the LICENSE file for more info.

repository: serhii-londar/DotaComp

repo_name: serhii-londar/DotaComp


text:
# touch

Note that when PHP is called by f.e. apache or nginx instead of directly from the command line, touch() will not prefix the location of the invoking script, so the supplied filename must contain an absolute path.

With script started from /home/user/www, this will not touch "/home/user/www/somefile":

```
<?php
    touch( 'somefile' );
?>
```

But this will:

```
<?php
    touch( __DIR__ . '/somefile' );
?>
```

---

I've been trying to set a filemtime into the future with touch() on PHP5.

It seems touch $time has a future limit around 1000000 seconds (11 days or so). Beyond this point it reverts to a previous $time.

It doesn't make much sense but I could save you hours of time.

$time = time()+1500000;
touch($cachedfile,$time);

---

[Official documentation page](https://www.php.net/manual/en/function.touch.php)

**[To root](/README.md)**


text:
VANILLA PHP MVC

## [Veja em Português](README.PTBR.md)

---

# DIRECTORY STRUCTURE
```
├───app
│   ├───controllers      contains Web controller classes
│   ├───db               contains database class
│   ├───http             contains Web manager classes
│   ├───manager          contains abstracts classes for Controllers, Models, etc.
│   ├───models           contains model classes
│   ├───script           contains scripts to configure your development environment
│   └───widgets          contains widgets do be used on views
├───config               contains application configurations
├───src
│   ├───assets           contains Web resources
│   └───views            contains view files for the Web application
└───tests                contains tests for the basic application
```

This repository has two Models:
- `User`
- `Debt`

This repository has three Controllers:
- `SiteController` main controller that displays the `home page` and `profile page`.
- `DebtController` controller that manages the `Debt` Model.
- `AuthController` controller responsible for `Login` and `Logout`.

## Usage

---

### Models

- If you want to create more `Models` just create a new class that extends `app\manager\Model` and define the properties inside the body of the class along with their respective `Get's` and `Set's`.
- To assign values to all properties at once use `$yourModel->load(array $content)`, recommended to do this in controllers to be more practical.
  - Example:
    ```php
    public static function actionSave() {
        /** @var app\http\Request $request */
        $request = self::getRequest();

        $model = new ExampleModel();

        if($request->isPost()) {
            $model->load($request->post());
            $new = $model->isNewRecord();
            if($model->save()) {
                if($new) {
                    self::setFlash('success', 'Created successful!');
                } else {
                    self::setFlash('success', 'Updated successful!');
                }

                self::redirect('/example/index');
            }
        }

        return self::render('form', [
            'model' => $model
        ]);
    }
    ```
- Override the `validate()` function to create the model validation that is performed in `save()`. For each error found use `setError('key', 'value')` to log it. The error will appear on the user's screen in the output of the `app\widgets\Alert::run()` widget.

### Controllers

- If you want to create more `Controllers` just create a new class that extends `app\manager\Controller` and create their actions inside the body of the class. It is **important** that all routes start with `action` and be `static`! Example: `public static function actionIndex()`

- To render a page use inside the controller: `self::render('page');` without `.php`
  - The files are rendered from the `src/views` directory and the folder where `page.php` is located has the **same** controller name using a dash (`-`) between the words.
    - Example: if the controller name is `HomePageController` the folder name will be `home-page`.
- To pass parameters to the rendered page pass as second parameter.
  - Example:
    ```php
      public static function actionIndex() {
          return self::render('home', [
              'title' => 'Home Page'
          ]);
      }
    ```
- To render another page already inside a page use the `app\manager\View` class for this.
  - Example:
    ```php
    /** filename without .php */
    <?= View::render('folder', 'file') ?>
                    or
    <?php echo View::render('folder', 'file') ?>
    ```
  - Important to remember that all pages are rendered from `src/views`, so if `'folder'` and `'file'` were passed as parameters, it is understood that the file to be rendered is located at: `src /views/folder/file.php`.
- To redirect the user to a new page use in the controller: `self::redirect('/new/page')`.
- To display a feedback message to the user use in the controller: `self::setFlash('type', 'message')`.
  - Available types: `danger`, `success`, `info` and `warning`.
  - See above how to use it.
  - Use `app\widgets\Alert::run()` to display the alert on the page.
  - To register your route so that all users can access it go to `/index.php`:
    - create an instance `$router = new app\http\Router;`
    - use `$router->get()`, `$router->post()`, `$router->put()` or `$router->delete()` to define the method type.
    -
    - ```php
      $router = new Router();

      // DebtController

      /**
       * - Method POST
       * - Receive param {id}
       * - DebtController and action Delete respectively
       * - Only logged users can access this route
       *
       * @ = logged
       * ? = guest
       *
       * ignore `rules` will set ['@', '?'] as the default value
       */
      $router->post('debt/{id}/delete', 'debt/delete', ['rules' => '@']);
      ```

## Installation

```
0. Recommended use of `XAMPP` or some similar program.
1. Clone this repository and place it in your "htdocs" folder (or where you render your projects).
2. Create a database (preferably in MySQL).
3. Run the script located in `script/database.sql`.
4. Copy the content into `script/httpd-vhost.conf` and place it in your `httpd-vhost.conf` or your VirtualHost configuration file.
5. Restart Apache.
6. Put your database information in `config/main.php`.
7. Run `php composer update` on terminal.
8. Go to `http://mvc.localhost`.
9. Done!
```

## Test

```bash
composer run test
```

## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

## License
[MIT](https://choosealicense.com/licenses/mit/)

branch_name: refs/heads/main


text:
---
feature name: Go Language Bindings
start date: 2020-07-17
rfc pr: (leave this empty)
related issue: <https://github.com/aws/aws-cdk/issues/547>
---

# Summary

This RFC proposes to support Go language bindings for the CDK.

# Motivation

Go has seen a huge rise in popularity in recent years and is the language of choice for many infrastructure tools, particularly in the container
world. It has ranked high in recent years on the StackOverflow Developer Survey, especially for such a young language, and with the continued
popularity of containers and trend towards developers owning their infrastructure, there is a high demand for using Go for infrastructure-as-code
tooling.

# Design Summary

In order to create the jsii Go language binding, the various types defined in the jsii spec need to be translated into equivalent types in Go. The
three main types discussed here are Enums, Interfaces, and Classes.

# Detailed Design

## Enums

The standard way of specifying an enum in Go is with a custom type and constant generator iota, e.g.

```go
type Month int // custom type, like type alias

const (
    Jan Month = iota + 1
    Feb
    Mar
    Apr
    May
    ...
)
// Jan=1, Feb=2, Mar=3 ...
```

Since Enums in the CDK are not always iterative, using a constant generator may not be the best translation. We could instead have string values, with
the name of the constant prefixed with the name of the Typescript enum to avoid potential namespace collisions, e.g.:

```ts
export enum LaunchType {
  /**
   * The service will be launched using the EC2 launch type
   */
  EC2 = 'EC2',

  /**
   * The service will be launched using the FARGATE launch type
   */
  FARGATE = 'FARGATE',

  /**
   * A third option (made up for the sake of the exercise - many enum constants
   * have underscores in their names).
   */
  THIRD_OPTION = 'THIRD_OPTION',
}
```

Go translation:

```go
package launchtype

type LaunchType string

const (
 LaunchType_EC2          LaunchType = "EC2"
 LaunchType_FARGATE      LaunchType = "FARGATE"
 LaunchType_THIRD_OPTION LaunchType = "THIRD_OPTION"
)
```

*_NOTE_*: This would be consistent with how the [aws-sdk-go](https://github.com/aws/aws-sdk-go/blob/master/service/ecs/api.go#L20410-L20416) handles
enums.

### Possible Extensions

We could also add some utility functions to make the API a little neater:

```go
func EC2() LaunchType {
    return LaunchType_EC2
}

func FARGATE() LaunchType {
    return LaunchType_FARGATE
}

func THIRD_OPTION() LaunchType {
    return LauncType_THIRD_OPTION
}

func Values() []LaunchType {
    return []LaunchType{
        LaunchType_EC2,
        LaunchType_FARGATE,
        LaunchType_THIRD_OPTION,
    }
}
```

Encapsulating the enum within a package would then create an intuitive namespacing (Run example in the [Go
playground](https://play.golang.org/p/olztr74OKsk))

```go
fmt.Println(launchtype.EC2()) // => "EC2"
fmt.Println(launchtype.FARGATE()) // => "FARGATE"
fmt.Println(launchtype.THIRD_OPTION()) // => "THIRD_OPTION"
fmt.Println(launchtype.Values()) // => [EC2 FARGATE THIRD_OPTION]
```

## Interfaces

### Go Interfaces

Go Interfaces are named collections of *method signatures*. They can be implemented by other types, including other interfaces. Go interfaces are
implemented *implicitly*, so, e.g., the implements keyword is not needed by the type that is implementing an interface. Interfaces can embed other
interfaces, which effectively allows the embedding interface to “inherit” all the methods defined in the embedded interface. This is the closest to
how typescript interfaces use extends.

Interfaces can be used as fields on structs as way to encapsulate behavior and facilitate testing.

See [optional values and pointer types](#optional-values-and-pointer-types) for more information about the usage of pointer to literals the usage of
related helper functions.

### Typescript Interfaces

Typescript Interfaces are types (similar to type aliases) which have *methods* and *properties*. They can *extend* other interfaces or other
types/classes (whereas a type alias would use a type intersection instead of extends). There are three major differences between type aliases and
interfaces:

1. _Shape rather than type definition_: Define a shape rather than a collection of possible types
2. _Extension type checking_: Extending an interface with any of the properties/methods overridden by the interface that is extending it will cause a
   type error, whereas a type alias will do its best to create an overloaded signature. This is useful when modeling inheritance.
3. _Declaration merging_: Multiple interfaces in the same scope with the same name are merged; multiple type aliases of the same name will throw a
   compile-time error.

Classes that implement an interface do so *explicitly* by using the implements keyword.

In jsii, there are two types of interfaces; *structs* (aka: *datatypes* - immutable pure data objects) and *behavioral interfaces* (named `IXxx`,
where `Xxx` is a resource name). The following describes how to handle each kind.

### JSII Non-Datatype Interfaces (`IResource`)

Typescript interfaces that define method signatures can be translated directly as Go interfaces. Any properties that the interface may contain would
be converted to getters (and setters, as needed).

**Example**:

Typescript interface:

```ts
export interface ISecurityGroup extends IResource, IPeer {
  readonly securityGroupId: string;
  readonly allowAllOutbound: boolean;

  addIngressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): void;
  addEgressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): void;
}
```

Go interface:

```go
type ISecurityGroup interface {
    IResource
    IPeer

    SecurityGroupId() *string
    AllowAllOutbound() *bool
    AddIngressRule(peer: IPeer, connect: *Port, description: *string, remoteRule: *boolean)
    AddEgressRule(peer: IPeer, connect: *Port, description: *string, remoteRule: *boolean)
}

// Concrete implementation for jsii proxy values.
type iSecurityGroup struct {
    IResource
    IPeer
}
```

### JSII Datatype Interfaces (Structs)

In jsii, the InterfaceType has a [datatype field](https://github.com/aws/jsii/blob/master/packages/%40jsii/spec/lib/assembly.ts#L879-L888) attribute
that indicates that the interface only contains readonly properties. While this does corresponds directly to a Go struct, we would likely need to
generate both a Go interface that contains getter methods that correspond to each property as well as a Go struct that implements that interface. This
is in order to support subtyping, as the interface is typically what is passed as an argument into other functions, as well as to ensure forward
compatibility in case the datatype interface eventually extends another. Were it not for these considerations, it would be simpler to simply have a
single Go struct that corresponds to a datatype interface (see last bullet point in Notes/Concerns).

#### Case 1: Typescript struct/datatype interface (no extensions)

In the case of a simple a datatype interface (`HealthCheck`) without extensions, we would generate both a Go struct (`HealthCheck`), which would hold
the properties of the original typescript interface as public members, and a Go interface (`IHealthCheck`) that defines getter methods for each
property that would be implemented by the corresponding struct (jsii datatype properties always are readonly, so there are no setter methods
generated). Since Go does not allow a struct to have exported members with the same name as an interface method, we would have to prefix the interface
methods; the recommendation here is to use a `Get` prefix.

[Example](https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/aws-ecs/lib/container-definition.ts#L596):

```ts
export interface HealthCheck {
  readonly command: string[];
  readonly interval?: cdk.Duration;
  readonly retries?: number;
  readonly startPeriod?: cdk.Duration;
  readonly timeout?: cdk.Duration;
}

function renderHealthCheck(hc: HealthCheck): cfntaskdefinition.HealthCheckProperty {
  return {
    command: getHealthCheckCommand(hc),
    interval: hc.interval != null ? hc.interval.toSeconds() : 30,
    retries: hc.retries !== undefined ? hc.retries : 3,
    startPeriod: hc.startPeriod && hc.startPeriod.toSeconds(),
    timeout: hc.timeout !== undefined ? hc.timeout.toSeconds() : 5,
  };
}
```

Go translation (Run example in the [Go playground](https://play.golang.org/p/o84uoUGORYH)):

```go
package ecs

type IHealthCheck interface{
   GetCommand() *[]*string
   GetInterval() cdk.Duration
   GetRetries() *int
   GetStartPeriod() cdk.Duration
   GetTimeout() cdk.Duration
}

type HealthCheck struct {
    Command     *[]*string
    Interval    cdk.Duration
    Retries     *float64
    StartPeriod cdk.Duration
    Timeout     cdk.Duration
}

// See NOTE below
func (h HealthCheck) GetCommand() *[]*string {
    return append(*[]*string{}, h.Command...)
}

func (h HealthCheck) GetRetries() *float64 {
    return h.Retries
}

func (h HealthCheck) GetInterval() cdk.Duration {
    return h.Interval
}

func (h HealthCheck) GetStartPeriod() cdk.Duration {
    return h.StartPeriod
}

func (h HealthCheck) GetTimeout() cdk.Duration {
    return h.Timeout
}

func renderHealthCheck(hc HealthCheck) CfnTaskDefinition.HealthCheckProperty {
    return CfnTaskDefintion.HealthCheckProperty{
        Command:     hc.GetCommand(),
        Interval:    hc.GetInterval(),
        Retries:     hc.GetRetries(),
        StartPeriod: hc.GetStartPeriod(),
        Timeout:     hc.GetTimeout(),
    }
}
```

**NOTE**: To ensure immutability, getters that return a slice type should return a copy of the slice, since elements could be reordered or replaced

It is worth noting that this is not the idiomatic Go way of accessing struct members; normally, a struct would contain unexported members (e.g.
`command`) and implement a Getter method with the uppercase method name (e.g.  `Command()`). However, having unexported members would make
instantiating the struct unreasonably difficult for our use case, as struct members can only be set if they are exported. This does make the syntax
more unwieldy when accessing the members within a function that takes the datatype interface as an argument, but the tradeoff is easier instantiation.

#### Case 2: Extending Typescript datatype interfaces

For Typescript datatype interfaces that extend another datatype interface, the corresponding interfaces and implementing structs would be generated in
go, with the extending interface embedding the extended one, e.g.:

```ts
export interface BaseServiceOptions {
  readonly cluster: ICluster;
  readonly desiredCount?: number;
  readonly serviceName?: string;
  readonly maxHealthyPercent?: number;
  readonly minHealthyPercent?: number;
  readonly healthCheckGracePeriod?: Duration;
  readonly cloudMapOptions?: CloudMapOptions;
  readonly propagateTags?: PropagatedTagSource;
  readonly enableECSManagedTags?: boolean;
  readonly deploymentController?: DeploymentController;
}

export interface BaseServiceProps extends BaseServiceOptions {
  readonly launchType: LaunchType;
}
```

As before, the Go translation would have the getter methods (e.g. readonly cluster) defined in a the generated interface, which correspond to
non-exported struct members in the struct that implements each getter.

The interface generated for the jsii struct being extended would be **embedded** in the extending struct's interface.

```go
package ecs

type IBaseServiceOptions interface {
    GetCluster()                ICluster
    GetDesiredCount()           *int
    GetServiceName()            *string
    GetMaxHealthyPercent()      *int
    GetMinHealthyPercent()      *int
    GetHealthCheckGracePeriod() *Duration
    GetCloudMapOptions()        CloudMapOptions
    GetPropagateTags()          PropagatedTagSource
    GetEnableECSManagedTags()   *bool
    GetDeploymentController()   DeploymentController
}

type IBaseServiceProps interface {
    IBaseServiceOptions  // embeddeded interface
    GetLaunchType()             LaunchType
}
```

However, for the corresponding structs, we can take one of four approaches:

1. Embedding parent structs
1. Flattening struct properties, with interface
1. Providing a struct constructor
1. **Recommended:** Flattening struct properties, without interface

##### Approach 1: embedding parent structs

the first is to embed the extended struct into the extending struct:
(See: [Go playground example](https://play.golang.org/p/Dcww2kYR_Qx)).

```go
type BaseServiceOptions struct {
    Cluster                ICluster
    DesiredCount           *int
    ServiceName            *string
    MaxHealthyPercent      *int
    MinHealthyPercent      *int
    HealthCheckGracePeriod *Duration
    CloudMapOptions        *CloudMapOptions
    PropagateTags          *PropagatedTagSource
    EnableECSManagedTags   *bool
    DeploymentController   *DeploymentController
}
type BaseServiceProps struct {
    BaseServiceOptions  // embedded (anonymous) field
    LaunchType          *LaunchType
}

func (o BaseServiceOptions) Cluster() ICluster { return o.Cluster }
func (o BaseServiceOptions) DesiredCount() *int { return o.DesiredCount }
// ... etc

// BaseServiceProps does not have to re-implement all the methods above
func (p BaseServiceProps) GetLaunchType() *string     { return p.LaunchType }

// example function that takes the embedding interface
func TakesIBaseServiceProps(props IBaseServiceProps) {
    fmt.Printf("Class: %T\nValue:%+[1]v", props)
}
```

This allows the embedding struct (here, `BaseServiceProps`) to "inherit" all the methods defined in the embedded interface
(`IBaseServiceOptions`) automatically.

The advantages of this approach are:

- there would be less boilerplate, since `BaseServiceProps` would not need to re-implement the methods defined in `IBaseServiceOptions`.
- any changes to the extended interface would automatically be inherited by the extending interface.

The main disadvantage of embedding is that instantiating the struct would require knowledge of which properties are inherited from the embedded
struct (at least until [golang/go#9859](https://github.com/golang/go/issues/9859) is accepted and implemented), i.e.:

```go
serviceProps := ecs.BaseServiceProps{
    BaseServiceOptions{
        ServiceName:       jsii.String("myService"),
        MaxHealthyPercent: jsii.Number(100),
        MinHealthyPercent: jsii.Number(50),
    },
    LaunchType: jsii.String("EC2"),
}

ecs.TakesIBaseServiceProps(&serviceProps)
```

##### Approach 2: flattening struct properties

The second approach is not to embed the struct, but **flatten** all the properties inherited from the extended interface.
(See: [Go playground example](https://play.golang.org/p/ioL4XRpjETA)).

```go
type BaseServiceOptions struct {
    Cluster                ICluster
    DesiredCount           *int
    ServiceName            *string
    MaxHealthyPercent      *int
    MinHealthyPercent      *int
    HealthCheckGracePeriod *Duration
    CloudMapOptions        *CloudMapOptions
    PropagateTags          *PropagatedTagSource
    EnableECSManagedTags   *bool
    DeploymentController   *DeploymentController
}

type BaseServiceProps struct {
    // Flattened properties generated from extended interface (i.e. Base ServiceOptions)
    Cluster                ICluster
    DesiredCount           *int
    ServiceName            *string
    MaxHealthyPercent      *int
    MinHealthyPercent      *int
    HealthCheckGracePeriod *Duration
    CloudMapOptions        *CloudMapOptions
    PropagateTags          *PropagatedTagSource
    EnableECSManagedTags   *bool
    DeploymentController   *DeploymentController

    LaunchType          LaunchType
}

func (o BaseServiceOptions) GetServiceName() *string    { return o.ServiceName }
func (o BaseServiceOptions) GetMaxHealthyPercent() *float64 { return o.MaxHealthyPercent }
func (o BaseServiceOptions) GetMinHealthyPercent() *float64 { return o.MinHealthyPercent }

// ... etc

// Generated interface methods inherited from IBaseServiceOptions
func (p BaseServiceProps) GetServiceName() *string    { return p.ServiceName }
func (p BaseServiceProps) GetMaxHealthyPercent() *float64 { return p.MaxHealthyPercent }
func (p BaseServiceProps) GetMinHealthyPercent() *float64 { return p.MinHealthyPercent }
func (p BaseServiceProps) GetLaunchType() *string     { return p.LaunchType }

// ... etc
```

This approach would allow for properties to be passed to a function in a flattened data structure, i.e.

```go
serviceProps := ecs.BaseServiceProps{
    ServiceName:       jsii.String("myService"),
    MaxHealthyPercent: jsii.Number(100),
    MinHealthyPercent: jsii.Number(50),
    LaunchType: jsii.String("EC2"),
}

ecs.TakesIBaseServiceProps(&serviceProps)
```

The disadvantage is that there is much more boilerplate generated to implement the inherited methods, and any change to the inherited interface would
be a breaking change to anything inheriting it. For the latter concern, within the jsii, any generated code would be tied to some version of jsii, so
we would be able to re-generate datatype interfaces that extend other datatypes. For customers creating their own custom constructs, they could
mitigate potential breaking changes in jsii interfaces by either embedding the generated type in their constructs, or creating their own interface
wrappers, e.g.

```go
// custom method that takes wrapped interface
func myCustomMethod(props ICustomServiceProps) {...}

// Option 1 - embed the generated struct
type ICustomServiceProps interface {
    IBaseServiceOptions
}

// Option 2 - wrapper that takes subset of methods defined in IBaseServiceOptions
type ICustomServiceProps interface {
    GetServiceName() *string
    GetMaxHealthyPercent() *float64
    GetMinHealthyPercent() *float64
}
```

##### Approach 3: providing a struct constructor

The last option is effectively a mix of approach 1 and 2: the struct is represented by its interface on any API, and the interface is implemented
by a go struct that embeds parent structs. A constructor is provided to "hide" the embedding layout from the user, while a flattened struct is emitted
to be used as the parameter for the constructor, preserving the naming around the initialization:

```go
package ecs

type IBaseServiceOptions interface {
 GetCluster() ICluster
 GetDesiredCount() *int
 GetServiceName() *string
 GetMaxHealthyPercent() *int
 GetMinHealthyPercent() *int
 GetHealthCheckGracePeriod() *Duration
 GetCloudMapOptions() *CloudMapOptions
 GetPropagateTags() *PropagatedTagSource
 GetEnableECSManagedTags() *bool
 GetDeploymentController() *DeploymentController
}

type BaseServiceOptions struct {
 Cluster                ICluster
 DesiredCount           *int
 ServiceName            *string
 MaxHealthyPercent      *int
 MinHealthyPercent      *int
 HealthCheckGracePeriod *Duration
 CloudMapOptions        *CloudMapOptions
 PropagateTags          *PropagatedTagSource
 EnableECSManagedTags   *bool
 DeploymentController   *DeploymentController
}

// NOTE: Here, baseServiceOptions is almost identical to BaseServiceOptions,
// however we refrain from using the same type in order to avoid the risk of
// mis-use -- users should always invoke NewBaseServiceOptions & use the result.
type baseServiceOptions struct {
 cluster                ICluster
 desiredCount           *int
 serviceName            *string
 maxHealthyPercent      *int
 minHealthyPercent      *int
 healthCheckGracePeriod *Duration
 cloudMapOptions        *CloudMapOptions
 propagateTags          *PropagatedTagSource
 enableECSManagedTags   *bool
 deploymentController   *DeploymentController
}

func (b *baseServiceOptions) GetCluster() ICluster    { return b.cluster }
func (b *baseServiceOptions) GetDesiredCount() *int   { return b.desiredCount }
func (b *baseServiceOptions) GetServiceName() *string { return b.serviceName }
// etc...

func NewBaseServiceOptions(args *BaseServiceOptions) IBaseServiceOptions {
 argsstrct := *args
 return &baseServiceOptions{
  cluster:                argsstrct.Cluster,
  desiredCount:           argsstrct.DesiredCount,
  serviceName:            argsstrct.ServiceName,
  maxHealthyPercent:      argsstrct.MaxHealthyPercent,
  minHealthyPercent:      argsstrct.MinHealthyPercent,
  healthCheckGracePeriod: argsstrct.HealthCheckGracePeriod,
  cloudMapOptions:        argsstrct.CloudMapOptions,
  propagateTags:          argsstrct.PropagateTags,
  enableECSManagedTags:   argsstrct.EnableECSManagedTags,
  deploymentController:   argsstrct.DeploymentController,
 }
}

type IBaseServiceProps interface {
    IBaseServiceOptions  // embeddeded interface
    GetLaunchType()             LaunchType
}

type BaseServiceProps struct {
    // Flattened properties generated from extended interface (i.e. Base ServiceOptions)
    Cluster                ICluster
    DesiredCount           *int
    ServiceName            *string
    MaxHealthyPercent      *int
    MinHealthyPercent      *int
    HealthCheckGracePeriod *Duration
    CloudMapOptions        *CloudMapOptions
    PropagateTags          *PropagatedTagSource
    EnableECSManagedTags   *bool
    DeploymentController   *DeploymentController
    // New properties introduced by BaseServiceProps
    LaunchType             LaunchType
}

type baseServiceProps struct {
    // NOTE: This could be baseServiceOptions, when both structs are defined in
    // the same package. This could offer a marginal performance improvement,
    // and perhaps a slightly more compact memory layout... Opting out of it
    // on the other hand (as is done below), ensures the code path is always the
    // same, regardless of the package layout.
    IBaseServiceOptions // Embedded supertype

    launchType             LaunchType
}

// Don't have to re-implement parent methods, as these are promoted from the
// anonymous embed.
func (b *baseServiceProps) GetLaunchType() { return b.launchType }

func NewBaseServiceProps(args *BaseServiceProps) IBaseServiceProps {
    argsstrct := *args
    return &baseServiceProps{
        IBaseServiceOptions: NewBaseServiceOptions(BaseServiceOptions{
            Cluster:                argsstrct.Cluster,
            DesiredCount:           argsstrct.DesiredCount,
            ServiceName:            argsstrct.ServiceName,
            MaxHealthyPercent:      argsstrct.MaxHealthyPercent,
            MinHealthyPercent:      argsstrct.MinHealthyPercent,
            HealthCheckGracePeriod: argsstrct.HealthCheckGracePeriod,
            CloudMapOptions:        argsstrct.CloudMapOptions,
            PropagateTags:          argsstrct.PropagateTags,
            EnableECSManagedTags:   argsstrct.EnableECSManagedTags,
            DeploymentController:   argsstrct.DeploymentController,
        }),
        launchType: argsstrct.LaunchType,
    }
}
```

The advantage of this approach is that adding a new optional property to a super struct no longer results in a breaking change (the field will be
absent from the subtype until it is re-generated against the new parent), as the embedding technique guarantees methods are promoted from the
supertype. It also guarantees immutability of built instances, as the actual implementation is not exported.

The inconvenient is that this adds relatively heavy boilerplate around use of structs, where the name of the struct is repeated twice in sequence.
This could lead to some user confusion (at least until the suer becomes familiar with this idiom).  All previous approaches attempt to
preserve properties of their TypeScript interface counterparts: immutability (they cannot be modified once created) and subsitutability (a child
struct can be passed where it's parent type is expected).

However, maintaining those properties is unlikely to be necessary in go:

- if structs are always passed by-value, mutations of a struct performed by a function that received it will never be visible to the caller,
  effectively maintaining the immutability from the point of view of the caller
- code that has a child struct instance, and needs to provide this to a call that accepts a super-type of it can copy from it's instance to create
  the super-type instance "manually" (although a helper function can be provided on the child struct to convert it to any of it's parent types to
  reduce the burden on the user)

Consequently, the simplest possible generated code is the following:

```go
package ecs

// Note: no interfaces are defined for these, ever!

type BaseServiceOptions struct {
    Cluster                ICluster
    DesiredCount           *int
    ServiceName            *string
    MaxHealthyPercent      *int
    MinHealthyPercent      *int
    HealthCheckGracePeriod *Duration
    CloudMapOptions        *CloudMapOptions
    PropagateTags          *PropagatedTagSource
    EnableECSManagedTags   *bool
    DeploymentController   *DeploymentController
}

type BaseServiceProps struct {
    // Flattened properties generated from extended interface (i.e. Base ServiceOptions)
    Cluster                ICluster
    DesiredCount           *int
    ServiceName            *string
    MaxHealthyPercent      *int
    MinHealthyPercent      *int
    HealthCheckGracePeriod *Duration
    CloudMapOptions        *CloudMapOptions
    PropagateTags          *PropagatedTagSource
    EnableECSManagedTags   *bool
    DeploymentController   *DeploymentController

    // Fields introduced by BaseServiceProps
    LaunchType          LaunchType
}

// Optional - we can reduce boilerplate for conversion of BaseServiceProps -> BaseServiceOptions:
func (b BaseServiceProps) ToBaseServiceOptions() BaseServiceOptions {
    return BaseServiceOptions{
        Cluster:                b.Cluster,
        DesiredCount:           b.DesiredCount,
        ServiceName:            b.ServiceName,
        MaxHealthyPercent:      b.MaxHealthyPercent,
        MinHealthyPercent:      b.MinHealthyPercent,
        HealthCheckGracePeriod: b.HealthCheckGracePeriod,
        CloudMapOptions:        b.CloudMapOptions,
        PropagateTags:          b.PropagateTags,
        EnableECSManagedTags:   b.EnableECSManagedTags,
        DeploymentController:   b.DeploymentController,
    }
}
```

And the usage would simply be:

```go
// in package ecs, the struct is passed by value:
func TakesBaseServiceProps(props &BaseServiceProps) { /* ... */ }

// User code:
ecs.TakesBaseServiceProps(&ecs.BaseServiceProps{
    ServiceName:       jsii.String("myService"),
    MaxHealthyPercent: jsii.Number(100),
    MinHealthyPercent: jsii.Number(50),
    LaunchType: jsii.String("EC2"),
})
```

Since there are no interfaces to be implemented here, whenever the `@jsii/kernel` decides to pass a struct by-reference, the properties of the object
will be eagerly fetched, and a struct value initialized with those directly. Such values are never proxied away to JavaScript.

### Notes/Concerns

* Like the AWS Go SDK, we can use pointers to primitive types to simulate that fields are optional (i.e. allow null values rather than default "empty"
  values for each type, which are not nullable). However, this might result in a less than ideal developer experience. Another option is to use a
  wrapper type for optional values.
* Generated Go interfaces corresponding to a datatype interface would need a name addendum, e.g. I prefix of Iface suffix, in order to disambiguate
  it from the struct name. This can be confusing (I prefix makes structs and behavioral interfaces similarly named on APIs) or a bit verbose (Iface
  suffix), and it may be worth considering switching the naming (i.e. adding a suffix to the struct instead), as the interface name is what will
  primarily be used by the customer.
* As the `@jsii/kernel` may decide to pass a data type by-reference (and not by-value), either a concrete struct needs to be implemented that does
  the correct call forwarding to `@jsii/kernel` via the runtime library, or the de-serialization procedure must eagerly read all properties from the
  received reference, and intialize a value correctly.
* The alternative to having to implement both a struct and interface is simply translating the datatype interface into a struct. This option has the
  added advantage of having a more streamlined API, rather than having to convert each property into a getter method and having to call those methods
  to access data fields. However, this is not a viable option since in order to pass them as arguments to functions, structs would have to be
  structurally typed (for otherwise, the user code is coupled to the embedding layout of structs, which would make certain backwards-compatible code
  changes in the TypeScript library result in source-breaking changes in go), which is not the case for Go structs. The only way to satisfy the
  structural typing requirements of argments is through interfaces.

## Classes

Typescript takes an object-oriented approach to classes, which includes using polymorphism and subtyping, neither of which are natively supported in
Go, which is not an object-oriented language. While custom structs, which can be used as pointer receivers in function definitions to simulate
methods", can be used to encapsulate object-like behavior in Go, subtyping on these custom structs is not possible. In order to simulate subtyping, we
would need to generate an interface in addition to a concrete struct for each jsii class.

The jsii [ClassType](https://github.com/aws/jsii/blob/master/packages/%40jsii/spec/lib/assembly.ts#L803) provides information on whether a
class is abstract, whether it extends another class, and whether it implements other interfaces. We will discuss each case in turn.

### Case 1: Simple class

Example (Taken from [Typescript handbook](https://www.typescriptlang.org/docs/handbook/classes.html#classes)):
Readonly properties on the class would be translated as exported methods on the interface, implemented by the generated target struct (see section on
datatype interfaces). Instance methods would be declared in the generated interface and implemented by the target struct.

Static methods, on the other hand, would be generated as package-level functions. Since there could be multiple classes within a package, there is not
a good way to namespace a static function in an idiomatic way (e.g. `ClassName.StaticMethod()`); to ensure that static methods maintain the
characteristic of not requiring a concrete receiver while still ensuring some kind of namespacing, the proposal is to add the class name is a prefix
to the top-level function, and separating with a `_` to avoid namespace conflicts. These methods would not be included in the corresponding interface.

Similarly, static properties would be generated as a function at the package level with the same prefixing as with static methods. This way, we can
still delegate calls to the jsii runtime to get the static property value.

```ts
class Greeter {
    readonly greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet(): string {
        return "Hello, " + this.greeting;
    }

    public static foo(): string {
        return "foo";
    }

    public static hello = "hello";
}

let greeter = new Greeter("world");
greeter.greet() // "Hello, world"
```

In Go: ([Go playground example](https://play.golang.org/p/T20xlddRo6A))

```go
package greeter

import "jsii"

// The interface represents the class in the API.
type Greeter interface {
    Greet()    *string
    Greeting() *string
}

// The struct is the concrete implementation for the type. This is a JS object
// proxy.
type greeter struct {
    // We need padding to ensure the struct is not 0-width, otherwise object
    // identity is impossible to verify (if the struct occupies no memory, any
    // object allocated right after an instance of it will share the exact same
    // memory address).
    _ byte // padding
}

func NewGreeter(message *string) Greeter {
    g := &greeter{}
    // Creating the backing instance in the JS process
    jsii.Create(g, "example.Greeter", []interface{}{message})
    return g
}

func (g *greeter) Greeting() (result *string) {
    // Getting the property from the JS process
    jsii.Get(g, "greeting", &result)
    return
}

func (g *greeter) Greet() (result *string) {
    // Invoking the method in the JS process
    jsii.Invoke(g, "greet", []interface{}{}, &result)
    return
}

// static method
func Greeter_Foo() (result *string) {
    jsii.StaticInvoke("example.Greeter", "foo", []interface{}, &result)
    return
}

// static property getter
func Greeter_Hello() *string {
    jsii.StaticGet("example.Greeter", "hello", &result)
    return
}

// static property setter
func Greeter_SetHello(hello *string) {
    jsii.StaticSet("example.Greeter", "hello", hello)
}

// usage
g := greeter.NewGreeter(jsii.String("world"))
fmt.Println(*g.Greet()) // "Hello, world"
fmt.Println(*greeter.GreeterFoo()) // "foo"
```

### Case 2: Extending a Base class

Example (taken from [here](https://www.typescriptlang.org/docs/handbook/classes.html#inheritance)):

```ts
class Animal {
    public readonly name: string;

    constructor(theName: string) { this.name = theName; }

    public move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    public move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

const sam = new Snake("Sammy the Python");

sam.move();
//  Slithering...
// Sammy the Python moved 5m.
```

In Go:
([Go playground example](https://play.golang.org/p/v9gVW0bG2y1))
([Example with embedded field as named property](https://play.golang.org/p/nWfmHhxbs1G))

```go
package animal

import "jsii"

// Base class as interface
type Animal interface {
    Name() *string

    Move(distance *float64)
    isAnimal() // private method saftey check
}

// Base class implementation
type animal struct {
    // So this is not 0-wodth
    _ byte // padding
}

func NewAnimal(name *string) Animal {
    a := &animal{}
    jsii.Create(a, "example.Animal", []interface{}{name})
    return a
}

func (a *animal) Name() (result *string) {
    jsii.Get(a, "name", &result)
    return
}

func (a *animal) Move(distance *float64) {
    jsii.InvokeVoid(a, "move", []interface{}{distance})
}

// Child class
type Snake interface {
  Animal
}

// Snake class would be customer-defined extension of Animal
type snake struct {
    Animal
}

func NewSnake(name *string) Snake {
    a := NewAnimal(name)  // or ExtendAnimal, to avoid introspection for super calls later
    return &snake{a}
}

func (s *snake) Move(distance *float64) {
    fmt.Printf("Slithering...\n")
    // how to look up Animal.Move to delegate to the node runtime? Use JSII-reflect
    s.Animal.Move(distance)
}

// usage:
dumpling := NewAnimal(_jsii_.String("Dumpling the Dog"))
dumpling.Move(_jsii_.Number(5))

sam := NewSnake(_jsii_.String("Sammy the Python"))
sam.Move(10)

// Dumpling the Dog moved 5m.
// Slithering...
// Sammy the Python moved 10m.
```

### Case 3: Class that implements an interface

Using embedding can also be used for a Typescript class that implements an interface:

```ts
// Typescript

export interface ICluster extends IResource {
  readonly clusterName: string;
  readonly clusterArn: string;
  readonly vpc: ec2.IVpc;
  readonly connections: ec2.Connections;
  readonly hasEc2Capacity: boolean;
  readonly defaultCloudMapNamespace?: cloudmap.INamespace;
  readonly autoscalingGroup?: autoscaling.IAutoScalingGroup;
}

export class Cluster extends Resource implements ICluster {
  public static fromClusterAttributes(scope: Construct, id: string, attrs: ClusterAttributes): ICluster {
    return new ImportedCluster(scope, id, attrs);
  }
  public readonly connections: ec2.Connections = new ec2.Connections();
  public readonly vpc: ec2.IVpc;
  public readonly clusterArn: string;
  public readonly clusterName: string;

  private _defaultCloudMapNamespace?: cloudmap.INamespace;
  private _hasEc2Capacity: boolean = false;
  private _autoscalingGroup?: autoscaling.IAutoScalingGroup;
...
}
```

Go struct (derived from TS class) with embedded struct (derived from TS datatype interface):

```go
type ICluster interface {
    IResource

    ClusterName()              *string
    ClusterArn()               *string
    Vpc()                      ec2.IVpc
    Connections()              ec2.Connections
    HasEc2Capacity()           *bool
    DefaultCloudMapNamespace() cloudmap.INamespace
    AutoscalingGroup()         autoscaling.IAutoScalingGroup
}

// Generated interface for Cluster class
type Cluster interface {
    Resource
    ICluster
}

// Generated struct for Cluster class
type cluster struct {
    Resource
    ICluster
}

// Public getter on public property
func (c *cluster) ClusterName() (result *string) {
    jsii.Get(c, "clusterName", &result)
    return
}

// Public getter on private property
func (c *cluster) HasEc2Capacity() (result *bool) {
    jsii.Get(c, "hasEc2Capacity", &result)
    return
}

// ...etc
```

### Case 4: Abstract Classes

These should be able to be handled much in the same way as regular classes, by generating an interface and a struct. The struct generation is still
necessary in this case because method implementations can actually be defined on abstract classes in Typescript.

## Optional Values and Pointer Types

Go doesn't have 'nullable' types. This presents an issue when transpiling various typescript types to Go. Particularly, this is an issue for methods with
optional arguments and interfaces/structs/classes with optional fields. The accepted solution for this in Go, is to use a pointer to the corresponding
type, as pointers can be `nil`. This is used in the aws and github go sdks.

For example:

```typescript
// A JSII struct with an optional readonly property.
export interface OptionalPropertyProps {
  readonly optionalString?: string;
}

// A JSII class with an optional property
export class MyClass {
  public readonly optionalString?: string;

  // constructor function has an optional argument
  public constructor(props: OptionalPropertyProps) {
    this.optionalString = props.optionalString;
  }

  // A method accepting an optional argument and returning a nullable type
  public static someStatic(arg?: string): string? {
    return arg;
  }
}
```

This allows construction like so:

```typescript
const hasString = new MyClass({ optionalString: "I have a string!" });
const notSoMuch = new MyClass({});

console.log(hasString); // =>"I have a string"!
console.log(notSoMuch); // =>undefined
console.log(MyClass.SomeStatic("returns a string")); // =>"returns a string"
console.log(MyClass.SomeStatic()); // =>undefined
```

In order to represent this in Go, we use pointers for all types.

```go
type OptionlPropertyProps struct {
  OptionalString *string
}

type myClassStruct struct {
}

type MyClass Interface {
  OptionalString() *string
}

func NewMyClass(props *OptionalPropertyProps) MyClass {
  // magic jsii client implementation
  return &myClassStruct{}
}

func MyClass_SomeStatic(arg *string) *string {
  // magic jsii client implementation
  return arg
}

// OptionalString is nil
myStruct := OptionalPropertyProps{}
myClass := NewMyClass(&myStruct)
fmt.Println(myClass.OptionalString()) // =>nil
```

All method arguments, return types, behavioral interface fields, and struct fields need to be pointer types. In cases where a type is a Go interface,
ie a jsii generated class or behavioral interface, these are already pointer types, as interfaces dictate method signatures for pointer receivers.

```go
type MyJsiiInterface interface {
  Property() *string
}

type MyJsiiStruct struct {
  IProperty MyJsiiInterface
}
```

### Downsides

This is annoying for users when passing simple values to structs or class methods. This can be mitigated by providing the user with convenience
functions to allow them to continue to define these values inline.

```go
// You have to allocate a variable here in order to address it via `&`
myOptionalString := "string"
myStruct := OptionalPropertyProps{OptionalString: &myOptionalString}

// Now using a helper function with signature string -> *string
myStruct := OptionalPropertyProps{OptionalString: jsii.String("string")}

type SomeStructSlice {
  MySlice: *[]*string
}
// Complex types can be addressed without allocation as they are already pointers
myStruct := SomeStructSlice{MySlice: &[]*string{jsii.String("string")}}
```

Additionally, users will have to always check returned values for nil pointers before dereferencing them.

```go
myStruct := OptionalPropertyProps{}
myClass := NewMyClass(&myStruct)
// I want to access the string value
fmt.Println(*myClass.OptionalString()) // =>Panics!

// Good and safe
if myClass.OptionalString() != nil {
  fmt.Println(*myClass.OptionalString()) // =>Panics!
}
```

Essentially every type that the user passes to or receives from the JSII runtime will have to be a pointer type. We can't only make
optional values pointers because then when a required value became optional in TS, this causes a type change in the generated go code which requires
a code change. This means many non-breaking changes to the TS source would require major version bumps to the generated go modules. The inverse is
also true, an output value, IE a method's return value, cannot be changed from nullable to non-nullable, as this would break consumers.

With these downsides, it still seems like this is the most idiomatic route to take. Go users are familiar with using pointer types in this way from other
popular modules. Additionally, it is the only strategy we can identify that allows us to maintain JSII's versioning compatibility strategy.

### Explored Alternatives

1. Don't use pointers.

When a variable is allocated in Go and not specified, it is immediately initialized as that types zero value. Since the jsii runtime relies on type reflection
in order to serialize and deserialize values between Go and JSON, an unset string is indistinguishable from the user explicitly passing "". In go, you
can leave out struct fields during construction and this may appear to be what the user wants, but they won't actually be setting the unspecified
properties to `nil`.

```go
type OptionlPropertyProps struct {
  OptionalString string
}

myStruct := OptionalPropertyProps{}
fmt.Println(myStruct.OptionalString == "") // =>true
```

2. Wrapper Types

Specifying a wrapper type to express nullability would allow users to explicitly pass `nil` values, but the ergonomics are unwieldy and not what Go users
expect. Additionally the lack of generics means we would have to generate these wrappers for every single generated type for the user to have compile
time type checking.

```go
type OptionalString struct {
  val string
  // bool zero value is true so this is slightly more convenient
  // than `isNil`
  isDefined bool
}

// Some convenience method to make construction easier
func NewOptionalString(val string) OptionalString {
  return OptionalString {
    val: val,
    isDefined: true,
  }
}

type OptionlPropertyProps struct {
  OptionalString OptionalString
}
```

We could define custom serialization and deserialization functionality for passing these optional values over the wire, and provide convenience
functions for construction and dereferencing them, but the main hurdle is that every field, function argument, and return value would have to be
these `OptionalX` types in order to maintain compatibility with JSII versioning. If we only used these types to describe fields we knew were optional,
then when a required struct field changed to optional in typescript, this would change the generated type of the field in Go. This is a backwards
incompatible change in generated code caused by a non-breaking change in the typescript source.

3. Use Pointers Only for Optional Types

This has the same issue as the wrapper types above, changing a property from required to optional would result in that properties type in Go changing,
requiring code changes in the consuming Go application.

## Other considerations

### Primitive types

#### Date

JSII Date would be satisfied by Go's `time.Time` type.

#### String

JSII String would be satisfied by Go's string type.

#### Number

JSII number does not distinguish the difference between integer and float. This either requires jsii for Go to treat all numbers as float64, or define
a new jsii.Number type that "wraps" Go number types into the singular jsii Number type.

Typescript numbers are float64 with a max safe integer size of 2^53 -1. This means that Customers could want to provide a int64 value that would lose
precision.

#### Any

JSII any maps to Go's empty interface type. JSII for Go should replace all jsii any types with interface{}.

### Promise

Promises do not exist natively in Go. JSII functions would be wrapped within a synchronous Go function that wait for the async jsii function to be
complete, and return either the result or an error. This is the same pattern used for Java and .Net jsii bindings.

```go
func JSIIPromise() (resp, error) { /* ... */ }
```

### Packages and submodules

Go package names correspond to a single directory, since their full path is used when imported from other packages. Packages cannot be split across
multiple directories, nor can more than one package be specified in the same directory. NOTE: This does not apply subdirectories.

By convention, package names in go are lower case without underscores or mixed caps. However, many of the module names in the CDK are quite
long/verbose, resulting in names that don’t necessarily fit the succinct style of Go. Currently, we are staying with convention of having a single,
lower-cased package name. However, we may want to consider alternatives such as adding underscores or mixed caps for readability.

### Packaging

Unlike Node, which has NPM, or other languages, there is no central package repository for Go; packages/dependencies are fetched from their source
location, usually on GitHub.

Packages are imported by name (for stdlib packages) or URL (for external packages) using the import keyword, and should be grouped alphabetically
(running gofmt will take care of the alphabetization automatically). As of Go 1.11, the use of go modules is the recommended mechanism for managing
package dependencies. Imports may be aliased to avoid namespace collisions.

# Drawbacks

The programming model for Go differs significantly from that of Typescript. Imposing an object-oriented philosophy on a procedural language may result
in non-idiomatic constructs and APIs in the target language. However, the tradeoff for having CDK constructs available in more languages outweighs
this disadvantage.

# Unresolved questions

- Some details of class inheritence, especially from abstract classes, as they are tricky to model in Go idiomatically.
- Naming of interfaces/structs generated for datatype interfaces and classes
- submodule/package organization within a construct library

# Future Possibilities

This will hopefully further pave the way for more language bindings for the CDK. It would also be interesting to use this as a stepping stone to
create an automated scaffolding for other target language code generation.

repository: aws/aws-cdk-rfcs

gha_language: JavaScript

repo_name: aws/aws-cdk-rfcs


text:
# Open in CMDER

Thanks to ziyasal's [open-in-cmd](https://github.com/lmatt-bit/atom_open_in_cmd).

Thanks to ziyasal's [open-conemu-here](https://github.com/ziyasal/atom-open-conemu-here), I can create "open_in_cmd" package. With "open_in_cmd", User can open a CMD in Atom directly from tree-view & editor.

Note: This package is only enabled on Windows.

##License
MIT License


text:
Revogi Smart Power Strip setup
==============================

Follow these directions to add support for Revogi Smart Power Strip to your SmartThings setup:

1. Setup your Revogi Device in the Revogi App
2. Add the [device script](revogi/revogi-sps.groovy) to your list of [Device Types](https://graph.api.smartthings.com/ide/devices)
2. Add the [device script](revogi/revogi-sps-switch.groovy) to your list of [Device Types](https://graph.api.smartthings.com/ide/devices)
3. Add the [app script](revogi/revogi-connect.groovy) to [your list of SmartApps](https://graph.api.smartthings.com/ide/apps)
4. Using the SmartThings App, go to "My Apps" and run the Revogi Connect app

repository: Tonyowner/smartthings

repo_name: Tonyowner/smartthings


text:
# Tips and tricks

This page contains examples of coding patterns in WDL. Sometimes, the correct WDL way of
doing things is not immediately obvious, and here we provide some worked examples.

## Optional argument with a default

Examine a situation where you want to write a task that takes an
optional argument with a default. For example, the task `hello` takes
an optional username argument. If this is not supplied, the default is `dave.jones`.

```wdl
workflow foo {
    String? username
    hello { input: who = username }
}

task hello {
    String? who
    String who_actual = select_first([who, "dave.jones"])

    command {
        echo "Hello, ${who_actual}"
    }
    output {
        String result = read_string(stdout())
    }
}
```

## Assertions

Currently, WDL does not have a way to throw exceptions, or report errors. A way around
this limitation is to write an `assert` task (suggested by [@mlin](https://github.com/mlin)).

```wdl
task assert {
    Boolean value
    String msg

    command {
        if [ "${value}" == "false" ]; then
            echo $msg
            exit 1
        fi
        exit 0
    }
}
```

You can call it from a workflow when you want to check a condition.

```wdl
workflow foo {
    call assert { input: value= CONDITION_TO_CHECK,
                         msg = ERROR_MESSAGE }
}
```

A method that works directly with the platform error reporting mechanism, suggested by [@jtratner](https://github.com/jtratner), is:

```wdl
workflow show_error {
    call make_error {}
}

task make_error {
    command <<<
        echo '{"error": {"type": "AppError", "message": "x must be at least 2' $(hostname)'"}}' > job_error.json
        exit 1
    >>>
}
```

(including the hostname in the error message allows the message to have the root
job ID, facilitating debugging in complex workflows that may be deeply nested.)

repository: dnanexus/dxWDL

gha_language: Java

repo_name: dnanexus/dxWDL