text:
angular.module('starter', ['ionic', 'starter.controllers','ngMap'])
.directive('myMap', function($http) {
    var jsonArr = [];
    var json1 =[];

    // directive link function
    var link = function(scope, element, attrs) {
        var map, infoWindow;
        var markers = [];

        // map config
        var mapOptions = {
            //center: new google.maps.LatLng(50, 2),
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false
        };

        // init the map
        function initMap() {
            if (map === void 0) {
                map = new google.maps.Map(element[0], mapOptions);
                getLocation();

                function getLocation() {
                  if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(showPosition);
                  } else {
                    alert("Geolocation is not supported by this browser.");
                  }
                }
                function showPosition(position) {
                  var lat = position.coords.latitude;
                  var lng = position.coords.longitude;
                  map.setCenter(new google.maps.LatLng(lat, lng));

                  var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat, lng),
                    map: map,
                    icon: "img/current.png"
                  });
                  marker.setMap(map);
                }

                // place a marker
                function setMarker(map, position, title, content) {
                    var marker;
                    var markerOptions = {
                        position: position,
                        map: map,
                        title: title,
                        icon: 'https://maps.google.com/mapfiles/ms/icons/red-dot.png'
                    };

                    marker = new google.maps.Marker(markerOptions);
                    markers.push(marker); // add marker to array

                    google.maps.event.addListener(marker, 'click', function () {
                        // close window if not undefined
                        if (infoWindow !== void 0) {
                            infoWindow.close();
                        }
                        // create new window
                        var infoWindowOptions = {
                            content: content
                        };
                        infoWindow = new google.maps.InfoWindow(infoWindowOptions);
                        infoWindow.open(map, marker);
                    });
                }

                $http.get('js/guiderest.json').success(function(data){

                //var markers2 = JSON.search(data, '//*[id]');

                for( var i = 0; i<data.length; i++ ){
                    setMarker(map, new google.maps.LatLng(data[i].map.latitud, data[i].map.longitud), " ", ""+data[i].name+"");
                  }
                })
            }
        }

        // show the map and place some markers
        initMap();
    };

    return {
        restrict: 'A',
        template: '

',
        replace: true,
        link: link
    };
})

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

  $ionicConfigProvider.backButton.text('').icon('ion-ios7-arrow-left').previousTitleText(false);;
  $stateProvider

  .state('app', {
    url: "/app",
    abstract: true,
    templateUrl: "templates/menu.html",
    controller: 'AppCtrl'
  })

  // todos los restaurantes

  .state('app.restaurants', {
    url: "/restaurants",
    views: {
      'menuContent': {
        templateUrl: "templates/restaurants.html",
        controller: 'RestaurantsCtrl'
      }
    }
  })

  .state('app.restaurant', {
    url: "/restaurant/:restaurantId",
    cache: false,
    views: {
      'menuContent':{
        templateUrl: "templates/restaurant.html",
        controller: 'RestaurantCtrl'
      }
    }
  })

  //por cocina

  .state('app.restaurantscook', {
    url: "/restaurantscook",
    cache: false,
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantscook.html",
        controller: 'RestaurantsByCookCtrl'
      }
    }
  })

  .state('app.restaurantcook', {
    url: "/restaurantcook/:cookId",
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantscooklist.html",
        controller: 'RestaurantsListByCookCtrl'
      }
    }
  })

  // por zona

  .state('app.restaurantszone', {
    url: "/restaurantszone",
    cache: false,
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantszone.html",
        controller: 'RestaurantsByZoneCtrl'
      }
    }
  })

  .state('app.restaurantzone', {
    url: "/restaurantzone/:zoneId",
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantszonelist.html",
        controller: 'RestaurantsListByZoneCtrl'
      }
    }
  })

  // por plan

  .state('app.restaurantsplan', {
    url: "/restaurantsplan",
    cache: false,
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantsplan.html",
        controller: 'RestaurantsByPlanCtrl'
      }
    }
  })

  .state('app.restaurantplan', {
    url: "/restaurantplan/:planId",
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantplanlist.html",
        controller: 'RestaurantsListByPlanCtrl'
      }
    }
  })

  // todos los restaurantes promocion banorte

  .state('app.restaurantsbanorte', {
    url: "/restaurantsbanorte",
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantsbanorte.html",
        controller: 'RestaurantsBanorteCtrl'
      }
    }
  })

  // todos los restaurantes promocion banorte por cocina

  .state('app.restaurantscookbanorte', {
    url: "/restaurantscookbanorte",
    cache: false,
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantscookbanorte.html",
        controller: 'RestaurantsByCookBanorteCtrl'
      }
    }
  })

  .state('app.restaurantcookbanorte', {
    url: "/restaurantcookbanorte/:cookId",
    cache: false,
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantscooklistbanorte.html",
        controller: 'RestaurantsListByCookBanorteCtrl'
      }
    }
  })

  // todos los restaurantes promocion banorte por zona

  .state('app.restaurantszonebanorte', {
    url: "/restaurantszonebanorte",
    cache: false,
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantszonebanorte.html",
        controller: 'RestaurantsByZoneBanorteCtrl'
      }
    }
  })

  .state('app.restaurantzonebanorte', {
    url: "/restaurantzonebanorte/:zoneId",
    cache: false,
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantszonelist.html",
        controller: 'RestaurantsListByZoneBanorteCtrl'
      }
    }
  })

  // todos los restaurantes promocion banorte por plan

  .state('app.restaurantsplanbanorte', {
    url: "/restaurantsplanbanorte",
    cache: false,
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantsplanbanorte.html",
        controller: 'RestaurantsByPlanBanorteCtrl'
      }
    }
  })

  .state('app.restaurantplanbanorte', {
    url: "/restaurantplanbanorte/:planId",
    views: {
      'menuContent': {
        templateUrl: "templates/restaurantplanlistbanorte.html",
        controller: 'RestaurantsListByPlanBanorteCtrl'
      }
    }
  })

  .state('app.restaurantRecomendacion', {
    url: "/restaurantRecomendacion",
    views: {
      'menuContent':{
        templateUrl: "templates/restaurantrecomendacion.html",
        controller: 'RestaurantRecomendacionCtrl'
      }
    }
  })

  .state('app.restaurantesCercanos',{
    url: "/restaurantesCercanos",
    views: {
      'menuContent':{
        templateUrl: "templates/restaurantescercanos.html",
        controller: "RestaurantesCercanosCtrl"
      }
    }
  })

  .state('app.marco',{
    url: "/marcobeteta",
    views: {
      'menuContent':{
        templateUrl : "templates/marcobeteta.html"
      }
    }
  })

  .state('app.search', {
    url: "/search",
    views: {
      'menuContent': {
        templateUrl: "templates/search.html"
      }
    }
  })

  .state('app.browse', {
    url: "/browse",
    views: {
      'menuContent': {
        templateUrl: "templates/browse.html"
      }
    }
  })

  .state('app.playlists', {
    url: "/playlists",
    views: {
      'menuContent': {
        templateUrl: "templates/playlists.html",
        controller: 'PlaylistsCtrl'
      }
    }
  })

  .state('app.single', {
    url: "/playlists/:playlistId",
    views: {
      'menuContent': {
        templateUrl: "templates/playlist.html",
        controller: 'PlaylistCtrl'
      }
    }
  });
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/restaurantRecomendacion');
});


text:
package de.uni_heidelberg.cos.agw.imglib2.realtransform;

