text:
[![Build Status](https://travis-ci.org/M-Porter/small-state.svg?branch=master)](https://travis-ci.org/M-Porter/small-state)

**small-state** is a minimalistic state management library which encourages
immutability and strict unidirectional data flow in frontend applications.
This library was created for use in Backbone and Marionette applications to
provide a predictable state container.

> My goal was to create a state management library with minimal API but
> completely predictable behavior, so it is possible to implement logging, hot
> reloading, time travel, universal apps, record and replay, without any buy-in
> from the developer."
>
> — Dan Abramov on Redux

## Influences

- [Redux](http://redux.js.org/)
- [Flux](https://facebook.github.io/flux/)
- [MobX](https://mobxjs.github.io/mobx/)

If you have used any of the libraries above, the action/reducer pattern in
this library will come easily to you.

## Features
- Pure state reducers
- No side effects
- Immutable State based on [seamless-immutable](https://github.com/rtfeldman/seamless-immutable)
- Promise based
- Minimal event system for registering state change hooks

## Installation

`npm install https://github.com/M-Porter/small-state`

This assumes you are using npm as your package manager.

**small-state** was written in ES2015 and currently is not precompiled before
distribution so Babel is currently needed to use. Currently, only
`babel-preset-2015` is required to use the library but more may be included
in the future. View `.babelrc` with each release to stay up to date with
required Babel plugins.

If you wish to use the UMD or CommonJS versions of the library, clone down
the library and run `npm install` and `npm run build`. This will build the
UMD, CommonJS and ES versions of the library.

## Usage

### Setup

```js
import Marionette, { Application } from 'backbone.marionette';
import { createStore } from 'small-state';

const app = new Application();
app.appStore = createStore();

export default app;
```

The `createStore` call also accepts an object as a parameter. If passed,
this object will become the inital state. For example...

```js
app.appStore = createStore({
  foo: 'bar',
  someList: [1, 2, 3, 4, 5]
});
```
Or how I do it...

```js
app.appStore = createStore(window.INITIAL_STATE);
```

**small-state** does not need to be attached to a Marionette application
instance to work. It can also be mixed in with a plain javascript object.

```js
import { createStore } from 'small-state';

const app = {};
app.appStore = createStore();

export default app;
```

### Working with the store

The store instance has 3 exposed functions: `getStore()`, `getState()`,
and `dispatch()`. The `getState()` function is an alias for
`getStore().getState()`.

```js
// Assume this for the code blocks below
import { createStore } from 'small-state';

const store = createStore();
```

The `getStore()` function returns the current store object which exposes useful
functions such as `on()`, `off()`, and `trigger()` which allows you to add
listener events to the store which can be trigger from the reducers.

```js
// Add listen event to the store
store.getStore().on('some:event', () => doSomething());

// Trigger event
store.getStore().trigger('some:event');

// Remove the event since small-state does not clean up after itself
store.getStore().off('some:event');
```

The `dispatch()` function is used to actually update the state. We will get
into how to actually update the state in the next section
(_"Mutating the state"_) below.

```js
const store = store.getStore();

store.dispatch(someReducerFunction); // Dispatch returns a thenable
```

### Mutating the state

The most important part about **small-state**, and what you're probably here
for, is how to set and update the state of your application. You can assume this
is set for the rest of the code in this section:

```js
import { createStore } from 'small-state';

const store = createStore({
  count: 0
});
```

In **small-state**, the state is updated through _reducers_ which are
_dispatched_ from the `store` object. The simplest of reducers could look like this:

```js
const incrementCounter = ({ state, resolve }) => {
  const newState = state.update('count', x => x + 1);
  resolve(newState);
}

const decrementCounter = ({ state, resolve }) => {
  const newState = state.update('count', x => x + 1);
  resolve(newState);
}

const resetCounter = ({ state, resolve }) => {
  const newState = state.setIn('count', 0);
  resolve(newState);
}
```

These reducers are then dispatched like so:

```js
store.dispatch(incrementCounter)
  .then(state => console.log(state.count)); // Prints out '1'

store.dispatch(incrementCounter)
  .then(state => console.log(state.count)); // Prints out '2'

store.dispatch(decrementCounter)
  .then(state => console.log(state.count)); // Prints out '1'

store.dispatch(resetCounter)
  .then(state => console.log(state.count)); // Prints out '0'
```

Notice that the function is passed to the dispatcher, not called directly. This
is because the dispatcher inject `store`, `state`, `payload`, `resolve`, and
`reject` into the reducer allowing for better encapsulation.

It is extremely important to **always** `resolve(state)` in each reducer after
the state was updated and modified. This is because the reducers are meant
to be pure functions with the state being immutable. If the state is not
resolved, the state will not be updated.

### Events

After every reducer is resolved, the event `state:change` is triggered whether
or not the state was actually updated or not. Additionally, you can define your
own events in the reducers. This is useful if you prefer to use events over
thenables.

```js
// reducer with event
const incrementCounter = ({ state, store, resolve }) => {
  const newState = state.update('count', x => x + 1);

  store.trigger('count:incremented');

  resolve(newState);
}

// store and listener callbacks
store.getStore().on('count:incremented', () => console.log(store.getState().count));

store.dispatch(incrementCounter);

// Important to remove your events if you are creating them inside of destroyable
// js objects such as views in Backbone or Marionette.
store.getStore().off('count:incremented');
```

Events can be useful but can lead to issues. One of those issues is that
there is no guarentee that the state has been updated at the time of event
triggers within your reducers. To ensure that your events are triggered _after_
the state has been updated, you can pass the events you wish to be triggered
alongside the resolved state.

[Much like how functions can only return single values, promises can only resolve
a single value.](http://stackoverflow.com/a/28703648) To get around this and to
allow for resolving of state and events, the resolved value must be an array.

```js
// Incorrect
resolve(
  newState,
  ['event1', 'event2']
);

// Incorrect
resolve([
  newState,
  'event1',
  'event2'
]);

// Correct
resolve([
  newState,
  ['event1', 'event2']
]);
```

```js
const incrementCounter = ({ state, store, resolve }) => {
  const newState = state.update('count', x => x + 1);

  // 'count:incremented' will now be updated AFTER the new state has been set
  resolve([newState, ['count:incremented']]);
}
```

## Connecting the store to your views

**small-state** comes with a helper function to automatically connect your store
and state to your views so that your views always have the latest state.

```js
import View from 'your/View';
import { connectStoreToView, createStore } from 'small-state';

const appStore = createStore();
const ConnectedView = connectStoreToView(View, appStore);

// view now has the property stateContainer (aliased as sc$)
const view = new ConnectedView();
```

In the above code block, `view` now has the property `stateContainer`, which can
also be accessed as the property `sc$`. The `stateContainer` in the views behave
slightly different than that of the small-state store.

_Assume `const view = new (connectStoreToView(View, appStore))` and `const store =
createStore()` for the points below:_

- `view.storeContainer` return the store object **but no methods can be invoked
  on it**. This is because the `storeContainer` property is a `Proxy` of the
  small-state store object.
- `view.storeContainer.store` is the same as `store` which has the methods
  `getState()`, `getStore()`, and `dispatch()`
- `view.storeContainer.store.getStore()` is the same as `store.getStore()` which
  has the methods `on()`, `of(), `trigger()`, and `getState()`
- `view.storeContainer.state` is the same as `store.getState()`


text: OxideMod Corrosion

redpajama_set_name: RedPajamaGithub


text:
Back

Color Themes

Framework7 comes with default 10 iOS color themes set and three layout color themes (default, dark and pure white):

Choose Layout Theme

Choose Color Theme


text:
/**
 * Created by feichongzheng on 16/12/15.
 */
import React, {Component} from 'react';
import Menu from 'antd/lib/menu';
import 'FayAntd/menu/style/index.js';
import 'FayAntd/icon/style/index.js';
import PropTypes from 'prop-types';

let pathname;

class NavLeft extends Component {

    constructor (props) {
        super(props);
        const location = this.props.location;
        pathname = location.pathname;
        pathname = pathname.indexOf('/') === 0 ? pathname : '/' + pathname;
        this.state = {
            current: pathname,
            openKeys: null,
            html: [],
        };
    }

    handleClick = (e) => {
        const history = this.props.history;
        let key = e.key;
        if (key !== undefined) {
            this.setState({
                current: key,
            });
            this.props.changeNavTopCurrent(key);
            history.push(key, null);
        }
    };

    render () {
        let html;
        if (this.state.html.length === 0) {
            html =
{this.state.html}
;
        } else {
            html = <Menu onClick={this.handleClick}
                     style={{ width: 150 }}
                     defaultOpenKeys={this.state.openKeys}
                     selectedKeys={[this.state.current]}
                     mode="inline"
                     id="nav-left-menu">
                     {this.state.html}
            </Menu>;
        }
        return (

{html}

        );
    }
}

NavLeft.propTypes = {
    location: PropTypes.any,
    history: PropTypes.object,
    changeNavTopCurrent: PropTypes.func,
    changeContentStyle: PropTypes.func,
};

export default NavLeft;


text:
Errors faced during installation/configuration

First, read the instructions at INSTALL.md !

* Some python libraries where missing from the 'as is' Ubuntu 13.10 install and had to be installed:

````
sudo apt-get install python-dev
sudo apt-get install libldap2-dev
sudo apt-get install libsasl2-dev
sudo apt-get install python-ldap
sudo apt-get install gettext # to compile messages
sudo apt-get install libapache2-mod-wsgi # if using apache
pip install uwsgi
````

* Helios original settings file come with
    'django.contrib.auth',
    'django.contrib.contenttypes',
apps commented out.

When I've tried to login using ldap user and password, I've got the following error:

```
DatabaseError: relation "auth_user" does not exist
LINE 1: ...ser"."last_login", "auth_user"."date_joined" FROM "auth_user...

...
Exception Type:     DatabaseError
Exception Value:

current transaction is aborted, commands ignored until end of transaction block
```
Enabling those apps solved the problem.

* Vote hash was not saving

Everything was working fine, except that the vote hash wasn't being saved.  This was happening because I didn't started the background job processor (issue kindly answered by Ben Adida)

Run the following command in a separate terminal window:

````
python manage.py celeryd
````

Dont' forget to install rabbitmq (https://www.rabbitmq.com/)

````
sudo apt-get install rabbitmq-server
````

* module' object has no attribute 'STATUS_UPDATES

Your auth model needs to declare STATUS_UPDATES


text:
extern zend_class_entry *zendxml_exception_runtimeexception_ce;

ZEPHIR_INIT_CLASS(ZendXml_Exception_RuntimeException);


text:
IMPLEMENT_TEST_SUITE_START(Scope);
REGISTER_TEST_CASE(Scope, GlobalScope);
REGISTER_TEST_CASE(Scope, ParentScope);
REGISTER_TEST_CASE(Scope, ChildScopes);
REGISTER_TEST_CASE(Scope, NameSpace);
REGISTER_TEST_CASE(Scope, Class);
IMPLEMENT_TEST_SUITE_END;

IMPLEMENT_TEST_SETUP(Scope)
{
}

IMPLEMENT_TEST_TEARDOWN(Scope)
{
  cGlobalScope::FreeGlobalScope();
}

IMPLEMENT_TEST_CASE(Scope, GlobalScope)
{
  cScope* pScope = cGlobalScope::GetGlobalScope();
  TEST_NOT_NULL(pScope);
  TEST(pScope->IsGlobalScope());
}

IMPLEMENT_TEST_CASE(Scope, ParentScope)
{
  cScope* pScope = new cScope(cGlobalScope::GetGlobalScope());

  TEST_NOT_NULL(pScope);
  TEST_NOT_NULL(pScope->GetParentScope());
  TEST(pScope->GetParentScope()->IsGlobalScope());

  cScope* pScope2 = new cScope(pScope);

  TEST_NOT_NULL(pScope2);
  TEST_NOT_NULL(pScope2->GetParentScope());
  TEST(pScope2->GetParentScope() != pScope->GetParentScope());
  TEST_EQUALS(pScope2->GetParentScope(), pScope);
}

IMPLEMENT_TEST_CASE(Scope, ChildScopes)
{
  cScope* pScope = new cScope(cGlobalScope::GetGlobalScope());
  tScopeList& ChildScopes = cGlobalScope::GetGlobalScope()->GetChildScopes();
  TEST_EQUALS(1, ChildScopes.size());

  cScope* pScope2 = new cScope(cGlobalScope::GetGlobalScope());
  TEST_EQUALS(2, ChildScopes.size());

  cScope* pScope3 = new cScope(pScope);
  TEST_EQUALS(1, pScope->GetChildScopes().size());
  TEST_EQUALS(0, pScope2->GetChildScopes().size());
  TEST_EQUALS(0, pScope3->GetChildScopes().size());
}

IMPLEMENT_TEST_CASE(Scope, NameSpace)
{
  cGlobalScope* pGlobalScope = cGlobalScope::GetGlobalScope();

  TEST_NOT_NULL(pGlobalScope);
  TEST_EQUALS("", pGlobalScope->GetName());

  cNameSpace* pNameSpace = new cNameSpace("Test", cGlobalScope::GetGlobalScope());
  TEST_EQUALS("Test", pNameSpace->GetName());

  tScopeList& ChildScopes = cGlobalScope::GetGlobalScope()->GetChildScopes();
  TEST_EQUALS(1, ChildScopes.size());

  pNameSpace->AddNameSpace(new cNameSpace("TestNameSpace", pNameSpace));
  TEST_EQUALS(1, pNameSpace->GetChildScopes().size());
  TEST_EQUALS(1, pNameSpace->GetNameSpaces().size());

  cNameSpace* pTestNameSpace = pNameSpace->GetNameSpace("TestNameSpace");
  TEST_NOT_NULL(pTestNameSpace);
  TEST_EQUALS("TestNameSpace", pTestNameSpace->GetName());
}

IMPLEMENT_TEST_CASE(Scope, Class)
{
  cGlobalScope* pGlobalScope = cGlobalScope::GetGlobalScope();
  cClass* pClass = new cClass("cTest", pGlobalScope);
  TEST_EQUALS("cTest", pClass->GetName());
  TEST_EQUALS(pGlobalScope, pClass->GetParentScope());
  pGlobalScope->AddClass(pClass);
  TEST_EQUALS(pGlobalScope->GetClass("cTest"), pClass);
  pGlobalScope->AddClass(new cClass("cClass", pGlobalScope));
  TEST_EQUALS(pGlobalScope->GetClass("cTest"), pClass);
  TEST_NOT_NULL(pGlobalScope->GetClass("cClass"));
}


text:
<?php

/* SonataSeoBundle:Block:block_twitter_hashtag_button.html.twig */
class __TwigTemplate_737f358e25f75e3608b52e90a710ac4dcf0ff4c015048ca695afda2db3481bcb extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->blocks = array(
            'block' => array($this, 'block_block'),
        );
    }

    protected function doGetParent(array $context)
    {
        // line 11
        return $this->loadTemplate($this->getAttribute($this->getAttribute((isset($context["sonata_block"]) ? $context["sonata_block"] : null), "templates", array()), "block_base", array()), "SonataSeoBundle:Block:block_twitter_hashtag_button.html.twig", 11);
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
    }

    // line 13
    public function block_block($context, array $blocks = array())
    {
        // line 14
        ob_start();
        // line 15
        echo "
    ";
        // line 16
        if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "hashtag", array())) {
            // line 17
            echo "
        env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "hashtag", array()), "html", null, true);
            echo "\" class=\"twitter-hashtag-button\"
            ";
            // line 19
            if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "text", array())) {
                echo "data-text=\"";
                echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "text", array()), "html", null, true);
                echo "\"";
            }
            // line 20
            echo "            ";
            if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "recommend", array())) {
                echo "data-related=\"";
                echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "recommend", array()), "html", null, true);
                echo "\"";
            }
            // line 21
            echo "            ";
            if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "url", array())) {
                echo "data-url=\"";
                echo twig_escape_filter($this->env, $this->getAttribute((isset($context["setting"]) ? $context["setting"] : null), "url", array()), "html", null, true);
                echo "\"";
            }
            // line 22
            echo "            ";
            if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "large_button", array())) {
                echo "data-size=\"large\"";
            }
            // line 23
            echo "            data-lang=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "language", array()), "html", null, true);
            echo "\"
            ";
            // line 24
            if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "opt_out", array())) {
                echo "data-dnt=\"true\"";
            }
            echo ">
            Tweet ";
            // line 25
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : null), "hashtag", array()), "html", null, true);
            echo "

    ";
        }
        // line 29
        echo "
";
        echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
    }

    public function getTemplateName()
    {
        return "SonataSeoBundle:Block:block_twitter_hashtag_button.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  87 => 29,  80 => 25,  74 => 24,  69 => 23,  64 => 22,  57 => 21,  50 => 20,  44 => 19,  40 => 18,  37 => 17,  35 => 16,  32 => 15,  30 => 14,  27 => 13,  18 => 11,);
    }
}
/* {#*/
/* */
/* This file is part of the Sonata package.*/
/* */
/* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>*/
/* */
/* For the full copyright and license information, please view the LICENSE*/
/* file that was distributed with this source code.*/
/* */
/* #}*/
/* {% extends sonata_block.templates.block_base %}*/
/* */
/* {% block block %}*/
/* {% spaceless %}*/
/* */
/*     {% if settings.hashtag %}*/
/* */
/*         <a href="https://twitter.com/intent/tweet?button_hashtag={{ settings.hashtag }}" class="twitter-hashtag-button"*/
/*             {% if settings.text %}data-text="{{ settings.text }}"{% endif %}*/
/*             {% if settings.recommend %}data-related="{{ settings.recommend }}"{% endif %}*/
/*             {% if settings.url %}data-url="{{ setting.url }}"{% endif %}*/
/*             {% if settings.large_button %}data-size="large"{% endif %}*/
/*             data-lang="{{ settings.language }}"*/
/*             {% if settings.opt_out %}data-dnt="true"{% endif %}>*/
/*             Tweet {{ settings.hashtag }}*/
/*         */
/* */
/*     {% endif %}*/
/* */
/* {% endspaceless %}*/
/* {% endblock %}*/
/* */


text:
package org.kurento.tutorial.helloworld;

import java.io.IOException;

import org.kurento.client.EndOfStreamEvent;
import org.kurento.client.ErrorEvent;
import org.kurento.client.EventListener;
import org.kurento.client.IceCandidate;
import org.kurento.client.IceCandidateFoundEvent;
import org.kurento.client.KurentoClient;
import org.kurento.client.MediaPipeline;
import org.kurento.client.MediaProfileSpecType;
import org.kurento.client.MediaType;
import org.kurento.client.PausedEvent;
import org.kurento.client.PlayerEndpoint;
import org.kurento.client.RecorderEndpoint;
import org.kurento.client.RecordingEvent;
import org.kurento.client.StoppedEvent;
import org.kurento.client.WebRtcEndpoint;
import org.kurento.jsonrpc.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

/**
 * Hello World with recording handler (application and media logic).
 *
 * @author Boni Garcia (bgarcia@gsyc.es)
 * @author David Fernandez (d.fernandezlop@gmail.com)
 * @author Radu Tom Vlad (rvlad@naevatec.com)
 * @author Ivan Gracia (igracia@kurento.org)
 * @since 6.1.1
 */
public class HelloWorldRecHandler extends TextWebSocketHandler {

  private static final String RECORDER_FILE_PATH = "file:///tmp/HelloWorldRecorded.webm";

  private final Logger log = LoggerFactory.getLogger(HelloWorldRecHandler.class);
  private static final Gson gson = new GsonBuilder().create();

  @Autowired
  private UserRegistry registry;

  @Autowired
  private KurentoClient kurento;

  @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class);

    log.debug("Incoming message: {}", jsonMessage);

    UserSession user = registry.getBySession(session);
    if (user != null) {
      log.debug("Incoming message from user '{}': {}", user.getId(), jsonMessage);
    } else {
      log.debug("Incoming message from new user: {}", jsonMessage);
    }

    switch (jsonMessage.get("id").getAsString()) {
      case "start":
        start(session, jsonMessage);
        break;
      case "stop":
        if (user != null) {
          user.stop();
        }
      case "stopPlay":
        if (user != null) {
          user.release();
        }
        break;
      case "play":
        play(user, session, jsonMessage);
        break;
      case "onIceCandidate": {
        JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject();

        if (user != null) {
          IceCandidate candidate = new IceCandidate(jsonCandidate.get("candidate").getAsString(),
              jsonCandidate.get("sdpMid").getAsString(),
              jsonCandidate.get("sdpMLineIndex").getAsInt());
          user.addCandidate(candidate);
        }
        break;
      }
      default:
        sendError(session, "Invalid message with id " + jsonMessage.get("id").getAsString());
        break;
    }
  }

  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    super.afterConnectionClosed(session, status);
    registry.removeBySession(session);
  }

  private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {

      // 1. Media logic (webRtcEndpoint in loopback)
      MediaPipeline pipeline = kurento.createMediaPipeline();
      WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
      webRtcEndpoint.connect(webRtcEndpoint);

      MediaProfileSpecType profile = getMediaProfileFromMessage(jsonMessage);

      RecorderEndpoint recorder = new RecorderEndpoint.Builder(pipeline, RECORDER_FILE_PATH)
      .withMediaProfile(profile).build();

      // Error listeners.
      pipeline.addErrorListener(new EventListener<ErrorEvent>() {
        @Override
        public void onEvent(ErrorEvent ev) {
          log.error("[MediaPipeline::ErrorEvent] Error code {}: '{}', source: {}, timestamp: {}, tags: {}, description: {}",
              ev.getErrorCode(), ev.getType(), ev.getSource().getName(),
              ev.getTimestampMillis(), ev.getTags(), ev.getDescription());
            sendError(session, "[MediaPipeline] " + ev.getDescription());
        }
      });
      webRtcEndpoint.addErrorListener(new EventListener<ErrorEvent>() {
        @Override
        public void onEvent(ErrorEvent ev) {
          log.error("[WebRtcEndpoint::ErrorEvent] Error code {}: '{}', source: {}, timestamp: {}, tags: {}, description: {}",
              ev.getErrorCode(), ev.getType(), ev.getSource().getName(),
              ev.getTimestampMillis(), ev.getTags(), ev.getDescription());
            sendError(session, "[WebRtcEndpoint] " + ev.getDescription());
        }
      });
      recorder.addErrorListener(new EventListener<ErrorEvent>() {
        @Override
        public void onEvent(ErrorEvent ev) {
          log.error("[RecorderEndpoint::ErrorEvent] Error code {}: '{}', source: {}, timestamp: {}, tags: {}, description: {}",
              ev.getErrorCode(), ev.getType(), ev.getSource().getName(),
              ev.getTimestampMillis(), ev.getTags(), ev.getDescription());
            sendError(session, "[RecorderEndpoint] " + ev.getDescription());
        }
      });

      recorder.addRecordingListener(new EventListener<RecordingEvent>() {

        @Override
        public void onEvent(RecordingEvent event) {
          JsonObject response = new JsonObject();
          response.addProperty("id", "recording");
          try {
            synchronized (session) {
              session.sendMessage(new TextMessage(response.toString()));
            }
          } catch (IOException e) {
            log.error(e.getMessage());
          }
        }

      });

      recorder.addStoppedListener(new EventListener<StoppedEvent>() {

        @Override
        public void onEvent(StoppedEvent event) {
          JsonObject response = new JsonObject();
          response.addProperty("id", "stopped");
          try {
            synchronized (session) {
              session.sendMessage(new TextMessage(response.toString()));
            }
          } catch (IOException e) {
            log.error(e.getMessage());
          }
        }

      });

      recorder.addPausedListener(new EventListener<PausedEvent>() {

        @Override
        public void onEvent(PausedEvent event) {
          JsonObject response = new JsonObject();
          response.addProperty("id", "paused");
          try {
            synchronized (session) {
              session.sendMessage(new TextMessage(response.toString()));
            }
          } catch (IOException e) {
            log.error(e.getMessage());
          }
        }

      });

      connectAccordingToProfile(webRtcEndpoint, recorder, profile);

      // 2. Store user session
      UserSession user = new UserSession(session);
      user.setMediaPipeline(pipeline);
      user.setWebRtcEndpoint(webRtcEndpoint);
      user.setRecorderEndpoint(recorder);
      registry.register(user);

      // 3. SDP negotiation
      String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
      String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

      // 4. Gather ICE candidates
      webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

        @Override
        public void onEvent(IceCandidateFoundEvent event) {
          JsonObject response = new JsonObject();
          response.addProperty("id", "iceCandidate");
          response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
          try {
            synchronized (session) {
              session.sendMessage(new TextMessage(response.toString()));
            }
          } catch (IOException e) {
            log.error(e.getMessage());
          }
        }
      });

      JsonObject response = new JsonObject();
      response.addProperty("id", "startResponse");
      response.addProperty("sdpAnswer", sdpAnswer);

      synchronized (user) {
        session.sendMessage(new TextMessage(response.toString()));
      }

      webRtcEndpoint.gatherCandidates();

      recorder.record();
    } catch (Throwable t) {
      log.error("Start error", t);
      sendError(session, t.getMessage());
    }
  }

  private MediaProfileSpecType getMediaProfileFromMessage(JsonObject jsonMessage) {

    MediaProfileSpecType profile;
    switch (jsonMessage.get("mode").getAsString()) {
      case "audio-only":
        profile = MediaProfileSpecType.WEBM_AUDIO_ONLY;
        break;
      case "video-only":
        profile = MediaProfileSpecType.WEBM_VIDEO_ONLY;
        break;
      default:
        profile = MediaProfileSpecType.WEBM;
    }

    return profile;
  }

  private void connectAccordingToProfile(WebRtcEndpoint webRtcEndpoint, RecorderEndpoint recorder,
      MediaProfileSpecType profile) {
    switch (profile) {
      case WEBM:
        webRtcEndpoint.connect(recorder, MediaType.AUDIO);
        webRtcEndpoint.connect(recorder, MediaType.VIDEO);
        break;
      case WEBM_AUDIO_ONLY:
        webRtcEndpoint.connect(recorder, MediaType.AUDIO);
        break;
      case WEBM_VIDEO_ONLY:
        webRtcEndpoint.connect(recorder, MediaType.VIDEO);
        break;
      default:
        throw new UnsupportedOperationException("Unsupported profile for this tutorial: " + profile);
    }
  }

  private void play(UserSession user, final WebSocketSession session, JsonObject jsonMessage) {
    try {

      // 1. Media logic
      final MediaPipeline pipeline = kurento.createMediaPipeline();
      WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
      PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, RECORDER_FILE_PATH).build();
      player.connect(webRtcEndpoint);

      // Player listeners
      player.addErrorListener(new EventListener<ErrorEvent>() {
        @Override
        public void onEvent(ErrorEvent event) {
          log.info("ErrorEvent for session '{}': {}", session.getId(), event.getDescription());
          sendPlayEnd(session, pipeline);
        }
      });
      player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
        @Override
        public void onEvent(EndOfStreamEvent event) {
          log.info("EndOfStreamEvent for session '{}'", session.getId());
          sendPlayEnd(session, pipeline);
        }
      });

      // 2. Store user session
      user.setMediaPipeline(pipeline);
      user.setWebRtcEndpoint(webRtcEndpoint);

      // 3. SDP negotiation
      String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
      String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

      JsonObject response = new JsonObject();
      response.addProperty("id", "playResponse");
      response.addProperty("sdpAnswer", sdpAnswer);

      // 4. Gather ICE candidates
      webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

        @Override
        public void onEvent(IceCandidateFoundEvent event) {
          JsonObject response = new JsonObject();
          response.addProperty("id", "iceCandidate");
          response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
          try {
            synchronized (session) {
              session.sendMessage(new TextMessage(response.toString()));
            }
          } catch (IOException e) {
            log.error(e.getMessage());
          }
        }
      });

      // 5. Play recorded stream
      player.play();

      synchronized (session) {
        session.sendMessage(new TextMessage(response.toString()));
      }

      webRtcEndpoint.gatherCandidates();
    } catch (Throwable t) {
      log.error("Play error", t);
      sendError(session, t.getMessage());
    }
  }

  public void sendPlayEnd(WebSocketSession session, MediaPipeline pipeline) {
    try {
      JsonObject response = new JsonObject();
      response.addProperty("id", "playEnd");
      session.sendMessage(new TextMessage(response.toString()));
    } catch (IOException e) {
      log.error("Error sending playEndOfStream message", e);
    }
    // Release pipeline
    pipeline.release();
  }

  private void sendError(WebSocketSession session, String message) {
    JsonObject response = new JsonObject();
    response.addProperty("id", "error");
    response.addProperty("message", message);

    try {
      synchronized (session) {
        session.sendMessage(new TextMessage(response.toString()));
      }
    } catch (IOException e) {
      log.error("Exception sending message", e);
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
-->
<faces-config version="2.2"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">

    <name>myfaces_mvc</name>

    <ordering>
        <after>
            <others/>
        </after>
    </ordering>

    <factory>
        <lifecycle-factory>org.apache.myfaces.mvc.impl.lifecycle.LifecycleWrapperFactoryImpl</lifecycle-factory>
        <partial-view-context-factory>org.apache.myfaces.mvc.impl.context.ActionPartialViewContextFactory</partial-view-context-factory>
        <view-declaration-language-factory>org.apache.myfaces.mvc.impl.view.ActionViewDeclarationLanguageFactory</view-declaration-language-factory>
    </factory>
</faces-config>


text:
//
//  SideBarController.m
//  CityPlace
//
//  Created by Yuri Korshev on 15.10.14.
//  Copyright (c) 2014 SoftGears. All rights reserved.
//

#import "SideBarController.h"
#import "SWRevealViewController.h"

@interface SideBarController ()

@property (nonatomic, strong) NSArray *menuItems;

@end

@implementation SideBarController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg"]];
     _menuItems = @[@"title", @"city", @"news", @"events",@"places", @"settings", @"about"];
}

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

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [_menuItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *CellIdentifier = [self.menuItems objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (indexPath.row > 0){
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.contentView.frame.size.height - 1.0, cell.contentView.frame.size.width, 2)];

        lineView.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:1];
        [cell.contentView addSubview:lineView];
    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if(indexPath.row == 0)
    {
        return 63.0f;
    }
    else
    {
        return 42.0f;
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    // Set the title of navigation bar by using the menu items
    UINavigationController *destViewController = (UINavigationController*)segue.destinationViewController;

    UINavigationController* navController = (UINavigationController*)self.revealViewController.frontViewController;
    [navController setViewControllers: @[destViewController] animated: NO ];

    [self.revealViewController revealToggle:nil];
}

@end


text:
Originally published: 2009-03-30 14:54:40
Last updated: 2009-03-30 14:54:40
Author: Tucker Beck

The xzip function provides the same functionality as zip (python builtin), but utilizes a generator list comprehension so that zipped collections can be accessed iteratively.

Example:
for t in xzip( xrange( 1000000 ), xrange( 1000000, 2000000, 1 ), xrange( 888,100000000, 1 ):
    print t

This Will begin to produce output immediately, because the collections are zipped iteratively
The output of this code is exactly equivalent to:

for t in zip( xrange( 1000000 ), xrange( 1000000, 2000000, 1 ), xrange( 888,100000000, 1 ):
    print t

However, the second block (using zip) must first build the zipped collection entirely before the
for loop can iterate over it.  This could take a long time.

Note, I used xrange here so that we don't have to wait for python to build the initial lists.
The xzip function would probably show its usefulness most if one had several huge collections that
needed to be combined iteratively.

I developed this function to zip long lists ( >100000 ) of vertex triples with color triples in a volume
visualizer.


text:
<?php

/**
 * @codingStandardsIgnoreFile
 */

require_once __DIR__.'/AppKernel.php';

use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;

class AppCache extends HttpCache
{
}


text:
/*
    DGItemHandle class implementation
    (c) 2003 root-1 Software
*/

#include "dgitemhandle.h"

DGItemHandle::DGItemHandle()
{
}

char* DGItemHandle::Name(int ind) const
{
    switch (ind)
    {
        case 0: return "Potion";
        case 1: return "Ether";
        case 2: return "Phoenix Down";
        case 3: return "Cure";
        case 4: return "Rest Potion";
        default: return "Bug02";
    }
    return "Bug02";
}

bool DGItemHandle::Use(DGCharacter* victim, int ind) const
{
    switch (ind)
    {
        case 0: //Potion
            if (victim->HP() == victim->MaxHP()) return false;
            victim->HPUp(30);
            return true;
        case 1: //Ether
            if (victim->MP() == victim->MaxMP()) return false;
            victim->MPUp(30);
            return true;
        case 2: //Phoenix Down
            if (victim->Status() != 'k') return false;
            victim->Revive();
            return true;
        case 3: //Cure
            if (victim->Status() == ('n' || 'k')) return false;
            victim->ChangeStatus('n');
            return true;
        case 4: //Rest Potion
            if (victim->Status() == 'k') victim->Revive();
            victim->HPUp(victim->MaxHP());
            victim->MPUp(victim->MaxMP());
            victim->ChangeStatus('n');
            return true;
        default: return false;
    }
    return false;
}


text:
package org.zeksa.jsongeneric.app.dto;

import java.util.ArrayList;
import java.util.List;

public class SectionDTO {

    private String sectionId;
    private List<SubSectionDTO> subSections;

    public String getSectionId() {
        return sectionId;
    }

    public void setSectionId(String sectionId) {
        this.sectionId = sectionId;
    }

    public List<SubSectionDTO> getSubSections() {
        if (subSections == null) {
            subSections = new ArrayList<>();
        }
        return subSections;
    }

    public void setSubSections(List<SubSectionDTO> subSections) {
        this.subSections = subSections;
    }
}


text:
/*!
	@file
	@author		Generate utility by Albert Semenov
	@date		01/2009
	@module
*/

#ifndef EXPORT_WIDGET_Window_H_
#define EXPORT_WIDGET_Window_H_

#include "../ExportDefine.h"
#include "../ExportMarshaling.h"
#include "MyGUI_Export_MarshalingWidget.h"
#include "../ExportMarshalingType.h"
#include <MyGUI.h>

namespace Export
{
	//InsertPoint

	namespace ScopeWindowEvent_WindowChangeCoord
	{
		typedef void (MYGUICALLBACK *ExportHandle)(
			MyGUI::Window *);
		ExportHandle mExportHandle = nullptr;

		void OnEvent(
			MyGUI::Window * _sender)
		{
			mExportHandle(
				_sender);
		}

		MYGUIEXPORT void MYGUICALL ExportWindowEvent_DelegateWindowChangeCoord(ExportHandle _delegate)
		{
			mExportHandle = _delegate;
		}
		MYGUIEXPORT void MYGUICALL ExportWindowEvent_AdviseWindowChangeCoord(MyGUI::Widget* _widget, bool _advise)
		{
			if (_advise)
				static_cast<MyGUI::Window*>(_widget)->eventWindowChangeCoord += MyGUI::newDelegate(OnEvent);
			else
				static_cast<MyGUI::Window*>(_widget)->eventWindowChangeCoord -= MyGUI::newDelegate(OnEvent);
		}
	}
	namespace ScopeWindowEvent_WindowButtonPressed
	{
		typedef void (MYGUICALLBACK *ExportHandle)(
			MyGUI::Window *,
			Convert<const std::string &>::Type);
		ExportHandle mExportHandle = nullptr;

		void OnEvent(
			MyGUI::Window * _sender,
			const std::string & _name)
		{
			mExportHandle(
				_sender,
				Convert<const std::string &>::To(_name));
		}

		MYGUIEXPORT void MYGUICALL ExportWindowEvent_DelegateWindowButtonPressed(ExportHandle _delegate)
		{
			mExportHandle = _delegate;
		}
		MYGUIEXPORT void MYGUICALL ExportWindowEvent_AdviseWindowButtonPressed(MyGUI::Widget* _widget, bool _advise)
		{
			if (_advise)
				static_cast<MyGUI::Window*>(_widget)->eventWindowButtonPressed += MyGUI::newDelegate(OnEvent);
			else
				static_cast<MyGUI::Window*>(_widget)->eventWindowButtonPressed -= MyGUI::newDelegate(OnEvent);
		}
	}
	namespace ScopeWindowMethod_SetMaxSize
	{
		MYGUIEXPORT void MYGUICALL ExportWindow_SetMaxSize__width__height(MyGUI::Widget* _native,
			Convert<int>::Type _width,
			Convert<int>::Type _height)
		{
			static_cast<MyGUI::Window*>(_native)->setMaxSize(
				Convert<int>::From(_width),
				Convert<int>::From(_height));
		}
	}
	namespace ScopeWindowMethod_SetMinSize
	{
		MYGUIEXPORT void MYGUICALL ExportWindow_SetMinSize__width__height(MyGUI::Widget* _native,
			Convert<int>::Type _width,
			Convert<int>::Type _height)
		{
			static_cast<MyGUI::Window*>(_native)->setMinSize(
				Convert<int>::From(_width),
				Convert<int>::From(_height));
		}
	}
	namespace ScopeWindowMethod_SetVisibleSmooth
	{
		MYGUIEXPORT void MYGUICALL ExportWindow_SetVisibleSmooth__value(MyGUI::Widget* _native,
			Convert<bool>::Type _value)
		{
			static_cast<MyGUI::Window*>(_native)->setVisibleSmooth(
				Convert<bool>::From(_value));
		}
	}
	namespace ScopeWindowProperty_Movable
	{
		MYGUIEXPORT Convert<bool>::Type MYGUICALL ExportWindow_GetMovable(MyGUI::Widget* _native)
		{
			return Convert<bool>::To(static_cast<MyGUI::Window*>(_native)->getMovable());
		}
		MYGUIEXPORT void MYGUICALL ExportWindow_SetMovable(MyGUI::Widget* _native, Convert<bool>::Type _value)
		{
			static_cast<MyGUI::Window*>(_native)->setMovable(Convert<bool>::From(_value));
		}
	}
	namespace ScopeWindowProperty_ActionScale
	{
		MYGUIEXPORT Convert<const MyGUI::types::TCoord < int > &>::Type MYGUICALL ExportWindow_GetActionScale(MyGUI::Widget* _native)
		{
			return Convert<const MyGUI::types::TCoord < int > &>::To(static_cast<MyGUI::Window*>(_native)->getActionScale());
		}
	}
	namespace ScopeWindowProperty_Snap
	{
		MYGUIEXPORT Convert<bool>::Type MYGUICALL ExportWindow_GetSnap(MyGUI::Widget* _native)
		{
			return Convert<bool>::To(static_cast<MyGUI::Window*>(_native)->getSnap());
		}
		MYGUIEXPORT void MYGUICALL ExportWindow_SetSnap(MyGUI::Widget* _native, Convert<bool>::Type _value)
		{
			static_cast<MyGUI::Window*>(_native)->setSnap(Convert<bool>::From(_value));
		}
	}
	namespace ScopeWindowProperty_MaxSize
	{
		MYGUIEXPORT Convert<MyGUI::types::TSize < int >>::Type MYGUICALL ExportWindow_GetMaxSize(MyGUI::Widget* _native)
		{
			return Convert<MyGUI::types::TSize < int >>::To(static_cast<MyGUI::Window*>(_native)->getMaxSize());
		}
		MYGUIEXPORT void MYGUICALL ExportWindow_SetMaxSize(MyGUI::Widget* _native, Convert<const MyGUI::types::TSize < int > &>::Type _value)
		{
			static_cast<MyGUI::Window*>(_native)->setMaxSize(Convert<const MyGUI::types::TSize < int > &>::From(_value));
		}
	}
	namespace ScopeWindowProperty_MinSize
	{
		MYGUIEXPORT Convert<MyGUI::types::TSize < int >>::Type MYGUICALL ExportWindow_GetMinSize(MyGUI::Widget* _native)
		{
			return Convert<MyGUI::types::TSize < int >>::To(static_cast<MyGUI::Window*>(_native)->getMinSize());
		}
		MYGUIEXPORT void MYGUICALL ExportWindow_SetMinSize(MyGUI::Widget* _native, Convert<const MyGUI::types::TSize < int > &>::Type _value)
		{
			static_cast<MyGUI::Window*>(_native)->setMinSize(Convert<const MyGUI::types::TSize < int > &>::From(_value));
		}
	}
	namespace ScopeWindowProperty_CaptionWidget
	{
		MYGUIEXPORT Convert<MyGUI::TextBox *>::Type MYGUICALL ExportWindow_GetCaptionWidget(MyGUI::Widget* _native)
		{
			return Convert<MyGUI::TextBox *>::To(static_cast<MyGUI::Window*>(_native)->getCaptionWidget());
		}
	}
	namespace ScopeWindowProperty_AutoAlpha
	{
		MYGUIEXPORT Convert<bool>::Type MYGUICALL ExportWindow_GetAutoAlpha(MyGUI::Widget* _native)
		{
			return Convert<bool>::To(static_cast<MyGUI::Window*>(_native)->getAutoAlpha());
		}
		MYGUIEXPORT void MYGUICALL ExportWindow_SetAutoAlpha(MyGUI::Widget* _native, Convert<bool>::Type _value)
		{
			static_cast<MyGUI::Window*>(_native)->setAutoAlpha(Convert<bool>::From(_value));
		}
	}
}

#endif


text:
namespace beluga
{
    class continue_event
    {
    public:
	continue_event(bool _continue);

	virtual ~continue_event() = default;

	void set_continue(bool _continue);
	bool get_continue() const;

    private:
	bool _continue;
    };
}


text:
layout: default
---

{% for item in site.sections %}
  {% if item.name == "Cloud computing"%}
    {% include section-hero.html name=item.name title=item.title description=item.description hero_description=item.hero_description icon=item.icon %}
  {% endif %}
{% endfor %}

{% capture cc1 %}

Free tier for the first 12 months

Some services have free forever tiers

More features than competition

Longest time on market
(more 3rd party libraries,
 better documentation)

Open AWS

{% endcapture %}

{% capture cc2 %}

$300 free credits to spend during first 12 months

Always Free tier:
1 f1-micro VPS
 1 GB NoSQL DB,
 28 hours/day of Google App Engine,
 5 GB of cloud storage
 2 000 000 cloud functions invocations
        and more

Open Google Cloud

{% endcapture %}

{% capture cc3 %}

$200 free credits to spend during 30 days

12 months free trial of some services:750 hours/month of
 Linux and Windows VM,
 2x 64GB managed disks,
 5GB of File storage,
 250GB SQL database and more

Always free tier:
10 web, mobile or API apps,
 1 000 000 serverless functions/month
 and more

Good support for Windows application

Open Azure

{% endcapture %}

          {% include pricing-card.html title="AWS" block=cc1 %}
          {% include pricing-card.html title="Google Cloud" block=cc2 %}
          {% include pricing-card.html title="Azure" block=cc3 %}

Cloud computing platforms are complex and hard to compare (the list of features and pricing is changing
              often).
Based on a specific use case, you will have to pick the best option yourself. Check those articles if
              you need help choosing:
              Sitepoint, Hacker
                News, RightScale.


text:
Ext.define('Panax.data.Proxy', {
	extend: 'Ext.data.proxy.Ajax',
	alias: 'proxy.panax_proxy'

    , timeout: 360000
    , api: {
          create: "Scripts/update.asp"
        , read: "request.asp"
        , update: "Scripts/update.asp"
        , destroy: "Scripts/update.asp"
    }
	, settings: {
		catalogName: undefined
		, lang: undefined
		//, filters: undefined
		, identityKey: undefined
		, primaryKey: undefined
		, mode: undefined
		//, view: undefined
		//, identity: undefined
	}
	, constructor: function(configuration) {
        var me = this;
		me.callParent(arguments);
		Ext.apply(me, {
			extraParams: {
				catalogName: me.config.settings.catalogName
				, lang: me.config.settings.lang
				//, filters: me.config.settings.filters
				, identityKey: me.config.settings.identityKey
				, primaryKey: me.config.settings.primaryKey
				, mode: me.config.settings.mode
				, output: 'json'
			}
		});
	}
    ,writer: {
        type:'xml',
        successProperty: 'success',
        writeAllFields: false,
        rootProperty:'data'
        // , partialDataOptions: { // Se evita esta configuración porque recupera toda la información asociada y no solamente los cambios
            // associated: true
        // },
    }
    ,reader: {
    	type: 'json',
        rootProperty:'data',
        successProperty: 'success'
    }
    , pageParam: 'pageIndex'
    , limitParam: 'pageSize'
    , filterParam: 'filters'
    , sortParam: 'sorters'
    , encodeFilters: function(filters) {
	    filterOperator = function(filter) {
	    	var op = filter.getOperator(),
	    		val = Ext.XML.encodeValue(filter.getValue());

			switch(op) {
				case 'gt': 		return '> ' + val;
				case 'gte': 	return '>= ' + val;
				case 'lt': 		return '< ' + val;
				case 'lte': 	return '<= ' + val;
				case 'like': 	return "LIKE '%'+REPLACE("+val+",'','%')+'%'"
				case 'eq': 		return '= ' + val;
				default: 		return '= ' + val;
			}
	    };

        var a = [""], //["<values>"],
            len = filters.length,
            i;

        //a.push('<filterGroup operator="AND">');
        for (i = 0; i < len; i += 1) {
            a.push(filters[i].getProperty());
            a.push(filterOperator(filters[i]));
        }
        //a.push('</filterGroup>');

    	return a.join(" ").trim();
    }
    , success: function(xhr) {
    	alert("success");
        var response=Ext.JSON.decode(xhr.responseText);
        parameters["success"] = (response.success/* && confirm("Se reconstruyó el módulo, continuar?")*/);
            if (response.callback) {
                response.callback();
            }
            else {
                if (response.message) {
                    Ext.MessageBox.show({
                        title: 'MENSAJE DEL SISTEMA',
                        msg: response.message,
                        icon: Ext.MessageBox.ERROR,
                        buttons: Ext.Msg.OK
                    });
                }
            }
        parameters = Ext.apply(parameters, response.catalog)
    }
    , failure: function() {
        Ext.Msg.alert("Error de comunicación", "La conexión con el servidor falló, favor de intentarlo nuevamente en unos segundos.");
        parameters["success"] = false;
    }
    , exception: function( me, request, operation, eOpts ){
        Ext.Msg.alert("Error en el script", "La conexión con el servidor falló, favor de intentarlo nuevamente en unos segundos.");
    }
});


text:
This template provides an easy way to deploy web app with custom deployment slots/environments on Azure Web Apps.

The `environments` parameter (array) can be used to specify different slot/environment names, and a slot will be created for every item listed in the array.

To specify multiple environments, say N, follow this simple rule:

Add N - 1 items, as depicted in the below example, with N = 5. There's always a default "nameless" slot created by default:

// Environments -> Deployment slots will be created for every environment listed here

```javascript
    "environments": {
      "value": [
        "Dev",
        "Next",
        "Preview",
        "Future"
        // A default, "nameless" slot will be created; so don't list it here
      ]
     }
```

Please note that different app service plans has different caps on the number of slots that can be created.

For example, at the time of this writing, a *Standard* plan puts a cap of **5** and a *Premium* plan **20**. The *Free*, *Shared* or *Basic* plans are not allowed to have any slots.


text:
package org.opensmartgridplatform.cucumber.platform.smartmetering.glue.steps.ws.smartmetering.smartmeteringbundle;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.Map;

import org.opensmartgridplatform.adapter.ws.schema.smartmetering.bundle.ActionResponse;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.bundle.SetAdministrativeStatusRequest;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.common.Response;
import org.opensmartgridplatform.cucumber.platform.smartmetering.PlatformSmartmeteringKeys;
import org.opensmartgridplatform.cucumber.platform.smartmetering.support.ws.smartmetering.bundle.SetAdministrativeStatusRequestBuilder;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;

public class BundledSetAdministrativeStatusSteps extends BaseBundleSteps {

    @Given("^the bundle request contains a set administrative status action$")
    public void theBundleRequestContainsASetAdministrativeStatusAction() throws Throwable {

        final SetAdministrativeStatusRequest action = new SetAdministrativeStatusRequestBuilder().withDefaults()
                .build();

        this.addActionToBundleRequest(action);
    }

    @Given("^the bundle request contains a set administrative status action with parameters$")
    public void theBundleRequestContainsASetAdministrativeStatusAction(final Map<String, String> parameters)
            throws Throwable {

        final SetAdministrativeStatusRequest action = new SetAdministrativeStatusRequestBuilder()
                .fromParameterMap(parameters).build();

        this.addActionToBundleRequest(action);
    }

    @Then("^the bundle response should contain a set administrative status response$")
    public void theBundleResponseShouldContainASetAdministrativeStatusResponse() throws Throwable {
        final Response response = this.getNextBundleResponse();

        assertTrue("Not a valid response", response instanceof ActionResponse);
    }

    @Then("^the bundle response should contain a set administrative status response with values$")
    public void theBundleResponseShouldContainASetAdministrativeStatusResponse(final Map<String, String> values)
            throws Throwable {

        final Response response = this.getNextBundleResponse();

        assertTrue("Not a valid response", response instanceof ActionResponse);
        assertEquals("Result is not as expected.", values.get(PlatformSmartmeteringKeys.RESULT),
                response.getResult().name());
    }

}


text:
<bill session="110" type="s" number="3639" updated="2009-01-09T19:27:56-05:00">
	<status><calendar date="1221624000" datetime="2008-09-17" /></status>

	<introduced date="1222401600" datetime="2008-09-26"/>
	<titles>
		<title type="short" as="introduced">Protect Pregnant Women and Children from Dangerous Lead Exposures Act of 2008</title>
		<title type="official" as="introduced">An original bill to protect pregnant women and children from dangerous lead exposures.</title>
	</titles>
	<sponsor id="300011"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<calendar date="1221624000" datetime="2008-09-17" ><text>Committee on Environment and Public Works ordered to be reported an original measure.</text></calendar>
		<action date="1222401600" datetime="2008-09-26"><text>Committee on Environment and Public Works. Original measure reported to Senate by Senator Boxer. With written report No. 110-515. Additional views filed.</text></action>
		<calendar under="General Orders" number="1097" date="1222401600" datetime="2008-09-26" calendar="Senate Legislative" ><text>Placed on Senate Legislative Calendar under General Orders. Calendar No. 1097.</text></calendar>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>


text:
#ifndef memleak_h
#define memleak_h

/* Used for tracking allocations */
extern void* XWBMalloc (
    unsigned int iSize,
    const char* iFile,
    const unsigned int iLine);
extern void* XWBCalloc (
    unsigned int iNum,
    unsigned int iSize,
    const char* iFile,
    const unsigned int iLine);
extern char* XWBStrDup (
    const char* iOrig,
    const char* iFile,
    const unsigned int iLine);
/* Used for tracking reallocations */
extern void* XWBRealloc (
    void* iPrev,
    unsigned int iSize,
    const char* iFile,
    const unsigned int iLine);
/* Used for tracking deallocations */
extern void  XWBFree (
    void* iPtr,
    const char* iDesc,
    const char* iFile,
    const unsigned int iLine);
/* Used for reporting */
extern void  XWBReport (const char* iTag);
extern void  XWBReportFinal (void);
/* Used for detecting FMW */
extern void  XWBNoFree (void);
extern void  XWBPreallocate (const int iInitialAllocations);

#ifdef MEM_LEAK_CHECK
#define malloc(x) XWBMalloc((x), __FILE__, __LINE__)
#define realloc(x,size) XWBRealloc(x,(size),__FILE__,__LINE__)
#define free(x)   XWBFree(x, #x, __FILE__, __LINE__)
#ifdef _MSC_VER
#define _strdup(x) XWBStrDup(x, __FILE__, __LINE__)
#else
#define strdup(x) XWBStrDup(x, __FILE__, __LINE__)
#endif
#define calloc(num,size) XWBCalloc((num), (size), __FILE__, __LINE__)
#endif

#endif


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.2.3.6-4-321
description: >
    Object.defineProperty - 'O' is an Arguments object, 'P' is own
    accessor property of 'O', test TypeError is thrown when updating
    the [[Get]] attribute value of 'P' which is not configurable (10.6
    [[DefineOwnProperty]] step 4)
includes: [propertyHelper.js]
---*/

(function () {
    function getFunc() {
        return "genericPropertyString";
    }
    function setFunc(value) {
        this.helpVerifyGet = value;
    }
    Object.defineProperty(arguments, "genericProperty", {
        get: getFunc,
        set: setFunc,
        configurable: false
    });
    try {
        Object.defineProperty(arguments, "genericProperty", {
            get: function () {
                return "overideGenericPropertyString";
            }
        });
        $ERROR("Expected an exception.");
    } catch (e) {
        verifyEqualTo(arguments, "genericProperty", getFunc());

        verifyWritable(arguments, "genericProperty", "helpVerifyGet");

        verifyNotEnumerable(arguments, "genericProperty");

        verifyNotConfigurable(arguments, "genericProperty");

        if (!(e instanceof TypeError)) {
            $ERROR("Expected TypeError, got " + e);
        }

    }
}(1, 2, 3));


text:
//>>built
define("dojo/cldr/nls/pt-pt/currency",{HKD_displayName:"D\u00f3lar de Hong Kong",CHF_displayName:"Franco su\u00ed\u00e7o",JPY_symbol:"JP\u00a5",CAD_displayName:"D\u00f3lar canadiano",HKD_symbol:"HK$",CNY_displayName:"Yuan chin\u00eas",USD_symbol:"US$",AUD_displayName:"D\u00f3lar australiano",JPY_displayName:"Iene japon\u00eas",CAD_symbol:"CA$",USD_displayName:"D\u00f3lar dos Estados Unidos",EUR_symbol:"\u20ac",CNY_symbol:"CN\u00a5",GBP_displayName:"Libra esterlina brit\u00e2nica",GBP_symbol:"\u00a3",
AUD_symbol:"AU$",EUR_displayName:"Euro"});
//# sourceMappingURL=currency.js.map


text:
require "rubocops/extend/formula"
require "extend/string"

module RuboCop
  module Cop
    module FormulaAudit
      # This cop audits `patch`es in formulae.
      class Patches < FormulaCop
        extend T::Sig

        def audit_formula(node, _class_node, _parent_class_node, body)
          @full_source_content = source_buffer(node).source

          external_patches = find_all_blocks(body, :patch)
          external_patches.each do |patch_block|
            url_node = find_every_method_call_by_name(patch_block, :url).first
            url_string = parameters(url_node).first
            patch_problems(url_string)
          end

          inline_patches = find_every_method_call_by_name(body, :patch)
          inline_patches.each { |patch| inline_patch_problems(patch) }

          if inline_patches.empty? && patch_end?
            offending_patch_end_node(node)
            problem "patch is missing 'DATA'"
          end

          patches_node = find_method_def(body, :patches)
          return if patches_node.nil?

          legacy_patches = find_strings(patches_node)
          problem "Use the patch DSL instead of defining a 'patches' method"
          legacy_patches.each { |p| patch_problems(p) }
        end

        private

        def patch_problems(patch)
          patch_url = string_content(patch)

          if regex_match_group(patch, %r{https://github.com/[^/]*/[^/]*/pull})
            problem "Use a commit hash URL rather than an unstable pull request URL: #{patch_url}"
          end

          if regex_match_group(patch, %r{.*gitlab.*/merge_request.*})
            problem "Use a commit hash URL rather than an unstable merge request URL: #{patch_url}"
          end

          if regex_match_group(patch, %r{https://github.com/[^/]*/[^/]*/commit/[a-fA-F0-9]*\.diff})
            problem <<~EOS.chomp
              GitHub patches should end with .patch, not .diff:
                #{patch_url}
            EOS
          end

          if regex_match_group(patch, %r{.*gitlab.*/commit/[a-fA-F0-9]*\.diff})
            problem <<~EOS.chomp
              GitLab patches should end with .patch, not .diff:
                #{patch_url}
            EOS
          end

          gh_patch_param_pattern = %r{https?://github\.com/.+/.+/(?:commit|pull)/[a-fA-F0-9]*.(?:patch|diff)}
          if regex_match_group(patch, gh_patch_param_pattern) && !patch_url.match?(/\?full_index=\w+$/)
            problem <<~EOS
              GitHub patches should use the full_index parameter:
                #{patch_url}?full_index=1
            EOS
          end

          gh_patch_patterns = Regexp.union([%r{/raw\.github\.com/},
                                            %r{/raw\.githubusercontent\.com/},
                                            %r{gist\.github\.com/raw},
                                            %r{gist\.github\.com/.+/raw},
                                            %r{gist\.githubusercontent\.com/.+/raw}])
          if regex_match_group(patch, gh_patch_patterns) && !patch_url.match?(%r{/[a-fA-F0-9]{6,40}/})
            problem <<~EOS.chomp
              GitHub/Gist patches should specify a revision:
                #{patch_url}
            EOS
          end

          gh_patch_diff_pattern =
            %r{https?://patch-diff\.githubusercontent\.com/raw/(.+)/(.+)/pull/(.+)\.(?:diff|patch)}
          if regex_match_group(patch, gh_patch_diff_pattern)
            problem "Use a commit hash URL rather than patch-diff: #{patch_url}"
          end

          if regex_match_group(patch, %r{macports/trunk})
            problem <<~EOS.chomp
              MacPorts patches should specify a revision instead of trunk:
                #{patch_url}
            EOS
          end

          if regex_match_group(patch, %r{^http://trac\.macports\.org})
            problem <<~EOS.chomp
              Patches from MacPorts Trac should be https://, not http:
                #{patch_url}
            EOS
          end

          return unless regex_match_group(patch, %r{^http://bugs\.debian\.org})

          problem <<~EOS.chomp
            Patches from Debian should be https://, not http:
              #{patch_url}
          EOS
        end

        def inline_patch_problems(patch)
          return unless patch_data?(patch) && !patch_end?

          offending_node(patch)
          problem "patch is missing '__END__'"
        end

        def_node_search :patch_data?, <<~AST
          (send nil? :patch (:sym :DATA))
        AST

        sig { returns(T::Boolean) }
        def patch_end?
          /^__END__$/.match?(@full_source_content)
        end

        def offending_patch_end_node(node)
          @offensive_node = node
          @source_buf = source_buffer(node)
          @line_no = node.loc.last_line + 1
          @column = 0
          @length = 7 # "__END__".size
          @offense_source_range = source_range(@source_buf, @line_no, @column, @length)
        end
      end
    end
  end
end


text:
import assert from 'assert';

import * as Actions from 'app/actions/views/login';
import configureStore from 'app/store';

import TestHelper from 'test/test_helper';

describe('Actions.Views.Login', () => {
    let store;
    beforeEach(async () => {
        store = configureStore();
        await TestHelper.wait();
    });

    it('handleLoginIdChanged', async () => {
        await Actions.handleLoginIdChanged('email@example.com')(store.dispatch, store.getState);
        const loginId = store.getState().views.login.loginId;
        assert.equal('email@example.com', loginId);
    });

    it('handlePasswordChanged', async () => {
        await Actions.handlePasswordChanged('password')(store.dispatch, store.getState);
        const password = store.getState().views.login.password;
        assert.equal('password', password);
    });
});


text: A simple interface for Keychain in iOS and OSX, as simple as NSUserDefault !


text:
#pragma once

/*
 * Model a non-convex optimization problem by defining Cost and Constraint objects
 * which know how to generate a convex approximation
 *
 *
 */

#include <vector>
#include <boost/shared_ptr.hpp>
#include <map>
#include "sco/sco_fwd.hpp"
#include "sco/solver_interface.hpp"

namespace sco {

using std::vector;
using std::pair;
using std::map;

enum ObjectiveType {
  Objective_AffExpr,
  Objective_QuadExpr,
  Objective_Hinge,
  Objective_Abs,
  Objective_Max,
  Objective_Min
};

typedef map<Model*, vector<Var> > Model2Vars;
typedef pair<Model*, vector<Var> > ModelVarsPair;
typedef map<Model*, vector<Cnt> > Model2Cnts;
typedef pair<Model*, vector<Cnt> > ModelCntsPair;
typedef map<Model*, QuadExpr > Model2Quad;
typedef pair<Model*, QuadExpr > ModelQuadPair;

/**
Stores convex terms in a objective
For non-quadratic terms like hinge(x) and abs(x), it needs to add auxilliary variables and linear constraints to the model
Note: When this object is deleted, the constraints and variables it added to the model are removed
 */
class ConvexObjective {
public:

  struct ObjectiveInfo {
    ObjectiveInfo(ObjectiveType type, const QuadExpr& quadexpr, double coeff=1) : type_(type), quadexpr_(quadexpr), coeff_(coeff) {}
    ObjectiveInfo(ObjectiveType type, const AffExpr& affexpr, double coeff=1) : type_(type), affexpr_(affexpr), coeff_(coeff) {}
    ObjectiveInfo(ObjectiveType type, const AffExprVector& ev, double coeff=1) : type_(type), ev_(ev), coeff_(coeff) {}
    ObjectiveType type_;
    AffExpr affexpr_;
    QuadExpr quadexpr_;
    AffExprVector ev_;
    double coeff_;
  };

  ConvexObjective() {}
  void addAffExpr(const AffExpr&);
  void addQuadExpr(const QuadExpr&);
  void addHinge(const AffExpr&, double coeff=1);
  void addAbs(const AffExpr&, double coeff=1);
  void addHinges(const AffExprVector&);
  void addL1Norm(const AffExprVector&);
  void addL2Norm(const AffExprVector&);
  void addMax(const AffExprVector&, double coeff=1);

  void addToModelAndObjective(Model* model, AffExpr& objective, bool permissive=false);
  void addToModelAndObjective(Model* model, QuadExpr& objective);
  void removeFromModel(Model* model);
  void removeFromModels();

  double value(const vector<double>& x, Model* model);

  ~ConvexObjective();

  Model2Vars model2vars_;
  Model2Cnts model2cnts_;
  Model2Quad model2quad_;
  vector<ObjectiveInfo> objective_infos_;
private:
  ConvexObjective(ConvexObjective&)  {}
};

/**
Stores convex inequality constraints and affine equality constraints.
Actually only affine inequality constraints are currently implemented.
*/
class ConvexConstraints {
public:
  ConvexConstraints() {}
  /** Expression that should == 0 */
  void addEqCnt(const AffExpr&);
  /** Expression that should <= 0 */
  void addIneqCnt(const AffExpr&);

  void addToModel(Model* model);
  void removeFromModel(Model* model);
  void removeFromModels();

  vector<double> violations(const vector<double>& x, Model* model);
  double violation(const vector<double>& x, Model* model);

  ~ConvexConstraints();
  vector<AffExpr> eqs_;
  vector<AffExpr> ineqs_;
  Model2Cnts model2cnts_;
private:
   ConvexConstraints(ConvexConstraints&) {}
};

/**
Non-convex cost function, which knows how to calculate its convex approximation (convexify() method)
*/
class Cost {
public:
  /** Evaluate at solution vector x*/
  virtual double value(const vector<double>&, Model*) = 0;
  /** Convexify at solution vector x*/
  virtual ConvexObjectivePtr convex(const vector<double>& x) = 0;

  string name() {return name_;}
  void setName(const string& name) {name_=name;}
  Cost() : name_("unnamed") {}
  Cost(const string& name) : name_(name) {}
  virtual ~Cost() {}
protected:
  string name_;
};

/**
Non-convex vector-valued constraint function, which knows how to calculate its convex approximation
*/
class Constraint {
public:

  /** inequality vs equality */
  virtual ConstraintType type() = 0;
  /** Evaluate at solution vector x*/
  virtual vector<double> value(const vector<double>& x, Model*) = 0;
  /** Convexify at solution vector x*/
  virtual ConvexConstraintsPtr convex(const vector<double>& x) = 0;
  /** Calculate constraint violations (positive part for inequality constraint, absolute value for inequality constraint)*/
  vector<double> violations(const vector<double>& x, Model*);
  /** Sum of violations */
  double violation(const vector<double>& x, Model*);

  string name() {return name_;}
  void setName(const string& name) {name_=name;}
  Constraint() : name_("unnamed") {}
  Constraint(const string& name) : name_(name) {}
  virtual ~Constraint() {}

protected:
  string name_;
};

class EqConstraint : public Constraint{
public:
  ConstraintType type() {return EQ;}
};

class IneqConstraint : public Constraint {
public:
  ConstraintType type() {return INEQ;}
};

/**
Non-convex optimization problem
*/
class OptProb {
public:
  OptProb();
  /** create variables with bounds [-INFINITY, INFINITY]  */
  VarVector createVariables(const vector<string>& names);
  /** create variables with bounds [lb[i], ub[i] */
  VarVector createVariables(const vector<string>& names, const vector<double>& lb, const vector<double>& ub);
  /** set the lower bounds of all the variables */
  void setLowerBounds(const vector<double>& lb);
  /** set the upper bounds of all the variables */
  void setUpperBounds(const vector<double>& ub);
  /** set lower bounds of some of the variables */
  void setLowerBounds(const vector<double>& lb, const vector<Var>& vars);
  /** set upper bounds of some of the variables */
  void setUpperBounds(const vector<double>& ub, const vector<Var>& vars);
  /** Note: in the current implementation, this function just adds the constraint to the
   * model. So if you're not careful, you might end up with an infeasible problem. */
  void addLinearConstraint(const AffExpr&, ConstraintType type);
  /** Add nonlinear cost function */
  void addCost(CostPtr);
  /** Add nonlinear constraint function */
  void addConstraint(ConstraintPtr);
  void addEqConstraint(ConstraintPtr);
  void addIneqConstraint(ConstraintPtr);
  virtual ~OptProb() {}
  /** Find closest point to solution vector x that satisfies linear inequality constraints */
  vector<double> getCentralFeasiblePoint(const vector<double>& x);
  vector<double> getClosestFeasiblePoint(const vector<double>& x);

  vector<ConstraintPtr> getConstraints() const;
  vector<CostPtr>& getCosts() {return costs_;}
  vector<ConstraintPtr>& getIneqConstraints() {return ineqcnts_;}
  vector<ConstraintPtr>& getEqConstraints() {return eqcnts_;}
  DblVec& getLowerBounds() {return lower_bounds_;}
  DblVec& getUpperBounds() {return upper_bounds_;}
  ModelPtr getModel() {return model_;}
  vector<Var>& getVars() {return vars_;}
  int getNumCosts() {return costs_.size();}
  int getNumConstraints() {return eqcnts_.size() + ineqcnts_.size();}
  int getNumVars() {return vars_.size();}

protected:
  ModelPtr model_;
  vector<Var> vars_;
  vector<double> lower_bounds_;
  vector<double> upper_bounds_;
  vector<CostPtr> costs_;
  vector<ConstraintPtr> eqcnts_;
  vector<ConstraintPtr> ineqcnts_;

  OptProb(OptProb&);
};

template <typename VecType>
inline void setVec(DblVec& x, const VarVector& vars, const VecType& vals) {
  assert(vars.size() == vals.size());
  for (int i = 0; i < vars.size(); ++i) {
    x[vars[i].var_rep->index] = vals[i];
  }
}
template <typename OutVecType>
inline OutVecType getVec1(const vector<double>& x, const VarVector& vars) {
  OutVecType out(vars.size());
  for (unsigned i=0; i < vars.size(); ++i) out[i] = x[vars[i].var_rep->index];
  return out;
}

}


text:
#include "stdafx.h"
#include "MipDataPacket.h"

#include "mscl/Utils.h"
#include "MipFieldParser.h"
#include "mscl/MicroStrain/DataBuffer.h"

namespace mscl
{
    MipDataPacket::MipDataPacket():
        m_collectedTime(0),
        m_deviceTime(0),
        m_hasDeviceTime(false),
        m_deviceTimeValid(false),
        m_deviceTimeFlags(0)
    {
    }

    MipDataPacket::MipDataPacket(const MipPacket& packet):
        m_collectedTime(Timestamp::timeNow()),
        m_deviceTime(0),
        m_hasDeviceTime(false),
        m_deviceTimeValid(false),
        m_deviceTimeFlags(0)
    {
        //construct the data packet from the MipPacket passed in
        m_descriptorSet     = packet.descriptorSet();
        m_payload           = Payload(packet.payload());

        //parse the data fields in the packet
        parseDataFields();
    }

    void MipDataPacket::parseDataFields()
    {
        uint8 fieldDescriptor;
        uint16 fieldType;
        uint32 fieldLen;

        //create a DataBuffer to make parsing easier
        DataBuffer payloadData(m_payload.data());

        while(payloadData.moreToRead())
        {
            try
            {
                Bytes fieldBytes;

                //read the field length byte
                fieldLen = payloadData.read_uint8();

                //read the field descriptor byte
                fieldDescriptor = payloadData.read_uint8();

                //read all the bytes for the current field (up to the field length)
                for(uint32 itr = 0; itr < fieldLen - 2; itr++)
                {
                    //add the field bytes to a container
                    fieldBytes.push_back(payloadData.read_uint8());
                }

                fieldType = Utils::make_uint16(m_descriptorSet, fieldDescriptor);

                //add the field to the m_dataFields vector
                MipDataField tempField(fieldType, fieldBytes);
                m_dataFields.push_back(tempField);

                //parse the data points that are in the existing field that we just created
                parsePointsInField(tempField);
            }
            catch(...)
            {
                //possible corrupted packet, just break out and skip trying to parse anything else
                break;
            }
        }
    }

    void MipDataPacket::parsePointsInField(const MipDataField& field)
    {
        bool isTimestamp = false;
        bool isData = true;

        MipTypes::ChannelField id = MipTypes::getChannelField_baseDataClass(static_cast<MipTypes::ChannelField>(field.fieldId()));

        switch(id)
        {
            //fields that should only be used as timestamp, and not stored as data
            case MipTypes::CH_FIELD_DISP_DISPLACEMENT_TS:
                isTimestamp = true;
                isData = false;
                break;

            //fields that will get passed along as data points as well
            case MipTypes::CH_FIELD_SENSOR_GPS_CORRELATION_TIMESTAMP:
            case MipTypes::CH_FIELD_GNSS_GPS_TIME:
            case MipTypes::CH_FIELD_ESTFILTER_GPS_TIMESTAMP:
            case MipTypes::CH_FIELD_SENSOR_SHARED_GPS_TIMESTAMP:
                isTimestamp = true;
                isData = true;
                break;

            default:
                break;
        }

        // don't re-process if a different timestamp already found
        if(isTimestamp && !m_hasDeviceTime)
        {
            m_hasDeviceTime = true;
            parseTimeStamp(field);
        }

        // get number of points prior to parsing new points
        // if field is shared, new points are then added to m_sharedFields
        size_t currentPointsCount = m_points.size();
        if(isData)
        {
            MipFieldParser::parseField(field, m_points);
        }

        // add data points from shared fields to m_sharedFields
        if (MipTypes::isSharedChannelField(id))
        {
            // add only the points newly added for this field at the end of m_points
            for (size_t i = currentPointsCount; i < m_points.size(); i++)
            {
                MipDataPoint& point = m_points[i];
                m_sharedFields.addPoint(point.field(), point.qualifier(), point);
            }
        }
    }

    bool MipDataPacket::timestampWithinRange(const Timestamp& timestamp) const
    {
        //timestamp is out of range if it is over an hour in the future
        static const uint64 NANOS_IN_1_HOUR = 3600000000000;

        //not valid if time is more than 1 hour in the past or future
        return ((timestamp - collectedTimestamp()).getNanoseconds() < NANOS_IN_1_HOUR);
    }

    void MipDataPacket::parseTimeStamp(const MipDataField& field)
    {
        DataBuffer bytes(field.fieldData());

        MipTypes::ChannelField id = MipTypes::getChannelField_baseDataClass(static_cast<MipTypes::ChannelField>(field.fieldId()));

        switch (id)
        {
            case MipTypes::CH_FIELD_DISP_DISPLACEMENT_TS:
            {
                m_deviceTimeFlags = bytes.read_uint8();
                m_deviceTimeValid = (m_deviceTimeFlags == 1);
                m_deviceTime.setTime(bytes.read_uint64());
                break;
            }

            case MipTypes::CH_FIELD_SENSOR_GPS_CORRELATION_TIMESTAMP:
            {
                double gpsTimeOfWeek = bytes.read_double();
                uint16 gpsWeekNumber = bytes.read_uint16();

                //convert to UTC time
                m_deviceTimeFlags = bytes.read_uint16();
                m_deviceTime.setTime(Timestamp::gpsTimeToUtcTime(gpsTimeOfWeek, gpsWeekNumber));

                //check the GPS time looks like a valid absolute timestamp
                //Note: unfortunately, the flags that come with this packet can't be used to identify this,
                //      so we are just checking for an old or future timestamp, since it starts at 0 when first powered on
                m_deviceTimeValid = timestampWithinRange(m_deviceTime);

                break;
            }

            case MipTypes::CH_FIELD_SENSOR_SHARED_GPS_TIMESTAMP:
            case MipTypes::CH_FIELD_GNSS_GPS_TIME:
            {
                double gpsTimeOfWeek = bytes.read_double();
                uint16 gpsWeekNumber = bytes.read_uint16();

                //convert to UTC time
                m_deviceTimeFlags = bytes.read_uint16();
                m_deviceTime.setTime(Timestamp::gpsTimeToUtcTime(gpsTimeOfWeek, gpsWeekNumber));

                //check the GPS time looks like a valid absolute timestamp
                //Note: we might be able to use the flags here, but we're doing this check for the other descriptor sets anyway
                m_deviceTimeValid = timestampWithinRange(m_deviceTime);

                break;
            }

            case MipTypes::CH_FIELD_ESTFILTER_GPS_TIMESTAMP:
            {
                double gpsTimeOfWeek = bytes.read_double();
                uint16 gpsWeekNumber = bytes.read_uint16();

                //convert to UTC time
                m_deviceTimeFlags = bytes.read_uint16();
                m_deviceTime.setTime(Timestamp::gpsTimeToUtcTime(gpsTimeOfWeek, gpsWeekNumber));

                //check the GPS time looks like a valid absolute timestamp
                //Note: unfortunately, the flags that come with this packet can't be used to identify this, as it seems
                //      they are invalid if the estimation filter isn't initialized, even if the time is initialized
                m_deviceTimeValid = timestampWithinRange(m_deviceTime);

                break;
            }

            default:
                assert(false);  //shouldn't get to this function without being able to parse the timestamp
                break;
        }

    }

    const MipDataPoints& MipDataPacket::data() const
    {
        return m_points;
    }

    const MipSharedDataFields& MipDataPacket::shared() const
    {
        return m_sharedFields;
    }

    const Timestamp& MipDataPacket::collectedTimestamp() const
    {
        return m_collectedTime;
    }

    const Timestamp& MipDataPacket::deviceTimestamp() const
    {
        return m_deviceTime;
    }

    bool MipDataPacket::deviceTimeValid() const
    {
        return m_deviceTimeValid;
    }

    bool MipDataPacket::hasDeviceTime() const
    {
        return m_hasDeviceTime;
    }

    uint16 MipDataPacket::deviceTimeFlags() const
    {
        return m_deviceTimeFlags;
    }
}


text:
This is the Perl version of the Try catch stack overflow. Use the try catch block used in [tcso.pl](tcso.pl). You can use it in your projects. Please don't forget to make  improvements and submit a new pull request.
#### Requirements
Uses perl Try::Tiny  module. Remember to include it in your code by using  `use Try:Tiny;` statement.
#### Credits
Developed by: [Gautam krishna R](https://github.com/gautamkrishnar/)

###### Contributors
*  [Peter Mayr](https://github.com/hatorikibble/)


text:
import logging
import os.path
import tempfile
import uuid

import aiohttp
import rdflib

from pit.archive import archive
from pit.pcdm import PcdmObject, PREFER_HEADER

class DocumentSet:
    def __init__(self, members, client):
        self.members = members
        self.client = client

    def __aiter__(self):
        return self

    async def __anext__(self):
        try:
            doc = self.members.pop(0)
        except IndexError:
            raise StopAsyncIteration
        res = await self.client.get(doc, headers={'Prefer': PREFER_HEADER,
                                                  'Accept': 'text/n3'})
        data = await res.text()
        graph = rdflib.Graph().parse(data=data, format='n3')
        return PcdmObject(graph, self.client)

async def create_package(url, session=None):
    session = session or aiohttp.ClientSession()
    tmp = tempfile.gettempdir()
    archive_name = os.path.join(tmp, uuid.uuid4().hex) + '.zip'
    res = await session.get(url)
    docset = await res.json()
    with archive(archive_name) as arxv:
        async for doc in DocumentSet(docset.get('members'), session):
            for f in doc.files:
                if f.mimetype == 'application/pdf':
                    r = await session.get(str(f.uri))
                    with tempfile.NamedTemporaryFile() as fp:
                        async for chunk in r.content.iter_chunked(1024):
                            fp.write(chunk)
                        arxv.write(fp.name, f.uri.split('/')[-1])
    return archive_name

class Packager:
    def __init__(self, bucket, session=None):
        self.bucket = bucket
        self.session = session or aiohttp.ClientSession()

    async def on_message(self, frame):
        logger = logging.getLogger(__name__)
        docset = frame.body.strip()
        try:
            arxv = await create_package(docset, self.session)
        except Exception as e:
            logger.error('Error creating package for docset {}: {}'
                         .format(docset, e))
            return
        try:
            size = os.stat(arxv).st_size
            blob = self.bucket.create(os.path.basename(arxv))
            await blob.upload(arxv)
            # notify API
        except Exception as e:
            logger.error('Error uploading package for docset {}: {}'
                         .format(docset, e))
        finally:
            os.remove(arxv)


text:
import time, types, os, sys, signal
import multiprocessing

"""
This class is simple enough to allow workers which take incomming log lines and do things with them.
I really dont know what people will want to do with there logs and how they will want to output them
but this is where they will be able to control the output system.
"""

workers = {}

def workerTarget(*args, **kw):
    global workers
    method_name = args[0]
    return getattr(workers[args[0]], 'worker_loop')(*args[1:])

class workerBase(object):

    def __init__(self, name="master", pool_size=0, queue_size=1024):
        self.queue_size, self.pool_size, self.name = queue_size, pool_size, name
        self.queue_active = True
        self.workers_stopped = False

        signal.signal(signal.SIGINT, self.signal_handler) #shut down hoandler
        signal.signal(signal.SIGTERM, self.signal_handler) #shut down hoandler

        if self.pool_size == 0: #if no size is set lets use the total number of processses the system have
            self.pool_size = multiprocessing.cpu_count()

        global workers
        workers[name] = self

    def run(self):
        if isinstance (self.worker_loop, types.MethodType):
            args = list()
            args.insert(0, self.name)

        self.queue = multiprocessing.Queue(self.queue_size)
        self.pool = multiprocessing.Pool(self.pool_size)
        for x in range(0, self.pool_size): #avoid needing to run map but still get all the workers to start up
            self.pool.apply_async(workerTarget, args)
        return self

    def queue_line(self, entry, metadata): #put the data in the queue
        if self.queue_active == True:
            try:
                self.queue.put([entry, metadata], False) #should come up with a better method that the server will wait on false and try to queue there
            except Queue.Full, e:
                print (str(e))
            except Exception, e:
                sys.stderr.write("queue_line: "+str(e)+"\n")
        else:
            return False

    def worker_stop(self):
        self.queue_active = False
        self.stop_loop = True

        if self.workers_stopped == False:
            while self.stop_loop == True:
                if self.queue.empty == False:
                    time.sleep(1)
                    sys.stderr.write("Waiting for queue: "+queue+" to reach 0, currntly at "+str(self.queue.qsize()))
                else:
                    try:
                        self.queue.close() # close the queue now since its empty
                    except:
                        pass
                    sys.stderr.write("Giving the workers a little more time to finish there last task\n")
                    self.stop_loop = False
                    self.workers_stopped = False
                    time.sleep(2)
                    try:
                        sys.stderr.write("Closing pool\n")
                        self.pool.close()
                        sys.stderr.write("after pool close\n")
                    finally:
                        sys.stderr.write("")
                        exit()
        sys.stderr.write("")
        exit(False)

    def worker_loop(self): #to simplyfiy things this is the loop that feeds the data into the worker so users just need to handle data entry or what ever
        while self.queue.empty == False or self.workers_stopped == False:
            try:
                #sys.stderr.write("Queue size: "+str(self.queue.qsize())+" @ "+str(time.time())+"\n")
                todo = self.queue.get()
                #print sys.stderr.write("Queue object: "+str(todo)+"\n")
                self.worker(todo[0], todo[1])
                #time.sleep(1)
            except Queue.Empty, e:
                print (str(e))
                time.sleep(1)
            except Exception, e:
                sys.stderr.write("worker_loop: "+str(e)+"\n")

        exit()
        return True

    def worker(self, entry, metadata):
        raise NotImplementedError( "Write a method that gets run as a callback once for every log entry worker(self, entry, metadata)" )

    def signal_handler(self, signal, frame):
        self.worker_stop()


text:
package org.joeffice.desktop.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import org.joeffice.desktop.ui.OfficeTopComponent;

import org.openide.cookies.CloseCookie;
import org.openide.cookies.OpenCookie;
import org.openide.cookies.SaveCookie;
import org.openide.cookies.ViewCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.*;
import org.openide.nodes.Children;
import org.openide.nodes.CookieSet;
import org.openide.nodes.Node;
import org.openide.util.Lookup;
import org.openide.windows.CloneableTopComponent;

/**
 * Generic data object for the office documents.
 * This class is abstract as sub class should implement opening and saving a document.
 *
 * @author Anthony Goubard - Japplis
 */
public abstract class OfficeDataObject extends MultiDataObject implements SaveCookie, SaveAsCapable, CookieSet.Factory {

    private Object document;

    private OfficeOpenSupport opener;

    public OfficeDataObject(FileObject pf, MultiFileLoader loader) throws DataObjectExistsException {
        super(pf, loader);
        CookieSet cookies = getCookieSet();
        cookies.add(OfficeOpenSupport.class, this);
        cookies.add(SaveCookie.class, this);
        cookies.assign(SaveAsCapable.class, this);
    }

    public void setDocument(Object document) {
        this.document = document;
    }

    public Object getDocument() {
        return document;
    }

    @Override
    public void setModified(boolean modified) {
        super.setModified(modified);
        if (modified) {
            getCookieSet().add(this);
        } else {
            getCookieSet().remove(this);
        }
    }

    @Override
    protected Node createNodeDelegate() {
        return new DataNode(this, Children.LEAF, getLookup());
    }

    @Override
    public Lookup getLookup() {
        return getCookieSet().getLookup();
    }

    @Override
    public <T extends Node.Cookie> T createCookie(Class<T> type) {
        if (type.isAssignableFrom(OfficeOpenSupport.class)) {
            if (opener == null) {
                opener = new OfficeOpenSupport(getPrimaryEntry());
            }
            return (T) opener;
        }
        if (type.isAssignableFrom(SaveCookie.class)) {
            return (T) this;
        }
        return null;
    }

    @Override
    protected int associateLookup() {
        return 1;
    }

    @Override
    public synchronized void save() throws IOException {
        File currentFile = FileUtil.toFile(getPrimaryFile());
        File backup = backupOriginal(currentFile);
        File secureSave = new File(currentFile.getAbsolutePath() + ".new." + getPrimaryFile().getExt());
        save(secureSave);
        if (secureSave.exists() && secureSave.length() > 0) {
            try (OutputStream currentFileStream = new FileOutputStream(currentFile)) {
                Files.copy(secureSave.toPath(), currentFileStream);
            }
            boolean deleted = backup.delete();
            boolean newDeleted = secureSave.delete();
        }
        setModified(false);
    }

    private synchronized File backupOriginal(File currentFile) throws IOException {
        File backupFile = new File(currentFile.getAbsolutePath() + ".backup." + getPrimaryFile().getExt());
        if (!backupFile.exists() && currentFile.length() > 0) {
            Files.copy(currentFile.toPath(), backupFile.toPath(), StandardCopyOption.COPY_ATTRIBUTES);
        }
        return backupFile;
    }

    @Override
    public void saveAs(FileObject folder, String fileName) throws IOException {
        FileObject newFile = folder.getFileObject(fileName);
        if (newFile == null) {
            newFile = folder.createData(fileName);
        }
        save(FileUtil.toFile(newFile));
    }

    public abstract OfficeTopComponent open(OfficeDataObject dataObject);

    public abstract void save(File file) throws IOException;

    private class OfficeOpenSupport extends OpenSupport implements OpenCookie, CloseCookie, ViewCookie {

        private OfficeOpenSupport(MultiDataObject.Entry entry) {
            super(entry);
        }

        @Override
        protected CloneableTopComponent createCloneableTopComponent() {
            OfficeDataObject dataObject = (OfficeDataObject) entry.getDataObject();
            return OfficeDataObject.this.open(dataObject);
        }
    }
}