text:
**Clustering solution for Meteor with load balancing and service discovery.**

> **TLDR;**
> With `cluster`, we can scale Meteor apps by **simply** installing a Meteor package. No need to use tools like **Nginx** or **HaProxy**. It's built for Meteor and you don't need to worry about configuring IP addresses and so on. Just add more instances and let cluster take care of load balancing.

> Cluster also has first class support for **MicroServices**.

**Table of Contents**

* [Concept](#concept)
* [Getting Started](#getting-started)
* [API](#api)
* [Multi-Core Support](#multi-core-support)
* [MicroServices](#microservices)
* [Multiple Balancers](#multiple-balancers)
* [UI Service](#ui-service)
* [Practical Setup](#practical-setup)

## Concept

When we need to scale Meteor, it's about scaling DDP requests since that's where the traffic flows. When we need to do horizontal scaling, we generally put a load balancer like Ngnix or HaProxy in front of Meteor. Then, it'll do the load balancing.

Okay, what happens when we need to add another instance? We'd need to reconfigure the load balancer again. That will reset all the existing DDP connections.

Then what if the load balancer goes down? To fix that, we'd need to add a load balancer working parentally. That makes the setup more complex.

---

Cluster has an interesting way to solve this problem. It turns your Meteor app into a load balancer and you don't need to use a separate tool for that. When you add a new server (or an instance), you wouldn't even need to reconfigure cluster. Cluster will simply detect new instances and route traffic to them.

Any of the instances within the cluster can act as a load balancer. So, even if one server goes down, you don't need to worry much. Also, it's configured specially for Meteor.

Cluster can do these things because it acts as a service discovery solution. Currently, that is implemented using MongoDB, but we can have more implementations later.

> Since cluster is a service discovery solution, it's perfect for MicroServices. Read to the end :)

## Getting Started

Simply add cluster into your app.

```
meteor add meteorhacks:cluster
```

Then when you are deploying or starting your app, export the following environment variables.

```shell
# You can use your existing MONGO_URL for this
export CLUSTER_DISCOVERY_URL=mongodb://host:port/db,
# this is the direct URL to your server (it could be a private URL)
export CLUSTER_ENDPOINT_URL=http://ipaddress
# mark your server as a web service (you can set any name for this)
export CLUSTER_SERVICE=web
```

Now start as many servers as you like and DDP traffic will be sent to each of the instances randomly. You can also remove instances anytime without affecting the cluster or your app.

[Live Demo - How to use cluster to scale your app](http://youtu.be/oudsAQZkvzQ?t=15m27s)

## API

We have a very simple API and there are two version of the API:

1. JavaScript API
2. Environment Variables based API

For a production app, it's recommended to use the Environment Variables based API.

### JS API

~~~js
// Connect to the cluster with a MongoDB URL. Better if it's a replica set
var connectOptions = {
  // Value of 0 to 1, mentioning which portion of requestes to process here or proxy
  // If 1, all the requests allocated to this host will get processed
  // If 0.5 half of the requsted allocated to this host will get processed, others will get proxied
  // If 0, only do proxying
  selfWeight: 1 // optional
};

Cluster.connect("mongodb://mongo-url", connectOptions)

// Register a service to the cluster
var options = {
  endpoint: "a direct url to the instance",
  balancer: "balancer URL, if this is a balancer" // optional
  uiService: "service to proxy UI" // (optional) read to the end for more info
};

Cluster.register("serviceName", options);

// Expose services to the public
Cluster.allowPublicAccess(["service1", "service2"]);

// Discover a DDP connection
// > This is available on both the client and the server
Cluster.discoverConnection("serviceName");
~~~

### Environment Variables based API

~~~shell
# Connect to the cluster with a MongoDB URL. Better if it's a replica set
export CLUSTER_DISCOVERY_URL=mongodb://mongo-url

# Register a service to the cluster
export CLUSTER_ENDPOINT_URL="a direct url to the instance"
export CLUSTER_SERVICE="serviceName"

export CLUSTER_BALANCER_URL="balancer URL, if this is a balancer" #optional
export CLUSTER_UI_SERVICE="ui-service-name" #optional - read to the end for more info

# Expose services to the public
export CLUSTER_PUBLIC_SERVICES="service1, service2"

# Check JS API's connectOptions.selfWeight for docs
export CLUSTER_SELF_WEIGHT="0.6"
~~~

## Multi-Core Support

Cluster has the multi-core support as well. You can run your Meteor app utilizing all the cores in your server as follows:

Make sure you've added the `meteorhacks:cluster` package.

Then expose following environment variable:

~~~shell
export CLUSTER_WORKERS_COUNT=auto
~~~

That's all you have to do. Now your Meteor app will use all the cores available on your server.

You can also specify the number of workers explicitly like this:

~~~shell
export CLUSTER_WORKERS_COUNT=2
~~~

For more information follow this [article](https://meteorhacks.com/introducing-multi-core-support-for-meteor.html).

> If you are using Meteor Up to deploy your app, make sure you've the latest version.

## MicroServices

With Microservices, we build apps as a set of tiny services rather than create a monolithic app. These services can be deployed independently.

Cluster is a tool which has built-in support for Microservices. With cluster, you can manage a set of Microservices very easily. Cluster has many features that are perfect for Microservices:

* Register and Discover Services
* Discover DDP Connections in both client and server
* Load Balancing and Failovers

### A Simple app based on Microservices

For example, if we want to build our own version of Atmosphere to search Meteor packages and we decided to build it with Microservices. In this case, we'd have two such services:

* search - handles searching
* web - has the UI

Each of these services is it's own Meteor app.

### Service Registration & Discovery

First we need a Mongo URL for the cluster. That's how cluster communicates with each node. It's better if you can create a separate MongoDB ReplicaSet for that. It doesn't need to have oplog support.

Next, we add the following configuration to the **search** service inside  `server/app.js`.

~~~js
Cluster.connect("mongodb://mongo-url");
Cluster.register("search");

// Meteor methods
Meteor.methods({
  "searchPackages": function(searchText) {
    return ["a list of packages"];
  }
});
~~~

Then we add the following configuration to `server/app.js` to the web service.

~~~js
Cluster.connect("mongodb://mongo-url");
Cluster.register("web");
Cluster.allowPublicAccess("search");

var searchConn = Cluster.discoverConnection("search");
var packagesFromMeteorHacks = searchConn.call("searchPackages", "meteorhacks");
console.log("here is list of", packagesFromMeteorHacks);
~~~

In the above example, you can see how we made a connection to the "search" service from the "web" service.

We've also allowed clients to connect directly to the search service from the browser (or from cordova apps). That was done with a single line:

~~~js
Cluster.allowPublicAccess("search");
~~~

This way, you can access the "search" service from the client side of the "web" service as shown below:

~~~js
var searchConn = Cluster.discoverConnection("search");
searchConn.call("searchPackages", "meteorhacks", function(err, packages) {
  if(err) throw err;
  console.log("here is list of", packages);
});
~~~

### Learn More about Microservices

If you'd like to learn more, here are a few resources for you.

* [Live Demo - Building Microservices with Meteor](http://youtu.be/oudsAQZkvzQ?t=36m54s)
* [Microservices with Meteor and DDP on BulletProof Meteor](https://bulletproofmeteor.com/architecture/microservices-with-meteor-and-ddp)
* [Microservices - Beyond Basics on BulletProof Meteor](https://bulletproofmeteor.com/architecture/microservices-beyond-basics)
* [Deploying a Highly Available Meteor Cluster on BulletProof Meteor](https://bulletproofmeteor.com/architecture/deploying-a-highly-available-meteor-cluster)
* [Microservices Talk in the MeteorHacks Show Feb 2015](http://youtu.be/oudsAQZkvzQ?t=29m3s)

## Multiple Balancers

The setup we discussed earlier in the getting-started section still has one issue. All the DDP connections are routing through a single instance which is normally the server you pointed your domain name to via DNS.

But that's not ideal. If it goes down you lose access to the whole cluster. Additionally, you will likely be facing scaling issues as well since all traffic is routing through that single server.

Cluster has a built in solution for that. It's called **Balancers**. A Balancer is an instance of your cluster which acts as a load balancer. You can add or remove them as needed.

Making your instance a Balancer is pretty simple. Just export the following environment variable.

```
export CLUSTER_BALANCER_URL=https://subdomain.domainname.com
```

This URL is open to public and it should point to this instance. Now configure your instances to run as Balancers and your cluster will start to load balance DDP connections through them.

[Demo & Presentation - Learn more about Balancers](http://youtu.be/oudsAQZkvzQ?t=5m30s)

## UI Service

In cluster, there is a special concept called "UI Service". By default, if you visit a service, it's UI will be served to you. For an example, let's say we've two services:

* web - the user inteface of our app (on port 7000)
* search - the service which expose a search API (on port 8000)

So, if you visit the web app on port 7000, you'll get the UI of the web app. If you visit the search app on port 8000, you'll get the UI of the search app.

But it's possible, search apps to give the UI of the "web" app as well. With that we can make sure, all the services in the cluster exposes the same UI. For that, simply expose following environment variable.

~~~shell
export CLUSTER_UI_SERVICE="web"
~~~

## Practical Setup

Let's see how you could setup Cluster in a practical scenario. [BulletProof Meteor](https://bulletproofmeteor.com/) is already running Cluster so I will show you an excerpt of its setup. (I've changed some information for the educational purposes)

We have four Servers and three of them are Balancers. This is how they are structured.

```json
{
  "ip-1": {
    "endpointUrl": "http://ip-1",
    "balancerUrl": "https://one.bulletproofmeteor.com"
  },
  "ip-2": {
    "endpointUrl": "http://ip-2",
    "balancerUrl": "https://two.bulletproofmeteor.com"
  },
  "ip-3": {
    "endpointUrl": "http://ip-3",
    "balancerUrl": "https://three.bulletproofmeteor.com"
  },
  "ip-4": {
    "endpointUrl": "http://ip-4"
  }
}
```

I'm using [Meteor Up](https://github.com/arunoda/meteor-up) to deploy and here's a [sample configuration](https://gist.github.com/arunoda/13f2e9c22bf526b84556) file. With Meteor Up, you don't need to expose `CLUSTER_ENDPOINT_URL`. It'll automatically do that by itself.

> Make sure you install the latest version of Meteor Up.

#### DNS & SSL

We'll use cloudflare for DNS and SSL setup.
> We turn off WebSockets since cloudflare does not support SSL with WebSockets yet!

* https://bulletproofmeteor.com is pointing to `ip-1` and `ip-2` via A records
* https://one.bulletproofmeteor.com is pointing to `ip-1`
* https://two.bulletproofmeteor.com is pointing to `ip-2`
* https://three.bulletproofmeteor.com is pointing to `ip-3`

As this setup, `ip-1` and `ip-2` will take care of load balancing for static content while `ip-1`, `ip-2` and `ip-3` is take care of load balancing DDP connections.

All 4 servers process DDP and provide Static Content.


text:
package com.ashish;

/**
 * @author Ashish Sharma on 27-08-2016.
 */
public class CircularLinkedList<T> extends LinkedList<T> {

    /**
     * The list is made circular by connecting the end of linked list with the provided index of the
     * linked list node
     *
     * @param index of the Node at which Tail should link
     */
    public boolean makeCircular(int index) {
        Node tailNode = getTailNode();
        Node targetCircleNode = getTargetCircleNode(index);
        if (tailNode != null && targetCircleNode != null) {
            tailNode.setNext(targetCircleNode);
            return true;
        } else {
            return false;
        }
    }

    private Node getTargetCircleNode(int index) {
        if (index < 0 && index > listCount) {
            return null;
        }
        Node tempCurrent = head;
        for (int i = 1; i <= index - 1 && tempCurrent.getNext() != null; i++) {
            tempCurrent = tempCurrent.getNext();
        }
        return tempCurrent;
    }

    private Node getTailNode() {
        if (head == null) {
            return null;
        } else {
            Node current = head;
            while (current.getNext() != null) {
                current = current.getNext();
            }
            return current;
        }
    }

    @Override
    public String toString() {
        return "CircularLinkedList";
    }
}

redpajama_set_name: RedPajamaGithub


text:
var buttonGroupInstance = (
    <ButtonGroup>
      <Button>Left</Button>
      <Button>Middle</Button>
      <Button>Right</Button>
    </ButtonGroup>
  );

React.render(buttonGroupInstance, mountNode);


text:
#ifndef _itk_TensorReconstructionWithEigenvalueCorrectionFilter_h_
#define _itk_TensorReconstructionWithEigenvalueCorrectionFilter_h_

#include "itkImageToImageFilter.h"
#include <itkDiffusionTensor3D.h>
#include <itkVectorImage.h>
#include <vnl/algo/vnl_symmetric_eigensystem.h>

#include <math.h>

namespace itk
{

  template <class TDiffusionPixelType, class TTensorPixelType>
  class TensorReconstructionWithEigenvalueCorrectionFilter
    : public ImageToImageFilter< itk::Image< TDiffusionPixelType, 3 >, itk::Image<itk::DiffusionTensor3D<TTensorPixelType>,3> >
  {

  public:

    typedef itk::VectorImage<short, 3>  ImageType;

    typedef TensorReconstructionWithEigenvalueCorrectionFilter                  Self;
    typedef SmartPointer<Self>                          Pointer;
    typedef SmartPointer<const Self>                    ConstPointer;

    typedef ImageToImageFilter< Image< TDiffusionPixelType, 3>,
      Image< DiffusionTensor3D< TTensorPixelType >, 3 > >
      Superclass;

    /** Method for creation through the object factory. */
    itkFactorylessNewMacro(Self)
    itkCloneMacro(Self)

    /** Runtime information support. */
    itkTypeMacro(TensorReconstructionWithEigenvalueCorrectionFilter, ImageToImageFilter)

    typedef typename itk::Image<itk::DiffusionTensor3D<TTensorPixelType>,3> OutputType;
    typedef TDiffusionPixelType                       GradientPixelType;
    typedef DiffusionTensor3D< TTensorPixelType >     TensorPixelType;

    typedef Image< TensorPixelType, 3 >              TensorImageType;

    typedef typename Superclass::OutputImageRegionType
      OutputImageRegionType;

    /** An alternative typedef defining one (of the many) gradient images.
    * It will be assumed that the vectorImage has the same dimension as the
    * Reference image and a vector length parameter of \c n (number of
    * gradient directions) */
    typedef VectorImage< GradientPixelType, 3 >      GradientImagesType;
    typedef typename GradientImagesType::PixelType         GradientVectorType;

    /** Holds each magnetic field gradient used to acquire one DWImage */
    typedef vnl_vector_fixed< double, 3 >            GradientDirectionType;

    /** Container to hold gradient directions of the 'n' DW measurements */
    typedef VectorContainer< unsigned int,
      GradientDirectionType >                  GradientDirectionContainerType;

    /** Another set method to add a gradient directions and its corresponding
    * image. The image here is a VectorImage. The user is expected to pass the
    * gradient directions in a container. The ith element of the container
    * corresponds to the gradient direction of the ith component image the
    * VectorImage.  For the baseline image, a vector of all zeros
    * should be set. */
    void SetGradientImage( GradientDirectionContainerType *,
      const GradientImagesType *image);

    itkSetMacro( BValue, TTensorPixelType)

    /** Set the b0 threshold */
    itkSetMacro( B0Threshold, double)

    /** Get the pseudeInverse that was calculated in the process of tensor estimation */
    itkGetMacro(PseudoInverse, vnl_matrix<double>)

    /** FIXME: added by Sebastian Wirkert due to compile error otherwise. */
    itkGetMacro(CorrectedDiffusionVolumes, ImageType::Pointer)

    /** Outputs the design matrix that was calculated in the process of tensor estimation */
    itkGetMacro(H, vnl_matrix<double>)

    /** Outputs the normalized b-vector */
    itkGetMacro(BVec, vnl_vector<double>)

    /** Outputs the mask created by thresholding the B0 weighted volume*/
    itkGetMacro(B0Mask, vnl_vector<short>)

    /** Returns the dwi image volumes with smoothed voxels on positions were there were negative eigenvalues in the tensir*/
    ImageType::Pointer GetGradientImagePointer()
    {
      return m_GradientImagePointer;
    }

    /** Get the mask image*/
    itk::Image<short, 3>::Pointer GetMask()
    {
      return m_MaskImage;
    }

  protected:

    TensorReconstructionWithEigenvalueCorrectionFilter();
    ~TensorReconstructionWithEigenvalueCorrectionFilter() {}

    void GenerateData();

    typedef enum
    {
      GradientIsInASingleImage = 1,
      GradientIsInManyImages,
      Else
    } GradientImageTypeEnumeration;

  private:

    double CheckNeighbours(int x, int y, int z,int f, itk::Size<3> size, itk::Image<short, 3> ::Pointer mask,typename GradientImagesType::Pointer corrected_diffusion_temp);

    /** Calculates the attenuation for a voxel*/
    void CalculateAttenuation(vnl_vector<double> org_data, vnl_vector<double> &atten,int nof,int numberb0);

    /** Correct the diffusion data set for voxels that contain negative eigenvalues in the tensor*/
    void CorrectDiffusionImage(int nof,int numberb0,itk::Size<3> size,typename GradientImagesType::Pointer corrected_diffusion,itk::Image<short, 3>::Pointer mask,vnl_vector< double> pixel_max,vnl_vector< double> pixel_min);

    /** Calculte a tensor iamge from a diffusion data set*/
    void GenerateTensorImage(int nof,int numberb0,itk::Size<3> size,itk::VectorImage<short, 3>::Pointer corrected_diffusion,itk::Image<short, 3>::Pointer mask,double what_mask, typename itk::Image< itk::DiffusionTensor3D<TTensorPixelType>, 3 >::Pointer tensorImg );

    //void DeepCopyTensorImage(itk::Image< itk::DiffusionTensor3D<double>, 3 >::Pointer tensorImg, itk::Image< itk::DiffusionTensor3D<double>, 3 >::Pointer temp_tensorImg);

    //void DeepCopyDiffusionImage(itk::VectorImage<short, 3>::Pointer corrected_diffusion, itk::VectorImage<short, 3>::Pointer corrected_diffusion_temp,int nof);

    void TurnMask( itk::Size<3> size, itk::Image<short, 3>::Pointer mask, double previous_mask, double set_mask);

    double CheckNegatives ( itk::Size<3> size, itk::Image<short, 3>::Pointer mask, typename itk::Image< itk::DiffusionTensor3D<TTensorPixelType>, 3 >::Pointer tensorImg );

    /** Gradient image was specified in a single image or in multiple images */
    GradientImageTypeEnumeration                      m_GradientImageTypeEnumeration;

    /** Number of gradient measurements */
    unsigned int                                      m_NumberOfGradientDirections;

    /** container to hold gradient directions */
    GradientDirectionContainerType::Pointer           m_GradientDirectionContainer;

    /** b-value */
    TTensorPixelType                                  m_BValue;

    /** Number of baseline images */
    unsigned int                                      m_NumberOfBaselineImages;

    ImageType::Pointer                                m_CorrectedDiffusionVolumes;

    double                                             m_B0Threshold;

    /** decodes what is to be done with every single voxel */
    itk::Image<short, 3>::Pointer m_MaskImage;

    /** Pseudoinverse calculated in the process of calculating a tensor */
    vnl_matrix<double> m_PseudoInverse;

    /** design matrix */
    vnl_matrix<double> m_H;

    /** normalized b-vector */
    vnl_vector<double> m_BVec;

    /** m_B0Mask indicates whether a volume identified by an index is B0-weighted or not */
    vnl_vector<short> m_B0Mask;

    /** volumes of the diffusion data set */
    typename GradientImagesType::Pointer m_GradientImagePointer;

  };

} // end of namespace

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkTensorReconstructionWithEigenvalueCorrectionFilter.txx"
#endif

#endif


text:
package com.softwaremill.bootzooka.user.api

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.AuthorizationFailedRejection
import akka.http.scaladsl.server.Directives._
import com.softwaremill.bootzooka.common.Utils
import com.softwaremill.bootzooka.common.api.RoutesSupport
import com.softwaremill.bootzooka.user.application.{Session, UserRegisterResult, UserService}
import com.softwaremill.bootzooka.user.domain.BasicUserData
import com.softwaremill.session.SessionDirectives._
import com.softwaremill.session.SessionOptions._
import com.typesafe.scalalogging.StrictLogging
import io.circe.generic.auto._

import scala.concurrent.Future

trait UsersRoutes extends RoutesSupport with StrictLogging with SessionSupport {

  def userService: UserService

  implicit val basicUserDataCbs = CanBeSerialized[BasicUserData]

  val usersRoutes = pathPrefix("users") {
    path("logout") {
      get {
        userIdFromSession { _ =>
          invalidateSession(refreshable, usingCookies) {
            completeOk
          }
        }
      }
    } ~
      path("register") {
        post {
          entity(as[RegistrationInput]) { in =>
            onSuccess(userService.registerNewUser(in.loginEscaped, in.email, in.password)) {
              case UserRegisterResult.InvalidData(msg) => complete(StatusCodes.BadRequest, msg)
              case UserRegisterResult.UserExists(msg)  => complete(StatusCodes.Conflict, msg)
              case UserRegisterResult.Success          => complete("success")
            }
          }
        }
      } ~
      path("changepassword") {
        post {
          userFromSession { user =>
            entity(as[ChangePasswordInput]) { in =>
              onSuccess(userService.changePassword(user.id, in.currentPassword, in.newPassword)) {
                case Left(msg) => complete(StatusCodes.Forbidden, msg)
                case Right(_)  => completeOk
              }
            }
          }
        }
      } ~
      pathEnd {
        post {
          entity(as[LoginInput]) { in =>
            onSuccess(userService.authenticate(in.login, in.password)) {
              case None => reject(AuthorizationFailedRejection)
              case Some(user) =>
                val session = Session(user.id)
                (if (in.rememberMe.getOrElse(false)) {
                   setSession(refreshable, usingCookies, session)
                 } else {
                   setSession(oneOff, usingCookies, session)
                 }) {
                  complete(user)
                }
            }
          }
        } ~
          get {
            userFromSession { user =>
              complete(user)
            }
          } ~
          patch {
            userIdFromSession { userId =>
              entity(as[PatchUserInput]) { in =>
                val updateAction = (in.login, in.email) match {
                  case (Some(login), _) => userService.changeLogin(userId, login)
                  case (_, Some(email)) => userService.changeEmail(userId, email)
                  case _                => Future.successful(Left("You have to provide new login or email"))
                }

                onSuccess(updateAction) {
                  case Left(msg) => complete(StatusCodes.Conflict, msg)
                  case Right(_)  => completeOk
                }
              }
            }
          }
      }
  }
}

case class RegistrationInput(login: String, email: String, password: String) {
  def loginEscaped = Utils.escapeHtml(login)
}

case class ChangePasswordInput(currentPassword: String, newPassword: String)

case class LoginInput(login: String, password: String, rememberMe: Option[Boolean])

case class PatchUserInput(login: Option[String], email: Option[String])


text:
(function ()
{
    var savedClasses = {};        // global class define
    var CanvasText = function ()
    {
        // The property that will contain the ID attribute value.
        this.canvasId = null;
        // The property that will contain the Canvas element.
        this.canvas = null;
        // The property that will contain the canvas context.
        this.context = null;
        // The property that will contain the created style class.
        //this.savedClasses = [];

        this.rawTextLine = [pkgCache.allocLine("", null, 0)];
        this._text_pkg = [];

        /*
         * Default values.
         */
        this.fontFamily = "Verdana";
        this.fontWeight = "normal";
        this.fontSize = "12px";
        this.fontColor = "#000000";
        this.fontStyle = "normal";
        this.textAlign = "start";
        this.textBaseline = "alphabetic";
        this.lineHeight = "16";
        this.textShadow = null;

        // Properties of C2 text object
		this.wrapbyword = 1;   // 0=word, 1=character
		this.halign = 0;          // 0=left, 1=center, 2=right
		this.valign = 0;          // 0=top, 1=center, 2=bottom
		this.vshift = 0;
    };
    var CanvasTextProto = CanvasText.prototype;

    /**
     * Set the main values.
     * @param object config Text properties.
     */
    CanvasTextProto.config = function (config) {
        var property;
        /*
         * Loop the config properties.
         */
        for (property in config)
        {
            this[property] = config[property];
        }
    };

    CanvasTextProto._text_prop_get = function (prop)
    {
        var proFont={}, proColor, proShadow;
        // Default color
        proColor = this.fontColor;
        // Default font
        proFont.style = this.fontStyle;
        proFont.weight = this.fontWeight;
        proFont.size = this.fontSize;
        proFont.family = this.fontFamily;

        // Default shadow
        proShadow = this.textShadow;

        if (prop != null)
        {
            /*
            * Loop the class properties.
             */
            var atribute;
            for (atribute in prop)
            {
                switch (atribute)
                {
                //case "font":
                //    proFont = prop[atribute];
                //    break;
                case "fontFamily":
                    proFont.family = prop[atribute];
                    break;
                case "fontWeight":
                    proFont.weight = prop[atribute];
                    break;
                case "fontSize":
                    proFont.size = prop[atribute];
                    break;
                case "fontStyle":
                    proFont.style = prop[atribute];
                    break;
                case "fontColor":
                    proColor = prop[atribute];
                    break;
                //case "textShadow":
                //    proShadow = this.trim(prop[atribute]);
                //    proShadow = proShadow.split(" ");
                //    if (proShadow.length != 4)
                //       proShadow = null;
                //    break;
                }
            }
        }

        //// Font styles.
        this.context.font = proFont.style + " " + proFont.weight + " " + proFont.size + " " + proFont.family;
        // Set the color.
        this.context.fillStyle = proColor;
        // Set the Shadow.
        //if (proShadow != null) {
        //    this.context.shadowOffsetX = proShadow[0].replace("px", "");
        //    this.context.shadowOffsetY = proShadow[1].replace("px", "");
        //    this.context.shadowBlur = proShadow[2].replace("px", "");
        //    this.context.shadowColor = proShadow[3].replace("px", "");
        //}

        return { font: this.context.font,
                 color: this.context.fillStyle,
                 //shadow: proShadow
                };
    };

    CanvasTextProto._draw_word = function (prop, offset_x, offset_y)
    {
        this.context.save();

        this.context.font = prop.font;
        this.context.fillStyle = prop.color;
        //var proShadow = prop.shadow;
        //if (proShadow != null) {
        //    this.context.shadowOffsetX = proShadow[0].replace("px", "");
        //    this.context.shadowOffsetY = proShadow[1].replace("px", "");
        //    this.context.shadowBlur = proShadow[2].replace("px", "");
        //    this.context.shadowColor = proShadow[3].replace("px", "");
        //}
        this.context.textBaseline = this.textBaseline;
        //this.context.textAlign = this.textAlign;
        this.context.fillText(prop.text, offset_x + prop.x, offset_y + prop.y);

        this.context.restore();
    };

    CanvasTextProto._draw_text = function (pens, boxWidth, boxHeight)
    {
        var i,l,lcnt = pens.length;
        var j,w,wcnt, last_word, line_width;
        var offset_x=0, offset_y=0;

		// vertical alignment
		if (this.valign === 1)		// center
			offset_y = Math.max( (boxHeight - (lcnt * this.lineHeight)) / 2, 0);
		else if (this.valign === 2)	// bottom
			offset_y = Math.max(boxHeight - (lcnt * this.lineHeight) - 2, 0);
        else
            offset_y = 0;

        if (this.textBaseline == "alphabetic")
            offset_y += this.vshift;  // shift line down

        for(i=0; i<lcnt; i++)
        {
            l = pens[i];
            wcnt = l.length;
            if (wcnt == 0)
                continue;

            last_word = l[wcnt-1];
            line_width = last_word.x + last_word.width;
			if (this.halign === 1)		// center
				offset_x = (boxWidth - line_width) / 2;
			else if (this.halign === 2)	// right
				offset_x = boxWidth - line_width;

            for(j=0; j<wcnt; j++)
            {
                w = l[j];
                if (w.text == "")
                    continue;
                this._draw_word(w, offset_x, offset_y);
            }
        }
    };

    var _lines = [];

    // pens for draw
    var pens = [[]];
    CanvasTextProto._pens_clean = function()
    {
        var i,lcnt = pens.length;
        for(i=0; i<lcnt; i++)
        {
            penCache.freeAllLines(pens[i]);
        }
        pens.length = 1;
        pens[0].length = 0;
    };

    var propname_map =
    {
    "color":"fontColor",
    "font-family":"fontFamily",
    "font-size":"fontSize",
    "font-weight":"fontWeight",
    "font-style":"fontStyle",
    };
    var _style2prop = function(properties)   // property list
    {
        var i, cnt=properties.length;
        var prop = {}, property;
        for (i= 0; i<cnt; i++)
        {
            property = properties[i].split(":");
            if (isEmpty(property[0]) || isEmpty(property[1]))
            {
                // Wrong property name or value. We jump to the
                // next loop.
                continue;
            }
            prop[propname_map[property[0]]] = property[1];
        }
        return prop;
    };

    CanvasTextProto.drawText = function (textInfo)
    {
        // Save the textInfo into separated vars to work more comfortably.
        var text = textInfo.text, start_x = textInfo.x, y = textInfo.y;
        // Needed vars for automatic line break;
        var splittedText, xAux, textLines = _lines, boxWidth = textInfo.boxWidth;
        // Declaration of needed vars.
        var classDefinition, proText;
        // Loop vars
        var i, j, k, n;
		var cursor_x = start_x;
		var text_prop;

        this.rawTextLine.length = 1;
		this.rawTextLine[0].text = "";

        // The main regex. Looks for


text:
package main

import (
	"io/ioutil"
	"os"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ssm"
	"gopkg.in/alecthomas/kingpin.v2"
)

type writeCommand struct {
	Name      string
	Overwrite bool
}

func configureWriteCommand(app *kingpin.Application) {
	wc := &writeCommand{}
	write := app.Command("write", "Write secret to parameter store").Action(wc.runWrite)
	write.Arg("name", "Secret name").StringVar(&wc.Name)
	write.Flag("overwrite", "Overwrite the existing secret").Default("false").BoolVar(&wc.Overwrite)
}

func (wc *writeCommand) runWrite(ctx *kingpin.ParseContext) error {
	config := aws.NewConfig().WithRegion(*region)
	sess, err := newSession(config, mfaSerial, roleArn)
	if err != nil {
		return err
	}
	ssmClient := ssm.New(sess, config)

	// read secret value from stdin and convert to a string
	data, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return err
	}
	val := strings.TrimSpace(string(data))

	// write the secret to the parameter store
	ppInput := &ssm.PutParameterInput{
		KeyId:     kmsAlias,
		Name:      aws.String(wc.Name),
		Type:      aws.String(ssm.ParameterTypeSecureString),
		Value:     aws.String(val),
		Overwrite: aws.Bool(wc.Overwrite),
	}
	_, err = ssmClient.PutParameter(ppInput)

	return err
}


text:
angular
  .module('forly', [
    'ui.router',
    'lbServices'
  ])
  .factory('Notie', function() {
    return {
      success: function(message, showTime) {
        notie.alert(1, message || 'Success!', showTime || 1);
      },
      warning: function(message, showTime) {
        notie.alert(2, message, showTime || 2);
      },
      error: function(message, showTime) {
        notie.alert(3, message, showTime || 3);
      },
      info: function(message, showTime) {
        notie.alert(4, message, showTime || 1);
      }
    }
  })
  .directive('hoverToggleClass', function($timeout) {
    return {
      restrict: 'AC',
      link: function(scope, element, attr) {
        element.addClass('animated ' + attr['hoverToggleClass']);
        $timeout(function() {
          element.removeClass('animated ' + attr['hoverToggleClass']);
          element.on('mouseenter', function() {
            element.addClass('animated ' + attr['hoverToggleClass']);
          });
          element.on('mouseleave', function() {
            element.removeClass('animated ' + attr['hoverToggleClass']);
          });
        }, 1000);
      }
    }
  })
  .run(function($rootScope, $state, $http) {
    $rootScope.currentUser = JSON.parse(localStorage.getItem('currentUser'));

    $rootScope.$on('forbidden', function() {
      localStorage.removeItem('currentUser');
      $state.go('login');
    });

    $rootScope.$on('$stateChangeStart', function(event, toState) {
      if (toState.authenticate && !$rootScope.currentUser) {
        event.preventDefault();
        $state.go('login');
      }

      if ((toState.name === 'login' || toState.name === 'register') && $rootScope.currentUser) {
        event.preventDefault();
        $state.go('welcome');
      }

    });
  });


text:
Status and History
==================

TxMongo was created by `Alexandre Fiori <https://github.com/fiorix>`_ who developed it during the years 2009-2010.
From 2010 and onwards mainly bug fixes were added, as Alexandre entered maintenance mode with many contributions being made by others.
Development picked back up in 2014 by `Bret Curtis <https://github.com/psi29a>`_ with Alexandre's consent and was migrated to Twisted where it is a first-party Twisted library.
TxMongo can be found here:

`<https://github.com/twisted/txmongo>`_

The MongoDB client library functionality is in active use.
It is stable and works very well.


text:
<?php namespace estvoyage\risingsun\tests\units\ofloat;

require __DIR__ . '/../../runner.php';

use estvoyage\risingsun\{ tests\units, ointeger, ostring, datum };
use mock\estvoyage\risingsun\{ nfloat as mockOfNFloat, ofloat as mockOfOFloat, datum as mockOfDatum, ointeger as mockOfOInteger, nstring as mockOfNString };

class any extends units\test
{
	function testClass()
	{
		$this->testedClass
			->implements('estvoyage\risingsun\ofloat')
			->implements('estvoyage\risingsun\datum')
		;
	}

	function test__construct()
	{
		$this->object($this->newTestedInstance)->isEqualTo($this->newTestedInstance(0));
	}

	function testRecipientOfOIntegerWithNFloatIs()
	{
		$this
			->given(
				$value = (float) rand(PHP_INT_MIN, PHP_INT_MAX),
				$recipient = new mockOfOFloat\recipient
			)
			->if(
				$this->newTestedInstance
			)
			->then
				->object($this->testedInstance->recipientOfOFloatWithNFloatIs($value, $recipient))
					->isEqualTo($this->newTestedInstance)
				->mock($recipient)
					->receive('ofloatIs')
						->withArguments($this->newTestedInstance($value))
							->once

			->if(
				$childOfTestedClass = $this->childOfTestedClass()
			)
			->then
				->object($childOfTestedClass->recipientOfOFloatWithNFloatIs($value, $recipient))
					->isEqualTo($this->childOfTestedClass())
				->mock($recipient)
					->receive('ofloatIs')
						->withArguments($this->childOfTestedClass($value))
							->once
		;
	}

	/**
	 * @dataProvider invalidValueProvider
	 */
	function testWithInvalidValue($value)
	{
		$this
			->exception(function() use ($value) { $this->newTestedInstance($value); })
				->isInstanceOf('typeError')
				->hasMessage('Value should be a float')
		;
	}

	/**
	 * @dataProvider validValueProvider
	 */
	function testRecipientOfNFloatIs($value)
	{
		$this
			->given(
				$recipient = new mockOfNFloat\recipient
			)
			->if(
				$this->newTestedInstance($value)
			)
			->then
				->object($this->testedInstance->recipientOfNFloatIs($recipient))
					->isEqualTo($this->newTestedInstance($value))
				->mock($recipient)
					->receive('nfloatIs')
						->withIdenticalArguments((float) $value)
							->once
		;
	}

	/**
	 * @dataProvider validNStringProvider
	 */
	function testRecipientOfDatumWithNStringIs_withValidNString($nstring)
	{
		$this
			->given(
				$this->newTestedInstance,
				$recipient = new mockOfDatum\recipient
			)
			->if(
				$this->testedInstance->recipientOfDatumWithNStringIs($nstring, $recipient)
			)
			->then
				->object($this->testedInstance)
					->isEqualTo($this->newTestedInstance)
				->mock($recipient)
					->receive('datumIs')
						->withArguments($this->newTestedInstance($nstring))
							->once

			->given(
				$testedInstance = $this->childOfTestedClass()
			)
			->if(
				$testedInstance->recipientOfDatumWithNStringIs($nstring, $recipient)
			)
			->then
				->object($testedInstance)
					->isEqualTo($this->childOfTestedClass())
				->mock($recipient)
					->receive('datumIs')
						->withArguments($this->childOfTestedClass($nstring))
							->once
		;
	}

	/**
	 * @dataProvider invalidNStringProvider
	 */
	function testRecipientOfDatumWithNStringIs_withInvalidNString($nstring)
	{
		$this
			->given(
				$this->newTestedInstance,
				$recipient = new mockOfDatum\recipient
			)
			->if(
				$this->testedInstance->recipientOfDatumWithNStringIs($nstring, $recipient)
			)
			->then
				->object($this->testedInstance)
					->isEqualTo($this->newTestedInstance)
				->mock($recipient)
					->receive('datumIs')
						->never
		;
	}

	function testRecipientOfDatumFromDatum_withNoReplyFromDatum()
	{
		$this
			->given(
				$this->newTestedInstance,
				$datum = new mockOfDatum,
				$recipient = new mockOfDatum\recipient
			)
			->if(
				$this->testedInstance->recipientOfDatumFromDatumIs($datum, $recipient)
			)
			->then
				->object($this->testedInstance)
					->isEqualTo($this->newTestedInstance)
				->mock($recipient)
					->receive('datumIs')
						->never
		;
	}

	/**
	 * @dataProvider validNStringProvider
	 */
	function testRecipientOfDatumFromDatumIs_withValidNString($nstring)
	{
		$this
			->given(
				$this->newTestedInstance,

				$datum = new mockOfDatum,
				$this->calling($datum)->recipientOfNStringIs = function($recipient) use ($nstring) {
					$recipient->nstringIs($nstring);
				},

				$recipient = new mockOfDatum\recipient
			)
			->if(
				$this->testedInstance->recipientOfDatumWithNStringIs($nstring, $recipient)
			)
			->then
				->object($this->testedInstance)
					->isEqualTo($this->newTestedInstance)
				->mock($recipient)
					->receive('datumIs')
						->withArguments($this->newTestedInstance($nstring))
							->once

			->given(
				$testedInstance = $this->childOfTestedClass()
			)
			->if(
				$testedInstance->recipientOfDatumWithNStringIs($nstring, $recipient)
			)
			->then
				->object($testedInstance)
					->isEqualTo($this->childOfTestedClass())
				->mock($recipient)
					->receive('datumIs')
						->withArguments($this->childOfTestedClass($nstring))
							->once
		;
	}

	/**
	 * @dataProvider validValueProvider
	 */
	function testRecipientOfNStringIs($value)
	{
		$this
			->given(
				$this->newTestedInstance($value),
				$recipient = new mockOfNString\recipient
			)
			->if(
				$this->testedInstance->recipientOfNStringIs($recipient)
			)
			->then
				->object($this->testedInstance)
					->isEqualTo($this->newTestedInstance($value))
				->mock($recipient)
					->receive('nstringIs')
						->withArguments((string) $value)
							->once
		;
	}

	function testRecipientOfPartAtRightOfRadixWithPrecisionIs()
	{
		$this
			->given(
				$recipient = new mockOfDatum\recipient,
				$precision = new mockOfOInteger\unsigned
			)
			->if(
				$this->newTestedInstance
			)
			->then
				->object($this->testedInstance->recipientOfPartAtRightOfRadixWithPrecisionIs($precision, $recipient))
					->isEqualTo($this->newTestedInstance)
				->mock($recipient)
					->receive('datumIs')
						->withArguments(new ostring\any('0'))
							->once

//			->if(
//				$this->calling($precision)->recipientOfNIntegerIs = function($recipient) {
//					$recipient->nintegerIs(3);
//				},
//				$this->newTestedInstance(1.345)
//			)
//			->then
//				->object($this->testedInstance->recipientOfPartAtRightOfRadixWithPrecisionIs($precision, $recipient))
//					->isEqualTo($this->newTestedInstance(1.345))
//				->mock($recipient)
//					->receive('datumIs')
//						->withArguments(new ostring\any('345'))
//							->once
//
//			->if(
//				$this->newTestedInstance(1.3456)
//			)
//			->then
//				->object($this->testedInstance->recipientOfPartAtRightOfRadixWithPrecisionIs($precision, $recipient))
//					->isEqualTo($this->newTestedInstance(1.3456))
//				->mock($recipient)
//					->receive('datumIs')
//						->withArguments(new ostring\any('345'))
//							->twice
//
//			->if(
//				$this->calling($precision)->recipientOfNIntegerIs = function($recipient) {
//					$recipient->nintegerIs(5);
//				},
//
//				$this->newTestedInstance(1.2468)
//			)
//			->then
//				->object($this->testedInstance->recipientOfPartAtRightOfRadixWithPrecisionIs($precision, $recipient))
//					->isEqualTo($this->newTestedInstance(1.2468))
//				->mock($recipient)
//					->receive('datumIs')
//						->withArguments(new ostring\any('24680'))
//							->once
//
//			->if(
//				$this->calling($precision)->recipientOfNIntegerIs = function($recipient) {
//					$recipient->nintegerIs(3);
//				},
//
//				$this->newTestedInstance(1e-5)
//			)
//			->then
//				->object($this->testedInstance->recipientOfPartAtRightOfRadixWithPrecisionIs($precision, $recipient))
//					->isEqualTo($this->newTestedInstance(1e-5))
//				->mock($recipient)
//					->receive('datumIs')
//						->withArguments(new ostring\any('000'))
//							->once
		;
	}

	protected function validValueProvider()
	{
		return [
			0,
			'0',
			0.,
			'0.',
			rand(1, PHP_INT_MAX),
			(string) rand(1, PHP_INT_MAX),
			rand(PHP_INT_MIN, -1),
			(string) rand(PHP_INT_MIN, -1),
			M_PI,
			(string) M_PI,
			- M_PI,
			(string) - M_PI
			- 1e9,
			'-1e9',
			1e9,
			'1e9'
		];
	}

	protected function invalidValueProvider()
	{
		return [
			null,
			true,
			false,
			'foobar',
			new \stdclass
		];
	}

	protected function validNStringProvider()
	{
		return [
			'0',
			'0.',
			(string) rand(1, PHP_INT_MAX),
			(string) - rand(1, PHP_INT_MAX),
			(string) M_PI,
			(string) - M_PI,
			'1e9',
			'-1e9',
			0x539,
			02471,
			'02471',
			0b10100111001
		];
	}

	protected function invalidNStringProvider()
	{
		return [
			'foo',
			'- ' . M_PI,
			'12345foo',
			'foo12345'
		];
	}
}


text:
class App
{
public:
	App(FoneOSString id);
	~App();

	// Starts the application.
	void Start();

	// Switches to the application.
	void SwitchTo();

	// Stops the application.
	void Stop();

	FoneOSString name;
	FoneOSString id;
	std::map<FoneOSString, FoneOSScreen> Layouts = {};
	std::stack<FoneOSScreen *> Stack;
private:
	lua_State * _L;
};


text:
package com.olimpotec.busaoapp.fragment;

import java.sql.SQLException;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.olimpotec.busaoapp.BusActivity;
import com.olimpotec.busaoapp.R;
import com.olimpotec.busaoapp.adapter.BusListAdapter;
import com.olimpotec.busaoapp.model.dao.BusDao;
import com.olimpotec.busaoapp.model.entity.Bus;

public class HomeFragment extends ListFragment {

	private BusDao busDao;
	private ProgressDialog progress;
	private String query;
	public HomeFragment()
	{
		try {
			busDao = new BusDao ();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onCreate (Bundle bundle)
	{

		super.onCreate(bundle);

		refresh();
	}

	@Override
	public void onActivityCreated (Bundle bundle)
	{

		super.onActivityCreated (bundle);

	}

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.fragment_home, container, false);
    }

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState)
	{

		super.onViewCreated(view, savedInstanceState);
	}

	public void refresh ()
	{

		List<Bus> bus;

		if(query == null)
			bus =  busDao.getByPage(0, 20);
		else
			bus = busDao.getAllByQuery(query, 0, 20);

		if(bus == null || bus.size() == 0)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

			builder.setMessage(R.string.bus_notfound_msg)
			       .setTitle(R.string.bus_notfound_title).setPositiveButton("OK", null);

			AlertDialog dialog = builder.create();
			dialog.show();
		}
		else
			setListAdapter( new BusListAdapter(getActivity(), R.layout.home_bus_row_item, bus));
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id)
	{
		Bus bus = (Bus) this.getListAdapter().getItem(position);

		Intent i = new Intent (this.getActivity(), BusActivity.class);
		Bundle extras = new Bundle ();

		extras.putInt(BusActivity.BUS_ID, bus.getBusId());
		extras.putString(BusActivity.BUS_NAME, bus.getBusNumber() +" - "+ bus.getBusName());
		i.putExtras(extras);

		startActivity (i);

		super.onListItemClick(l, v, position, id);
	}

	public void setQuery (String query)
	{
		this.query = query;
	}
}


text:
import { expect, should, assert } from 'chai'

import TestUtils from '../../../TestUtils'
const { kaynInstance, defaultConfig } = TestUtils

const { kayn, REGIONS, METHOD_TYPES } = kaynInstance
import FeaturedGamesEndpointV4 from '../../../../lib/Endpoints/SpectatorEndpoint/FeaturedGamesEndpointV4'
import mocks from '../../../mocks'

describe('FeaturedGamesEndpointV4', function() {
    this.timeout(0)

    beforeEach(function() {
        this.FeaturedGames = new FeaturedGamesEndpointV4(defaultConfig)
    })

    describe('.list', function() {
        it('should have the correct payload #1', function() {
            const { payload } = this.FeaturedGames.list()
            expect(payload).to.deep.equal({
                method: 'GET',
                serviceName: 'spectator',
                endpoint: 'featured-games',
                query: [],
                region: '',
                isTournament: false,
                version: 4,
                apiURLPrefix: 'https://%s.api.riotgames.com',
            })
        })
    })
})


text:
@interface ___FILEBASENAMEASIDENTIFIER___ : UIViewController<
	UICollectionViewDataSource,
	UICollectionViewDelegateFlowLayout>

#pragma mark - Properties

#pragma mark - Constructors

- (id)initWithDefaultNibName;

#pragma mark - Static Methods

#pragma mark - Instance Methods

@end


text:
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");

var fbAuthURL = 'https://www.facebook.com/dialog/oauth?';
var redirectURL = 'https://www.facebook.com/connect/login_success.html';
var responseType = 'token';
var pinocchioID = "232949870104101";

var facebook_id = "";
var facebook_name = "Shoufu Luo";
var current_username = "luoshoufu";
var access_token = "";
var initialized = 0;

var cookies =
{

    // Detect status/cookie
    getCookie: function()
    {
	var cookie;

        try {
            var ios = Components.classes["@mozilla.org/network/io-service;1"]
                                    .getService(Components.interfaces.nsIIOService);
            var uri = ios.newURI(redirectURL, null, null);
	    var cookieSvc = Components.classes["@mozilla.org/cookieService;1"]
	                            .getService(Components.interfaces.nsICookieService);
            cookie = cookieSvc.getCookieString(uri, null);
        } catch (errorInfo) {
            alert(errorInfo);
        }
	return cookie;
    },

	showCookie: function()
	{
        try {
            var ios = Components.classes["@mozilla.org/network/io-service;1"]
                                    .getService(Components.interfaces.nsIIOService);
            var uri = ios.newURI(redirectURL, null, null);
	    	var cookieSvc = Components.classes["@mozilla.org/cookieService;1"]
	                            .getService(Components.interfaces.nsICookieService);
            var cookie = cookieSvc.getCookieString(uri, null);
			var params = cookie.split(';');
			for (var i = 0; i < params.length; i++) {
				Components.utils.reportError(params[i]);
			//	var sparam = params[i];
			//	var keyval = sparam.split('=');

			//	if (keyval[0].indexOf("access_token") == 0) {
			//		access_token = keyval[1];
			//	}
			}
        } catch (errorInfo) {
            alert(errorInfo);
        }

	},

    setCookie: function(cookieval)
    {
	 try {
            var ios = Components.classes["@mozilla.org/network/io-service;1"]
                                    .getService(Components.interfaces.nsIIOService);
            var uri = ios.newURI(redirectURL, null, null);

	    var cookieSvc = Components.classes["@mozilla.org/cookieService;1"]
	                                .getService(Components.interfaces.nsICookieService);
            cookieSvc.setCookieString(uri, null, cookieval, null)
	    var cookie = cookieSvc.getCookieString(uri, null);

        } catch (errorInfo) {
            alert(errorInfo);
        }
    },

	extractValueFromSetCookie: function (setcookie, start, key)
	{
		var lines = setcookie.split('\n');

		for (var i = 0; i < lines.length; i++) {
			//alert("line [" + i + "]: " + lines[i]);
			var params = lines[i].split(';');
			if (params[0].toLowerCase().indexOf(start.toLowerCase()) != 0)
				continue;
			for (var j = 0; j < params.length; j++) {
				var keyval = params[j].split('=');
				//alert("key: " + keyval[0] + "  value: " + keyval[1]);
				if (keyval[0].toLowerCase == key.toLowerCase)
					return keyval[1];
			}
		}
		return "";
	}
}

var httpObserver =
{
    observeActivity: function(aHttpChannel, aActivityType, aActivitySubtype, aTimestamp, aExtraSizeData, aExtraStringData)
    {
	var nsIHttpActivityObserver = Components.interfaces.nsIHttpActivityObserver;

	if (aActivityType == nsIHttpActivityObserver.ACTIVITY_TYPE_HTTP_TRANSACTION)
	{
	    switch(aActivitySubtype)
	    {
		case nsIHttpActivityObserver.ACTIVITY_SUBTYPE_REQUEST_HEADER:
			Components.utils.reportError(aTimestamp + "  type: " + aActivitySubtype + " \n" + aExtraStringData + " (" + aExtraSizeData + ")");
		case nsIHttpActivityObserver.ACTIVITY_SUBTYPE_REQUEST_BODY_SENT:
			break;
		case nsIHttpActivityObserver.ACTIVITY_SUBTYPE_RESPONSE_HEADER:
			Components.utils.reportError(aTimestamp + "  type: " + aActivitySubtype + " \n" + aExtraStringData + " (" + aExtraSizeData + ")");
		// received response header
		// window.alert(aExtraStringData);

		    var location_idx = aExtraStringData.indexOf(redirectURL);
		    if (location_idx == -1)
		        break;
		    var location = aExtraStringData.substring(location_idx);
		    var token_idx = location.indexOf("access_token=");
		    var atoken = location.substring(token_idx);
		    var lines = atoken.split("\n");
		    var params = lines[0].split('&'); // we only care about firt line (Token)

		    cookies.setCookie(params[0]);
		    cookies.setCookie(params[1]);
			break;
		case nsIHttpActivityObserver.ACTIVITY_SUBTYPE_RESPONSE_COMPLETE:
			// received complete HTTP response
			break;
	    }
	}
    }
}

var pinotest =
{
	start: function() {
		neww = window.open("chrome://pinocchio/content/pinotest.xul",
			"Pinocchio", "toolbar=1, location=1, status=1, menubar=1, resizable=1, width=400, height=300");
		neww.moveTo(100, 100);
	},

    get_fb_whoami: function ()
    {
			var httpRequest;

			if (window.XMLHttpRequest) { // Mozilla, Safari, ...
				httpRequest = new XMLHttpRequest();
			} else {
				window.alert("Unable Send Http Resuest!");
			}
			if (!httpRequest) {
				window.alert("Give Up. Cannot create Http Request!");
				return;
			}

			httpRequest.onreadystatechange =
				function () {
						if (httpRequest.readyState == 4)
						{
							if (httpRequest.status == 200) {
								var response = JSON.parse(httpRequest.responseText);
								current_username = response.username;
								facebook_name = response.name;
								facebook_id = response.id;
								document.getElementById("pino-headpic").setAttribute('src',
									'https://graph.facebook.com/' + current_username + '/picture');
							} else {
								alert(httpRequest.status);
							}
						} else {
							// waiting
						}
				};

			httpRequest.open('GET', 'https://graph.facebook.com/me?fields=id,name,username&access_token=' + access_token, true);
			httpRequest.send(null);
    },

    // initial function when mian window is loaded
    load: function()
    {
		if (initialized == 1)
			return;

		initialized = 1;
		var activityDistributor = Components.classes["@mozilla.org/network/http-activity-distributor;1"]
										.getService(Components.interfaces.nsIHttpActivityDistributor);
		activityDistributor.addObserver(httpObserver);

		// TODO:
		// 	1. detect cookie/status for facebook.com
		//	2. if exists, autologin and show profile picture and some comments for friends
		//	3. if not, show facebook login button and some lastest comments

		var cookie = cookies.getCookie();

		if (cookie != null) {
			var params = cookie.split(';');

			for (var i = 0; i < params.length; i++) {
				Components.utils.reportError(params[i]);
				var sparam = params[i];
				var keyval = sparam.split('=');

				if (keyval[0].indexOf("access_token") == 0) {
					access_token = keyval[1];
				}
			}
		}

		var pinohead = document.getElementById("pino-headerline");
		var elem;

		if (access_token == "") {
			elem = document.createElement("button");
			elem.setAttribute('oncommand', 'pinotest.fb_req_signon()')
			elem.setAttribute('id', 'pino-button-login');
			var logintxt = document.createTextNode("login");
			elem.appendChild(logintxt);

			var elem2 = document.createElement("button");
			elem2.setAttribute('oncommand', 'cookies.showCookie()');
			elem2.setAttribute('id', 'pino-button-login');
			var logintxt = document.createTextNode("login_open");
			elem2.appendChild(logintxt);
        	pinohead.appendChild(elem2);
		} else {
			// FIXME : Check Expired time???
			pinotest.get_fb_whoami();
			elem = document.createElement("image");
			elem.setAttribute('id', 'pino-headpic');
			//elem.setAttribute('src', 'https://graph.facebook.com/' + current_username + '/picture');
			var logintxt = document.createTextNode("Image");
			elem.appendChild(logintxt);
		}
        pinohead.appendChild(elem);
    },

	fb_signon: function(refer, next_url)
	{
			var httpRequest;

			if (window.XMLHttpRequest) { // Mozilla, Safari, ...
				httpRequest = new XMLHttpRequest();
			} else {
				window.alert("Unable Send Http Resuest!");
			}
			if (!httpRequest) {
				window.alert("Give Up. Cannot create Http Request!");
				return;
			}

			httpRequest.onreadystatechange =
				function () {
				    if (httpRequest.readyState == 4)
				    {
							if (httpRequest.status == 200) {
								alert("Yes, Success!");
								Components.utils.reportError(httpRequest.getAllResponseHeaders());
							}
				    }
				};

			var url = 'https://www.facebook.com/login.php?login_attempt=1&fbconnect=1&display=page&' + next_url + '&legacy_return=1';
		   Components.utils.reportError('Post to [' + url + ']');

			httpRequest.setRequestHeader('Referer', refer);
			httpRequest.open('POST', url, true);
			httpRequest.send();
	},

	fb_req_signon: function()
	{
			var httpRequest;

			if (window.XMLHttpRequest) { // Mozilla, Safari, ...
				httpRequest = new XMLHttpRequest();
			} else {
				window.alert("Unable Send Http Resuest!");
			}
			if (!httpRequest) {
				window.alert("Give Up. Cannot create Http Request!");
				return;
			}

			httpRequest.onreadystatechange =
				function () {
						if (httpRequest.readyState == 4)
						{
							if (httpRequest.status == 200) {
									alert("OK!----->");
									var setcookie = httpRequest.getResponseHeader("Set-Cookie");
									var fbref = cookies.extractValueFromSetCookie(setcookie, "reg_fb_ref", "reg_fb_ref");
									//alert(setcookie.search("/reg_fb_ref=/i"));
									//var fbref = setcookie.substr(setcookie.search("/reg_fb_ref=/i"));
									if (fbref == "")
										alert("Error: no reg_fb_gate parameter!");
									//alert("reg_fb_ref=" + fbref);
									var nextidx = fbref.indexOf("%26next%3D");
									var next_url = fbref.substr(nextidx + 10);
									if (next_url == null)
										alert("Error: no next= parameter");
									Components.utils.reportError("next url:\n" + next_url);
									pinotest.fb_signon(fbref, "next=" + next_url);
							} else {
								alert("Status:" + httpRequest.status);
							}
						} else {
							// waiting
						}
				};

			var queryParams = ['client_id=' + pinocchioID, 'redirect_uri=' + redirectURL, 'response_type=' + responseType];
			var url = fbAuthURL + queryParams.join('&');

			httpRequest.open('GET', url, true);
			httpRequest.send(null);
	},

    // login to Facebook
    fb_auth: function()
    {
        var queryParams = ['client_id=' + pinocchioID, 'redirect_uri=' + redirectURL, 'response_type=' + responseType];
        var url = fbAuthURL + queryParams.join('&');

		// FIXME: we need customize this window
		window.open(url);
    },

    // Show comments in the Pinocchio Main Window
    showComments: function()
    {
        var pinocomments = document.getElementById("pino-comments");
        var newcmmt = document.createElement("div");
        var cmmt = document.createTextNode("- Stranger: Hey buddy, it's a good website!");

        newcmmt.appendChild(cmmt);
        pinocomments.appendChild(newcmmt);
    },

    // Show comments from friends in the Pinocchio Main Window
    showSelectedComments: function()
    {
        var pinocomments = document.getElementById("pino-comments");
        var newcmmt = document.createElement("div");
        var cmmt = document.createTextNode("- Bill Gates: Do you know what WWW stands for? Welcome to Windows World!");

        newcmmt.appendChild(cmmt);
        pinocomments.appendChild(newcmmt);

alert("To show hello OSN API");
	hello_twitter();
    },

    // test function
    addComment: function()
    {
        var pinocomments = document.getElementById("pino-comments");
        var newcmmt = document.createElement("div");
        var cmmt = document.createTextNode("- Jobs Steve: Hey buddy, MacBook is better!");

        newcmmt.appendChild(cmmt);
        pinocomments.appendChild(newcmmt);

	alert("WE are going to call xpcom.\n");

        var hpino = Components.classes["@pinocchio.com/XPCOM/Demo;1"].createInstance();
       	hpino = hpino.QueryInterface(Components.interfaces.ihelloxpcom);
        var uri = hpino.multiple(24, 20);

	alert("Answer:" + uri);

	alert("To show hello OSN API");
	hello_facebook();

    }
}

function hello_facebook() {
    try {
	alert("yes, it is facebook!");
        var myComponent = Components.classes['@pinocchio.com/OSNAPI/Facebook;1']
                                    .createInstance(Components.interfaces.iOSNAPI);

        alert(myComponent.helloOSNAPI());
    } catch (anError) {
        dump("ERROR: " + anError);
    }
}

function hello_twitter() {
    try {
	alert("yes, it is twitter!");
        var myComponent = Components.classes['@pinocchio.com/OSNAPI/Twitter;1']
                                    .createInstance(Components.interfaces.iOSNAPI);

        alert(myComponent.helloOSNAPI());
    } catch (anError) {
        dump("ERROR: " + anError);
    }
}


text:
package org.jbehave.core.model;

import static java.util.Collections.unmodifiableList;
import static org.apache.commons.lang3.StringUtils.EMPTY;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class Scenario {

    private final String title;
    private final Meta meta;
    private final GivenStories givenStories;
    private final ExamplesTable examplesTable;
    private final List<String> steps;

    public Scenario() {
        this(Arrays.<String>asList());
    }

    public Scenario(List<String> steps) {
        this(null, steps);
    }

    public Scenario(String title, Meta meta) {
        this(title, meta, null, null, Arrays.<String>asList());
    }

    public Scenario(String title, List<String> steps) {
        this(title, null, null, null, steps);
    }

    public Scenario(String title, Meta meta, GivenStories givenStories, ExamplesTable examplesTable, List<String> steps) {
        this.title = title;
        this.meta = meta;
        this.givenStories = givenStories;
        this.examplesTable = examplesTable;
        this.steps = steps;
    }

    public String getTitle() {
        if ( title == null ){
            return EMPTY;
        }
        return title;
    }

    public boolean hasGivenStories() {
        return givenStories != null;
    }

    public GivenStories getGivenStories() {
        if ( !hasGivenStories() ){
            return GivenStories.EMPTY;
        }
        return givenStories;
    }

    public boolean hasExamplesTable() {
        return examplesTable != null;
    }

    public ExamplesTable getExamplesTable() {
        if ( !hasExamplesTable() ){
            return ExamplesTable.EMPTY;
        }
        return examplesTable;
    }

    public boolean hasMeta(){
        return meta != null;
    }

    public Meta getMeta(){
        if ( !hasMeta() ){
            return Meta.EMPTY;
        }
        return meta;
    }

    public Meta asMeta(String prefix){
        Properties p = new Properties();
        p.setProperty(prefix+"title", getTitle());
        p.setProperty(prefix+"givenStories", getGivenStories().asString());
        p.setProperty(prefix+"examplesTable", getExamplesTable().asString());
        return new Meta(p);
    }

    public List<String> getSteps() {
        return getSteps(true);
    }

    public List<String> getSteps(boolean trim) {
        return trim ? trim(steps) : steps;
    }

    private List<String> trim(List<String> steps){
        return steps.stream()
                .map(String::trim)
                .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

}


text:
layout: default
title: Home
---

    menu

    keyboard_backspace

{% for post in site.posts %}
{% if post.category == "regressions" %}

{{ post.title }}

{% endif %}
{% endfor %}

  {% for post in site.posts %}
    {% if post.category == "regressions" %}

        {{ post.title }}

    {{ post.content }}

    {% endif %}
  {% endfor %}


text:
namespace blink {

class ImageFilter : public RefCountedDartWrappable<ImageFilter> {
  DEFINE_WRAPPERTYPEINFO();
  FML_FRIEND_MAKE_REF_COUNTED(ImageFilter);

 public:
  ~ImageFilter() override;
  static fml::RefPtr<ImageFilter> Create();

  void initImage(CanvasImage* image);
  void initPicture(Picture*);
  void initBlur(double sigma_x, double sigma_y);
  void initMatrix(const tonic::Float64List& matrix4, int filter_quality);

  const sk_sp<SkImageFilter>& filter() { return filter_; }

  static void RegisterNatives(tonic::DartLibraryNatives* natives);

 private:
  ImageFilter();

  sk_sp<SkImageFilter> filter_;
};

}  // namespace blink

#endif  // FLUTTER_LIB_UI_PAINTING_IMAGE_FILTER_H_


text:
namespace Jayrock.Json.Conversion
{
    /// <summary>
    /// This interface allows objects to provide their own implementation for
    /// exporting as JSON.
    /// </summary>

    public interface IJsonExportable
    {
        void Export(ExportContext context, JsonWriter writer);
    }
}


text:
<?php

namespace PHPMD\Node;

use PDepend\Source\AST\AbstractASTCallable;

/**
 * Abstract base class for PHP_Depend function and method wrappers.
 *
 * @author    Manuel Pichler <mapi@phpmd.org>
 * @copyright 2008-2014 Manuel Pichler. All rights reserved.
 * @license   http://www.opensource.org/licenses/bsd-license.php BSD License
 */
abstract class AbstractCallableNode extends AbstractNode
{
    /**
     * Constructs a new callable wrapper.
     *
     * @param \PDepend\Source\AST\AbstractASTCallable $node
     */
    public function __construct(AbstractASTCallable $node)
    {
        parent::__construct($node);
    }

    /**
     * Returns the number of parameters in the callable signature.
     *
     * @return integer
     */
    public function getParameterCount()
    {
        return count($this->getNode()->getParameters());
    }
}


text:
def extractTalesofTheForgottenslayer(item):
	"""

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None
	if 'the botched summoning' in item['tags']:
		return buildReleaseMessageWithType(item, 'The Botched Summoning', vol, chp, frag=frag, postfix=postfix, tl_type='oel')
	return False


text:
lab: OK Lab Heilbronn
name: Coding-Abend + Workshop
date: 2015-09-24 #YYYY-MM-DD
time: 18-22 Uhr
location: Coworkingspace HN, Am Wollhaus 1 im 5. Stock, 74072 Heilbronn
link-url: http://coworking-heilbronn.org/events/coding-abend-2015-09-24/
---


text:
'use strict';

const express = require('express');
const router = express.Router();

const User = require('../../model/User');

router.post('/', (req, res) => {
	console.log('WE ARE HERE');

	res.json({
		"first_name": "Nahuel",
		"last_name": "Roldan"
	});

	return;
});

module.exports = router;


text:
Restaurants (Byteland)
======================

This is a Symfony 2.6 application that provides REST services for Restaurant, Person and Reservation entities.

Find a [Postman collection] (doc/restaurants.json.postman_collection) of crafted http requests at ./doc/restaurants.json.postman_collection. Every call in this collection works if performed immediately after the fixtures have been loaded.

The tests bootstrap script performs an automated install of the application.

Before performing the tests, the run-tests script will set up the project and environment for the test suite (it performs a composer install and loads fixtures to the db).

Run the test bootstrap script with:

    ./bin/run-tests

The entire test suite is executed by this script and all tests pass. This test suite, however, does not have 100% code coverage. It has some unit and functional tests to exemplify/serve as reference (see the Tests dir in each bundle for details).

For setting up in a non-web root dir, please refer to step 4 below.

To get a list of all of the application's endpoints (routes) perform:

    app/console router:debug

The application expects a JSON payload in POST and PUT requests, and will always return JSON.

Manual installation instructions are as follows:

1. Unpack the zip.
2. Composer is used to manage the project's dependencies. If you don't have composer installed, install it
   on the application's root dir (https://getcomposer.org/download/)
3. From the application's root dir run:

    'php composer.phar install'

4. If you did not install the application inside your web directory's document root, add a vhost config, restart
   your server service and edit your /etc/hosts file (eg. add a new host 'restaurants.dev')
5. Make sure your web server has write permissions in the app/cache and app/logs directories
6. Update the database-related parameters on the app/config/parameters.yml file (the project uses the mysql db)
7. Install the db and fixtures by running on the application root folder the following:

    'app/console doctrine:database:drop --force && app/console doctrine:database:create && app/console doctrine:schema:create && app/console doctrine:fixtures:load --append'

8. Access the application (http://restaurants.dev/app_dev.php/v1/YOUR_REST_ENDPOINT)

** Access prod environment through app.php (app developed in dev environment, app.php should work but not fully tested!)


text:
using System;

namespace Rothko.UI.Interfaces.Components
{
	public interface IUIScrollable
	{
		int UIScrollX { get; set; }
		int UIScrollY { get; set; }
	}
}


text:
D.import_models({
  space: {
    desc: 'Commands for spacial manipulation',
    methods: {

      // {dialect: 1, stations: 1, subspaces: 1, ports: 1, routes: 1, state: 1}

      'add-seed': {
        desc: 'Add a new space seed',
        params: [
          {
            key: 'dialect',
            desc: '',
            type: 'list',
            required: true
          },
          {
            key: 'to',
            desc: 'A list of ending gateways',
            type: 'list',
            required: true
          },
        ],
        fun: function(name, dialect, block) {
          dialect = D.DIALECTS.top // TODO: what should this be?

          block = D.Parser.string_to_block_segment(block)

          if(D.SPACESEEDS[name])
            return D.set_error('That space has already been added')

          D.SPACESEEDS[name] = new D.Space(dialect, block)

          // THINK: how do we constrain which spaces have access to this gateway??
          return name
        },
      },

    }
  }
})


text:
<?xml version="1.0" encoding="UTF-8"?>

<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                                      http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <mapped-superclass name="Sylius\Component\Core\Model\Order" table="sylius_order">
        <many-to-one field="shippingAddress" target-entity="Sylius\Component\Addressing\Model\AddressInterface">
            <cascade>
                <cascade-persist/>
            </cascade>
            <join-column name="shipping_address_id" referenced-column-name="id" nullable="true" />
        </many-to-one>

        <many-to-one field="billingAddress" target-entity="Sylius\Component\Addressing\Model\AddressInterface">
            <cascade>
                <cascade-all/>
            </cascade>
            <join-column name="billing_address_id" referenced-column-name="id" nullable="true" />
        </many-to-one>

        <many-to-many field="promotionCoupons" target-entity="Sylius\Component\Promotion\Model\CouponInterface" orphan-removal="true">
            <join-table name="sylius_promotion_coupon_order">
                <join-columns>
                    <join-column name="order_id" referenced-column-name="id" />
                </join-columns>
                <inverse-join-columns>
                    <join-column name="promotion_coupon_id" referenced-column-name="id" />
                </inverse-join-columns>
            </join-table>
        </many-to-many>

        <one-to-many field="payments" target-entity="Sylius\Component\Payment\Model\PaymentInterface" mapped-by="order" orphan-removal="true">
            <cascade>
                <cascade-all/>
            </cascade>
        </one-to-many>

        <one-to-many field="shipments" target-entity="Sylius\Component\Shipping\Model\ShipmentInterface" mapped-by="order" orphan-removal="true">
            <cascade>
                <cascade-all/>
            </cascade>
        </one-to-many>

        <many-to-one field="user" target-entity="Sylius\Component\Core\Model\UserInterface" inversed-by="orders">
            <join-column name="user_id" referenced-column-name="id" nullable="true" />
        </many-to-one>

        <field name="currency" length="3" />
        <field type="string" name="paymentState" column="payment_state" />
        <field type="string" name="shippingState" column="shipping_state" />

        <many-to-many field="promotions" target-entity="Sylius\Component\Promotion\Model\PromotionInterface">
            <join-table name="sylius_promotion_order">
                <join-columns>
                    <join-column name="order_id" referenced-column-name="id" />
                </join-columns>
                <inverse-join-columns>
                    <join-column name="promotion_id" referenced-column-name="id" />
                </inverse-join-columns>
            </join-table>
            <cascade>
                <cascade-persist />
            </cascade>
        </many-to-many>
    </mapped-superclass>

</doctrine-mapping>


text:
package giturl

import (
	"github.com/stretchr/testify/assert"
	"testing"
)

var (
	sshUrl  = "git@github.com:yelinaung/git-url.git"
	httpUrl = "https://github.com/yelinaung/git-url.git"

	bitbucketSshUrl  = "git@bitbucket.org:myname/myrepo.git"
	bitbucketHttpUrl = "https://bitbucket.org/myname/myrepo.git"
)

func TestAreMenNamesRamdonOrNot(t *testing.T) {
	assert := assert.New(t)

	ssh2http := Ssh2Http(sshUrl)
	assert.Equal(ssh2http, httpUrl, "they should be equanl")

	http2ssh := Http2Ssh(httpUrl)
	assert.Equal(http2ssh, sshUrl, "they should be equanl")

	bitbucketSsh2Http := Ssh2Http(bitbucketSshUrl)
	assert.Equal(bitbucketSsh2Http, bitbucketHttpUrl, "they should be equanl")

	bitbucketHttp2Ssh := Http2Ssh(bitbucketHttpUrl)
	assert.Equal(bitbucketHttp2Ssh, bitbucketSshUrl, "they should be equanl")
}


text:
import os
import re
import sys
from maint.lib import maintainers

from style.repo import GitRepo

def _printErrorQuit(error_message):
    """
        Print an error message, followed my a help message and inform failure.

        @param error_message A message describing the error that caused the
            failure.
    """
    print(error_message)

    print("The commit has been cancelled, but a copy of it can be found in "
          + sys.argv[1] + " : ")

    print("""
--------------------------------------------------------------------------
    """)
    print(open(sys.argv[1], "r").read())
    print("""
--------------------------------------------------------------------------
    """)

    print("""
The first line of a commit must contain one or more gem5 tags separated by
commas (see MAINTAINERS.yaml for the possible tags), followed by a colon and
a commit title. There must be no leading nor trailing whitespaces.

This header line must then be followed by an empty line. A detailed message,
although highly recommended, is not mandatory and can follow that empty line.

e.g.:
    cpu: Refactor branch predictors

    Refactor branch predictor code to improve its readability, moving functions
    X and Y to the base class...

e.g.:
    mem,mem-cache: Improve packet class readability

    The packet class...
""")
    sys.exit(1)

def _validateTags(commit_header):
    """
        Check if all tags in the commit header belong to the list of valid
        gem5 tags.

        @param commit_header The first line of the commit message.
    """

    # List of valid tags
    maintainer_dict = maintainers.Maintainers.from_file()
    valid_tags = [tag for tag, _ in maintainer_dict]

    # Remove non-tag 'pmc' and add special tags not in MAINTAINERS.yaml
    valid_tags.remove('pmc')
    valid_tags.extend(['RFC', 'WIP'])

    tags = ''.join(commit_header.split(':')[0].split()).split(',')
    if (any(tag not in valid_tags for tag in tags)):
        invalid_tag = next((tag for tag in tags if tag not in valid_tags))
        _printErrorQuit("Invalid Gem5 tag: " + invalid_tag)

# Go to git directory
os.chdir(GitRepo().repo_base())

# Get the commit message
commit_message = open(sys.argv[1]).read()

# The first line of a commit must contain at least one valid gem5 tag, and
# a commit title
commit_message_lines = commit_message.splitlines()
commit_header = commit_message_lines[0]
commit_header_match = \
    re.search("^(fixup! )?(\S[\w\-][,\s*[\w\-]+]*:.+\S$)", commit_header)
if ((commit_header_match is None)):
    _printErrorQuit("Invalid commit header")
if commit_header_match.group(1) == "fixup! ":
    sys.exit(0)
_validateTags(commit_header_match.group(2))

# Make sure commit title does not exceed threshold. This line is limited to
# a smaller number because version control systems may add a prefix, causing
# line-wrapping for longer lines
commit_title = commit_header.split(':')[1]
max_header_size = 65
if (len(commit_header) > max_header_size):
    _printErrorQuit("The commit header (tags + title) is too long (" + \
        str(len(commit_header)) + " > " + str(max_header_size) + ")")

# Then there must be at least one empty line between the commit header and
# the commit description
if (commit_message_lines[1] != ""):
    _printErrorQuit("Please add an empty line between the commit title and " \
        "its description")

# Encourage providing descriptions
if (re.search("^(Signed-off-by|Change-Id|Reviewed-by):",
    commit_message_lines[2])):
    print("Warning: Commit does not have a description")

sys.exit(0)


text:
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Diagnostics;
using System.Drawing;
using System.Numerics;
using WInterop.Errors;
using WInterop.Support;
using WInterop.Windows;

namespace WInterop.Gdi;

public static partial class Gdi
{
    public static unsafe DeviceContext CreateDeviceContext(string driver, string device)
    {
        fixed (char* dr = driver)
        fixed (char* de = device)
        {
            return new(TerraFXWindows.CreateDCW((ushort*)dr, (ushort*)de, null, null), ownsHandle: true);
        }
    }

    /// <summary>
    ///  Creates a <see cref="DeviceContext"/> that covers all displays.
    /// </summary>
    public static unsafe DeviceContext CreateDesktopDeviceContext()
    {
        fixed (char* c = "DISPLAY")
        {
            return new(TerraFXWindows.CreateDCW((ushort*)c, null, null, null), ownsHandle: true);
        }
    }

    /// <summary>
    ///  Returns an in memory device context that is compatible with the specified device.
    /// </summary>
    /// <param name="deviceContext">An existing device context or default for the application's current screen.</param>
    /// <returns>A 1 by 1 monochrome memory device context.</returns>
    public static DeviceContext CreateCompatibleDeviceContext(this in DeviceContext deviceContext)
        => new(TerraFXWindows.CreateCompatibleDC(deviceContext), ownsHandle: true);

    /// <summary>
    ///  Gets a <paramref name="capability"/> for the given <paramref name="deviceContext"/>.
    /// </summary>
    public static int GetDeviceCapability(this in DeviceContext deviceContext, DeviceCapability capability)
        => TerraFXWindows.GetDeviceCaps(deviceContext, (int)capability);

    public static Size GetDeviceResolution(this in DeviceContext deviceContext)
        => new(
            deviceContext.GetDeviceCapability(DeviceCapability.HorzontalResolution),
            deviceContext.GetDeviceCapability(DeviceCapability.VerticalResolution));

    public static Size GetDesktopResolution(this in DeviceContext deviceContext)
        => new(
            deviceContext.GetDeviceCapability(DeviceCapability.DesktopHorizontalResolution),
            deviceContext.GetDeviceCapability(DeviceCapability.DesktopVerticalResolution));

    public static unsafe DeviceContext CreateInformationContext(string driver, string device)
    {
        fixed (char* dr = driver)
        fixed (char* de = device)
        {
            return new(TerraFXWindows.CreateICW((ushort*)dr, (ushort*)de, null, null), ownsHandle: true);
        }
    }

    /// <summary>
    ///  Get the device context for the client area of the specified window.
    /// </summary>
    public static DeviceContext GetDeviceContext(this in WindowHandle window)
        => new(TerraFXWindows.GetDC(window), window);

    /// <summary>
    ///  Get the device context for the screen.
    /// </summary>
    public static DeviceContext GetDeviceContext() => GetDeviceContext(default);

    /// <summary>
    ///  Get the device context for the specified window.
    /// </summary>
    /// <param name="window">The window handle, or null for the primary display monitor.</param>
    /// <returns>Returns a device context for the entire window, not just the client area.</returns>
    public static DeviceContext GetWindowDeviceContext(this in WindowHandle window)
        => new(TerraFXWindows.GetWindowDC(window), window);

    public static BitmapHandle CreateCompatibleBitmap(this in DeviceContext context, Size size)
        => new(TerraFXWindows.CreateCompatibleBitmap(context, size.Width, size.Height));

    public static void BitBlit(
        this in DeviceContext source,
        in DeviceContext destination,
        Point sourceOrigin,
        Rectangle destinationBounds,
        RasterOperation operation)
    {
        Error.ThrowLastErrorIfFalse(
            TerraFXWindows.BitBlt(
                destination,
                destinationBounds.X,
                destinationBounds.Y,
                destinationBounds.Width,
                destinationBounds.Height,
                source,
                sourceOrigin.X,
                sourceOrigin.Y,
                operation.Value));
    }

    public static StretchMode SetStretchBlitMode(this DeviceContext context, StretchMode mode)
    {
        StretchMode oldMode = (StretchMode)TerraFXWindows.SetStretchBltMode(context, (int)mode);
        if ((WindowsError)oldMode == WindowsError.ERROR_INVALID_PARAMETER)
            WindowsError.ERROR_INVALID_PARAMETER.Throw();
        return oldMode;
    }

    public static bool StretchBlit(
        this in DeviceContext source,
        in DeviceContext destination,
        Rectangle sourceBounds,
        Rectangle destinationBounds,
        RasterOperation operation)
    {
        return TerraFXWindows.StretchBlt(
            destination,
            destinationBounds.X,
            destinationBounds.Y,
            destinationBounds.Width,
            destinationBounds.Height,
            source,
            sourceBounds.X,
            sourceBounds.Y,
            sourceBounds.Width,
            sourceBounds.Height,
            operation.Value);
    }

    /// <summary>
    ///  Enumerate display device info for the given device name.
    /// </summary>
    /// <param name="deviceName">The device to enumerate or null for all devices.</param>
    public static IEnumerable<DisplayDevice> EnumerateDisplayDevices(string deviceName)
        => new DisplayDeviceEnumerable(deviceName);

    public static IEnumerable<DeviceMode> EnumerateDisplaySettings(string deviceName, uint modeIndex = 0)
        => new DisplaySettingsEnumerable(deviceName, modeIndex);

    /// <summary>
    ///  Selects the given object into the specified device context.
    /// </summary>
    /// <returns>The previous object or null if failed OR null if the given object was a region.</returns>
    public static GdiObjectHandle SelectObject(this in DeviceContext context, GdiObjectHandle @object)
    {
        HGDIOBJ handle = TerraFXWindows.SelectObject(context, @object);
        if (handle == HGDIOBJ.INVALID_VALUE)
            return default;

        ObjectType type = (ObjectType)TerraFXWindows.GetObjectType(@object);
        return type == ObjectType.Region ? default : new GdiObjectHandle(handle, ownsHandle: false);
    }

    public static bool UpdateWindow<T>(this T window) where T : IHandle<WindowHandle>
        => TerraFXWindows.UpdateWindow(window.Handle);

    public static unsafe bool ValidateRectangle(this in WindowHandle window, ref Rectangle rectangle)
    {
        Rect rect = rectangle;
        return TerraFXWindows.ValidateRect(window, (RECT*)&rect);
    }

    /// <summary>
    ///  Validates the entire Window.
    /// </summary>
    public static unsafe bool Validate(this in WindowHandle window)
        => TerraFXWindows.ValidateRect(window, null);

    /// <summary>
    ///  Calls BeginPaint and returns the created DeviceContext. Disposing the returned DeviceContext will call EndPaint.
    /// </summary>
    public static unsafe DeviceContext BeginPaint(this in WindowHandle window)
    {
        PAINTSTRUCT paintStruct = default;
        TerraFXWindows.BeginPaint(window, &paintStruct);
        return new DeviceContext(paintStruct, window);
    }

    /// <summary>
    ///  Calls BeginPaint and returns the created DeviceContext. Disposing the returned DeviceContext will call EndPaint.
    /// </summary>
    public static unsafe DeviceContext BeginPaint(this in WindowHandle window, out Rectangle paintRectangle)
    {
        PAINTSTRUCT paintStruct = default;
        TerraFXWindows.BeginPaint(window, &paintStruct);
        paintRectangle = paintStruct.rcPaint.ToRectangle();
        return new DeviceContext(paintStruct, window);
    }

    /// <summary>
    ///  Calls BeginPaint and returns the created DeviceContext. Disposing the returned DeviceContext will call EndPaint.
    /// </summary>
    public static unsafe DeviceContext BeginPaint(this in WindowHandle window, out PaintStruct paintStruct)
    {
        PAINTSTRUCT ps = default;
        TerraFXWindows.BeginPaint(window, &ps);
        paintStruct = ps;
        return new DeviceContext(ps, window);
    }

    public static unsafe bool InvalidateRectangle(this in WindowHandle window, Rectangle rectangle, bool erase)
    {
        Rect rect = rectangle;
        return TerraFXWindows.InvalidateRect(window, (RECT*)&rect, erase);
    }

    public static unsafe bool Invalidate(this in WindowHandle window, bool erase = true)
        => TerraFXWindows.InvalidateRect(window, null, erase);

    public static RegionHandle CreateEllipticRegion(Rectangle bounds)
        => new(TerraFXWindows.CreateEllipticRgn(bounds.Left, bounds.Top, bounds.Right, bounds.Bottom));

    public static RegionHandle CreateRectangleRegion(Rectangle rectangle)
        => new(TerraFXWindows.CreateRectRgn(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom));

    public static RegionType CombineRegion(
        this in RegionHandle destination,
        RegionHandle sourceOne,
        RegionHandle sourceTwo,
        CombineRegionMode mode)
        => (RegionType)TerraFXWindows.CombineRgn(destination, sourceOne, sourceTwo, (int)mode);

    public static RegionType SelectClippingRegion(this in DeviceContext context, RegionHandle region)
        => (RegionType)TerraFXWindows.SelectClipRgn(context, region);

    public static unsafe Rectangle GetClipBox(this in DeviceContext context, out RegionType regionType)
    {
        Rect rect;
        regionType = (RegionType)TerraFXWindows.GetClipBox(context, (RECT*)&rect);
        return rect;
    }

    public static RegionHandle GetClippingRegion(this in DeviceContext context, out bool hasRegion)
    {
        HRGN hrgn = TerraFXWindows.CreateRectRgn(0, 0, 0, 0);
        int result = TerraFXWindows.GetClipRgn(context, hrgn);
        hasRegion = result switch
        {
            0 => false,
            1 => true,
            _ => throw new WInteropIOException("Failed to get the clipping region")
        };

        return new RegionHandle(hrgn);
    }

    public static Point GetViewportOrigin(this in DeviceContext context)
        => GetViewportOrigin(context, out _);

    public static unsafe Point GetViewportOrigin(this in DeviceContext context, out bool success)
    {
        Point point;
        success = TerraFXWindows.GetViewportOrgEx(context, (POINT*)&point);
        return point;
    }

    public static unsafe bool SetViewportOrigin(this in DeviceContext context, Point point)
        => TerraFXWindows.SetViewportOrgEx(context, point.X, point.Y, null);

    public static Point GetWindowOrigin(this in DeviceContext context)
        => GetWindowOrigin(context, out _);

    public static unsafe Point GetWindowOrigin(this in DeviceContext context, out bool success)
    {
        Point point;
        success = TerraFXWindows.GetWindowOrgEx(context, (POINT*)&point);
        return point;
    }

    public static unsafe bool SetWindowOrigin(this in DeviceContext context, Point point)
        => TerraFXWindows.SetWindowOrgEx(context, point.X, point.Y, null);

    /// <summary>
    ///  Shared brush, handle doesn't need disposed.
    /// </summary>
    public static BrushHandle GetSystemColorBrush(SystemColor systemColor)
        => new(TerraFXWindows.GetSysColorBrush((int)systemColor), ownsHandle: false);

    public static Color GetBackgroundColor(this in DeviceContext context)
        => TerraFXWindows.GetBkColor(context).ToColor();

    public static Color GetBrushColor(this in DeviceContext context)
        => TerraFXWindows.GetDCBrushColor(context).ToColor();

    public static Color SetBackgroundColor(this in DeviceContext context, Color color)
        => TerraFXWindows.SetBkColor(context, color.ToCOLORREF()).ToColor();

    public static Color SetBackgroundColor(this in DeviceContext context, SystemColor color)
        => TerraFXWindows.SetBkColor(context, TerraFXWindows.GetSysColor((int)color)).ToColor();

    public static BackgroundMode SetBackgroundMode(this in DeviceContext context, BackgroundMode mode)
        => (BackgroundMode)TerraFXWindows.SetBkMode(context, (int)mode);

    public static BackgroundMode GetBackgroundMode(this in DeviceContext context)
        => (BackgroundMode)TerraFXWindows.GetBkMode(context);

    public static PenMixMode SetRasterOperation(this in DeviceContext context, PenMixMode foregroundMixMode)
        => (PenMixMode)TerraFXWindows.SetROP2(context, (int)foregroundMixMode);

    public static PenMixMode GetRasterOperation(this in DeviceContext context)
        => (PenMixMode)TerraFXWindows.GetROP2(context);

    public static unsafe bool ScreenToClient<T>(this T window, ref Point point) where T : IHandle<WindowHandle>
    {
        fixed (Point* p = &point)
        {
            return TerraFXWindows.ScreenToClient(window.Handle, (POINT*)p);
        }
    }

    public static unsafe bool ScreenToClient<T>(this T window, ref Rectangle rectangle) where T : IHandle<WindowHandle>
    {
        Point location = rectangle.Location;
        bool result = TerraFXWindows.ScreenToClient(window.Handle, (POINT*)&location);
        rectangle.Location = location;
        return result;
    }

    public static unsafe bool ClientToScreen(this in WindowHandle window, ref Point point)
    {
        fixed (Point* p = &point)
        {
            return TerraFXWindows.ClientToScreen(window, (POINT*)p);
        }
    }

    public static bool DeviceToLogical(this in DeviceContext context, params Point[] points)
        => DeviceToLogical(context, points.AsSpan());

    public static unsafe bool DeviceToLogical(this in DeviceContext context, ReadOnlySpan<Point> points)
    {
        fixed (Point* p = points)
        {
            return TerraFXWindows.DPtoLP(context, (POINT*)p, points.Length);
        }
    }

    public static unsafe bool LogicalToDevice(this in DeviceContext context, params Point[] points)
        => LogicalToDevice(context, points);

    public static unsafe bool LogicalToDevice(this in DeviceContext context, ReadOnlySpan<Point> points)
    {
        fixed (Point* p = points)
        {
            return TerraFXWindows.LPtoDP(context, (POINT*)p, points.Length);
        }
    }

    public static unsafe bool OffsetWindowOrigin(this in DeviceContext context, int x, int y)
        => TerraFXWindows.OffsetWindowOrgEx(context, x, y, null);

    public static unsafe bool OffsetViewportOrigin(this in DeviceContext context, int x, int y)
        => TerraFXWindows.OffsetViewportOrgEx(context, x, y, null);

    public static unsafe bool GetWindowExtents(this in DeviceContext context, out Size size)
    {
        fixed (Size* s = &size)
        {
            return TerraFXWindows.GetWindowExtEx(context, (SIZE*)s);
        }
    }

    /// <summary>
    ///  Sets the logical ("window") dimensions of the device context.
    /// </summary>
    public static unsafe bool SetWindowExtents(this in DeviceContext context, Size size)
        => TerraFXWindows.SetWindowExtEx(context, size.Width, size.Height, null);

    public static unsafe bool GetViewportExtents(this in DeviceContext context, out Size size)
    {
        fixed (Size* s = &size)
        {
            return TerraFXWindows.GetViewportExtEx(context, (SIZE*)s);
        }
    }

    public static unsafe bool SetViewportExtents(this in DeviceContext context, Size size)
        => TerraFXWindows.SetViewportExtEx(context, size.Width, size.Height, null);

    public static MappingMode GetMappingMode(this in DeviceContext context)
        => (MappingMode)TerraFXWindows.GetMapMode(context);

    public static MappingMode SetMappingMode(this in DeviceContext context, MappingMode mapMode)
        => (MappingMode)TerraFXWindows.SetMapMode(context, (int)mapMode);

    public static unsafe Rectangle GetBoundsRect(this in DeviceContext context, bool reset = false)
    {
        Rect rect;
        TerraFXWindows.GetBoundsRect(context, (RECT*)&rect, reset ? (uint)BoundsState.Reset : default);
        return rect;
    }

    public static unsafe Rectangle GetBoundsRect(
        this in DeviceContext context,
        out BoundsState state,
        bool reset = false)
    {
        Rect rect;
        state = (BoundsState)TerraFXWindows.GetBoundsRect(
            context,
            (RECT*)&rect,
            reset ? (uint)BoundsState.Reset : default);
        return rect;
    }

    public static unsafe Span<PaletteEntry> GetPaletteEntries(this in PaletteHandle palette)
    {
        uint count = TerraFXWindows.GetPaletteEntries(palette, 0, 0, null);

        if (count == 0)
        {
            return Span<PaletteEntry>.Empty;
        }

        PaletteEntry[] entries = new PaletteEntry[count];

        fixed (PaletteEntry* pe = entries)
        {
            count = TerraFXWindows.GetPaletteEntries(palette, 0, count, (PALETTEENTRY*)pe);
        }

        Debug.Assert(count == entries.Length);
        return new Span<PaletteEntry>(entries, 0, (int)count);
    }

    public static unsafe Span<PaletteEntry> GetSystemPaletteEntries(this in DeviceContext deviceContext)
    {
        uint count = TerraFXWindows.GetSystemPaletteEntries(deviceContext, 0, 0, null);

        if (count == 0)
            return Span<PaletteEntry>.Empty;

        PaletteEntry[] entries = new PaletteEntry[count];

        fixed (PaletteEntry* pe = entries)
        {
            count = TerraFXWindows.GetSystemPaletteEntries(deviceContext, 0, count, (PALETTEENTRY*)pe);
        }

        Debug.Assert(count == entries.Length);
        return new Span<PaletteEntry>(entries, 0, (int)count);
    }

    /// <summary>
    ///  Sets the graphics mode for the given device context.
    /// </summary>
    /// <remarks>
    ///  You cannot set the mode to <see cref="GraphicsMode.Compatible"/> if the device context currently
    ///  has a non-identity transform.
    /// </remarks>
    public static GraphicsMode SetGraphicsMode(this in DeviceContext deviceContext, GraphicsMode graphicsMode)
        => (GraphicsMode)TerraFXWindows.SetGraphicsMode(deviceContext, (int)graphicsMode);

    public static GraphicsMode GetGraphicsMode(this in DeviceContext deviceContext)
        => (GraphicsMode)TerraFXWindows.GetGraphicsMode(deviceContext);

    /// <summary>
    ///  Set the transform for the given device context.
    /// </summary>
    /// <returns>
    ///  True if successful. SetWorldTransform doesn't set last error unless you try to pass a handle
    ///  that isn't a device context. The other failure case is that the graphics mode isn't set to
    ///  advanced.
    /// </returns>
    public static unsafe bool SetWorldTransform(this in DeviceContext deviceContext, ref Matrix3x2 transform)
    {
        fixed (Matrix3x2* t = &transform)
        {
            return TerraFXWindows.SetWorldTransform(deviceContext, (XFORM*)t);
        }
    }

    public static unsafe bool GetWorldTransform(this in DeviceContext deviceContext, out Matrix3x2 transform)
    {
        fixed (Matrix3x2* t = &transform)
        {
            return TerraFXWindows.GetWorldTransform(deviceContext, (XFORM*)t);
        }
    }
}


text:
module.exports = function (sequelize, DataTypes) {
  return sequelize.define('Building', {
    id: { type: DataTypes.STRING(100), primaryKey: true, unique: true },
    name: { type: DataTypes.STRING(255), allowNull: true, comment: '楼盘名称' },
    address: { type: DataTypes.STRING(255), allowNull: true, comment: '地址' },
    priority: { type: DataTypes.BIGINT(11), allowNull: true, comment: '排序' },
    provinceId: { type: DataTypes.BIGINT(11), allowNull: true, comment: '所属省' },
    cityId: { type: DataTypes.BIGINT(11), allowNull: true, comment: '所属市' },
    countyId: { type: DataTypes.BIGINT(11), allowNull: true, comment: '所属区' }
  },
    {
      timestamps: true,
      underscored: true,
      paranoid: true,
      freezeTableName: true,
      tableName: 'building',
      charset: 'utf8',
      collate: 'utf8_general_ci'
    });
}