text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.CMS.Content.Models;
using NCMIS.Produce;
using Kooboo.CMS.Content.Services;
using NCMIS.ObjectModel;
using Kooboo.Extensions;

namespace Kooboo.CMS.Content.Interoperability.CMIS
{
    public class FolderObjectService : IObjectService
    {
        string prefix = "_folder";

        public CmisObject CreateFolder(string repositoryId, NCMIS.ObjectModel.CmisProperties properties, string folderId)
        {
            Kooboo.CMS.Content.Models.Repository repository = new Models.Repository(repositoryId);
            Folder parent = null;
            var objectId = folderId;

            var values = properties.ToNameValueCollection();
            if (string.IsNullOrEmpty(values["name"]))
            {
                throw new Exception("The property \"Name\" is required.");
            }
            if (TryPraseObjectId(objectId, out folderId))
            {
                var folderType = CmisFolderHelper.IdentifyFolderType(repository, folderId);
                switch (folderType)
                {
                    case FolderType.Root:
                        throw new Exception("Could not create folder under root folder.");
                    case FolderType.Content_Folder_Root:
                        parent = null;
                        return AddContentFolder(repository, parent, values);

                    case FolderType.Media_Folder_Root:
                        parent = null;
                        return AddMediaFolder(repository, parent, values);

                    case FolderType.Content_Folder:
                        parent = CmisFolderHelper.Parse(repository, folderId);
                        return AddContentFolder(repository, parent, values);

                    case FolderType.Media_Folder:
                        parent = CmisFolderHelper.Parse(repository, folderId);
                        return AddMediaFolder(repository, parent, values);
                    default:
                        break;
                }
            }
            throw new InvalidOperationException("Create folder failed.");
        }

        private static CmisObject AddContentFolder(Kooboo.CMS.Content.Models.Repository repository, Folder parent, System.Collections.Specialized.NameValueCollection values)
        {
            var textFolder = new TextFolder(repository, values["name"], parent);
            textFolder.DisplayName = values["DisplayName"];
            textFolder.SchemaName = values["schemaName"];
            var categories = values["CategoryFolders"];
            if (!string.IsNullOrEmpty(categories))
            {
                textFolder.CategoryFolders = categories.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            }
            var creationDate = values["UtcCreationDate"];
            if (!string.IsNullOrEmpty(creationDate))
            {
                textFolder.UtcCreationDate = DateTime.Parse(creationDate).ToUniversalTime();
            }

            ServiceFactory.TextFolderManager.Add(repository, textFolder);

            return ObjectConvertor.ToCmis(textFolder, false);
        }

        private static CmisObject AddMediaFolder(Kooboo.CMS.Content.Models.Repository repository, Folder parent, System.Collections.Specialized.NameValueCollection values)
        {
            var mediaFolder = new MediaFolder(repository, values["name"], parent);
            mediaFolder.DisplayName = values["DisplayName"];
            var allowedExtensions = values["AllowedExtensions"];
            if (!string.IsNullOrEmpty(allowedExtensions))
            {
                mediaFolder.AllowedExtensions = allowedExtensions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }

            var creationDate = values["UtcCreationDate"];
            if (!string.IsNullOrEmpty(creationDate))
            {
                mediaFolder.UtcCreationDate = DateTime.Parse(creationDate).ToUniversalTime();
            }

            ServiceFactory.MediaFolderManager.Add(repository, mediaFolder);

            return ObjectConvertor.ToCmis(mediaFolder, false);
        }

        #region IObjectService<Folder> Members

        public bool TryPraseObjectId(string objectId, out string id)
        {
            id = string.Empty;
            if (IsSystemFolder(objectId))
            {
                id = objectId;
                return false;
            }
            if (objectId.StartsWith(prefix))
            {
                id = objectId.Substring(prefix.Length);
                return true;
            }
            return false;
        }
        public bool IsSystemFolder(string objectId)
        {
            if (objectId.EqualsOrNullEmpty(CmisFolderHelper.Content_Folder_Root, StringComparison.CurrentCultureIgnoreCase)
                || objectId.EqualsOrNullEmpty(CmisFolderHelper.Media_Folder_Root, StringComparison.CurrentCultureIgnoreCase)
                || objectId.EqualsOrNullEmpty(CmisFolderHelper.RootFolderName, StringComparison.CurrentCultureIgnoreCase))
            {
                return true;
            }
            return false;
        }
        public string GetObjectId(object o)
        {
            return prefix + CmisFolderHelper.CompositeFolderId((Folder)o);
        }

        public NCMIS.ObjectModel.CmisObject GetObject(string objectId)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<NCMIS.ObjectModel.CmisObject> All(string repositoryId)
        {
            throw new NotImplementedException();
        }
        public IEnumerable<NCMIS.ObjectModel.CmisObject> GetChildren(string repositoryId, string objectId, string filter, IncludeRelationships includeRelationships)
        {
            Kooboo.CMS.Content.Models.Repository repository = new Models.Repository(repositoryId);
            string folderId;
            TryPraseObjectId(objectId, out folderId);
            switch (CmisFolderHelper.IdentifyFolderType(repository, folderId))
            {
                case FolderType.Root:
                    return new[] {
                    CmisFolderHelper.CreateSystemFolderObject(CmisFolderHelper.Content_Folder_Root,CmisFolderHelper.RootFolderName),
                   CmisFolderHelper.CreateSystemFolderObject(CmisFolderHelper.Media_Folder_Root,CmisFolderHelper.RootFolderName)
                    };
                case FolderType.Content_Folder_Root:
                    return ServiceFactory.TextFolderManager.All(repository, filter).Select(it => ObjectConvertor.ToCmis((TextFolder)(it.AsActual()), includeRelationships != IncludeRelationships.None));
                case FolderType.Media_Folder_Root:
                    return ServiceFactory.MediaFolderManager.All(repository, filter).Select(it => ObjectConvertor.ToCmis((MediaFolder)(it.AsActual()), includeRelationships != IncludeRelationships.None));
                case FolderType.Content_Folder:
                    var textFolder = (TextFolder)CmisFolderHelper.Parse(repository, folderId);
                    return ServiceFactory.TextFolderManager.ChildFolders(textFolder, filter).Select(it => ObjectConvertor.ToCmis((TextFolder)(it.AsActual()), includeRelationships != IncludeRelationships.None));
                case FolderType.Media_Folder:
                    var mediaFolder = (MediaFolder)CmisFolderHelper.Parse(repository, folderId);
                    return ServiceFactory.MediaFolderManager.ChildFolders(mediaFolder, filter).Select(it => ObjectConvertor.ToCmis((MediaFolder)(it.AsActual()), includeRelationships != IncludeRelationships.None));
                default:
                    break;
            }
            return new[] { ObjectConvertor.EmptyCmisObject() };
        }

        public NCMIS.ObjectModel.CmisObject GetParent(string repositoryId, string objectId)
        {
            Kooboo.CMS.Content.Models.Repository repository = new Models.Repository(repositoryId);
            string folderId;

            if (!IsSystemFolder(objectId) && TryPraseObjectId(objectId, out folderId))
            {
                var folder = CmisFolderHelper.Parse(repository, folderId);

                if (folder.Parent != null)
                {
                    return ObjectConvertor.ToCmis(folder.Parent.AsActual(), false);
                }
            }

            return ObjectConvertor.EmptyCmisObject();
        }

        public void DeleteObject(string repositoryId, string objectId)
        {
            string folderId;
            TryPraseObjectId(objectId, out folderId);
            Kooboo.CMS.Content.Models.Repository repository = new Models.Repository(repositoryId);
            var folder = CmisFolderHelper.Parse(repository, folderId);

            if (folder is TextFolder)
            {
                ServiceFactory.TextFolderManager.Remove(repository, (TextFolder)folder);
            }
            else
            {
                ServiceFactory.MediaFolderManager.Remove(repository, (MediaFolder)folder);
            }

        }

        public NCMIS.ObjectModel.MetaData.AllowableActions GetAllowableActions(string repositoryId, string objectId)
        {
            if (IsSystemFolder(objectId))
            {
                return new NCMIS.ObjectModel.MetaData.AllowableActions()
                {
                    CanAddObjectToFolder = false,
                    CanApplyACL = false,
                    CanApplyPolicy = false,
                    CanCancelCheckOut = false,
                    CanCheckIn = false,
                    CanCheckOut = false,
                    CanCreateDocument = false,
                    CanCreateFolder = CmisFolderHelper.IdentifyFolderType(new Kooboo.CMS.Content.Models.Repository(repositoryId), objectId) != FolderType.Root,
                    CanCreateRelationship = false,
                    CanDeleteContentStream = false,
                    CanDeleteObject = true,
                    CanDeleteTree = false,
                    CanGetACL = false,
                    CanGetAllVersions = false,
                    CanGetAppliedPolicies = false,
                    CanGetChildren = true,
                    CanGetContentStream = false,
                    CanGetDescendants = false,
                    CanGetFolderParent = false,
                    CanGetFolderTree = false,
                    CanGetObjectParents = false,
                    CanGetObjectRelationships = true,
                    CanGetProperties = false,
                    CanGetRenditions = false,
                    CanMoveObject = false,
                    CanRemoveObjectFromFolder = false,
                    CanRemovePolicy = false,
                    CanSetContentStream = false,
                    CanUpdateProperties = false

                };
            }
            else
            {
                return new NCMIS.ObjectModel.MetaData.AllowableActions()
                {
                    CanAddObjectToFolder = false,
                    CanApplyACL = false,
                    CanApplyPolicy = false,
                    CanCancelCheckOut = false,
                    CanCheckIn = false,
                    CanCheckOut = false,
                    CanCreateDocument = true,
                    CanCreateFolder = true,
                    CanCreateRelationship = true,
                    CanDeleteContentStream = false,
                    CanDeleteObject = true,
                    CanDeleteTree = false,
                    CanGetACL = false,
                    CanGetAllVersions = false,
                    CanGetAppliedPolicies = false,
                    CanGetChildren = true,
                    CanGetContentStream = true,
                    CanGetDescendants = false,
                    CanGetFolderParent = true,
                    CanGetFolderTree = false,
                    CanGetObjectParents = false,
                    CanGetObjectRelationships = true,
                    CanGetProperties = true,
                    CanGetRenditions = false,
                    CanMoveObject = false,
                    CanRemoveObjectFromFolder = false,
                    CanRemovePolicy = false,
                    CanSetContentStream = false,
                    CanUpdateProperties = true

                };
            }
        }