import net.imglib2.RealLocalizable;
import net.imglib2.RealPoint;
import net.imglib2.RealPositionable;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class SphericalToCartesianTransformTest {

    protected final double PREC_DOUBLE = 1E-14;
    protected final float PREC_FLOAT = 1E-5f;
    private double[][] sphericalToCartesianCases, cartesianToSphericalCases;

    @Before
    public void setUp() {
        sphericalToCartesianCases = new double[][]{
                {-5, -3 * Math.PI, 0}, {0, 0, 5},
                {0, -3 * Math.PI, 0}, {0, 0, 0},
                {5, -3 * Math.PI, 0}, {0, 0, -5},
                {-5, -0.5 * Math.PI, 0}, {5, 0, 0},
                {0, -0.5 * Math.PI, 0}, {0, 0, 0},
                {5, -0.5 * Math.PI, 0}, {-5, 0, 0},
                {-5, 0, 0}, {0, 0, -5},
                {0, 0, 0}, {0, 0, 0},
                {5, 0, 0}, {0, 0, 5},
                {-5, 0.5 * Math.PI, 0}, {-5, 0, 0},
                {0, 0.5 * Math.PI, 0}, {0, 0, 0},
                {5, 0.5 * Math.PI, 0}, {5, 0, 0},
                {-5, Math.PI, 0}, {0, 0, 5},
                {0, Math.PI, 0}, {0, 0, 0},
                {5, Math.PI, 0}, {0, 0, -5},
                {-5, 1.5 * Math.PI, 0}, {5, 0, 0},
                {0, 1.5 * Math.PI, 0}, {0, 0, 0},
                {5, 1.5 * Math.PI, 0}, {-5, 0, 0},
                {-5, 2 * Math.PI, 0}, {0, 0, -5},
                {0, 2 * Math.PI, 0}, {0, 0, 0},
                {5, 2 * Math.PI, 0}, {0, 0, 5},
                {-5, 3 * Math.PI, 0}, {0, 0, 5},
                {0, 3 * Math.PI, 0}, {0, 0, 0},
                {5, 3 * Math.PI, 0}, {0, 0, -5},
                {-5, 0, Math.PI}, {0, 0, -5},
                {0, 0, 1.5 * Math.PI}, {0, 0, 0},
                {5, 0, 2 * Math.PI}, {0, 0, 5},
                {5, 0, 3 * Math.PI}, {0, 0, 5},
                {-5, Math.PI, Math.PI}, {0, 0, 5},
                {-5, 0.5 * Math.PI, -3 * Math.PI}, {5, 0, 0},
                {-5, 0.5 * Math.PI, 0.5 * Math.PI}, {0, -5, 0},
                {5, 0.25 * Math.PI, 0.25 * Math.PI}, {2.5, 2.5, 3.5355339059327373},
                {5, 02.5 * Math.PI, -0.75 * Math.PI}, {-3.5355339059327373, -3.5355339059327373, 0}
        };

        cartesianToSphericalCases = new double[][]{
                {2.5, 2.5, 3.5355339059327373}, {5, 0.25 * Math.PI, 0.25 * Math.PI},
                {0, 0, 0}, {0, 0, 0},
                {0, 0, -5}, {5, 0, Math.PI},
                {0, 0, 5}, {5, 0, 0},
                {0, -5, 0}, {5, -0.5*Math.PI, 0.5*Math.PI},
                {0, 5, 0}, {5, 0.5*Math.PI, 0.5*Math.PI},
                {-5, 0, 0}, {5, Math.PI, 0.5*Math.PI},
                {5, 0, 0}, {5, 0, 0.5*Math.PI}
        };
    }

    @Test
    public void testApply_floatArr_floatArr() {
        System.out.println("apply(float[], float[])");
        SphericalToCartesianTransform instance = new SphericalToCartesianTransform();
        final float[] source = new float[instance.numSourceDimensions()];
        final float[] target = new float[instance.numTargetDimensions()];
        final float[] truth = new float[instance.numTargetDimensions()];
        for (int i = 0; i < sphericalToCartesianCases.length; i += 2) {
            for (int j = 0; j < instance.numSourceDimensions(); ++j) {
                source[j] = (float) sphericalToCartesianCases[i][j];
                truth[j] = (float) sphericalToCartesianCases[i + 1][j];
            }
            instance.apply(source, target);
            Assert.assertArrayEquals(truth, target, PREC_FLOAT);
        }
    }

    @Test
    public void testApply_doubleArr_doubleArr() {
        System.out.println("apply(double[], double[])");
        SphericalToCartesianTransform instance = new SphericalToCartesianTransform();
        final double[] source = new double[instance.numSourceDimensions()];
        final double[] target = new double[instance.numTargetDimensions()];
        final double[] truth = new double[instance.numTargetDimensions()];
        for (int i = 0; i < sphericalToCartesianCases.length; i += 2) {
            for (int j = 0; j < instance.numSourceDimensions(); ++j) {
                source[j] = sphericalToCartesianCases[i][j];
                truth[j] = sphericalToCartesianCases[i + 1][j];
            }
            instance.apply(source, target);
            Assert.assertArrayEquals(truth, target, PREC_DOUBLE);
        }
    }

    @Test
    public void testApply_RealLocalizable_RealPositionable() {
        System.out.println("apply(RealLocalizable, RealPositionable)");
        SphericalToCartesianTransform instance = new SphericalToCartesianTransform();
        final RealLocalizable source = new RealPoint(instance.numSourceDimensions());
        final RealPositionable target = new RealPoint(instance.numTargetDimensions());
        final double[] targetArray = new double[instance.numTargetDimensions()];
        for (int i = 0; i < sphericalToCartesianCases.length; i += 2) {
            ((RealPoint) source).setPosition(sphericalToCartesianCases[i]);
            instance.apply(source, target);
            ((RealPoint) target).localize(targetArray);
            Assert.assertArrayEquals(sphericalToCartesianCases[i + 1], targetArray, PREC_DOUBLE);
        }
    }

    @Test
    public void testApplyInverse_floatArr_floatArr() {
        System.out.println("applyInverse(float[], float[])");
        SphericalToCartesianTransform instance = new SphericalToCartesianTransform();
        final float[] source = new float[instance.numSourceDimensions()];
        final float[] target = new float[instance.numTargetDimensions()];
        final float[] truth = new float[instance.numSourceDimensions()];
        for (int i = 0; i < cartesianToSphericalCases.length; i += 2) {
            for (int j = 0; j < instance.numSourceDimensions(); ++j) {
                target[j] = (float) cartesianToSphericalCases[i][j];
                truth[j] = (float) cartesianToSphericalCases[i + 1][j];
            }
            instance.applyInverse(source, target);
            Assert.assertArrayEquals(truth, source, PREC_FLOAT);
        }
    }

    @Test
    public void testApplyInverse_doubleArr_doubleArr() {
        System.out.println("applyInverse(double[], double[])");
        SphericalToCartesianTransform instance = new SphericalToCartesianTransform();
        final double[] source = new double[instance.numSourceDimensions()];
        final double[] target = new double[instance.numTargetDimensions()];
        final double[] truth = new double[instance.numSourceDimensions()];
        for (int i = 0; i < cartesianToSphericalCases.length; i += 2) {
            for (int j = 0; j < instance.numSourceDimensions(); ++j) {
                target[j] = cartesianToSphericalCases[i][j];
                truth[j] = cartesianToSphericalCases[i + 1][j];
            }
            instance.applyInverse(source, target);
            Assert.assertArrayEquals(truth, source, PREC_DOUBLE);
        }
    }

    @Test
    public void testApplyInverse_RealPositionable_RealLocalizable() {
        System.out.println("applyInverse(RealLocalizable, RealPositionable)");
        SphericalToCartesianTransform instance = new SphericalToCartesianTransform();
        final RealPositionable source = new RealPoint(instance.numSourceDimensions());
        final RealLocalizable target = new RealPoint(instance.numTargetDimensions());
        final double[] sourceArray = new double[instance.numTargetDimensions()];
        for (int i = 0; i < cartesianToSphericalCases.length; i += 2) {
            ((RealPoint) target).setPosition(cartesianToSphericalCases[i]);
            instance.applyInverse(source, target);
            ((RealPoint) source).localize(sourceArray);
            Assert.assertArrayEquals(cartesianToSphericalCases[i + 1], sourceArray, PREC_DOUBLE);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import numpy as np
from citysim3d.spaces import Space
import citysim3d.utils.transformations as tf

class AxisAngleSpace(Space):
    """
    SO(3) space where the rotation is represented as an axis-angle vector in
    R^3 where its magnitude is constrained within an interval and the axis can
    optionally be constrained. If the axis is not constrained, then the
    absolute value of low and high should be equal to each other.
    """
    def __init__(self, low, high, axis=None):
        """
        TODO: handle angle wrap-around
        """
        self.low = np.squeeze(low)[None]
        self.high = np.squeeze(high)[None]
        if self.low.shape != (1,) or self.high.shape != (1,):
            raise ValueError("low and high should each contain a single number or be a single number")
        self.axis = axis / np.linalg.norm(axis) if axis is not None else None
        if self.axis is None:
            assert -self.low == self.high

    def sample(self):
        if self.axis is None:
            axis_angle = tf.axis_angle_from_matrix(tf.random_rotation_matrix())
            axis, angle = tf.split_axis_angle(axis_angle)
            if not (self.low <= angle <= self.high):
                # rescale angle from [-pi, pi) to [-low_angle, high_angle)
                angle = self.low + (self.high - self.low) * (angle + np.pi) / (2 * np.pi)
            return angle * axis
        else:
            angle = np.random.uniform(low=self.low, high=self.high, size=self.shape)
            return angle

    def contains(self, x):
        angle = np.linalg.norm(x)
        return x.shape == self.shape and (self.low <= angle <= self.high)

    def clip(self, x, out=None):
        assert x.shape == self.shape
        if self.axis is None:
            axis, angle = tf.split_axis_angle(x)
            x_clipped = np.clip(angle, self.low, self.high) * axis
        else:
            x_clipped = np.clip(x, self.low, self.high)
        if out is not None:
            out[:] = x_clipped
            x_clipped = out
        return x_clipped

    @property
    def shape(self):
        """
        shape of data that this space handles
        """
        if self.axis is None:
            return (3,)
        else:
            return (1,)


text:
import socket
import json
from threading import Thread, Lock
from port_scanner import PortScanner

class PortScanPlugin:
    def __init__(self):
        self.host = None
        self.port = None
        self.pollInterval = None
        self.source = socket.gethostname()
        self.result = None
        self.response = None
        self.config = None

    def parse_configuration(self):
        with open('param.json') as f:
            self.config = json.load(f)

    def execute(self):
        self.parse_configuration()
        self.run()

    def run(self):
        stdoutmutex = Lock()  # same as thread.allocate_lock()

        threads = []
        config_items = self.config['items']
        print(len(config_items))
        for item in config_items:
            host = item['host']
            port = item['port']
            source = item['source']
            if len(source) == 0:
                source = host
            interval = item['pollInterval']

            print(host)
            p = PortScanner(host=host,
                            port=port,
                            source=source,
                            interval=interval,
                            mutex=stdoutmutex)
            thread = Thread(target=p.scan_port())
            threads.append(thread)

        for thread in threads:
            thread.start()

        for thread in threads:
            thread.join()  # wait for thread exits

if __name__ == "__main__":
    p = PortScanPlugin()
    p.execute()


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from third_party.baselines.bench.monitor import *


text:
/** Defines $.fn.jsonapi() for adding triggers to elements to send form data to
 *    JsonApi actions.
 *
 * @param Object $options
 *
 *  Standard Options:
 *  - url:                    URL to send Ajax request to.  If not specified,
 *                             the action of the [parent] form will be used.
 *
 *                             For non-form-related elements, this option needs
 *                             to be set explicitly.
 *
 *                            This option can be a function that returns a URL.
 *                             The function will be executed after the
 *                             pre_execute() hook (see below).
 *
 *                            Parameters:
 *                             - jQuery $element Element that triggered the
 *                                jsonapi call.
 *
 *                            If the function returns (bool) false, the Ajax
 *                              request will not fire.  Note that post_execute()
 *                              will still be executed if url() returns false
 *                              (see below).
 *
 *  Hooks:
 *  - pre_execute:            Runs as soon as the plugin is triggered.
 *                             Return (bool) false to cancel the Ajax request.
 *                             Note that post_execute() will still be executed
 *                             if pre_execute() returns false (see below).
 *
 *                             Parameters:
 *                              - jQuery $element Element that triggered the
 *                                 jsonapi call.
 *                              - Event  $event   Event that triggered the
 *                                 jsonapi call.
 *
 *  - before_send:            Runs immediately before sending the ajax request.
 *                              This method has the same signature and purpose
 *                              as jQuery's `beforeSend` handler.
 *                            @see http://api.jquery.com/Ajax_Events/
 *
 *  - success:                Runs when Ajax response has status of 'ok'.
 *                             Return value is ignored.
 *
 *                             Parameters:
 *                              - Object $res     Result object from Ajax call.
 *                              - jQuery $element Element that triggered the
 *                                 jsonapi call.
 *                              - Object $data    Data that were sent to remote.
 *
 *  - failure:                Runs when Ajax response has status of 'fail'.
 *                             Return value is ignored.
 *
 *                             Parameters:
 *                              - Object $res     Result object from Ajax call.
 *                              - jQuery $element Element that triggered the
 *                                 jsonapi call.
 *                              - Object $data    Data that were sent to remote.
 *
 *  - error:                  Runs when Ajax response is not decipherable or has
 *                             an invalid status value.  Return value is
 *                             ignored.
 *
 *                             Parameters:
 *                              - Error          $err     Exception that was
 *                                 thrown.
 *                              - jQuery         $element Element that triggered
 *                                 the jsonapi call.
 *                              - Object         $data    Data that were sent to
 *                                 remote.
 *                              - XMLHttpRequest $xhr     XMLHttpRequest object
 *                                 created during the request.
 *
 *  - post_execute:           Runs upon completion of Ajax request regardless of
 *                             status.  Return value is ignored.
 *
 *                             Note that post_execute() ALWAYS runs, regardless
 *                              of whether the result of the Ajax call was
 *                              success(), failure() or error(), or if
 *                              pre_execute() returned false to prevent the Ajax
 *                              call from firing.
 *
 *                             Parameters:
 *                              - jQuery      $element Element that triggered
 *                                 the jsonapi call.
 *                              - Object|null $data    Data that were sent to
 *                                 remote, or null if called as a result of
 *                                 pre_execute() returning false (see above).
 *                              - String      $from    Name of the method that
 *                                 invoked post_execute():
 *                                  - "pre_execute"
 *                                  - "url"
 *                                  - "data"
 *                                  - "cached"
 *                                  - "success"
 *                                  - "failure"
 *                                  - "error"
 *
 *  Advanced Options:
 *  - async:                  If true (default), the Ajax request will be
 *                             asynchronous.
 *
 *                             Note that synchronous ajax (sjax?) on the main
 *                              thread is not allowed in modern browsers.
 *
 *  - cache_key:              Specifies the key to use when determining whether
 *                             to make an ajax request or use locally-cached
 *                             response data.
 *
 *                             You can pass a function here; it will be
 *                              evaluated immediately before sending the Ajax
 *                              request and should return a string or (bool)
 *                              false.
 *
 *                             Parameters:
 *                              - String $url   The request URL.
 *                              - Object $data  The request data.
 *
 *                             If the function returns (bool) false, the
 *                              response data will not be cached.
 *
 *                             Note that by default, responses are NOT cached.
 *                              If you want to use caching, you MUST specify a
 *                              function for this option.
 *
 *                             Note also that only success responses are cached;
 *                              failure responses are never cached.
 *
 *  - cached:                 Runs when using a cached response instead of
 *                             making an ajax call (see `cache_key` above).
 *
 *                            By default, this just invokes the success() hook.
 *
 *  - data:                   Data to send with the HTTP request, specified as
 *                             a key/value object, query string or function that
 *                             returns same.
 *
 *                             If not specified, the element's parent form (or
 *                              the element itself, if it is a form) will be
 *                              serialize()'d, and the result will be used as
 *                              the value of this option.
 *
 *                             You can pass a function here; it will be
 *                              evaluated immediately before sending the Ajax
 *                              request and should return an object or query
 *                              string.
 *
 *                             Parameters:
 *                              - jQuery $element Element that triggered the
 *                                 jsonapi call.
 *
 *                             If the function returns (bool) false, the Ajax
 *                              request will not fire.  Note that post_execute()
 *                              will still be executed even if $data() returns
 *                              false.
 *
 *                             Note that $data will not be evaluated if
 *                              pre_execute() returns false.
 *
 *  - jsonp:                  Whether to send the request using JSONP.  Default
 *                              is null (auto-detect).
 *
 *  - method:                 HTTP request method.  Default is 'post' (or auto-
 *                              detected if the element is a form).
 *
 *  - return:                 Return value after event handler fires.  Default
 *                             is false to prevent default event handler from
 *                             firing after jsonapi.
 *
 *                             Note that if you instruct jsonapi to return true,
 *                              the default event handler will likely fire
 *                              *before* the Ajax call returns.  Watch out for
 *                              race conditions!
 *
 *                             Consider whether you can implement the desired
 *                              functionality in post_execute before relying on
 *                              this option.
 *
 * - traditional:            Set this to true if you wish to use the traditional
 *                              style of param serialization.
 *
 *                              See http://api.jquery.com/jQuery.param/ for more
 *                                info.
 *
 * - trigger:                Specify the event to listen for.
 *                             Defaults:
 *                              - forms:            'submit'
 *                              - select boxes:     'change'
 *                              - textual inputs:   'change'
 *                              - everything else:  'click'
 *
 *                             You may specify a
 *                              space-delimited list of events if more than one
 *                              event can trigger the Ajax call.
 *
 * Note that $.fn.jsonapi() is a wrapper for $.jsonapi(), which you can use to
 *  make JsonApi calls outside the context of an HTML element.  The parameters
 *  and behavior of $.jsonapi() are identical to those of $.fn.jsonapi(), sans
 *  anything related to HTML elements.
 *
 * @author Phoenix Zerin <phoenix@todofixthis.com>
 *
 * @package sfJwtJsonApiPlugin
 * @subpackage web
 */
(function( $ ) {
  /** Caches response data locally.  See `cache_key` documentation above. */
  var cache = {};

  /** $.jsonapi() for making an ad-hoc JsonApi request.
   *
   * Also leveraged by $.fn.jsonapi() below.
   */
  $.extend({'jsonapi': function( $options ) {
    //noinspection AssignmentToFunctionParameterJS
    $options = $.extend(
      {
        /* Standard Options */
        'url':                    '',

        /* Hooks */
        'pre_execute':            null,
        'before_send':            null,
        'success':                null,
        'failure':                null,
        'error':                  null,
        'post_execute':           null,

        /* Advanced Options */
        'async':                  true,
        'cache_key':              false,
        'cached':                 null,
        'data':                   null,
        'jsonp':                  null,
        'method':                 'post',
        'traditional':            false
      },
      ($options || {})
    );

    var $data;

    /** Executes the post-execute handler.
     *
     * @param $data Object
     * @param $from String
     *
     * @return void
     */
    function _postExecute( $data, $from ) {
      if( typeof($options.post_execute) == 'function' ) {
        $options.post_execute($data, $from);
      }
    }

    /** Handle an exception from the Ajax call.
     *
     * @param $err  Error
     * @param $xhr  XMLHttpRequest
     *
     * @return Boolean
     */
    function _handleException( $err, $xhr ) {
      if( typeof($options.error) == 'function' ) {
        if( typeof($err.constructor) == 'undefined' || $err.constructor != Error ) {
          //noinspection AssignmentToFunctionParameterJS
          $err = new Error($err);
        }

        /* $err is kind of like $res, so it goes before $data. */
        $options.error($err, $data, $xhr);
      }

      _postExecute($data, 'error');
    }

    try
    {
      /* Call pre_execute hook.  Use return value to determine whether to
       *  continue.
       */
      if( typeof($options.pre_execute) == 'function' ) {
        if( $options.pre_execute() === false ) {
          return _postExecute(null, 'pre_execute');
        }
      }

      while( typeof($options.url) == 'function' ) {
        $options.url = $options.url()
      }

      /* The only value in $options that *must* have a value is url. */
      if( $options.url === false ) {
        return _postExecute(null, 'url');
      } else {
        //noinspection EqualityComparisonWithCoercionJS
        if( $options.url == '' ) {
          return _handleException('url option not set.', null);
        }
      }

      $data = $options.data;
      while( typeof($data) == 'function' ) {
        $data = $data();
      }

      if( $data === false ) {
        return _postExecute(null, 'data');
      }
    }
    catch( $err ) {
      return _handleException($err, null);
    }

    if( ! ($options.jsonp || ($options.jsonp === false)) )
    {
      /* Check to see if we should use jsonp (for cross-domain request). */
      var $target = $(document.createElement('a'))
        .prop('href', $options.url)
        .get(0)
        .hostname;

      $options.jsonp = ($target !== location.hostname);
    }

    /* Check to see if we are using the cache. */
    var cache_key = null;
    if( typeof($options.cache_key) == 'function' ) {
        cache_key = $options.cache_key($options.url, $data);
    }

    /* Check for cache hit. */
    if( cache_key && cache.hasOwnProperty(cache_key) ) {
      try {
        /* Prefer the 'cached' handler, but fall back on 'success'. */
        if( typeof($options.cached) == 'function' ) {
            $options.cached(cache[cache_key], $data);
        } else if( typeof($options.success) == 'function' ) {
            $options.success(cache[cache_key], $data);
        }

        /* Else raise exception?  This would be a pretty weird case.
         *
         *  Ehhhh, we'll assume the developer knows what he's doing.  That's
         *      usually a safe assumption.
         *
         *  Usually.
         */

        return _postExecute($data, 'cached');
      } catch( $err ) {
        return _handleException($err, null);
      }
    }

    //noinspection JSUnusedLocalSymbols
    $.ajax({
      'async':        $options.async,
      'type':         $options.method,
      'url':          $options.url,

      'data':         $data,
      'dataType':     ($options.jsonp ? 'jsonp' : 'json'),
      'traditional':  $options.traditional,
      'beforeSend':   $options.before_send,

      // https://bugs.jquery.com/ticket/12326
      'contentType':  'application/json',

      'success':  function( $res, $status, $xhr ) {
        try {
          if( typeof($res.status) != 'undefined' ) {
            if( $res.status == 'ok' ) {
              if( typeof($options.success) == 'function' ) {
                $options.success($res.detail, $data);
              }

              /* If we are caching, store the result in the local cache. */
              if( cache_key ) {
                  cache[cache_key] = $res.detail;
              }
            }
            /* Allow 200 failures if the request uses JSONP. */
            else if( $res.status == 'fail' ) {
              if( typeof($options.failure) == 'function' ) {
                $options.failure($res.detail, $data);
              }
            }

            _postExecute($data, 'success');
          } else {
            //noinspection ExceptionCaughtLocallyJS
            throw new Error('Malformed success response from server.');
          }
        } catch( $err ) {
          _handleException($err, $xhr);
        }
      },

      'error':    function( $xhr, $status, $exc ) {
        try {
          if($.inArray($xhr.status, [200, 400]) === -1) {
            //noinspection ExceptionCaughtLocallyJS
            throw new Error(
              'XmlHttpRequest received ' + $xhr.status + ' response from server (jQuery says: ' + $status + ').'
            );
          }

          var $res = $.parseJSON($xhr.responseText);

          if( ! $res ) {
            //noinspection ExceptionCaughtLocallyJS
            throw new Error('No response from server.');
          }

          if( typeof($res.status) != 'undefined' && $res.status == 'fail' ) {
            if( typeof($options.failure) == 'function' ) {
              $options.failure($res.detail, $data);
            }

            _postExecute($data, 'failure');
          } else {
            //noinspection ExceptionCaughtLocallyJS
            throw new Error('Malformed error response from server.');
          }
        } catch( $err ) {
          _handleException($err, $xhr);
        }
      }
    });
  }});

  /** $.fn.jsonapi() for adding JsonApi triggers to object events.
   *
   * See document docblock for more information.
   */
  $.extend($.fn, {'jsonapi': function( $options ) {
    //noinspection AssignmentToFunctionParameterJS
    $options = $.extend(
      {
        /* Standard Options */
        'url':                    '',

        /* Hooks */
        'pre_execute':            null,
        'before_send':            null,
        'success':                null,
        'failure':                null,
        'error':                  null,
        'post_execute':           null,

        /* Advanced Options */
        'async':                  true,
        'cache_key':              false,
        'cached':                 null,
        'data':                   null,
        'method':                 null,
        'return':                 false,
        'traditional':            false,
        'trigger':                ''
      },
      ($options || {})
    );

    /** Executes the post-execute handler.
     *
     * @param $data Object
     * @param $from String
     *
     * @return void
     */
    function _postExecute( $data, $from ) {
      if( typeof($options.post_execute) == 'function' ) {
        $options.post_execute($data, $from);
      }
    }

    /* Could be called on multiple elements, and the default behavior will be
     *  slightly different depending on each element.
     */
    $(this).each(function(  ) {
      var $this     = $(this);
      var $tagName  = String(this.tagName).toLowerCase();

      var $trigger;
      if( $options.trigger ) {
        //noinspection JSUnusedAssignment
        $trigger = $options.trigger;
      } else {
        switch( $tagName )
        {
          case 'form':
            $trigger = 'submit';
          break;

          case 'select':
          case 'textarea':
            $trigger = 'change';
          break;

          case 'input':
            switch( $this.prop('type') ) {
              case 'text':
              case 'password':
                $trigger = 'change';
              break;

              default:
                $trigger = 'click';
              break;
            }
          break;

          default:
            $trigger = 'click';
          break;
        }
      }

      $this.on($trigger, function( $event ) {
        /* Call pre_execute hook.  Use return value to determine whether to
         *  continue.
         *
         * We have to duplicate a little code here to avoid calling
         *  $options.data() if pre_execute() returns false.
         */
        if( typeof($options.pre_execute) == 'function' ) {
          if( $options.pre_execute($this, $event) === false ) {
            _postExecute(null, 'pre_execute');
            return $options.return;
          }
        }

        /* URL could be different for each element in the selector.  Create
         *  local variable to determine.
         */
        var $url = $options.url;
        while( typeof($url) == 'function' ) {
          $url = $url($this);
        }

        /* Last-ditch effort to determine a default value for $options.url. */
        if( (! $url) && ($url !== false) ) {
          if( $tagName == 'form' ) {
            $url = $this.prop('action');
          }
          else if( $tagName == 'a' ) {
            $url = $this.prop('href');
          } else {
            $url = $this.parents('form:first').prop('action');
          }
        }

        /* Double-check to see if we know how we are sending the data. */
        var $method = $options.method;
        if( (! $method) && ($tagName === 'form') )
        {
          $method = $this.prop('method');
        }

        /* Post by default. */
        if( ! $method )
        {
          $method = 'post';
        }

        /* Same goes for the request data. */
        var $data = $options.data;
        while( typeof($data) == 'function' ) {
          $data = $data($this);
        }

        if( ! $data ) {
          if( $data === false ) {
            return _postExecute(null, 'data');
          } else if( $tagName == 'form' ) {
            $data = $this.serialize();
          } else {
            $data = $this.parents('form:first').serialize();
          }
        }

        $.jsonapi($.extend(
          {},
          $options,
          {
            'url':          $url,
            'data':         $data,
            'method':       $method,
            'traditional':  $options.traditional,

            'pre_execute':  null, // If it's defined, we already called it!

            'success':      function( $res, $data ) {
              if( typeof($options.success) == 'function' ) {
                return $options.success($res, $this, $data);
              }
            },

            'failure':      function( $res, $data ) {
              if( typeof($options.failure) == 'function' ) {
                return $options.failure($res, $this, $data);
              }
            },

            'error':        function( $err, $data, $xhr ) {
              if( typeof($options.error) == 'function' ) {
                return $options.error($err, $this, $data, $xhr);
              }
            },

            'post_execute': function( $data, $from ) {
              if( typeof($options.post_execute) == 'function' ) {
                $options.post_execute($this, $data, $from);
              }
            },

            'cache_key':    $options.cache_key,
            'cached':       $options.cached
          }
        ));

        return $options['return'];
      });
    });

    return this;
  }});
})(jQuery);


text:
package softuni.dto.binding.Add;

import com.google.gson.annotations.Expose;

public class CategoryAddDto {
    @Expose
    private String name;

    public CategoryAddDto() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
layout: post
title:  "dzen2 och infopanel"
date:   2016-02-09 18:05:59 +0200
tags:
    - dzen2
    - rss
    - Arch Linux
categories: jekyll update
---
Jag har nu grejat lite mer med dzen2 och kommit till en fas då denna panel är färdig. Känner jag mig själv rätt kommer det dock någon ändring lite då och då. Den visar nyheter från Arch Linux hemsida om det hänt något inom den senaste månaden.

![](/images/info.png)


text:
namespace hawkeye
{

PhysicsSocketConstraint::PhysicsSocketConstraint(PhysicsRigidBody* a, PhysicsRigidBody* b)
    : PhysicsConstraint(a, b)
{
    GP_ASSERT(a && a->_body && a->getNode());
    if (b)
    {
        GP_ASSERT(b->_body && b->getNode());
        Vector3 origin = centerOfMassMidpoint(a->getNode(), b->getNode());
        btTransform frameInA = getTransformOffset(a->getNode(), origin);
        btTransform frameInB = getTransformOffset(b->getNode(), origin);

        _constraint = bullet_new<btPoint2PointConstraint>(*a->_body, *b->_body, frameInA.getOrigin(), frameInB.getOrigin());
    }
    else
    {
        _constraint = bullet_new<btPoint2PointConstraint>(*a->_body, btVector3(0.0f, 0.0f, 0.0f));
    }
}

PhysicsSocketConstraint::PhysicsSocketConstraint(PhysicsRigidBody* a, const Vector3& translationOffsetA,
                                                 PhysicsRigidBody* b, const Vector3& translationOffsetB)
    : PhysicsConstraint(a, b)
{
    GP_ASSERT(a && a->_body && a->getNode());

    // Take scale into account for the first node's translation offset.
    Vector3 sA;
    a->getNode()->getWorldMatrix().getScale(&sA);
    Vector3 tA(translationOffsetA.x * sA.x, translationOffsetA.y * sA.y, translationOffsetA.z * sA.z);

    if (b)
    {
        GP_ASSERT(b->_body && b->getNode());

        // Take scale into account for the second node's translation offset.
        Vector3 sB;
        b->getNode()->getWorldMatrix().getScale(&sB);
        Vector3 tB(translationOffsetB.x * sB.x, translationOffsetB.y * sB.y, translationOffsetB.z * sB.z);

        _constraint = bullet_new<btPoint2PointConstraint>(*a->_body, *b->_body, BV(tA), BV(tB));
    }
    else
    {
        _constraint = bullet_new<btPoint2PointConstraint>(*a->_body, BV(tA));
    }
}

PhysicsSocketConstraint::~PhysicsSocketConstraint()
{
    // Used
}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="format-detection" content="telephone=no, email=no"/>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">

    <title>vue2-demo</title>

    <div id="initData" csrf="<?=Yii::$app->getRequest()->getCsrfToken();?>">


text:
"""
Tests for forms/util.py module.
"""

tests = r"""
>>> from django.forms.util import *
>>> from django.core.exceptions import ValidationError
>>> from django.utils.translation import ugettext_lazy

###########
# flatatt #
###########

>>> from django.forms.util import flatatt
>>> flatatt({'id': "header"})
u' id="header"'
>>> flatatt({'class': "news", 'title': "Read this"})
u' class="news" title="Read this"'
>>> flatatt({})
u''

###################
# ValidationError #
###################

# Can take a string.
>>> print ErrorList(ValidationError("There was an error.").messages)

There was an error.

# Can take a unicode string.
>>> print ErrorList(ValidationError(u"Not \u03C0.").messages)

Not π.

# Can take a lazy string.
>>> print ErrorList(ValidationError(ugettext_lazy("Error.")).messages)

Error.

# Can take a list.
>>> print ErrorList(ValidationError(["Error one.", "Error two."]).messages)

Error one.

Error two.

# Can take a mixture in a list.
>>> print ErrorList(ValidationError(["First error.", u"Not \u03C0.", ugettext_lazy("Error.")]).messages)

First error.

Not π.

Error.

>>> class VeryBadError:
...     def __unicode__(self): return u"A very bad error."

# Can take a non-string.
>>> print ErrorList(ValidationError(VeryBadError()).messages)

A very bad error.

# Escapes non-safe input but not input marked safe.
>>> example = 'Example of link: example'
>>> print ErrorList([example])

Example of link: <a href="http://www.example.com/">example</a>

>>> print ErrorList([mark_safe(example)])

Example of link: example

"""


text:
/* DO NOT EDIT: Automatically generated from IMutableKernel.idl by idl */

#ifndef IMutableKernel_FWD_DEFINED
# define IMutableKernel_FWD_DEFINED
typedef struct IMutableKernel IMutableKernel;
#endif

#ifndef IMUTABLEKERNEL_H_IDL_
# define IMUTABLEKERNEL_H_IDL_

/* Odin: The Talisker nanokernel */

/* Copyright 2017 Mo McRoberts.
 *
 *  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.
 */
# include <Odin/IKernel.h>
# include <Odin/IMutableTask.h>
# include <Odin/IConsole.h>

/* IMutableKernel version 0.0 */

# ifndef __IMutableKernel_INTERFACE_DEFINED__
#  define __IMutableKernel_INTERFACE_DEFINED__
#ifndef W_NO_UNSTABLE_INTERFACES
# warning The IMutableKernel interface is currently considered unstable; source and binary compatibility is not assured.
#endif
#  undef INTEFACE
#  define INTERFACE IMutableKernel

DECLARE_INTERFACE_(IMutableKernel, IKernel)
{
	BEGIN_INTERFACE

# if !defined(__cplusplus)
# if !defined(__cplusplus)
	/* IObject */
	STDMETHOD_(int, queryInterface)(THIS_ const uuid_t riid, void **object) PURE;
	STDMETHOD_(int32_t, retain)(THIS) PURE;
	STDMETHOD_(int32_t, release)(THIS) PURE;
# endif /*!__cplusplus*/

	/* IKernel */
	STDMETHOD_(int, mm)(THIS_ IMemoryManager **intf) PURE;
	STDMETHOD_(int, allocator)(THIS_ IAllocator **intf) PURE;
	STDMETHOD_(void*, alloc)(THIS_ size_t nbytes) PURE;
	STDMETHOD_(int, free)(THIS_ void *ptr) PURE;
# endif /*!__cplusplus*/

	/* IMutableKernel */
	STDMETHOD_(int, panic)(THIS_ const char *message) PURE;
	STDMETHOD_(int, console)(THIS_ IConsole **cons) PURE;
	STDMETHOD_(int, createTask)(THIS_ IMutableTask **task) PURE;

	END_INTERFACE
};

#  if !defined(__cplusplus)
#   define IMutableKernel_queryInterface(__this, riid, object) __this->lpVtbl->queryInterface(__this, riid, object)
#   define IMutableKernel_retain(__this) __this->lpVtbl->retain(__this)
#   define IMutableKernel_release(__this) __this->lpVtbl->release(__this)
#   define IMutableKernel_mm(__this, intf) __this->lpVtbl->mm(__this, intf)
#   define IMutableKernel_allocator(__this, intf) __this->lpVtbl->allocator(__this, intf)
#   define IMutableKernel_alloc(__this, nbytes) __this->lpVtbl->alloc(__this, nbytes)
#   define IMutableKernel_free(__this, ptr) __this->lpVtbl->free(__this, ptr)
#   define IMutableKernel_panic(__this, message) __this->lpVtbl->panic(__this, message)
#   define IMutableKernel_console(__this, cons) __this->lpVtbl->console(__this, cons)
#   define IMutableKernel_createTask(__this, task) __this->lpVtbl->createTask(__this, task)
#  endif /*!__cplusplus*/
#  undef INTERFACE
# endif /*!__IMutableKernel_INTERFACE_DEFINED__*/

/* IID_IMutableKernel = {876d8caf-8434-41e0-ab38-256dabb2d8dc} */
UUID_DEFINE(IID_IMutableKernel, 0x87, 0x6d, 0x8c, 0xaf,  0x84, 0x34, 0x41, 0xe0, 0xab, 0x38, 0x25, 0x6d, 0xab, 0xb2, 0xd8, 0xdc);

#endif /*!IMUTABLEKERNEL_H_IDL_*/


text:
@class ImageContentView;
@class ContentScrollView;
@protocol ContentScrollViewDelegate <UIScrollViewDelegate>

- (void)headerScroll:(ContentScrollView *)scroll didSelectItemAtIndex:(NSInteger)index;
- (void)headerScroll:(ContentScrollView *)scroll didClose:(BOOL)close;

@end

@interface ContentScrollView : UIScrollView

@property (nonatomic ,assign ,readonly) NSInteger currentIndex;

- (void)setCurrentIndex:(NSInteger)currentIndex;

- (instancetype)initWithFrame:(CGRect)frame imageArray:(NSArray *)imageArray index:(NSInteger)index;

@end


text:
package x0961h.aoc16.day09;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by 0x0961h on 09.12.16.
 */
public class DaySolverAdvanced {
    public static void main(String[] args) throws IOException {
        String input = new String(Files.readAllBytes(Paths.get("src/main/resources/day09", "data.txt")));
        System.out.println("Result = " + solve(input));
    }

    private static List<MultiplierStruct> multipliers;

    public static long solve(String input) {
        long length = 0;
        multipliers = new LinkedList<>();

        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);

            if (ch == '(') {
                String instructions = input.substring(i + 1, input.indexOf(')', i));
                String[] spl = instructions.split("x");
                i += instructions.length() + 1;

                int blockSize = Integer.parseInt(spl[0]);
                int repeatTimes = Integer.parseInt(spl[1]);

                decMultipliers(instructions.length() + 2);
                multipliers.add(new MultiplierStruct(blockSize, repeatTimes));
            } else {
                Integer mlt = getMultiplier();
                length += mlt;

                decMultipliers();
            }
        }

        return length;
    }

    private static void decMultipliers(int i) {
        multipliers = multipliers.stream().
                map(m -> {
                    m.dec(i);
                    return m;
                }).
                filter(m -> !m.done()).
                collect(Collectors.toList());
    }

    private static void decMultipliers() {
        decMultipliers(1);
    }

    private static Integer getMultiplier() {
        return multipliers.stream().
                map(m -> m.multiplier).
                collect(Collectors.toList()).
                stream().
                reduce((i, j) -> i * j).
                orElseGet(() -> 1);
    }

    private static class MultiplierStruct {
        final int multiplier;
        int charsLeft;

        MultiplierStruct(int charsLeft, int multiplier) {
            this.multiplier = multiplier;
            this.charsLeft = charsLeft;
        }

        void dec(int i) {
            charsLeft -= i;
            if (charsLeft < 0) throw new RuntimeException("charsLeft is negative");
        }

        boolean done() {
            return charsLeft == 0;
        }

        @Override
        public String toString() {
            return "(x" + multiplier +
                    ", " + charsLeft +
                    ")";
        }
    }
}


text:
 0">
        Status:


text:
package org.innovateuk.ifs.security;

import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.mapper.UserMapper;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class LoggedInUserSupplier {

    @Autowired
    private UserMapper userMapper;

    public User get() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserResource user = (UserResource) authentication.getDetails();
        return userMapper.mapToDomain(user);
    }
}


text:
package org.zstack.header.identity;

import org.springframework.http.HttpMethod;
import org.zstack.header.message.APIDeleteMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.rest.RestRequest;

/**
 * Created by frank on 7/9/2015.
 */
@Action(category = AccountConstant.ACTION_CATEGORY, accountOnly = true)
@RestRequest(
        path = "/accounts/groups/{uuid}",
        method = HttpMethod.DELETE,
        parameterName = "params",
        responseClass = APIDeleteUserGroupEvent.class
)
public class APIDeleteUserGroupMsg extends APIDeleteMessage implements AccountMessage {
    @APIParam(resourceType = UserGroupVO.class, checkAccount = true, operationTarget = true)
    private String uuid;

    @Override
    public String getAccountUuid() {
        return getSession().getAccountUuid();
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public static APIDeleteUserGroupMsg __example__() {
        APIDeleteUserGroupMsg msg = new APIDeleteUserGroupMsg();
        msg.setUuid(uuid());
        return msg;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@android:color/white"
              android:orientation="vertical">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <ImageView
            android:id="@+id/image"
            android:layout_width="185dp"
            android:layout_height="165dp"
            android:background="#ccc"
            android:scaleType="centerCrop"/>

        <ImageView
            android:id="@+id/selectedBg"
            android:layout_width="185dp"
            android:layout_height="165dp"
            android:orientation="vertical"
            android:scaleType="centerCrop"
            android:src="@drawable/blac_shadow_curtain">

        </ImageView>

        <TextView
            android:id="@+id/desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Mood"
            android:textColor="#fff"
            android:textSize="16sp"/>
    </FrameLayout>

</LinearLayout>


text:
package org.apache.orc;

import static org.junit.Assert.assertEquals;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class TestTypeDescription {
  @Rule
  public ExpectedException thrown= ExpectedException.none();

  @Test
  public void testJson() {
    TypeDescription bin = TypeDescription.createBinary();
    assertEquals("{\"category\": \"binary\", \"id\": 0, \"max\": 0}",
        bin.toJson());
    assertEquals("binary", bin.toString());
    TypeDescription struct = TypeDescription.createStruct()
        .addField("f1", TypeDescription.createInt())
        .addField("f2", TypeDescription.createString())
        .addField("f3", TypeDescription.createDecimal());
    assertEquals("struct<f1:int,f2:string,f3:decimal(38,10)>",
        struct.toString());
    assertEquals("{\"category\": \"struct\", \"id\": 0, \"max\": 3, \"fields\": [\n"
            + "  \"f1\": {\"category\": \"int\", \"id\": 1, \"max\": 1},\n"
            + "  \"f2\": {\"category\": \"string\", \"id\": 2, \"max\": 2},\n"
            + "  \"f3\": {\"category\": \"decimal\", \"id\": 3, \"max\": 3, \"precision\": 38, \"scale\": 10}]}",
        struct.toJson());
    struct = TypeDescription.createStruct()
        .addField("f1", TypeDescription.createUnion()
            .addUnionChild(TypeDescription.createByte())
            .addUnionChild(TypeDescription.createDecimal()
                .withPrecision(20).withScale(10)))
        .addField("f2", TypeDescription.createStruct()
            .addField("f3", TypeDescription.createDate())
            .addField("f4", TypeDescription.createDouble())
            .addField("f5", TypeDescription.createBoolean()))
        .addField("f6", TypeDescription.createChar().withMaxLength(100));
    assertEquals("struct<f1:uniontype<tinyint,decimal(20,10)>,f2:struct<f3:date,f4:double,f5:boolean>,f6:char(100)>",
        struct.toString());
    assertEquals(
        "{\"category\": \"struct\", \"id\": 0, \"max\": 8, \"fields\": [\n" +
            "  \"f1\": {\"category\": \"uniontype\", \"id\": 1, \"max\": 3, \"children\": [\n" +
            "    {\"category\": \"tinyint\", \"id\": 2, \"max\": 2},\n" +
            "    {\"category\": \"decimal\", \"id\": 3, \"max\": 3, \"precision\": 20, \"scale\": 10}]},\n" +
            "  \"f2\": {\"category\": \"struct\", \"id\": 4, \"max\": 7, \"fields\": [\n" +
            "    \"f3\": {\"category\": \"date\", \"id\": 5, \"max\": 5},\n" +
            "    \"f4\": {\"category\": \"double\", \"id\": 6, \"max\": 6},\n" +
            "    \"f5\": {\"category\": \"boolean\", \"id\": 7, \"max\": 7}]},\n" +
            "  \"f6\": {\"category\": \"char\", \"id\": 8, \"max\": 8, \"length\": 100}]}",
        struct.toJson());
  }

  @Test
  public void testParserSimple() {
    TypeDescription expected = TypeDescription.createStruct()
        .addField("b1", TypeDescription.createBinary())
        .addField("b2", TypeDescription.createBoolean())
        .addField("b3", TypeDescription.createByte())
        .addField("c", TypeDescription.createChar().withMaxLength(10))
        .addField("d1", TypeDescription.createDate())
        .addField("d2", TypeDescription.createDecimal().withScale(5).withPrecision(20))
        .addField("d3", TypeDescription.createDouble())
        .addField("fff", TypeDescription.createFloat())
        .addField("int", TypeDescription.createInt())
        .addField("l", TypeDescription.createList
            (TypeDescription.createLong()))
        .addField("map", TypeDescription.createMap
            (TypeDescription.createShort(), TypeDescription.createString()))
        .addField("str", TypeDescription.createStruct()
           .addField("u", TypeDescription.createUnion()
               .addUnionChild(TypeDescription.createTimestamp())
               .addUnionChild(TypeDescription.createVarchar()
                   .withMaxLength(100))));
    String expectedStr =
        "struct<b1:binary,b2:boolean,b3:tinyint,c:char(10),d1:date," +
            "d2:decimal(20,5),d3:double,fff:float,int:int,l:array<bigint>," +
            "map:map<smallint,string>,str:struct<u:uniontype<timestamp," +
            "varchar(100)>>>";
    assertEquals(expectedStr, expected.toString());
    TypeDescription actual = TypeDescription.fromString(expectedStr);
    assertEquals(expected, actual);
    assertEquals(expectedStr, actual.toString());
  }

  @Test
  public void testParserUpper() {
    TypeDescription type = TypeDescription.fromString("BIGINT");
    assertEquals(TypeDescription.Category.LONG, type.getCategory());
    type = TypeDescription.fromString("STRUCT<MY_FIELD:INT>");
    assertEquals(TypeDescription.Category.STRUCT, type.getCategory());
    assertEquals("MY_FIELD", type.getFieldNames().get(0));
    assertEquals(TypeDescription.Category.INT,
        type.getChildren().get(0).getCategory());
    type = TypeDescription.fromString("UNIONTYPE<STRING>");
    assertEquals(TypeDescription.Category.UNION, type.getCategory());
    assertEquals(TypeDescription.Category.STRING,
        type.getChildren().get(0).getCategory());
  }

  @Test
  public void testParserUnknownCategory() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Can't parse category at 'FOOBAR^'");
    TypeDescription.fromString("FOOBAR");
  }

  @Test
  public void testParserEmptyCategory() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Can't parse category at '^<int>'");
    TypeDescription.fromString("<int>");
  }

  @Test
  public void testParserMissingInt() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Missing integer at 'char(^)'");
    TypeDescription.fromString("char()");
  }

  @Test
  public void testParserMissingSize() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Missing required char '(' at 'struct<c:char^>'");
    TypeDescription.fromString("struct<c:char>");
  }

  @Test
  public void testParserExtraStuff() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Extra characters at 'struct<i:int>^,'");
    TypeDescription.fromString("struct<i:int>,");
  }
}


