text:
package org.pac4j.scribe.model;

import com.github.scribejava.core.model.OAuth2AccessToken;

/**
 * Weibo token extra.
 *
More info at: Oauth2/access token

 *
 * @author zhangzhenli
 * @since 3.1.0
 */
public class WeiboToken extends OAuth2AccessToken {

    private static final long serialVersionUID = 1489916603771001585L;
    private String uid;

    public WeiboToken(OAuth2AccessToken accessToken, String uid) {
        super(accessToken.getAccessToken(), accessToken.getTokenType(), accessToken.getExpiresIn(),
            accessToken.getRefreshToken(), accessToken.getScope(),
            accessToken.getRawResponse());
        this.uid = uid;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof WeiboToken)) return false;
        if (!super.equals(o)) return false;

        WeiboToken that = (WeiboToken) o;

        return uid != null ? uid.equals(that.uid) : that.uid == null;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (uid != null ? uid.hashCode() : 0);
        return result;
    }
}


text:
layout: page
title: Base Spring International Award Ceremony
date: 2016-05-24
author: Mary Rodgers
tags: weekly links, java
status: published
summary: Nulla consequat, lectus vitae aliquet.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 07/09/2016
  endDate: 07/12/2016
  ctyhocn: ATLNLHX
  groupCode: BSIAC
published: true
---
Suspendisse id lectus lectus. Sed at lacus in lacus congue tincidunt. Nulla aliquet sagittis faucibus. Suspendisse consequat, nisi ac lacinia aliquet, ligula diam porttitor mi, ut varius ex ante at turpis. Sed dictum arcu eget elit elementum semper. Vestibulum elementum ultrices mi at ultrices. Donec vel tellus dolor. Donec vitae justo pulvinar, bibendum mi vitae, rhoncus mi. Vestibulum dapibus, turpis eu efficitur lobortis, dui quam semper nunc, et consectetur leo purus quis dui. Vivamus interdum facilisis euismod.
Suspendisse ornare dolor nec posuere molestie. Sed sit amet imperdiet lectus. Fusce vel urna vitae justo varius rhoncus. Nunc nisi sem, vestibulum maximus egestas non, aliquam sit amet orci. Duis euismod viverra tellus. Integer a risus at mi eleifend mollis ut ac ante. Ut viverra vestibulum efficitur. Aenean justo quam, gravida id fermentum ut, feugiat ac metus. Aliquam erat volutpat. Fusce mattis turpis id erat vulputate, non posuere justo gravida. Quisque tortor tortor, dictum non lectus bibendum, hendrerit egestas nisi. Quisque auctor laoreet lorem, eget tristique leo sagittis sit amet. Nam et urna sit amet sapien finibus ullamcorper.

1 Donec efficitur odio ac justo suscipit ultrices
1 Maecenas non nibh vel ante faucibus fermentum
1 Cras vel erat ultrices, consequat erat vel, rutrum dolor
1 Sed elementum odio in orci porttitor, quis pretium orci porta.

Morbi lectus magna, mattis vitae sem vel, lobortis lobortis ipsum. Proin vestibulum feugiat purus, ut vulputate magna varius vitae. Integer malesuada nunc ac aliquam auctor. Duis commodo, mi vitae dictum blandit, lorem turpis fermentum quam, vitae euismod nisl elit id dolor. Donec id efficitur lorem. Aliquam placerat tempor lectus sed sollicitudin. Sed eleifend dignissim consequat. Sed posuere maximus neque, quis pellentesque sapien tempus a. Quisque porta magna sed urna volutpat hendrerit. Morbi dignissim nibh vel ultricies convallis.

redpajama_set_name: RedPajamaGithub


text:
/* tslint:disable */
/* eslint-disable */

import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ViewInRoomArtwork_artwork = {
    readonly widthCm: number | null;
    readonly heightCm: number | null;
    readonly image: {
        readonly resized: {
            readonly src: string;
            readonly srcSet: string;
            readonly width: number | null;
            readonly height: number | null;
        } | null;
    } | null;
    readonly " $refType": "ViewInRoomArtwork_artwork";
};
export type ViewInRoomArtwork_artwork$data = ViewInRoomArtwork_artwork;
export type ViewInRoomArtwork_artwork$key = {
    readonly " $data"?: ViewInRoomArtwork_artwork$data;
    readonly " $fragmentRefs": FragmentRefs<"ViewInRoomArtwork_artwork">;
};

const node: ReaderFragment = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "ViewInRoomArtwork_artwork",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "widthCm",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "heightCm",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "concreteType": "Image",
      "kind": "LinkedField",
      "name": "image",
      "plural": false,
      "selections": [
        {
          "alias": null,
          "args": [
            {
              "kind": "Literal",
              "name": "height",
              "value": 800
            },
            {
              "kind": "Literal",
              "name": "version",
              "value": [
                "normalized",
                "larger",
                "large"
              ]
            },
            {
              "kind": "Literal",
              "name": "width",
              "value": 800
            }
          ],
          "concreteType": "ResizedImageUrl",
          "kind": "LinkedField",
          "name": "resized",
          "plural": false,
          "selections": [
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "src",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "srcSet",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "width",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "height",
              "storageKey": null
            }
          ],
          "storageKey": "resized(height:800,version:[\"normalized\",\"larger\",\"large\"],width:800)"
        }
      ],
      "storageKey": null
    }
  ],
  "type": "Artwork"
};
(node as any).hash = 'bc5464f76e87fec45a2755a5c070c322';
export default node;


text:
.class Lcom/google/common/collect/Multimaps$MapMultimap$1$1;
.super Ljava/lang/Object;
.source "Multimaps.java"

# interfaces
.implements Ljava/util/Iterator;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/google/common/collect/Multimaps$MapMultimap$1;->iterator()Ljava/util/Iterator;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Ljava/util/Iterator",
        "<TV;>;"
    }
.end annotation

# instance fields
.field i:I

.field final synthetic this$1:Lcom/google/common/collect/Multimaps$MapMultimap$1;

# direct methods
.method constructor <init>(Lcom/google/common/collect/Multimaps$MapMultimap$1;)V
    .locals 0

    .prologue
    .line 1009
    .local p0, "this":Lcom/google/common/collect/Multimaps$MapMultimap$1$1;, "Lcom/google/common/collect/Multimaps$MapMultimap$1.1;"
    iput-object p1, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->this$1:Lcom/google/common/collect/Multimaps$MapMultimap$1;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public hasNext()Z
    .locals 2

    .prologue
    .line 1014
    .local p0, "this":Lcom/google/common/collect/Multimaps$MapMultimap$1$1;, "Lcom/google/common/collect/Multimaps$MapMultimap$1.1;"
    iget v0, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->i:I

    if-nez v0, :cond_0

    iget-object v0, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->this$1:Lcom/google/common/collect/Multimaps$MapMultimap$1;

    iget-object v0, v0, Lcom/google/common/collect/Multimaps$MapMultimap$1;->this$0:Lcom/google/common/collect/Multimaps$MapMultimap;

    iget-object v0, v0, Lcom/google/common/collect/Multimaps$MapMultimap;->map:Ljava/util/Map;

    iget-object v1, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->this$1:Lcom/google/common/collect/Multimaps$MapMultimap$1;

    iget-object v1, v1, Lcom/google/common/collect/Multimaps$MapMultimap$1;->val$key:Ljava/lang/Object;

    invoke-interface {v0, v1}, Ljava/util/Map;->containsKey(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public next()Ljava/lang/Object;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TV;"
        }
    .end annotation

    .prologue
    .line 1019
    .local p0, "this":Lcom/google/common/collect/Multimaps$MapMultimap$1$1;, "Lcom/google/common/collect/Multimaps$MapMultimap$1.1;"
    invoke-virtual {p0}, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->hasNext()Z

    move-result v0

    if-nez v0, :cond_0

    .line 1020
    new-instance v0, Ljava/util/NoSuchElementException;

    invoke-direct {v0}, Ljava/util/NoSuchElementException;-><init>()V

    throw v0

    .line 1022
    :cond_0
    iget v0, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->i:I

    add-int/lit8 v0, v0, 0x1

    iput v0, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->i:I

    .line 1023
    iget-object v0, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->this$1:Lcom/google/common/collect/Multimaps$MapMultimap$1;

    iget-object v0, v0, Lcom/google/common/collect/Multimaps$MapMultimap$1;->this$0:Lcom/google/common/collect/Multimaps$MapMultimap;

    iget-object v0, v0, Lcom/google/common/collect/Multimaps$MapMultimap;->map:Ljava/util/Map;

    iget-object v1, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->this$1:Lcom/google/common/collect/Multimaps$MapMultimap$1;

    iget-object v1, v1, Lcom/google/common/collect/Multimaps$MapMultimap$1;->val$key:Ljava/lang/Object;

    invoke-interface {v0, v1}, Ljava/util/Map;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method public remove()V
    .locals 2

    .prologue
    .local p0, "this":Lcom/google/common/collect/Multimaps$MapMultimap$1$1;, "Lcom/google/common/collect/Multimaps$MapMultimap$1.1;"
    const/4 v0, 0x1

    .line 1028
    iget v1, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->i:I

    if-ne v1, v0, :cond_0

    :goto_0
    invoke-static {v0}, Lcom/google/common/base/Preconditions;->checkState(Z)V

    .line 1029
    const/4 v0, -0x1

    iput v0, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->i:I

    .line 1030
    iget-object v0, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->this$1:Lcom/google/common/collect/Multimaps$MapMultimap$1;

    iget-object v0, v0, Lcom/google/common/collect/Multimaps$MapMultimap$1;->this$0:Lcom/google/common/collect/Multimaps$MapMultimap;

    iget-object v0, v0, Lcom/google/common/collect/Multimaps$MapMultimap;->map:Ljava/util/Map;

    iget-object v1, p0, Lcom/google/common/collect/Multimaps$MapMultimap$1$1;->this$1:Lcom/google/common/collect/Multimaps$MapMultimap$1;

    iget-object v1, v1, Lcom/google/common/collect/Multimaps$MapMultimap$1;->val$key:Ljava/lang/Object;

    invoke-interface {v0, v1}, Ljava/util/Map;->remove(Ljava/lang/Object;)Ljava/lang/Object;

    .line 1031
    return-void

    .line 1028
    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {DefaultUpdater, UpdateOptions} from '../default';
import {logger as defaultLogger, Logger} from '../../util/logger';

const INLINE_UPDATE_REGEX = /{x-version-update:([\w\-_]+):(current|released)}/;
const BLOCK_START_REGEX =
  /{x-version-update-start:([\w\-_]+):(current|released)}/;
const BLOCK_END_REGEX = /{x-version-update-end}/;
const VERSION_REGEX = /\d+\.\d+\.\d+(-\w+(\.\d+)?)?(-SNAPSHOT)?/;

interface JavaUpdateOptions extends UpdateOptions {
  isSnapshot?: boolean;
}

/**
 * Updates a file annotated with region markers. These region markers are
 * either denoted inline with `{x-version-update:<component-name>:current|released}`
 * or with a `{x-version-update-start:<component-name>}` and `{x-version-update-end}`.
 */