        public ContentStream GetContentStream(string repositoryId, string objectId, string streamId)
        {
            throw new NotSupportedException();
        }

        public CmisObject GetObject(string repositoryId, string objectId)
        {
            string folderId;
            TryPraseObjectId(objectId, out folderId);
            Kooboo.CMS.Content.Models.Repository repository = new Models.Repository(repositoryId);
            var folder = CmisFolderHelper.Parse(repository, folderId);

            return ObjectConvertor.ToCmis(folder.AsActual(), false);
        }

        public CmisProperties GetProperties(string repositoryId, string objectId)
        {
            return GetObject(repositoryId, objectId).Properties;
        }

        public void SetContentStream(string repositoryId, string documentId, ContentStream contentStream, bool? overwriteFlag)
        {
            throw new NotSupportedException();
        }

        public void UpdateProperties(string repositoryId, string objectId, CmisProperties properties)
        {
            Kooboo.CMS.Content.Models.Repository repository = new Models.Repository(repositoryId);
            string folderId;
            TryPraseObjectId(objectId, out folderId);
            var folder = CmisFolderHelper.Parse(repository, folderId);

            var values = properties.ToNameValueCollection();
            if (folder is TextFolder)
            {
                var textFolder = (TextFolder)folder;

                if (values["DisplayName"] != null)
                {
                    textFolder.DisplayName = values["DisplayName"];
                }
                if (values["SchemaName"] != null)
                {
                    textFolder.SchemaName = values["SchemaName"];
                }
                if (values["CategoryFolders"] != null)
                {
                    textFolder.CategoryFolders = values["CategoryFolders"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                }
                ServiceFactory.TextFolderManager.Update(repository, textFolder, textFolder);
            }
            else
            {
                var mediaFolder = (MediaFolder)folder;
                if (values["DisplayName"] != null)
                {
                    mediaFolder.DisplayName = values["DisplayName"];
                }
                if (values["AllowedExtensions"] != null)
                {
                    mediaFolder.AllowedExtensions = values["AllowedExtensions"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                }
                ServiceFactory.MediaFolderManager.Update(repository, mediaFolder, mediaFolder);
            }
        }

        #endregion
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.springframework.ejb.support (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package org.springframework.ejb.support

Superclasses to make implementing EJBs simpler and less error-prone,
as well as guaranteeing a Spring BeanFactory is available to EJBs.

See:

          Description

Interface Summary

SmartSessionBean
Interface to be implemented by Session Beans that want
 to expose important state to cooperating classes.

Class Summary

AbstractEnterpriseBean
Base class for all Spring-based EJBs.

AbstractJmsMessageDrivenBean
Convenient superclass for JMS MDBs.

AbstractMessageDrivenBean
Convenient superclass for MDBs.

AbstractSessionBean
Base class for all Spring-based EJB session beans.

AbstractStatefulSessionBean
Convenient superclass for stateful session beans.

AbstractStatelessSessionBean
Convenient superclass for stateless session beans (SLSBs), minimizing
 the work involved in implementing an SLSB and preventing common errors.

Package org.springframework.ejb.support Description

Superclasses to make implementing EJBs simpler and less error-prone,
as well as guaranteeing a Spring BeanFactory is available to EJBs.
This promotes good practice, with EJB services used for transaction
management, thread management, and (possibly) remoting, while
business logic is implemented in easily testable POJOs.

In this model, the EJB is a facade, with as many POJO helpers
behind the BeanFactory as required.

The classes in this package are discussed in Chapter 11 of
Expert One-On-One J2EE Design and Development
by Rod Johnson (Wrox, 2002).
The present version has changed somewhat, but has the same goals.

Note that the default behavior is to look for an EJB enviroment variable
with name ejb/BeanFactoryPath that specifies the
location on the classpath of an XML bean factory definition
file (such as /com/mycom/mypackage/mybeans.xml).
If this JNDI key is missing, your EJB subclass won't successfully
initialize in the container.

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2007 The Spring Framework.

redpajama_set_name: RedPajamaGithub


text:
package com.martensigwart.fakeload;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * Created by martensigwart on 28.07.17.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
        SimpleFakeLoadTest.class,
        CompositeFakeLoadTest.class
})
public class FakeLoadTestSuite {
}


text:
* {
	transition:none!important;
	animation:none!important;
	box-shadow:none!important;
}

.tweet-button {
	transform:scale(1);
}

.mtd-drawer-button {
	opacity:1;
}


text:
layout: post
title: "Reactive Programming in Python"
description: "Learn how to use reactive programming in Python to process data streams asynchronously."
longdescription: "Let's learn how to use reactive programming in Python to create asynchronous and event-based programs by implementing observables, observers/subscribers, and subjects. We will start by getting our data stream from the GitHub with a Tornado web socket and then we will filter and process it asynchronously."
date: "2018-01-25 08:30"
author:
  name: "Valery Calderon"
  url: "https://twitter.com/valerybriz"
  mail: "valerybriz@gmail.com"
  avatar: "https://twitter.com/valerybriz/profile_image?size=original"
design:
  bg_color: "#4A4A4A"
  image: https://cdn.auth0.com/blog/python-restful/logo.png
tags:
- python
- reactive
- programming
- reactive-programming
- rxpy
- functional
- github
- tornado
related:
- 2017-09-28-developing-restful-apis-with-python-and-flask
- 2017-04-20-image-processing-in-python-with-pillow
- 2017-12-06-mocking-api-calls-in-python
---

**TL;DR:** In this tutorial, we'll be learning how to use the [RxPy](https://rxpy.codeplex.com/) library to create asynchronous and event-based programs by implementing observables, observers/subscribers, and subjects. We will start by getting our data stream from the [GitHub API](https://developer.github.com/v3/) with a [Tornado](http://www.tornadoweb.org) web socket and then we will filter and process it asynchronously. [In this GitHub repository](https://github.com/valerybriz/RxGithubSearcher), you can find the code that we are going to create in this tutorial.

## Why Reactive Programming?

In a way, reactive programming isn't a new thing. Our typical click events are an asynchronous data stream which we can observe and trigger actions from it. That's how it works, but Reactive Programming makes things so much easier by adding a toolbox of operators to filter, create, transform, and unify any of those streams. In just a few lines of maintainable code, we can have web sockets that receive multiple requests and handle them on an asynchronous process that serves a filtered output.

Web applications contain lots of database operations, network calls, nested callbacks, and other computationally expensive tasks that might take a long time to complete (or even block other threads until it's done). This is where Reactive Programming enters, it gives us the facility to convert almost anything to streams (like variables, properties, user inputs, caches, etc) to manage it asynchronously. Besides that, it also gives us an easy way to handle errors. A task that is usually hard task within asynchronous programming. Reactive Programming makes our code more flexible, readable, maintainable, and easy to write.

{% include tweet_quote.html quote_text="Reactive Programming makes our code more flexible, readable, maintainable, and easy to write." %}

## What Does Reactive Programming Really Means?

The main difference between [Event-Driven programming](https://en.wikipedia.org/wiki/Event-driven_programming) and Reactive Programming is the real trigger of the action. While the Event-Driven programming focuses on handling any event (such as a button click) to trigger the corresponding action, Reactive Programming wraps data into the reactive system as events. This enables us to do things like listening to user inputs as events that trigger actions only if the input changed from the previous one.

{% include tweet_quote.html quote_text="Reactive, in Reactive Programming, means a dynamic reaction to change in streams." %}

Reactive Programming is a programming paradigm oriented around data flows and the propagation of change. This means that, when a data flow is emitted by one component, the Reactive Programming library will automatically propagate those changes to other components until it reaches the final receiver.

## How Does Reactive Programming Works?

Let's take into consideration [ReactiveX](http://reactivex.io/), the most famous implementation of the Reactive Programming paradigm. ReactiveX is mainly based on two classes: the `Observable` and `Observer` classes. The `Observable` class is the source of data streams or events and the `Observer` class is the one that consumes (or reacts to) the emitted elements.

### Observables in Reactive Programming

An `Observable` packs the incoming data so it can be passed from one thread to another. The `Observable` can be configured so it regulates when to supply data. For example, it could be triggered periodically or only once in their life cycle. There are also various functions that can be used to filter or transform the observable so the observer only emits certain data. All this is used instead of callbacks, which means that our code becomes more readable and less fallible.

```python
from rx import Observable, Observer

source = Observable.from_list([1,2,3,4,5,6])
```

It's common to use `Observables` in a way that it doesn't give data until some `Observer` subscribes to it. Known as ["call by need"](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_need), this is an evaluation strategy which delays the evaluation of an event until its value is needed.

### Observers in Reactive Programming

The `Observer` consumes the data stream emitted by the `Observable`. An `Observable` can have multiple `Observers` so each data item emitted will be received by each `Observer`. The "listening" to the stream is called subscribing. `Observers` subscribe to the `Observable` with the `subscribe()` method to receive the emitted data.

The `Observer` can receive three types of events:

* **on_next()**: when there is an element in the data stream;
* **on_completed()**: when no more items are coming, it implies end of emission.
* **on_error()**: when there is an error thrown from the `Observable` (it also implies end of emission);

```python
class PrintObserver(Observer):

    def on_next(self, value):
        print("Received {0}".format(value))

    def on_completed(self):
        print("Done!")

    def on_error(self, error):
        print("Error Occurred: {0}".format(error))

source.subscribe(PrintObserver())
```

We don't have to specify all three event types in the code. We can choose which events to observe using the named arguments, or simply providing a lambda for the `on_next` function. Typically, in production, we will want to provide an `on_error` handler so errors are explicitly handled by the subscriber.

```python
source = Observable.from_list([1,2,3,4,5,6])

source.subscribe(lambda value: print("Received {0}".format(value)))
```

### Subjects in Reactive Programming

The `Subject` is the `Observable` extension that simultaneously implements the `Observer` interface. That is, `Subjects` acts like both `Observers` and `Observables`. They receive messages about events (like `Observers`) and notify their subscribers (like `Observables`). This implies two things:

* We can subscribe to a `Subject`, just like an `Observable`.
* A `Subject` can subscribe to other `Observables`.

Therefore, the main difference between a `Subject` and an `Observable` is that all of the `Subject` subscribers share the same action. This means that, when a `Subject` produces data, all of its subscribers will receive the same data. This is unlike `Observables`, where each subscription causes an independent execution of the observable.

A `Subscriber` can not only subscribe to an `Observable` but also unsubscribe from it. It is important to remember to unsubscribe from the asynchronous calls. When calling `unsubscribe()`, all the operators unsubscribe from one another in sequence from top to bottom. So we can avoid memory leaks. In the case of the `Subjects`, we will use the `dispose` method which can be thought of as the subscription itself, or perhaps a token representing the subscription. Disposing it will dispose the subscription and also unsubscribe. The unsubscribe call can be placed in the socket `on_close()` method:

```python
def on_close(self):
    self.combine_latest_sbs.dispose()
    print("WebSocket closed")
```

### Data Operators in Reactive Programming

The essence of Reactive Programming is working with streams. As we saw before, we have an `Observable` class that supplies the data stream and an `Observer` which consumes it. But, along the way from the `Observable` to the subscriber, we can apply many `Operators` to the stream. These `Operators` define how and when the `Observables` should emit streams.

Most `Operators` execute a function on an `Observable` and return an `Observable`. So we can apply these operators one after the other, in a chain. Each operator in the chain modifies the `Observable` that results from the operation of the previous operator.

There are plenty of operators available. We will be exploring only the ones that we use for this tutorial. The operators can be classified by categories of their utility as:

* Creating Observables
* Transforming Observables
* Filtering Observables
* Combining Observables
* Error Handling Operators
* Observable Utility Operators
* Conditional and Boolean Operators
* Mathematical and Aggregate Operators
* Connectable Observable Operators

#### **Creating Observables Category**

The `just()` operator, as the name suggests, emits `Observables` with the same values provided in the arguments.

![Just operator marble diagram](https://cdn.auth0.com/blog/rxpy/just.png)

As we can see in the following example, our `Observable` just emits `a`, `b`, `c`, `d` one after another:

```python
Observable.just(a,b,c,d)
```

The `interval()` operator creates an `Observable` that emits a sequence of integers spaced by a given time interval.

![Interval operator marble diagram](https://cdn.auth0.com/blog/rxpy/interval.png)

For example, the following `Observable` refreshes the value every 60 Seconds for periodic updates:

```python
Observable.interval(60000)
```

#### **Filtering Observables Category**

The `filter()` operator emits only those items from an `Observable` that pass a predicate test.

![ Filter operator marble diagram](https://cdn.auth0.com/blog/rxpy/filter.png)

In the following example, we are filtering by the text size so it emits only the strings that exceed a length of 2 characters.

```python
Subject.filter( lambda text: not text or len(text) > 2 )
```

The `throttle_last()` operator emits the most recent items emitted by an `Observable` within periodic time intervals.

![ ThrottleLast operator marble diagram](https://cdn.auth0.com/blog/rxpy/throttlelast.png)

For example, to get the last value in a given time interval we could use RxPy as follows:

```python
Subject.throttle_last( 1000 )
```

#### **Transforming Observables Category**

The `flat_map()` operator transforms the items emitted by an `Observable` into `Observables`, then flatten the emissions from those into a single `Observable`.

![Flat_Map operator marble diagram](https://cdn.auth0.com/blog/rxpy/flat_map.png)

Here we get the repositories information by the user input which is the name of the organization repository. As you can see, we are calling a `from_future()` observable, since we use an asynchronous tornado web socket to request the API information.

```python
Subject.flat_map( lambda name: Observable.from_future(self.get_org_repos(name)) )
```

#### **Observable Utility Operators Category**

The `do_action()` operator registers an action to take upon a variety of `Observable` lifecycle events.

![ Do_action operator marble diagram](https://cdn.auth0.com/blog/rxpy/do_action.png)

Here we call the `send_response` function for each item in the data stream.

```python
Subject.do_action( lambda x: send_response('clear') )
```

#### **Combining Observables Category**

The `combine_latest()` operator combines, when an item is emitted by either of two `Observables`, the latest item emitted by each `Observable` via a specified function and emit items based on the results of this function.

![Combine_lastest operator marble diagram](https://cdn.auth0.com/blog/rxpy/combine_lastest.png)

Here we combine an interval `Observable` which will be sending the last input of the user every 60 seconds and the `input_value` `Observable` itself which will be emitted every time it changes:

```python
user_input.combine_latest( interval_observable, lambda input_value, i: input_value )
```

## Advantages of Reactive Programming

With Reactive Programming, we can raise the level of abstraction of our code so we can focus on the interdependence of events that define the business logic, rather than having to constantly fiddle with a large number of implementation details. With the help of the functional programming, the code will also be more concise.

We can use Reactive Programming to process asynchronous incoming data—perhaps tasks with a lot of user interaction (clicks, gestures, etc.)—or processing system events (sensors, gyroscope, etc.). That is, we can use with all kind of interactions where the events are portrayed as the object states. Such an approach allows better dynamic process description, also simplifying the asynchronous code writing. Finally, we've got better performance in the asynchronous context and the parallel processing of the data streams.

## Building an App with RxPy

First of all, we need to set up our environment by installing all the requirements we need to get our reactive web socket working. To do that in an easier and more organized way we are going to use [Pipenv](https://github.com/kennethreitz/pipenv). Pipenv is a dependency manager that isolates projects on private environments, replacing `pip` and allowing us to install only what we really need for a certain project. With Pipenv, we will easily manage the environment and the libraries we need to install.

```bash
# we might need to use pip3 instead of pip
pip install pipenv
```

Now, we have to create the new environment by executing the following commands:

```bash
# create our project directory and move to it
mkdir rxtornado && cd rxtornado

# run pipenv to create a Python 3 (--three) virtualenv for our project
pipenv --three

# you might need to define what SSL library to use
# http://pycurl.io/docs/latest/install.html#ssl
export PIP_GLOBAL_OPTION="--with-openssl"

# install the dependencies we need
pipenv install tornado rx pycurl
```

Once we execute these commands we can find two new files created on our project's root directory:

* `Pipfile`: a file that contains details about our project, like the Python version that we are using and the packages that our project needs.
* `Pipenv.lock`: a file that contains exactly what version of each package our project depends on, and their transitive dependencies.

Now that we are ready with the environment, we need to create a file called `config.py` which will contain constants (like the `address` of the organizations we will be searching for in GitHub) and also a token to use the GitHub API. We will have to replace `<TOKEN>` with our own GitHub Token. To get one, we need to follow the instructions on [this page](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/).

```python
TOKEN = <TOKEN>
headers = {
    "Content-Type": "application/json",
    "Authorization": "token " + TOKEN
}
GITHUB_API_URL = "https://api.github.com"
orgs = ["/twitter/repos", "/auth0/repos", "/nasa/repos", "/mozilla/repos", "/adobe/repos"]
```

After that, we need to create a file called `server.py` which will contain the main code for the project. For this code, we need to import certain modules from the libraries we just installed:

```python
import json
import os
import config as conf

from rx import Observable
from rx.subjects import Subject
from tornado import ioloop
from tornado.escape import json_decode
from tornado.httpclient import AsyncHTTPClient
from tornado.web import Application, RequestHandler, StaticFileHandler, url
from tornado.websocket import WebSocketHandler
```

Here we have imported the `Observable` and `Subject` modules from the RxPy library and the `async` and `websocket` modules from Tornado to handle the requests.

It is important to notice that, to use the GitHub API authentication, we need to configure the Tornado HttpClient as a `curl` async client with the following line right after the imported libraries:

```python
AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
```

We also need to initialize our headers and the organizations' addresses we already declared on the config file.

```python
headers = conf.headers
GIT_ORG = conf.GITHUB_API_URL+"/orgs"
```

### Building a WebSocket Handler

Our application will exchange messages with a browser using web sockets. Web sockets allow bidirectional communication between the browser and server in real time. The main idea is to define a class that inherits from the `WebSocketHandler` class. We can find more information about Tornado WebSockets [here](http://www.tornadoweb.org).

Let's define the `WebSocketHandler` class with the following code:

```python
class WSHandler(WebSocketHandler):
    orgs = conf.orgs

    def check_origin(self, origin):
        #Override to enable support for allowing alternate origins.
        return True
```

Here we are initializing the organizations names and defining the origin check, which we can override if we need support for alternate origins.

### Obtaining Data

To obtain the data from the GitHub API, first we need to define a function inside our `WebSocketHandler`. This function will create an asynchronous `http_client` which will take the organization names received and return the requested repository information asynchronously as a response.

```python
def get_org_repos(self, org):
    """request the repos to the GitHub API"""
    http_client = AsyncHTTPClient()
    response = http_client.fetch(GIT_ORG + org, headers=headers, method="GET")
    return response
```

In our implementation of the `WebSocketHandler` class, we will override the following methods:

* `on_message()`: This function will be called when there is an incoming message on the web socket. As our response is formatted as JSON objects, we have to decode it and then push it to the `Subject` with the `on_next()` operator.
* `on_close()`: This function will be called once we close the web socket. As we read before, it is very important to unsubscribe the `Observable` once the operation has been terminated to avoid memory leaks. As such, in this method we are going to use the `dispose()` method.
* `open()`: This function will be called when the web socket is opened for the first time.

Inside the `open()` method, we are also going to define the `send_response()` and `on_error()` methods to handle this two kinds of events. In this case, we are printing the message or the exception on the log.

```python
def on_message(self, message):
    obj = json_decode(message)
    self.subject.on_next(obj['term'])

def on_close(self):
    # Unsubscribe from observable
    #  will stop the work of all observable
    self.combine_latest_sbs.dispose()
    print("WebSocket closed")

def open(self):
    print("WebSocket opened")
    self.write_message("connection opened")

    def send_response(x):
        self.write_message(json.dumps(x))

    def on_error(ex):
        print(ex)

    self.subject = Subject()

    user_input = self.subject.throttle_last(
        1000  # Given the last value in a given time interval
    ).start_with(
        ''  # Immediately after the subscription sends the default value
    ).filter(
        lambda text: not text or len(text) > 2
    )

    interval_obs = Observable.interval(
        60000  #refresh the value every 60 Seconds for periodic updates
    ).start_with(0)

    self.combine_latest_sbs = user_input.combine_latest(
        interval_obs, lambda input_val, i: input_val
    ).do_action(
        lambda x: send_response('clear')
    ).flat_map(
        self.get_data
    ).subscribe(send_response, on_error)
```

We are going to filter the incoming user input by the size of the string to consider values with a length higher than 2 characters. Then, we are going to emit these values.

After that, we are going to create an interval `Observable` which will help us to "refresh" the input every 60 seconds and push this input again to the `Subject`.

Finally, we will combine both the interval `Observable` and the input value `Subject` so when either of it has a change it will be emitting a Subject to the chain. The chain will send it to the `send_response` method and then to the `get_data` method to be filtered and showed as the result.

### Filtering Incoming Data

To get the data filtered, we are going to use a chain of `Observable` maps which are going to take the query (the user input) and evaluate it according to the requirements we have set.

First we need to create the `get_info` method inside the `WebSocketHandler` class with the following:
```python
def get_info(self,req):
    """managing error codes and returning a list of json with content"""
    if req.code == 200:
        jsresponse = json.loads(req.body)
        return jsresponse
    elif req.code == 403:
        print("403 error")
        jsresponse = json.loads(req.body)
        return json.dumps("clear")
    else:
        return json.dumps("failed")
```

This method will help us to handle the exceptions of the request or, if everything's ok (`code == 200`), we will get a JSON formatted response with the information.

Now, we create the `get_data` method also inside the `WebSocketHandler` class with:

```python
def get_data(self,query):
    """ query the data to the API and return the contet filtered"""
    return Observable.from_list(
        self.orgs
    ).flat_map(
        lambda name: Observable.from_future(self.get_org_repos(name))
    ).flat_map(
        lambda x: Observable.from_list(

            self.get_info(x) #transform the response to a json list

         ).filter(

            lambda val: (val.get("description") is not None
		and (val.get("description").lower()).find(query.lower())!= -1)
            	or (val.get("language") is not None
            	and (val.get("language").lower()).find(query.lower())!= -1)
         ).take(10)  #just take 10 repos from each org

    ).map(lambda x: {'name': x.get("name"),
	'stars': str(x.get("stargazers_count")),
	'link': x.get("svn_url"),'description': x.get("description"),
	'language': x.get("language")})
```

First, we are iterating by the organizations list defined on the config file. We get the organization repository information and then transform the response to the desired format with the `get_info` method. After that, we are making the query to the information we just got and take only the first 10 results that accomplish with this query. Finally, we emit the `Observable` as a dictionary with the characteristics we will be showing in the page as a result.

Finally we need to initialize and start the `ioLoop` for the web socket and render the `index.html` page which is going to show the results of the request with the following code:

```python
class MainHandler(RequestHandler):
    def get(self):
        self.render("index.html")

def main():
    port = os.environ.get("PORT", 8080)
    app = Application([
        url(r"/", MainHandler),
        (r'/ws', WSHandler),
        (r'/static/(.*)', StaticFileHandler, {'path': "."})
    ])
    print("Starting server at port: %s" % port)
    app.listen(port)
    ioloop.IOLoop.current().start()

if __name__ == '__main__':
    main()
```

Here we are starting the web socket so it can listen on port `8080`.

We can check [the entire code of the `server.py` here](https://github.com/valerybriz/RxGithubSearcher/blob/master/server.py)

### Showing the results on the page

To show the results, we will use two static files: `index.html` and `feeder.js`. Let's create the `index.html` in the project root and add the following code:

{% highlight html %}
{% raw %}
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Github Searcher</title>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <div class="col-xs-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
      <div class="page-header">
        <h1>Github Repositories Searcher with RxPY</h1>
        <p class="lead">You are searching repositories from Auth0, Mozilla, Adobe, Twitter and Nasa</p>
      </div>
      <form role="form">
        <div class="form-group">
          <label for="textInput">Enter keywords or a programming language to search on the repos</label>
          <input type="text" id="textInput" class="form-control" placeholder="Query...">
        </div>
      </form>
      <ul id="results"></ul>
    </div>
  </div>
  <script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
  <script src="static/feeder.js"></script>
</body>
</html>
{% endraw %}
{% endhighlight %}

As you can see, we will be replacing the `<ul id="results"></ul>` with the results of the request to the GitHub API dynamically.

Now, let's create the `feeder.js` file in the project root and add the following to it:

```javascript
(function (global, $, undefined) {
    function main() {
        var $input = $('#textInput'),
            $results = $('#results');
        var ws = new WebSocket("ws://localhost:8080/ws");

        $input.keyup(function(ev) {
            var msg = { term: ev.target.value };
            ws.send(JSON.stringify(msg));
        });
	ws.onmessage = function(msg) {
	    var value = JSON.parse(msg.data);
	    if (value === "clear") {$results.empty(); return;}
		    $('<li><h3><a tabindex="-1" href="' + value.link +
		        '">' + value.name +'</a></h3> <p> Description : '
			+ value.description +
		        '</p><p> Language : ' + value.language +
		        '</p><p> Stars : ' + value.stars + '</p></li>'
		    ).appendTo($results);
		    $results.show();
	}
    }
    main();
}(window, jQuery));
```

There you go!

Now to run it we just execute the `server.py` file and the app will be served at `http://localhost:8080`:

```bash
# activate virtualenv
pipenv shell

# run the server
python server.py
```

## Conclusions

Apps and systems nowadays have a lot of real-time computationally expensive events that enables a highly interactive experience for the user. Here is where Reactive Programming shows up to help us properly dealing with that. With the help of the Reactive Programming operators, we can not only manage these events but filter, unify, and transform them on an inherent declarative style way.

I hope this serves as a useful introduction to Reactive Programming in Python and as an overview of its basic capabilities. To learn more about Reactive Programming, I encourage you to browse the resources available at [ReactiveX](http://reactivex.io).

Thanks for reading!


text:
package com.aspsine.multithreaddownload;

import com.aspsine.multithreaddownload.core.ConnectTaskImpl;

import java.net.HttpURLConnection;

/**
 * CallBack of download status
 */
public interface CallBack {

    void onStarted();

    /**
     * <p> this will be the the first method called by
     * {@link ConnectTaskImpl}.
     */
    void onConnecting();

    /**
     * <p> if {@link ConnectTaskImpl} is successfully
     * connected with the http/https server this method will be invoke. If not method
     * {@link #onFailed(DownloadException)} will be invoke.
     *
     * @param total          The length of the file. See {@link HttpURLConnection#getContentLength()}
     * @param isRangeSupport indicate whether download can be resumed from pause.
     *                       See {@link ConnectTaskImpl#run()}. If the value of http header field
     *                       {@code Accept-Ranges} is {@code bytes} the value of  isRangeSupport is
     *                       {@code true} else {@code false}
     */
    void onConnected(long total, boolean isRangeSupport);

    /**
     * <p> progress callback.
     *
     * @param finished the downloaded length of the file
     * @param total    the total length of the file same value with method {@link }
     * @param progress the percent of progress (finished/total)*100
     */
    void onProgress(long finished, long total, int progress);

    /**
     * <p> download complete
     */
    void onCompleted();

    /**
     * <p> if you invoke {@link DownloadManager#pause(String)} or {@link DownloadManager#pauseAll()}
     * this method will be invoke if the downloading task is successfully paused.
     */
    void onDownloadPaused();

    /**
     * <p> if you invoke {@link DownloadManager#cancel(String)} or {@link DownloadManager#cancelAll()}
     * this method will be invoke if the downloading task is successfully canceled.
     */
    void onDownloadCanceled();

    /**
     * <p> download fail or exception callback
     *
     * @param e download exception
     */
    void onFailed(DownloadException e);
}


text:
'use strict';

var spawn = require('child_process').spawn;
var path = require('path');

var ps = spawn(process.execPath, [path.join(__dirname, 'max_listeners', 'source.js')]);

ps.stdout.pipe(process.stdout, { end: false });

ps.stderr.on('data', function (buf) {
	console.log('not ok ' + buf);
});


text:
package example

import utest._
import org.scalajs.dom

object ScalaJSChartTest extends TestSuite {

  import ScalaJSChart._
  val elem=dom.document.createElement("p")
  dom.document.body.appendChild(elem)

  def tests = TestSuite {
    'ScalaJSChart {
      ScalaJSChart.main()
      val actual=dom.document.getElementsByTagName("body")
      println(actual.length)
      println( actual.item(0).asInstanceOf[dom.Element].getAttribute("width"))

    }
  }
}


text:
var buster         = require("buster"),
    SprocketsChain = require("../../lib/sprockets_chain"),
    _path          = require("path"),
    expect         = buster.referee.expect;

buster.spec.expose();

describe("SprocketsChain", function() {

  before(function() {
    var sc     = new SprocketsChain("./spec");
    sc.appendPath("fixtures");
    sc.appendPath("fixtures2");
    sc.appendPath("fixtures3");
    this.trail = sc._trail;
    this.res   = new SprocketsChain.Resource( "one.js", sc._trail );
    this.res2  = new SprocketsChain.Resource( "two/two.js", sc._trail );
    this.res3  = new SprocketsChain.Resource( "bad_eoln.js", sc._trail );
    this.res4  = new SprocketsChain.Resource( "multi.js", sc._trail );
    this.res5  = new SprocketsChain.Resource( "eleven/one.js", sc._trail );
  });

  describe("SprocketsChain.Resource", function() {

    describe("initialize", function() {
      it("sets the correct full path", function() {
        var res = new SprocketsChain.Resource( "one.js", this.trail );
        expect( res.full_path ).toEqual( _path.resolve(".", "spec/fixtures/one.js") );
      });

      it("sets the correct logical path with extension", function() {
        var res = new SprocketsChain.Resource( "one", this.trail );
        expect( res.logical_path ).toEqual( "one.js" );
      });

      it("sets the correct full path for index files", function() {
        var res = new SprocketsChain.Resource( "nine", this.trail );
        expect( res.full_path ).toEqual( _path.resolve(".", "spec/fixtures/nine/index.js") );
      });

      it("sets the correct logical path with extension for index files", function() {
        var res = new SprocketsChain.Resource( "nine", this.trail );
        expect( res.logical_path ).toEqual( "nine/index.js" );
      });

      it("sets the correct full path from bower.json's main", function() {
        var res = new SprocketsChain.Resource( "twelve", this.trail );
        expect( res.full_path ).toEqual( _path.resolve(".", "spec/fixtures3/twelve/one.js") );
      });

      it("sets the correct logical path from bower.json's main", function() {
        var res = new SprocketsChain.Resource( "twelve", this.trail );
        expect( res.logical_path ).toEqual( "twelve/one.js" );
      });

      it("sets the correct full path from bower.json's main", function() {
        var res = new SprocketsChain.Resource( "thirteen", this.trail );
        expect( res.full_path ).toEqual( _path.resolve(".", "spec/fixtures3/thirteen/one.js") );
      });

      it("parses bower.json's main property when an array", function() {
        var res = new SprocketsChain.Resource( "thirteen", this.trail );
        expect( res.logical_path ).toEqual( "thirteen/one.js" );
      });

      describe("Windows paths", function() {
        var mockPath;
        var mockTrail;

        beforeEach(function(){
          mockTrail = {
            find: function(logical_path){
              return mockPath;
            }
          };
        });

        describe("simple resource path", function(){
          beforeEach(function(){
            mockPath = "c:\\Users\\MockUser\\sprockets-chain\\spec\\fixtures\\one.js";
          });

          it("sets the correct full path with Windows separators", function(){
            var res = new SprocketsChain.Resource( "one.js", mockTrail );
            expect( res.full_path ).toEqual( "c:\\Users\\MockUser\\sprockets-chain\\spec\\fixtures\\one.js" );
            expect( res.logical_path ).toEqual( "one.js" );
          });

          it("sets the correct logical path with extension with Windows separators", function() {
            var res = new SprocketsChain.Resource( "one", mockTrail );
            expect( res.full_path ).toEqual( "c:\\Users\\MockUser\\sprockets-chain\\spec\\fixtures\\one.js" );
            expect( res.logical_path ).toEqual( "one.js" );
          });
        });

        describe("complex resource path", function(){
          beforeEach(function(){
            mockPath = "c:\\Users\\MockUser\\sprockets-chain\\spec\\fixtures\\two\\two.js";
          });

          it("sets the correct full path with Windows separators", function(){
            var res = new SprocketsChain.Resource( "two/two.js", mockTrail );
            expect( res.full_path ).toEqual( "c:\\Users\\MockUser\\sprockets-chain\\spec\\fixtures\\two\\two.js" );
            expect( res.logical_path ).toEqual( "two/two.js" );
          });

          it("sets the logical path extension with Windows separators", function(){
            var res = new SprocketsChain.Resource( "two/two", mockTrail );
            expect( res.full_path ).toEqual( "c:\\Users\\MockUser\\sprockets-chain\\spec\\fixtures\\two\\two.js" );
            expect( res.logical_path ).toEqual( "two/two.js" );
          });
        });
      });
    });

    describe("resolve", function() {
      it("resolves the logical path given a path relative to the current resource", function() {
        expect( this.res2.resolve("./three") ).toEqual("two/three");
      });

      it("just returns the logical path if given", function() {
        expect( this.res2.resolve("two/three") ).toEqual("two/three");
      });
    });

    describe("parseRequires", function() {
      it("returns all require directives", function() {
        this.stub( this.res, "content", function() {
          return "//= require four\n#=  require_self\n/*\n*= require_directory  ./two\n*/"
        });
        expect( this.res.parseRequires() ).toEqual(["require four", "require_self", "require_directory  ./two"]);
      });

      it("does not return directives happening after code", function() {
        this.stub( this.res, "content", function() {
          return "//= require four\nsome code\n#=  require_self\n/*\n*= require_directory  ./two\n*/"
        });
        expect( this.res.parseRequires() ).toEqual(["require four"]);
      });
    });

    describe("parseDeps", function() {
      it("returns all dependencies, with logical path and directive", function() {
        this.stub( this.res, "parseRequires", function() {
          return ["require four", "require_self", "require_directory ./two", "require_tree ./five"];
        });
        expect( this.res.parseDeps() ).toEqual([
          { path: "four",                     directive: "require" },
          { path: "one.js",                   directive: "require_self" },
          { path: "two/three.coffee",         directive: "require_directory" },
          { path: "two/two.js",               directive: "require_directory" },
          { path: "five/six/seven.js.coffee", directive: "require_tree" },
          { path: "five/six/six.js",          directive: "require_tree" }
        ]);
      });

      it("throws error if require_directory is used with non-relative path", function() {
        var self = this;
        this.stub( this.res, "parseRequires", function() {
          return ["require_directory two"];
        });
        expect(function() {
          self.res.parseDeps();
        }).toThrow("Error");
      });

      it("throws error if require_tree is used with non-relative path", function() {
        var self = this;
        this.stub( this.res, "parseRequires", function() {
          return ["require_tree five"];
        });
        expect(function() {
          self.res.parseDeps();
        }).toThrow("Error");
      });
    });

    describe("depTree", function() {
      it("creates the dependency tree", function() {
        var tree = this.res.depTree();
        expect( tree.dependencies[0].logical_path ).toEqual("four.js");
        expect( tree.dependencies[1].logical_path ).toEqual("one.js");
        expect( tree.dependencies[0].dependencies[0].logical_path ).toEqual("eight/eight.coffee");
      });
    });

    describe("depTree", function() {
      it("creates the dependency tree", function() {
        var tree = this.res3.depTree();
        expect( tree.dependencies[0].logical_path ).toEqual("five/six/six.js");
      });
    });

    describe("depChain", function() {
      function full_path(file_name, fixtures_dir) {
        if (!fixtures_dir) {
          fixtures_dir = "spec/fixtures"
        }
        return _path.join( _path.resolve(".", fixtures_dir), file_name );
      }

      it("returns the dependency chain", function() {
        var chain    = this.res.depChain(),
            expected = [ "eight/eight.coffee", "four.js", "one.js", "two/three.coffee", "two/two.js", "five/six/seven.js.coffee", "five/six/seven.js.coffee", "five/six/six.js" ]
            .map(function( p ) {
              var fixtures_dir = "spec/fixtures";
              if ( p === "four.js" ) {
                fixtures_dir = "spec/fixtures2";
              }
              return full_path(p, fixtures_dir);
            });
        expect( chain ).toEqual( expected );
      });

      it("only includes dependencies required by siblings once", function() {
        var chain = this.res4.depChain();
        expect( chain.length ).toEqual(4);
        expect( chain[0] ).toEqual(full_path("ten/one.js"));
        expect( chain[1] ).toEqual(full_path("ten/two.js"));
        expect( chain[2] ).toEqual(full_path("ten/three.js"));
        expect( chain[3] ).toEqual(full_path("multi.js"));
      });

      it("returns all dependencies for require_tree when the path is for the current directory (ie. 'require_tree ./') ", function() {
        //Doing this has resulted in an infinite loop in the past.
        var chain = this.res5.depChain();
        expect( chain.length ).toEqual(2);
        expect( chain[0] ).toEqual(full_path("eleven/one.js"));
        expect( chain[1] ).toEqual(full_path("eleven/two.js"));
      });
    });
  });

});


text:
"""Support for the Airly sensor service."""
from homeassistant.const import (
    ATTR_ATTRIBUTION,
    ATTR_DEVICE_CLASS,
    CONF_LATITUDE,
    CONF_LONGITUDE,
    CONF_NAME,
    DEVICE_CLASS_HUMIDITY,
    DEVICE_CLASS_PRESSURE,
    DEVICE_CLASS_TEMPERATURE,
    PRESSURE_HPA,
    TEMP_CELSIUS,
)
from homeassistant.helpers.entity import Entity

from .const import (
    ATTR_API_HUMIDITY,
    ATTR_API_PM1,
    ATTR_API_PRESSURE,
    ATTR_API_TEMPERATURE,
    DATA_CLIENT,
    DOMAIN,
)

ATTRIBUTION = "Data provided by Airly"

ATTR_ICON = "icon"
ATTR_LABEL = "label"
ATTR_UNIT = "unit"

HUMI_PERCENT = "%"
VOLUME_MICROGRAMS_PER_CUBIC_METER = "µg/m³"

SENSOR_TYPES = {
    ATTR_API_PM1: {
        ATTR_DEVICE_CLASS: None,
        ATTR_ICON: "mdi:blur",
        ATTR_LABEL: ATTR_API_PM1,
        ATTR_UNIT: VOLUME_MICROGRAMS_PER_CUBIC_METER,
    },
    ATTR_API_HUMIDITY: {
        ATTR_DEVICE_CLASS: DEVICE_CLASS_HUMIDITY,
        ATTR_ICON: None,
        ATTR_LABEL: ATTR_API_HUMIDITY.capitalize(),
        ATTR_UNIT: HUMI_PERCENT,
    },
    ATTR_API_PRESSURE: {
        ATTR_DEVICE_CLASS: DEVICE_CLASS_PRESSURE,
        ATTR_ICON: None,
        ATTR_LABEL: ATTR_API_PRESSURE.capitalize(),
        ATTR_UNIT: PRESSURE_HPA,
    },
    ATTR_API_TEMPERATURE: {
        ATTR_DEVICE_CLASS: DEVICE_CLASS_TEMPERATURE,
        ATTR_ICON: None,
        ATTR_LABEL: ATTR_API_TEMPERATURE.capitalize(),
        ATTR_UNIT: TEMP_CELSIUS,
    },
}

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up Airly sensor entities based on a config entry."""
    name = config_entry.data[CONF_NAME]
    latitude = config_entry.data[CONF_LATITUDE]
    longitude = config_entry.data[CONF_LONGITUDE]

    data = hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id]

    sensors = []
    for sensor in SENSOR_TYPES:
        unique_id = f"{latitude}-{longitude}-{sensor.lower()}"
        sensors.append(AirlySensor(data, name, sensor, unique_id))

    async_add_entities(sensors, True)

def round_state(func):
    """Round state."""

    def _decorator(self):
        res = func(self)
        if isinstance(res, float):
            return round(res)
        return res

    return _decorator

class AirlySensor(Entity):
    """Define an Airly sensor."""

    def __init__(self, airly, name, kind, unique_id):
        """Initialize."""
        self.airly = airly
        self.data = airly.data
        self._name = name
        self._unique_id = unique_id
        self.kind = kind
        self._device_class = None
        self._state = None
        self._icon = None
        self._unit_of_measurement = None
        self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION}

    @property
    def name(self):
        """Return the name."""
        return f"{self._name} {SENSOR_TYPES[self.kind][ATTR_LABEL]}"

    @property
    def state(self):
        """Return the state."""
        self._state = self.data[self.kind]
        if self.kind in [ATTR_API_PM1, ATTR_API_PRESSURE]:
            self._state = round(self._state)
        if self.kind in [ATTR_API_TEMPERATURE, ATTR_API_HUMIDITY]:
            self._state = round(self._state, 1)
        return self._state

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return self._attrs

    @property
    def icon(self):
        """Return the icon."""
        self._icon = SENSOR_TYPES[self.kind][ATTR_ICON]
        return self._icon

    @property
    def device_class(self):
        """Return the device_class."""
        return SENSOR_TYPES[self.kind][ATTR_DEVICE_CLASS]

    @property
    def unique_id(self):
        """Return a unique_id for this entity."""
        return self._unique_id

    @property
    def unit_of_measurement(self):
        """Return the unit the value is expressed in."""
        return SENSOR_TYPES[self.kind][ATTR_UNIT]

    @property
    def available(self):
        """Return True if entity is available."""
        return bool(self.data)

    async def async_update(self):
        """Update the sensor."""
        await self.airly.async_update()

        if self.airly.data:
            self.data = self.airly.data


text:
TIMER
=====

Introduction
------------

The ESP32 chip contains two hardware timer groups. Each group has two general-purpose hardware timers. They are all 64-bit generic timers based on 16-bit prescalers and 64-bit auto-reload-capable up / down counters.

Functional Overview
-------------------

Typical steps to configure an operate the timer are described in the following sections:

* :ref:`timer-api-timer-initialization` - what parameters should be set up to get the timer working and what specific functionality is provided depending on the set up.
* :ref:`timer-api-timer-control` - how to read the timer's value, pause / start the timer, and change how it operates.
* :ref:`timer-api-alarms` - setting and using alarms.
* :ref:`timer-api-interrupts`- how to enable and use interrupts.

.. _timer-api-timer-initialization:

Timer Initialization
^^^^^^^^^^^^^^^^^^^^

The two timer groups on-board of the ESP32 are identified using :cpp:type:`timer_group_t`. Individual timers in a group are identified with :cpp:type:`timer_idx_t`. The two groups, each having two timers, provide the total of four individual timers to our disposal.

Before starting the timer, it should be initialized by calling :cpp:func:`timer_init`. This function should be provided with a structure :cpp:type:`timer_config_t` to define how timer should operate. In particular the following timer's parameters may be set:

    * **Divider**: How quickly the timer's counter is "ticking". This depends on the setting of :cpp:member:`divider`, that will be used as divisor of the incoming 80 MHz APB_CLK clock.
    * **Mode**: If the the counter is incrementing or decrementing, defined using :cpp:member:`counter_dir` by selecting one of values from :cpp:type:`timer_count_dir_t`.
    * **Counter Enable**: If the counter is enabled, then it will start incrementing / decrementing immediately after calling :cpp:func:`timer_init`. This action is set using :cpp:member:`counter_en` by selecting one of vales from :cpp:type:`timer_start_t`.
    * **Alarm Enable**: Determined by the setting of :cpp:member:`alarm_en`.
    * **Auto Reload**: Whether the counter should :cpp:member:`auto_reload` a specific initial value on the timer's alarm, or continue incrementing or decrementing.
    * **Interrupt Type**: Whether an interrupt is triggered on timer's alarm. Set the value defined in :cpp:type:`timer_intr_mode_t`.

To get the current values of the timers settings, use function :cpp:func:`timer_get_config`.

.. _timer-api-timer-control:

Timer Control
^^^^^^^^^^^^^

Once the timer is configured and enabled, it is already "ticking". To check it's current value call :cpp:func:`timer_get_counter_value` or :cpp:func:`timer_get_counter_time_sec`. To set the timer to specific starting value call :cpp:func:`timer_set_counter_value`.

The timer may be paused at any time by calling :cpp:func:`timer_pause`. To start it again call :cpp:func:`timer_start`.

To change how the timer operates you can call once more :cpp:func:`timer_init` described in section :ref:`timer-api-timer-initialization`. Another option is to use dedicated functions to change individual settings:

    * **Divider** value - :cpp:func:`timer_set_divider`. **Note:** the timer should be paused when changing the divider to avoid unpredictable results. If the timer is already running, :cpp:func:`timer_set_divider` will first pause the timer, change the divider, and finally start the timer again.
    * **Mode** (whether the counter incrementing or decrementing) - :cpp:func:`timer_set_counter_mode`
    * **Auto Reload** counter on alarm - :cpp:func:`timer_set_auto_reload`

.. _timer-api-alarms:

Alarms
^^^^^^

To set an alarm, call function :cpp:func:`timer_set_alarm_value` and then enable it with :cpp:func:`timer_set_alarm`. The alarm may be also enabled during the timer initialization stage, when :cpp:func:`timer_init` is called.

After the alarm is enabled and the timer reaches the alarm value, depending on configuration, the following two actions may happen:

    * An interrupt will be triggered, if previously configured. See section :ref:`timer-api-interrupts` how to configure interrupts.
    * When :cpp:member:`auto_reload` is enabled, the timer's counter will be reloaded to start counting from specific initial value. The value to start should be set in advance with :cpp:func:`timer_set_counter_value`.

.. note::

    * The alarm will be triggered immediately, if an alarm value is set and the timer has already passed this value.
    * Once triggered the alarm will be disabled automatically and needs to be re-armed to trigger again.

To check what alarm value has been set up, call :cpp:func:`timer_get_alarm_value`.

.. _timer-api-interrupts:

Interrupts
^^^^^^^^^^

Registration of the interrupt handler for a specific timer group and timer is done be calling :cpp:func:`timer_isr_register`.

To enable interrupts for a timer group call :cpp:func:`timer_group_intr_enable`. To do it for a specific timer, call :cpp:func:`timer_enable_intr`. Disabling of interrupts is done with corresponding functions :cpp:func:`timer_group_intr_disable` and :cpp:func:`timer_disable_intr`.

When servicing an interrupt within an ISR, the interrupt need to explicitly cleared. To do so, set the ``TIMERGN.int_clr_timers.tM`` structure defined in :component_file:`soc/esp32/include/soc/timer_group_struct.h`, where N is the timer group number [0, 1] and M is the timer number [0, 1]. For example to clear an interrupt for the timer 1 in the timer group 0, call the following::

    TIMERG0.int_clr_timers.t1 = 1

See the application example below how to use interrupts.

Application Example
-------------------

The 64-bit hardware timer example: :example:`peripherals/timer_group`.

API Reference
-------------

.. include:: /_build/inc/timer.inc


text:
require 'spec_helper'
require_relative '../../tasks/backend_upgrade.rb'

describe SensuBackendUpgrade do
  let(:output) { my_fixture_read('logs.out') }
  let(:logs) do
    [
      {"component" => "store","level" => "warning","msg" => "migrating etcd database to a new version","time" => "2020-07-11T15:07:50Z"},
      {"component" => "store","database_version" => 1,"level" => "info","msg" => "successfully upgraded database","time" => "2020-07-11T15:07:50Z"},
      {"component" => "store","database_version" => 2,"level" => "info","msg" => "successfully upgraded database","time" => "2020-07-11T15:07:50Z"},
    ]
  end

  it 'executes upgrade with no arguments' do
    expect(Open3).to receive(:capture3).with('sensu-backend upgrade --skip-confirm').and_return(["", output, 0])
    ret = described_class.upgrade({})
    expect(ret).to eq(logs)
  end

  it 'handles arguments' do
    expected_cmd = 'sensu-backend upgrade --skip-confirm --config-file /etc/foo.yml --timeout 10 --etcd-client-cert-auth --etcd-cipher-suites foo bar'
    params = {
      '_task': 'sensu::backend_upgrade',
      'config_file': '/etc/foo.yml',
      'timeout': 10,
      'etcd_client_cert_auth': true,
      'etcd_cipher_suites': ['foo','bar'],
    }
    expect(Open3).to receive(:capture3).with(expected_cmd).and_return(["", output, 0])
    described_class.upgrade(params)
  end
end


text:
class CreateVersions < ActiveRecord::Migration[4.2]
  def change
    create_table :versions do |t|
      t.string   :item_type, null: false
      t.integer  :item_id,   null: false
      t.string   :event,     null: false
      t.string   :whodunnit
      t.json     :object
      t.json     :object_changes
      t.datetime :created_at
    end
    add_index :versions, [:item_type, :item_id]
  end
end


text:
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters
{
    [ExportHighlighter(LanguageNames.CSharp)]
    internal class BindStatementHighlighter : AbstractKeywordHighlighter<BindStatementSyntax>
    {
        protected override IEnumerable<TextSpan> GetHighlights(
            BindStatementSyntax bindStatement, CancellationToken cancellationToken)
        {
            yield return bindStatement.BindKeyword.Span;
        }
    }
}


text:
/* ----------------------------------------------------------------------------------
 * Hint: This is a derived (generated) file. Changes should be done in the underlying
 * source files only (*.control, *.js) or they will be lost after the next generation.
 * ---------------------------------------------------------------------------------- */

// Provides control sap.ui.ux3.Feeder.
jQuery.sap.declare("sap.ui.ux3.Feeder");
jQuery.sap.require("sap.ui.ux3.library");
jQuery.sap.require("sap.ui.core.Control");

/**
 * Constructor for a new Feeder.
 *
 * Accepts an object literal mSettings that defines initial
 * property values, aggregated and associated objects as well as event handlers.
 *
 * If the name of a setting is ambiguous (e.g. a property has the same name as an event),
 * then the framework assumes property, aggregation, association, event in that order.
 * To override this automatic resolution, one of the prefixes "aggregation:", "association:"
 * or "event:" can be added to the name of the setting (such a prefixed name must be
 * enclosed in single or double quotes).
 *
 * The supported settings are:
 *

 *
Properties
 *

 *
{@link #getThumbnailSrc thumbnailSrc} : sap.ui.core.URI

 *
{@link #getText text} : string

 *
{@link #getType type} : sap.ui.ux3.FeederType (default: sap.ui.ux3.FeederType.Large)

 *
{@link #getPlaceholderText placeholderText} : string

 *

 *
Aggregations
 *

 *

 *
Associations
 *

 *

 *
Events
 *

 *
{@link sap.ui.ux3.Feeder#event:submit submit} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]

 *

 *

 *
 * @param {string} [sId] id for the new control, generated automatically if no id is given
 * @param {object} [mSettings] initial settings for the new control
 *
 * @class
 * This feed control flavor represents a lean common feed, or a comment feed, with a text commit function.
 * The control can be used stand alone or in a multiple way, and generally would be integrated directly into a UIArea.
 * @extends sap.ui.core.Control
 *
 * @author SAP AG
 * @version 1.22.10
 *
 * @constructor
 * @public
 * @experimental Since version 1.2.
 * The whole Feed/Feeder API is still under discussion, significant changes are likely. Especially text presentation (e.g. @-references and formatted text) is not final. Also the Feed model topic is still open.
 * @name sap.ui.ux3.Feeder
 */
sap.ui.core.Control.extend("sap.ui.ux3.Feeder", { metadata : {

	// ---- object ----

	// ---- control specific ----
	library : "sap.ui.ux3",
	properties : {
		"thumbnailSrc" : {type : "sap.ui.core.URI", group : "Data", defaultValue : null},
		"text" : {type : "string", group : "Data", defaultValue : null},
		"type" : {type : "sap.ui.ux3.FeederType", group : "Appearance", defaultValue : sap.ui.ux3.FeederType.Large},
		"placeholderText" : {type : "string", group : "Appearance", defaultValue : null}
	},
	events : {
		"submit" : {}
	}
}});

/**
 * Creates a new subclass of class sap.ui.ux3.Feeder with name sClassName
 * and enriches it with the information contained in oClassInfo.
 *
 * oClassInfo might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}.
 *
 * @param {string} sClassName name of the class to be created
 * @param {object} [oClassInfo] object literal with informations about the class
 * @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata.
 * @return {function} the created class / constructor function
 * @public
 * @static
 * @name sap.ui.ux3.Feeder.extend
 * @function
 */

sap.ui.ux3.Feeder.M_EVENTS = {'submit':'submit'};

/**
 * Getter for property thumbnailSrc.
 * URL to the thumb nail image
 * This property is optional if the feeder is a sub-control of a feed or a feedChunk control. In this case the value of the feed or feddChunk control is used if it's not set. So it must be only set once on the feed or feedChunk control.
 *
 * Default value is empty/undefined
 *
 * @return {sap.ui.core.URI} the value of property thumbnailSrc
 * @public
 * @name sap.ui.ux3.Feeder#getThumbnailSrc
 * @function
 */

/**
 * Setter for property thumbnailSrc.
 *
 * Default value is empty/undefined
 *
 * @param {sap.ui.core.URI} sThumbnailSrc  new value for property thumbnailSrc
 * @return {sap.ui.ux3.Feeder} this to allow method chaining
 * @public
 * @name sap.ui.ux3.Feeder#setThumbnailSrc
 * @function
 */

/**
 * Getter for property text.
 * The text for the Feeder. @References are supported.
 *
 * Default value is empty/undefined
 *
 * @return {string} the value of property text
 * @public
 * @name sap.ui.ux3.Feeder#getText
 * @function
 */

/**
 * Setter for property text.
 *
 * Default value is empty/undefined
 *
 * @param {string} sText  new value for property text
 * @return {sap.ui.ux3.Feeder} this to allow method chaining
 * @public
 * @name sap.ui.ux3.Feeder#setText
 * @function
 */

/**
 * Getter for property type.
 * Type and size of the Feeder
 *
 * Default value is sap.ui.ux3.FeederType.Large
 *
 * @return {sap.ui.ux3.FeederType} the value of property type
 * @public
 * @name sap.ui.ux3.Feeder#getType
 * @function
 */

/**
 * Setter for property type.
 *
 * Default value is sap.ui.ux3.FeederType.Large
 *
 * @param {sap.ui.ux3.FeederType} oType  new value for property type
 * @return {sap.ui.ux3.Feeder} this to allow method chaining
 * @public
 * @name sap.ui.ux3.Feeder#setType
 * @function
 */

/**
 * Getter for property placeholderText.
 * This property could be used for costum placeholder. If it is not set, the default text is used.
 *
 * Default value is empty/undefined
 *
 * @return {string} the value of property placeholderText
 * @public
 * @name sap.ui.ux3.Feeder#getPlaceholderText
 * @function
 */

/**
 * Setter for property placeholderText.
 *
 * Default value is empty/undefined
 *
 * @param {string} sPlaceholderText  new value for property placeholderText
 * @return {sap.ui.ux3.Feeder} this to allow method chaining
 * @public
 * @name sap.ui.ux3.Feeder#setPlaceholderText
 * @function
 */

/**
 * Event is fired when the entered text is submitted
 *
 * @name sap.ui.ux3.Feeder#submit
 * @event
 * @param {sap.ui.base.Event} oControlEvent
 * @param {sap.ui.base.EventProvider} oControlEvent.getSource
 * @param {object} oControlEvent.getParameters

 * @param {string} oControlEvent.getParameters.text The text that is submitted
 * @public
 */

/**
 * Attach event handler fnFunction to the 'submit' event of this sap.ui.ux3.Feeder.
.
 * When called, the context of the event handler (its this) will be bound to oListener if specified
 * otherwise to this sap.ui.ux3.Feeder.
 itself.
 *
 * Event is fired when the entered text is submitted
 *
 * @param {object}
 *            [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
 * @param {function}
 *            fnFunction The function to call, when the event occurs.
 * @param {object}
 *            [oListener] Context object to call the event handler with. Defaults to this sap.ui.ux3.Feeder.
 itself.
 *
 * @return {sap.ui.ux3.Feeder} this to allow method chaining
 * @public
 * @name sap.ui.ux3.Feeder#attachSubmit
 * @function
 */

/**
 * Detach event handler fnFunction from the 'submit' event of this sap.ui.ux3.Feeder.

 *
 * The passed function and listener object must match the ones used for event registration.
 *
 * @param {function}
 *            fnFunction The function to call, when the event occurs.
 * @param {object}
 *            oListener Context object on which the given function had to be called.
 * @return {sap.ui.ux3.Feeder} this to allow method chaining
 * @public
 * @name sap.ui.ux3.Feeder#detachSubmit
 * @function
 */

/**
 * Fire event submit to attached listeners.
 *
 * Expects following event parameters:
 *

 *
'text' of type string The text that is submitted

 *

 *
 * @param {Map} [mArguments] the arguments to pass along with the event.
 * @return {sap.ui.ux3.Feeder} this to allow method chaining
 * @protected
 * @name sap.ui.ux3.Feeder#fireSubmit
 * @function
 */

// Start of sap\ui\ux3\Feeder.js
jQuery.sap.require("sap.ui.core.theming.Parameters");
jQuery.sap.require("sap.ui.commons.Button");

/**
 * This file defines behavior for the control,
 */

sap.ui.ux3.Feeder.prototype.init = function(){
	this.rb = sap.ui.getCore().getLibraryResourceBundle("sap.ui.ux3");
	this.oSendButton = new sap.ui.commons.Button( this.getId() + "-send", {
			style: sap.ui.commons.ButtonStyle.Emph,
			icon: "sap-icon://feeder-arrow"
		}).setParent(this);
	this.oSendButton.attachEvent('press', this.handleSendButtonPress, this); // attach event this way to have the right this-reference in handler

};

/*
 * as onBeforeRendering only runs while re-rendering this module is called in renderer
 */
sap.ui.ux3.Feeder.prototype.initSendButton = function(){
	if (this.getText() == "") {
		// no re-rendering as button is not rendered now.
		this.oSendButton.setProperty('enabled', false, true);
	}

};

sap.ui.ux3.Feeder.prototype.exit = function(){
	this.rb = undefined;
	this.oInput = undefined;
	if(this.oSendButton){
		this.oSendButton.destroy();
		delete this.oSendButton;
	}
};

/**
 * After rendering, keep the input field jQuery object as attribute
 * for reuse
 *
 * @private
 */
sap.ui.ux3.Feeder.prototype.onAfterRendering = function () {
	this.oInput = this.$("input");
};

/**
 * handler for click event
 *
 * @private
 */
sap.ui.ux3.Feeder.prototype.onclick = function(oEvent){

	var sTargetId = oEvent.target.getAttribute( 'ID' );

	switch ( sTargetId ){
	case ( this.getId() + '-send' ):
		// Click on send button (should be handled in button)
	break;
	case ( this.getId() + '-input'):
		// Click on input field

	break;
	default:

	break;
	}

};

/**
 * handler for focusIn
 *
 * If the Feeder is empty the default text must be cleared
 * @private
 */
sap.ui.ux3.Feeder.prototype.onfocusin = function(oEvent){

	this.oInput.find(".sapUiFeederEmptyText").remove();

};

/**
 * handler for focusOut
 *
 * If the Feeder is empty the default text written
 * @private
 */
sap.ui.ux3.Feeder.prototype.onfocusout = function(oEvent){

	var sText = this.oInput.text();
	if(sText == ""){
		this.oInput.empty(); // to remove invisible line breaks and so on
		this.oInput.append(sap.ui.ux3.FeederRenderer.getEmptyTextInfo(this));
	}

	this.setProperty("text", sText, true); // no rerendering!

};

// overrides sap.ui.core.Element.getFocusDomRef()
sap.ui.ux3.Feeder.prototype.getFocusDomRef = function(){
	return this.getDomRef("input");
};

/**
 * handler for keyUp
 *
 * if text is entered the button must be enables, if empty it must be disabled
 * @private
 */
sap.ui.ux3.Feeder.prototype.onkeyup = function(oEvent){

	if(this.oInput.text() == ""){
		this.oSendButton.setEnabled(false);
	}else{
		this.oSendButton.setEnabled(true);
	}

	//Clean input so we avoid having invisible DOM content
//	if(!this.oInput.text()){
//		this.oInput.empty();
//	}

};

/**
 * Handler for send-button press
 *
 * @private
 */
sap.ui.ux3.Feeder.prototype.handleSendButtonPress = function(oEvent){

	var sText = this.getMultilineText(this.oInput);
	this.setProperty("text", sText, true); // no rerendering!
	this.fireSubmit({text: sText});
	this.setText(''); // clear text after submit

};

/**
 * get multiline text from input DIV
 *
 * @param {object} [oInput] jQuery object of the input field
 *
 * @private
 */
sap.ui.ux3.Feeder.prototype.getMultilineText = function(oInput) {

	function parseText(nodes) {

		var node;
		var sText = '';

		for (var i = 0; i < nodes.length; i++) {
			node = nodes[i];

			// text / cdata
			if (node.nodeType === 3 || node.nodeType === 4) {

				// ignore non-breakable space in IE
				if (!(!!sap.ui.Device.browser.internet_explorer && node.nodeValue === '\xA0')) {
					sText += node.nodeValue.replace(/\n/g, ''); // filter out line breaks in text-nodes
				}
			}

			// check for "linebreaking"-nodes
			if (node.nodeName === 'DIV' ||
					node.nodeName ===  'P' ||
					(node.nodeName === 'BR' && !!!sap.ui.Device.browser.webkit)) { // ignore BR in webkit

				// ignore last
 with type="_moz" in mozilla
				if (node.nodeName === 'BR' &&
					!!sap.ui.Device.browser.firefox &&
					i === nodes.length - 1 &&
					jQuery(node).attr("type") === "_moz") {
					continue;
				}

				// do not add a newline if no text was found until now (IE)
				if (!(!!sap.ui.Device.browser.internet_explorer && sText === '') &&

					// same as above but only for
 and webkit/mozilla
					!((!!sap.ui.Device.browser.firefox || !!sap.ui.Device.browser.webkit) && sText === '' && node.nodeName ===  'P') &&

					// ignore
's containing linebreaks only (\n)
					!(!!sap.ui.Device.browser.webkit && node.nodeName ===  'P' && node.textContent.match(/^(\n)*$/))) {

					sText += '\n';
				}

			}

			// parse child elements, ignore comments in mozilla
			if (node.nodeType !== 8) {
				sText += parseText(node.childNodes);
			}

		}

		return sText;
	}

	return parseText(oInput.get(0).childNodes);
};

/*
 * Overwrite standard getter for thumbnail source:
 * If not set and feeder is child of a Feed or FeedChunk use the thumbnailsource of the parent
 * So it must not be set manually for each sub-control and is always in sync
 */
sap.ui.ux3.Feeder.prototype.getThumbnailSrc = function() {
	var sThumbnailSrc =  this.getProperty("thumbnailSrc");

	if (!sThumbnailSrc || sThumbnailSrc == "") {
		var oParent = this.getParent();
		if (oParent &&(oParent instanceof sap.ui.ux3.Feed || oParent instanceof sap.ui.ux3.FeedChunk)) {
			sThumbnailSrc = oParent.getFeederThumbnailSrc();
		}
	}

	return sThumbnailSrc;
};

sap.ui.ux3.Feeder.prototype.onpaste = function(oEvent){

	// call after paste function delayed to have content already pasted (in the moment only needed in FireFox)
	if (!!sap.ui.Device.browser.firefox) {
		jQuery.sap.delayedCall(10, this, "onAfterPaste");
	}

};

sap.ui.ux3.Feeder.prototype.onAfterPaste = function(){

	// if pasted from MS Word in FireFox text is longer that contenteditable DIV
	// -> add overflow:hidden to PRE elements
	var aChildren = this.oInput.get(0).childNodes;

	for ( var i = 0; i < aChildren.length; i++) {
		var oChild = aChildren[i];
		if (oChild.nodeName == "PRE") {
			jQuery(oChild).css("overflow", "hidden");
		}
	}

};


text:
using BadgerJaus.Util;

namespace BadgerJaus.Messages.LocalWaypointDriver
{
    public class QueryLocalWaypoint : Message
    {
        protected JausBytePresenceVector presence;

        protected override int CommandCode
        {
            get { return JausCommandCode.QUERY_LOCAL_WAYPOINT; }
        }

        protected override void InitFieldData()
        {
            presence = new JausBytePresenceVector();
        }

        public bool IsFieldSet(int bit)
        {
            return presence.IsBitSet(bit);
        }

        protected override bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset)
        {
            return PresenceOperation(buffer, index, out indexOffset, true);
        }

        protected override bool PayloadToJausBuffer(byte[] buffer, int index, out int indexOffset)
        {
            return PresenceOperation(buffer, index, out indexOffset, false);
        }

        private bool PresenceOperation(byte[] buffer, int index, out int indexOffset, bool set)
        {
            if (set)
                return presence.Deserialize(buffer, index, out indexOffset);
            return presence.Serialize(buffer, index, out indexOffset);
        }
    }
}


text:
.tabbedPane {
   vertical-align: top;
   border: thin solid Blue;
}
.tabbedPaneContent {
   font-family: Times;
}
.tab {
   padding: 3px;
   border: thin solid CornflowerBlue;
   color: Blue;
   background: #eee;
}
.selectedTab {
   padding: 3px;
   border: thin solid CornflowerBlue;
   color: Blue;
   background: PowderBlue;
}


text:
![falls back to /tmp](http://cl.ly/image/2b3K3D3w2C11/Screen%20Shot%202014-02-24%20at%2012.24.32%20pm.png)

## Installation

```bash
mkdir -p ~/Library/Application\ Support/Avian/Bundles
cd ~/Library/Application\ Support/Avian/Bundles
git clone https://github.com/elia/pow-server.tmbundle
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Copyright

Copyright © 2013 Elia Schito. See MIT-LICENSE for details.


text:
namespace Microsoft.Azure.Management.AzureStackHCI
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using Newtonsoft.Json;

    /// <summary>
    /// Azure Stack HCI management service
    /// </summary>
    public partial interface IAzureStackHCIClient : System.IDisposable
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        System.Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        JsonSerializerSettings SerializationSettings { get; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        JsonSerializerSettings DeserializationSettings { get; }

        /// <summary>
        /// Credentials needed for the client to connect to Azure.
        /// </summary>
        ServiceClientCredentials Credentials { get; }

        /// <summary>
        /// The API version to use for this operation.
        /// </summary>
        string ApiVersion { get; }

        /// <summary>
        /// The ID of the target subscription.
        /// </summary>
        string SubscriptionId { get; set; }

        /// <summary>
        /// The preferred language for the response.
        /// </summary>
        string AcceptLanguage { get; set; }

        /// <summary>
        /// The retry timeout in seconds for Long Running Operations. Default
        /// value is 30.
        /// </summary>
        int? LongRunningOperationRetryTimeout { get; set; }

        /// <summary>
        /// Whether a unique x-ms-client-request-id should be generated. When
        /// set to true a unique x-ms-client-request-id value is generated and
        /// included in each request. Default is true.
        /// </summary>
        bool? GenerateClientRequestId { get; set; }

        /// <summary>
        /// Gets the IArcSettingsOperations.
        /// </summary>
        IArcSettingsOperations ArcSettings { get; }

        /// <summary>
        /// Gets the IClustersOperations.
        /// </summary>
        IClustersOperations Clusters { get; }

        /// <summary>
        /// Gets the IExtensionsOperations.
        /// </summary>
        IExtensionsOperations Extensions { get; }

        /// <summary>
        /// Gets the IOperations.
        /// </summary>
        IOperations Operations { get; }

    }
}


text:
package com.android.tools.swing.layoutlib;

/**
 * An {@linkplain UnsupportedLayoutlibException} is thrown when layoutlib doesn't support the required features.
 */
public class UnsupportedLayoutlibException extends InitializationException {
  UnsupportedLayoutlibException(String message) {
    super(message);
  }

  UnsupportedLayoutlibException(Throwable cause) {
    super(cause);
  }
}


text:
table, th, td {
	border: 1px solid black;
	border-collapse: collapse;
	padding: 15px;
	text-align: center;
    cursor: pointer;
}


text:
-Mailbox hike --> www.blissfulbritt.com
-Snow Lake hike --> www.trover.com
-Annette Lake hike --> www.pinterest.com by Kelly Marks
-Cape Flattery hike --> www.trover.com


text:
import java.lang.annotation.*;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface FooInherited {
    int value();
}


text:
require 'spec_helper'
module Cudd
  describe Interface::BDD, 'zero' do

    subject{ zero }

    it_behaves_like "a BDD"

    it 'is zero' do
      subject.should be_zero
      subject.should be_contradiction
      subject.false?.should eq(true)
    end

    it 'is not one' do
      subject.should_not be_one
      subject.true?.should eq(false)
      subject.should_not be_tautology
    end

    it 'is not satisfiable' do
      subject.should_not be_satisfiable
    end

  end
end