text:
local addonName, ns, _ = ...
local DATA_TIMEOUT = 60*3

-- GLOBALS: IsInRaid, IsRatedBattleground, InCombatLockdown, PlaySound, BNGetNumFriendInvites, BNGetFriendInviteInfo, BNAcceptFriendInvite, BNDeclineFriendInvite
-- GLOBALS: time, date, pairs, wipe, collectgarbage, select, strsplit

local function SanitizeText(text)
	-- text = text:gsub('[°!"§$%?^*#]', ' ') -- :gsub('[.,+><]+', ' ')
	text = text:gsub('`´', '\''):gsub('%s+', ' ')
	-- text = text:lower():gsub('^%l', string.utf8upper):gsub(' %l', string.utf8upper) -- create common capitalization
	-- text = text:match("^[%p%s]+(.-)[%p%s]-$") or text 	-- snipe away punctuation
	text = text:trim() 					-- trim spaces, can also supply specific characters for removal
	return text
end

function ns.PruneData()
	-- remove posts older than 2min
	local outdatedTime = time() - DATA_TIMEOUT
	for leader, info in pairs(ns.db.premadeCache) do
		if info.updated < outdatedTime then
			if not ns.db.queued[leader] then
				wipe(info)
				ns.db.premadeCache[leader] = nil
			else
				ns.db.premadeCache[leader].updated = 0
			end
		end
	end

	ns.UpdateUI()
	if not InCombatLockdown() then
		collectgarbage()
	end