export class JavaUpdate extends DefaultUpdater {
  isSnapshot: boolean;
  constructor(options: JavaUpdateOptions) {
    super(options);
    this.isSnapshot = !!options.isSnapshot;
  }
  /**
   * Given initial file contents, return updated contents.
   * @param {string} content The initial content
   * @returns {string} The updated content
   */
  updateContent(content: string, logger: Logger = defaultLogger): string {
    if (!this.versionsMap) {
      logger.warn('missing versions map');
      return content;
    }
    const newLines: string[] = [];
    let blockPackageName: string | null = null;
    content.split(/\r?\n/).forEach(line => {
      let match = line.match(INLINE_UPDATE_REGEX);
      if (match && (!this.isSnapshot || match[2] === 'current')) {
        const newVersion = this.versionsMap!.get(match[1]);
        if (newVersion) {
          newLines.push(line.replace(VERSION_REGEX, newVersion.toString()));
        } else {
          newLines.push(line);
        }
      } else if (blockPackageName) {
        const newVersion = this.versionsMap!.get(blockPackageName);
        if (newVersion) {
          newLines.push(line.replace(VERSION_REGEX, newVersion.toString()));
        } else {
          newLines.push(line);
        }
        if (line.match(BLOCK_END_REGEX)) {
          blockPackageName = null;
        }
      } else {
        match = line.match(BLOCK_START_REGEX);
        if (match && (!this.isSnapshot || match[2] === 'current')) {
          blockPackageName = match[1];
        }
        newLines.push(line);
      }
    });
    return newLines.join('\n');
  }
}


text:
import os
import re
import math
import string
import hashlib
from collections import Counter

from viper.common.abstracts import Module
from viper.core.session import __sessions__

try:
    from bs4 import BeautifulSoup
    HAVE_BS4 = True
except ImportError:
    HAVE_BS4 = False

class HTMLParse(Module):
    cmd = 'html'
    description = 'Parse html files and extract content'
    authors = ['Kevin Breen', 'nex']

    def __init__(self):
        super(HTMLParse, self).__init__()
        self.parser.add_argument('-s', '--script', action='store_true', help='Extract all script tags')
        self.parser.add_argument('-l', '--links', action='store_true', help='Show all links')
        self.parser.add_argument('-f', '--iframe', action='store_true', help='Show all iframes')
        self.parser.add_argument('-e', '--embed', action='store_true', help='Show all embedded files')
        self.parser.add_argument('-i', '--images', action='store_true', help='Extract all images')
        self.parser.add_argument('-d', '--dump', metavar='dump_path', help='Dump all outputs to files. This option is availiable for iframes scripts and images, if you use it with images an http request will be executed to fetch each image')
        self.soup = None

    def string_clean(self, value):
        try:
            value = filter(lambda x: x in string.printable, value)
            return re.sub('[\n\t\r]', '', value)
        except:
            return value

    def shannon_entropy(self, s):
        s = str(s)
        p, lns = Counter(s), float(len(s))
        return -sum(count / lns * math.log(count / lns, 2) for count in p.values())

    def dump_output(self, stream, out_dir, out_type):
        stream = str(stream)
        # TODO: Change this to a folder per type.
        md5 = hashlib.md5(stream).hexdigest()

        out_name = "HTML_{0}_{1}".format(md5, out_type)
        out_path = os.path.join(out_dir, out_name)

        with open(out_path, 'w') as out:
            out.write(stream)

    def parse_scripts(self):
        scripts = []
        script_content = []
        for script in self.soup.find_all('script'):
            script_type = script.get('type')
            script_src = script.get('src')
            content = script.string
            script_content.append(content)
            script_entropy = self.shannon_entropy(script_content)
            scripts.append([
                script_type,
                script_src,
                script_entropy
            ])

        return scripts, script_content

    def parse_hrefs(self):
        links = []
        for link in self.soup.find_all('a'):
            url = link.get('href')
            text = link.string
            links.append([url, text])

        return links

    def parse_iframes(self):
        # TODO: soup the iframe contents and look for hrefs.
        iframes = []
        frame_content = []
        for frame in self.soup.find_all('iframe'):
            src = frame.get('src')
            content = frame
            entropy = self.shannon_entropy(content)
            size = "{0}x{1}".format(frame.get('width'), frame.get('height'))
            # Because None can be misleading when no width or height is specified for the ifame
            size = size.replace('NonexNone', 'Not Specified')
            iframes.append([src, size, entropy])
            frame_content.append(content)
        return iframes, frame_content

    def parse_embedded(self):
        # Java Applets
        java = []
        flash = []
        for applet in self.soup.find_all('applet'):
            archive = applet.get('archive')
            code = applet.get('code')
            java.append([archive, code])
        # flash
        for embed in self.soup.find_all('embed'):
            src = embed.get('src')
            flash.append([src])
        for obj in self.soup.find_all('object'):
            data = obj.get('data')
            flash.append([data])
        return java, flash

    def parse_images(self):
        images = []
        for image in self.soup.find_all('img'):
            img_src = image.get('src')
            img_alt = image.get('alt')
            images.append([img_src, img_alt])
        return images

    def run(self):
        super(HTMLParse, self).run()
        if self.args is None:
            return

        if not __sessions__.is_set():
            self.log('error', "No session opened")
            return

        try:
            html_data = open(__sessions__.current.file.path).read()
            self.soup = BeautifulSoup(html_data)
        except Exception as e:
            self.log('error', "Something went wrong: {0}".format(e))
            return

        # Set dump path, none if not set.
        arg_dump = self.args.dump

        if self.args.script:

            scripts, script_content = self.parse_scripts()
            if arg_dump:
                self.log('info', "Dumping Output to {0}".format(arg_dump))
                for s in script_content:
                    self.dump_output(s, arg_dump, 'Scripts')
            else:
                self.log('info', "Scripts:")
                self.log('table', dict(header=['Type', 'Source', 'Entropy'], rows=scripts))

        elif self.args.links:
                links = self.parse_hrefs()
                self.log('info', "Links")
                self.log('info', "Target \t Text")
                for link in links:
                    self.log('item', "{0}\t {1}".format(link[0], self.string_clean(link[1])))
        # iFrames
        elif self.args.iframe:
            frames, frame_content = self.parse_iframes()
            if arg_dump:
                self.log('info', "Dumping Output to {0}".format(arg_dump))
                for f in frame_content:
                    self.dump_output(f, arg_dump, 'iframe')
            else:
                self.log('info', "IFrames")
                self.log('table', dict(header=['Source', 'Size', 'Entropy'], rows=frames))

        # Images
        elif self.args.images:
            images = self.parse_images()
            if arg_dump:
                self.log('info', "Dumping Images to {0}".format(arg_dump))
                self.log('error', "Not Implemented Yet")
                # this will need an extra http request to download the images
            else:
                self.log('info', "Images")
                self.log('table', dict(header=['Source', 'Alt', ], rows=images))

        # Embedded
        elif self.args.embed:
            java, flash = self.parse_embedded()
            if arg_dump:
                self.log('info', "Dumping Embedded Items to {0}".format(arg_dump))
                self.log('error', "Not Implemented Yet")
                # this will need an extra http request to download the images
            else:
                if len(java) > 0:
                    self.log('info', "Embedded Java Objects")
                    self.log('table', dict(header=['Archive', 'Code', ], rows=java))
                    print ""
                if len(flash) > 0:
                    self.log('info', "Embedded Flash Objects")
                    self.log('table', dict(header=['Swf Src'], rows=flash))
        else:
            self.log('error', 'At least one of the parameters is required')
            self.usage()


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.learn.api</groupId>
    <artifactId>api-service</artifactId>
	<packaging>jar</packaging>
	<name>api-service</name>
	<version>0.1</version>
	<url>http://maven.apache.org</url>

	<parent>
		<groupId>com.learn</groupId>
		<artifactId>learn</artifactId>
		<version>0.1</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.github.ulisesbocchio</groupId>
			<artifactId>jasypt-spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-crypto</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

	</dependencies>

</project>


text:
window.eu_dusse_vaadin_waypoints_StickyExtensionImpl = function() {

	// extension connector
	var connector = this;

	// id of extended connector
	var parentConnectorId = connector.getParentId();

	// element of extended connector
	var element = connector.getElement(parentConnectorId);

	// TODO does not work!

	var sticky = new Waypoint.Sticky({
		element : element,
		direction : connector.getState().direction,
		stuckClass : connector.getState().stuckClass,
		wrapper : connector.getState().wrapper
	});

	this.destroy = function() {
		sticky.destroy();
	}

}


text:
Out of the box, Lagom will use JSON for request and response message format for the external API of the service, using Jackson to serialize and deserialize messages. The messages that are sent within the cluster of the service must also be serializable and so must the events that are stored by [[Persistent Entities|PersistentEntity]]. We recommend JSON for these as well and Lagom makes it easy to add Jackson serialization support to such classes.

Do not depend on Java serialization for production deployments. It is inefficient both in serialization size and speed. It is very difficult to evolve the classes when using Java serialization, which is especially important for the persistent state and events, since you must be able to deserialize old objects that were stored.

## Enabling JSON Serialization

To enable JSON serialization for a class you need to implement the [Jsonable](api/index.html?com/lightbend/lagom/serialization/Jsonable.html) marker interface.

@[jsonable](code/docs/home/serialization/AbstractUser.java)

Note that we're using the [[Immutables|Immutable]] library here, so this will generate an immutable `User` class. This is the reason for adding the `@JsonDeserialize` annotation.

### Jackson Modules

