text:
"""Base TestCase"""
# pylint: disable=unused-import

from __future__ import (absolute_import, division)

import unittest

from pyposast.cross_version import only_python2, only_python3
from pyposast.cross_version import only_python35, only_python36
from pyposast.cross_version import only_python38
from pyposast import get_nodes

class NodeTestCase(unittest.TestCase):
    """Base test case"""
    # pylint: disable=invalid-name

    def assertPosition(self, node, first, last, uid, messages=None):
        """Check node positions"""
        # pylint: disable=no-self-use
        node_first = (node.first_line, node.first_col)
        node_last = (node.last_line, node.last_col)
        messages = messages or []
        if not node_first == first:
            messages.append(
                'first does not match: {} != {}'.format(node_first, first))
        if not node_last == last:
            messages.append(
                'last does not match: {} != {}'.format(node_last, last))
        if not node.uid == uid:
            messages.append(
                'uid does not match: {} != {}'.format(node.uid, uid))
        if messages:
            raise AssertionError('\n'.join(messages))

    def assertOperation(self, node, first, last, uid, kind):
        messages = []
        if not node.kind == kind:
            messages.append(
                'kind does not match: {} != {}'.format(node.kind, kind)
            )
        self.assertPosition(node, first, last, uid, messages=messages)

    def assertNoBeforeInnerAfter(self, node):
        """Check if node does not have pos_before, pos_inner, pos_after"""
        self.assertFalse(hasattr(node, 'pos_before'))
        self.assertFalse(hasattr(node, 'pos_inner'))
        self.assertFalse(hasattr(node, 'pos_after'))

    def assertSimpleInnerPosition(self, node, first, last):
        """Check pos_before, pos_inner, pos_after"""
        node_first = (node.first_line, node.first_col)
        node_last = (node.last_line, node.last_col)
        self.assertPosition(node.pos_before, node_first, first, first)
        self.assertPosition(node.pos_inner, first, last, last)
        self.assertPosition(node.pos_after, last, node_last, node_last)


text:
<?php

namespace Google\Service\Integrations;

class EnterpriseCrmEventbusProtoSuspensionAuthPermissionsGaiaIdentity extends \Google\Model
{
  /**
   * @var string
   */
  public $emailAddress;
  /**
   * @var string
   */
  public $gaiaId;