end

function ns.GetLeaderByRequestToken(reqToken)
	for leader, token in pairs(ns.db.tokens) do
		if token == reqToken then
			return leader
		end
	end
end

function ns.GetLeaderByToken(token)
	for leader, data in pairs(ns.db.premadeCache) do
		if data.token == token then
			return leader
		end
	end
end

-- handles "Mychar-Myrealm", "Mychar-123" and "Mychar" ["Myrealm"]
function ns.GetLeaderByName(name, realm)
	if not name or name == '' then return end
	if not realm and name:find('-') then
		name, realm = strsplit("-", name)
		realm = realm and tonumber(realm) or realm
	end

	if not realm then
		realm = ns.playerRealm
	elseif type(realm) ~= "number" then
		realm = ns.GetRealmInfoByName(realm)
	end

	local leaderName, leaderRealm
	for leader, data in pairs(ns.db.premadeCache) do
		leaderName, leaderRealm, _ = ns.oq.DecodeLeaderData(leader)
		if leaderName == name and leaderRealm == realm then
			return leader
		end
	end
end

function ns.GetOQMessageInfo(message)
	local version, token, ttl, messageType, message = message:match("^OQ,([^,]+),([^,]+),([^,]+),([^,]+),(.-)$")
	return version, token, ttl, messageType, message