The enabled Jackson modules are listed in the [Akka documentation](https://doc.akka.io/docs/akka/2.6/serialization-jackson.html#jackson-modules), and additionally following Jackson modules are enabled by default:

@[jackson-modules](../../../../../jackson/src/main/resources/reference.conf)

You can amend the configuration `akka.serialization.jackson.jackson-modules` to enable other modules.

The [ParameterNamesModule](https://github.com/FasterXML/jackson-modules-java8/tree/master/parameter-names) requires that the `-parameters` Java compiler option is enabled.

The section [[Immutable Objects|Immutable]] contains more examples of classes that are `Jsonable`.

You can use the [PersistentEntityTestDriver](api/index.html?com/lightbend/lagom/javadsl/testkit/PersistentEntityTestDriver.html) that is described in the [[Persistent Entity Unit Testing|PersistentEntity#Unit-Testing]] section to verify that all commands, events, replies and state are serializable.

### Compression

Compression, as described here, is only used for persistent events, persistent snapshots and remote messages with the service cluster. It is not used for messages that are serialized in the external API of the service.

JSON can be rather verbose and for large messages it can be beneficial to enable compression. That is done by using the [CompressedJsonable](api/index.html?com/lightbend/lagom/serialization/CompressedJsonable.html) instead of the `Jsonable` marker interface.

@[compressed-jsonable](code/docs/home/serialization/AbstractAuthor.java)

The serializer will by default only compress messages that are larger than 32 Kb. This threshold can be changed with configuration property `akka.serialization.jackson.jackson-json-gzip.compress-larger-than`.

## Schema Evolution

When working on long running projects using [[Persistence|PersistentEntity]], or any kind of Event Sourcing, schema evolution becomes an important aspects of developing your application. The requirements as well as our own understanding of the business domain may (and will) change over time.

Lagom provides a way to perform transformations of the JSON tree model during deserialization.

We will look at a few scenarios of how the classes may be evolved.

### Remove Field

Removing a field can be done without any migration code. The Jackson JSON serializer will ignore properties that does not exist in the class.

### Add Field

Adding an optional field can be done without any migration code. The default value will be `Optional.empty`.

Old class:

@[add-optional](code/docs/home/serialization/v1/AbstractItemAdded.java)

New class with a new optional `discount` property and a new `note` field with default value:

@[add-optional](code/docs/home/serialization/v2a/AbstractItemAdded.java)

Let's say we want to have a mandatory `discount` property without default value instead:

@[add-mandatory](code/docs/home/serialization/v2b/AbstractItemAdded.java)

To add a new mandatory field we have to use a JSON migration class and set the default value in the migration code, which extends the `JacksonMigration`.

This is how a migration class would look like for adding a `discount` field:

@[add](code/docs/home/serialization/v2b/ItemAddedMigration.java)

Override the `currentVersion` method to define the version number of the current (latest) version. The first version, when no migration was used, is always 1. Increase this version number whenever you perform a change that is not backwards compatible without migration code.

Implement the transformation of the old JSON structure to the new JSON structure in the `transform` method. The [JsonNode](https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/JsonNode.html) is mutable so you can add and remove fields, or change values. Note that you have to cast to specific sub-classes such as [ObjectNode](https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/node/ObjectNode.html) and [ArrayNode](https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/node/ArrayNode.html) to get access to mutators.

The migration class must be defined in configuration file:

    akka.serialization.jackson.migrations {
      "com.myservice.event.ItemAdded" = "com.myservice.event.ItemAddedMigration"
    }

### Rename Field

Let's say that we want to rename the `productId` field to `itemId` in the previous example.

@[rename](code/docs/home/serialization/v2c/AbstractItemAdded.java)

The migration code would look like:

@[rename](code/docs/home/serialization/v2c/ItemAddedMigration.java)

### Structural Changes

In a similar way we can do arbitrary structural changes.

Old class:

@[structural](code/docs/home/serialization/v1/AbstractCustomer.java)

New class:

@[structural](code/docs/home/serialization/v2a/AbstractCustomer.java)

with the `Address` class:

@[structural](code/docs/home/serialization/v2a/AbstractAddress.java)

The migration code would look like:

@[structural](code/docs/home/serialization/v2a/CustomerMigration.java)

### Rename Class

It is also possible to rename the class. For example, let's rename `OrderAdded` to `OrderPlaced`.

Old class:

@[rename-class](code/docs/home/serialization/v1/AbstractOrderAdded.java)

New class:

@[rename-class](code/docs/home/serialization/v2d/AbstractOrderPlaced.java)

The migration code would look like:

@[rename-class](code/docs/home/serialization/v2d/OrderPlacedMigration.java)

Note the override of the `transformClassName` method to define the new class name.

That type of migration must be configured with the old class name as key. The actual class can be removed.

    akka.serialization.jackson.migrations {
      "com.myservice.event.OrderAdded" = "com.myservice.event.OrderPlacedMigration"
    }


text:
module ShopifyClient
  VERSION = "0.0.1"
end


text:
namespace ash {

// static
OobeConfiguration* OobeConfiguration::instance = nullptr;
bool OobeConfiguration::skip_check_for_testing_ = false;

OobeConfiguration::OobeConfiguration() : check_completed_(false) {
  DCHECK(!OobeConfiguration::Get());
  OobeConfiguration::instance = this;
}

OobeConfiguration::~OobeConfiguration() {
  DCHECK_EQ(instance, this);
  OobeConfiguration::instance = nullptr;
}

// static
OobeConfiguration* OobeConfiguration::Get() {
  return OobeConfiguration::instance;
}

void OobeConfiguration::AddAndFireObserver(Observer* observer) {
  observer_list_.AddObserver(observer);
  if (check_completed_) {
    observer->OnOobeConfigurationChanged();
  }
}

void OobeConfiguration::RemoveObserver(Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

bool OobeConfiguration::CheckCompleted() const {
  return check_completed_;
}

void OobeConfiguration::ResetConfiguration() {
  configuration_ = base::Value::Dict();
  if (check_completed_) {
    NotifyObservers();
  }
}

void OobeConfiguration::CheckConfiguration() {
  if (skip_check_for_testing_)
    return;
  OobeConfigurationClient::Get()->CheckForOobeConfiguration(base::BindOnce(
      &OobeConfiguration::OnConfigurationCheck, weak_factory_.GetWeakPtr()));
}

void OobeConfiguration::OnConfigurationCheck(bool has_configuration,
                                             const std::string& configuration) {
  check_completed_ = true;
  if (!has_configuration) {
    NotifyObservers();
    return;
  }

  auto parsed_json = base::JSONReader::ReadAndReturnValueWithError(
      configuration,
      base::JSON_PARSE_CHROMIUM_EXTENSIONS | base::JSON_ALLOW_TRAILING_COMMAS);
  if (!parsed_json.has_value()) {
    LOG(ERROR) << "Error parsing OOBE configuration: "
               << parsed_json.error().message;
  } else if (!parsed_json->is_dict()) {
    LOG(ERROR) << "Configuration should be a dictionary";
  } else if (!configuration::ValidateConfiguration(parsed_json->GetDict())) {
    LOG(ERROR) << "Invalid OOBE configuration";
  } else {
    configuration_ = std::move(parsed_json->GetDict());
    UpdateConfigurationValues();
  }
  NotifyObservers();
}

void OobeConfiguration::UpdateConfigurationValues() {
  auto* ime_value = configuration_.FindString(configuration::kInputMethod);
  if (ime_value) {
    auto* imm = input_method::InputMethodManager::Get();
    configuration_.Set(
        configuration::kInputMethod,
        imm->GetInputMethodUtil()->MigrateInputMethod(*ime_value));
  }
}

void OobeConfiguration::NotifyObservers() {
  for (auto& observer : observer_list_)
    observer.OnOobeConfigurationChanged();
}

}  // namespace ash


text:
namespace Microsoft.Azure.Management.Logic.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The Edifact agreement framing settings.
    /// </summary>
    public partial class EdifactFramingSettings
    {
        /// <summary>
        /// Initializes a new instance of the EdifactFramingSettings class.
        /// </summary>
        public EdifactFramingSettings()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the EdifactFramingSettings class.
        /// </summary>
        /// <param name="protocolVersion">The protocol version.</param>
        /// <param name="dataElementSeparator">The data element
        /// separator.</param>
        /// <param name="componentSeparator">The component separator.</param>
        /// <param name="segmentTerminator">The segment terminator.</param>
        /// <param name="releaseIndicator">The release indicator.</param>
        /// <param name="repetitionSeparator">The repetition separator.</param>
        /// <param name="characterSet">The EDIFACT frame setting characterSet.
        /// Possible values include: 'NotSpecified', 'UNOB', 'UNOA', 'UNOC',
        /// 'UNOD', 'UNOE', 'UNOF', 'UNOG', 'UNOH', 'UNOI', 'UNOJ', 'UNOK',
        /// 'UNOX', 'UNOY', 'KECA'</param>
        /// <param name="decimalPointIndicator">The EDIFACT frame setting
        /// decimal indicator. Possible values include: 'NotSpecified',
        /// 'Comma', 'Decimal'</param>
        /// <param name="segmentTerminatorSuffix">The EDIFACT frame setting
        /// segment terminator suffix. Possible values include: 'NotSpecified',
        /// 'None', 'CR', 'LF', 'CRLF'</param>
        /// <param name="serviceCodeListDirectoryVersion">The service code list
        /// directory version.</param>
        /// <param name="characterEncoding">The character encoding.</param>
        public EdifactFramingSettings(int protocolVersion, int dataElementSeparator, int componentSeparator, int segmentTerminator, int releaseIndicator, int repetitionSeparator, string characterSet, EdifactDecimalIndicator decimalPointIndicator, SegmentTerminatorSuffix segmentTerminatorSuffix, string serviceCodeListDirectoryVersion = default(string), string characterEncoding = default(string))
        {
            ServiceCodeListDirectoryVersion = serviceCodeListDirectoryVersion;
            CharacterEncoding = characterEncoding;
            ProtocolVersion = protocolVersion;
            DataElementSeparator = dataElementSeparator;
            ComponentSeparator = componentSeparator;
            SegmentTerminator = segmentTerminator;
            ReleaseIndicator = releaseIndicator;
            RepetitionSeparator = repetitionSeparator;
            CharacterSet = characterSet;
            DecimalPointIndicator = decimalPointIndicator;
            SegmentTerminatorSuffix = segmentTerminatorSuffix;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the service code list directory version.
        /// </summary>
        [JsonProperty(PropertyName = "serviceCodeListDirectoryVersion")]
        public string ServiceCodeListDirectoryVersion { get; set; }

        /// <summary>
        /// Gets or sets the character encoding.
        /// </summary>
        [JsonProperty(PropertyName = "characterEncoding")]
        public string CharacterEncoding { get; set; }

        /// <summary>
        /// Gets or sets the protocol version.
        /// </summary>
        [JsonProperty(PropertyName = "protocolVersion")]
        public int ProtocolVersion { get; set; }

        /// <summary>
        /// Gets or sets the data element separator.
        /// </summary>
        [JsonProperty(PropertyName = "dataElementSeparator")]
        public int DataElementSeparator { get; set; }

        /// <summary>
        /// Gets or sets the component separator.
        /// </summary>
        [JsonProperty(PropertyName = "componentSeparator")]
        public int ComponentSeparator { get; set; }

        /// <summary>
        /// Gets or sets the segment terminator.
        /// </summary>
        [JsonProperty(PropertyName = "segmentTerminator")]
        public int SegmentTerminator { get; set; }

        /// <summary>
        /// Gets or sets the release indicator.
        /// </summary>
        [JsonProperty(PropertyName = "releaseIndicator")]
        public int ReleaseIndicator { get; set; }

        /// <summary>
        /// Gets or sets the repetition separator.
        /// </summary>
        [JsonProperty(PropertyName = "repetitionSeparator")]
        public int RepetitionSeparator { get; set; }

        /// <summary>
        /// Gets or sets the EDIFACT frame setting characterSet. Possible
        /// values include: 'NotSpecified', 'UNOB', 'UNOA', 'UNOC', 'UNOD',
        /// 'UNOE', 'UNOF', 'UNOG', 'UNOH', 'UNOI', 'UNOJ', 'UNOK', 'UNOX',
        /// 'UNOY', 'KECA'
        /// </summary>
        [JsonProperty(PropertyName = "characterSet")]
        public string CharacterSet { get; set; }

        /// <summary>
        /// Gets or sets the EDIFACT frame setting decimal indicator. Possible
        /// values include: 'NotSpecified', 'Comma', 'Decimal'
        /// </summary>
        [JsonProperty(PropertyName = "decimalPointIndicator")]
        public EdifactDecimalIndicator DecimalPointIndicator { get; set; }

        /// <summary>
        /// Gets or sets the EDIFACT frame setting segment terminator suffix.
        /// Possible values include: 'NotSpecified', 'None', 'CR', 'LF', 'CRLF'
        /// </summary>
        [JsonProperty(PropertyName = "segmentTerminatorSuffix")]
        public SegmentTerminatorSuffix SegmentTerminatorSuffix { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (CharacterSet == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "CharacterSet");
            }
        }
    }
}


text:
cBarBar
=======

A developmental boss bar API which bypasses the new frustum checks using simple methods.

### Requires

* [ProtocolLib](http://assets.comphenix.net/job/ProtocolLib%20-%20Spigot%20Compatible%201.8/)
* [PacketWrapper](http://assets.comphenix.net/job/PacketWrapper/)


text:
package com.linkedin.thirdeye.bootstrap.partition;

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

import com.linkedin.thirdeye.api.DimensionSpec;
import com.linkedin.thirdeye.api.MetricSpec;
import com.linkedin.thirdeye.api.MetricType;
import com.linkedin.thirdeye.api.StarTreeConfig;

public class PartitionPhaseConfig {

  private List<String> dimensionNames;
  private List<String> metricNames;
  private List<MetricType> metricTypes;

  public PartitionPhaseConfig() {

  }

  public PartitionPhaseConfig(List<String> dimensionNames,
      List<String> metricNames, List<MetricType> metricTypes) {
    super();
    this.dimensionNames = dimensionNames;
    this.metricNames = metricNames;
    this.metricTypes = metricTypes;
  }

  public List<String> getDimensionNames() {
    return dimensionNames;
  }

  public List<String> getMetricNames() {
    return metricNames;
  }

  public List<MetricType> getMetricTypes() {
    return metricTypes;
  }

  public static PartitionPhaseConfig fromStarTreeConfig(StarTreeConfig config)
  {
    List<String> metricNames = new ArrayList<String>(config.getMetrics().size());
    List<MetricType> metricTypes = new ArrayList<MetricType>(config.getMetrics().size());
    for (MetricSpec spec : config.getMetrics())
    {
      metricNames.add(spec.getName());
      metricTypes.add(spec.getType());
    }

    List<String> dimensionNames = new ArrayList<String>(config.getDimensions().size());
    for (DimensionSpec dimensionSpec : config.getDimensions())
    {
      dimensionNames.add(dimensionSpec.getName());
    }

    return new PartitionPhaseConfig(dimensionNames,
                                    metricNames,
                                    metricTypes);
  }
}


text:
<!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="{{ site.url }}/js/jquery.js"></script>
    <script src="{{ site.url }}/js/bootstrap.min.js"></script>
  </body>
</html>


text:
using System;
using System.Data;
using NHibernate;
using NHibernate.Engine;
using NHibernate.Type;
using NHibernate.UserTypes;
using NodaTime;

namespace Dematt.Airy.Nhibernate.NodaTime
{
    /// <summary>
    /// Abstract class the implements all of the methods required to store a <see cref="ZonedDateTime"/> except,
    /// the NullSafeGet method which is implemented in two derived class one for Tzdb data sources and the other for
    /// </summary>
    /// <remarks>
    /// This could have also be implemented using the <see cref="IParameterizedType"/> interface.
    /// However it is currently preferred to have this base class and then two implantations of it.
    /// </remarks>
    public abstract class ZonedDateTimeType : ImmutableCompositeUserType
    {
        /// <summary>
        /// Gets the "property names" that may be used in a query.
        /// </summary>
        public string[] PropertyNames
        {
            get
            {
                return new[] { "DateTimeOffset", "DateTimeZoneId" };
            }
        }

        /// <summary>
        /// Gets the corresponding "property types".
        /// </summary>
        public IType[] PropertyTypes
        {
            get
            {
                return new IType[] { NHibernateUtil.DateTimeOffset, TypeFactory.GetStringType(35) };
            }
        }

        /// <summary>
        /// Gets the type of the class returned by NullSafeGet().
        /// </summary>
        public Type ReturnedClass
        {
            get
            {
                return typeof(ZonedDateTime?);
            }
        }

        /// <summary>
        /// Gets the value of a property.
        /// </summary>
        /// <param name="component">An instance of the class mapped by this "type".</param>
        /// <param name="property">The index of the property to get.</param>
        /// <returns>The property value.</returns>
        public object GetPropertyValue(object component, int property)
        {
            var zonedDateTime = AsZonedDateTime(component);
            if (zonedDateTime == null)
            {
                return null;
            }

            switch (property)
            {
                case 0:
                    return zonedDateTime.Value.ToDateTimeOffset();
                case 1:
                    return zonedDateTime.Value.Zone.Id;
                default:
                    throw new Exception(string.Format("No implementation for property index of '{0}'.", property));
            }
        }

        /// <summary>
        /// Set the value of a property.
        /// </summary>
        /// <param name="component">An instance of class mapped by this "type".</param>
        /// <param name="property">The index of the property to set.</param>
        /// <param name="value">The value to set.</param>
        public void SetPropertyValue(object component, int property, object value)
        {
            throw new InvalidOperationException("ZonedDateTime is an immutable object. SetPropertyValue isn't supported.");
        }

        /// <summary>
        /// Write an instance of the mapped class to a prepared statement. We should handle possibility of null values.
        /// A multi-column type should be written to parameters starting from index.
        /// If a property is not settable, skip it and don't increment the index.
        /// </summary>
        /// <param name="cmd">The command used for writing the value.</param>
        /// <param name="value">The value to write.</param>
        /// <param name="index">The parameters index to start at.</param>
        /// <param name="settable">Array indicating which properties are settable</param>
        /// <param name="session">The session.</param>
        public void NullSafeSet(IDbCommand cmd, object value, int index, bool[] settable, ISessionImplementor session)
        {
            if (value == null)
            {
                NHibernateUtil.DateTimeOffset.NullSafeSet(cmd, null, index);
                NHibernateUtil.String.NullSafeSet(cmd, null, index + 1);
            }
            else
            {
                var zonedDateTime = (ZonedDateTime)value;
                PropertyTypes[0].NullSafeSet(cmd, zonedDateTime.ToDateTimeOffset(), index, session);
                PropertyTypes[1].NullSafeSet(cmd, zonedDateTime.Zone.Id, index + 1, session);

            }
        }

        /// <summary>
        /// Compare two instances of the class mapped by this type for persistence
        /// "equality", i.e. equality of persistent state.
        /// </summary>
        /// <param name="x">The first object to compare.</param>
        /// <param name="y">The second object to compare.</param>
        /// <returns>true if the objects are considered equal; otherwise, false. If both x and y are null, the method returns true.</returns>
        public new bool Equals(object x, object y)
        {
            // Probably the best approach is to use object.Equals() which should call the overridden ZoneDateTime.Equals().
            // From the NodaTime api reference:
            //  http://nodatime.org/1.3.x/api/?topic=html/M_NodaTime_ZonedDateTime_Equals.htm
            // "True if the specified value is the same instant in the same time zone; false otherwise."
            // i.e. only true if the Instant and the DateTimeZone have the same values as those of the object being compared to.
            if (x == y)
            {
                return true;
            }

            if (x == null || y == null)
            {
                return false;
            }
            return x.Equals(y);

            #region Other equals option
            // The other option if we wanted to ignore the time zone and just compare on the Instant would be to use ZonedDateTime.CompareTo(object):
            // From the NodaTime api reference:
            //  http://nodatime.org/1.3.x/api/?topic=html/M_NodaTime_ZonedDateTime_CompareTo.htm)
            //  http://nodatime.org/1.3.x/api/?topic=html/P_NodaTime_ZonedDateTime_Comparer_Instant.htm
            // "A value less than zero if the instant represented by this zoned date/time is earlier than the one in other;
            // zero if the instant is the same as the one in other; a value greater than zero if the instant is later than the one in other."
            ////var zonedDateTimeX = x as ZonedDateTime?;
            ////var zonedDateTimeY = y as ZonedDateTime?;
            ////if (zonedDateTimeX == null || zonedDateTimeY == null)
            ////{
            ////    return x.Equals(y);
            ////}

            ////if (zonedDateTimeX.Value.CompareTo(zonedDateTimeY.Value) == 0)
            ////{
            ////    return true;
            ////}

            ////return false;
            #endregion
        }

        /// <summary>
        /// Gets a hash code for the instance, consistent with persistence "equality"
        /// </summary>
        /// <param name="x">The object to get the hash code for.</param>
        /// <returns>A hash code for the object x.</returns>
        public int GetHashCode(object x)
        {
            return x == null ? 0 : x.GetHashCode();
        }

        /// <summary>
        /// Tries to cast an unknown object to an <see cref="ZonedDateTime"/> object.
        /// </summary>
        /// <param name="value">The object to try to cast to a <see cref="ZonedDateTime"/> object.</param>
        /// <returns>A <see cref="ZonedDateTime"/> object if the value can be cast.</returns>
        private static ZonedDateTime? AsZonedDateTime(object value)
        {
            if (value == null)
            {
                return null;
            }

            var ts = value as ZonedDateTime?;
            if (ts == null)
            {
                throw new InvalidCastException(
                    string.Format("Expected '{0}' but received '{1}'.", typeof(ZonedDateTime?), value.GetType()));
            }

            return ts;
        }
    }
}


text:
		74_1

		74_2

		74_3

		74_4

		74_5

		74_6

		74_7

		74_8


text:
@interface JKUnimplementedPatch : JKPatch

- (id) initWithName:(NSString *)name;

@end


text:
<?php

namespace AppBundle\Controller\Api\Orders;

use AppBundle\Entity\RarOrder;
use AppBundle\Entity\User;
use AppBundle\Entity\RarModelOrdered;
use AppBundle\Entity\RarOrderLog;

use AppBundle\Services\MessageGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class ApiUpdateOrderController extends Controller
{

	/**
     * @Route("/api/order/update", name="apiupdateorder")
     */
	public function indexAction(Request $request){

            $params = array();
            $content = $request->getContent();
            $time = date_create(date('Y/m/d H:i:s'));

            if (!empty($content)){
                // On décode :
                $params = json_decode($content, true); // 2nd param to get as array
                // On check les droits
                if($params['tokenUser'] != ''){

                    // Initialisation du manager doctrine
                    $em = $this->getDoctrine()->getManager();
                    $orderrepository = $this->getDoctrine()->getRepository(RarOrder::class);
                    $order = $orderrepository->findOneBy( [ "idEshop" => $params['fk_shop'] ] );
                    // On récupère l'utilisateur
                    $userrepository = $this->getDoctrine()->getRepository(User::class);
                    $user = $userrepository->findOneBy([ "token" => $params['tokenUser'] ]);
                    $firstName = $user->getFirstName();
                    $lastName = $user->getLastName();
                    $fullName = $firstName.' '.$lastName;

                    if($params['action'] == 'canceled'){
                        $order->setState('4');
                        $stateWord = 'canceled';
                    }

                    if($params['action'] == 'complete'){
                        $order->setState('6');
                        $order->setDateShipped(date_create(date('Y/m/d H:i:s')));
                        $stateWord = 'finished';
                    }

                    $em->persist($order);
                    $em->flush();

                    // Notification
                    $newOrderLog = new RarOrderLog();
                    $newOrderLog->setDate($time);
                    $newOrderLog->setUser($user);
                    $newOrderLog->setMessage('Order #'.$params['fk_shop'].' status updated to "'.$stateWord.'" par '.$fullName.'.');
                    $newOrderLog->setOrder($order);
                    $em->persist($newOrderLog);
                    $em->flush();

                    $message = 'Done';

                }else{
                    $message = 'Access forbiden';
                }
            }else{
                $message = 'Content empty';
            }
            return new Response($message, 400);
	}
}


text:
package org.apache.druid.query.aggregation.post;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.PostAggregator;
import org.apache.druid.query.cache.CacheKeyBuilder;
import org.apache.druid.segment.column.ValueType;

import javax.annotation.Nullable;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;

/**
 */
public class FieldAccessPostAggregator implements PostAggregator
{
  @Nullable
  private final String name;
  private final String fieldName;
  // type is ignored from equals and friends because it is computed by decorate, and all post-aggs should be decorated
  // prior to usage (and is currently done so in the query constructors of all queries which can have post-aggs)
  @Nullable
  private final ValueType type;

  @JsonCreator
  public FieldAccessPostAggregator(
      @JsonProperty("name") @Nullable String name,
      @JsonProperty("fieldName") String fieldName
  )
  {
    this(name, fieldName, null);
  }

  private FieldAccessPostAggregator(@Nullable String name, String fieldName, @Nullable ValueType type)
  {
    Preconditions.checkNotNull(fieldName);
    this.name = name;
    this.fieldName = fieldName;
    this.type = type;
  }

  @Override
  public Set<String> getDependentFields()
  {
    return Sets.newHashSet(fieldName);
  }

  @Override
  public Comparator getComparator()
  {
    throw new UnsupportedOperationException();
  }

  @Override
  public Object compute(Map<String, Object> combinedAggregators)
  {
    return combinedAggregators.get(fieldName);
  }

  @Nullable
  @Override
  @JsonProperty
  public String getName()
  {
    return name;
  }

  @Override
  public ValueType getType()
  {
    return type;
  }

  @Override
  public FieldAccessPostAggregator decorate(Map<String, AggregatorFactory> aggregators)
  {
    final ValueType type;

    if (aggregators != null && aggregators.containsKey(fieldName)) {
      type = aggregators.get(fieldName).getType();
    } else {
      type = null;
    }

    return new FieldAccessPostAggregator(
        name,
        fieldName,
        type
    );
  }

  @Override
  public byte[] getCacheKey()
  {
    return new CacheKeyBuilder(PostAggregatorIds.FIELD_ACCESS)
        .appendString(fieldName)
        .build();
  }

  @JsonProperty
  public String getFieldName()
  {
    return fieldName;
  }

  @Override
  public String toString()
  {
    return "FieldAccessPostAggregator{" +
           "name='" + name + '\'' +
           ", fieldName='" + fieldName + '\'' +
           '}';
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    FieldAccessPostAggregator that = (FieldAccessPostAggregator) o;

    if (!fieldName.equals(that.fieldName)) {
      return false;
    }
    if (name != null ? !name.equals(that.name) : that.name != null) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode()
  {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + fieldName.hashCode();
    return result;
  }
}


text:
#ifndef __TestAccelerometer_h__
#define __TestAccelerometer_h__

#include "../TestBasic.h"

class TestAccelerometer : public TestBasic
{
	public :

		CREATE_FUNC ( TestAccelerometer );

	protected :

		virtual KDbool		init ( KDvoid );

		virtual KDvoid		didAccelerate ( CCAcceleration* pAccelerationValue );

	protected :

		CCSprite*			m_pBall;
		CCPoint				m_tPos;
};

#endif


text:
Share This

	Tweet

	<g:plusone size="medium"></g:plusone>


text:
.. Gini documentation master file, created by
   sphinx-quickstart on Wed Feb  4 11:09:43 2015.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Gini's documentation!
================================

Contents:

.. toctree::
   :maxdepth: 2

   semantics
   personality

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
from functools import partial
import argparse
from inout import load_off, convert_sequence_to_hdf5

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Import a sequence of OFF files and convert to HDF5 file format')
    parser.add_argument('input_filename_pattern',
                        help='Input filename pattern, e.g. "/tmp/file_*.off", '
                             'notice that you may have to escape the pattern with " to prevent shell expansion')
    parser.add_argument('output_filename',
                        help='Output file path, e.g. /tmp/face.hdf5')
    args = parser.parse_args()
    convert_sequence_to_hdf5(
        args.input_filename_pattern,
        partial(load_off, no_colors=True),
        args.output_filename)


text:
tutum-docker-rabbitmq
=====================

Base docker image to run a RabbitMQ server

Usage
-----

To create the image `tutum/rabbitmq`, execute the following command on the tutum-rabbitmq folder:

	sudo docker build -t tutum/rabbitmq .

Running the RabbitMQ server
---------------------------

Run the following command to start rabbitmq:

	docker run -d -p 5672:5672 -p 15672:15672 tutum/rabbitmq

The first time that you run your container, a new random password will be set.
To get the password, check the logs of the container by running:

	docker logs <CONTAINER_ID>

You will see an output like the following:

	========================================================================
	You can now connect to this RabbitMQ server using, for example:

	    rabbitmqadmin -u admin -p 5elsT6KtjrqV -H <host> -P <port> list vhosts

	Please remember to change the above password as soon as possible!
	========================================================================

In this case, `5elsT6KtjrqV` is the password set.
You can then connect to RabbitMQ:

	rabbitmqadmin -u admin -p 5elsT6KtjrqV -P 15672 list vhosts

Done!

Setting a specific password for the admin account
-------------------------------------------------

If you want to use a preset password instead of a randomly generated one, you can
set the environment variable `RABBITMQ_PASS` to your specific password when running the container:

	docker run -d -p 5672:5672 -p 15672:15672 -e RABBITMQ_PASS="mypass" tutum/rabbitmq

You can now test your new admin password:

	rabbitmqadmin -u admin -p mypass -P 15672 list vhosts


text:
<?php  namespace php\observerPattern;
/*
|=====================================================================
|
|----------------------------------------------------------------------
|	The ApplicationUser is the 'concrete-observer' in this pattern
|----------------------------------------------------------------------
|
|======================================================================
|
*/
class ApplicationUser implements User {

	/**
	 * Conference city
	 *
	 * @var string $city
	 */
	private $city;

	/**
	 * Conference price
	 *
	 * @var int $price
	 */
	private $price;

	/**
	 * Administrator instance
	 *
	 * @var string $venue
	 */
	private $venue;

	/**
	 * Conference city
	 *
	 * @var Administrator $admin
	 */
	private $data;

	/**
	 * Register user for conference
	 *
	 * @param Administrator $admin
	 * @return void
	 */
	public function userReg(Administrator $admin) {
		$this->data = $admin;
		$this->data->registerUser(new ApplicationUser);
	}

	/**
	 * Update details for conference
	 *
	 * @param string $city
	 * @param int $price
	 * @param string $venue
	 * @return void
	 */
	public function update($city, $price, $venue) {
		$this->city = $city;
		$this->price = $price;
		$this->venue = $venue;
	}

}


text:
using ppapi::thunk::EnterResourceNoLock;
using ppapi::thunk::PPB_ImageData_API;

namespace content {

namespace {

const int64 kOffscreenCallbackDelayMs = 1000 / 30;  // 30 fps

// Converts a rect inside an image of the given dimensions. The rect may be
// NULL to indicate it should be the entire image. If the rect is outside of
// the image, this will do nothing and return false.
bool ValidateAndConvertRect(const PP_Rect* rect,
                            int image_width,
                            int image_height,
                            gfx::Rect* dest) {
  if (!rect) {
    // Use the entire image area.
    *dest = gfx::Rect(0, 0, image_width, image_height);
  } else {
    // Validate the passed-in area.
    if (rect->point.x < 0 || rect->point.y < 0 || rect->size.width <= 0 ||
        rect->size.height <= 0)
      return false;

    // Check the max bounds, being careful of overflow.
    if (static_cast<int64>(rect->point.x) +
            static_cast<int64>(rect->size.width) >
        static_cast<int64>(image_width))
      return false;
    if (static_cast<int64>(rect->point.y) +
            static_cast<int64>(rect->size.height) >
        static_cast<int64>(image_height))
      return false;

    *dest = gfx::Rect(
        rect->point.x, rect->point.y, rect->size.width, rect->size.height);
  }
  return true;
}

// Converts BGRA <-> RGBA.
void ConvertBetweenBGRAandRGBA(const uint32_t* input,
                               int pixel_length,
                               uint32_t* output) {
  for (int i = 0; i < pixel_length; i++) {
    const unsigned char* pixel_in =
        reinterpret_cast<const unsigned char*>(&input[i]);
    unsigned char* pixel_out = reinterpret_cast<unsigned char*>(&output[i]);
    pixel_out[0] = pixel_in[2];
    pixel_out[1] = pixel_in[1];
    pixel_out[2] = pixel_in[0];
    pixel_out[3] = pixel_in[3];
  }
}

// Converts ImageData from PP_IMAGEDATAFORMAT_BGRA_PREMUL to
// PP_IMAGEDATAFORMAT_RGBA_PREMUL, or reverse. It's assumed that the
// destination image is always mapped (so will have non-NULL data).
void ConvertImageData(PPB_ImageData_Impl* src_image,
                      const SkIRect& src_rect,
                      PPB_ImageData_Impl* dest_image,
                      const SkRect& dest_rect) {
  ImageDataAutoMapper auto_mapper(src_image);

  DCHECK(src_image->format() != dest_image->format());
  DCHECK(PPB_ImageData_Impl::IsImageDataFormatSupported(src_image->format()));
  DCHECK(PPB_ImageData_Impl::IsImageDataFormatSupported(dest_image->format()));

  const SkBitmap* src_bitmap = src_image->GetMappedBitmap();
  const SkBitmap* dest_bitmap = dest_image->GetMappedBitmap();
  if (src_rect.width() == src_image->width() &&
      dest_rect.width() == dest_image->width()) {
    // Fast path if the full line needs to be converted.
    ConvertBetweenBGRAandRGBA(
        src_bitmap->getAddr32(static_cast<int>(src_rect.fLeft),
                              static_cast<int>(src_rect.fTop)),
        src_rect.width() * src_rect.height(),
        dest_bitmap->getAddr32(static_cast<int>(dest_rect.fLeft),
                               static_cast<int>(dest_rect.fTop)));
  } else {
    // Slow path where we convert line by line.
    for (int y = 0; y < src_rect.height(); y++) {
      ConvertBetweenBGRAandRGBA(
          src_bitmap->getAddr32(static_cast<int>(src_rect.fLeft),
                                static_cast<int>(src_rect.fTop + y)),
          src_rect.width(),
          dest_bitmap->getAddr32(static_cast<int>(dest_rect.fLeft),
                                 static_cast<int>(dest_rect.fTop + y)));
    }
  }
}

}  // namespace

struct PepperGraphics2DHost::QueuedOperation {
  enum Type { PAINT, SCROLL, REPLACE, };

  QueuedOperation(Type t)
      : type(t), paint_x(0), paint_y(0), scroll_dx(0), scroll_dy(0) {}

  Type type;

  // Valid when type == PAINT.
  scoped_refptr<PPB_ImageData_Impl> paint_image;
  int paint_x, paint_y;
  gfx::Rect paint_src_rect;

  // Valid when type == SCROLL.
  gfx::Rect scroll_clip_rect;
  int scroll_dx, scroll_dy;

  // Valid when type == REPLACE.
  scoped_refptr<PPB_ImageData_Impl> replace_image;
};

// static
PepperGraphics2DHost* PepperGraphics2DHost::Create(
    RendererPpapiHost* host,
    PP_Instance instance,
    PP_Resource resource,
    const PP_Size& size,
    PP_Bool is_always_opaque,
    scoped_refptr<PPB_ImageData_Impl> backing_store) {
  PepperGraphics2DHost* resource_host =
      new PepperGraphics2DHost(host, instance, resource);
  if (!resource_host->Init(size.width,
                           size.height,
                           PP_ToBool(is_always_opaque),
                           backing_store)) {
    delete resource_host;
    return NULL;
  }
  return resource_host;
}

PepperGraphics2DHost::PepperGraphics2DHost(RendererPpapiHost* host,
                                           PP_Instance instance,
                                           PP_Resource resource)
    : ResourceHost(host->GetPpapiHost(), instance, resource),
      renderer_ppapi_host_(host),
      bound_instance_(NULL),
      need_flush_ack_(false),
      offscreen_flush_pending_(false),
      is_always_opaque_(false),
      scale_(1.0f),
      is_running_in_process_(host->IsRunningInProcess()),
      texture_mailbox_modified_(true) {}

PepperGraphics2DHost::~PepperGraphics2DHost() {
  // Unbind from the instance when destroyed if we're still bound.
  if (bound_instance_)
    bound_instance_->BindGraphics(bound_instance_->pp_instance(), 0);
}

bool PepperGraphics2DHost::Init(
    int width,
    int height,
    bool is_always_opaque,
    scoped_refptr<PPB_ImageData_Impl> backing_store) {
  // The underlying PPB_ImageData_Impl will validate the dimensions.
  image_data_ = backing_store;
  if (!image_data_->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
                         width,
                         height,
                         true) ||
      !image_data_->Map()) {
    image_data_ = NULL;
    return false;
  }
  is_always_opaque_ = is_always_opaque;
  scale_ = 1.0f;
  return true;
}

int32_t PepperGraphics2DHost::OnResourceMessageReceived(
    const IPC::Message& msg,
    ppapi::host::HostMessageContext* context) {
  PPAPI_BEGIN_MESSAGE_MAP(PepperGraphics2DHost, msg)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Graphics2D_PaintImageData,
                                      OnHostMsgPaintImageData)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Graphics2D_Scroll,
                                      OnHostMsgScroll)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Graphics2D_ReplaceContents,
                                      OnHostMsgReplaceContents)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL_0(PpapiHostMsg_Graphics2D_Flush,
                                        OnHostMsgFlush)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Graphics2D_SetScale,
                                      OnHostMsgSetScale)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_Graphics2D_ReadImageData,
                                      OnHostMsgReadImageData)
  PPAPI_END_MESSAGE_MAP()
  return PP_ERROR_FAILED;
}

bool PepperGraphics2DHost::IsGraphics2DHost() { return true; }

bool PepperGraphics2DHost::ReadImageData(PP_Resource image,
                                         const PP_Point* top_left) {
  // Get and validate the image object to paint into.
  EnterResourceNoLock<PPB_ImageData_API> enter(image, true);
  if (enter.failed())
    return false;
  PPB_ImageData_Impl* image_resource =
      static_cast<PPB_ImageData_Impl*>(enter.object());
  if (!PPB_ImageData_Impl::IsImageDataFormatSupported(image_resource->format()))
    return false;  // Must be in the right format.

  // Validate the bitmap position.
  int x = top_left->x;
  if (x < 0 ||
      static_cast<int64>(x) + static_cast<int64>(image_resource->width()) >
          image_data_->width())
    return false;
  int y = top_left->y;
  if (y < 0 ||
      static_cast<int64>(y) + static_cast<int64>(image_resource->height()) >
          image_data_->height())
    return false;

  ImageDataAutoMapper auto_mapper(image_resource);
  if (!auto_mapper.is_valid())
    return false;

  SkIRect src_irect = {x, y, x + image_resource->width(),
                       y + image_resource->height()};
  SkRect dest_rect = {SkIntToScalar(0), SkIntToScalar(0),
                      SkIntToScalar(image_resource->width()),
                      SkIntToScalar(image_resource->height())};

  if (image_resource->format() != image_data_->format()) {
    // Convert the image data if the format does not match.
    ConvertImageData(image_data_.get(), src_irect, image_resource, dest_rect);
  } else {
    SkCanvas* dest_canvas = image_resource->GetCanvas();

    // We want to replace the contents of the bitmap rather than blend.
    SkPaint paint;
    paint.setXfermodeMode(SkXfermode::kSrc_Mode);
    dest_canvas->drawBitmapRect(
        *image_data_->GetMappedBitmap(), src_irect, dest_rect, &paint);
  }
  return true;
}

bool PepperGraphics2DHost::BindToInstance(
    PepperPluginInstanceImpl* new_instance) {
  if (new_instance && new_instance->pp_instance() != pp_instance())
    return false;  // Can't bind other instance's contexts.
  if (bound_instance_ == new_instance)
    return true;  // Rebinding the same device, nothing to do.
  if (bound_instance_ && new_instance)
    return false;  // Can't change a bound device.

  if (!new_instance) {
    // When the device is detached, we'll not get any more paint callbacks so
    // we need to clear the list, but we still want to issue any pending
    // callbacks to the plugin.
    if (need_flush_ack_)
      ScheduleOffscreenFlushAck();
  } else {
    // Devices being replaced, redraw the plugin.
    new_instance->InvalidateRect(gfx::Rect());
  }

  cached_bitmap_.reset();
  texture_mailbox_modified_ = true;

  bound_instance_ = new_instance;
  return true;
}

// The |backing_bitmap| must be clipped to the |plugin_rect| to avoid painting
// outside the plugin area. This can happen if the plugin has been resized since
// PaintImageData verified the image is within the plugin size.
void PepperGraphics2DHost::Paint(blink::WebCanvas* canvas,
                                 const gfx::Rect& plugin_rect,
                                 const gfx::Rect& paint_rect) {
  TRACE_EVENT0("pepper", "PepperGraphics2DHost::Paint");
  ImageDataAutoMapper auto_mapper(image_data_.get());
  const SkBitmap& backing_bitmap = *image_data_->GetMappedBitmap();

  gfx::Rect invalidate_rect = plugin_rect;
  invalidate_rect.Intersect(paint_rect);
  SkRect sk_invalidate_rect = gfx::RectToSkRect(invalidate_rect);
  SkAutoCanvasRestore auto_restore(canvas, true);
  canvas->clipRect(sk_invalidate_rect);
  gfx::Size pixel_image_size(image_data_->width(), image_data_->height());
  gfx::Size image_size =
      gfx::ToFlooredSize(gfx::ScaleSize(pixel_image_size, scale_));

  PepperPluginInstance* plugin_instance =
      renderer_ppapi_host_->GetPluginInstance(pp_instance());
  if (!plugin_instance)
    return;
  if (plugin_instance->IsFullPagePlugin()) {
    // When we're resizing a window with a full-frame plugin, the plugin may
    // not yet have bound a new device, which will leave parts of the
    // background exposed if the window is getting larger. We want this to
    // show white (typically less jarring) rather than black or uninitialized.
    // We don't do this for non-full-frame plugins since we specifically want
    // the page background to show through.
    SkAutoCanvasRestore auto_restore(canvas, true);
    SkRect image_data_rect =
        gfx::RectToSkRect(gfx::Rect(plugin_rect.origin(), image_size));
    canvas->clipRect(image_data_rect, SkRegion::kDifference_Op);

    SkPaint paint;
    paint.setXfermodeMode(SkXfermode::kSrc_Mode);
    paint.setColor(SK_ColorWHITE);
    canvas->drawRect(sk_invalidate_rect, paint);
  }

  SkBitmap image;
  // Copy to device independent bitmap when target canvas doesn't support
  // platform paint.
  if (!skia::SupportsPlatformPaint(canvas))
    backing_bitmap.copyTo(&image, kN32_SkColorType);
  else
    image = backing_bitmap;

  SkPaint paint;
  if (is_always_opaque_) {
    // When we know the device is opaque, we can disable blending for slightly
    // more optimized painting.
    paint.setXfermodeMode(SkXfermode::kSrc_Mode);
  }

  SkPoint origin;
  origin.set(SkIntToScalar(plugin_rect.x()), SkIntToScalar(plugin_rect.y()));

  SkPoint pixel_origin = origin;

  if (scale_ != 1.0f && scale_ > 0.0f) {
    canvas->scale(scale_, scale_);
    pixel_origin.set(pixel_origin.x() * (1.0f / scale_),
                     pixel_origin.y() * (1.0f / scale_));
  }
  canvas->drawBitmap(image, pixel_origin.x(), pixel_origin.y(), &paint);
}

void PepperGraphics2DHost::ViewInitiatedPaint() {
  TRACE_EVENT0("pepper", "PepperGraphics2DHost::ViewInitiatedPaint");
  if (need_flush_ack_) {
    SendFlushAck();
    need_flush_ack_ = false;
  }
}

void PepperGraphics2DHost::SetScale(float scale) { scale_ = scale; }

float PepperGraphics2DHost::GetScale() const { return scale_; }

bool PepperGraphics2DHost::IsAlwaysOpaque() const { return is_always_opaque_; }

PPB_ImageData_Impl* PepperGraphics2DHost::ImageData() {
  return image_data_.get();
}

gfx::Size PepperGraphics2DHost::Size() const {
  if (!image_data_.get())
    return gfx::Size();
  return gfx::Size(image_data_->width(), image_data_->height());
}

void PepperGraphics2DHost::ClearCache() {
  cached_bitmap_.reset();
}

int32_t PepperGraphics2DHost::OnHostMsgPaintImageData(
    ppapi::host::HostMessageContext* context,
    const ppapi::HostResource& image_data,
    const PP_Point& top_left,
    bool src_rect_specified,
    const PP_Rect& src_rect) {
  EnterResourceNoLock<PPB_ImageData_API> enter(image_data.host_resource(),
                                               true);
  if (enter.failed())
    return PP_ERROR_BADRESOURCE;
  PPB_ImageData_Impl* image_resource =
      static_cast<PPB_ImageData_Impl*>(enter.object());

  QueuedOperation operation(QueuedOperation::PAINT);
  operation.paint_image = image_resource;
  if (!ValidateAndConvertRect(src_rect_specified ? &src_rect : NULL,
                              image_resource->width(),
                              image_resource->height(),
                              &operation.paint_src_rect))
    return PP_ERROR_BADARGUMENT;

  // Validate the bitmap position using the previously-validated rect, there
  // should be no painted area outside of the image.
  int64 x64 = static_cast<int64>(top_left.x);
  int64 y64 = static_cast<int64>(top_left.y);
  if (x64 + static_cast<int64>(operation.paint_src_rect.x()) < 0 ||
      x64 + static_cast<int64>(operation.paint_src_rect.right()) >
          image_data_->width())
    return PP_ERROR_BADARGUMENT;
  if (y64 + static_cast<int64>(operation.paint_src_rect.y()) < 0 ||
      y64 + static_cast<int64>(operation.paint_src_rect.bottom()) >
          image_data_->height())
    return PP_ERROR_BADARGUMENT;
  operation.paint_x = top_left.x;
  operation.paint_y = top_left.y;

  queued_operations_.push_back(operation);
  return PP_OK;
}

int32_t PepperGraphics2DHost::OnHostMsgScroll(
    ppapi::host::HostMessageContext* context,
    bool clip_specified,
    const PP_Rect& clip,
    const PP_Point& amount) {
  QueuedOperation operation(QueuedOperation::SCROLL);
  if (!ValidateAndConvertRect(clip_specified ? &clip : NULL,
                              image_data_->width(),
                              image_data_->height(),
                              &operation.scroll_clip_rect))
    return PP_ERROR_BADARGUMENT;

  // If we're being asked to scroll by more than the clip rect size, just
  // ignore this scroll command and say it worked.
  int32 dx = amount.x;
  int32 dy = amount.y;
  if (dx <= -image_data_->width() || dx >= image_data_->width() ||
      dy <= -image_data_->height() || dy >= image_data_->height())
    return PP_ERROR_BADARGUMENT;

  operation.scroll_dx = dx;
  operation.scroll_dy = dy;

  queued_operations_.push_back(operation);
  return PP_OK;
}

int32_t PepperGraphics2DHost::OnHostMsgReplaceContents(
    ppapi::host::HostMessageContext* context,
    const ppapi::HostResource& image_data) {
  EnterResourceNoLock<PPB_ImageData_API> enter(image_data.host_resource(),
                                               true);
  if (enter.failed())
    return PP_ERROR_BADRESOURCE;
  PPB_ImageData_Impl* image_resource =
      static_cast<PPB_ImageData_Impl*>(enter.object());

  if (!PPB_ImageData_Impl::IsImageDataFormatSupported(image_resource->format()))
    return PP_ERROR_BADARGUMENT;

  if (image_resource->width() != image_data_->width() ||
      image_resource->height() != image_data_->height())
    return PP_ERROR_BADARGUMENT;

  QueuedOperation operation(QueuedOperation::REPLACE);
  operation.replace_image = image_resource;
  queued_operations_.push_back(operation);
  return PP_OK;
}

int32_t PepperGraphics2DHost::OnHostMsgFlush(
    ppapi::host::HostMessageContext* context) {
  // Don't allow more than one pending flush at a time.
  if (HasPendingFlush())
    return PP_ERROR_INPROGRESS;

  PP_Resource old_image_data = 0;
  flush_reply_context_ = context->MakeReplyMessageContext();
  if (is_running_in_process_)
    return Flush(NULL);

  // Reuse image data when running out of process.
  int32_t result = Flush(&old_image_data);

  if (old_image_data) {
    // If the Graphics2D has an old image data it's not using any more, send
    // it back to the plugin for possible re-use. See ppb_image_data_proxy.cc
    // for a description how this process works.
    ppapi::HostResource old_image_data_host_resource;
    old_image_data_host_resource.SetHostResource(pp_instance(), old_image_data);
    host()->Send(new PpapiMsg_PPBImageData_NotifyUnusedImageData(
        ppapi::API_ID_PPB_IMAGE_DATA, old_image_data_host_resource));
  }

  return result;
}

int32_t PepperGraphics2DHost::OnHostMsgSetScale(
    ppapi::host::HostMessageContext* context,
    float scale) {
  if (scale > 0.0f) {
    scale_ = scale;
    return PP_OK;
  }
  return PP_ERROR_BADARGUMENT;
}

int32_t PepperGraphics2DHost::OnHostMsgReadImageData(
    ppapi::host::HostMessageContext* context,
    PP_Resource image,
    const PP_Point& top_left) {
  context->reply_msg = PpapiPluginMsg_Graphics2D_ReadImageDataAck();
  return ReadImageData(image, &top_left) ? PP_OK : PP_ERROR_FAILED;
}

void PepperGraphics2DHost::ReleaseCallback(scoped_ptr<cc::SharedBitmap> bitmap,
                                           const gfx::Size& bitmap_size,
                                           uint32 sync_point,
                                           bool lost_resource) {
  cached_bitmap_.reset();
  // Only keep around a cached bitmap if the plugin is currently drawing (has
  // need_flush_ack_ set).
  if (need_flush_ack_ && bound_instance_)
    cached_bitmap_ = bitmap.Pass();
  cached_bitmap_size_ = bitmap_size;
}

bool PepperGraphics2DHost::PrepareTextureMailbox(
    cc::TextureMailbox* mailbox,
    scoped_ptr<cc::SingleReleaseCallback>* release_callback) {
  if (!texture_mailbox_modified_)
    return false;
  // TODO(jbauman): Send image_data_ through mailbox to avoid copy.
  gfx::Size pixel_image_size(image_data_->width(), image_data_->height());
  scoped_ptr<cc::SharedBitmap> shared_bitmap;
  if (cached_bitmap_) {
    if (cached_bitmap_size_ == pixel_image_size)
      shared_bitmap = cached_bitmap_.Pass();
    else
      cached_bitmap_.reset();
  }
  if (!shared_bitmap) {
    shared_bitmap = RenderThreadImpl::current()
                        ->shared_bitmap_manager()
                        ->AllocateSharedBitmap(pixel_image_size);
  }
  if (!shared_bitmap)
    return false;
  void* src = image_data_->Map();
  memcpy(shared_bitmap->pixels(),
         src,
         cc::SharedBitmap::CheckedSizeInBytes(pixel_image_size));
  image_data_->Unmap();

  *mailbox = cc::TextureMailbox(shared_bitmap.get(), pixel_image_size);
  *release_callback = cc::SingleReleaseCallback::Create(
      base::Bind(&PepperGraphics2DHost::ReleaseCallback,
                 this->AsWeakPtr(),
                 base::Passed(&shared_bitmap),
                 pixel_image_size));
  texture_mailbox_modified_ = false;
  return true;
}

void PepperGraphics2DHost::AttachedToNewLayer() {
  texture_mailbox_modified_ = true;
}

int32_t PepperGraphics2DHost::Flush(PP_Resource* old_image_data) {
  bool done_replace_contents = false;
  bool no_update_visible = true;
  bool is_plugin_visible = true;
  for (size_t i = 0; i < queued_operations_.size(); i++) {
    QueuedOperation& operation = queued_operations_[i];
    gfx::Rect op_rect;
    switch (operation.type) {
      case QueuedOperation::PAINT:
        ExecutePaintImageData(operation.paint_image.get(),
                              operation.paint_x,
                              operation.paint_y,
                              operation.paint_src_rect,
                              &op_rect);
        break;
      case QueuedOperation::SCROLL:
        ExecuteScroll(operation.scroll_clip_rect,
                      operation.scroll_dx,
                      operation.scroll_dy,
                      &op_rect);
        break;
      case QueuedOperation::REPLACE:
        // Since the out parameter |old_image_data| takes ownership of the
        // reference, if there are more than one ReplaceContents calls queued
        // the first |old_image_data| will get overwritten and leaked. So we
        // only supply this for the first call.
        ExecuteReplaceContents(operation.replace_image.get(),
                               &op_rect,
                               done_replace_contents ? NULL : old_image_data);
        done_replace_contents = true;
        break;
    }

    // For correctness with accelerated compositing, we must issue an invalidate
    // on the full op_rect even if it is partially or completely off-screen.
    // However, if we issue an invalidate for a clipped-out region, WebKit will
    // do nothing and we won't get any ViewFlushedPaint calls, leaving our
    // callback stranded. So we still need to check whether the repainted area
    // is visible to determine how to deal with the callback.
    if (bound_instance_ && !op_rect.IsEmpty()) {
      gfx::Point scroll_delta(operation.scroll_dx, operation.scroll_dy);
      if (!ConvertToLogicalPixels(scale_,
                                  &op_rect,
                                  operation.type == QueuedOperation::SCROLL
                                      ? &scroll_delta
                                      : NULL)) {
        // Conversion requires falling back to InvalidateRect.
        operation.type = QueuedOperation::PAINT;
      }

      gfx::Rect clip = PP_ToGfxRect(bound_instance_->view_data().clip_rect);
      is_plugin_visible = !clip.IsEmpty();

      // Set |no_update_visible| to false if the change overlaps the visible
      // area.
      if (!gfx::IntersectRects(clip, op_rect).IsEmpty()) {
        no_update_visible = false;
      }

      // Notify the plugin of the entire change (op_rect), even if it is
      // partially or completely off-screen.
      if (operation.type == QueuedOperation::SCROLL) {
        bound_instance_->ScrollRect(
            scroll_delta.x(), scroll_delta.y(), op_rect);
      } else {
        if (!op_rect.IsEmpty())
          bound_instance_->InvalidateRect(op_rect);
      }
      texture_mailbox_modified_ = true;
    }
  }
  queued_operations_.clear();

  if (!bound_instance_) {
    // As promised in the API, we always schedule callback when unbound.
    ScheduleOffscreenFlushAck();
  } else if (no_update_visible && is_plugin_visible &&
             bound_instance_->view_data().is_page_visible) {
    // There's nothing visible to invalidate so just schedule the callback to
    // execute in the next round of the message loop.
    ScheduleOffscreenFlushAck();
  } else {
    need_flush_ack_ = true;
  }

  if (bound_instance_ && bound_instance_->throttler() &&
      bound_instance_->throttler()->needs_representative_keyframe()) {
    bound_instance_->throttler()->OnImageFlush(image_data_->GetMappedBitmap());
  }

  return PP_OK_COMPLETIONPENDING;
}

void PepperGraphics2DHost::ExecutePaintImageData(PPB_ImageData_Impl* image,
                                                 int x,
                                                 int y,
                                                 const gfx::Rect& src_rect,
                                                 gfx::Rect* invalidated_rect) {
  // Ensure the source image is mapped to read from it.
  ImageDataAutoMapper auto_mapper(image);
  if (!auto_mapper.is_valid())
    return;

  // Portion within the source image to cut out.
  SkIRect src_irect = {src_rect.x(), src_rect.y(), src_rect.right(),
                       src_rect.bottom()};

  // Location within the backing store to copy to.
  *invalidated_rect = src_rect;
  invalidated_rect->Offset(x, y);
  SkRect dest_rect = {SkIntToScalar(invalidated_rect->x()),
                      SkIntToScalar(invalidated_rect->y()),
                      SkIntToScalar(invalidated_rect->right()),
                      SkIntToScalar(invalidated_rect->bottom())};

  if (image->format() != image_data_->format()) {
    // Convert the image data if the format does not match.
    ConvertImageData(image, src_irect, image_data_.get(), dest_rect);
  } else {
    // We're guaranteed to have a mapped canvas since we mapped it in Init().
    SkCanvas* backing_canvas = image_data_->GetCanvas();

    // We want to replace the contents of the bitmap rather than blend.
    SkPaint paint;
    paint.setXfermodeMode(SkXfermode::kSrc_Mode);
    backing_canvas->drawBitmapRect(
        *image->GetMappedBitmap(), src_irect, dest_rect, &paint);
  }
}

void PepperGraphics2DHost::ExecuteScroll(const gfx::Rect& clip,
                                         int dx,
                                         int dy,
                                         gfx::Rect* invalidated_rect) {
  gfx::ScrollCanvas(image_data_->GetCanvas(), clip, gfx::Vector2d(dx, dy));
  *invalidated_rect = clip;
}

void PepperGraphics2DHost::ExecuteReplaceContents(PPB_ImageData_Impl* image,
                                                  gfx::Rect* invalidated_rect,
                                                  PP_Resource* old_image_data) {
  if (image->format() != image_data_->format()) {
    DCHECK(image->width() == image_data_->width() &&
           image->height() == image_data_->height());
    // Convert the image data if the format does not match.
    SkIRect src_irect = {0, 0, image->width(), image->height()};
    SkRect dest_rect = {SkIntToScalar(0), SkIntToScalar(0),
                        SkIntToScalar(image_data_->width()),
                        SkIntToScalar(image_data_->height())};
    ConvertImageData(image, src_irect, image_data_.get(), dest_rect);
  } else {
    // The passed-in image may not be mapped in our process, and we need to
    // guarantee that the current backing store is always mapped.
    if (!image->Map())
      return;

    if (old_image_data)
      *old_image_data = image_data_->GetReference();
    image_data_ = image;
  }
  *invalidated_rect =
      gfx::Rect(0, 0, image_data_->width(), image_data_->height());
}

void PepperGraphics2DHost::SendFlushAck() {
  host()->SendReply(flush_reply_context_, PpapiPluginMsg_Graphics2D_FlushAck());
}

void PepperGraphics2DHost::SendOffscreenFlushAck() {
  DCHECK(offscreen_flush_pending_);

  // We must clear this flag before issuing the callback. It will be
  // common for the plugin to issue another invalidate in response to a flush
  // callback, and we don't want to think that a callback is already pending.
  offscreen_flush_pending_ = false;
  SendFlushAck();
}

void PepperGraphics2DHost::ScheduleOffscreenFlushAck() {
  offscreen_flush_pending_ = true;
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&PepperGraphics2DHost::SendOffscreenFlushAck, AsWeakPtr()),
      base::TimeDelta::FromMilliseconds(kOffscreenCallbackDelayMs));
}