  /**
   * @param string
   */
  public function setEmailAddress($emailAddress)
  {
    $this->emailAddress = $emailAddress;
  }
  /**
   * @return string
   */
  public function getEmailAddress()
  {
    return $this->emailAddress;
  }
  /**
   * @param string
   */
  public function setGaiaId($gaiaId)
  {
    $this->gaiaId = $gaiaId;
  }
  /**
   * @return string
   */
  public function getGaiaId()
  {
    return $this->gaiaId;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(EnterpriseCrmEventbusProtoSuspensionAuthPermissionsGaiaIdentity::class, 'Google_Service_Integrations_EnterpriseCrmEventbusProtoSuspensionAuthPermissionsGaiaIdentity');

redpajama_set_name: RedPajamaGithub


text:
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>High Performance Primitive Collections Realtime (HPPC-RT): predicates</title>

        Predicates that return a boolean true/ false for
        a given value. Useful in pseudo-closures applied to values of containers.


text:
package net.mostlyharmless.jghservice.connector.github;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import net.mostlyharmless.jghservice.resources.ObjectMapperProvider;
import net.mostlyharmless.jghservice.resources.ServiceConfig.Repository;
import net.mostlyharmless.jghservice.resources.github.GithubEvent;
import net.mostlyharmless.jghservice.resources.github.GithubEvent.Milestone;

/**
 *
 * @author Brian Roach <roach at mostlyharmless dot net>
 */
public class GetMilestones implements GithubCommand<List<Milestone>>
{
    private final Repository repo;

    private GetMilestones(Builder builder)
    {
        this.repo = builder.repo;
    }

    @Override
    public URL getUrl(String apiUrlBase) throws MalformedURLException
    {
        return new URL(apiUrlBase +
                        repo.getGithubOwner() +
                        "/" +
                        repo.getGithubName() +
                        "/milestones");
    }

    @Override
    public String getJson() throws JsonProcessingException
    {
        throw new UnsupportedOperationException("Not supported for GET.");
    }

    @Override
    public String getRequestMethod()
    {
        return GET;
    }

    @Override
    public int getExpectedResponseCode()
    {
        return 200;
    }

    @Override
    public List<Milestone> processResponse(String jsonResponse) throws IOException
    {
        TypeReference<List<Milestone>> tr = new TypeReference<List<Milestone>>(){};
        ObjectMapper m = new ObjectMapperProvider().getContext(GithubEvent.Milestone.class);
        return m.readValue(jsonResponse, tr);
    }

    public static class Builder
    {
        private Repository repo;

        public Builder withRepositoy(Repository repo)
        {
            this.repo = repo;
            return this;
        }

        public GetMilestones build()
        {
            if (repo == null)
            {
                throw new IllegalStateException("Repository is required");
            }

            return new GetMilestones(this);
        }

    }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>
		Xi Huang | Full Stack Developer | Female Entrepreneur
	</title>
	<link href='http://fonts.googleapis.com/css?family=Dosis:300,400,500,600,700,800' rel='stylesheet' type='text/css'>
	<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>

	<link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
	<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

	<link rel="stylesheet" href="style.css">
	<link rel="stylesheet" href="css/owl.carousel.css">
	<link rel="stylesheet" href="css/owl.theme.default.css">

	<link rel="stylesheet" href="css/animate.css">

	<link rel="stylesheet" href="css/style.css">

	<link href="css/responsive.css" rel="stylesheet">

			YUMIKO

				Menu

Yumiko Huang

A Full Stack Developer

FRONT END

HTML5 CSS3

Javascript

jQuery

AngularJS

IONIC

next: React

BACKEND

Ruby on Rails

Express

Node.js

Meteorjs

DATABASE

SQL

PostgreSQL

MongoDB

AWS

EC2

Elastic Beanstalk

S3

CloudFront

RDS

PORTFOLIOS

									Earnings Report

									A web app analyzes stock equities

									https://options-er.herokuapp.com

									Funding Without Money

									Lincoln Labs Hackathon 2015, 3rd place


text:
geometricmusicjs
================

Remix of the Geometric Music app in javascript in one weekend.

## Description

The aim of this application is to reproduce the main features of the iOs Geometric Music app using only web standard technologies in one weekend (2 days).

The development of the project will run from 2014-07-12 10:15am to 2014-07-14 01:00am CEST.

Strict conformity to the original application is not the point (its source code is not disclosed anyway), neither is a good UI (because I'm not a designer).

### Priorities :

* The audio engine is the top priority.
* Builtin sample library.
* Shapes from 1 to 8 segments.
* Different 'vector' per segments : 'silent', 'normal', 'reverse'
* Precise tuning per shape (replacing the 'down' vector, thus enabling to play a sample in reverse and down 7 semitones for example).
* Output saving as WAV
* Minimal UI : premature UI considerations are considered harmful (I just [made this up](http://modelviewculture.com/pieces/the-making-of-myths)).

### Extras (if time permits) :

* Being able to add samples in the library by microphone recording.
* More vectors : 'X repeats', 'vinyl scratch', 'vinyl stop', 'vinyl start', etc.
* Time offset per shape.
* Making it visually appealing.

## Motivations

* Challenging myself.
* Making a case for web-(and javascript)-based audio application for my employers and coworkers.
* Making a test case for the unstable [Aural.js](https://github.com/kchapelier/Aural.js).


text:
package bwfla.modules.pdp.service;

import javax.ejb.EJB;
import javax.jws.WebService;

@WebService(serviceName = "PolicyDecisionService", endpointInterface = "bwfla.modules.pdp.service.PolicyDecisionService", targetNamespace = "http://bw-fla.uni-freiburg.de/")
public class PolicyDecisionServiceImpl implements PolicyDecisionService {

	@EJB
	PolicyDecisionPointLocal policyDecisionPoint;

	/**
	 * @WebMethod to test the availability of the web service.
	 * @param name
	 *          of the person to greet
	 * @returns a greeting String
	 */
	@Override
	public String sayHi(String name) {
		return "Hi " + name + "!";
	}

	@Override
	public String evaluate(String request) {
		return policyDecisionPoint.evaluate(request);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using EventStore.ClientAPI;
using Newtonsoft.Json;

namespace SuperGlue.EventStore
{
    public class DefaultEventSerializer : IHandleEventSerialization
    {
        private static readonly JsonSerializerSettings SerializerSettings;
        private const string EventClrTypeHeader = "EventClrTypeName";

        static DefaultEventSerializer()
        {
            SerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None };
        }

        public SerializationResult Serialize(Guid eventId, object evnt, IDictionary<string, object> headers)
        {
            var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(evnt, SerializerSettings));

            var eventHeaders = new Dictionary<string, object>(headers)
            {
                [EventClrTypeHeader] = evnt.GetType().AssemblyQualifiedName
            };

            var metadata = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(eventHeaders, SerializerSettings));
            var typeName = evnt.GetType().Name;

            return new SerializationResult(eventId, typeName, true, data, metadata);
        }

        public DeSerializationResult DeSerialize(ResolvedEvent resolvedEvent)
        {
            try
            {
                var deSerializedMetaData = (Dictionary<string, object>)JsonConvert.DeserializeObject(Encoding.UTF8.GetString(resolvedEvent.Event.Metadata), typeof(Dictionary<string, object>));

                var deSerializedData = deSerializedMetaData.ContainsKey(EventClrTypeHeader) ? JsonConvert.DeserializeObject(Encoding.UTF8.GetString(resolvedEvent.Event.Data),
                    Type.GetType((string)deSerializedMetaData[EventClrTypeHeader])) : new EventStoreEvent();

                return new DeSerializationResult(resolvedEvent.Event.EventId, resolvedEvent.Event.EventNumber, resolvedEvent.OriginalEventNumber, deSerializedData, deSerializedMetaData, resolvedEvent);
            }
            catch (Exception exception)
            {
                return new DeSerializationResult(resolvedEvent.Event.EventId, resolvedEvent.Event.EventNumber, resolvedEvent.OriginalEventNumber, null, new Dictionary<string, object>(), resolvedEvent, exception);
            }
        }

        public class EventStoreEvent
        {

        }
    }
}


text:
'use strict';

/* eslint-disable max-statements: 'off' */

const dateparser = require('dateparser');

const one = 1;
const ten = 10;

const getTodayDateObject = function() {
  return new Date();
};

const getDateString = function(date) {
  let day = date.getDate();
  let month = date.getMonth() + one;
  const year = date.getFullYear();

  if (day < ten) {
    day = `0${day}`;
  }

  if (month < ten) {
    month = `0${month}`;
  }

  return `${month}/${day}/${year}`;
};

class Config {

  /**
   * Gets the options object for the plugin
   *
   * @static
   * @param   {string} startDate Start date of stats range
   * @param   {string} endDate End date of stats range
   * @param   {string} relativeRange Relative time range
   * @returns {Object} Options object for the plugin
   * @memberof Config
   */
  static getOptions(startDate, endDate, relativeRange) {
    const isStartDateSet = typeof startDate === 'string' && startDate !== '';
    const isEndDateSet = typeof endDate === 'string' && endDate !== '';
    const isRangeSet = typeof relativeRange === 'string' && relativeRange !== '';

    if (isStartDateSet && isEndDateSet) {
      return {
        startDate,
        endDate
      };
    } else if (isRangeSet) {
      const endDateString = getDateString(getTodayDateObject());
      const rangeInMillisecs = dateparser.parse(relativeRange).value;
      const startDateInMillisecs = getTodayDateObject().getTime() - rangeInMillisecs;
      const startDateDt = new Date(startDateInMillisecs);
      const startDateString = getDateString(startDateDt);

      return {
        startDate: startDateString,
        endDate: endDateString
      };
    }

    throw new Error('Relative time range or fixed start/end dates are required.');
  }

}

module.exports = Config;


text:
package com.google.errorprone.bugpatterns;

import com.google.common.base.Objects;

/**
 * @author alexeagle@google.com (Alex Eagle)
 */
public class SelfEqualsNegativeCases {
  private String field;

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

    SelfEqualsNegativeCases other = (SelfEqualsNegativeCases) o;
    return Objects.equal(field, other.field);
  }

  @Override
  public int hashCode() {
    return field != null ? field.hashCode() : 0;
  }

  public boolean equals2(Object o) {
    if (!(o instanceof SelfEqualsNegativeCases)) {
      return false;
    }

    SelfEqualsNegativeCases other = (SelfEqualsNegativeCases) o;
    return field.equals(other.field);
  }

  public boolean test() {
    return Boolean.TRUE.toString().equals(Boolean.FALSE.toString());
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  main
  main.cpp

  Member

    Cp3mm::Tds::Member::Member(unsigned int l, const std::string &n, const std::string *t=&VoidType)
    Cp3mm::Tds::Member::Member(unsigned int l, const std::string &n, const std::string &t)

  Method

    Cp3mm::Tds::Method::Method(unsigned int l, const std::string &n, const std::string *t=&VoidType)
    Cp3mm::Tds::Method::Method(unsigned int l, const std::string &n, const std::string &t)

  Module
  Cp3mm::Tds::Module

Searching...

No Matches


text:
package com.jcwhatever.nucleus.internal.managed.scripting.api;

import com.jcwhatever.nucleus.Nucleus;
import com.jcwhatever.nucleus.mixins.IDisposable;
import com.jcwhatever.nucleus.providers.bankitems.IBankItem;
import com.jcwhatever.nucleus.providers.bankitems.IBankItemsAccount;
import com.jcwhatever.nucleus.providers.bankitems.InsufficientItemsException;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.player.PlayerUtils;

import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.util.List;

/**
 * Provide scripts with API access to Item Bank.
 */
public class SAPI_ItemBank implements IDisposable {

    private boolean _isDisposed;

    @Override
    public boolean isDisposed() {
        return _isDisposed;
    }

    @Override
    public void dispose() {
        _isDisposed = true;
    }

    /**
     * Deposit an {@link ItemStack} into the players account.
     *
     * @param player  The player.
     * @param item    The item to deposit.
     * @param qty     The quantity to deposit.
     */
    public void deposit(Object player, ItemStack item, int qty) {
        PreCon.notNull(player);
        PreCon.notNull(item);
        PreCon.greaterThanZero(qty);

        Player p = PlayerUtils.getPlayer(player);
        PreCon.notNull(p);

        IBankItemsAccount account = Nucleus.getProviders().getBankItems()
                .getAccount(p.getUniqueId());

        account.deposit(item, qty);
    }

    /**
     * Withdraw items from the players account.
     *
     * @param player  The player.
     * @param item    The item to withdraw.
     * @param qty     The quantity to withdraw.
     *
     * @return  True if successful, false if insufficient items.
     */
    public boolean withdraw(Object player, ItemStack item, int qty) {
        PreCon.notNull(player);
        PreCon.notNull(item);
        PreCon.greaterThanZero(qty);

        Player p = PlayerUtils.getPlayer(player);
        PreCon.notNull(p);

        IBankItemsAccount account = Nucleus.getProviders().getBankItems()
                .getAccount(p.getUniqueId());

        try {
            account.withdraw(item, qty);
        } catch (InsufficientItemsException e) {
            return false;
        }
        return true;
    }

    /**
     * Get all {@link ItemStack}'s in the players item bank account.
     *
     * @param player  The player.
     */
    public IBankItem[] getBankItems(Object player) {
        PreCon.notNull(player);

        Player p = PlayerUtils.getPlayer(player);
        PreCon.notNull(p);

        IBankItemsAccount account = Nucleus.getProviders().getBankItems()
                .getAccount(p.getUniqueId());

        List<IBankItem> items = account.getItems();
        if (items == null)
            return new IBankItem[0];

        IBankItem[] itemsArray = new IBankItem[items.size()];

        for (int i=0; i < itemsArray.length; i++) {
            itemsArray[i] = items.get(i);
        }

        return itemsArray;
    }

    /**
     * Determine if the player has the specified {@link ItemStack} in the
     * specified quantity available in account.
     *
     * @param player  The player.
     * @param item    The item to check.
     * @param qty     The quantity to check for.
     *
     * @return  True if available.
     */
    public boolean has(Object player, ItemStack item, int qty) {
        PreCon.notNull(player);
        PreCon.notNull(item);
        PreCon.greaterThanZero(qty);

        Player p = PlayerUtils.getPlayer(qty);
        PreCon.notNull(p);

        IBankItemsAccount account = Nucleus.getProviders().getBankItems()
                .getAccount(p.getUniqueId());

        IBankItem bankItem = account.getItem(item);
        return bankItem != null && bankItem.getAmount() >= qty;
    }

    /**
     * Get the total quantity available of the specified item
     * from the players item bank account.
     *
     * @param player  The player.
     * @param item    The item to check.
     */
    public int getBalance(Object player, ItemStack item) {
        PreCon.notNull(player);
        PreCon.notNull(item);

        Player p = PlayerUtils.getPlayer(player);
        PreCon.notNull(p);

        IBankItemsAccount account = Nucleus.getProviders().getBankItems()
                .getAccount(p.getUniqueId());

        IBankItem bankItem = account.getItem(item);
        if (bankItem == null)
            return 0;

        return bankItem.getAmount();
    }
}


text:
![](https://raw.githubusercontent.com/TelerikAcademy/Common/master/logos/telerik-header-logo.png)
## Telerik Software Academy
## C# Fundamentals Exam - 25 April 2016

### Task 1 - Feathers
#### [Description](./01.Feathers/README.md) / [Author's Solution](./01.Feathers/FeathersStartup.cs)

### Task 2 - Busses
#### [Description](./02.Busses/README.md) / [Author's Solution](./02.Busses/BussesStartup.cs)

### Task 3(Morning) - Number of Digits
#### [Description](./03.NumberOfDigits - Morning/README.md) / [Author's Solution](./03.NumberOfDigits - Morning/NumberOfDigitsStartup.cs)

### Task 3(Evening) - Number of Pages
#### [Description](./03.NumberOfPages - Evening/README.md) / [Author's Solution](./03.NumberOfPages - Evening/NumberOfPagesStartup.cs)

### Task 4 - Batman
#### [Description](./04.Batman/README.md) / [Author's Solution](./04.Batman/BatmanStartup.cs)

### Task 5 - Bobby Avokadoto
#### [Description](./05.BobbyAvokadoto/README.md) / [Author's Solution](./05.BobbyAvokadoto/BobbyStartup.cs)


text:
package service

import (
	"fmt"
	"reflect"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/endpoints"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/cnaize/kubernetes/pkg/api"
	"github.com/cnaize/kubernetes/pkg/api/v1beta1"
	"github.com/cnaize/kubernetes/pkg/api/v1beta2"

	"github.com/golang/glog"
)

// EndpointController manages selector-based service endpoints.
type EndpointController struct {
	client *client.Client
}

// NewEndpointController returns a new *EndpointController.
func NewEndpointController(client *client.Client) *EndpointController {
	return &EndpointController{
		client: client,
	}
}

// SyncServiceEndpoints syncs endpoints for services with selectors.
func (e *EndpointController) SyncServiceEndpoints() error {
	services, err := e.client.Services(api.NamespaceAll).List(labels.Everything())
	if err != nil {
		glog.Errorf("Failed to list services: %v", err)
		return err
	}
	var resultErr error
	for i := range services.Items {
		service := &services.Items[i]

		if service.Spec.Selector == nil {
			// services without a selector receive no endpoints from this controller;
			// these services will receive the endpoints that are created out-of-band via the REST API.
			continue
		}

		glog.V(5).Infof("About to update endpoints for service %s/%s", service.Namespace, service.Name)
		pods, err := e.client.Pods(service.Namespace).List(labels.Set(service.Spec.Selector).AsSelector())
		if err != nil {
			glog.Errorf("Error syncing service: %s/%s, skipping", service.Namespace, service.Name)
			resultErr = err
			continue
		}

		subsets := []api.EndpointSubset{}
		for i := range pods.Items {
			pod := &pods.Items[i]

			// TODO: Once v1beta1 and v1beta2 are EOL'ed, this can
			// assume that service.Spec.TargetPort is populated.
			_ = v1beta1.Dependency
			_ = v1beta2.Dependency
			// TODO: Add multiple-ports to Service and expose them here.
			portName := ""
			portProto := service.Spec.Protocol
			portNum, err := findPort(pod, service)
			if err != nil {
				glog.Errorf("Failed to find port for service %s/%s: %v", service.Namespace, service.Name, err)
				continue
			}
			if len(pod.Status.PodIP) == 0 {
				glog.Errorf("Failed to find an IP for pod %s/%s", pod.Namespace, pod.Name)
				continue
			}

			inService := false
			for _, c := range pod.Status.Conditions {
				if c.Type == api.PodReady && c.Status == api.ConditionTrue {
					inService = true
					break
				}
			}
			if !inService {
				glog.V(5).Infof("Pod is out of service: %v/%v", pod.Namespace, pod.Name)
				continue
			}

			epp := api.EndpointPort{Name: portName, Port: portNum, Protocol: portProto}
			epa := api.EndpointAddress{IP: pod.Status.PodIP, TargetRef: &api.ObjectReference{
				Kind:            "Pod",
				Namespace:       pod.ObjectMeta.Namespace,
				Name:            pod.ObjectMeta.Name,
				UID:             pod.ObjectMeta.UID,
				ResourceVersion: pod.ObjectMeta.ResourceVersion,
			}}
			subsets = append(subsets, api.EndpointSubset{Addresses: []api.EndpointAddress{epa}, Ports: []api.EndpointPort{epp}})
		}
		subsets = endpoints.RepackSubsets(subsets)

		// See if there's actually an update here.
		currentEndpoints, err := e.client.Endpoints(service.Namespace).Get(service.Name)
		if err != nil {
			if errors.IsNotFound(err) {
				currentEndpoints = &api.Endpoints{
					ObjectMeta: api.ObjectMeta{
						Name: service.Name,
					},
				}
			} else {
				glog.Errorf("Error getting endpoints: %v", err)
				continue
			}
		}
		if reflect.DeepEqual(currentEndpoints.Subsets, subsets) {
			glog.V(5).Infof("endpoints are equal for %s/%s, skipping update", service.Namespace, service.Name)
			continue
		}
		newEndpoints := currentEndpoints
		newEndpoints.Subsets = subsets

		if len(currentEndpoints.ResourceVersion) == 0 {
			// No previous endpoints, create them
			_, err = e.client.Endpoints(service.Namespace).Create(newEndpoints)
		} else {
			// Pre-existing
			_, err = e.client.Endpoints(service.Namespace).Update(newEndpoints)
		}
		if err != nil {
			glog.Errorf("Error updating endpoints: %v", err)
			continue
		}
	}
	return resultErr
}

func findDefaultPort(pod *api.Pod, servicePort int, proto api.Protocol) int {
	for _, container := range pod.Spec.Containers {
		for _, port := range container.Ports {
			if port.Protocol == proto {
				return port.ContainerPort
			}
		}
	}
	return servicePort
}

// findPort locates the container port for the given manifest and portName.
// If the targetPort is a non-zero number, use that.  If the targetPort is 0 or
// not specified, use the first defined port with the same protocol.  If no port
// is defined, use the service's port.  If the targetPort is an empty string use
// the first defined port with the same protocol.  If no port is defined, use
// the service's port.  If the targetPort is a non-empty string, look that
// string up in all named ports in all containers in the target pod.  If no
// match is found, fail.
func findPort(pod *api.Pod, service *api.Service) (int, error) {
	portName := service.Spec.TargetPort
	switch portName.Kind {
	case util.IntstrString:
		if len(portName.StrVal) == 0 {
			return findDefaultPort(pod, service.Spec.Port, service.Spec.Protocol), nil
		}
		name := portName.StrVal
		for _, container := range pod.Spec.Containers {
			for _, port := range container.Ports {
				if port.Name == name && port.Protocol == service.Spec.Protocol {
					return port.ContainerPort, nil
				}
			}
		}
	case util.IntstrInt:
		if portName.IntVal == 0 {
			return findDefaultPort(pod, service.Spec.Port, service.Spec.Protocol), nil
		}
		return portName.IntVal, nil
	}

	return 0, fmt.Errorf("no suitable port for manifest: %s", pod.UID)
}


text:
'use strict';

angular.module('EggJogApp')
  .controller('AboutCtrl', ['$scope', function ($scope) {
  }]);


text:
module.exports = {
  default: '--format-options \'{"snippetInterface": "promise"}\''
}


text:
package mpsidekiq

import (
	"flag"
	"fmt"
	"os"
	"strconv"

	r "github.com/go-redis/redis"
	mp "github.com/mackerelio/go-mackerel-plugin-helper"
)

// SidekiqPlugin for fetching metrics
type SidekiqPlugin struct {
	Client    *r.Client
	Namespace string
	Prefix    string
}

var graphdef = map[string]mp.Graphs{
	"ProcessedANDFailed": mp.Graphs{
		Label: "Sidekiq processed and failed count",
		Unit:  "integer",
		Metrics: []mp.Metrics{
			{Name: "processed", Label: "Processed", Type: "uint64", Diff: true},
			{Name: "failed", Label: "Failed", Type: "uint64", Diff: true},
		},
	},
	"Stats": mp.Graphs{
		Label: "Sidekiq stats",
		Unit:  "integer",
		Metrics: []mp.Metrics{
			{Name: "busy", Label: "Busy", Type: "uint64"},
			{Name: "enqueued", Label: "Enqueued", Type: "uint64"},
			{Name: "schedule", Label: "Schedule", Type: "uint64"},
			{Name: "retry", Label: "Retry", Type: "uint64"},
			{Name: "dead", Label: "Dead", Type: "uint64"},
		},
	},
}

// GraphDefinition Graph definition
func (sp SidekiqPlugin) GraphDefinition() map[string]mp.Graphs {
	return graphdef
}

func (sp SidekiqPlugin) get(key string) uint64 {
	val, err := sp.Client.Get(key).Result()
	if err == r.Nil {
		return 0
	}

	r, _ := strconv.ParseUint(val, 10, 64)
	return r
}

func (sp SidekiqPlugin) zCard(key string) uint64 {
	val, err := sp.Client.ZCard(key).Result()
	if err == r.Nil {
		return 0
	}

	return uint64(val)
}

func (sp SidekiqPlugin) sMembers(key string) []string {
	val, err := sp.Client.SMembers(key).Result()
	if err == r.Nil {
		return make([]string, 0)
	}

	return val
}

func (sp SidekiqPlugin) hGet(key string, field string) uint64 {
	val, err := sp.Client.HGet(key, field).Result()
	if err == r.Nil {
		return 0
	}

	r, _ := strconv.ParseUint(val, 10, 64)
	return r
}

func (sp SidekiqPlugin) lLen(key string) uint64 {
	val, err := sp.Client.LLen(key).Result()
	if err == r.Nil {
		return 0
	}

	return uint64(val)
}

func addNamespace(namespace string, key string) string {
	if namespace == "" {
		return key
	}
	return namespace + ":" + key
}

func (sp SidekiqPlugin) getProcessed() uint64 {
	key := addNamespace(sp.Namespace, "stat:processed")
	return sp.get(key)
}

func (sp SidekiqPlugin) getFailed() uint64 {
	key := addNamespace(sp.Namespace, "stat:failed")
	return sp.get(key)
}

func inject(slice []uint64, base uint64) uint64 {
	for _, e := range slice {
		base += uint64(e)
	}

	return base
}

func (sp SidekiqPlugin) getBusy() uint64 {
	key := addNamespace(sp.Namespace, "processes")
	processes := sp.sMembers(key)
	busies := make([]uint64, 10)
	for _, e := range processes {
		e := addNamespace(sp.Namespace, e)
		busies = append(busies, sp.hGet(e, "busy"))
	}

	return inject(busies, 0)
}

func (sp SidekiqPlugin) getEnqueued() uint64 {
	key := addNamespace(sp.Namespace, "queues")
	queues := sp.sMembers(key)
	queuesLlens := make([]uint64, 10)

	prefix := addNamespace(sp.Namespace, "queue:")
	for _, e := range queues {
		queuesLlens = append(queuesLlens, sp.lLen(prefix+e))
	}

	return inject(queuesLlens, 0)
}

func (sp SidekiqPlugin) getSchedule() uint64 {
	key := addNamespace(sp.Namespace, "schedule")
	return sp.zCard(key)
}

func (sp SidekiqPlugin) getRetry() uint64 {
	key := addNamespace(sp.Namespace, "retry")
	return sp.zCard(key)
}

func (sp SidekiqPlugin) getDead() uint64 {
	key := addNamespace(sp.Namespace, "dead")
	return sp.zCard(key)
}

func (sp SidekiqPlugin) getProcessedFailed() map[string]interface{} {
	data := make(map[string]interface{}, 20)

	data["processed"] = sp.getProcessed()
	data["failed"] = sp.getFailed()

	return data
}

func (sp SidekiqPlugin) getStats(field []string) map[string]interface{} {
	stats := make(map[string]interface{}, 20)
	for _, e := range field {
		switch e {
		case "busy":
			stats[e] = sp.getBusy()
		case "enqueued":
			stats[e] = sp.getEnqueued()
		case "schedule":
			stats[e] = sp.getSchedule()
		case "retry":
			stats[e] = sp.getRetry()
		case "dead":
			stats[e] = sp.getDead()
		}
	}

	return stats
}

// FetchMetrics fetch the metrics
func (sp SidekiqPlugin) FetchMetrics() (map[string]interface{}, error) {
	field := []string{"busy", "enqueued", "schedule", "retry", "dead"}
	stats := sp.getStats(field)
	pf := sp.getProcessedFailed()

	// merge maps
	m := func(map1 map[string]interface{}, map2 map[string]interface{}) map[string]interface{} {
		for k, v := range map2 {
			map1[k] = v
		}

		return map1
	}(stats, pf)

	return m, nil
}

// MetricKeyPrefix interface for PluginWithPrefix
func (sp SidekiqPlugin) MetricKeyPrefix() string {
	if sp.Prefix == "" {
		sp.Prefix = "sidekiq"
	}
	return sp.Prefix
}

// Do the plugin
func Do() {
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "6379", "Port")
	optPassword := flag.String("password", os.Getenv("SIDEKIQ_PASSWORD"), "Password")
	optDB := flag.Int("db", 0, "DB")
	optNamespace := flag.String("redis-namespace", "", "Redis namespace")
	optPrefix := flag.String("metric-key-prefix", "sidekiq", "Metric key prefix")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	client := r.NewClient(&r.Options{
		Addr:     fmt.Sprintf("%s:%s", *optHost, *optPort),
		Password: *optPassword,
		DB:       *optDB,
	})

	sp := SidekiqPlugin{
		Client:    client,
		Namespace: *optNamespace,
		Prefix:    *optPrefix,
	}
	helper := mp.NewMackerelPlugin(sp)
	helper.Tempfile = *optTempfile

	helper.Run()
}


text:
[![Build Status](https://travis-ci.org/codisart/polygones.svg?branch=master)](https://travis-ci.org/codisart/polygones)

# polygones

Allow the use of polygones in PHP.


text:
package org.apache.ignite.cache.query;

import org.apache.ignite.*;
import org.apache.ignite.internal.util.tostring.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.spi.indexing.*;

/**
 * Query to be used by {@link IndexingSpi} implementations.
 *
 * @see IgniteCache#query(Query)
 * @see IgniteCache#localQuery(Query)
 */
public final class SpiQuery extends Query<SpiQuery> {
    /** */
    private static final long serialVersionUID = 0L;

    /** Arguments. */
    @GridToStringInclude
    private Object[] args;

    /**
     * Gets SQL arguments.
     *
     * @return SQL arguments.
     */
    public Object[] getArgs() {
        return args;
    }

    /**
     * Sets SQL arguments.
     *
     * @param args SQL arguments.
     * @return {@code this} For chaining.
     */
    public SpiQuery setArgs(Object... args) {
        this.args = args;

        return this;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(SpiQuery.class, this);
    }
}


text:
<?php

use ElkArte\Cache\Cache;
use ElkArte\Languages\Txt;

/**
 * Gets a list of all available message icons.
 */
function fetchMessageIconsDetails()
{
	static $icons;

	if (isset($icons))
	{
		return $icons;
	}

	$db = database();

	$icons = array();
	$last_icon = 0;
	$trueOrder = 0;
	$db->fetchQuery('
		SELECT
			m.id_icon, m.title, m.filename, m.icon_order, m.id_board, b.name AS board_name
		FROM {db_prefix}message_icons AS m
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
		WHERE ({query_see_board} OR b.id_board IS NULL)
		ORDER BY m.icon_order',
		array()
	)->fetch_callback(
		function ($row) use (&$icons, &$last_icon, &$trueOrder) {
			global $settings, $txt;

			$icons[$row['id_icon']] = array(
				'id' => $row['id_icon'],
				'title' => $row['title'],
				'filename' => $row['filename'],
				'image_url' => $settings[file_exists($settings['theme_dir'] . '/images/post/' . $row['filename'] . '.png') ? 'actual_images_url' : 'default_images_url'] . '/post/' . $row['filename'] . '.png',
				'board_id' => $row['id_board'],
				'board' => empty($row['board_name']) ? $txt['icons_edit_icons_all_boards'] : $row['board_name'],
				'order' => $row['icon_order'],
				'true_order' => $trueOrder++,
				'after' => $last_icon,
			);
			$last_icon = $row['id_icon'];
		}
	);

	return $icons;
}

/**
 * Delete a message icon.
 *
 * @param int[] $icons
 */
function deleteMessageIcons($icons)
{
	$db = database();

	// Do the actual delete!
	$db->query('', '
		DELETE FROM {db_prefix}message_icons
		WHERE id_icon IN ({array_int:icon_list})',
		array(
			'icon_list' => $icons,
		)
	);
}

/**
 * Updates a message icon.
 *
 * @param mixed[] $icon array of values to use in the $db->insert
 */
function updateMessageIcon($icon)
{
	$db = database();

	$db->replace(
		'{db_prefix}message_icons',
		array('id_icon' => 'int', 'id_board' => 'int', 'title' => 'string-80', 'filename' => 'string-80', 'icon_order' => 'int'),
		$icon,
		array('id_icon')
	);
}

/**
 * Adds a new message icon.
 *
 * @param mixed[] $icon associative array to use in the insert
 */
function addMessageIcon($icon)
{
	$db = database();

	$db->insert('',
		'{db_prefix}message_icons',
		array('id_board' => 'int', 'title' => 'string-80', 'filename' => 'string-80', 'icon_order' => 'int'),
		$icon,
		array('id_icon')
	);
}

/**
 * Retrieves a list of message icons.
 * - Based on the settings, the array will either contain a list of default
 *   message icons or a list of custom message icons retrieved from the database.
 * - The board_id is needed for the custom message icons (which can be set for
 *   each board individually).
 *
 * @param int $board_id
 * @return array
 */
function getMessageIcons($board_id)
{
	global $modSettings, $txt, $settings;

	$db = database();

	if (empty($modSettings['messageIcons_enable']))
	{
		Txt::load('Post');

		$icons = array(
			array('value' => 'xx', 'name' => $txt['standard']),
			array('value' => 'thumbup', 'name' => $txt['thumbs_up']),
			array('value' => 'thumbdown', 'name' => $txt['thumbs_down']),
			array('value' => 'exclamation', 'name' => $txt['exclamation_point']),
			array('value' => 'question', 'name' => $txt['question_mark']),
			array('value' => 'lamp', 'name' => $txt['lamp']),
			array('value' => 'smiley', 'name' => $txt['icon_smiley']),
			array('value' => 'angry', 'name' => $txt['icon_angry']),
			array('value' => 'cheesy', 'name' => $txt['icon_cheesy']),
			array('value' => 'grin', 'name' => $txt['icon_grin']),
			array('value' => 'sad', 'name' => $txt['icon_sad']),
			array('value' => 'wink', 'name' => $txt['icon_wink']),
			array('value' => 'poll', 'name' => $txt['icon_poll']),
		);

		foreach ($icons as $k => $dummy)
		{
			$icons[$k]['url'] = $settings['images_url'] . '/post/' . $dummy['value'] . '.png';
			$icons[$k]['is_last'] = false;
		}
	}
	// Otherwise load the icons, and check we give the right image too...
	else
	{
		$icons = array();
		if (!Cache::instance()->getVar($icons, 'posting_icons-' . $board_id, 480))
		{
			$icon_data = $db->fetchQuery('
				SELECT
					title, filename
				FROM {db_prefix}message_icons
				WHERE id_board IN (0, {int:board_id})
				ORDER BY icon_order',
				array(
					'board_id' => $board_id,
				)
			);
			$icons = array();
			foreach ($icon_data->fetch_all() as $icon)
			{
				$icons[$icon['filename']] = array(
					'value' => $icon['filename'],
					'name' => $icon['title'],
					'url' => $settings[file_exists($settings['theme_dir'] . '/images/post/' . $icon['filename'] . '.png') ? 'images_url' : 'default_images_url'] . '/post/' . $icon['filename'] . '.png',
					'is_last' => false,
				);
			}

			Cache::instance()->put('posting_icons-' . $board_id, $icons, 480);
		}
	}

	return array_values($icons);
}


text:
layout: post

title: "Ghost in the Iframe"
date: 2013-10-31 10:00:00
tags: javascript

project: "https://github.com/shokai/xframe.js"
author: "https://github.com/shokai"
discuss: "https://github.com/nealrs/gitatme-comments/issues/9"
description: "xframe.js enables you to scroll through cross-domain iframes with JavaScript. Once again, UI design is your prerogative."
issue: "9"
---
Skip the haunted house this year. You can spook a room full of designers and engineers with just one word. Turn down the lights and slowly creak out _frameset_. Goose bumps, right?

And to _really_ terrify them, follow it up with same-origin policy. Don't get the joke? I'll explain.

Inline frames enable you to present content from different sources as a single document. However, because of the same-origin policy, that's about all you can do. Interactivity between cross-domain elements is extremely limited.

For a parent page hosted at X.com with iframe content from Y.com, there isn't an easy way to manipulate the iframe's DOM. Want to scroll the iframe from the parent page? Sorry, no dice. You'll have to focus on it with your mouse to scroll, and that's not always practical from a UI standpoint.

Fortunately, xframe.js overcomes some of these contraints. Created by Sho Hashimoto, xframes enable you to scroll through cross-domain iframes with JavaScript. Once again, UI design is your prerogative.

Here's a demo, although implementation is quite straightforward:

```html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="xframe.min.js"></script>

<script type="text/javascript">
  var xframe = null;
  var url = "http://gitat.me";

  $(document).ready(function(){
    xframe = new XFrame("div#frame");
    xframe.load(url); // load iframe
    xframe.mouseScroll = true; // enable mouse scrolling
  });
</script>

</head>
<body>

  <!-- scroll via javascript or mouse -->
  <button onclick="xframe.scrollY(50)">scroll down</button>
  <button onclick="xframe.scrollY(-50)">scroll up</button>

  <div id="frame" style="width:450px; height:300px; padding:10px;"></div>

</body>
</html>
```

Granted, there are more powerful ways (easyXDM & postMessage) to enable cross-domain interaction, but in this case xframe.js requires less code. That's a trick _and_ a treat—Happy Halloween!

Join the  discussion


text:
class Referer
  include Mongoid::Document
  include Mongoid::Timestamps::Created

  # Feed index
  field :fid, type: String
  index({ fid: 1 })

  # Authorized referers domains
  field :rf, type: String

end


text:
$("#page2-button").click(function(e){
  e.preventDefault();
  $("#page1")[0].style.display = "none";
  $("#page2")[0].style.display = "block";
});

$("#page1-button").click(function(e){
  e.preventDefault();
  $("#page1")[0].style.display = "block";
  $("#page2")[0].style.display = "none";
});

$('a.portfolio-box').click(function(e){
    e.preventDefault();
});

$(".eachProject").click(function(){
    var aux = $(this).children();
    window.open(aux.attr("href"), '_blank');
});


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "New Planet", menuName = "Planet Type")]
public class PlanetScriptable : ScriptableObject
{
    public string planetType;
    public GameObject planetMesh;
    public float meshScale = 1;
    public Vector3 meshRotation;

    public Quaternion getRotation()
    {
        return Quaternion.Euler(meshRotation.x, meshRotation.y, meshRotation.z);
    }

    public Vector3 getPosition()
    {
        return Vector3.zero;
    }

    public Vector3 getScale()
    {
        return new Vector3(meshScale, meshScale, meshScale);
    }
}


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="document-function.xsl"?>
<doc>
<para>This tests the xslt document() function. If this test is successful, there should be three paragraphs below.</para>
<para>This is a paragraph</para>
<para>This is another paragraph</para>
</doc>


text:
/*global define */
define([
    "js/util",
    "js/EventEmitter",
    "js/Exception",
    "js/Promise"
], function (
    util,
    EventEmitter,
    Exception,
    Promise
) {
    "use strict";

    function IO() {
        EventEmitter.call(this);

        this.devices = [];
        this.nullDevice = {
            ioRead: function (port, length) {
                //util.problem("Read from unregistered port 0x" + port.toString(16).toUpperCase() + " (length " + length + ")");

                // Return max value
                if (length === 1) {
                    return 0xFF;
                }

                if (length === 2) {
                    return 0xFFFF;
                }

                return 0xFFFFFFFF;
            },

            ioWrite: function (port, value, length) {
                // Do nothing

                //util.problem("Write to unregistered port 0x" + port.toString(16).toUpperCase() + ": " + util.hexify(value) + " (length " + length + ")");
            }
        };
        this.ports = [];

        (function (io) {
            util.from(0).to(0xFFFF, function (port) {
                io.ports[port] = {
                    allowedIOLengths: {1: true, 2: true},
                    description: "<unassigned>",
                    device: io.nullDevice
                };
            });
        }(this));
    }

    util.inherit(IO).from(EventEmitter);

    util.extend(IO.prototype, {
        getRegisteredDevice: function (identifier) {
            var device = null;

            util.each(this.devices, function (registeredDevice) {
                if (registeredDevice.getIdentifier() === identifier) {
                    device = registeredDevice;
                    return false;
                }
            });

            return device;
        },

        init: function () {
            var index = 0,
                io = this,
                promise = new Promise();

            (function next() {
                if (index >= io.devices.length) {
                    promise.resolve();
                } else {
                    io.devices[index].init().done(function () {
                        index++;
                        next();
                    }).fail(function (exception) {
                        promise.reject(exception);
                    });
                }
            }());

            return promise;
        },

        read: function (port, length) {
            var io = this,
                portOptions = io.ports[port];

            if (portOptions.allowedIOLengths[length]) {
                io.emit("io read", port, length);

                return portOptions.device.ioRead(port, length);
            } else {
                //throw new Exception("IO.read() :: Read from port #" + util.hexify(port) + " with length " + length + " ignored");
                return 0;
            }
        },

        register: function (device) {
            var io = this,
                ports = io.ports;

            io.devices.push(device);

            util.each(device.getIOPorts(), function (portOptions, port) {
                var description = portOptions.description;

                if (ports[port].device !== io.nullDevice) {
                    throw new Exception("IO.register() :: IO port conflict for #" + util.hexify(port) + " '" + description + "' (already in use by '" + ports[port].description + "')");
                }

                ports[port] = {
                    allowedIOLengths: portOptions.allowedIOLengths,
                    description: description,
                    device: device
                };
            });
        },

        reset: function () {
            util.each(this.devices, function (device) {
                device.reset();
            });
        },

        write: function (port, value, length) {
            var io = this,
                portOptions = io.ports[port];

            if (portOptions.allowedIOLengths[length]) {
                io.emit("io write", port, value, length);

                return portOptions.device.ioWrite(port, value, length);
            }
        }
    });

    return IO;
});


text:
from django.conf.urls import patterns, include, url

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^hubbubs/', include('hubbubs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)


text:
define([
    'jquery',
    'underscore',
    'uiRegistry',
    'jquery/ui'
], function ($, _, registry) {
    'use strict';

    $.widget('mage.productAttributes', {
        _create: function () {
            this._on({
                'click': '_showPopup'
            });
        },

        _initModal: function () {
            var self = this;

            this.modal = $('<div id="create_new_attribute"/>').modal({
                 title: $.mage.__('New Attribute'),
                type: 'slide',
                buttons: [],
                opened: function () {
                    $(this).parent().addClass('modal-content-new-attribute');
                    self.iframe = $('<iframe id="create_new_attribute_container">').attr({
                        src: self._prepareUrl(),
                        frameborder: 0
                    });
                    self.modal.append(self.iframe);
                    self._changeIframeSize();
                    $(window).off().on('resize.modal', _.debounce(self._changeIframeSize.bind(self), 400));
                },
                closed: function () {
                    var doc = self.iframe.get(0).document;

                    if (doc && $.isFunction(doc.execCommand)) {
                        //IE9 break script loading but not execution on iframe removing
                        doc.execCommand('stop');
                        self.iframe.remove();
                    }
                    self.modal.data('modal').modal.remove();
                    $(window).off('resize.modal');
                }
            });
        },

        _getHeight: function () {
            var modal = this.modal.data('modal').modal,
                modalHead = modal.find('header'),
                modalHeadHeight = modalHead.outerHeight(),
                modalHeight = modal.outerHeight(),
                modalContentPadding = this.modal.parent().outerHeight() - this.modal.parent().height();

            return modalHeight - modalHeadHeight - modalContentPadding;
        },

        _getWidth: function () {
            return this.modal.width();
        },

        _changeIframeSize: function () {
            this.modal.parent().outerHeight(this._getHeight());
            this.iframe.outerHeight(this._getHeight());
            this.iframe.outerWidth(this._getWidth());

        },

        _prepareUrl: function () {
            var productSource,
                attributeSetId = '';

            if (this.options.dataProvider) {
                try {
                    productSource = registry.get(this.options.dataProvider);
                    attributeSetId = productSource.data.product['attribute_set_id'];
                } catch (e) {}
            }

            return this.options.url +
                (/\?/.test(this.options.url) ? '&' : '?') +
                'set=' + attributeSetId;
        },

        _showPopup: function () {
            this._initModal();
            this.modal.modal('openModal');
        }
    });

    return $.mage.productAttributes;
});


text:
// ZAP: 2013/07/02 Changed Vector to generic List
// ZAP: 2013/07/02 Changed API to public for future extensible Variant model
package org.parosproxy.paros.core.scanner;

import java.util.List;

import org.parosproxy.paros.network.HttpMessage;

public interface Variant {

    public void setMessage(HttpMessage msg);
    public List<NameValuePair> getParamList();
    public String setParameter(HttpMessage msg, NameValuePair originalPair, String param, String value);
    public String setEscapedParameter(HttpMessage msg, NameValuePair originalPair, String param, String value);

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Helotium chlorosplenioides Speg.

### Remarks
null


text:
using Mono.Unix;
using Mono.Unix.Native;
using System;
using System.Threading;

namespace SharpOCSP
{
	public class SignalHandler : IDisposable
	{
		public delegate void SignaledDelegate();
		private static Thread signaling_thread;
		private SignaledDelegate _sigusr1_delegate = null;
		private SignaledDelegate _sigusr2_delegate = null;

		private void signalHandlerThread()
		{
			UnixSignal[] signals = new UnixSignal [] {
				new UnixSignal (Signum.SIGUSR1),
				new UnixSignal (Signum.SIGUSR2),
			};

			while (true) {
				int index = UnixSignal.WaitAny (signals, -1);
				Signum signal = signals [index].Signum;
				signalHandler(signal);
			};
		}

		private void signalHandler(Signum signal)
		{
			switch (signal)
			{
			case Signum.SIGUSR1:
				_sigusr1_delegate();
				break;
			case Signum.SIGUSR2:
				_sigusr2_delegate();
				break;
			case Signum.SIGINT:
				Environment.Exit (1);
				break;
			default:
				break;
			}
		}
		public SignalHandler (SignaledDelegate sigusr1_delegate, SignaledDelegate sigusr2_delegate)
		{
			_sigusr1_delegate = sigusr1_delegate;
			_sigusr2_delegate = sigusr2_delegate;
			signaling_thread = new Thread(new ThreadStart(signalHandlerThread));
			signaling_thread.Start();
		}
        protected virtual void Dispose(bool nativeonly)
        {
            if(nativeonly)
            {
                return;
            }
            signaling_thread.Abort();
        }
		public void Dispose()
		{
            Dispose(true);
            GC.SuppressFinalize(this);
		}
	}
}


text:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class NathanI extends Robot
{
    public NathanI(){
        super(Color.blue);
    }

    public void init(){

    }

    /**
     * What your robot can do:
     * right() => move 1 to the right
     * left() => move 1 to the left
     * up() => move 1 up
     * down() => move 1 down
     * isClearRight() => true means no block to the right
     * isClearRight() => true means no block to the left
     * isClearUp() => true means no block up
     * isClearDown() => true means no block down
     */
    public void behave(){
        right();
    }
}


text:
var utils = require( "../../lib/utilities" ),
    loginClient = require( "../../lib/loginapi" ),
    makeClient = require( "../../lib/makeapi" ),
    metrics = require( "../../lib/metrics" );

module.exports = function( Project ) {
  return function( req, res, next ) {
    makeClient.id( res.locals.project.makeid ).then(function( err, make ) {
      var remixId;
      if ( err ) {
        metrics.increment( "project.load.error" );
        return res.json( 500, { error: err } );
      }

      if ( !make.length ) {
        metrics.increment( "project.make.load.error" );
        return res.json( 404, { error: "Make was not found" } );
      }
      req.projectJSON.tags = make[ 0 ].rawTags;

      if ( req.isRemix ) {
        remixId = req.projectJSON.remixedFrom;
      } else {
        remixId = res.locals.project.remixedFrom;
      }

      if ( remixId || remixId === 0 ) {
        Project.find({ id: remixId }, function( err, doc ) {
          if ( err ) {
            metrics.increment( "project.remixedFrom.removed" );
            return next( utils.error( 500, err ) );
          }

          if ( !doc ) {
            metrics.increment( "project.make.load.error" );
            return res.json( req.projectJSON );
          }

          req.projectJSON.remixedFrom = doc.id;

          loginClient.getUserByEmail( doc.email, function( err, user ) {
            if ( err || !user ) {
              // If there's an error, user doesn't exist on loginapi so we use popcorn.wmc.o
              // Or there could actually be an error of some sort.
              // TODO FIX THIS API
              req.projectJSON.remixedFromUrl = "http://popcorn.webmadecontent.org/" + doc.id.toString( 36 );
            } else {
              req.projectJSON.remixedFromUrl = utils.embedShellURL( doc.author, doc.id );
            }

            if ( req.isRemix ) {
              metrics.increment( "user.remix" );
            }

            res.json( req.projectJSON );
          });
        });
        return;
      }

      res.json( req.projectJSON );
    });
  };
};


text:
{% load i18n %}

      {% if comment_list %}

          {% for comment in comment_list %}

                {% if comment.page %}

                  {{ comment.page }}

                {% endif %}

                  {% trans "Comment by" %}
                  {{ comment.username }},
                  {{ comment.date_added }}

                {% for cr in comment.commentrelation_set.all %}

                    {{ cr.content_object }}{% if cr.page %}, {% trans "Page" %} {{ cr.page }}{% endif %}

                {% endfor %}

                {{ comment.comment|linebreaksbr }}

          {% endfor %}

          {% if comment_list|length < num_total_comments %}

              {% trans "All Comments" %} ({{ num_total_comments }})

          {% endif %}

      {% else %}

        {% trans "No comments yet." %}

      {% endif %}


text:
CKEDITOR.editorConfig = function( config ) {
    config.toolbar_DrupalCustom = [
      ['Source'],
      ['Cut','Copy','Paste','PasteText','-','SpellChecker', 'Scayt'],
      ['Undo','Redo','Find','Replace','-','SelectAll','RemoveFormat'],
      ['Image','HorizontalRule','Smiley','SpecialChar'],
      ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
      ['NumberedList','BulletedList','-','Blockquote'],
      ['Link','Unlink','Anchor','LinkToNode', 'LinkToMenu'],
      ['Format','Font','FontSize'],
      ['TextColor','BGColor'],
      ['Maximize', 'ShowBlocks'],
      ['DrupalBreak', 'DrupalPageBreak']
     ];
};


text:
#ifndef AXIS2_QPID_RECEIVER_INTERFACE_H
#define AXIS2_QPID_RECEIVER_INTERFACE_H

#include <axis2_util.h>
#include <axis2_conf_init.h>

#ifdef __cplusplus
extern "C"
{
#endif

	typedef struct axis2_qpid_receiver_resource_pack
	{
		void* qpid_receiver;
	}axis2_qpid_receiver_resource_pack_t;

	AXIS2_EXTERN axis2_qpid_receiver_resource_pack_t* AXIS2_CALL
	axis2_qpid_receiver_create(
		const axutil_env_t* env,
		axis2_conf_ctx_t* conf_ctx);

	AXIS2_EXTERN axis2_status_t AXIS2_CALL
		axis2_qpid_receiver_start(
		axis2_qpid_receiver_resource_pack_t* receiver_resource_pack,
		const axutil_env_t* env);

	AXIS2_EXTERN axis2_bool_t AXIS2_CALL
		axis2_qpid_receiver_is_running(
		axis2_qpid_receiver_resource_pack_t* receiver_resource_pack,
		const axutil_env_t* env);

	AXIS2_EXTERN void AXIS2_CALL
		axis2_qpid_receiver_free(
		axis2_qpid_receiver_resource_pack_t* receiver_resource_pack,
		const axutil_env_t* env);

#ifdef __cplusplus
}
#endif

#endif


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

<title>com.centurylink.mdw.workflow.activity.sync (MDW 6 API JavaDocs)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

com.centurylink.mdw.workflow.activity.sync

Classes

SynchronizationActivity


text:
typedef struct bnoode{
	record r;
	struct bnoode *c[BINARY];
} bnode;

typedef struct parentchild{
	bnode *parent;	// pointer to parent node of node of interest
	int which;	// tells us whether it is a left or right child
} pc;

int
locate(pc *p, char *key);

void
find_min(pc *p);

void
set_dummy(pc *p, bnode *dummy);

bnode *
zap(pc *p);

void
dump_it(bnode *this, int offset);

// create an empty bst that has a dummy head node
void *
initialize(void)
{
	bnode *dummy; // its right pointer points to the root (when it exists)
	char zero[1] = MINSTRING;
	dummy = (bnode *) smalloc(sizeof(bnode));
	set_key(&dummy->r,zero);	// yes, this is a dummy head node!
	dummy->c[LEFT] = NULL;
	dummy->c[RIGHT] = NULL;

	return dummy;
}

// find the location of the key: if it is not present, the returned
// pc should have now set to NULL and parent/which set up so that the key
// would be inserted as the 'which' child of parent.
int
locate(pc *p, char *key)
{
	bnode *this = p->parent->c[p->which];	// pointer to the child of
						// interest

	if(this == NULL){		// if we have fallen off the tree
		return FALSE;	// the key is not present, but
				// return this location, where it
			// *should* be
	}
	if(comp_key(key,get_key(&this->r)) < 0){
		p->parent = this;
		p->which = LEFT;
		return locate(p,key);	// in tree
	}
	if(comp_key(key,get_key(&this->r)) > 0){
		p->parent = this;
		p->which = RIGHT;
		return locate(p,key);
	}

	// if we have reached here, then we have found the key
	return TRUE;
}

// here we insert a (new) record into the bst
int
insert(void *ds, char *k, int v, FILE *output)
{
	bnode *dummy = (bnode *) ds;
	pc pw;
	pc *p = &pw;
	bnode *new;
	bnode *found;
	int old;

	set_dummy(p,dummy);
	// find the correct place for insertion
	if(locate(p,k)){
		found = p->parent->c[p->which];
		old = get_value(&found->r);
		set_value(&found->r,v);
		if(output != NULL){
			report_insert(TRUE,k,old,v,output);
		}
	} else {
		// set up the new node, which will be a leaf (NULL children)
		new = (bnode *) smalloc(sizeof(bnode));
		set_key(&new->r,k);
		set_value(&new->r,v);
		new->c[LEFT] = NULL;
		new->c[RIGHT] = NULL;
		// connect the parent to the new node, appropriately
		p->parent->c[p->which] = new;
		if(output != NULL){
			report_insert(FALSE,k,NOTFOUND,v,output);
		}
	}
	return TRUE;
}

// deletes the record corresponding to the given key
void
destroy(void *ds, char *key)
{
	pc pw;
	pc *p = &pw;
	bnode *dummy = (bnode *) ds;

	// find out where the node corresponding to this key is
	set_dummy(p,dummy);
	if(locate(p,key)){
		free(zap(p));
	} else {
		fprintf(stderr, "Couldn't find key %s to destroy.\n",key);
		return;
	}
}

// does the hard work of deleting the record
bnode *
zap(pc *p)
{
	pc mw;
	pc *m = &mw;
	bnode *this;
	bnode *replacement;
	this = p->parent->c[p->which];

	// if has neither child
	if(this->c[LEFT] == NULL && this->c[RIGHT] == NULL){
		// just ignore the node
		p->parent->c[p->which] = NULL;
		// and return it to be freed or reused
		return this;
	}
	// if has only right child
	if(this->c[LEFT] == NULL){
		// connect the parent to the right child
		p->parent->c[p->which] = this->c[RIGHT];
		return this;
	}
	// similarly, if has only left child
	if(this->c[RIGHT] == NULL){
		p->parent->c[p->which] = this->c[LEFT];
		return this;
	}
	// else has both kids

	// so find the minimum node in the right subtree
	m->parent = this;
	m->which = RIGHT;

	// sets up m to refer to the correct part of the tree
	find_min(m);
	replacement = zap(m);

	p->parent->c[p->which] = replacement;
	replacement->c[LEFT] = this->c[LEFT];
	replacement->c[RIGHT] = this->c[RIGHT];

	return this;
}

void
find_min(pc *m)
{
	// if there is a left child
	bnode *this = m->parent->c[LEFT];
	if(this->c[LEFT] != NULL){
		// keep going
		m->parent = this;
		m->which = LEFT;
		find_min(m);
	}
}

// given a key, put the value corrsponding to it in the string s
int
find(void *ds, char *key, int *v)
{
	bnode *dummy = (bnode *) ds;
	pc pw;
	pc *p = &pw;

	set_dummy(p,dummy);
	// find out the appropriate location of where this key should be
	if(locate(p,key)){
		*v = get_value(&p->parent->c[p->which]->r);
		return TRUE;
	} else {
		return FALSE;
	}

}

void
set_dummy(pc *p, bnode *dummy)
{
	p->parent = dummy;
	p->which = RIGHT;
}

void
test_dump(void *ds)
{
	bnode *dummy = (bnode *) ds;
	printf("--- begin dump ---\n");
	if(dummy->c[RIGHT] != NULL){
		dump_it(dummy->c[RIGHT],0);
	}
	printf("--- end dump ---\n");
}

void
dump_it(bnode *this, int offset)
{
	char s[2*MAXSTR];
	if(this->c[RIGHT] != NULL){
		dump_it(this->c[RIGHT],offset+EXTRA);
	}
        record_to_string(s,&this->r);
	printf("%*s%s\n",offset,"",s);
	if(this->c[LEFT] != NULL){
		dump_it(this->c[LEFT],offset+EXTRA);
	}

}


text:
package org.jbpm.kie.services.impl.admin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jbpm.kie.services.impl.admin.commands.AddPeopleAssignmentsCommand;
import org.jbpm.kie.services.impl.admin.commands.AddTaskInputsCommand;
import org.jbpm.kie.services.impl.admin.commands.CancelTaskDeadlineCommand;
import org.jbpm.kie.services.impl.admin.commands.ListTaskNotificationsCommand;
import org.jbpm.kie.services.impl.admin.commands.ListTaskReassignmentsCommand;
import org.jbpm.kie.services.impl.admin.commands.RemovePeopleAssignmentsCommand;
import org.jbpm.kie.services.impl.admin.commands.RemoveTaskDataCommand;
import org.jbpm.kie.services.impl.admin.commands.ScheduleTaskDeadlineCommand;
import org.jbpm.runtime.manager.impl.AbstractRuntimeManager;
import org.jbpm.services.api.RuntimeDataService;
import org.jbpm.services.api.TaskNotFoundException;
import org.jbpm.services.api.UserTaskService;
import org.jbpm.services.api.admin.ExecutionErrorNotFoundException;
import org.jbpm.services.api.admin.TaskNotification;
import org.jbpm.services.api.admin.TaskReassignment;
import org.jbpm.services.api.admin.UserTaskAdminService;
import org.jbpm.services.api.model.UserTaskInstanceDesc;
import org.jbpm.services.api.service.ServiceRegistry;
import org.jbpm.shared.services.impl.QueryManager;
import org.jbpm.shared.services.impl.TransactionalCommandService;
import org.jbpm.shared.services.impl.commands.QueryNameCommand;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.query.QueryContext;
import org.kie.api.task.model.I18NText;
import org.kie.api.task.model.OrganizationalEntity;
import org.kie.internal.identity.IdentityProvider;
import org.kie.internal.runtime.error.ExecutionError;
import org.kie.internal.runtime.manager.RuntimeManagerRegistry;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
import org.kie.internal.task.api.TaskDeadlinesService.DeadlineType;
import org.kie.internal.task.api.TaskModelProvider;
import org.kie.internal.task.api.model.Deadline;
import org.kie.internal.task.api.model.EmailNotification;
import org.kie.internal.task.api.model.EmailNotificationHeader;
import org.kie.internal.task.api.model.Escalation;
import org.kie.internal.task.api.model.InternalI18NText;
import org.kie.internal.task.api.model.Language;
import org.kie.internal.task.api.model.Notification;
import org.kie.internal.task.api.model.Reassignment;

public class UserTaskAdminServiceImpl implements UserTaskAdminService {

    public static final int POT_OWNER = 0;
    public static final int EXCL_OWNER = 1;
    public static final int ADMIN = 2;

    private UserTaskService userTaskService;
    private RuntimeDataService runtimeDataService;
    private IdentityProvider identityProvider;

    private TransactionalCommandService commandService;

    public UserTaskAdminServiceImpl() {
        ServiceRegistry.get().register(UserTaskAdminService.class.getSimpleName(), this);
    }

    public void setUserTaskService(UserTaskService userTaskService) {
        this.userTaskService = userTaskService;
    }

    public void setRuntimeDataService(RuntimeDataService runtimeDataService) {
        this.runtimeDataService = runtimeDataService;
    }

    public void setIdentityProvider(IdentityProvider identityProvider) {
        this.identityProvider = identityProvider;
    }

    public void setCommandService(TransactionalCommandService commandService) {
        this.commandService = commandService;
    }

    @Override
    public void addPotentialOwners(long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addPotentialOwners(null, taskId, removeExisting, orgEntities);
    }

    @Override
    public void addPotentialOwners(String deploymentId, long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addPeopleAssignment(deploymentId, taskId, removeExisting, POT_OWNER, orgEntities);
    }

    @Override
    public void addPotentialOwners(String userId, String deploymentId, long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addPeopleAssignment(userId, deploymentId, taskId, removeExisting, POT_OWNER, orgEntities);
    }

    @Override
    public void addExcludedOwners(long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addExcludedOwners(null, taskId, removeExisting, orgEntities);
    }

    @Override
    public void addExcludedOwners(String deploymentId, long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addPeopleAssignment(deploymentId, taskId, removeExisting, EXCL_OWNER, orgEntities);
    }

    @Override
    public void addExcludedOwners(String userId, String deploymentId, long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addPeopleAssignment(userId, deploymentId, taskId, removeExisting, EXCL_OWNER, orgEntities);
    }

    @Override
    public void addBusinessAdmins(long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addBusinessAdmins(null, taskId, removeExisting, orgEntities);
    }

    @Override
    public void addBusinessAdmins(String deploymentId, long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addPeopleAssignment(deploymentId, taskId, removeExisting, ADMIN, orgEntities);
    }

    @Override
    public void addBusinessAdmins(String userId, String deploymentId, long taskId, boolean removeExisting, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        addPeopleAssignment(userId, deploymentId, taskId, removeExisting, ADMIN, orgEntities);
    }

    @Override
    public void removePotentialOwners(long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        removePotentialOwners(null, taskId, orgEntities);
    }

    @Override
    public void removePotentialOwners(String userId, String deploymentId, long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        removePeopleAssignment(userId, deploymentId, taskId, POT_OWNER, orgEntities);
    }

    @Override
    public void removePotentialOwners(String deploymentId, long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        removePeopleAssignment(deploymentId, taskId, POT_OWNER, orgEntities);
    }

    @Override
    public void removeExcludedOwners(long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        removeExcludedOwners(null, taskId, orgEntities);
    }

    @Override
    public void removeExcludedOwners(String userId, String deploymentId, long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        removePeopleAssignment(userId, deploymentId, taskId, EXCL_OWNER, orgEntities);
    }

    @Override
    public void removeExcludedOwners(String deploymentId, long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        removePeopleAssignment(deploymentId, taskId, EXCL_OWNER, orgEntities);
    }

    @Override
    public void removeBusinessAdmins(long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException, IllegalStateException {
        removeBusinessAdmins(null, taskId, orgEntities);
    }

    @Override
    public void removeBusinessAdmins(String deploymentId, long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException, IllegalStateException {
        removePeopleAssignment(deploymentId, taskId, ADMIN, orgEntities);
    }

    @Override
    public void removeBusinessAdmins(String userId, String deploymentId, long taskId, OrganizationalEntity... orgEntities) throws TaskNotFoundException, IllegalStateException {
        removePeopleAssignment(userId, deploymentId, taskId, ADMIN, orgEntities);
    }

    @Override
    public void addTaskInput(long taskId, String name, Object value) throws TaskNotFoundException {
        addTaskInput(null, taskId, name, value);
    }

    @Override
    public void addTaskInput(String deploymentId, long taskId, String name, Object value) throws TaskNotFoundException {
        Map<String, Object> data = new HashMap<>();
        data.put(name, value);
        addTaskInputs(deploymentId, taskId, data);
    }

    @Override
    public void addTaskInputs(long taskId, Map<String, Object> data) throws TaskNotFoundException {
        addTaskInputs(null, taskId, data);
    }

    @Override
    public void addTaskInputs(String deploymentId, long taskId, Map<String, Object> data) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new AddTaskInputsCommand(identityProvider.getName(), taskId, data));
    }

    @Override
    public void removeTaskInputs(long taskId, String... name) throws TaskNotFoundException {
        removeTaskInputs(null, taskId, name);
    }

    @Override
    public void removeTaskInputs(String deploymentId, long taskId, String... name) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new RemoveTaskDataCommand(identityProvider.getName(), taskId, Arrays.asList(name), true));

    }

    @Override
    public void removeTaskOutputs(long taskId, String... name) throws TaskNotFoundException {
        removeTaskOutputs(null, taskId, name);
    }

    @Override
    public void removeTaskOutputs(String deploymentId, long taskId, String... name) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new RemoveTaskDataCommand(identityProvider.getName(), taskId, Arrays.asList(name), false));

    }

    @Override
    public Long reassignWhenNotStarted(long taskId, String timeExpression, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        return reassignWhenNotStarted(null, taskId, timeExpression, orgEntities);
    }

    @Override
    public Long reassignWhenNotStarted(String deploymentId, long taskId, String timeExpression, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        return reassign(deploymentId, taskId, timeExpression, DeadlineType.START, orgEntities);
    }

    @Override
    public Long reassignWhenNotCompleted(long taskId, String timeExpression, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        return reassignWhenNotCompleted(null, taskId, timeExpression, orgEntities);
    }

    @Override
    public Long reassignWhenNotCompleted(String deploymentId, long taskId, String timeExpression, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        return reassign(deploymentId, taskId, timeExpression, DeadlineType.END, orgEntities);

    }

    @Override
    public Long notifyWhenNotStarted(long taskId, String timeExpression, Notification notification) throws TaskNotFoundException {
        return notifyWhenNotStarted(null, taskId, timeExpression, notification);
    }

    @Override
    public Long notifyWhenNotStarted(String deploymentId, long taskId, String timeExpression, Notification notification) throws TaskNotFoundException {
        return notify(deploymentId, taskId, timeExpression, DeadlineType.START, notification);

    }

    @Override
    public Long notifyWhenNotCompleted(long taskId, String timeExpression, Notification notification) throws TaskNotFoundException {
        return notifyWhenNotCompleted(null, taskId, timeExpression, notification);
    }

    @Override
    public Long notifyWhenNotCompleted(String deploymentId, long taskId, String timeExpression, Notification notification) throws TaskNotFoundException {
        return notify(deploymentId, taskId, timeExpression, DeadlineType.END, notification);

    }

    @Override
    public Collection<TaskReassignment> getTaskReassignments(long taskId, boolean activeOnly) throws TaskNotFoundException {
        return getTaskReassignments(null, taskId, activeOnly);
    }

    @Override
    public Collection<TaskReassignment> getTaskReassignments(String deploymentId, long taskId, boolean activeOnly) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        return userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new ListTaskReassignmentsCommand(identityProvider.getName(), taskId, activeOnly));
    }

    @Override
    public Collection<TaskNotification> getTaskNotifications(long taskId, boolean activeOnly) throws TaskNotFoundException {
        return getTaskNotifications(null, taskId, activeOnly);
    }

    @Override
    public Collection<TaskNotification> getTaskNotifications(String deploymentId, long taskId, boolean activeOnly) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        return userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new ListTaskNotificationsCommand(identityProvider.getName(), taskId, activeOnly));
    }

    @Override
    public void cancelNotification(long taskId, long notificationId) throws TaskNotFoundException {
        cancelNotification(null, taskId, notificationId);
    }

    @Override
    public void cancelNotification(String deploymentId, long taskId, long notificationId) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new CancelTaskDeadlineCommand(identityProvider.getName(), taskId, notificationId));
    }

    @Override
    public void cancelReassignment(long taskId, long reassignmentId) throws TaskNotFoundException {
        cancelReassignment(null, taskId, reassignmentId);
    }

    @Override
    public void cancelReassignment(String deploymentId, long taskId, long reassignmentId) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new CancelTaskDeadlineCommand(identityProvider.getName(), taskId, reassignmentId));
    }

    @Override
    public EmailNotification buildEmailNotification(String subjectStr, List<OrganizationalEntity> recipients, String bodyStr, String fromStr, String replyToStr) {
        EmailNotification emailNotification = TaskModelProvider.getFactory().newEmialNotification();

        Map<Language, EmailNotificationHeader> emailHeaders = new HashMap<Language, EmailNotificationHeader>();
        List<I18NText> subjects = new ArrayList<I18NText>();
        List<I18NText> names = new ArrayList<I18NText>();

        String locale = "en-UK";

        EmailNotificationHeader emailHeader = TaskModelProvider.getFactory().newEmailNotificationHeader();
        emailHeader.setBody(bodyStr);
        emailHeader.setFrom(fromStr);
        emailHeader.setReplyTo(replyToStr);
        emailHeader.setLanguage(locale);
        emailHeader.setSubject(subjectStr);

        Language lang = TaskModelProvider.getFactory().newLanguage();
        lang.setMapkey(locale);
        emailHeaders.put(lang, emailHeader);

        I18NText subject = TaskModelProvider.getFactory().newI18NText();
        ((InternalI18NText) subject).setLanguage(locale);
        ((InternalI18NText) subject).setText(emailHeader.getSubject());;

        subjects.add(subject);
        names.add(subject);

        emailNotification.setEmailHeaders(emailHeaders);
        emailNotification.setNames(names);
        emailNotification.setRecipients(new ArrayList<>(recipients));
        emailNotification.setSubjects(subjects);

        return emailNotification;
    }

    /*
     * Error handling related
     */

    @Override
    public List<ExecutionError> getErrors(boolean includeAcknowledged, QueryContext queryContext) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("ack", getAckMode(includeAcknowledged));
        applyQueryContext(params, queryContext);

        List<ExecutionError> execErrors = commandService.execute(new QueryNameCommand<List<ExecutionError>>("getTaskErrors",params));
        return execErrors;
    }

    @Override
    public List<ExecutionError> getErrorsByTaskId(long taskId, boolean includeAcknowledged, QueryContext queryContext) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("taskId", taskId);
        params.put("ack", getAckMode(includeAcknowledged));
        applyQueryContext(params, queryContext);

        List<ExecutionError> execErrors = commandService.execute(new QueryNameCommand<List<ExecutionError>>("getErrorsByTaskId",params));
        return execErrors;
    }

    @Override
    public List<ExecutionError> getErrorsByTaskName(String taskName, boolean includeAcknowledged, QueryContext queryContext) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("taskName", taskName);
        params.put("ack", getAckMode(includeAcknowledged));
        applyQueryContext(params, queryContext);

        List<ExecutionError> execErrors = commandService.execute(new QueryNameCommand<List<ExecutionError>>("getErrorsByTaskName",params));
        return execErrors;
    }

    @Override
    public List<ExecutionError> getErrorsByTaskName(String processId, String taskName, boolean includeAcknowledged, QueryContext queryContext) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("processId", processId);
        params.put("taskName", taskName);
        params.put("ack", getAckMode(includeAcknowledged));
        applyQueryContext(params, queryContext);

        List<ExecutionError> execErrors = commandService.execute(new QueryNameCommand<List<ExecutionError>>("getErrorsByTaskNameProcessId",params));

        return execErrors;
    }

    @Override
    public List<ExecutionError> getErrorsByTaskName(String deploymentId, String processId, String taskName, boolean includeAcknowledged, QueryContext queryContext) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("deploymentId", deploymentId);
        params.put("processId", processId);
        params.put("taskName", taskName);
        params.put("ack", getAckMode(includeAcknowledged));
        applyQueryContext(params, queryContext);

        List<ExecutionError> execErrors = commandService.execute(new QueryNameCommand<List<ExecutionError>>("getErrorsByTaskNameProcessIdDeploymentId",params));

        return execErrors;
    }

    @Override
    public void acknowledgeError(String... errorId) throws ExecutionErrorNotFoundException {

        for (String error : errorId) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("errorId", error);
            params.put("ack", new Short("0"));
            List<ExecutionError> execErrors = commandService.execute(new QueryNameCommand<List<ExecutionError>>("getErrorById",params));

            if (execErrors.isEmpty()) {
                throw new ExecutionErrorNotFoundException("No execution error found for id " + errorId);
            }

            ExecutionError errorInstance = execErrors.get(0);
            RuntimeManager runtimeManager = RuntimeManagerRegistry.get().getManager(errorInstance.getDeploymentId());
            if (runtimeManager != null) {
                ((AbstractRuntimeManager) runtimeManager).getExecutionErrorManager().getStorage().acknowledge(identityProvider.getName(), errorInstance.getErrorId());
            }
        }
    }

    @Override
    public ExecutionError getError(String errorId) throws ExecutionErrorNotFoundException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("errorId", errorId);
        List<ExecutionError> execErrors = commandService.execute(new QueryNameCommand<List<ExecutionError>>("getErrorByIdSkipAckCheck",params));

        if (execErrors.isEmpty()) {
            throw new ExecutionErrorNotFoundException("No execution error found for id " + errorId);
        }
        ExecutionError error = execErrors.get(0);
        return error;
    }

    /*
     * Internal methods
     */
    protected void addPeopleAssignment(String userId, String deploymentId, long taskId, boolean removeExisting, int type, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new AddPeopleAssignmentsCommand(userId, taskId, type, orgEntities, removeExisting));
    }

    protected void addPeopleAssignment(String deploymentId, long taskId, boolean removeExisting, int type, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new AddPeopleAssignmentsCommand(identityProvider.getName(), taskId, type, orgEntities, removeExisting));
    }

    protected void removePeopleAssignment(String userId, String deploymentId, long taskId, int type, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new RemovePeopleAssignmentsCommand(userId, taskId, type, orgEntities));
    }

    protected void removePeopleAssignment(String deploymentId, long taskId, int type, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new RemovePeopleAssignmentsCommand(identityProvider.getName(), taskId, type, orgEntities));
    }

    protected Long reassign(String deploymentId, long taskId, String timeExpression, DeadlineType type, OrganizationalEntity... orgEntities) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        if(timeExpression == null || timeExpression.isEmpty()) {
            throw new IllegalArgumentException("Invalid time expression");
        }

        if(orgEntities == null || orgEntities.length <= 0) {
            throw new IllegalArgumentException("Invalid org entity");
        }

        List<Escalation> escalations = new ArrayList<Escalation>();
        Deadline taskDeadline = TaskModelProvider.getFactory().newDeadline();
        taskDeadline.setEscalations(escalations);

        Escalation escalation = TaskModelProvider.getFactory().newEscalation();
        escalations.add(escalation);
        escalation.setName("Admin reassignment for task " + taskId);

        List<Reassignment> reassignments = new ArrayList<Reassignment>();
        Reassignment reassignment = TaskModelProvider.getFactory().newReassignment();
        reassignment.setPotentialOwners(new ArrayList<>(Arrays.asList(orgEntities)));

        reassignments.add(reassignment);

        escalation.setReassignments(reassignments);

        return userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new ScheduleTaskDeadlineCommand(identityProvider.getName(), taskId, type, taskDeadline, timeExpression));
    }

    protected Long notify(String deploymentId, long taskId, String timeExpression, DeadlineType type, Notification notification) throws TaskNotFoundException {
        UserTaskInstanceDesc task = runtimeDataService.getTaskById(taskId);
        validateTask(deploymentId, taskId, task);

        List<Escalation> escalations = new ArrayList<Escalation>();
        Deadline taskDeadline = TaskModelProvider.getFactory().newDeadline();
        taskDeadline.setEscalations(escalations);

        Escalation escalation = TaskModelProvider.getFactory().newEscalation();
        escalations.add(escalation);
        escalation.setName("Admin notification for task " + taskId);

        List<Notification> notifications = new ArrayList<Notification>();
        notifications.add(notification);

        escalation.setNotifications(notifications);

        return userTaskService.execute(task.getDeploymentId(), ProcessInstanceIdContext.get(task.getProcessInstanceId()),
                new ScheduleTaskDeadlineCommand(identityProvider.getName(), taskId, type, taskDeadline, timeExpression));
    }

    protected void applyQueryContext(Map<String, Object> params, QueryContext queryContext) {
        if (queryContext != null) {
            params.put("firstResult", queryContext.getOffset());
            params.put("maxResults", queryContext.getCount());

            if (queryContext.getOrderBy() != null && !queryContext.getOrderBy().isEmpty()) {
                params.put(QueryManager.ORDER_BY_KEY, queryContext.getOrderBy());

                if (queryContext.isAscending()) {
                    params.put(QueryManager.ASCENDING_KEY, "true");
                } else {
                    params.put(QueryManager.DESCENDING_KEY, "true");
                }
            }
        }
    }

    protected List<Short> getAckMode(boolean includeAcknowledged) {
        List<Short> ackMode = new ArrayList<>();
        ackMode.add(new Short("0"));
        if (includeAcknowledged) {
            ackMode.add(new Short("1"));
        }

        return ackMode;
    }

    protected void validateTask(String deploymentId, Long taskId, UserTaskInstanceDesc task) {
        if (task == null) {
            throw new TaskNotFoundException("Task with id " + taskId + " was not found");
        }

        if (deploymentId != null && !task.getDeploymentId().equals(deploymentId)) {
            throw new TaskNotFoundException("Task with id " + taskId + " is not associated with " + deploymentId);
        }
    }
}