end

local function OnPremade(version, token, ttl, messageType, messageText)
	local sender, targetName, targetRealm
	-- local message, to, realm, from = messageText:match("^(.-),#to:([^,]+),#rlm:([^,]+),#fr:([^,]+)$")
	-- TODO: FIXME: re-creating functions on every premade/disband is really bad
	local message = messageText:gsub('(,#([^:]+):([^,]+))', function(field, key, value)
		-- remove all fields from messsage string, but store their values
		if key == 'to' then
			targetName = value
		elseif key == 'rlm' then
			targetRealm = value
		elseif key == 'fr' then
			sender = value
		end
		return ''
	end)

	local raidToken, premadeTitle, premadeInfo, leaderInfo, comment, premadeType, groupData, leaderExperience = strsplit(",", message)
	local faction, hasPassword, realmSpecific, is_source, level, iLvl, resilience, numMembers, numWaiting, status, msgTime, minMMR = ns.oq.DecodePremadeInfo(premadeInfo)

	-- a message from the future!
	if msgTime > time() + 4*24*60 then return end
	--[[ TYPE_NONE, TYPE_ARENA, TYPE_BG, TYPE_DUNGEON, TYPE_QUESTS, TYPE_RBG, TYPE_RAID, TYPE_SCENARIO, TYPE_CHALLENGE, --]]

	faction = faction == "H" and "Horde" or "Alliance"
	premadeTitle = ns.oq.DecodeText(premadeTitle)
	comment = ns.oq.DecodeText(comment)

	local tank, heal, dps = 0, 0, 0
	if groupData:match('^[THDX]+$') then
		groupData:gsub(".", function(character)
			if character == 'T' then tank = tank + 1
			elseif character == 'H' then heal = heal + 1
			else dps = dps + 1 end
		end)
	else
		tank, heal, dps = groupData:match("^(.)(.)(.)")
		tank 	= tank   == '-' and 0 or ns.oq.DecodeDigit(tank)
		heal 	= heal   == '-' and 0 or ns.oq.DecodeDigit(heal)
		dps 	= dps    == '-' and 0 or ns.oq.DecodeDigit(dps)
	end

	local premadeCache = ns.db.premadeCache
	-- use leader as unique key, as every player can only ever have one premade to his or her name
	premadeCache[leaderInfo] = premadeCache[leaderInfo] or {}
	if premadeCache[leaderInfo].updated and premadeCache[leaderInfo].updated > msgTime then return end
	premadeCache[leaderInfo].token      = raidToken
	premadeCache[leaderInfo].faction    = faction
	premadeCache[leaderInfo].type       = premadeType
	premadeCache[leaderInfo].password   = (hasPassword and hasPassword ~= 0) and true or false
	premadeCache[leaderInfo].title      = SanitizeText(premadeTitle)
	premadeCache[leaderInfo].comment    = SanitizeText(comment)
	premadeCache[leaderInfo].leader     = leaderInfo
	premadeCache[leaderInfo].size       = numMembers > 0 and numMembers or 1
	premadeCache[leaderInfo].waiting    = numWaiting
	premadeCache[leaderInfo].updated    = msgTime

	premadeCache[leaderInfo].level      = level
	premadeCache[leaderInfo].ilvl       = iLvl
	premadeCache[leaderInfo].resilience = resilience

	premadeCache[leaderInfo].group      = premadeCache[leaderInfo].group or {}
	premadeCache[leaderInfo].group.tank = tank
	premadeCache[leaderInfo].group.heal = heal
	premadeCache[leaderInfo].group.dps  = dps

	ns.UpdateUI()