bool PepperGraphics2DHost::HasPendingFlush() const {
  return need_flush_ack_ || offscreen_flush_pending_;
}

// static
bool PepperGraphics2DHost::ConvertToLogicalPixels(float scale,
                                                  gfx::Rect* op_rect,
                                                  gfx::Point* delta) {
  if (scale == 1.0f || scale <= 0.0f)
    return true;

  gfx::Rect original_rect = *op_rect;
  // Take the enclosing rectangle after scaling so a rectangle scaled down then
  // scaled back up by the inverse scale would fully contain the entire area
  // affected by the original rectangle.
  *op_rect = gfx::ToEnclosingRect(gfx::ScaleRect(*op_rect, scale));
  if (delta) {
    gfx::Point original_delta = *delta;
    float inverse_scale = 1.0f / scale;
    *delta = gfx::ToFlooredPoint(gfx::ScalePoint(*delta, scale));

    gfx::Rect inverse_scaled_rect =
        gfx::ToEnclosingRect(gfx::ScaleRect(*op_rect, inverse_scale));
    if (original_rect != inverse_scaled_rect)
      return false;
    gfx::Point inverse_scaled_point =
        gfx::ToFlooredPoint(gfx::ScalePoint(*delta, inverse_scale));
    if (original_delta != inverse_scaled_point)
      return false;
  }

  return true;
}

}  // namespace content