text:
import { EventEmitter } from 'events';

import dispatcher from '../dispatcher';

class BlogStore extends EventEmitter {
    constructor() {
        super();

        //this is a kind of initial load message.
        // it will be overwrite till the first GET :P
        this.blogs = [
            {
                'id': 38,
                'title': 'loading',
                'content': ''
            }
        ];
    }

    createBlog(data) {
        const id = Date.now(),
            title = data.data.title,
            content = data.data.content;

        this.blogs.unshift({
            id,
            title,//thanks es6 for all the magic xD
            content
        });

        this.emit('change');
    }

    getAll() {
        return this.blogs;
    }

    handleActions(action) {
        switch (action.type) {
        case 'CREATE_BLOG': {
            this.createBlog(action.data);
            break;
        }
        case 'RECEIVE_BLOGS': {
            this.blogs = action.blog;
            this.emit('change');
            break;
        }
        case 'DELETE_BLOG': {
            this.blogs.splice(this.searchInJson(action.id), 1);
            this.emit('change');
            break;
        }
        case 'UPDATE_BLOG': {
            this.blogs[ this.searchInJson(action.data.id) ] = action.data;
            this.emit('change');
            break;
        }
        }
    }

    searchInJson(id) {
        for (let i=0 ; i < this.blogs.length ; i++) {
            if (this.blogs[i]['id'] === id) {
                return i;
            }
        }
    }
}

const blogStore = new BlogStore;

dispatcher.register(blogStore.handleActions.bind(blogStore));
export default blogStore;