end

local function OnDisband(version, token, ttl, messageType, messageText)
	local raidToken, msgToken, targetName, targetRealm, sender = strsplit(",", messageText)
	targetName  = targetName  and string.sub(targetName, 5)
	targetRealm = targetRealm and string.sub(targetRealm, 6)
	sender      = sender      and string.sub(sender, 5)

	local leader = ns.GetLeaderByToken(raidToken) or ns.GetLeaderByName(sender)
	if leader then
		ns.LeaveQueue(leader)
		wipe(ns.db.premadeCache[leader])
		ns.db.premadeCache[leader] = nil
	else
		-- ns.Print("Could not find disbanded group %s by %s", raidToken or '', sender or '')
	end
end

local function OnJoin(version, token, ttl, messageType, message)
	-- "invite_group,"..req_token ..","..group_id ..","..slot ..","..oq.encode_name( oq.raid.name ) ..","..oq.raid.leader_class  ..","..enc_data ..","..oq.raid.raid_token ..",".oq.encode_note( oq.raid.notes ) ;

	print('OnJoin', version, token, ttl, messageType, message)
	-- BN_FRIEND_INVITE_ADDED nil: OQ,GTo8dm,#tok:QRvkoi,#grp:1,#nam:Бриллианта-362

	local reqToken, invType, leader = strsplit(',', message)
	reqToken = reqToken and string.sub(reqToken, 6) -- strip "#tok:"
	leader   = leader   and string.sub(leader, 6)   -- strip "#nam:"

	local friendNote
	if invType == '#lead' then
		friendNote = 'OQ,leader'
	else
		invType = string.sub(invType, 6)    -- strip "#grp:"
		friendNote = 'OQ'
		-- group leader:
		-- local leadName, leadRealmID = strsplit('-', leader)
	end

	--[[-- TODO: do this when receiving friend request leading to invite
	if IsInGroup(_G.LE_PARTY_CATEGORY_HOME) then
		if ns.db.leaveExistingGroup then
			LeaveParty()
		else
			ns.Print('You are already in a group.')
			return
		end
	end
	--]]

	-- OQ,GQIXxf,#tok:QOX3Xy,#grp:1,#nam:Darthsetta-231
	local data = ns.oq.EncodeLeaderData(ns.playerName, ns.playerRealm, ns.playerBattleTag)
	local _, _, battleTag = ns.oq.DecodeLeaderData(leader)
	local slot = 1
	local message = strjoin(",", token, invType, slot, player_class, data, reqToken)
	ns.SendMessage(battleTag, true, 'invite_accepted', message, nil, 1)

	-- ns.db.tokens[reqToken] = nil
	-- ns.db.queued[leader] = ns.const.status.GROUPED

	-- accept friend request + add reason/note to db
	return true, friendNote