text:
import math
import rospy
import tf
from flexbe_core import EventState, Logger

from flexbe_core.proxy import ProxyActionClient, ProxyPublisher

from hector_move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseActionPath
from rospy import Time

from visualization_msgs.msg import MarkerArray, Marker

'''
Created on 15.06.2015

@author: Philipp Schillinger
'''

class MoveAlongPath(EventState):
	'''
	Lets the robot move along a given path.

	># path		PoseStamped[]			Array of Positions of the robot.
	># speed	float				Speed of the robot

	<= reached 					Robot is now located at the specified waypoint.
	<= failed 					Failed to send a motion request to the action server.
	'''

	def __init__(self):
		'''
		Constructor
		'''
		super(MoveAlongPath, self).__init__(outcomes=['reached', 'failed'], input_keys=['path','speed'])

		self._failed = False
		self._reached = False

		self._pathTopic = '/controller/path'
		self._marker_topic = '/debug/path'

		self._pub = ProxyPublisher({self._pathTopic: MoveBaseActionPath, self._marker_topic: MarkerArray})

	def execute(self, userdata):
		'''
		Execute this state
		'''

		if self._failed:
			return 'failed'
		if self._reached:
			return 'reached'

	def on_enter(self, userdata):

		ma = MarkerArray()
		self._path = MoveBaseActionPath()

		for i in range(len(userdata.path.poses)):

			marker = Marker(type=Marker.ARROW)
			marker.header = userdata.path.header
			marker.pose = userdata.path.poses[i].pose
			marker.scale.x = 0.2
			marker.scale.y = 0.02
			marker.scale.z = 0.02
			marker.color.b = 1.0
			marker.color.r = 0.9 - 0.7 * i / len(userdata.path.poses)
			marker.color.g = 0.9 - 0.7 * i / len(userdata.path.poses)
			marker.color.a = 0.8 - 0.5 * i / len(userdata.path.poses)
			marker.id = i
			ma.markers.append(marker)

		self._failed = False

		self._path.goal.target_path.poses = userdata.path.poses
		self._path.goal.target_path.header.frame_id = 'map'

		self._pub.publish(self._pathTopic, self._path)
		self._pub.publish(self._marker_topic, ma)
		self._reached = True

	def on_stop(self):
		pass

	def on_exit(self, userdata):
		pass

	def on_pause(self):
		pass

	def on_resume(self, userdata):
		self.on_enter(userdata)


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Prediction_model extends MY_Model
{
	public $protected_attributes = array( 'id' );
	public $belongs_to = array( 'match', 'user');

	public $before_create = array( 'created_at', 'updated_at' );
  public $before_update = array( 'updated_at' );
  protected $soft_delete = TRUE;

    function generate_predictions($match_id = NULL) {
    	// use this only for test purposes !!!!

    	$this->load->model('user_model', 'user');

    	$users = $this->user->get_all();
    	if (is_null($match_id)) {
    		$matches = $this->match->get_all();
    	}

    	foreach($users as $user) {

    		foreach($matches as $match) {

    			$home_goals = mt_rand(0,4);
    			$away_goals = mt_rand(0,4);
    			if ($home_goals > $away_goals) {
    				$pred_result = 1;
    			} elseif ($home_goals < $away_goals) {
    				$pred_result = 2;
    			} else {
    				$pred_result = 3;
    			}

    			$data[] = array('match_id'=>$match->id,
    							'user_id'=>$user->id,
    							'pred_home_goals' => $home_goals,
    							'pred_away_goals' => $away_goals,
    							'pred_result' => $pred_result);
    		}
    		$ids[] = $this->prediction->insert_many($data);
    		unset($data);
    	}
    	print_r($ids);
    }

	function calculate($match_id) {
    $this->load->model('match_model', 'match');
		$predictions = $this->prediction->with('user')
                                    ->get_many_by('match_id',$match_id);
        $match = $this->match->get($match_id);

        if($match->matchtype_id<10) {

          $points_for_goals = $this->config->item('pool_points_for_goals_group_match');
    			$points_for_result = $this->config->item('pool_points_for_result_group_match');
    			$points_for_bonus = $this->config->item('pool_bonus_points_group_match');
		    } else {
    			$points_for_goals = $this->config->item('pool_points_for_goals_knockout_match');
    			$points_for_result = $this->config->item('pool_points_for_result_knockout_match');
    			$points_for_bonus = $this->config->item('pool_bonus_points_knockout_match');
    		}
        $count=0;
        foreach($predictions as $prediction) {

          $bonus = true;
          $total = 0;
          $user_total = $this->get_total_user_before_match($prediction->user_id, $match_id);

          if($match->result_home_goals == $prediction->pred_home_goals) {
            $update[$count]['points_for_home_goals'] = $points_for_goals;
            $total += $points_for_goals;
          } else {
            $update[$count]['points_for_home_goals'] = NULL;
            $bonus = false;
          }

          if($match->result_away_goals == $prediction->pred_away_goals) {
            $update[$count]['points_for_away_goals'] = $points_for_goals;
            $total += $points_for_goals;
          } else {
            $update[$count]['points_for_away_goals'] = NULL;
            $bonus = false;
          }

          if($match->result == $prediction->pred_result) {
            $update[$count]['points_for_result'] = $points_for_result;
            $total += $points_for_result;
          } else {
            $update[$count]['points_for_result'] = NULL;
            $bonus = false;
          }

          if ($bonus == true) {
            $update[$count]['points_for_bonus'] = $points_for_bonus;
            $total += $points_for_bonus;
          } else {
            $update[$count]['points_for_bonus'] = NULL;
          }

          $update[$count]['points_total_for_this_match'] = $total;
          $update[$count]['points_after_this_match'] = $user_total + $total;
          $update[$count]['id'] = $prediction->id;
          $update[$count]['calculated'] = 1;
          $count++;
        }
		    $rows = $this->db->update_batch('predictions', $update, 'id');
        return $count;
	}

  function get_total_user_before_match($user_id, $match_id) {
    $this->db->select_max('points_after_this_match');
    $this->db->where('user_id', $user_id);
    $this->db->where('match_id <', $match_id);
    $query =  $this->db->get('predictions')->row();
    return $query->points_after_this_match;
  }

  function get_total_user($user_id) {
    $this->db->select_sum('points_total_for_this_match');
    $this->db->where('user_id', $user_id);
    $query =  $this->db->get('predictions')->row();
    return $query->points_total_for_this_match;
  }

}