text:
## Ben Ilegbodu

[@benmvp](https://twitter.com/benmvp) | [benmvp.com](/) | [@HackReactor](https://twitter.com/hackreactor)

December 7, 2017

NOTES:
- My name is Ben Ilegbodu
- It was nearly 2 years ago that we (Eventbrite) embarked on the journey of transitioning our frontend from Backbone to React
- So this talk is about the first part of that transition: convincing everyone that it was a good idea 😀
- Wanna pull back the covers on the rationales we used to make that switch
- You're likely not making the switch, but it should give you great understanding of the pros/cons of React
- Should be helpful as you interview and meet people; can speak deep about React
- Posted link to slides on twitter if you want to follow along

=====

## What this talk is **not** about... 😞

React tutorial

React is better than X

React 💕 fest

NOTES:
- Quick heads up
- The goal of this talk is not to teach you React, so you can go off and build the next app that's gonna change the game
- Even if I wanted to, not possible in an hour
- Also not gonna be framework bashing; talking about how React is better than Angular or Vue or Ember
- Although I am basically saying it's better than Backbone since we switched
- Lastly, not gonna be a React love-fest
- There's no perfect framework; there are trade-offs and I'll try to point them out
- So hopefully if you're still investigating, you'll get a somewhat balanced opinion

/////

## What this talk is about! 😄

Rationales explained in code

Shameless plugs

NOTES:
- Wanna walk through the many reasons why we made the switch
- But not just talk about; I want to demonstrate it w/ a lil' code
- Heads up!
- I've had the opportunity now to speak about a variety of different React topics over the last year
- Covering a lot of topics at a high-level; videos go into detail
- Throughout the talk I'll be giving shameless plugs to those talks
- Forewarning you now, so you can get all of your eye rolls out early

=====

## me.json

{
  "name": "Ben Ilegbodu",
  "priorities": [
    "Jesus", "family", "work"
  ],
  "location": "Pittsburg, CA",
  "work": "Eventbrite",
  "role": "Principal UI Engineer",
  "hobbies": [
    "basketball", "DIY", "movies"
  ]
}

NOTES:
/////

![Eventbrite logo](../../img/eventbrite/wordmark-white.png)

NOTES:
- I'm a Principal Frontend Engineer on our Frontend Platform team
- We don't work on end-user features, but building the frontend platform that other devs build on
  top of
- Two main objectives: frontend infrastructure & component library

/////

![NBA Go CLI](../../img/giphy/nba-go-cli.gif)

[xxhomey19/nba-go](https://github.com/xxhomey19/nba-go)

NOTES:
- I'm a huge basketball fan; love playing & watching
- Got so excited when I was told about the NBA Go CLI
- I use VS Code, which has the terminal pane right at the bottom
- So I could literally be following the game and coding at the same time!

=====

# Why choose React?

NOTES:
- Why choose React?!
- Let's jump right in
- Feel free to ask questions!

/////

[![Tweet from Jordan Harband about how people are hard](../../img/why-react/jordan-harband-people-are-hard.png)](https://twitter.com/ljharb/status/927606717793296384)

NOTES:
- I've been in the industry for about a dozen years now
- And I've come to realize that software development isn't just the code you commit
- There's an equally important human element to it
- Whenever doing something buy-in is just as important as the technical approach
- When difficulties arise, it can be the difference between folks complaining or rallying to find a
  solution, is buy-in

/////

<video data-autoplay loop style="width: 55%">
  <source data-src="../../img/why-react/eventbrite-why-react-doc.m4v" />
</video>

NOTES:
- We had actually tried React a couple of times, ran into issues, and people concluded "React is no
  good"
- So this time, in early 2016, I put together a loooong 19-page document to explain why our Frontend
  Platform team thought we should make the switch
- And as I said "cuz everybody is using it!" wasn't a good enough reason 😉
- The rest of the talk is a talk-friendly distillation of that doc

=====

# CORE MOTIVATIONS

NOTES:
- Split this up into 2 main sections:
- Core Motivations & Additional Motivations
- Core ones will apply to everyone transitioning to React
- Part of the core React lib

=====

# 1. Declarative JSX

![Denzel Washington shouting](../../img/giphy/shouting-denzel-washington.gif)

NOTES:
- The first reason why we wanted to migrate from Backbone to React was its Declarative JSX

/////

## JSX

```js
<div>
  <span className="val">{this.state.value}</span>
  <button onClick={this._handleClick}>+</button>
</div>
```

NOTES:
- Here is some JSX
- Got a `<div>` wrapping a `<span>` display and a `<button>`
- Looks much like HTML and lives right w/in our JavaScript
- Many people didn't like the syntax at first
- But I find it very approachable
- What you may not realize is that this JSX gets converted into JavaScript

/////

## Transpiled JSX

```js
React.createElement(
  'div',
  null,
  React.createElement('span', {className: 'val'}, value),
  React.createElement('button', {onClick: this._handleClick}, '+'),
)
```

([Babel REPL](https://babeljs.io/repl/))

NOTES:
- Here it is transpiled; it's just JavaScript ultimately
- Thanks to the power of build tooling (aka Babel)
- We can write our code in friendly JSX
- But out comes normal JS
- I couldn't imagine building my React components like this

/////

## Collocated markup, logic & data

```js
class Incrementer extends React.Component {
  state = {value: 0}

  _handleClick = () => {
    this.setState((prevState) => ({value: prevState.value + 1}))
  }
  render() {
    return (
      <div>
        <span className="val">{this.state.value}</span>
        <button onClick={this._handleClick}>+</button>
      </div>
    )
  }
}
```

NOTES:
- Here's the JSX in the context of a full component
- We'll go into the details of what the component does in following sections
- With React, a component contains...
  - Markup (`render()`)
  - Data (`this.props` & `this.state`)
  - Logic (`_handleClick`)
- You can also include styling too, but not trying to start a flamewar over css-in-js right now
- So everything is collocated, which was very different than traditional MVC like Backbone

/////

## Traditional MVC equivalent

Handlebars template

```
<div>
  <span class="val">{{value}}</span>
  <button class="js-btn">+</button>
</div>
```

NOTES:
- This is the traditional MVC equivalent in Backbone
- You have a separate file for the template (markup) as well as model & view (logic)
- Nice things: a non-JS expert could come in and make changes in a familiar env
- We used `js-*` prefix in our templates to safely reference them in JavaScript

/////

## Traditional MVC equivalent

Backbone Model & View

```
var IncrementerModel = Backbone.Model.extend({
  defaults: {value: 0}
})
var IncrementerView = Backbone.View.extend({
  template: Handlebars.compile($('#template').html()),
  events: {
    'click .js-btn': 'increment'
  },
  initialize: function() {
    this.listenTo(this.model, 'change', this.render)
  },
  increment: function() {
    this.model.set({value: this.model.get('value') + 1})
  },
  render: function() {
    this.$el.html(this.template(this.model.attributes))
  }
})
```

NOTES:
- Here's the logic
- Focusing on how the view connected with the template
- The idea is that we wanted to have a "separation of concerns"
- But it didn't happen in practice
- But it was really "separation of technologies"
- But when the template changed, you needed to change the view
- When the model changed, you needed to change the template, and so on
- What we found was, as things got complex, hard to know the effects changing one would have on the other

/////

## Logic in the template (markup-driven)

```html
<select>
  {{#each values}}
    {{option_value}}
  {{/each}}
</select>
```

```js
Handlebars.registerHelper('option_value', function() {
  if (shouldShow(this)) {
    return new Handlebars.SafeString(
      '<option value="' + this.value + '">'
        + this.display + '</option>'
    )
  }
})
```

NOTES:
- And doing any kind of fancy logic in the template got really, really messy
- Plus we'd basically have to basically learn a new language
- At Eventbrite we registered Handlebars "helpers" so we could call functions in templates
- _explain what is happening_
- Alternative is to do a whole lot of pre-computation in the view to enable the template to be dumb
- Ya know, handlebars didn't even have `else-if`
- So we'd have a nested `if` w/in an `else`

/////

## Logic in React Component (logic-driven)

```js
class Selector extends React.Component {
  render() {
    let options = this.props.values.map((info) => {
      if (this._shouldShow(info)) {
        return (
          <option key={info.value} value={info.value}>
            {info.display}
          </option>
        )
      }
    })

    return (<select>{options}</select>)
  }
}
```

NOTES:
- But with React, since our markup is in JavaScript, the logic is in JS
- It's a little... different; not initially intuitive at first glance
- You see... _explain how it works_
- Backbone UI is template-driven, markup was primary and sprinkled in a little logic
- But React is reverse: logic is primary w/ JS and sprinkle in some markup
- We have the full use of JavaScript at our dispoable to build up the JSX to return
- Comes in handy

/////

[![Dan Abramov's tweet about no special JSX API for loops/conditionals](../../img/why-react/dan-abramov-jsx-tweet.png)](https://twitter.com/dan_abramov/status/929136989085093890)

(...but [StackOverflow](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx) 😞)

NOTES:
- Dan tweeted this in response to a request to add conditionals and loops into JSX
- I ❤ JavaScript so the more I can do in JS the better
- I'm glad that I don't have to learn a new API to do conditionals/loops in React
- Because it's JS, I can do whatever JS can do
- But for some though, this is a drawback because you _have_ to know JS pretty well to be effective
- Before if you were solid at HTML/CSS, you could throw in some jQuery & do really well
- Looping and conditionals in JSX is not intuitive
- That's a StackOveflow question about loops that has > 300k views and 520 upvotes!
- Now it's JS or bust, which takes some getting used to

/////

## JSX is not HTML!

```
class Label extends React.Component {
  render() {
    return (
      <label className="is-hidden" htmlFor={this.props.inputId}>
        {this.props.children}
      </label>
    )
  }
}
```

React JSX props mirror HTML DOM properties!

```
let labelNode = document.getElementById('label')
labelNode.className = 'is-hidden'
labelNode.htmlFor = this.props.inputId
```

NOTES:
- One other thing, is that although JSX looks like HTML, it's not
- We're creating a custom `<Label>` component
- The `className` & `htmlFor` props should make it clear that this isn't HTML
- React chose to mirror the JS DOM API for its props which are all camelCase
- And that's why its `className` & `htmlFor` instead of the HTML `class` & `for`
- It's also why it's `onClick`, `onChange`, etc.
- React is pretty good at giving great warnings if you forget or mess up
- Especially with React 16

/////

## [React exposed! 😮](http://www.benmvp.com/slides/2017/forwardjs/react-exposed.html)

### ForwardJS Spring 2017

NOTES:
- Shameless plug alert!
- I gave a talk called _React exposed! 😮_ at ForwardJS earlier this year
- I go through several JSX gotchas among other topics

**[ASK ABOUT QUESTIONS]**

=====

2. Component-driven

NOTES:
- The next motivation for the transition was React's component-based architecture

/////

## Everything is a component!

```js
class FormField extends React.Component {
  render() {
    let name = this.props.name
    return (
      <div>
        <Label inputId={name}>{this.props.label}</Label>
        <TextInput
          id={name}
          value={this.props.value}
          onChange={this.props.onChange}
        />
      </div>
    )
  }
}
```

NOTES:
- The sole way you build your UI in React is with "custom" components
- Everything is a component!
- And you build bigger components by combining smaller components w/ markup
- Here we have a FormField component made up of `Label` & `TextInput` components
- It defines 4 `props` (`name`, `label`, `value` & `onChange`), which are how the component is
  configured
- It lays out the `Label` & `TextInput` w/in `<div>` and then passes along those props as configuration

/////

## Everything is a component!

```js
import FormField from './FormField'
class NameForm extends React.Component {
  render() {
    return (
      <form onSubmit={this._handleSubmit}>
        <FormField
          name="fName"
          label="First"
          value={this.props.fields.first}
          onChange={this._handleFieldChange.bind(null, 'fName')}
        />
        <FormField name="lName" ... />
      </form>
    )
  }
}
```

NOTES:
- You include the component by importing it and then using it in `render()` like an HTML tag
- And you configure the props by passing them in via attributes, just like HTML
- Although we're in Javascript using JSX, the HTML-like syntax should feel familiar
- Then you can combine one or more `FormField` components to create a bigger `Form` component
- And keep doing that until you have a full-fledged app

/////

NOTES:
- Component-driven development seems pretty obvious right?
- All the modern libraries/frameworks are component-driven in their own way
- But not Backbone; you simply could not nest Backbone views
- At Eventbrite, we began to use Marionette; an architecture layer on top of Backbone to help w/ more complex UIs
- The version we were using had Layouts, which could contain Views, which could _be_ layouts so
  nesting was possible
- But it was not nearly as effortless as what I just showed w/ React
- Configuring the nested views wasn't simple either
- Way too much code to try to put on a slide
- The problem was that the idea of "components" was an add-on in Backbone/Marionette
- As opposed to being a core feature w/ React

**[ASK ABOUT QUESTIONS]**

=====

3. All JavaScript*

NOTES:
- The 3rd reason was React being exclusively JavaScript based
- I have the asterisk there because obviously we're building web apps so CSS is obviously involved
- But I'm conveniently ignoring that for now 😀

/////

```
class Section extends React.Component {
  render() {
    let headingText = this.props.headingText
    let headingElem

    if (headingText) {
      headingElem = (<h1>{headingText}</h1>)
    }

    return (
      <section className="section">
        {headingElem}
        <p>{this.props.children}</p>
      </section>
    )
  }
}
```

NOTES:
- The nice thing about React, the JavaScript UI lib, tying itself to JavaScript instead of its own API is that as JavaScript evolves, it auto-evolves
- You probably already noticed that we were using `class` keyword to create our React components
- That's ES6 and it's become standard way of creating React components
- I showed `import` w/ `FormField` which is the way of including other components & dependencies (also ES6)
- This `Section` component _[describe what it does]_
- But we can take this class-based component and...

/////

## React + ES.next = ❤

```
const Section = ({headingText, children}) => {
  let headingElem

  if (headingText) {
    headingElem = (<h1>{headingText}</h1>)
  }

  return (
    <section className="section">
      {headingElem}
      <p>{children}</p>
    </section>
  )
}
```

NOTES:
- ...rewrite it using the latest JavaScript
- React components can also be written as functions of their props
- Here we're using an arrow function instead of a standard function
- And we're immediately destructuring the props into `headerText` & `children`
- There's plenty more we can do too with new JS features in React

/////

## Gotta have a (modern) build system

		Babel

		Webpack

		TypeScript

		Rollup

Enable fun features like [tree-shaking](https://webpack.js.org/guides/tree-shaking/) &
[code splitting](https://webpack.js.org/guides/code-splitting/)!

NOTES:
- But all this goodness comes at a cost
- We basically are forced to have a modern build system that we must configure
- And that's where some combo of Babel, Webpack, TypeScript, Rollup, etc. come in
- Frontend Platform team is wrapping up a transition from requirejs to Webpack 3
- Chances are for any modern production apps you already had _some_ sort of build system
- Compile SASS -> CSS, minify & bundle JS, CoffeeScript, etc so not end of the world
- And by paying the upfront cost of the build system, it enables cool features: tree-shaking & code splitting

/////

## Create React App

Create React apps with no build configuration

```
$> npx create-react-app awesome-app

$> cd awesome-app

$> yarn start
```

Configures Babel, Webpack 3, ESLint, and more!

([`npx`](https://github.com/zkat/npx))

NOTES:
- Thankfully though, you don't have to roll your own build system w/ React; at least not initially
- Create React App is a tool that let's you bootstrap an app to start React-ing quickly
- `npx` is a new tool from NPM that allows you to easily/quickly run a global CLI tool...

/////

## [React + ES.next = ♥](http://www.benmvp.com/slides/2017/reactconf/react-esnext.html)

### ReactConf 2017

NOTES:
- Shameless plug alert!
- I gave a talk called _React + ES.next = ♥_ at React Conf back in March
- I go through a handful of ES.next features that go great with React
- So if some of the features I was talking about didn't quite make sense, check it out!

**[ASK ABOUT QUESTIONS]**

=====

4. State-driven

NOTES:
- So far we've talked about (1) JSX, (2) Component-driven & (3) JavaScript
- And so far we've basically been creating static user-interfaces; not user interaction
- To do that the state of the UI has to change over time
- So React components are state-driven instead event-driven, which is more familiar
- This is the hardest thing to wrap your head around if you're new to React
- It's just a different way of building UIs
- But I've found it to be very compelling
- And this is the 4th motivator for the transition away from Backbone to React

/////

## Event-driven jQuery

```html
<div>
  <span class="val">0</span>
  <button class="btnUp">+</button>
</div>
```

```js
$('.btnUp').click(function() {
  var $val = $('.val'),
      currentValue = parseInt($val.html(), 10)

  $val.html(currentValue + 1)
})
```

	0
	<button class="btnUp" style="font-size: 2em" onclick="$('.val').html(+$('.val').html() + 1)">  +  </button>

NOTES:
- Here's some event-driven jQuery code that should be pretty familiar
- Click a button and update `<span>`
- The driver is the event
- This is _really_ easy to follow (imperative), but as app grows in complexity, code turns into crazy spaghetti

/////

## State-driven React

```js
class Incrementer extends React.Component {
  state = {value: 0}

  _handleClick = () => {
    this.setState((prevState) => ({value: prevState.value + 1}))
  }
  render() {
    return (
      <div>
        <span className="val">{this.state.value}</span>
        <button onClick={this._handleClick}>+</button>
      </div>
    )
  }
}
```

NOTES:
_click through code highlights_

- Contrast this with the React code equivalent
- Simplest example of reactivity in React
- Explanation of code...
- It's the handler that does the logic of incrementing the value; separation of concerns!
- And since `value` is already in `state` we don't have to get it from the DOM
- Then calling `setState` causes `render` to be called again
- Click again and the cycle continues
- In the old world `_handleClick` would've directly manipulated the DOM
- But instead we update the state and that will indirectly update the DOM
- Layer of indirection is hard to wrap head around

/////

## React dev work can be boiled down to...

1. `render()` based on `props` & `state`
1. `onEvent` transform data → `setState()`
1. Profit 🎉

NOTES:
- So basically we do work in two main areas:
- 1/ Define what we're going to `render()` based on `props` & `state`
- Can have conditional logic, loops, other sophisticated logic to determine what to render
- Skill: Ability to build layouts with HTML & CSS
- 2/ When events happen, do stuff to transform data to generate new `state` (and `render` again)
- Can also do async transformation by making API calls
- Skill: Ability to transform data efficiently; algorithms are really handy
- And the loop continues

/////

[![Dan Abramov's tweet about how React code remains understandable as app gets more complex](../../img/why-react/dan-abramov-reactive-tweet.png)](https://twitter.com/dan_abramov/status/930380316463726593)

NOTES:
- When folks look at simple examples of "reactivity" in React, they find it to be too verbose; and
  it is
- But with React trades conciseness for predictability
- So you end up spending more time explicitly wiring things up together
- Buuuut... structure of your code can more or less stay the same as complexity grows
- Certainly not the case with jQuery or Backbone; things got cray
- So if an app grew organically, it never was rearchitected
- But prepare yourself for the fact that it'll feel like you're writing "more code" in the beginning

**[ASK ABOUT QUESTIONS]**

=====

5. Sophisticated reconciler

(aka Virtual DOM)

NOTES:
- Let's talk about our 5th reason for the transition:
- The killer feature of React: the Reconciler aka Virtual DOM
- Whenever anyone talks about React it's the cool feature they talk about
- Technically "Virtual DOM" is a misnomer

- So up until this point, it's looked like `render()` was rendering to the DOM
- But it's not...

/////

## React reconciler makes efficient updates easy 💯

```js
class Incrementer extends React.Component {
  state = {value: 0}

  _handleClick = () => {
    this.setState((prevState) => ({value: prevState.value + 1}))
  }
  render() {
    return (
      <div>
        <span className="val">{this.state.value}</span>
        <button onClick={this._handleClick}>+</button>
      </div>
    )
  }
}
```

NOTES:
- Let's take our example from before...
- When we call `setState` React calls `render()` w/ updated state
- So it looks like are re-rendering the `<div>` + children each time
- When we know all we _really_ are updating is _just_ the `innerHTML` of `<span>`
- `render()` is **not** updating DOM, but building up element hierarchy
- Basically a _new_ virtual representation of the DOM
- The reconciler (aka "Virtual DOM") keeps a copy of DOM, compares w/ newly rendered DOM and only
  updates changes
- So we don't have to do the hard work of figuring out how to make the "micro updates"
- We can just write our code the easy way: like it re-renders everything
- And React does the hard work of figuring out micro updates
- This is _really_ _really_ nice

/////

## No reconciler in Backbone 😩

```
var IncrementerView = Backbone.View.extend({
  template: Handlebars.compile($('#template').html()),
  events: {
    'click .js-btn': 'increment'
  },
  initialize: function() {
    this.listenTo(this.model, 'change', this.render)
  },
  increment: function() {
    this.model.set({value: this.model.get('value') + 1})
  },
  render: function() {
    this.$el.html(this.template(this.model.attributes))
  }
})
```

NOTES:
_click through code highlights_

- Here again is the equivalent Backbone code written to be "reactive"
- Probably not how it would normally be written; hard not to after knowing React
- It's pretty straightforward
- Clicking button calls `increment()`
- That updates model & `model` calls `render()`
- But this will actually re-render the whole template blowing away prev DOM
- This is super inefficient especially for bigger chunks of DOM; will get flashes

/////

## Manual update in Backbone 😭

```
var IncrementerView = Backbone.View.extend({
  template: Handlebars.compile($('#template').html()),
  events: {
    'click .js-btn': 'increment'
  },
  increment: function() {
    this.model.set({value: this.model.get('value') + 1})
    $('.val').html(this.model.get('value'))
  },
  render: function() {
    this.$el.html(this.template(this.model.attributes))
  }
})
```

NOTES:
- Instead of listening to model changes and re-rendering
- We _should_ just update the `innerHTML` of the `<span>` ourselves after updating the model
- Full `render` would only be for the initial render
- This is fine for this simple case; very easy to follow
- Nightmare when there are lots of events & states
- Confession: when I _have_ to go back to Backbone I just do it the easy way!
- If you see some UI flashing on Eventbrite, I may be to blame 😂

/////

## [Layperson's guide to React Fiber](http://www.benmvp.com/slides/2017/reactrally/fiber.html)

### React Rally 2017

NOTES:
- Shameless plug alert!
- React team completely rewrote the reconciler and named it Fiber
- I gave a talk called _Layperson's guide to React Fiber_ at React Rally in August
- I talk a little bit about React Fiber and other goodies in React 16

**[ASK ABOUT QUESTIONS]**

=====

# ADDITIONAL MOTIVATIONS

NOTES:
- So those were the Core Motivations
- The ones that will apply to everyone because they are part of the core lib
- Before we jump into Additional motivations, let's pause
- Everyone yell out the most recent JS lib/framework they used (jQuery, React, Vue, etc)

- Now let's jump into some additional motivations
- They applied to us at Eventbrite, but _may_ not apply to your situation

=====

6. Server-side rendering

(aka "Isomorphic React")

NOTES:
- Let's talk about the 6th reason: server-side rendering or "Isomorphic React"
- "Isomorphic JavaScript" or "Isomorphic React" is the idea of using the same templates rendered client-side on initial server render

/////

## Isomorphic React

Performance

SEO

Open Graph

NOTES:
- Three reasons:
- Performance: initial page render
- SEO: google includes page render speed in ranking algorithm
- Open Graph: media previews
- React, unlike other JS frameworks/libraries, is setup to render server-side, as we'll see
- Want to emphasize that I'm talking about the _initial_ render

/////

## React components only define **WHAT** to render!

```js
class Incrementer extends React.Component {
  state = {value: 0}

  _handleClick = () => {
    this.setState((prevState) => ({value: prevState.value + 1}))
  }
  render() {
    return (
      <div>
        <span className="val">{this.state.value}</span>
        <button onClick={this._handleClick}>+</button>
      </div>
    )
  }
}
```

NOTES:
- Let's return to our old friend the `Incrementer` component
- Up until this point I've kind of made it seem like `render()` after reconciliation was rendering to the DOM
- But event that's not true!
- `render()` just informs _what_ elements & child components should be rendered
- It doesn't dictate _how_ they should be rendered

/////

## DOM rendering happens at the root

```js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

const props = window.__SERVER_DATA__ || {}

ReactDOM.hydrate(
  <App {..props} />,
  document.getElementById('root')
)
```

[`ReactDOM.hydrate`](https://reactjs.org/docs/react-dom.html#hydrate) is new in React 16

NOTES:
_click through code highlights_

- Rendering to the DOM typically happens in the entry point of your app
- You'll import from `react-dom` and use it's `hydrate()` function (new to React 16)
- Inserts your app into the DOM location
- And then when your app updates, it produces a new component hierarchy
- `react-dom` is what takes that difference from reconciler and applies it to the DOM
- I bring up that distinction because that separation between building your UI and rendering to DOM...

/////

## Render to string server-side!

```js
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import App from './App'

const props = {
  // Data coalesced from DB / SOA calls
  // Data coalesced from Express GET/POST params
  // Data coalesced from other environment params
}

let markup = ReactDOMServer.renderToString(<App {...props} />)

// return `markup` in HTML response
// assign `props` to `window.__SERVER_DATA__` in HTML response
```

NOTES:
- Allows for us to render the _exact same_ UI server-side to a string!
- Take that string and include it in HTML response
- This is such a huge feature!
- Before this, all UI libraries just assumed the DOM and browser
- So getting your templates to run server-side was at best a pain; at worst in possible
- But now React allows us to do isomorphic javascript

/////

+

([pybars](https://github.com/wbond/pybars3))

NOTES:
- At Eventbrite our backend is in Python/Django
- Currently solved the "dual rendering issue" using a lib called Pybars
- Our JS templates are written in Handlebars & Pybars converts the Handlebars into Python functions
  that return a string
- It's like what happens in the original JS
- Except it's super-duper slow because it was poorly written
- Tried to speed it up, but it was still like 10x slower than rendering in Django/Mako templates

/////

## [Isomorphic React sans Node??](http://www.benmvp.com/slides/2017/render/iso-react.html)

### Render Conf 2017

NOTES:
- Shameless plug alert!
- I gave a talk called _Isomorphic React sans Node??_ at Render Conf earlier this year
- Because backend is Django, makes server-side rendering w/ React a bit tricky
- But we created a small Node service just for rendering components
- Passed it the path to the component and its props and it would give back the HTML
- This talk goes into all of the nitty gritty details plus various gotchas

**[ASK ABOUT QUESTIONS]**

=====

7. Testing

NOTES:
- The same component-based architecture that makes server-side rendering easy, also makes testing React components easy
- Since Backbone views were directly manipulating the DOM, they were hard to test
- Pretty much had to run tests in a browser or headless browser which brought a host of issues
- So the 7th reason for transition is about making testing life far simpler

/////

## Test public API only!

```js
class Incrementer extends React.Component {
  state = {value: 0}

  _handleClick = () => {
    this.setState((prevState) => ({value: prevState.value + 1}), () => {
      this.props.onIncrement(this.state.value)
    })
  }

  render() {
    return (
      <div>
        <span className="val">{this.state.value}</span>
        <button onClick={this._handleClick}>+</button>
      </div>
    )
  }
}
```

```
<Incrementer onIncrement={this._handleIncrement} />
```

NOTES:
- Again we have ol' faithful the `Incrementer` component
- Except this time after we click and update state, we also call `onIncrement` event handler prop
- We pass it `this.state.value` as a parameter
- At the bottom is an example of how you would call it
- We want to test the component's **public** API:
- The markup that it renders and the callback handlers it calls
- That's it! Don't want to test implementation details like `state` changes

/////

## Testing Render

```js
import {shallow} from 'enzyme'

it('renders a `.val`', () => {
  let wrapper = shallow(<Incrementer />)

  expect(wraper.find('.val')).toBePresent()
  expect(wrapper.find('.val')).toHaveText('0')
})
```

[Jest](https://facebook.github.io/jest/) + [Enzyme](http://airbnb.io/enzyme/) +
[`jest-enzyme`](https://yarnpkg.com/en/package/jest-enzyme) = 😍

NOTES:
- We can test `Incrementer` using Jest & Enzyme to test the public API
- Enzyme has a jQuery-like interface for manipulating React components
- All w/o a browser
- "Rendering" is creating an enzyme wrapper
- We use Jest as the test framework & assertion lib; also created by Facebook
- `jest-enzyme` provides additional enzyme-specific assertions to Jest
- Here we're asserting that `Incremener` renders an element with `.val` class
- And that that `.val` element has the text "0" inside of it

/////

## Testing callbacks

```js
import {shallow} from 'enzyme'

it('calls `onIncrement` prop with current value', () => {
  let onIncrement = jest.fn()
  let wrapper = shallow(<Incrementer onIncrement={onIncrement} />)
  let button = wrapper.find('button')

  // simulate clicking twice
  button.simulate('click')
  button.simulate('click')

  expect(onIncrement).toHaveBeenCalledTimes(2)
  expect(onIncrement).toHaveBeenLastCalledWith(2)
})
```

NOTES:
- If you recall, when we click the button we call our `onIncrement` handler
- We want to verify that when we click the button that `onIncrement` gets called w/ the right parameter
- Well with enzyme we can simulate clicking the button w/o running in a browser!
- And with Jest we can provide a mock function using `jest.fn()`
- Then we can assert things on that mock:
- How many times it was called (twice for 2 clicks)
- What arguments it was last called with (2)
- Again: we shouldn't inspect the `state` of the component (which would be 2)
- Instead we assert on the value in the handler (the public API)
- Being able to unit test like this is a game-changer

/////

## Jest Snapshots and Beyond

### React Conf 2017

NOTES:
- I haven't given a talk on React testing, although maybe I should
- But Rogelio (Jest core team) gave a talk at React Conf earlier this year called _Jest Snapshots
  and Beyond_
- And he talks about another fun way to test React components with "snapshots"

**[ASK ABOUT QUESTIONS]**

=====

8. React Native

(...and other renderers)

NOTES:
- Let's jump to the 8th reason for transitioning
- Eventbrite has 4 native apps: 2 on iOS & 2 on Android
- One set for people running events (organizer) / other set for people attending (attendee)
- We don't have any plans to replace our apps with React Native
- But should we need other native apps, being able to use React Native is appealing

/////

![Learn Once, Write Anywhere screenshot from react homepage](../../img/why-react/react-learn-once-write-anywhere.png)

NOTES:
- One of the benefits React mentions on its home page is that you can "Learn Once, Write Anywhere"
- Basically saying that once you learn React and its paradigms, you can build apps for _any_ environment
- Not just the web

/////

## React for the Web

```js
class Incrementer extends React.Component {
  state = {value: 0}

  _handleClick = () => {
    this.setState((prevState) => ({value: prevState.value + 1}))
  }
  render() {
    return (
      <div>
        <span className="val">{this.state.value}</span>
        <button onClick={this._handleClick}>+</button>
      </div>
    )
  }
}
```

NOTES:
- Let's bring back our good friend the `Incrementer` component one more time
- Here's what it looks like if we were writing for React in the web
- We're using HTML elements: `<div>`, `<span>` & `<button>`
- But...

/////

## React Native 😄

```js
import {View, Text, TouchableOpacity} from 'react-native'
class Incrementer extends React.Component {
  state = {value: 0}
  _handlePress = () => {
    this.setState((prevState) => ({value: prevState.value + 1}))
  }
  render() {
    return (
      <View>
        <Text style={...}>{this.state.value}</span>
        <TouchableOpacity onPress={this._handlePress}>+</TouchableOpacity>
      </View>
    )
  }
}
```

NOTES:
- If replaced `<div>`, `<span>` & `<button>` w/ `View`, `Text` & `TouchableOpacity` components from
  `react-native`
- You've got the makings a native app!
- I remember when I went to a React Native workshop and was blown away
- Everything I learned building React web apps, I could leverage in React Native
- Just like w/ the web there are special considerations for native of course
- Layout engine is different
- But there are a bunch more pre-built components
- And React is not just for mobile devices...

/////

## React exists in many environments

  [`ink`](https://github.com/vadimdemedes/ink)
  [`noop-renderer`](https://github.com/facebook/react/blob/master/src/renderers/noop/ReactNoop.js)
  [`rax`](https://github.com/alibaba/rax)
  [`react-art`](https://github.com/reactjs/react-art)
  [`react-blessed`](https://github.com/Yomguithereal/react-blessed)
  [`react-canvas`](https://github.com/Flipboard/react-canvas)
  [_**`react-dom`**_](https://github.com/facebook/react/tree/master/packages/react-dom)
  [`react-fs-renderer`](https://github.com/ericvicenti/react-fs-renderer)
  [`React-Gibbon`](http://techblog.netflix.com/2017/01/crafting-high-performance-tv-user.html)
  [`React-GL`](https://github.com/PixelsCommander/React-GL)
  [`react-hardware`](https://github.com/iamdustan/react-hardware)
  [`react-html-email`](https://github.com/chromakode/react-html-email)
  [`react-konsul`](https://github.com/mohebifar/konsul)
  [_**`react-native`**_](https://github.com/facebook/react-native)
  [`react-pdf`](https://github.com/diegomura/react-pdf)
  [_**`react-sketchapp`**_](https://github.com/airbnb/react-sketchapp)
  [_**`react-test-renderer`**_](https://www.npmjs.com/package/react-test-renderer)
  [`react-three`](https://github.com/Izzimach/react-three)
  [`react-titanium`](https://github.com/yuchi/react-titanium)
  [`react-tvml`](https://github.com/ramitos/react-tvml)
  [_**`react-vr`**_](https://github.com/facebookincubator/react-vr)
  [`react-worker-dom`](https://github.com/web-perf/react-worker-dom)
  [`react-x11`](https://github.com/sidorares/react-x11)
  [`ReactLiberty`](https://github.com/LibertyGlobal/ReactLiberty)

Source: [`awesome-react-renderer`](https://github.com/chentsulin/awesome-react-renderer)

NOTES:
- React is everywhere! Got 24 renderers listed here!
- And the new Fiber architecture should make building new renderers easier
- Remember the Reconciler determines what in the UI should change on re-render
- The renderer actually applies the changes in the environment
- We're pretty excited about `react-sketchapp` from Airbnb
- Just discovered `react-html-email`; need to look into that one!
- These are all links so feel free to check them out!

/////

## React as a Platform

### Chain React 2017

NOTES:
- Also I haven't given a talk about React Native, although I have an idea for one
- But Leland (Airbnb) gave a talk at Chain React earlier this year called _React as a Platform: A
  path towards a truly cross-platform UI_
- And he talks about a path to a world where we can actually write the _same_ code for Web & Native
- Sucky: building the same app for Web & Native would mean lots of code duplication for developer(s)
- Need core set of components (primitives) that exist for every renderer
- Build everything on top of that

**[ASK ABOUT QUESTIONS]**

=====

# 9. Unopinionated

![Lady falls down slipping on bowling lane](../../img/giphy/bowling-lane-fall.gif)

NOTES:
- Honestly this 9th reason can be seen as a pro or con depending on how you look at it
- React is pretty unopinionated on how your apps should be built

/////

## Decisions decisions...

Tooling

bundlers

task runners

static analyzers

Styling

global css

css modules

inline styles

css-in-js 🔥

Testing

jest

mocha + chai

State

setState

redux

mobx

API

REST + fetch

relay

apollo

falcor

Decision fatigue?

NOTES:
- React is just a UI library; it's a great one IMO, but just a UI library
- So to create apps you need to build up your own stack
- **Tooling:** probably Webpack, but need to configure it; gulp/grunt; eslint/flow/Typescript;
- Create React App helps w/ getting started; eject later
- **Styling:** glamorous, styled-components, radium, aphrodite
- You really get to tailor your own stack
- But if you're just getting started it's "decision fatigute"

/////

## Moar decisions decisions...

There's no **React way™** 🤷🏾♂

NOTES:
- But even when you have the stack down, there are all these debates abou the "right way" to do things
- Do you always use component classes or use stateless functions until you need state?
- `setState` gate
- Inline functions debate
- 4 different ways to do Redux side-effects: thunk, sagas, observables & promise middleware
- HOCs vs render props
- Can be a "pro" because you can look at the team and make decisions based on the skillset
- This is how you can from one team to another doing React and it'll be done completely differently

/////

## Eventbrite Stack

- React 15
- Babel 6 (`env` + `stage-3`)
- Webpack 3 + `sass-loader`
- Redux & Redux Thunk
- React Router 3
- Jest 21 + Enzyme 3 + `jest-enzyme`
- ESLint 3
- Eventbrite Design System
- Node 4
- Yarn 0.27

NOTES:
- Here's our stack at Eventbrite in case you're curious...
- React 15.4.2 - hopefully upgrading soon
- Babel: Stage 4 is truly safest, but stage 3 has goodies and unlikely to change
- Finished huge migration from requirejs to Webpack 3
- Enzyme: Had to upgrade cuz of intermittent failures
- Node: Upgrading to Node 8 right now

/////

## [Navigating the React Solar System](http://www.benmvp.com/slides/2017/modernweb/nav-react.html)

### Modern Web Meetup May 2017

NOTES:
- Final shameless plug alert!
- I gave a talk called _Navigating the React Solar System_ at a Bay Area meetup
- Go through all the important pieces that make up a React stack
- Talk about the different options and show code examples

**[ASK ABOUT QUESTIONS]**

=====

10. Miscellaneous

NOTES:
- Ok, the final reason that Eventbrite wanted to migrate to React is a sort of catch-all
- There are many other reason for going for React
- Don't really deserve their own section (and I don't have hours), but still important...

/////

## Other considerations

Deep commitment by Facebook

Dedicated Facebook dev staff

Rapid feedback loop

Huge ecosystem

Simple API

Popular

Stable

Evolving

Codemods

Developer Tools

Browser compatibility

Composable with existing apps

Thanks [Cory House 🏠](https://twitter.com/housecor/status/909145686498775040)!

NOTES:
- **Commitment**: Facebook uses it in their own products so less likely to go away
- **Staff**: is a big reason; it's not just some folks doing it in their spare time
- **Popular**: not a good enough reason by itself but doesn't hurt for recruiting/perception
- **Simple API**: I rarely have to go to the docs (except for prop types)
- **Ecosystem**: Similarly the eco-system is huge so if you need to do something probably already
  exists
- **Feedback**: React + webpack makes developing a sync with webpack dev server
- **Evolving + Stable**: React continues to grow greatly (Fiber) but few breaking changes & there
  are long deprecations
- **Codemods**: enable switching code when features are deprecated
- **Existing apps**: React _can_ be used with other libs like Backbone for a gradual transition
  (what we're doing)
- This list was lifted from a tweet from Cory, so thanks!

**[ASK ABOUT QUESTIONS]**

=====

## Recap

Declarative JSX

Component-driven

All JavaScript*

State-driven

Sophisticated reconciler

Server-side rendering

Testing

React Native

Unopionated

...and more!

NOTES:
- Again these are the reasons **we** made the switch to React
- I really wish I could've gone into more details on each one
- Each one literally could be its own talk
- Talked about how JSX provides great developer ergonomics
- The fact that it's component-driven not only makes it easy to build UIs
- But also enables the reconciler, server-side rendering, testing & dozens of other renders
- It's state-driven instead of event-driven and we can use at lot of the latest JavaScript in our apps
- And many other goodies!
- My favorite one is the sophisticated reconciler!

=====

#### (Trust)
# The Process

![Joel Embiid Excited](../../img/giphy/joel-embiid-excited.gif)

NOTES:
- After presenting our compelling argument we got the greenlight to start React transition
- Eventbrite is not one single app, but made up multiple smaller apps
- No plan to stop and convert everything over; opportunistic rewrites
- First consumer was team building ambitious new event creation experience
- Existing experience pre-dates Backbone and mostly written in jQuery soup; complete rewrite
- Started building up stack and Design team came to us w/ opportunity also update visual design
- Began building out a design system

/////

## Eventbrite Design System

<video data-autoplay loop style="width: 80%">
  <source data-src="../../img/why-react/eventbrite-design-system.m4v" />
</video>

NOTES:
- It's filled with dozens of React components big and small
- But it's more than a component library; it's a design system
- Talks about _why_ components should be used, etc

/////

## [Sign-in / Sign-up](http://www.eventbrite.com/signin)

  <video data-autoplay loop style="width: 80%">
    <source data-src="../../img/why-react/eventbrite-sign-up-flow.m4v" />
  </video>

NOTES:
- We rebuilt our sign-in & sign-up experiences in React
- It's actually a modal that sits on top of the page
- And it's launchable from every page, React or not
- So it's an example of React co-existing w/ non React
- It's dynamically loaded using dynamic `import()`

/////

## [Checkout Widget](https://www.speednashvilledating.com/event-schedule/)

  <video data-autoplay loop style="width: 80%">
    <source data-src="../../img/why-react/eventbrite-checkout-widget.m4v" />
  </video>

NOTES:
- We want to give organizers the ability to control the experience of displaying tickets
- Checkout widget takes you to speednashvilledating.com FYI
- Taking place tonight at 8PM

/////

## [Organizer Onboarding](https://www.eventbrite.com/organizer/onboarding/)

  <video data-autoplay loop style="width: 80%">
    <source data-src="../../img/why-react/eventbrite-organizer-onboarding-flow.m4v" />
  </video>

/////

## [City Browse](https://www.eventbrite.com/d/tn--nashville/events/?janus_fv=exp_eb_60058_city_browse%3DB)

  <video data-autoplay loop style="width: 80%">
    <source data-src="../../img/why-react/eventbrite-city-browse-flow.m4v" />
  </video>

/////

## Eventbrite + React in the wild

- [Trending Searches](https://www.eventbrite.com/trending/searches/tn--nashville/daily/)
- Event Creation (Beta)
- Event Management Navigation
- Event Management Dashboard
- Admin Tools

NOTES:
- Event Management Navigation was an example where we mixed React & Backbone
- Dozens of management pages that share the same nav, so redid the nav in React
- So that when pages got rewritten or added, the IA would seem consistent

=====

## Additional resources

- [The Beginner's Guide to ReactJS](https://egghead.io/courses/the-beginner-s-guide-to-reactjs)
- [Advanced React Component Patterns](https://egghead.io/courses/advanced-react-component-patterns)
- [Eventbrite React coding styleguide](https://github.com/eventbrite/javascript/tree/master/react)
- [Eventbrite ES6+ coding styleguide](https://github.com/eventbrite/javascript/tree/master/es6)
- [Eventbrite React Testing Best Practices](https://github.com/eventbrite/javascript/blob/master/react/testing.md)
- [React/Redux Links](https://github.com/markerikson/react-redux-links)

NOTES:
- Mark (w/ help) has collection a bazillion links to resources covering React, Redux, ES6 and more!

=====

![Jack Sparrow Thanks](../../img/giphy/thanks-jack-sparrow.gif)

## Ben Ilegbodu

[benmvp.com](/) | [@benmvp](https://twitter.com/benmvp) | [ben@benmvp.com](mailto:ben@benmvp.com)
[github/benmvp](https://github.com/benmvp)

Ask me anything! [benmvp.com/ama](http://www.benmvp.com/ama/)

NOTES:
- So before I close...
- Wanted to thank Nodevember for inviting me to share with you
- Let's celebrate them for putting on another great conference
- Thanks to Eventbrite too for sponsoring and flying me out
- We're hiring!
- Also thank YOU for attending and sticking around!
- My goal is for you to learn at least one thing you can take away to be a better dev
- Hopefully if you are in the same boat of wanting to transition, you've got some good material
- Slides are available on Twitter and Blog
- Would love to hear from you about things that were unclear, wanna know more about or general questions
- Ask on Twitter, via AMA or email
- I hope you enjoyed the conference
- Thanks and let's enjoy the afterparty


text:
package cr_ee

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// CreateBuildRecordByRule invokes the cr.CreateBuildRecordByRule API synchronously
// api document: https://help.aliyun.com/api/cr/createbuildrecordbyrule.html
func (client *Client) CreateBuildRecordByRule(request *CreateBuildRecordByRuleRequest) (response *CreateBuildRecordByRuleResponse, err error) {
	response = CreateCreateBuildRecordByRuleResponse()
	err = client.DoAction(request, response)
	return
}

// CreateBuildRecordByRuleWithChan invokes the cr.CreateBuildRecordByRule API asynchronously
// api document: https://help.aliyun.com/api/cr/createbuildrecordbyrule.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateBuildRecordByRuleWithChan(request *CreateBuildRecordByRuleRequest) (<-chan *CreateBuildRecordByRuleResponse, <-chan error) {
	responseChan := make(chan *CreateBuildRecordByRuleResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.CreateBuildRecordByRule(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// CreateBuildRecordByRuleWithCallback invokes the cr.CreateBuildRecordByRule API asynchronously
// api document: https://help.aliyun.com/api/cr/createbuildrecordbyrule.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateBuildRecordByRuleWithCallback(request *CreateBuildRecordByRuleRequest, callback func(response *CreateBuildRecordByRuleResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *CreateBuildRecordByRuleResponse
		var err error
		defer close(result)
		response, err = client.CreateBuildRecordByRule(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// CreateBuildRecordByRuleRequest is the request struct for api CreateBuildRecordByRule
type CreateBuildRecordByRuleRequest struct {
	*requests.RpcRequest
	RepoId      string `position:"Query" name:"RepoId"`
	BuildRuleId string `position:"Query" name:"BuildRuleId"`
	InstanceId  string `position:"Query" name:"InstanceId"`
}

// CreateBuildRecordByRuleResponse is the response struct for api CreateBuildRecordByRule
type CreateBuildRecordByRuleResponse struct {
	*responses.BaseResponse
	CreateBuildRecordByRuleIsSuccess bool   `json:"IsSuccess" xml:"IsSuccess"`
	Code                             string `json:"Code" xml:"Code"`
	RequestId                        string `json:"RequestId" xml:"RequestId"`
	BuildRecordId                    string `json:"BuildRecordId" xml:"BuildRecordId"`
}

// CreateCreateBuildRecordByRuleRequest creates a request to invoke CreateBuildRecordByRule API
func CreateCreateBuildRecordByRuleRequest() (request *CreateBuildRecordByRuleRequest) {
	request = &CreateBuildRecordByRuleRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("cr", "2018-12-01", "CreateBuildRecordByRule", "acr", "openAPI")
	request.Method = requests.POST
	return
}

// CreateCreateBuildRecordByRuleResponse creates a response to parse from CreateBuildRecordByRule response
func CreateCreateBuildRecordByRuleResponse() (response *CreateBuildRecordByRuleResponse) {
	response = &CreateBuildRecordByRuleResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}

redpajama_set_name: RedPajamaGithub


text:
"use strict"

const mongodb = require('mongodb')

/** @type {mongodb.Collection<any>} */
let collection

/**
 * @typedef {Object} Settings
 * @property {mongodb.Db} settings.mongoDBConnection
 * @param {Settings} settings
 */
module.exports.setup = function(settings) {
  collection = settings.mongoDBConnection.collection('tests')
}

exports.findAll = function() {
  return collection.find({})
    .toArray()
    .then(tests => {
      for (let i = 0; i < tests.length; i++) {
        tests[i].id = tests[i]._id.toString()
        delete tests[i]._id
      }
      return tests
    })
}

/**
 * Find test by its identificator.
 * @param {string} id Identificator of test.
 * @returns {} Object for test.
 */
exports.findById = function(id) {
    return collection.findOne({_id: new mongodb.ObjectID(id)})
      .then(test => {
        if (test) {
          test.id = test._id.toString()
          delete test._id
        }
        return test
      })
}

exports.add = function(test) {
    if (test.author) {
      test.authors = [test.author];
      delete test.author;
    }
    test.created_at = new Date();
    test.updated_at = null;
    return collection.insertOne(test)
      .then(result => {
        let test = result.ops[0]
        test.id = test._id.toString()
        delete test._id
        return test
      });
}

exports.clear = function() {
    return collection.deleteMany({ })
}


text:
package net.openhft.chronicle.core.threads;

import net.openhft.chronicle.core.Jvm;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

// TODO Needs a test
public class MonitorProfileAnalyserMain {

    private static final int MAX_LINES = Jvm.getInteger("st.maxlines", 8);
    private static final String PROFILE_OF_THE_THREAD = "profile of the thread";
    private static final String THREAD_HAS_BLOCKED_FOR = "thread has blocked for";

    /**
     * Reads one or more log files and looks for thread profiles to summarise
     */
    public static void main(String[] args) throws IOException {
        if (args.length == 0)
            System.err.println("No input file(s) provided");

        final String stIgnore = Jvm.getProperty("st.ignore");
        List<String> ignoreSubStrings = stIgnore != null ? Arrays.asList(stIgnore.split(",")) : Collections.emptyList();
        int interval = Integer.getInteger("interval", 0);
        if (interval <= 0) {
            main0(ignoreSubStrings, args);
        } else {
            for (; ; ) {
                main0(ignoreSubStrings, args);
                JitterSampler.sleepSilently(interval * 1000);
                System.out.println("\n---\n");
            }
        }
    }

    public static void main0(List<String> ignoreSubStrings, String[] args) throws IOException {
        System.out.println("Grouped by line");
        Map<String, Integer> stackCount = new LinkedHashMap<>();

        for (String arg : args) {
            StringBuilder sb = new StringBuilder();
            int lineCount = -1;
            try (BufferedReader br = Files.newBufferedReader(Paths.get(arg))) {
                // TODO: PrintGCApplicationStoppedTime

                for (String line; (line = br.readLine()) != null; ) {
                    if (line.contains(PROFILE_OF_THE_THREAD) || line.contains(THREAD_HAS_BLOCKED_FOR)) {
                        if (sb.length() > 0) {
                            addToStackCount(ignoreSubStrings, stackCount, sb);
                        }
                        lineCount = 0;
                        sb.setLength(0);

                    } else if (partOfStackTrace(line) && lineCount >= 0) {
                        if (++lineCount <= MAX_LINES) {
                            sb.append(line).append("\n");
                        }
                    } else if (sb.length() > 0) {
                        addToStackCount(ignoreSubStrings, stackCount, sb);
                        sb.setLength(0);
                    }
                }
            }
        }
        List<Map.Entry<String, Integer>> stackSortedByCount =
                stackCount.entrySet().stream()
                        .filter(e -> e.getValue() > 2)
                        .sorted(Comparator.comparing(e -> -e.getValue())) // reversed
                        .limit(20)
                        .collect(Collectors.toList());
        stackSortedByCount.forEach(e -> {
                    stackCount.remove(e.getKey());
                    System.out.println(e.getValue() + e.getKey());
                });

        System.out.println("Grouped by method.");
        Map<String, Integer> methodCount = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> entry : stackCount.entrySet()) {
            String stack = entry.getKey().replaceFirst("\\(.*?\\)", "( * )");
            methodCount.compute(stack, (k, v) -> (v == null ? 0 : v) + entry.getValue());
        }

        List<Map.Entry<String, Integer>> methodSortedByCount =
                methodCount.entrySet().stream()
                        .filter(e -> e.getValue() > 2)
                        .sorted(Comparator.comparing(e -> -e.getValue())) // reversed
                        .limit(20)
                        .collect(Collectors.toList());
        methodSortedByCount
                .forEach(e -> System.out.println(e.getValue() + e.getKey()));
    }

    private static void addToStackCount(List<String> ignoreSubStrings, Map<String, Integer> stackCount, StringBuilder sb) {
        String lines = sb.toString();
        for (String ss : ignoreSubStrings)
            if (lines.contains(ss))
                return;
        stackCount.compute(lines, (k, v) -> v == null ? 1 : v + 1);
    }

    private static boolean partOfStackTrace(String line) {
        // make this more robust in the face of copy/pasting etc.
        return line.startsWith("\tat ") || line.matches("\\s+at .*");
    }
}


text:
import {Component, Input, Output, EventEmitter, OnChanges} from '@angular/core';

import { Grid } from '../../lib/grid';
import { DataSource } from '../../lib/data-source/data-source';

@Component({
    selector: '[ng2-st-thead]',
    templateUrl: './thead.component.html',
})
export class Ng2SmartTableTheadComponent implements OnChanges {

    @Input() grid: Grid;
    @Input() source: DataSource;
    @Input() isAllSelected: boolean;
    @Input() createConfirm: EventEmitter<any>;

    @Output() sort = new EventEmitter<any>();
    @Output() selectAllRows = new EventEmitter<any>();
    @Output() create = new EventEmitter<any>();
    @Output() filter = new EventEmitter<any>();

    isHideHeader: boolean;
    isHideSubHeader: boolean;

  ngOnChanges() {
      this.isHideHeader = this.grid.getSetting('hideHeader');
      this.isHideSubHeader = this.grid.getSetting('hideSubHeader');
    }
}


text:
package org.openmhealth.shim.jawbone.mapper;

import com.fasterxml.jackson.databind.JsonNode;
import org.openmhealth.schema.domain.omh.BodyWeight;
import org.openmhealth.schema.domain.omh.MassUnitValue;
import org.openmhealth.schema.domain.omh.Measure;

import java.util.Optional;

import static org.openmhealth.schema.domain.omh.MassUnit.KILOGRAM;
import static org.openmhealth.shim.common.mapper.JsonNodeMappingSupport.asOptionalDouble;
import static org.openmhealth.shim.jawbone.mapper.JawboneBodyEventType.BODY_WEIGHT;

/**
 * @author Chris Schaefbauer
 * @see API documentation
 */
public class JawboneBodyWeightDataPointMapper extends JawboneBodyEventsDataPointMapper<BodyWeight> {

    @Override
    protected Optional<Measure.Builder<BodyWeight, ?>> newMeasureBuilder(JsonNode listEntryNode) {

        Optional<Double> optionalWeight = asOptionalDouble(listEntryNode, "weight");

        if (!optionalWeight.isPresent()) {
            return Optional.empty();
        }

        return Optional.of(new BodyWeight.Builder(new MassUnitValue(KILOGRAM, optionalWeight.get())));
    }

    @Override
    protected JawboneBodyEventType getBodyEventType() {
        return BODY_WEIGHT;
    }
}


text:
echo Hash of Qt binary [experimental]...
bash dahash.sh $ROOTPATHSH/release/${COINNAME}-qt.exe
echo
echo


text:
package reusing.solution;

//: reusing/Beetle.java
//The full process of initialization.
import static net.mindview.util.Print.*;

class Insect {
	private int i = 9;
	protected int j;

	Insect() {
		print("i = " + i + ", j = " + j);
		j = 39;
	}

	private static int x1 = printInit("static Insect.x1 initialized");

	static int printInit(String s) {
		print(s);
		return s.length();
	}
}

class Beetle extends Insect {
	protected int k = printInit("Beetle.k initialized");

	public Beetle() {
		print("k = " + k);
		print("j = " + j);
	}

	private static int x2 = printInit("static Beetle.x2 initialized");

	public static void main(String[] args) {
		print("Beetle constructor");
		Beetle b = new Beetle();
	}
}

class Beetle1 extends Beetle {
	private static int x3 = printInit("static Beetle1.x3 initialized");
	private int t  = printInit("int Beetle1.t initialized");
	Beetle1(){
		print("j =" + j);
		print("k =" + k);
		print("t =" + t);
	}
}
public class Ex24 {
	public static void main(String[] args){
		Beetle1 ob = new Beetle1();

	}
}


text:
import TestContainer from 'mocha-test-container-support';

import {
  act
} from '@testing-library/preact';

import {
  bootstrapPropertiesPanel,
  inject
} from 'test/TestHelper';

import {
  query as domQuery,
  queryAll as domQueryAll
} from 'min-dom';

import {
  getBusinessObject
} from 'bpmn-js/lib/util/ModelUtil';

import CoreModule from 'bpmn-js/lib/core';
import SelectionModule from 'diagram-js/lib/features/selection';
import ModelingModule from 'bpmn-js/lib/features/modeling';

import BpmnPropertiesPanel from 'src/render';

import ZeebePropertiesProvider from 'src/provider/zeebe';

import zeebeModdleExtensions from 'zeebe-bpmn-moddle/resources/zeebe';

import {
  getOutputParameters,
  getIoMapping
} from 'src/provider/zeebe/utils/InputOutputUtil';

import diagramXML from './OutputProps.bpmn';

describe('provider/zeebe - OutputProps', function() {

  const testModules = [
    CoreModule, SelectionModule, ModelingModule,
    BpmnPropertiesPanel,
    ZeebePropertiesProvider
  ];

  const moddleExtensions = {
    zeebe: zeebeModdleExtensions
  };

  let container;

  beforeEach(function() {
    container = TestContainer.get(this);
  });

  beforeEach(bootstrapPropertiesPanel(diagramXML, {
    modules: testModules,
    moddleExtensions,
    debounceInput: false
  }));

  describe('bpmn:ServiceTask#output', function() {

    it('should NOT display for simple task', inject(async function(elementRegistry, selection) {

      // given
      const task = elementRegistry.get('Task_1');

      await act(() => {
        selection.select(task);
      });

      // when
      const outputGroup = getGroup(container, 'outputs');

      // then
      expect(outputGroup).to.not.exist;
    }));

    it('should display', inject(async function(elementRegistry, selection) {

      // given
      const serviceTask = elementRegistry.get('ServiceTask_1');

      await act(() => {
        selection.select(serviceTask);
      });

      // when
      const outputGroup = getGroup(container, 'outputs');
      const outputListItems = getOutputListItems(outputGroup);

      // then
      expect(outputGroup).to.exist;
      expect(outputListItems.length).to.equal(getOutputParameters(serviceTask).length);
    }));

    it('should add new output', inject(async function(elementRegistry, selection) {

      // given
      const serviceTask = elementRegistry.get('ServiceTask_1');

      await act(() => {
        selection.select(serviceTask);
      });

      const outputGroup = getGroup(container, 'outputs');
      const addEntry = domQuery('.bio-properties-panel-add-entry', outputGroup);

      // when
      await act(() => {
        addEntry.click();
      });

      // then
      expect(getOutputParameters(serviceTask)).to.have.length(5);
    }));

    it('should create non existing extension elements',
      inject(async function(elementRegistry, selection) {

        // given
        const serviceTask = elementRegistry.get('ServiceTask_empty');

        await act(() => {
          selection.select(serviceTask);
        });

        // assume
        expect(getBusinessObject(serviceTask).get('extensionElements')).not.to.exist;

        const outputGroup = getGroup(container, 'outputs');
        const addEntry = domQuery('.bio-properties-panel-add-entry', outputGroup);

        // when
        await act(() => {
          addEntry.click();
        });

        // then
        expect(getBusinessObject(serviceTask).get('extensionElements')).to.exist;
      })
    );

    it('should create non existing ioMapping',
      inject(async function(elementRegistry, selection) {

        // given
        const serviceTask = elementRegistry.get('ServiceTask_noIoMapping');

        await act(() => {
          selection.select(serviceTask);
        });

        // assume
        expect(getIoMapping(serviceTask)).not.to.exist;

        const outputGroup = getGroup(container, 'outputs');
        const addEntry = domQuery('.bio-properties-panel-add-entry', outputGroup);

        // when
        await act(() => {
          addEntry.click();
        });

        // then
        expect(getIoMapping(serviceTask)).to.exist;
      })
    );

    it('should delete output', inject(async function(elementRegistry, selection) {

      // given
      const serviceTask = elementRegistry.get('ServiceTask_1');

      await act(() => {
        selection.select(serviceTask);
      });

      const outputListItems = getOutputListItems(getGroup(container, 'outputs'));
      const removeEntry = domQuery('.bio-properties-panel-remove-entry', outputListItems[0]);

      // when
      await act(() => {
        removeEntry.click();
      });

      // then
      expect(getOutputParameters(serviceTask)).to.have.length(3);
    }));

    it('should remove ioMapping on last delete', inject(async function(elementRegistry, selection) {

      // given
      const serviceTask = elementRegistry.get('ServiceTask_2');

      await act(() => {
        selection.select(serviceTask);
      });

      // assume
      expect(getIoMapping(serviceTask)).to.exist;

      const outputListItems = getOutputListItems(getGroup(container, 'outputs'));
      const removeEntry = domQuery('.bio-properties-panel-remove-entry', outputListItems[0]);

      // when
      await act(() => {
        removeEntry.click();
      });

      // then
      expect(getIoMapping(serviceTask)).not.to.exist;
    }));

    it('should update on external change',
      inject(async function(elementRegistry, selection, commandStack) {

        // given
        const serviceTask = elementRegistry.get('ServiceTask_1');
        const originalOutputs = getOutputParameters(serviceTask);

        await act(() => {
          selection.select(serviceTask);
        });

        const addEntry = domQuery('.bio-properties-panel-add-entry', container);
        await act(() => {
          addEntry.click();
        });

        // when
        await act(() => {
          commandStack.undo();
        });

        const outputListItems = getOutputListItems(getGroup(container, 'outputs'));

        // then
        expect(outputListItems.length).to.equal(originalOutputs.length);
      })
    );

  });

});

// helper //////////////////

function getGroup(container, id) {
  return domQuery(`[data-group-id="group-${id}"`, container);
}

function getListItems(container, type) {
  return domQueryAll(`div[data-entry-id*="-${type}-"].bio-properties-panel-collapsible-entry`, container);
}

function getOutputListItems(container) {
  return getListItems(container, 'output');
}


text:
from setuptools import setup

setup(
    name='kairos_face_recognition_lib',
    version='0.3.0',
    packages=['kairos_face'],
    url='https://github.com/ffmmjj/kairos-face-sdk-python',
    license='MIT',
    author='Felipe Martins',
    author_email='',
    description='Kairos Face Recognition API Python Client Library',
    install_requires=[
        'requests'
    ]
)


text:
var mongoose = require('mongoose');
var config = require('../config/database');

var bulletSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    dateOfCreation: {
        type: String,
        required: true
    },
    lastUpdate: {
        type: String,
        required: true
    },
    color: {
        type: String,
        required: true
    },
    content: {
        type: Object,
    }
});

module.exports = mongoose.model('Bullet', bulletSchema);

module.exports.getBulletById = function(id, callback) {
    Bullet.findById(id, callback);
}

module.exports.getAllBullets = function(callback) {
    this.find(callback);
}

module.exports.addBullet = function(newBullet, callback) {
    newBullet.save(callback);
}

module.exports.removeBullet = function(bulletID, callback) {
    console.log(bulletID);
    this.findById(bulletID).remove(callback);
}

module.exports.addNewContentToBullet = function(bulletID, content, callback) {
    this.findById(bulletID).update({ _id: bulletID }, { $push: { "content": content } }, callback);
}

module.exports.updateTodayContentOfBullet = function(bulletID, content, callback) {
    console.log(content);
    this.findById(bulletID).update({ _id: bulletID }, { $pop: { "content": 1 } }, (err, res) => {});
    this.findById(bulletID).update({ _id: bulletID }, { $push: { "content": content } }, callback);
}
module.exports.updateLastUpdate = function(bulletID, lastUpdate, callback) {
    let lastUpdateString = lastUpdate._day + "/" + lastUpdate._mounth + "/" + lastUpdate._year;
    this.findById(bulletID).update({ _id: bulletID }, { $set: { "lastUpdate": lastUpdateString } }, callback);

}
module.exports.updateNewName = function(bulletID, newName, callback) {
    console.log(newName);
    this.findById(bulletID).update({ _id: bulletID }, { $set: { "name": newName } }, callback);

}


text:
import org.garret.perst.*;

public class OO7_DocumentImpl extends Persistent implements OO7_Document {
    String theTitle;
    long theId;
    String theText;

    public OO7_DocumentImpl() {
    }

    public void setTitle( String x ) {
        theTitle = x;
        modify();
    }

    public String title() {
        return theTitle;
    }

    public void setId( long x ) {
        theId = x;
        modify();
    }

    public long id() {
        return theId;
    }

    public void setText( String x ) {
        theText = x;
        modify();
    }

    public String text() {
        return theText;
    }
}


text:
<?php

namespace Seeren\Database\Statement;

use InvalidArgumentException;
use Seeren\Database\Entity\EntityInterface;
use Seeren\Database\Manager\ManagerInterface;

/**
 * Interface to represent a statement
 *
 *     __
 *    / /__ __ __ __ __ __
 *   / // // // // // // /
 *  /_// // // // // // /
 *    /_//_//_//_//_//_/
 *
 * @package Seeren\Database\Statement
 */
interface StatementInterface
{

    /**
     * @param ManagerInterface $manager
     * @param EntityInterface $table
     * @return mixed
     * @throws InvalidArgumentException
     */
    public function execute(ManagerInterface $manager, EntityInterface $table);

}


text:
//*******************************************************************
//
// program - DDESrvr.c
// purpose - DDE server interface routines. This file is part of the
//           MSGWND project.
//
//*******************************************************************

#define  STRICT
#include <windows.h>
#include <dde.h>
#include <stdio.h>
#include <string.h>

# include "ddesrvr.h"

# define WW_CLIENT 0
# define ACK       0x8000
# define BUSY      0x4000

static int  nServerClassRegistered;
static char szServerClass[] = "ddeserver";
static WORD wLastDDEServerMsg;

//*******************************************************************
// DDEServerInit - called in response to WM_DDE_INITIATE
//
// paramaters:
//             hParentWnd    - The handle of the server window trying to
//                             respond to this dde conversation.
//             hClientWnd    - The handle of the client window trying to start
//                             this dde conversation.
//             lParam        - lParam send by client window.
//                             Contains atoms of application and topic client
//                             wants to talk about.
//             szApp         - The name of the application server represents.
//             szTopic       - The name of the topic server knows about.
//
// returns:
//             The handle of the channel to use to continue the conversation
//                or
//             NULL if conversation could not be opened.
//
//*******************************************************************
HWND DDEServerInit(HWND hParentWnd, HWND hClientWnd, LPARAM lParam,
		  char *szApp, char *szTopic)
{
    HINSTANCE hInst;
    HWND     hChannel;
    ATOM     aApp;
    ATOM     aTopic;
    WNDCLASS wclass;
    char     szClassName[sizeof(szServerClass) + 10];

    // Get atoms representing application and topic we will talk about.
    aApp = GlobalAddAtom(szApp);
    if (!aApp)
        return(0);

    aTopic = GlobalAddAtom(szTopic);
    if (!aTopic)
    {
        GlobalDeleteAtom(aApp);
        return(0);
    }

    // If request is not for application and topic we will talk about
    // do not open conversaton.
    if ((aApp != LOWORD(lParam)) || (aTopic != HIWORD(lParam)))
    {
        GlobalDeleteAtom(aApp);
        GlobalDeleteAtom(aTopic);
        return(0);
    }

    // Get parents instance to use in creating window to carry on
    // dde conversation.
    hInst = (HANDLE)GetWindowWord(hParentWnd, GWW_HINSTANCE);
    if (!hInst)
        return(0);

    // Create a unique class name for this instance of the server.
    sprintf(szClassName, "%s%04X", szServerClass, hInst);

    // If we have not already done it, register the window class to
    // carry on this conversation.
    if (!nServerClassRegistered)
    {
        wclass.style         = CS_HREDRAW | CS_VREDRAW;
        wclass.lpfnWndProc   = DDEServerWndProc;
        wclass.cbClsExtra    = 0;
        wclass.cbWndExtra    = 2;
        wclass.hInstance     = hInst;
        wclass.hIcon         = 0;
        wclass.hCursor       = 0;
        wclass.hbrBackground = 0;
        wclass.lpszMenuName  = 0;
        wclass.lpszClassName = szClassName;

        // Do not fail if register fails, because another app may have
        // already registered this class.
        RegisterClass(&wclass);

	// So we won't try to register again.
        nServerClassRegistered = 1;
    }

    // Create the window that will remain hidden but will carry on the
    // conversation wih the dde client.
    hChannel = CreateWindow(szClassName,      // window class name
                            NULL,             // window title
                            WS_CHILD,         // window style
                            CW_USEDEFAULT,    // window origin
                            0,
                            CW_USEDEFAULT,    // window size
                            0,
                            hParentWnd,       // window parent
                            NULL,             // window id
                            hInst,            // window instance
                            NULL);            // no parms

    // If create of window failed we cannot continue.
    if (!hChannel)
        return(0);

    // Remember the handle of our client.
    SetWindowWord(hChannel, WW_CLIENT, (WORD)hClientWnd);

    // Send acknowledgement to client.
    wLastDDEServerMsg = WM_DDE_ACK;
    SendMessage(hClientWnd, (UINT)wLastDDEServerMsg, (WPARAM)hChannel, (LPARAM)MAKELONG(aApp, aTopic));

    // Return handle of window that will carry on the conversation for
    // this server.
    return(hChannel);
}

//*******************************************************************
// DDEServerClose - close the dde conversation with a client
//
// paramaters:
//             hChannel      - The handle of the window conducting
//                             the dde conversation.
//
//*******************************************************************
int DDEServerClose(HWND hChannel)
{
    HWND hClientWnd;

    // If the channel is still active.
    if (IsWindow(hChannel))
    {
        wLastDDEServerMsg = WM_DDE_TERMINATE;

        // Get handle of client we were conversing with.
        hClientWnd = (HWND)GetWindowWord(hChannel, WW_CLIENT);

        // If he is still active.
        if (IsWindow(hClientWnd))
            SendMessage(hClientWnd, (UINT)wLastDDEServerMsg, (WPARAM)hChannel, (LPARAM)0L);
    }

    return(1);
}

//*******************************************************************
// DDEServerWndProc - window proc to manage interface with client
//
// paramaters:
//             hWnd          - The window handle for this message
//             message       - The message number
//             wParam        - The WPARAM parameter for this message
//             lParam        - The LPARAM parameter for this message
//
// returns:
//             depends on message.
//
//*******************************************************************
LRESULT CALLBACK DDEServerWndProc(HWND hWnd, UINT message,
				 WPARAM wParam, LPARAM lParam)
{
    WORD         wStatus;
    HWND         hClientWnd;
    HANDLE       hCommand;
    HANDLE       hData;
    LPSTR        lpData;
    HANDLE       hShData;
    DDEDATA FAR *lpShData;
    char         szItem[30];
    ATOM         aItem;
    LPSTR        lpCommand;
    int          nRc;
    int          nSize;

    switch (message)
    {
        case WM_DDE_EXECUTE:         // execute a command for client
            // Get handle of client.
	    hClientWnd = (HWND)wParam;

            // Init status.
            wStatus = 0;

            // Get handle of command client is sending us.
            hCommand = (HANDLE)HIWORD(lParam);

            // Lock it down to get address.
            lpCommand = GlobalLock(hCommand);
            if (lpCommand)
            {
                // Call our function to execute the command.
                if (DDEExecuteCommand(lpCommand))
                    wStatus = ACK;

                GlobalUnlock(hCommand);
            }

	    // Send acknowledgement back to client.
            PostMessage(hClientWnd, WM_DDE_ACK, (WPARAM)hWnd,
                       (LPARAM)MAKELONG(wStatus, hCommand));
            break;

        case WM_DDE_REQUEST:         // data request from a client
            // Get handle of client.
            hClientWnd = (HWND)wParam;

            // Get atom representing data request item.
            aItem = HIWORD(lParam);
            if (!GlobalGetAtomName(aItem, szItem, sizeof(szItem)))
            {
                // Error if atom not found.
                PostMessage(hClientWnd, WM_DDE_ACK, (WPARAM)hWnd,
                           (LPARAM)MAKELONG(0, aItem));
                return(0L);
            }

	    // Init return code.
            nRc = 0;

            // Don't care about case.
            strupr(szItem);

            // Call our function to get the data item.
            nSize = DDEData(szItem, &hData);

            // If any data found.
            if (nSize)
            {
                // Get shared memory to send item back in.
                hShData = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT | GMEM_DDESHARE,
                                      (DWORD) (nSize + sizeof(DDEDATA) + 1));
                if (hShData)
                {
                    // Lock it down to get address.
                    lpShData = (DDEDATA FAR *) GlobalLock(hShData);
		    if (lpShData)
                    {
                        // Setup data header.
                        lpShData->fResponse = 1;
                        lpShData->fRelease = 1;
                        lpShData->fAckReq = 0;
                        lpShData->cfFormat = CF_TEXT;

                        // Lock out local copy of data to get address.
                        lpData = GlobalLock(hData);
                        if (lpData)
                        {
                            // Copy data to shared memory.
                            _fstrcpy((LPSTR)lpShData->Value, lpData);
                            GlobalUnlock(hData);

                            nRc = 1;
                        }

			GlobalUnlock(hShData);
                    }
                }

                GlobalFree(hData);
            }

            if (nRc)
            {
                // If ok send data back.
                PostMessage(hClientWnd, WM_DDE_DATA, (WPARAM)hWnd,
                           (LPARAM)MAKELONG(hShData, aItem));
            }
            else
            {
                // If errors just send negative acknowlegement back.
                PostMessage(hClientWnd, WM_DDE_ACK, (WPARAM)hWnd,
                           (LPARAM)MAKELONG(0, aItem));
            }
	    break;

        case WM_DDE_TERMINATE:      // server says terminate conversation
            // Get handle of client we are dealing with.
            hClientWnd = (HWND)GetWindowWord(hWnd, WW_CLIENT);

            // Ignore if not from our client.
            if (wParam != (WPARAM)hClientWnd)
                return(0L);

            // Forget who client is.
            SetWindowWord(hWnd, WW_CLIENT, 0);

            // Tell our parent conversation closed.
            SendMessage(GetParent(hWnd), WMU_DDE_CLOSED, (WPARAM)hWnd, 0L);

            // Send terminate to server to acknowledge we recieved
            // terminate,  if we did not initiate the termination ourselves.
            if ((wLastDDEServerMsg != WM_DDE_TERMINATE) && IsWindow(hClientWnd))
		PostMessage(hClientWnd, WM_DDE_TERMINATE, (WPARAM)hWnd, 0L);

            // Terminate this child window.
            DestroyWindow(hWnd);
            break;

        case WM_DESTROY:            // destroy this window
            // Terminate any ongoing conversation on our way out.
            DDEServerClose(hWnd);
            break;

        default:
            return(DefWindowProc(hWnd, message, wParam, lParam));
    }

    return(0L);
}

//*******************************************************************


text:
@interface RealmBarChartViewController () <ChartViewDelegate>

@property (nonatomic, strong) IBOutlet BarChartView *chartView;

@end

@implementation RealmBarChartViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self writeRandomDataToDbWithObjectCount:20];

    self.title = @"Realm.io Bar Chart";

    self.options = @[
                     @{@"key": @"toggleValues", @"label": @"Toggle Values"},
                     @{@"key": @"toggleHighlight", @"label": @"Toggle Highlight"},
                     @{@"key": @"animateX", @"label": @"Animate X"},
                     @{@"key": @"animateY", @"label": @"Animate Y"},
                     @{@"key": @"animateXY", @"label": @"Animate XY"},
                     @{@"key": @"saveToGallery", @"label": @"Save to Camera Roll"},
                     @{@"key": @"togglePinchZoom", @"label": @"Toggle PinchZoom"},
                     @{@"key": @"toggleAutoScaleMinMax", @"label": @"Toggle auto scale min/max"},
                     ];

    _chartView.delegate = self;

    [self setupBarLineChartView:_chartView];

    [self setData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setData
{

    RLMRealm *realm = [RLMRealm defaultRealm];

    RLMResults *results = [RealmDemoData allObjectsInRealm:realm];

    RealmBarDataSet *set = [[RealmBarDataSet alloc] initWithResults:results xValueField:@"xValue" yValueField:@"yValue"];
    set.colors = @[[ChartColorTemplates colorFromString:@"#FF5722"],
                   [ChartColorTemplates colorFromString:@"#03A9F4"]];
    set.label = @"Realm BarDataSet";

    NSArray<id <IChartDataSet>> *dataSets = @[set];

    BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
    [self styleData:data];

    _chartView.fitBars = YES;
    _chartView.data = data;
    [_chartView zoomWithScaleX:5.f scaleY:1.f x:0.f y:0.f];

    [_chartView animateWithYAxisDuration:1.4 easingOption:ChartEasingOptionEaseInOutQuart];
}

- (void)optionTapped:(NSString *)key
{
    [super handleOption:key forChartView:_chartView];
}

#pragma mark - ChartViewDelegate

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry highlight:(ChartHighlight * __nonnull)highlight
{
    NSLog(@"chartValueSelected");
}

- (void)chartValueNothingSelected:(ChartViewBase * __nonnull)chartView
{
    NSLog(@"chartValueNothingSelected");
}

@end


text:
"""
It's possible to use multiple types of host pythons to create virtual environments and all should work:

- host installation
- invoking from a venv (if Python 3.3+)
- invoking from an old style virtualenv (<17.0.0)
- invoking from our own venv
"""

import subprocess
import sys
from pathlib import Path
from subprocess import Popen

import pytest

from virtualenv.discovery.py_info import PythonInfo
from virtualenv.info import IS_WIN
from virtualenv.run import cli_run

CURRENT = PythonInfo.current_system()

# noinspection PyUnusedLocal
def root(tmp_path_factory, session_app_data):  # noqa: U100
    return CURRENT.system_executable

def venv(tmp_path_factory, session_app_data):
    if CURRENT.is_venv:
        return sys.executable
    elif CURRENT.version_info.major == 3:
        root_python = root(tmp_path_factory, session_app_data)
        dest = tmp_path_factory.mktemp("venv")
        process = Popen([str(root_python), "-m", "venv", "--without-pip", str(dest)])
        process.communicate()
        # sadly creating a virtual environment does not tell us where the executable lives in general case
        # so discover using some heuristic
        exe_path = CURRENT.discover_exe(prefix=str(dest)).original_executable
        return exe_path

def old_virtualenv(tmp_path_factory, session_app_data):
    if CURRENT.is_old_virtualenv:
        return CURRENT.executable
    else:
        env_for_old_virtualenv = tmp_path_factory.mktemp("env-for-old-virtualenv")
        result = cli_run(["--no-download", "--activators", "", str(env_for_old_virtualenv), "--no-periodic-update"])
        # noinspection PyBroadException
        try:
            process = Popen(
                [
                    str(result.creator.script("pip")),
                    "install",
                    "--no-index",
                    "--disable-pip-version-check",
                    str(Path(__file__).resolve().parent / "virtualenv-16.7.9-py2.py3-none-any.whl"),
                    "-v",
                ],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            _, __ = process.communicate()
            assert not process.returncode
        except Exception:
            return RuntimeError("failed to install old virtualenv")
        # noinspection PyBroadException
        try:
            old_virtualenv_at = tmp_path_factory.mktemp("old-virtualenv")
            cmd = [
                str(result.creator.script("virtualenv")),
                str(old_virtualenv_at),
                "--no-pip",
                "--no-setuptools",
                "--no-wheel",
            ]
            process = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            _, __ = process.communicate()
            assert not process.returncode
            if result.creator.interpreter.implementation == "PyPy" and IS_WIN:
                # old virtualenv creates pypy paths wrong on windows, so have to hardcode it
                return str(old_virtualenv_at / "bin" / "pypy.exe")
            exe_path = CURRENT.discover_exe(session_app_data, prefix=str(old_virtualenv_at)).original_executable
            return exe_path
        except Exception as exception:
            return RuntimeError(f"failed to create old virtualenv {exception}")

PYTHON = {
    "root": root,
    "venv": venv,
    "old_virtualenv": old_virtualenv,
}

@pytest.fixture(params=list(PYTHON.values()), ids=list(PYTHON.keys()), scope="session")
def python(request, tmp_path_factory, session_app_data):
    result = request.param(tmp_path_factory, session_app_data)
    if isinstance(result, Exception):
        pytest.skip(f"could not resolve interpreter based on {request.param.__name__} because {result}")
    if result is None:
        pytest.skip(f"requires interpreter with {request.param.__name__}")
    return result


text:
        <form name="form">

 Single Image with validations

Select

        </form>


text:
function getValidateRequired(key) {
    switch (key) {
        case "friendlyName":
            return true;
        default:
            return false;
    }
}

function getTabMapping(key) {
    switch (key) {
        case "license":
            return 3;
        case "releaseNotes":
            return 4;
        default:
            return 0;
    }
}

export function validationMapExtensionBeingEdited(extensionBeingEdited) {
    let _extensionBeingEdited = Object.assign({}, extensionBeingEdited);
    Object.keys(_extensionBeingEdited).forEach((key) => {
        let validateRequired = getValidateRequired(key);
        let tabMapping = getTabMapping(key);
        _extensionBeingEdited[key] = {
            value: _extensionBeingEdited[key] && !_extensionBeingEdited[key].hasOwnProperty("value") ? _extensionBeingEdited[key] : _extensionBeingEdited[key] && _extensionBeingEdited[key].value,
            validateRequired,
            tabMapping,
            error: false
        };
    });
    return _extensionBeingEdited;
}

export function getVersionDropdownValues() {
    let values = [];
    for (let i = 0; i < 100; i++) {
        values.push({
            label: formatVersionNumber(i),
            value: i
        });
    }
    return values;
}
export function formatVersionNumber(n) {
    return n > 9 ? "" + n : "0" + n;
}


text:
package com.graphhopper.routing;

import com.carrotsearch.hppc.IntArrayList;
import com.graphhopper.routing.ev.*;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.TraversalMode;
import com.graphhopper.routing.weighting.DefaultTurnCostProvider;
import com.graphhopper.routing.weighting.FastestWeighting;
import com.graphhopper.routing.weighting.TurnCostProvider;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.BaseGraph;
import com.graphhopper.storage.Graph;
import com.graphhopper.util.GHUtility;
import com.graphhopper.util.PMap;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.provider.ArgumentsSource;

import java.util.List;
import java.util.stream.Stream;

import static com.graphhopper.util.GHUtility.updateDistancesFor;
import static org.junit.jupiter.api.Assertions.*;

public class AlternativeRouteTest {

    private static final class Fixture {
        final Weighting weighting;
        final TraversalMode traversalMode;
        final BaseGraph graph;
        final BooleanEncodedValue accessEnc;
        final DecimalEncodedValue speedEnc;
        final DecimalEncodedValue turnCostEnc;

        public Fixture(TraversalMode tMode) {
            this.traversalMode = tMode;
            accessEnc = new SimpleBooleanEncodedValue("access", true);
            speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false);
            turnCostEnc = TurnCost.create("car", 1);

            EncodingManager em = EncodingManager.start().add(accessEnc).add(speedEnc).add(turnCostEnc).build();
            graph = new BaseGraph.Builder(em).withTurnCosts(true).create();
            TurnCostProvider turnCostProvider = tMode.isEdgeBased()
                    ? new DefaultTurnCostProvider(turnCostEnc, graph.getTurnCostStorage())
                    : TurnCostProvider.NO_TURN_COST_PROVIDER;
            weighting = new FastestWeighting(accessEnc, speedEnc, turnCostProvider);
        }

        @Override
        public String toString() {
            return traversalMode.toString();
        }
    }

    private static class FixtureProvider implements ArgumentsProvider {
        @Override
        public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception {
            return Stream.of(
                    new Fixture(TraversalMode.NODE_BASED),
                    new Fixture(TraversalMode.EDGE_BASED)
            ).map(Arguments::of);
        }
    }

    public static void initTestGraph(Graph graph, BooleanEncodedValue accessEnc, DecimalEncodedValue speedEnc) {
        /* 9
         _/\
         1  2-3-4-10
         \   /   \
         5--6-7---8

         */
        GHUtility.setSpeed(60, 60, accessEnc, speedEnc,
                graph.edge(1, 9).setDistance(1),
                graph.edge(9, 2).setDistance(1),
                graph.edge(2, 3).setDistance(1),
                graph.edge(3, 4).setDistance(1),
                graph.edge(4, 10).setDistance(1),
                graph.edge(5, 6).setDistance(1),
                graph.edge(6, 7).setDistance(1),
                graph.edge(7, 8).setDistance(1),
                graph.edge(1, 5).setDistance(2),
                graph.edge(6, 3).setDistance(1),
                graph.edge(4, 8).setDistance(1));

        updateDistancesFor(graph, 5, 0.00, 0.05);
        updateDistancesFor(graph, 6, 0.00, 0.10);
        updateDistancesFor(graph, 7, 0.00, 0.15);
        updateDistancesFor(graph, 8, 0.00, 0.25);

        updateDistancesFor(graph, 1, 0.05, 0.00);
        updateDistancesFor(graph, 9, 0.10, 0.05);
        updateDistancesFor(graph, 2, 0.05, 0.10);
        updateDistancesFor(graph, 3, 0.05, 0.15);
        updateDistancesFor(graph, 4, 0.05, 0.25);
        updateDistancesFor(graph, 10, 0.05, 0.30);
    }

    @ParameterizedTest
    @ArgumentsSource(FixtureProvider.class)
    public void testCalcAlternatives(Fixture f) {
        initTestGraph(f.graph, f.accessEnc, f.speedEnc);
        PMap hints = new PMap().
                putObject("alternative_route.max_share_factor", 0.5).
                putObject("alternative_route.max_weight_factor", 2).
                putObject("alternative_route.max_exploration_factor", 1.3);
        AlternativeRoute altDijkstra = new AlternativeRoute(f.graph, f.weighting, f.traversalMode, hints);
        List<AlternativeRoute.AlternativeInfo> pathInfos = altDijkstra.calcAlternatives(5, 4);
        checkAlternatives(pathInfos);
        assertEquals(2, pathInfos.size());

        DijkstraBidirectionRef dijkstra = new DijkstraBidirectionRef(f.graph, f.weighting, f.traversalMode);
        Path bestPath = dijkstra.calcPath(5, 4);

        Path bestAlt = pathInfos.get(0).getPath();
        Path secondAlt = pathInfos.get(1).getPath();

        assertEquals(bestPath.calcNodes(), bestAlt.calcNodes());
        assertEquals(bestPath.getWeight(), bestAlt.getWeight(), 1e-3);

        assertEquals(IntArrayList.from(5, 6, 3, 4), bestAlt.calcNodes());

        // Note: here plateau is longer, even longer than optimum, but path is longer
        // so which alternative is better? longer plateau.weight with bigger path.weight or smaller path.weight with smaller plateau.weight
        // assertEquals(IntArrayList.from(5, 1, 9, 2, 3, 4), secondAlt.calcNodes());
        assertEquals(IntArrayList.from(5, 6, 7, 8, 4), secondAlt.calcNodes());
        assertEquals(1667.9, secondAlt.getWeight(), .1);
    }

    @ParameterizedTest
    @ArgumentsSource(FixtureProvider.class)
    public void testCalcAlternatives2(Fixture f) {
        initTestGraph(f.graph, f.accessEnc, f.speedEnc);
        PMap hints = new PMap().putObject("alternative_route.max_paths", 3).
                putObject("alternative_route.max_share_factor", 0.7).
                putObject("alternative_route.min_plateau_factor", 0.15).
                putObject("alternative_route.max_weight_factor", 2).
                putObject("alternative_route.max_exploration_factor", 1.8);
        AlternativeRoute altDijkstra = new AlternativeRoute(f.graph, f.weighting, f.traversalMode, hints);
        List<AlternativeRoute.AlternativeInfo> pathInfos = altDijkstra.calcAlternatives(5, 4);
        checkAlternatives(pathInfos);
        assertEquals(3, pathInfos.size());

        // result is sorted based on the plateau to full weight ratio
        assertEquals(IntArrayList.from(5, 6, 3, 4), pathInfos.get(0).getPath().calcNodes());
        assertEquals(IntArrayList.from(5, 6, 7, 8, 4), pathInfos.get(1).getPath().calcNodes());
        assertEquals(IntArrayList.from(5, 1, 9, 2, 3, 4), pathInfos.get(2).getPath().calcNodes());
        assertEquals(2416.0, pathInfos.get(2).getPath().getWeight(), .1);
    }

    private void checkAlternatives(List<AlternativeRoute.AlternativeInfo> alternativeInfos) {
        assertFalse(alternativeInfos.isEmpty(), "alternativeInfos should contain alternatives");
        AlternativeRoute.AlternativeInfo bestInfo = alternativeInfos.get(0);
        for (int i = 1; i < alternativeInfos.size(); i++) {
            AlternativeRoute.AlternativeInfo a = alternativeInfos.get(i);
            if (a.getPath().getWeight() < bestInfo.getPath().getWeight())
                fail("alternative is not longer -> " + a + " vs " + bestInfo);

            if (a.getShareWeight() > bestInfo.getPath().getWeight()
                    || a.getShareWeight() > a.getPath().getWeight())
                fail("share or sortby incorrect -> " + a + " vs " + bestInfo);
        }
    }

    @ParameterizedTest
    @ArgumentsSource(FixtureProvider.class)
    public void testDisconnectedAreas(Fixture f) {
        initTestGraph(f.graph, f.accessEnc, f.speedEnc);

        // one single disconnected node
        updateDistancesFor(f.graph, 20, 0.00, -0.01);

        PMap hints = new PMap().putObject("alternative_route.max_exploration_factor", 1);
        AlternativeRoute altDijkstra = new AlternativeRoute(f.graph, f.weighting, f.traversalMode, hints);
        Path path = altDijkstra.calcPath(1, 20);
        assertFalse(path.isFound());

        // make sure not the full graph is traversed!
        assertEquals(3, altDijkstra.getVisitedNodes());
    }
}