end

local function OnWaitlistLeave(version, token, ttl, messageType, message)
	local raidToken, reqToken = strsplit(',', message)
	local leader = ns.GetLeaderByRequestToken(reqToken) or ns.GetLeaderByToken(raidToken)

	if leader then
		PlaySound("igQuestFailed")
		ns.Print("You were removed from '%s' wait list",
			ns.db.premadeCache[leader] and ns.db.premadeCache[leader].title or 'unknown')
		ns.LeaveQueue(leader)
	end

	-- decline friend request
	return false
end

local function OnResponse(version, token, ttl, messageType, message)
	local raidToken, reqToken, answer, reason = strsplit(",", message)
	if ns.Find(ns.db.tokens, reqToken) then
		-- multi-boxers can receive same msg if via real-id msg
		return
	end

	local leader = ns.GetLeaderByToken(raidToken)
	if not leader then
		ns.Print("Could not find premade %s that we tried to join", raidToken)
		return
	end

	local title = ns.db.premadeCache[leader].title
	if answer == 'Y' then
		PlaySound("PVPENTERQUEUE")
		ns.Print("Successfully joined wait list for '%s'", title)
		ns.db.queued[leader] = ns.const.status.QUEUED
	else
		PlaySound("igQuestFailed")
		ns.Print("Wait list slot for '%s' was declined: %s", title, reason)
		ns.db.queued[leader] = nil
	end

	-- decline friend request
	return false
end

local function OnPing(version, token, ttl, messageType, message, senderToonID)
	local toonName, realmName, faction, battleTag, timestamp, acknowledged = strsplit(",", message)
	local playerName, playerRealm = UnitName('player'), GetRealmName():gsub(' ', '')
	local timestamp = ns.oq.EncodeNumber64(ns.utc() or 0, 5)
	local message = strjoin(',', playerName, playerRealm, ns.playerFaction, ns.playerBattleTag, timestamp, 'ack')
	ns.SendMessage(senderToonID, true, 'oq_user', message, 'W1', 1)
end

local messageHandler = {
	["p8"] = OnPremade,
	["disband"] = OnDisband,
	["invite"]  = OnJoin,
	["invite_group"] = OnJoin,
	["invite_req_response"]   = OnResponse,
	["leave_waitlist"]        = OnWaitlistLeave,
	["removed_from_waitlist"] = OnWaitlistLeave,
	["oq_user"] = OnPing,
}

-- ================================================
--  Listen for message & handle appropriately
-- ================================================
local function HandleChatMessage(event, chatMessage, presenceID, senderName, blizzRealmID, senderToonID)
	local version, token, ttl, messageType, message = ns.GetOQMessageInfo(chatMessage)
	if messageType ~= "p8" and messageType ~= "scores" then
		if message then
			print(event, messageType, senderToonID, "\n".._G.GRAY_FONT_COLOR_CODE..chatMessage..'|r')
		else
			print(event, messageType, senderToonID, "UNPARSED\n".._G.GRAY_FONT_COLOR_CODE..chatMessage..'|r')
		end
	end
	if messageType and messageHandler[messageType] then
		messageHandler[messageType](version, token, ttl, messageType, message, senderToonID)
	end
end

ns.RegisterEvent('CHAT_MSG_CHANNEL', function(self, event, chatMessage, senderName, _, _, _, _, _, _, channelName)
	channelName = channelName:lower()
	if channelName == ns.OQchannel or channelName == 'oqgeneral' then
		HandleChatMessage(event, chatMessage, nil, senderName)
	end
end, 'oq_msg_channel')

ns.RegisterEvent('CHAT_MSG_ADDON', function(self, event, prefix, chatMessage, _, senderName)
	if prefix ~= 'OQ' or senderName == ns.playerName then return end
	HandleChatMessage(event, chatMessage, nil, senderName)
end, 'oq_msg_addon')

ns.RegisterEvent('BN_CHAT_MSG_ADDON', function(self, event, prefix, chatMessage, _, senderToonID)
	local _, toonName, client, realmName, realmID, _, _, _, _, _, _, _, _, _, _, presenceID = BNGetToonInfo(senderToonID)
	local senderName = toonName..'-'..realmName:gsub(' ', '')
	HandleChatMessage(event, chatMessage, presenceID, senderName, realmID, senderToonID)
end, 'oq_msg_bnet_addon')

ns.RegisterEvent('CHAT_MSG_BN_WHISPER', function(self, event, chatMessage, _, _, _, _, _, _, _, _, _, _, _, presenceID)
	HandleChatMessage(event, chatMessage, presenceID)
end, 'oq_msg_bnet')

local notes = {}
local function SetFriendNote()
	for presenceID, note in pairs(notes) do
		local noteText = select(12, BNGetFriendInfoByID(presenceID))
		if not noteText or noteText == '' then
			BNSetFriendNote(presenceID, note)
			notes[presenceID] = nil
		end
	end
	ns.UnregisterEvent("BN_FRIEND_LIST_SIZE_CHANGED", 'friendnote')
end
local function HandleFriendInvites(self, event, ...)
	local prefix, msg, _, senderToonID = ...

	for i = BNGetNumFriendInvites(), 1, -1 do
		local presenceID, presenceName, isBattleTagPresence, msg, broadcastTime = BNGetFriendInviteInfoByAddon(i)

		local version, token, ttl, messageType, message = ns.GetOQMessageInfo(msg)
		print(event, messageType, "\n".._G.GRAY_FONT_COLOR_CODE..msg.."|r")
		if not version then
			token, message = msg:match('^OQ,([^,]+),(.-)$')
			messageType = 'invite'
		end

		if messageType and messageHandler[messageType] then
			local shouldAccept, friendNote = messageHandler[messageType](version, token, ttl, messageType, message)

			if shouldAccept then
				if friendNote and friendNote ~= '' then
					notes[presenceID] = friendNote
					ns.RegisterEvent('BN_FRIEND_LIST_SIZE_CHANGED', SetFriendNote, 'friendnote', true)
				end

				BNAcceptFriendInvite(presenceID)
			else
				BNDeclineFriendInvite(presenceID)
			end
		end
	end
end
ns.RegisterEvent("BN_FRIEND_INVITE_LIST_INITIALIZED", HandleFriendInvites, "availfriendreq")
ns.RegisterEvent("BN_FRIEND_INVITE_ADDED", HandleFriendInvites, "newfriendreq")

local currentGroupLeader = nil
ns.RegisterEvent("PARTY_INVITE_REQUEST", function(self, event, leaderName, ...)
	local leader = ns.GetLeaderByName(leaderName)
	if leader then
		ns.db.tokens[leader] = nil
		if ns.db.queued[leader] then
			ns.db.queued[leader] = ns.const.status.GROUPED
			currentGroupLeader = leader
			ns.UpdateUI(true)
		end

		if not ns.db.stayQueuedOnInvite then
			for otherLeader, status in pairs(ns.db.queued) do
				if otherLeader ~= leader then
					ns.LeaveQueue(otherLeader, true)
				end
			end
		end
	end
	-- if removeFriendOnJoin then ... end
end, "invite_group")

ns.RegisterEvent("GROUP_ROSTER_UPDATE", function(self, event)
	if currentGroupLeader and GetNumGroupMembers() <= 1 then
		-- left group
		ns.LeaveQueue(currentGroupLeader)
		currentGroupLeader = nil
		ns.UpdateUI(true)
	end
end, 'leave_group')


text:
package engo

type Action int
type Key int
type Modifier int

var (
	Move    = Action(0)
	Press   = Action(1)
	Release = Action(2)
	Neutral = Action(99)
	Shift   = Modifier(0x0001)
	Control = Modifier(0x0002)
	Alt     = Modifier(0x0004)
	Super   = Modifier(0x0008)
)

// MouseButton corresponds to a mouse button.
type MouseButton int

// Mouse buttons
const (
	MouseButton1      MouseButton = 0 // left button
	MouseButton2      MouseButton = 1 // right button
	MouseButton3      MouseButton = 2 // middle button
	MouseButton4      MouseButton = 3
	MouseButton5      MouseButton = 4
	MouseButton6      MouseButton = 5
	MouseButton7      MouseButton = 6
	MouseButton8      MouseButton = 7
	MouseButtonLast   MouseButton = 7
	MouseButtonLeft   MouseButton = 0 // equivalent for MouseButton1
	MouseButtonRight  MouseButton = 1 // equivalent for MouseButton2
	MouseButtonMiddle MouseButton = 2 // equivalent for MouseButton3
)

// those are default values for engo_js defined here because some of them are shared
// with engo_glfw.
// engo_glfw redefines the variables it needs to other values during init() so
var (
	Dash         Key = 189
	Apostrophe   Key = 222
	Semicolon    Key = 186
	Equals       Key = 187
	Comma        Key = 188
	Period       Key = 190
	Slash        Key = 191
	Backslash    Key = 220
	Backspace    Key = 8
	Tab          Key = 9
	CapsLock     Key = 20
	Space        Key = 32
	Enter        Key = 13
	Escape       Key = 27
	Insert       Key = 45
	PrintScreen  Key = 42
	Delete       Key = 46
	PageUp       Key = 33
	PageDown     Key = 34
	Home         Key = 36
	End          Key = 35
	Pause        Key = 19
	ScrollLock   Key = 145
	ArrowLeft    Key = 37
	ArrowRight   Key = 39
	ArrowDown    Key = 40
	ArrowUp      Key = 38
	LeftBracket  Key = 219
	LeftShift    Key = 16
	LeftControl  Key = 17
	LeftSuper    Key = 73
	LeftAlt      Key = 18
	RightBracket Key = 221
	RightShift   Key = 16
	RightControl Key = 17
	RightSuper   Key = 73
	RightAlt     Key = 18
	Zero         Key = 48
	One          Key = 49
	Two          Key = 50
	Three        Key = 51
	Four         Key = 52
	Five         Key = 53
	Six          Key = 54
	Seven        Key = 55
	Eight        Key = 56
	Nine         Key = 57
	F1           Key = 112
	F2           Key = 113
	F3           Key = 114
	F4           Key = 115
	F5           Key = 116
	F6           Key = 117
	F7           Key = 118
	F8           Key = 119
	F9           Key = 120
	F10          Key = 121
	F11          Key = 122
	F12          Key = 123
	A            Key = 65
	B            Key = 66
	C            Key = 67
	D            Key = 68
	E            Key = 69
	F            Key = 70
	G            Key = 71
	H            Key = 72
	I            Key = 73
	J            Key = 74
	K            Key = 75
	L            Key = 76
	M            Key = 77
	N            Key = 78
	O            Key = 79
	P            Key = 80
	Q            Key = 81
	R            Key = 82
	S            Key = 83
	T            Key = 84
	U            Key = 85
	V            Key = 86
	W            Key = 87
	X            Key = 88
	Y            Key = 89
	Z            Key = 90
	NumLock      Key = 144
	NumMultiply  Key = 106
	NumDivide    Key = 111
	NumAdd       Key = 107
	NumSubtract  Key = 109
	NumZero      Key = 96
	NumOne       Key = 97
	NumTwo       Key = 98
	NumThree     Key = 99
	NumFour      Key = 100
	NumFive      Key = 101
	NumSix       Key = 102
	NumSeven     Key = 103
	NumEight     Key = 104
	NumNine      Key = 105
	NumDecimal   Key = 110
	NumEnter     Key = 13
)

// MouseState represents the current state of the Mouse (or latest Touch-events).
type MouseState struct {
	// X and Y are the coordinates of the Mouse, relative to the `Canvas`.
	X, Y float32
	// ScrollX and ScrollY are the amount of scrolling the user has done with his mouse wheel in the respective directions.
	ScrollX, ScrollY float32
	// Action indicates what the gamer currently has done with his mouse.
	Action Action
	// Button indicates which button is being pressed by the gamer (if any).
	Button MouseButton
	// Modifier indicates which modifier (shift, alt, etc.) has been pressed during the Action.
	Modifier Modifier
}


text:
package org.lorislab.armonitor.scm.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The SCM search result.
 *
 * @author Andrej Petras
 */
public class ScmResult implements Serializable {

    /**
     * The UID for this class.
     */
    private static final long serialVersionUID = 2706786230774245834L;
    /**
     * The list of SCM logs.
     */
    private final List<ScmLog> logs = new ArrayList<>();
    /**
     * The map of SCM logs.
     */
    private final Map<String, ScmLog> map = new HashMap<>();

    /**
     * Adds the SCM log to the result.
     *
     * @param log the SCM log.
     */
    public void addScmLog(ScmLog log) {
        if (!map.containsKey(log.getId())) {
            logs.add(log);
            map.put(log.getId(), log);
        }
    }

    /**
     * Gets the list of SCM logs.
     *
     * @return the list of SCM logs.
     */
    public List<ScmLog> getScmLogs() {
        return logs;
    }

    /**
     * Gets the SCM log by id.
     *
     * @param id the SCM log id.
     * @return the SCM log or null.
     */
    public ScmLog getScmLog(String id) {
        return map.get(id);
    }

    /**
     * The size of the result list.
     *
     * @return the size of the result list.
     */
    public int size() {
        return logs.size();
    }

    /**
     * Returns true if the list of logs is empty.
     *
     * @return true if the list of logs is empty.
     */
    public boolean isEmpty() {
        return logs.isEmpty();
    }
}


text:
  <input type="submit"
         class="button success {{ form.style }} {{form.fieldHtmlClass}}"
         value="{{form.title}}"
         ng-disabled="form.readonly"
         ng-if="form.type === 'submit'">
  <button class="button {{ form.style }}"
          type="button"
          ng-click="buttonClick($event,form)"
          ng-disabled="form.readonly"
          ng-if="form.type !== 'submit'">

      {{form.title}}
  </button>