text:
package io.reactivej.dcf.demo.test;

import io.reactivej.dcf.common.component.ClusterRootComponent;
import io.reactivej.dcf.common.info.LeaderInfo;
import io.reactivej.dcf.common.info.LeaderState;
import io.reactivej.dcf.common.info.TaskInfo;
import io.reactivej.dcf.common.info.WorkerState;
import io.reactivej.dcf.common.init.SystemConfig;
import io.reactivej.dcf.common.topology.GlobalTopologyId;
import io.reactivej.dcf.common.topology.Topology;
import io.reactivej.dcf.common.topology.client.DCFListener;
import io.reactivej.dcf.common.topology.client.DCFManager;
import io.reactivej.dcf.mock.ClusterMock;
import io.reactivej.dcf.mock.JobClusterMock;
import io.reactivej.dcf.mock.ReactiveSystemMock;

import java.io.Serializable;

import java.util.concurrent.CountDownLatch;

/***
 * @author heartup@gmail.com
 */
public abstract class DCFDemo {

    public void submitTopologyTest() throws InterruptedException {
        SystemConfig.setValue(SystemConfig.task_port_min, "9000");
        SystemConfig.setValue(SystemConfig.task_port_max, "9200");
        SystemConfig.setValue(SystemConfig.heartbeat_interval, "10000");
        ClusterMock cluster = JobClusterMock.start(1);

        ReactiveSystemMock system = new ReactiveSystemMock();
        system.setCluster(cluster);
        system.setSystemId("client");
        system.setPort(8998);
        system.setRootComponentClass(ClusterRootComponent.class.getName());
        system.init();

        final CountDownLatch waiter = new CountDownLatch(1);

        final DCFManager manager = new DCFManager(system);

        manager.setListener(new DCFListener() {
            @Override
            public void onTopologySubmitted(Topology topology) {
                System.out.println(topology.getTopologyId() + "提交成功");
                if (manager != null)
                    manager.startTopology(topology.getTopologyId());
            }

            @Override
            public void onTopologyStarted(Topology topology) {
                System.out.println(topology.getTopologyId() + "启动成功");
            }

            @Override
            public void onTopologyKilled(Topology topology) {

            }

            @Override
            public void onTopologyFinished(Topology topology, Serializable result) {
                System.out.println(topology.getTopologyId() + "执行结果: " + result.toString());
                waiter.countDown();
            }

            @Override
            public void onTopologyTerminated(Topology topology) {

            }

            @Override
            public void onException(Throwable e) {

            }

            @Override
            public void onTopologyMessage(GlobalTopologyId topologyId, Serializable message) {

            }

            @Override
            public void onLeaderStateUpdated(LeaderState state) {

            }

            @Override
            public void onLeaderInfoUpdated(LeaderInfo info) {

            }

            @Override
            public void onWorkerStateUpdated(WorkerState state) {

            }

            @Override
            public void onTaskStateUpdated(TaskInfo taskInfo) {

            }
        }, false);

        Thread.currentThread().sleep(3000);
        manager.submitTopology(createTestTopology());

        waiter.await();
    }

    protected abstract Topology createTestTopology();
}


text:
cmd_lock="i3lock"
cmd_sleep="systemctl suspend"
cmd_hibernate="systemctl hibernate"

entries=(
    "Chromium               : chromium"
    "Keepass X2             : keepassx2"
    "gvim                   : gvim"
    "Qt Creator             : qtcreator"
    "Color Selector         : gcolor2"
    "Font Selector          : fontsel"
    "Font Preview           : waterfall"
    "VNC                    : remmina"
    "GIMP                   : gimp"
    "RAW photo converter    : rawtherapee"
    "Blender                : blender"
    "Tracktion 7            : Tracktion7"
    # "QJackCtl             : qjackctl"
    "QSynth                 : qsynth"
    "TuxGuitar              : tuxguitar"
    "MPD client Cantata     : cantata"
    "EasyTag                : easytag"
    "Sketchup 2016          : wine C:\\\\windows\\\\command\\\\start.exe /d \"C:\\\\Program Files\\\\SketchUp\\\\SketchUp 2016\" \"C:\\\\Program Files\\\\SketchUp\\\\SketchUp 2016\\\\SketchUp.exe\""
    "xzoom                  : xzoom"
    "----------- : "
    "LibreOffice Calc         : libreoffice --calc"
    "LibreOffice Writer       : libreoffice --writer"
    "----------- : "
    "GTK theme              : lxappearance"
    "Qt theme               : qt5ct"
    # "Compton              : compton-conf"
    "Configure Tint2        : tint2conf"
    "Select Wallpaper       : nitrogen"
    # "Random Wallpaper     : wallpaper-wallhaven-dl.sh -m random -c 101 -f 101 -r 1920x1080"
    "----------- : "
    "Lock                   : $cmd_lock"
    "Lock & Sleep           : $cmd_lock && $cmd_sleep"
    "Hibernate              : $cmd_hibernate"
)

    # join the list of entries with newline, extract portion before the ":" separator

selection=$( printf "%s\n" "${entries[@]}" \
    | sed -n "s/:.*$//p" \
    | sed -n "s/[[:space:]]*$//p" \
    | rofi -dmenu -i -format i -p 'quickmenu:' -columns 1 -width 13 -lines 30 -location 0)
#echo $selection

if [ "$selection" != "" ]
then
    command=${entries[$selection]}
    # extract portion after ":" as shell command
    command=$(echo $command | sed "s/^.*://")
    #echo $command
    exec $command
fi

redpajama_set_name: RedPajamaGithub


text:
var present = require('present-express');
var Candidate = require('./candidate');

module.exports = present.extend(Candidate, function(data) {
  this.template = 'candidates/list-empty';
})


text:
package com.afterroot.toucherlegacy;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {
    public String TAG = "MyBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: Received");
        Toast.makeText(context, "Something Removed", Toast.LENGTH_SHORT).show();
        if (intent != null) {
            try {
                if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
                    Log.d(TAG, "onReceive: Raw " + intent.getData());
                    Log.d(TAG, "onReceive: host " + intent.getData().getHost());
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
    }
}


text:
class Action < Template
  include MongoMapper::Document

  belongs_to :section
  key :section_id

  private
  def content_type
    @content_type ||= section.content_type_as_const
  end

  def context
    @context ||= Congo::ContentTypeContext.new(content_type, section.website)
  end
end


text:
export const arraysEqual = (actual, expected) => (
  actual.length === expected.length &&
  actual.every((element, index) => element === expected[index])
)


text:
typedef struct Trie_ Trie;

Trie* Trie_New(void);

void Trie_Delete(Trie* self);

bool Trie_Set(Trie* self, unsigned char* key, int kenlen, void* entry, void** old);

void* Trie_Find(Trie* self, unsigned char* key, int keylen);

#endif //MYPROJ_TRIE_H


text:
title: 'How about busting a paradigm today? The 9-point exercise...'
date: 2014-04-12T12:20:00.000-06:00
draft: false
slug: how-about-busting-paradigm-today-9
tags: [Art Inspirations]
---

This one outta help bend your mind back into shape...

from
[The Art of Possibility](http://www.amazon.com/Art-Possibility-Transforming-Professional-Personal/dp/0875847706)

![](/images/blog/legacy/9+point+before001.jpg)

Ready for the solution? Its past the jump.

![](/images/blog/legacy/9+point+after002.jpg)


text:
Docker base image for a nginx web server
========================================

A base image for a nginx web server build on top of an archlinux base image.


text:
{-------------------------------------------------------------------------------
 MorphGrammar
 A generic morphology model.

 Jan Snajder <jan.snajder@fer.hr>

 (c) 2009 TakeLab
 University of Zagreb
 Faculty of Electrical Engineering and Computing
-------------------------------------------------------------------------------}

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}

module MorphGrammar (

 -- type classes:
 IP (..),
 IPR (..),
 DP (..),
 Labeled (..),

 -- functions:
 inflectionOf,
 iRelated,
 lWfs,
 lWfsMsd,
 wLemma,
 wLemmaMsd,
 lm,
 lm',
 lmMsd,
 lmMsd',
 sApp,
 lApp,
 lInflect, --inflectMsd,
 --lDerive,
 --derivationOf,dRelated,
 getPattern) where

import Data.List
import Control.Monad

--type Msd = String --TMP (should be a class)
-- TODO: ne uspijevam Msd ugraditi kao dodatni parametar klase
-- ... probaj jednog dana

--------------------------------------------------------------------------------
-- Inflectional pattern classes
--------------------------------------------------------------------------------

class (Eq ip, Ord x, Labeled ip) => IP ip x | ip -> x where
  sWfs    :: ip -> String -> [String]
  sWfsMsd :: ip -> String -> [(String,x)]
  sLemma  :: (MonadPlus m) => ip -> String -> m String  -- stem's lemma
  msds    :: ip -> [x]
--  inflect :: (MonadPlus m) => r -> Msd -> String -> m String

  -- minimal complete definition: sLemma, sWfsMsd, msds
  -- default definitions:
  sWfs f       = nub . map fst . sWfsMsd f

class (IP ip x) => IPR ip x where
  lStem     :: (MonadPlus m) => ip -> String -> m String   -- lemma's stem
  wStem     :: (MonadPlus m) => ip -> String -> m String
  wStemMsd  :: (MonadPlus m) => ip -> String -> m (String,x)

  -- minimal complete definition: lStem, wStemMsd
  -- default definitions:
  wStem ip = mnub . map fst . wStemMsd ip

--  wStemMsd r =
--    msum . liftM (\(l,d) -> do s <- lStem r l; return (s,d)) . wLemmaMsd r

-- other functions:

mnub :: (MonadPlus m, Eq a) => [a] -> m a
mnub = msum . map return . nub

lWfsMsd :: (IPR ip x) => ip -> String -> [(String,x)]
lWfsMsd ip = nub . concatMap (sWfsMsd ip) . lStem ip

lWfs :: (IPR ip x) => ip -> String -> [String]
lWfs ip = nub . concatMap (sWfs ip) . lStem ip

wLemmaMsd :: (MonadPlus m, IPR ip x) => ip -> String -> m (String,x)
wLemmaMsd ip =
  msum . liftM (\(s,x) -> do l <- sLemma ip s; return (l,x)) . wStemMsd ip

wLemma :: (MonadPlus m, IPR ip x) => ip -> String -> m String
wLemma ip = mnub . map fst . wLemmaMsd ip

sInflect :: (MonadPlus m, IP ip x) => ip -> x -> String -> m String
sInflect ip x = mnub . map fst . filter ((==x).snd) . sWfsMsd ip

lInflect :: (MonadPlus m, IPR ip x) => ip -> x -> String -> m String
lInflect ip x = mnub . map fst . filter ((==x).snd) . lWfsMsd ip

sApp :: (IP ip x) => ip -> String -> Bool
sApp ip = not . null . sWfs ip

lApp :: (IPR ip x) => ip -> String -> Bool
lApp ip = not . null . lWfs ip

-- groups together the inner homographs
--lWfsMsd' :: (IPR ip x) => ip -> String -> [(String,[x])]
--lWfsMsd' ip l = [(w,nub . sort $ map snd wds) |
--  wds@((w,_):_) <- eqClasses (equating fst) (lWfsMsd ip l)]

-- lemmatises a wordform according to a list of inflectional patterns
-- returns possible lemma-Pattern pairs wrapped in a MonadPlus instance
lm :: (IPR ip x, MonadPlus m) => [ip] -> String -> m (String,ip)
lm ips w = mnub [(l,ip) | ip <- ips, l <- wLemma ip w]

-- E.g.
-- > lemmatize [n01,n03] "izvorom"
-- [("izvorom",N01),("izvor",N01)]

lm' :: (IPR ip x, MonadPlus m) => [ip] -> String -> m (String,String)
lm' ips w = mnub [(l,label ip) | ip <- ips, l <- wLemma ip w]

-- same as above but associates a msd label to each lemma-pattern pair
lmMsd :: (IPR ip x, MonadPlus m) => [ip] -> String -> m (String,x,ip)
lmMsd ips w = mnub [(l,x,ip) | ip <- ips, (l,x) <- wLemmaMsd ip w]

-- E.g.
-- > lemmatizeMsd "izvorom" [n01,n03]
-- [("izvorom","N=msn",N01),("izvorom","N=msa",N01),("izvor","N=msi",N01)]

-- same as above but associates a msd label to each lemma-pattern pair
lmMsd' :: (IPR ip x, MonadPlus m) => [ip] -> String -> m (String,x,String)
lmMsd' ips w = mnub [(l,x,label ip) | ip <- ips, (l,x) <- wLemmaMsd ip w]

{- TODO: mnub
-- generates all wordforms of a lemma accoring to a list of
-- inflectional Patterns
generate :: (IPattern r) => [r] -> String -> [String]
generate rs s = concatMap
  (\r -> do l <- lm r s; w <- wfs r l; return w) rs

-- TODO: mnub
-- same as above but also attaches an Msd label
generateMsd :: (IPattern f x) => [f] -> String -> [(String,x)]
generateMsd rs s = concatMap
  (\r -> do l <- sLemma r s; (w,d) <- wfsMsd r l; return (w,d)) rs
-}

{- needed? -}
--wMsd :: (IPatternW r,MonadPlus m) => r -> String -> m Msd
--wMsd r = mnub . map snd . wLemmaMsd r

-- relation of inflectional relatedness between a lemma and a wordform
-- not symmetric, reflexive,.... <--- TODO
inflectionOf :: (IPR ip x) => ip -> String -> String -> Bool
inflectionOf ip l w = w `elem` lWfs ip l

-- relation of inflectional relatedness between two wordforms
-- (worforms are related by Pattern 'r' if they share the same lemma
-- according to Pattern 'r')
iRelated :: (IPR ip x) => ip -> String -> String -> Bool
iRelated ip w1 w2 = ls1 `intersect` ls2 /= []
  where ls1 = wLemma ip w1
        ls2 = wLemma ip w2

--------------------------------------------------------------------------------
-- Derivational pattern class
--------------------------------------------------------------------------------

-- imamo 4 mogućnosti:
-- cilj/odredište: sr-pair ili lr-pair
-- transformacija: lemma-lemma ili stem-stem <-- ovo nije stvar API-ja

-- važno: bez functional dependency "d -> r" neće raditi "invert"
--class (Labeled d,IPattern f) => DPattern d f | d -> f where
class (Labeled dp, IPR ip x) => DP dp ip x y where
  lDerive :: (MonadPlus m) => dp -> (String,ip) -> m (String,y)
--  lDerive :: (MonadPlus m) => d -> (String,f) -> m (String,[f])

-- other functions:
{-
lDerive :: (MonadPlus m, IPR f x, DP d f x) =>
  d -> (String,f) -> m (String,[f])
lDerive d (l1,f1) = mnub [(l2,fs2) |
  sf <- sfs, (s2,fs2) <- sDerive d sf, f2 <- fs2, l2 <- sLemma f2 s2]
  where sfs = [(s,f1) | s <- lStem f1 l1]
-}

-- relation of derivational relatedness
--derivationOf :: (DP d r) => d -> LR r -> LR r -> Bool
--derivationOf d lr1 lr2 = lr2 `elem` derive d lr1

-- symmetric and reflexive (but not transitive) closure of the above relation
--dRelated :: (DP d r) => d -> (String, r) -> (String, r) -> Bool
--dRelated d lr1 lr2 =
--  derivationOf d lr1 lr2 || derivationOf d lr2 lr1 || lr1==lr2

{-
-- applies 'derive' to a list of derivational Patterns
deriveAll :: (DP d r) => [d] -> (String,r) -> [(String,r)]
deriveAll ds lr1 = nub . concat $ [derive d lr1 | d <- ds]
-}

--------------------------------------------------------------------------------
-- Auxiliary classes
--------------------------------------------------------------------------------

class Labeled x where
  label :: x -> String

--- rest:

getPattern :: (Labeled p) => [p] -> String -> Maybe p
getPattern ps l = find ((==l).label) ps


text:
'use strict';

/**
 * Profile for Windows VMs in the container service cluster.
 *
 */
class ContainerServiceWindowsProfile {
  /**
   * Create a ContainerServiceWindowsProfile.
   * @property {string} adminUsername The administrator username to use for
   * Windows VMs.
   * @property {string} adminPassword The administrator password to use for
   * Windows VMs.
   */
  constructor() {
  }

  /**
   * Defines the metadata of ContainerServiceWindowsProfile
   *
   * @returns {object} metadata of ContainerServiceWindowsProfile
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ContainerServiceWindowsProfile',
      type: {
        name: 'Composite',
        className: 'ContainerServiceWindowsProfile',
        modelProperties: {
          adminUsername: {
            required: true,
            serializedName: 'adminUsername',
            constraints: {
              Pattern: /^[a-zA-Z0-9]+([._]?[a-zA-Z0-9]+)*$/
            },
            type: {
              name: 'String'
            }
          },
          adminPassword: {
            required: true,
            serializedName: 'adminPassword',
            constraints: {
              Pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%\^&\*\(\)])[a-zA-Z\d!@#$%\^&\*\(\)]{12,123}$/
            },
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ContainerServiceWindowsProfile;


text:
from . import sizedistribution
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
from scipy import signal
from scipy import optimize
from ...tools import math_functions

def fit_normal_dist(sd, log=True, p0=[10, 180, 0.2], boundary_width = [0.1, 0.6]):
    """Fits a normal distribution to a """
    if not log:
        txt = 'sorry, this is not working right now ... programming requried'
        raise ValueError(txt)

    def find_peak_arg(x, y, start_w=0.2, tol=0.3):
        """
        Parameters
        ----------
        x: nd_array
            log10 of the diameters
        y: nd_array
            intensities (number, volume, surface ...)
        start_w: float
            some reasonalble width for a log normal distribution (in log normal)
        tol: float
            Tolerance ratio for start_w"""

        med = np.median(x[1:] - x[:-1])

        low = np.floor((start_w * (1 - tol)) / med)
        top = np.ceil((start_w * (1 + tol)) / med)

        if low < 1:
            low = 1

        widths = np.arange(low, top)
        peakind = signal.find_peaks_cwt(y, widths)
        return peakind

    def multi_gauss(x, *params, verbose=False):
        y = np.zeros_like(x)
        for i in range(0, len(params), 3):
            if verbose:
                print(len(params), i)
            amp = params[i]
            pos = params[i + 1]
            sig = params[i + 2]
            y = y + math_functions.gauss(x, amp, pos, sig)
        return y

    out = {}

    x = sd.data.columns.values
    y = sd.data.iloc[0, :].values
    x = x[~ np.isnan(y)]
    y = y[~ np.isnan(y)]

    if len(x) == 0:
        return False

    if log:
        x_orig = x.copy()  # we have to keep it to avoide rounding errors when doing a back and forth calculation
        x = np.log10(x)

    out['as_fitted'] = (x, y)

    start_width = 0.2
    tol = 0.9
    # width_ll = start_width * (1 - tol)
    # width_ul = start_width * (1 + tol)
    peak_args = find_peak_arg(x, y, start_w=start_width, tol=tol)
    out['peak_args'] = peak_args

    param = []
    bound_l = []
    bound_h = []
    for pa in peak_args:
        # amp
        #         print('amp: ', y[pa])
        param.append(y[pa])
        #         bound_l.append(-np.inf)
        bound_l.append(0)
        bound_h.append(np.inf)

        # pos
        #         print('pos: ', 10**x[pa])
        param.append(x[pa])
        bound_l.append(x[pa] - 0.1)
        bound_h.append(x[pa] + 0.1)
        #         bound_l.append(0)
        #         bound_h.append(x[-1])

        # sig
        param.append(start_width)
        bound_l.append(boundary_width[0])
        bound_h.append(boundary_width[1])

    try:
        param, cm = optimize.curve_fit(multi_gauss, x, y, p0=param, bounds=(bound_l, bound_h))
    except RuntimeError:
        print('Runtime error!')
        return False
    y_fit = multi_gauss(x, *param)

    param = param.reshape(len(peak_args), 3).transpose()
    param_df = pd.DataFrame(param.transpose(), columns=['amp', 'pos', 'sig'])
    out['fit_res_param_pre'] = param_df.copy()

    #### mode attribution
    gaus = pd.DataFrame(index=x)
    for idx in param_df.index:
        gaus[idx] = pd.Series(math_functions.gauss(x, param_df.loc[idx, 'amp'], param_df.loc[idx, 'pos'], param_df.loc[idx, 'sig']), index=x)

    sum_peaks = gaus.sum(axis=1)

    gaus_rel = gaus.copy()
    for col in gaus.columns:
        gaus_rel[col] = gaus.loc[:, col] / sum_peaks

    dist_by_type = gaus_rel.copy()
    for col in gaus_rel.columns:
        dist_by_type[col] = gaus_rel.loc[:, col] * y

    #### fix x axis back to diameter
    if log:
        param[1] = 10 ** param[1]
        #         x = 10 ** x
        dist_by_type.index = x_orig

    param_df.index.name = 'peak'
    out['fit_res_param'] = param_df
    out['fit_res'] = pd.DataFrame(y_fit, index=x)
    dist_by_type.index.name = 'bin_center(nm)'
    dist_by_type.columns.name = 'peak'
    out['dist_by_type'] = dist_by_type
    return out

class FitRes(object):
    def __init__(self, fitres):
        self.fitres = fitres

    def plot(self, ax = None, scale = 2000, **kwargs):
        post = self.fitres['pos'].copy()
        post = np.log10(post)
        p_min = post.min()
        p_max = post.max() - p_min
        # cols = list(((post - p_min) / p_max).values)
        # cols = plt.cm.Accent(cols)

        if not ax:
            f ,a = plt.subplots()
        else:
            a = ax
            f = a.get_figure()
        a.scatter(self.fitres['pos'].index, self.fitres['pos'], s = self.fitres['area_rel'] * scale,
                  # color = cols,
                  **kwargs)
        # g = a.get_lines()[-1]
        # g.set_markersize(fit_res_all['area_rel'].values)
        a.set_yscale('log')
        a.set_xlim(self.fitres['pos'].index[0], self.fitres['pos'].index[-1])
        f.autofmt_xdate()
        return a

class ModeAnalysis(object):
    def __init__(self, sizedist):
        self._parent = sizedist

        self.__size_dist_aiken = None
        self.__size_dist_accu = None
        self.__size_dist_coarse = None
        self.__mode_fit_results = None

    @property
    def fit_results(self):
        if not self.__mode_fit_results:
            self.find_modes()
        return self.__mode_fit_results

    @property
    def size_dist_aiken(self):
        if not self.__size_dist_aiken:
            self.find_modes()
        return self.__size_dist_aiken

    @property
    def size_dist_accu(self):
        if not self.__size_dist_accu:
            self.find_modes()
        return self.__size_dist_accu

    @property
    def size_dist_coarse(self):
        if not self.__size_dist_coarse:
            self.find_modes()
        return self.__size_dist_coarse

    def find_modes(self):
        """This function will try to find different aerosol modes in sizedist.

        Parameters
        ----------
        sizedist: sizedistribution instances (SizeDist, SizeDist_TS, ...)
        """
        sizedist = self._parent
        boundary_accu_coars = 1000
        boundary_aiken_accu = 50

        sdts_aiken = sizedist.copy()
        sdts_aiken._update()
        sdts_aiken.data[:] = np.nan
        sdts_accu = sdts_aiken.copy()
        sdts_accu._update()
        sdts_coarse = sdts_aiken.copy()
        sdts_coarse._update()

        fit_res_all = pd.DataFrame(columns=['amp', 'pos', 'sig', 'area'])

        for which in sizedist.data.index:
            #     which = sizedist.data.index[21]
            sd = sizedistribution.SizeDist(pd.DataFrame(sizedist.data.loc[which ,:]).transpose(), sizedist.bins, sizedist.distributionType)
            #     sd = sd.convert2dVdlogDp()
            out_f = fit_normal_dist(sd)
            if not out_f:
                continue
            # res_dict[which] = out_f

            dist_by_type = out_f['dist_by_type'].copy()
            fit_res_param = out_f['fit_res_param']

            coarse = fit_res_param.loc[: ,'pos'] > boundary_accu_coars
            aiken = fit_res_param.loc[: ,'pos'] < boundary_aiken_accu
            accu = np.logical_and(fit_res_param.loc[: ,'pos'] <= boundary_accu_coars, fit_res_param.loc[: ,'pos'] >= boundary_aiken_accu)

            df = pd.DataFrame(index = dist_by_type.index)
            df['aiken'] = dist_by_type.iloc[: ,aiken.values].sum(axis = 1)
            df['accu'] = dist_by_type.iloc[: ,accu.values].sum(axis = 1)
            df['coarse'] = dist_by_type.iloc[: ,coarse.values].sum(axis = 1)
            sdts_aiken.data.loc[which ,:] = df.loc[: ,'aiken']
            sdts_accu.data.loc[which ,:] = df.loc[: ,'accu']
            sdts_coarse.data.loc[which ,:] = df.loc[: ,'coarse']

            fit_res_param['area'] = fit_res_param['amp'] * fit_res_param['sig'] * np.sqrt(2 * np.pi)
            fit_res_param['area_rel'] = fit_res_param['area'] / fit_res_param['area'].sum()
            fit_res_param.index = [which] * fit_res_param.shape[0]
            fit_res_all = fit_res_all.append(fit_res_param)
            if 0:
                f ,a = sd.plot()
                a.set_title(which)
                sdts_aiken.data.loc[which ,:].plot(ax = a)
                sdts_accu.data.loc[which ,:].plot(ax = a)
                sdts_coarse.data.loc[which ,:].plot(ax = a)
        # (sdts_coarse.data.loc[which,:] + sdts_accu.data.loc[which,:]).plot(ax = a, color = 'magenta')
        #     break
        # df

        # volumes = sdts_aiken.particle_volume_concentration.data.copy()
        # volumes.columns = ['aiken']
        # volumes['acccu'] = sdts_accu.particle_volume_concentration.data
        # volumes['coarse'] = sdts_coarse.particle_volume_concentration.data
        # volume_ratios = volumes.truediv(volumes.sum(axis = 1), axis=0)

        self.__size_dist_aiken = sdts_aiken
        self.__size_dist_accu = sdts_accu
        self.__size_dist_coarse = sdts_coarse

        self.__mode_fit_results = FitRes(fit_res_all)


text:
package com.winterwell.maths.stats.distributions.discrete;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.winterwell.maths.ITrainable;
import com.winterwell.maths.datastorage.IForget;
import com.winterwell.maths.datastorage.IPruneListener;
import com.winterwell.utils.MathUtils;
import com.winterwell.utils.Mutable;
import com.winterwell.utils.containers.ArrayMap;
import com.winterwell.utils.containers.Containers;
import com.winterwell.utils.log.Log;
import com.winterwell.utils.web.IHasJson;
import com.winterwell.utils.web.SimpleJson;

/**
 * A discrete distribution over a set of objects.
 *

 * By default this assigns zero probability to items it hasn't seen. This can be
 * over-ridden using {@link #setPseudoCount(double)}.
 *

 * Use {@link FiniteDistributionChart} to view this.
 *
 * @author daniel
 *
 * @testedby  ObjectDistributionTest}
 * @param <X>
 */
public class ObjectDistribution<X> extends AFiniteDistribution<X> implements
		Serializable, ITrainable.Unsupervised.Weighted<X>, IHasJson  {

	/**
	 * If true, it is an error to call {@link #normalise()}.
	 * This is a safety flag to protect the original data counts.
	 * You can still get normalised proabilities from {@link #normProb(Object)}
	 */
	private Boolean doNotNormalise;

	/**
	 * False by default. If true, it is an error to call {@link #normalise()}.
	 * This is a safety flag to protect the original data counts.
	 * You can still get normalised probabilities from {@link #normProb(Object)}
	 */
	public void setDoNotNormalise(boolean doNotNormalise) {
		this.doNotNormalise = doNotNormalise;
	}

	private static final String OTHER = "other";

	@Override
	public Object toJson2() throws UnsupportedOperationException {
		// a sorted map??
		return asMap();
	}

	/**
	 * @param n
	 * @return the top n, sorted highest-first, plus "other" if there is a remainder.
	 */
	public Map toJson2(int n) {
		List<X> keys = getMostLikely(n);
		Map map = new ArrayMap();
		double ttl=0;
		for (X x : keys) {
			double p = get(x);
			ttl += p;
			map.put(x, p);
		}
		double wt = getTotalWeight() + pseudoCount*size();
		if (ttl<wt && size() > n) {
			double rem = wt-ttl;
			map.put(OTHER, rem);
		}
		return map;
	}

	@Override
	public String toJSONString() {
		return new SimpleJson().toJson(toJson2());
	}

	@Override
	public void appendJson(StringBuilder sb) {
		sb.append(toJSONString());
	}

	/**
	 * @return true if this is in the backing map.
	 *
	 * Note: if a pseudo-count has been set, then x-in-the-collection
	 * is not equivalent to P(x) != 0
	 */
	@Override
	public boolean contains(Object o) {
		return backing.containsKey(o);
	}

	private static final long serialVersionUID = 1L;

	/**
	 * This is a synchronized HashMap by default -- but users can provide their own
	 * map via {@link #ObjectDistribution(Map, boolean)}
	 */
	private final Map<X, Double> backing;

	@Override
	public final void train(double[] weights, Iterable<? extends X> wdata) {
		int i=0;
		for (X x : wdata) {
			double wi = weights[i];
			i++;
			train1(x, wi);
		}
	}

	/**
	 * 0 by default
	 */
	private double pseudoCount;

	/**
	 * Use {@link #setProb(Object, double)} to add objects
	 */
	public ObjectDistribution() {
		this(Collections.EMPTY_MAP);
	}

	/**
	 * Copy constructor
	 * @param distro
	 */
	public ObjectDistribution(IFiniteDistribution<X> distro) {
		this(distro.asMap());
	}

	/**
	 * Create a new ObjectDistribution that starts off identical to the given
	 * info, but can then be edited. Effectively this is a copy constructor.
	 *
	 * @param probs
	 *            This is copied
	 */
	public ObjectDistribution(Map<X, ? extends Number> probs) {
		// Used to be a ConcurrentHashMap, but this has
		// too large a memory footprint for heavy use.
		// TODO use TObjectDoubleHashMap<X> instead (test speed)??
		// TODO use Mutable.Dble instead of Double for faster add??
		// TODO allow replacing the map?
		this.backing = Collections
				.synchronizedMap(new HashMap<X, Double>(probs.size()));
		// Using setProb will strip out zeroes and safety check
		for(Map.Entry<X, ? extends Number> e : probs.entrySet()) {
			Number v = e.getValue();
			setProb(e.getKey(), v.doubleValue());
		}
		// save some memory
		noTrainingDataCollection();
	}

	/**
	 * Create a new ObjectDistribution using the given probs map.
	 * E.g. use case: a HalfLifeMap, so the distro won't grow too big.
	 *
	 * @param probs This will be used directly (without a defensive copy).
	 * @param copyMap Must be false.
	 */
	public ObjectDistribution(Map<X, Double> probs, boolean copyMap) {
		assert ! copyMap;
		this.backing = probs;
		// sanity check
		for(Double v : backing.values()) {
			assert MathUtils.isFinite(v) : probs;
		}
		// save some memory
		noTrainingDataCollection();
		// catch pruning events
		if (this.backing instanceof IForget) {
			IForget forgetfulMap = (IForget) backing;
			forgetfulMap.addListener(new PruneListener());
		}
	}

	/**
	 * Respond to pruning events by re-calculating the cached weight.
	 */
	private final class PruneListener implements IPruneListener, Serializable {
		private static final long serialVersionUID = 1L;

		@Override
		public void pruneEvent(List pruned) {
			cachedWeight = -1;
		}
	}

	/**
	 * Create a new ObjectDistribution using the given tags & probs.
	 */
	public ObjectDistribution(String[] tags, double[] probs) {
		// Create with a suitable backing map
		this(ArrayMap.useMe(tags.length), false);
		double total = 0;
		for (int i = 0; i < probs.length; i++) {
			double pi = probs[i];
			assert MathUtils.isFinite(pi) : tags[i]+" = "+pi;
			backing.put((X)tags[i], pi);
		}
		cachedWeight = total;
	}

	@Override
	public final void addProb(X obj, double dp) {
		if (dp==0) return; //no-op
		normalised = false;
		if (dp<0) {
			throw new IllegalArgumentException("addProb "+dp+" < 0 for "+obj);
		}
		// Note: The super method would add in the pseudo-count as well
		// -- which over-eggs the training slightly.

		// This has some thread-safety
		double newValue = Containers.plus(backing, obj, dp);

		// NB: when caching weights with a forgetful map - prune-events will invalidate the cache
		if (cachedWeight > 0) {
			// NB: cachedWeight=0 could be a new map, or could be a freshly loaded (but not empty) map.
			// cachedWeight=-1 means a cache invalidation
			cachedWeight += dp;
			// Is it a new addition?
			if (newValue != dp) {
				cachedWeight += pseudoCount;
			}
		}
	}

	/**
	 * Equivalent to using the map constructor with {@link #getMap()}.
	 */
	public ObjectDistribution<X> copy() {
		ObjectDistribution<X> od = new ObjectDistribution<X>(backing);
		od.pseudoCount = pseudoCount;
		return od;
	}

	/**
	 * Count the occurrence of each item. Convenience method for
	 * {@link #addProb(Object, double)} or {@link #setProb(Object, double)}.
	 * This is identical to {@link #train1(Object)}. Used when in
	 * histogram mode.
	 *
	 * @param x
	 */
	public final void count(X x) {
		train1(x);
	}

	/**
	 * No-op (not needed and does nothing).
	 *
	 * Note: You may wish to call {@link #normalise()}.
	 */
	// NB: It is handy in some use-cases for this class to retain the raw counts.
	// Hence why this method does not call normalise itself.
	@Override
	public void finishTraining() {
		super.finishTraining();
	}

	/**
	 * Equivalent to {@link #prob(Object)}. Provided for similarity with Map.
	 */
	public final double get(X item) {
		return prob(item);
	}

	/**
	 * @return If pseudocount=0, then this is the backing map itself.
	 * If pseudocount !=0, then we wrap the backing map to include pseudocounts.
	 * Do NOT edit!
	 * @see #getBackingMap()
	 */
	public Map<X, Double> asMap() {
		if (pseudoCount==0) return
				// Don't wrap this, as WWModel & others may need to know if this is an IForget map
				backing;
		return super.asMap();
	}

	/**
	 * @return the underlying map.
	 */
	public Map<X, Double> getBackingMap() {
		return backing;
	}

	@Override
	public X getMostLikely() {
		assert size() != 0;
		return getSortedObjects().get(0);
	}

	/**
	 * @return The objects in the space, ordered with the most probable first.
	 */
	public List<X> getSortedObjects() {
		List<X> keys = Containers.getSortedKeys(backing);
		Collections.reverse(keys);
		return keys;
	}

	@Override
	public final double getTotalWeight() {
		// does NOT include pseudo-counts
		// this is a slow method - so cache the value
		if (cachedWeight > 0)
			return cachedWeight;
		double _cachedWeight = 0; //residue;
		Collection<Double> vs = backing.values();
		for (Double p : vs) {
			assert p!=null && p>=0 : p+" "+this;
			_cachedWeight += p;
		}
		_cachedWeight += pseudoCount * size();
		cachedWeight = _cachedWeight;
		assert MathUtils.isFinite(_cachedWeight) : _cachedWeight+" "+this;
		return cachedWeight;
	}

	@Override
	public boolean isReady() {
		return true;
	}

	/**
	 * Iterate over the known values.
	 *
	 * Note: if a pseudo-count has been set, then x-in-the-collection
	 * is not equivalent to P(x) != 0
	 */
	@Override
	public Iterator<X> iterator() {
		return backing.keySet().iterator();
	}

	public final Set<X> keySet() {
		return backing.keySet();
	}

	/**
	 * Convenience method to set P(object) *= a
	 *
	 * @param initial If P(object) is unset, what valuie should it start at?
	 * Normally either 0 (if you aren't in, then you don't get added), or 1 (start all-in and decay).
	 */
	public void multiply(X obj, double a, double initial) {
		assert pseudoCount==0 : pseudoCount;
		Double p = backing.get(obj);
		if (p==null) {
			// obj is new
			if (initial==0) return;
			setProb(obj, initial * a);
			return;
		}
		setProb(obj, p * a);
	}

	/**
	 * Multiply all stored values.
	 * So P(x)-after = a * P(x)-before
	 * @param a If 0, this will clear out the entries.
	 */
	public void multiply(double a) {
		assert pseudoCount==0 : pseudoCount;
		if (a==0) {
			clear();
			return;
		}
		for(Map.Entry<X,Double> xp : backing.entrySet()) {
			double p2 = xp.getValue() * a;
			xp.setValue(p2);
		}
		// mark cached weight as out of date
		normalised = false;
		cachedWeight = -1;
	}

	@Override
	public final synchronized void normalise() {
		if (isNormalised())
			return;
		if (doNotNormalise!=null && doNotNormalise) {
			throw new IllegalStateException("This distribution is set to 'doNotNormalise' to protect counts.");
		}
		// NB: This method does not modify pseudocount.
		// if the pseudo-count is high, you'll never get probabilities out
		// For normalised distributions -- pseudoCount should be low - e.g. 1/size()
		assert pseudoCount < 1.0 / size() : "pseudocount too high: "+pseudoCount;

		normalised = true;
		double sum = 0, count = 0;
		for (Double d : backing.values()) {
			sum += d;
			count++;
		}
		assert count == size();
		if (count == 0) {
			cachedWeight = 0;
			return;
		}
		if (sum == 0) {
			// no prob weight! - split evenly
			double split = (1.0 - pseudoCount * count) / count;
			for (Map.Entry<X, Double> e : backing.entrySet()) {
				e.setValue(split);
			}
			cachedWeight = 1;
			return;
		}

		// how much is a "unit weight" now?
		double n = (1.0 - pseudoCount * count) / sum;

		for (Map.Entry<X, Double> e : backing.entrySet()) {
			e.setValue(e.getValue() * n);
		}
		cachedWeight = 1;
	}

	/**
	 * The normalised probability (i.e. an actual probability).
	 *
	 * @param obj
	 * @return in [0,1]
	 */
	@Override
	public double normProb(X obj) {
		double po = prob(obj);
		double wt = getTotalWeight();
		if (wt==0) {
			// Wot no prob weight? So this is a completely untrained map.
			// TODO return nan??
//			return Double.NaN;
			// Assume all is fine.
			assert po==0 || pseudoCount > 0;
			assert backing.isEmpty() : backing;
			if (pseudoCount>0) {
				// How many possible values to count in?
				return po / (2*pseudoCount);
			}
			assert MathUtils.isProb(po) : po;
			return po;
		}
		double p = po / wt;
		assert MathUtils.isProb(p) : p+" = "+po+"/"+wt+" for "+obj;
		return p;
	}

	/**
	 * @param obj
	 *            Cannot be null
	 * @return the probability given to this object. This need not be
	 *         normalised! A common use case it to never normalise, and to use
	 *         this class as a counter. To get a normalised prob, use
	 *         {@link #normProb(Object)}
	 */
	@Override
	public final double prob(X obj) {
		assert obj != null;
		Double p = backing.get(obj);
		return p == null ? pseudoCount : p + pseudoCount;
	}

	/**
	 * Prune the histogram, keeping only the more common entries
	 *
	 * @param buckets
	 *            The number of buckets to keep
	 * @return The pruned keys (ie the entries just removed)
	 */
	public List<X> prune(int buckets) {
		return prune(buckets, null);
	}

	/**
	 * Prune the histogram, keeping only the more common entries
	 *
	 * @param buckets
	 *            The number of buckets to keep
	 * @param prunedWeight
	 *            Can be null. Provides a secondary output: the total weight
	 *            that has been removed. This can be used to create an "other"
	 *            slice in pie-charts. E.g.
		Mutable.Dble prunedWeight = new Mutable.Dble();
		dist.prune(10, prunedWeight);
		dist.setProb("other", prunedWeight.value);
		 (nb: the previous value of
	 *            prunedWeight will be discarded).
	 * @return The pruned keys (ie the entries just removed)
	 */
	public List<X> prune(int buckets, Mutable.Dble prunedWeight) {
		if (prunedWeight != null) {
			prunedWeight.value = 0;
		}
		int pruneCount = backing.size() - buckets;
		// Do we need to prune?
		if (pruneCount < 1)
			return Collections.emptyList();
		// prunedFlag = true;
		// Get the lowest ranking keys
		List toPrune = new ArrayList(pruneCount);
		for (Object k : Containers.getSortedKeys(backing)) {
			toPrune.add(k);
			if (toPrune.size() == pruneCount) {
				break;
			}
		}
		// Remove them
		for (Object k : toPrune) {
			Double v = backing.remove(k);
			assert v >= 0 : k+"="+v;
			if (prunedWeight != null) {
				prunedWeight.value += v;
			}
		}
		normalised = false;
		return toPrune;
	}

	public ArrayList<X> pruneBelow(double minProb) {
		return pruneBelow(minProb, null);
	}

	/**
	 * Remove all entries which have probability below the threshold. Note: this
	 * does not normalise either before or after.
	 *
	 * @param minProb
	 *            or min-count if un-normalised.
	 * @param prunedWeight
	 *            Can be null. Provides a secondary output: the total weight
	 *            that has been removed. This can be used to create an "other"
	 *            slice in pie-charts. E.g.
		Mutable.Dble prunedWeight = new Mutable.Dble();
		dist.pruneBelow(0.05, prunedWeight);
		dist.setProb("other", prunedWeight.value);
		 (nb: the previous value of
	 *            prunedWeight will be discarded).
	 * @return The pruned keys (ie the entries just removed).
	 */
	public ArrayList<X> pruneBelow(double minProb, Mutable.Dble prunedWeight) {
		if (prunedWeight != null) {
			prunedWeight.value = 0;
		}
		ArrayList<X> removed = new ArrayList();
		for (Object k : backing.keySet().toArray()) {
			X x = (X) k;
			double px = prob(x);
			if (px >= minProb) {
				continue;
			}
			backing.remove(k);
			removed.add(x);
			if (prunedWeight != null) {
				prunedWeight.value += px;
			}
		}
		return removed;
	}

	/**
	 * Equivalent to {@link #setProb(Object, double)}. Provided for similarity
	 * with Map.
	 */
	public final void put(X tag, double prob) {
		setProb(tag, prob);
	}

	/**
	 * Set to uniform: all info is discarded (including the keyset!)
	 */
	@Override
	public void resetup() {
		super.resetup();
		backing.clear();
		// double p = 1.0/size();
		// for(Entry<X, Double> e : backing.entrySet()) {
		// e.setValue(p);
		// }
	}

	/**
	 * Set the probability for this object. Will mark the distribution as
	 * un-normalised. Setting a zero probability will remove the object from the
	 * distribution.
	 *

	 * WARNING: cannot be called with zero values while looping over the objects
	 * in this distribution, as the removal will create a
	 * {@link ConcurrentModificationException}. Create an array-copy of the keys
	 * using getMap().keySet().toArray() if you need to do this.
	 *

	 * WARNING: either value=0 or pseudocount MUST = 0
	 *
	 * @param obj
	 * @param value
	 *            Does not need to be normalised
	 */
	@Override
	public final void setProb(X obj, double value) {
		if ( ! MathUtils.isFinite(value) || value < 0) {
			throw new IllegalArgumentException("Prob must be >= 0: P("+obj+") = "+ value + "\t in " + this);
		}
		normalised = false;
		if (value == 0) {
			Double old = backing.remove(obj);
			if (old != null && cachedWeight>0) {
				cachedWeight -= old;
			}
			return;
		}
		// setProb with pseudocount suggests a bug -- except this is how count()/train2() works!
//			assert pseudoCount==0 : pseudoCount+" "+obj+" "+value;
		Double old = backing.put(obj, value);
		if (cachedWeight>0) {
			if (old != null) {
				cachedWeight -= old;
			}
			cachedWeight += value;
		}
	}

	/**
	 * A simple method for handling unseen items. The pseudo-count is added to
	 * all values returned by {@link #prob(Object)}. size() * pseudoCount is
	 * added to {@link #getTotalWeight()}.
	 *

	 * Users of {@link ObjectDistribution} may implement their own (better)
	 * pseudocount system.
	 *
	 * @param pseudoCount
	 *            0 (the default) for no pseudo-count
	 * @return this
	 */
	public ObjectDistribution<X> setPseudoCount(double pseudoCount) {
		if ( ! MathUtils.isFinite(pseudoCount) || pseudoCount <0) {
			throw new IllegalArgumentException("pseudocount should be >= 0: "+pseudoCount);
		}
		this.pseudoCount = pseudoCount;
		// clear cache
		normalised = false;
		cachedWeight = -1;
		return this;
	}

	public double getPseudoCount() {
		return pseudoCount;
	}

	/**
	 * @return number of objects in this distribution.
	 * @see #getTotalWeight()
	 * @see #getEffectiveParticleCount()
	 */
	@Override
	public int size() {
		return backing.size();
	}

	@Override
	public Object[] toArray() {
		return backing.keySet().toArray();
	}

	/**
	 * In keeping with being almost a Collection, you can get an array of the
	 * elements.
	 *
	 * @param array
	 * @return things this distribution is over
	 */
	@Override
	public <X2> X2[] toArray(X2[] array) {
		return backing.keySet().toArray(array);
	}

	@Override
	public void train(Iterable<? extends X> data) {
		super.train(data);
	}

	/**
	 * Equivalent to {@link #addProb(Object, double)} with dp = 1
	 */
	@Override
	public final void train1(X data) {
		assert data != null;
		// assert ! isNormalised(); training after normalisation can be
		// inefficient (need to renormalise)
		// -- but it's legitimate
		addProb(data, 1);
	}

	/**
	 * Equivalent to {@link #addProb(Object, double)}
	 */
	@Override
	public final void train1(X data, double weight) {
		assert data != null;
		addProb(data, weight);
	}

	/**
	 * Return a set of randomly selected elements of the specified
	 * collection. Equality in the set is determined in the usual way i.e. by
	 * calling equals(). If num is greater than choices, then return all the
	 * choices in a fresh object.
	 *

	 * This has a time-out which can lead to it stopping early & short.
	 *
	 * @param num Can be 0, but not lower (throws IllegalArgumentException)
	 * @return set of randomly selected choices.
	 */
	public Set<X> sample(int num) {
		if (num >= size()) {
			// the lot
			return new HashSet<X>(super.asList());
		}
		if (num < 0)
			throw new IllegalArgumentException(num+" must be >= 0");
		Set<X> selected = new HashSet<X>(num);
		int iter = 0;
		while (selected.size() < num) {
			X x = sample();
			selected.add(x);
			// time out if we get stuck
			iter++;
			if (iter == num * 100) {
				Log.report("Breaking out of random-selection loop early: Failed to select a full "
						+ num + " from " + size());
				break;
			}
		}
		return selected;
	}

}


text:
declare module 'upfluence-oss-components/templates/*' {
  import { TemplateFactory } from 'htmlbars-inline-precompile';
  const tmpl: TemplateFactory;
  export default tmpl;
}


text:
<?php

namespace Octogun\Client;

use Octogun\Api;

class Downloads extends Api
{
    public $aliases = [
        'listDownloads' => 'downloads',
    ];

    /**
     * List available downloads for a repository.
     *
     * @deprecated As of December 11th, 2012: https://github.com/blog/1302-goodbye-uploads
     *
     * @see http://developer.github.com/v3/repos/downloads/#list-downloads-for-a-repository
     *
     * @param string $repo    A Github Repository.
     * @param array  $options Optional options.
     *
     * @return array A list of available downloads.
     */
    public function downloads($repo, array $options = [])
    {
        return $this->request()->get('repos/' . $repo . '/downloads', $options);
    }

    /**
     * Get single download for a repository.
     *
     * @deprecated As of December 11th, 2012: https://github.com/blog/1302-goodbye-uploads
     *
     * @see http://developer.github.com/v3/repos/downloads/#create-a-new-download-part-1-create-the-resource
     *
     * @param string $repo    A GitHub repository.
     * @param int    $id      ID of the download.
     * @param array  $options Optional options.
     *
     * @return array A single download from the repository.
     */
    public function download($repo, $id, array $options = [])
    {
        return $this->request()->get('repos/' . $repo . '/downloads/' . $id, $options);
    }

    /**
     * Delete a single download for a repository.
     *
     * @deprecated As of December 11th, 2012: https://github.com/blog/1302-goodbye-uploads
     *
     * @see http://developer.github.com/v3/repos/downloads/#delete-a-single-download
     *
     * @param string $repo    A GitHub repository.
     * @param int    $id      ID of the download.
     * @param array  $options Optional options.
     *
     * @return bool Status.
     */
    public function deleteDownload($repo, $id, array $options = [])
    {
        return $this->request()->booleanFromResponse('delete', 'repos/' . $repo . '/downloads/' . $id, $options);
    }
}


text:
package cloud::aws::ec2::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_custom);

sub new {
    my ( $class, %options ) = @_;
    my $self = $class->SUPER::new( package => __PACKAGE__, %options );
    bless $self, $class;

    $self->{version} = '0.1';
    %{ $self->{modes} } = (
        'asg-status'                => 'cloud::aws::ec2::mode::asgstatus',
        'cpu'                       => 'cloud::aws::ec2::mode::cpu',
        'discovery'                 => 'cloud::aws::ec2::mode::discovery',
        'discovery-fleet-requests'  => 'cloud::aws::ec2::mode::discoveryspotfleetrequests',
        'diskio'                    => 'cloud::aws::ec2::mode::diskio',
        'instances-status'          => 'cloud::aws::ec2::mode::instancesstatus',
        'instances-types'           => 'cloud::aws::ec2::mode::instancestypes',
        'list-asg'                  => 'cloud::aws::ec2::mode::listasg',
        'list-instances'            => 'cloud::aws::ec2::mode::listinstances',
        'list-spot-fleet-requests'  => 'cloud::aws::ec2::mode::listspotfleetrequests',
        'network'                   => 'cloud::aws::ec2::mode::network',
        'status'                    => 'cloud::aws::ec2::mode::status',
        'spot-active-instances'     => 'cloud::aws::ec2::mode::spotactiveinstances'
    );

    $self->{custom_modes}{paws} = 'cloud::aws::custom::paws';
    $self->{custom_modes}{awscli} = 'cloud::aws::custom::awscli';
    return $self;
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check Amazon Elastic Compute Cloud (Amazon EC2).

=cut


text:
#ifndef BOOST_COROUTINES_UNIDIRECT_DETAIL_PUSH_COROUTINE_CALLER_H
#define BOOST_COROUTINES_UNIDIRECT_DETAIL_PUSH_COROUTINE_CALLER_H

#include <boost/config.hpp>
#include <boost/context/fcontext.hpp>

#include <boost/coroutine/detail/config.hpp>
#include <boost/coroutine/v2/detail/push_coroutine_base.hpp>

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace coroutines {
namespace detail {

template< typename Arg, typename Allocator >
class push_coroutine_caller : public  push_coroutine_base< Arg >
{
public:
    typedef typename Allocator::template rebind<
        push_coroutine_caller< Arg, Allocator >
    >::other   allocator_t;

    push_coroutine_caller( coroutine_context const& callee, bool unwind,
                           bool preserve_fpu, allocator_t const& alloc) BOOST_NOEXCEPT :
        push_coroutine_base< Arg >( callee, unwind, preserve_fpu),
        alloc_( alloc)
    {}

    void deallocate_object()
    { destroy_( alloc_, this); }

private:
    allocator_t   alloc_;

    static void destroy_( allocator_t & alloc, push_coroutine_caller * p)
    {
        alloc.destroy( p);
        alloc.deallocate( p, 1);
    }
};

}}}

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_COROUTINES_UNIDIRECT_DETAIL_PUSH_COROUTINE_CALLER_H


text:
. "${root}/.ci/load-ci.sh"

export DEBIAN_FRONTEND="noninteractive"
export PATH="${PATH}:${root}/.ci"


text:
package org.apache.el;

public class TesterBeanBB extends TesterBeanB {

    private String extra;

    public String getExtra() {
        return extra;
    }

    public void setExtra(String extra) {
        this.extra = extra;
    }
}


text:
package org.sagebionetworks.repo.model.dbo.persistence;

import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_SECTOR_IDENTIFIER_CREATED_BY;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_SECTOR_IDENTIFIER_CREATED_ON;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_SECTOR_IDENTIFIER_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_SECTOR_IDENTIFIER_SECRET;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_SECTOR_IDENTIFIER_URI;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.DDL_OAUTH_SECTOR_IDENTIFIER;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_OAUTH_SECTOR_IDENTIFIER;

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

import org.sagebionetworks.repo.model.dbo.FieldColumn;
import org.sagebionetworks.repo.model.dbo.MigratableDatabaseObject;
import org.sagebionetworks.repo.model.dbo.TableMapping;
import org.sagebionetworks.repo.model.dbo.migration.BasicMigratableTableTranslation;
import org.sagebionetworks.repo.model.dbo.migration.MigratableTableTranslation;
import org.sagebionetworks.repo.model.migration.MigrationType;

/**
 * Contains information about comments posted to arbitrary objects
 */
public class DBOSectorIdentifier implements MigratableDatabaseObject<DBOSectorIdentifier, DBOSectorIdentifier> {

	private static FieldColumn[] FIELDS = new FieldColumn[]{
		new FieldColumn("id", COL_OAUTH_SECTOR_IDENTIFIER_ID, true).withIsBackupId(true),
		new FieldColumn("uri", COL_OAUTH_SECTOR_IDENTIFIER_URI),
		new FieldColumn("secret", COL_OAUTH_SECTOR_IDENTIFIER_SECRET),
		new FieldColumn("createdBy", COL_OAUTH_SECTOR_IDENTIFIER_CREATED_BY),
		new FieldColumn("createdOn", COL_OAUTH_SECTOR_IDENTIFIER_CREATED_ON),
	};

	private Long id;
	private String uri;
	private String secret;
	private Long createdBy;
	private Long createdOn;

	@Override
	public TableMapping<DBOSectorIdentifier> getTableMapping() {
		return new TableMapping<DBOSectorIdentifier>() {

			@Override
			public DBOSectorIdentifier mapRow(ResultSet rs, int index)
					throws SQLException {
				DBOSectorIdentifier dbo = new DBOSectorIdentifier();
				dbo.setId(rs.getLong(COL_OAUTH_SECTOR_IDENTIFIER_ID));
				dbo.setUri(rs.getString(COL_OAUTH_SECTOR_IDENTIFIER_URI));
				dbo.setSecret(rs.getString(COL_OAUTH_SECTOR_IDENTIFIER_SECRET));
				dbo.setCreatedOn(rs.getLong(COL_OAUTH_SECTOR_IDENTIFIER_CREATED_ON));
				dbo.setCreatedBy(rs.getLong(COL_OAUTH_SECTOR_IDENTIFIER_CREATED_BY));
				return dbo;
			}

			@Override
			public String getTableName() {
				return TABLE_OAUTH_SECTOR_IDENTIFIER;
			}

			@Override
			public String getDDLFileName() {
				return DDL_OAUTH_SECTOR_IDENTIFIER;
			}

			@Override
			public FieldColumn[] getFieldColumns() {
				return FIELDS;
			}

			@Override
			public Class<? extends DBOSectorIdentifier> getDBOClass() {
				return DBOSectorIdentifier.class;
			}
		};
	}

	@Override
	public MigrationType getMigratableTableType() {
		return MigrationType.OAUTH_SECTOR_IDENTIFIER;
	}

	static final MigratableTableTranslation<DBOSectorIdentifier, DBOSectorIdentifier> TRANSLATOR =
			new BasicMigratableTableTranslation<DBOSectorIdentifier>() {};

	@Override
	public MigratableTableTranslation<DBOSectorIdentifier, DBOSectorIdentifier> getTranslator() {
		return TRANSLATOR;
	}

	@Override
	public Class<? extends DBOSectorIdentifier> getBackupClass() {
		return DBOSectorIdentifier.class;
	}

	@Override
	public Class<? extends DBOSectorIdentifier> getDatabaseObjectClass() {
		return DBOSectorIdentifier.class;
	}

	@Override
	public List<MigratableDatabaseObject<?,?>> getSecondaryTypes() {
		return null;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}

	public Long getCreatedBy() {
		return createdBy;
	}

	public void setCreatedBy(Long createdBy) {
		this.createdBy = createdBy;
	}

	public Long getCreatedOn() {
		return createdOn;
	}

	public void setCreatedOn(Long createdOn) {
		this.createdOn = createdOn;
	}

	public String getSecret() {
		return secret;
	}

	public void setSecret(String secret) {
		this.secret = secret;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((createdBy == null) ? 0 : createdBy.hashCode());
		result = prime * result + ((createdOn == null) ? 0 : createdOn.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((secret == null) ? 0 : secret.hashCode());
		result = prime * result + ((uri == null) ? 0 : uri.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DBOSectorIdentifier other = (DBOSectorIdentifier) obj;
		if (createdBy == null) {
			if (other.createdBy != null)
				return false;
		} else if (!createdBy.equals(other.createdBy))
			return false;
		if (createdOn == null) {
			if (other.createdOn != null)
				return false;
		} else if (!createdOn.equals(other.createdOn))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (secret == null) {
			if (other.secret != null)
				return false;
		} else if (!secret.equals(other.secret))
			return false;
		if (uri == null) {
			if (other.uri != null)
				return false;
		} else if (!uri.equals(other.uri))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "DBOSectorIdentifier [id=" + id + ", uri=" + uri + ", secret=" + secret + ", createdBy=" + createdBy
				+ ", createdOn=" + createdOn + "]";
	}

}


text:
#include "config/stm32plus.h"
#include "config/timer.h"

#if defined(STM32PLUS_F1_XL)

using namespace stm32plus;

// static initialisers for the hack that forces the IRQ handlers to be linked

template<> TimerInterruptFeatureEnabler<8>::FPTR TimerInterruptFeatureEnabler<8>::_forceLinkage=nullptr;
template<> TimerInterruptFeatureEnabler<12>::FPTR TimerInterruptFeatureEnabler<12>::_forceLinkage=nullptr;
template<> TimerInterruptFeatureEnabler<13>::FPTR TimerInterruptFeatureEnabler<13>::_forceLinkage=nullptr;
template<> TimerInterruptFeatureEnabler<14>::FPTR TimerInterruptFeatureEnabler<14>::_forceLinkage=nullptr;

extern "C" {

  /**
   * TIM8_BRK and TIM12 (XL-density only) share the same vector.
   * TIM12 can have CC1, CC2, Update, Trigger
   */

#if defined(USE_TIM8_BRK_INTERRUPT) || defined(USE_TIM12_INTERRUPT)

  void __attribute__ ((interrupt("IRQ"))) TIM8_BRK_IRQHandler() {

    if(TIM_GetITStatus(TIM8,TIM_IT_Break)!=RESET) {
      TimerInterruptFeature<8>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_BREAK,8);
      TIM_ClearITPendingBit(TIM8,TIM_IT_Break);
    }
    else if(TIM_GetITStatus(TIM12,TIM_IT_CC1)!=RESET) {
      TimerInterruptFeature<12>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE1,12);
      TIM_ClearITPendingBit(TIM12,TIM_IT_CC1);
    }
    else if(TIM_GetITStatus(TIM12,TIM_IT_CC2)!=RESET) {
      TimerInterruptFeature<12>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE2,12);
      TIM_ClearITPendingBit(TIM12,TIM_IT_CC2);
    }
    else if(TIM_GetITStatus(TIM12,TIM_IT_Update)!=RESET) {
      TimerInterruptFeature<12>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_UPDATE,12);
      TIM_ClearITPendingBit(TIM12,TIM_IT_Update);
    }
    else if(TIM_GetITStatus(TIM12,TIM_IT_Trigger)!=RESET) {
      TimerInterruptFeature<12>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_TRIGGER,12);
      TIM_ClearITPendingBit(TIM12,TIM_IT_Trigger);
    }
    __DSB();      // prevent erroneous recall of this handler due to delayed memory write
  }

#endif

  /**
   * TIM8_UP and TIM13 (XL-density only) share the same vector.
   * TIM13 can have CC1, Update
   */

#if defined(USE_TIM8_UP_INTERRUPT) || defined(USE_TIM13_INTERRUPT)

  void __attribute__ ((interrupt("IRQ"))) TIM8_UP_IRQHandler() {

    if(TIM_GetITStatus(TIM8,TIM_IT_Update)!=RESET) {
      TimerInterruptFeature<8>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_UPDATE,8);
      TIM_ClearITPendingBit(TIM8,TIM_IT_Update);
    }
    else if(TIM_GetITStatus(TIM13,TIM_IT_CC1)!=RESET) {
      TimerInterruptFeature<13>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE1,13);
      TIM_ClearITPendingBit(TIM13,TIM_IT_CC1);
    }
    else if(TIM_GetITStatus(TIM13,TIM_IT_Update)!=RESET) {
      TimerInterruptFeature<13>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_UPDATE,13);
      TIM_ClearITPendingBit(TIM13,TIM_IT_Update);
    }
    __DSB();      // prevent erroneous recall of this handler due to delayed memory write
  }

#endif

  /**
   * TIM8_TRG_COM and TIM14 (XL-density only) share the same vector.
   * TIM14 can have CC1, Update
   */

#if defined(USE_TIM8_TRG_COM_INTERRUPT) || defined(USE_TIM14_INTERRUPT)

  void __attribute__ ((interrupt("IRQ"))) TIM8_TRG_COM_IRQHandler() {

    if(TIM_GetITStatus(TIM8,TIM_IT_Trigger)!=RESET) {
      TimerInterruptFeature<8>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_TRIGGER,8);
      TIM_ClearITPendingBit(TIM8,TIM_IT_Trigger);
    }
    else if(TIM_GetITStatus(TIM8,TIM_IT_COM)!=RESET) {
      TimerInterruptFeature<8>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COM,8);
      TIM_ClearITPendingBit(TIM8,TIM_IT_COM);
    }
    else if(TIM_GetITStatus(TIM14,TIM_IT_CC1)!=RESET) {
      TimerInterruptFeature<14>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE1,14);
      TIM_ClearITPendingBit(TIM14,TIM_IT_CC1);
    }
    else if(TIM_GetITStatus(TIM14,TIM_IT_Update)!=RESET) {
      TimerInterruptFeature<14>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_UPDATE,14);
      TIM_ClearITPendingBit(TIM14,TIM_IT_Update);
    }
    __DSB();      // prevent erroneous recall of this handler due to delayed memory write
  }

#endif

  /**
   * TIM8_CC interrupt handler
   */

#if defined(USE_TIM8_CC_INTERRUPT)

  void __attribute__ ((interrupt("IRQ"))) TIM8_CC_IRQHandler() {

    if(TIM_GetITStatus(TIM8,TIM_IT_CC1)!=RESET) {
      TimerInterruptFeature<8>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE1,8);
      TIM_ClearITPendingBit(TIM8,TIM_IT_CC1);
    }
    else if(TIM_GetITStatus(TIM8,TIM_IT_CC2)!=RESET) {
      TimerInterruptFeature<8>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE2,8);
      TIM_ClearITPendingBit(TIM8,TIM_IT_CC2);
    }
    else if(TIM_GetITStatus(TIM8,TIM_IT_CC3)!=RESET) {
      TimerInterruptFeature<8>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE3,8);
      TIM_ClearITPendingBit(TIM8,TIM_IT_CC3);
    }
    else if(TIM_GetITStatus(TIM8,TIM_IT_CC3)!=RESET) {
      TimerInterruptFeature<8>::_timerInstance->TimerInterruptEventSender.raiseEvent(TimerEventType::EVENT_COMPARE3,8);
      TIM_ClearITPendingBit(TIM8,TIM_IT_CC3);
    }
    __DSB();      // prevent erroneous recall of this handler due to delayed memory write
  }

#endif
} // extern "C"

#endif


text:
<?xml version="1.0"?>
<ruleset name="crap coding standard">
    <description>crap coding standard</description>
    <arg value="p"/><!-- display progress -->
    <arg name="colors"/><!-- make it pretty -->
    <rule ref="PSR2"/>
    <rule ref="Generic.Arrays.DisallowLongArraySyntax"/>
    <file>src</file>
    <file>tests</file>
</ruleset>


text:
from django.apps import apps
from django.conf import settings
from django.db.models import Q, QuerySet

from .functions import sanitize_order_by, _get_api_model
from .response import set_response_headers

get_model = apps.get_model

"""
In Django 1.9 _clone method no longer allows a different class. Instead need to subclass the ModelIterable class
Differences described below when the queryset is iterated:
1.8:
__iter__ -> _fetch_all -> list(self.iterator()) -> key generator code (QuerySet.iterator) -> the remainder code provided below to cast objects (SubclassQuerySet.iterator)
1.9:
__iter__ -> _fetch_all -> list(self.iterator()) -> return iter(self._iterable_class(self)) -> key generator code (ModelIterable.__iter__()) is almost identical to the key generator code from 1.8 and can be wrapped the same

Since the Iterable class is not created until needed it is possible to simly replace it.
See for example the values() method:
clone._iterable_class = ValuesIterable
"""

class SubclassQuerySet(QuerySet):
    """QuerySet that returns subclasses automatically when iterating."""
    def _clone(self, **kwargs):
        clone = super(SubclassQuerySet, self)._clone(**kwargs)
        clone._subclass_attrs = getattr(self, '_subclass_attrs', None)
        return clone
    def iterator(self):
        iter = super(SubclassQuerySet, self).iterator()
        for obj in iter:
            sub_obj = None
            for attr in self._subclass_attrs:
                if hasattr(obj, attr):
                    sub_obj = getattr(obj, attr)
                    break
            if sub_obj:
                yield sub_obj
            else:
                yield obj

def subclass_filter(*subclasses, **names):
    """
    Convert the QuerySet to a SubclassQuerySet, where only the specified subclasses are returned and each object is cast to its subclass.
    The keyword arguments, has the names for the collection when generating files. name and name_plural provided as CamelCase are required.
    """
    # TODO: To support multi-level inheritance, subclass_attrs needs find the common parent of all subclasses and will either be a dict tree of keys only (multi-level) or list (single).
    # The iterator() will then do multi-level getattr if isinstance(self._subclass_attrs, dict) otherwise use the existing code.
    # The select_related() part will also need to specify multi-level inheritance using intermediate__subclass strings
    subclasses = list(subclasses)
    for i, subclass in enumerate(subclasses):
        if isinstance(subclass, (str, unicode)):
            subclass = subclass.split('.')
            subclasses[i] = get_model(subclass[0], subclass[1])
    subclass_attrs = [cls.__name__.lower() for cls in subclasses]
    def subclass_filter_inner(request, queryset):
        set_response_headers(request, **{'X-Mixed-Results': True})
        queryset = queryset._clone(SubclassQuerySet).select_related(*subclass_attrs)
        # Remember the subclass arguments, because the queryset.query.select_related dict may have other non-subclass attributes
        queryset._subclass_attrs = subclass_attrs
        return queryset
    return subclass_filter_inner

def search_filter(request, queryset):
    """Filter down the result by using a q query parameter. API.search_fields MUST be set to use this."""
    query = request.GET.get('q')
    if query and hasattr(queryset.model, 'API') and hasattr(queryset.model.API, 'search_fields') and queryset.model.API.search_fields:
        params = None
        for field in queryset.model.API.search_fields:
            if field.find('.'):
                field = field.replace('.', '__')
            if not params:
                params = Q(**{field + '__icontains': query})
            else:
                params = params | Q(**{field + '__icontains': query})
        queryset = queryset.filter(params)
    return queryset

def field_filter(request, queryset):
    """Filter the results by named fields in the query string. API.filter_fields MUST be set to use this."""
    if len(request.GET) and hasattr(queryset.model, 'API'):
        if hasattr(queryset.model.API, 'filter_fields'):
            model = _get_api_model(queryset.model)
            for field in queryset.model.API.filter_fields:
                value = request.GET.get(field)
                if value:
                    encoded_field = model.encoded_fields[field]
                    key = encoded_field[0]
                    decode = encoded_field[3]
                    if decode:
                        value = decode(value)
                    queryset = queryset.filter(**{key: value})
        if hasattr(queryset.model.API, 'filters'):
            model = _get_api_model(queryset.model)
            for key in queryset.model.API.filters:
                value = request.GET.get(key)
                if value:
                    filtr = queryset.model.API.filters[key]
                    decoder = filtr.get('decoder')
                    lookup = filtr['lookup']
                    if decoder:
                        value = decoder(value)
                    if isinstance(lookup, (list, tuple)):
                        params = None
                        for l in lookup:
                            if not params:
                                params = Q(**{l: value})
                            else:
                                params = params | Q(**{l: value})
                        queryset = queryset.filter(params)
                    else:
                        queryset = queryset.filter(**{lookup: value})
    return queryset

def order_by_filter(request, queryset):
    """Order the results by using an orderby parameter."""
    order_by = sanitize_order_by(request.GET.get('orderby', ''))
    if order_by:
        if hasattr(queryset.model, 'API') and hasattr(queryset.model.API, 'order_by_fields') and queryset.model.API.order_by_fields:
            if order_by.lstrip('-') in queryset.model.API.order_by_fields:
                queryset = queryset.order_by(order_by)
        else:
            queryset = queryset.order_by(order_by)
    return queryset

__API_PAGE_SIZE = getattr(settings, 'API_PAGE_SIZE', 100)

def paginate_filter(request, queryset):
    """Paginate the results based on page and pagesize parameters. This should be the last filter applied."""
    page = request.GET.get('page', 0)
    if not isinstance(page, int):
        if page.isdigit():
            page = int(page)
        else:
            return queryset.none()
    if hasattr(queryset.model, 'API') and hasattr(queryset.model.API, 'page_size'):
        max_page_size = queryset.model.API.page_size
    else:
        max_page_size = __API_PAGE_SIZE
    page_size = request.GET.get('pagesize', max_page_size)
    if not isinstance(page_size, int):
        if page_size.isdigit():
            page_size = int(page_size)
        else:
            return queryset.none()
    if page_size > max_page_size or page_size < 0:
        page_size = max_page_size
    start_index = page * page_size
    end_index = start_index + page_size
    total = queryset.count()
    total_pages = total/page_size + (1 if total % page_size else 0)
    set_response_headers(request, **{'X-Total': total, 'X-Total-Pages': total_pages, 'X-Page': page, 'X-Page-Size': page_size})
    if (page + 1) < total_pages:
        set_response_headers(request, **{'X-Next-Page': page + 1})
    if page:
        set_response_headers(request, **{'X-Prev-Page': page - 1})
    return queryset[start_index:end_index]

def combine_filters(*filters):
    """Combine multiple filters into one."""
    def combine_filters_inner(request, queryset):
        for filter in filters:
            queryset = filter(request, queryset)
        return queryset
    return combine_filters_inner

def filter_as_authorization(model, filter):
    """Create an authorization function based on a collection filter."""
    if isinstance(model, (str, unicode)):
        model = model.split('.')
        model = get_model(model[0], model[1])
    def filter_as_authorization_fun(request, obj):
        return filter(request, model.objects.all()).filter(id=obj.id).exists()
    filter_as_authorization_fun.__doc__ = "Only allow access to objects in the filter: %s" % (filter.__doc__ if filter.__doc__ else filter.__name__ + '()')
    return filter_as_authorization_fun


text:
package com.fese.particleremote;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

//import org.joda.time.format.DateTimeFormatter;

import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import io.particle.android.sdk.cloud.*;
import io.particle.android.sdk.cloud.ParticleDevice;
import io.particle.android.sdk.utils.Async;
import io.particle.android.sdk.cloud.exceptions.ParticleCloudException;

public class TempHumiActivity extends AppCompatActivity {
    private TextView temperatureTV;
    private TextView humidityTV;
    private String myParticleID = null;
    private io.particle.android.sdk.cloud.ParticleDevice myParticleDevice;
    double temperatureVal;
    double humidityVal;
    String temperatureValuesChain = "";
    String humidityValuesChain = "";
    private LineChart tempHumiChart;
    private ArrayList<ILineDataSet> dataSets;
    final android.os.Handler handler = new android.os.Handler();
    private View viewTempHumi;
    //private Long referenceTimestamp = ((System.currentTimeMillis()/1000) - (25 * 3600));

    //static
    private int refresh_cycle;                                          //unit:
    private static final int RECORD_CYCLE_TEMP_HUMI_HISTORY = 1800;     //time interval in seconds when the particle device adds new values to the history
    private static final float MIN_TEMPERATURE_DEFAULT_VALUE = 10;
    private static final float MAX_TEMPERATURE_DEFAULT_VALUE = 30;
    private static final float MIN_HUMIDITY_DEFAULT_VALUE = 0;
    private static final float MAX_HUMIDITY_DEFAULT_VALUE = 100;
    private static final float X_AXIS_VISIBLE_RANGE = 24 * 3600;                     //visible entries for the last day = 24h
    private static final String CloudVariableTempLabel = "temperature";
    private static final String CloudVariableHumiLabel = "humidity";
    private static final String CloudVariableTempHistoryLabel = "tempRec";
    private static final String CloudVariableHumiHistoryLabel = "humiRec";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp_humi);

        temperatureTV = findViewById(R.id.tv_temperature);
        humidityTV = findViewById(R.id.tv_humidity);
        viewTempHumi = findViewById(R.id.RelLay_tempHumi);

        //Init Line Chart
        tempHumiChart = findViewById(R.id.tempHumiChart);
        dataSets = new ArrayList<>();
        LineData data = new LineData(dataSets);
        tempHumiChart.setData(data);
        tempHumiChart.getDescription().setEnabled(false);

        //TODO: show a MarkerView, class is prepared in the bottom code, xml layout can be found in the github link (also at the bottom)

        //MyMarkerView myMarkerView= new MyMarkerView(getApplicationContext(), R.layout.my_marker_view_layout, referenceTimestamp);
        //mChart.setMarkerView(myMarkerView);

        //Format the time xAxis
        XAxis xAxis = tempHumiChart.getXAxis();
        xAxis.setValueFormatter(new MyXAxisTimeFormatter());
        //xAxis.setAxisMinimum(0);
        //xAxis.setAxisMaximum(25 * 3600 * 1000);
        xAxis.setLabelCount(6, true);

        //Format the humidity yAxis
        YAxis yAxisRight = tempHumiChart.getAxisRight();
        yAxisRight.setValueFormatter(new MyYAxisHumidityFormatter());
        yAxisRight.setAxisMinimum(MIN_HUMIDITY_DEFAULT_VALUE);
        yAxisRight.setAxisMaximum(MAX_HUMIDITY_DEFAULT_VALUE);
        yAxisRight.setLabelCount(11, true);

        //Format the temperature yAxis
        YAxis yAxisLeft = tempHumiChart.getAxisLeft();
        yAxisLeft.setLabelCount(11, true);
        yAxisLeft.setAxisMinimum(MIN_TEMPERATURE_DEFAULT_VALUE);
        yAxisLeft.setAxisMaximum(MAX_TEMPERATURE_DEFAULT_VALUE);
        yAxisLeft.setValueFormatter(new MyYAxisTemperatureFormatter());

        //set toolbar and navigate up arrow
        android.support.v7.widget.Toolbar toolbar = findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        //call Methods
        ParticleCloudSDK.init(this);
        getParticleDeviceInstance();
        getTemperatureAndHumidity();

    }

    private void getTemperatureAndHumidity(){

        if (myParticleDevice != null) {
            Async.executeAsync(ParticleCloudSDK.getCloud(), new Async.ApiWork<ParticleCloud, Boolean>() {

                @Override
                public Boolean callApi(ParticleCloud particleCloud) throws ParticleCloudException, IOException {
                    boolean success = false;

                    try {
                        temperatureVal = myParticleDevice.getDoubleVariable(CloudVariableTempLabel);
                        humidityVal = myParticleDevice.getDoubleVariable(CloudVariableHumiLabel);
                        success = true;
                    }

                    catch (ParticleDevice.VariableDoesNotExistException e){
                        //Log.e("SOME_TAG", e.getMessage().toString());
                        Snackbar snackbarError = Snackbar
                                .make(viewTempHumi, e.getMessage(), Snackbar.LENGTH_LONG);
                        snackbarError.show();
                    }

                    return success;
                }

                public void onSuccess(Boolean onSuccess) {
                    if (onSuccess){
                        //addTempHumiValueToChart((float) temperatureVal, (float) humidityVal, refresh_cycle/1000);
                        if (temperatureVal == -100 || humidityVal == -100)
                        {
                            Snackbar snackbarError = Snackbar
                                    .make(viewTempHumi, R.string.DHT22_error_snackbar_message, Snackbar.LENGTH_LONG);
                            snackbarError.show();
                        }
                        else
                        {
                            setValuesToEditText();
                        }

                    }

                }

                public void onFailure(ParticleCloudException e) {
                    Log.e("SOME_TAG", e.getBestMessage());
                    Snackbar snackbarError = Snackbar
                            .make(viewTempHumi, e.getBestMessage(), Snackbar.LENGTH_LONG);
                    snackbarError.show();

                }

            });

        }
        else {
            handler.postDelayed(new Runnable() {
                public void run() {
                    getTemperatureAndHumidity();
                }
            }, 1000);
        }
    }

    //TODO: add menu "fast record" => show in the diagram the "live" values

    private void getTemperatureAndHumidityHistory(){

        if (myParticleDevice != null) {
            Async.executeAsync(ParticleCloudSDK.getCloud(), new Async.ApiWork<ParticleCloud, Boolean>() {

                @Override
                public Boolean callApi(ParticleCloud particleCloud) throws ParticleCloudException, IOException {
                    boolean success = false;

                    try {
                        temperatureValuesChain = myParticleDevice.getStringVariable(CloudVariableTempHistoryLabel);
                        humidityValuesChain = myParticleDevice.getStringVariable(CloudVariableHumiHistoryLabel);
                        success = true;
                    }

                    catch (ParticleDevice.VariableDoesNotExistException e){
                        //Log.e("SOME_TAG", e.getMessage().toString());
                        Snackbar snackbarError = Snackbar
                                .make(viewTempHumi, e.getMessage(), Snackbar.LENGTH_LONG);
                        snackbarError.show();
                    }

                    return success;
                }

                public void onSuccess(Boolean onSuccess) {
                    if (onSuccess){

                        String[] temperatureValuesArray = temperatureValuesChain.split(";");
                        String[] humidityValuesArray = humidityValuesChain.split(";");

                        float lastValueUpdateTimestamp = 0;

                        //check if the lastValueUpdateTimestamp is in the humidity array
                        if (humidityValuesArray.length > temperatureValuesArray.length){
                            lastValueUpdateTimestamp = Float.parseFloat(humidityValuesArray[humidityValuesArray.length - 1]);
                        }
                        else{
                            lastValueUpdateTimestamp = System.currentTimeMillis()/1000;                                                 //should never be called. inexact timestamp (the newest value could be 0-59min old)
                        }

                        //displaying the oldest value in the array first
                        for(int i = (temperatureValuesArray.length - 1); i >= 0; i--)
                        {

                            try {
                                addTempHumiValueToChart(Float.parseFloat(temperatureValuesArray[i])/10, Float.parseFloat(humidityValuesArray[i]), (lastValueUpdateTimestamp - (i * RECORD_CYCLE_TEMP_HUMI_HISTORY)));
                            }
                            catch(NumberFormatException ex) {
                                Log.e("SOME_TAG", ex.getMessage());
                                Snackbar snackbarNumberCheck = Snackbar
                                        .make(viewTempHumi, R.string.empty_value_temperature_history_snackbar_message, Snackbar.LENGTH_LONG);
                                snackbarNumberCheck.show();
                            }

                        }
                        //move visible range to the newest values
                        tempHumiChart.moveViewToX(lastValueUpdateTimestamp - X_AXIS_VISIBLE_RANGE + 100);               //100 = Offset to display the last X-Axis label value on the right

                    }

                }

                public void onFailure(ParticleCloudException e) {
                    Log.e("SOME_TAG", e.getBestMessage());
                    Snackbar snackbarError = Snackbar
                            .make(viewTempHumi, e.getBestMessage(), Snackbar.LENGTH_LONG);
                    snackbarError.show();

                }

            });

        }
        else {
            handler.postDelayed(new Runnable() {
                public void run() {
                    getTemperatureAndHumidityHistory();
                }
            }, 1000);
        }
    }

    private void clearDiagram(){
        LineData data = tempHumiChart.getData();
        data.clearValues();
        tempHumiChart.notifyDataSetChanged();
    }

    private void setValuesToEditText(){
        temperatureVal = (double)Math.round(temperatureVal * 100)/ 100d;
        humidityVal = (double)Math.round(humidityVal * 100)/ 100d;

        temperatureTV.setText(getString(R.string.temperature)+ ": " + String.valueOf(temperatureVal) + " °C");
        humidityTV.setText(getString(R.string.humidity) + ": " + String.valueOf(humidityVal) + " %");
    }

    private void addTempHumiValueToChart(float temperatureValueY, float humidityValueY, float timeValueX){

        LineData data = tempHumiChart.getData();

        if (data != null) {
            ILineDataSet tempSet = data.getDataSetByIndex(0);

            if (tempSet == null) {
                tempSet = createTemperatureSet();
                dataSets.add(tempSet);

            }

            ILineDataSet humiSet = data.getDataSetByIndex(1);

            if (humiSet == null) {
                humiSet = createHumiditySet();
                dataSets.add(humiSet);
            }

            if (temperatureValueY < MIN_TEMPERATURE_DEFAULT_VALUE){
                YAxis yAxisLeft = tempHumiChart.getAxisLeft();
                yAxisLeft.resetAxisMinimum();
            }
            else if (temperatureValueY > MAX_TEMPERATURE_DEFAULT_VALUE){
                YAxis yAxisLeft = tempHumiChart.getAxisLeft();
                yAxisLeft.resetAxisMaximum();
            }

            data.addEntry(new Entry(timeValueX, temperatureValueY), 0);
            data.addEntry(new Entry(timeValueX, humidityValueY), 1);
            data.notifyDataChanged();

            // let the chart know it's data has changed
            tempHumiChart.notifyDataSetChanged();

            // limit the number of visible entries
            tempHumiChart.setVisibleXRangeMaximum(X_AXIS_VISIBLE_RANGE);
            // tempHumiChart.setVisibleYRange(30, AxisDependency.LEFT);

        }

    }

    private void getRefreshCycleFromSettings(){
        Log.i("SOME_TAG", "getRefreshCycleFromSettings");
        SharedPreferences SharedPref  = PreferenceManager.getDefaultSharedPreferences(this);

        String refreshCycleString = SharedPref.getString(getString(R.string.pref_refresh_cycle_chart_key), getString(R.string.refresh_cycle_chart_default_value));
        refresh_cycle = Integer.valueOf(refreshCycleString) * 1000;

    }

    private LineDataSet createTemperatureSet(){
        LineDataSet set = new LineDataSet(null, getString(R.string.temperature) + " [°C]");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setColor(ColorTemplate.MATERIAL_COLORS[1]);
        //set.setCircleColor(Color.WHITE);
        set.setDrawCircles(false);
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set.setLineWidth(2f);
        //set.setCircleRadius(4f);
        set.setFillAlpha(65);
        set.setFillColor(ColorTemplate.getHoloBlue());
        set.setHighLightColor(Color.rgb(244, 117, 117));
        set.setValueTextColor(Color.WHITE);
        set.setValueTextSize(9f);
        set.setDrawValues(false);
        return set;
    }

    private LineDataSet createHumiditySet(){
        LineDataSet set = new LineDataSet(null, getString(R.string.humidity) + " [%]");
        set.setAxisDependency(YAxis.AxisDependency.RIGHT);
        set.setColor(ColorTemplate.MATERIAL_COLORS[3]);
        //set.setCircleColor(Color.WHITE);
        set.setDrawCircles(false);
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set.setLineWidth(2f);
        //set.setCircleRadius(4f);
        set.setFillAlpha(65);
        set.setFillColor(ColorTemplate.getHoloBlue());
        set.setHighLightColor(Color.rgb(244, 117, 117));
        set.setValueTextColor(Color.WHITE);
        set.setValueTextSize(9f);
        set.setDrawValues(false);
        return set;
    }

    private void getParticleDeviceInstance(){

        //get the ID of the selected Particle Device from the MainActivity
        myParticleID = (String) getIntent().getSerializableExtra("deviceID");

        Async.executeAsync(ParticleCloudSDK.getCloud(), new Async.ApiWork<ParticleCloud, Void>() {

            public Void callApi(ParticleCloud particleCloud) throws ParticleCloudException {
                myParticleDevice = ParticleCloudSDK.getCloud().getDevice(myParticleID);
                return null;
            }

            public void onSuccess(Void aVoid) {

            }

            public void onFailure(ParticleCloudException e) {
                Log.e("SOME_TAG", e.getBestMessage());
                Snackbar snackbarError = Snackbar
                        .make(viewTempHumi, e.getBestMessage(), Snackbar.LENGTH_LONG);
                snackbarError.show();
            }

        });

    }

    private Runnable getNewValuesRunnable = new Runnable() {
        @Override
        public void run() {

            getTemperatureAndHumidity();
            handler.postDelayed(getNewValuesRunnable, refresh_cycle);

        }
    };

    @Override
    protected void onPause() {
        handler.removeCallbacks(getNewValuesRunnable);
        super.onPause();
    }

    @Override
    protected void onResume()
    {
        getRefreshCycleFromSettings();
        handler.post(getNewValuesRunnable);
        clearDiagram();
        getTemperatureAndHumidityHistory();
        super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_temp_humi_activity, menu);
        return super.onCreateOptionsMenu(menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
            case R.id.menu_settings:
                Intent intentSettings = new Intent(TempHumiActivity.this, UserSettingsActivity.class);
                TempHumiActivity.this.startActivity(intentSettings);
                return true;

            case R.id.menu_history:
                clearDiagram();
                getTemperatureAndHumidityHistory();
                return true;

            case R.id.menu_clear_diagram:
                clearDiagram();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }

    }

}

class MyXAxisTimeFormatter implements IAxisValueFormatter {

    //private long referenceTimestamp; // minimum timestamp in your data set
    private DateFormat mDataFormat;
    private Date mDate;

    public MyXAxisTimeFormatter() {
        //this.referenceTimestamp = referenceTimestamp;
        this.mDataFormat = new SimpleDateFormat("EEE, HH:mm", Locale.ENGLISH);
        this.mDate = new Date();
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // convertedTimestamp = originalTimestamp - referenceTimestamp
        long convertedTimestamp = (long) value;

        // Retrieve original timestamp
        //long originalTimestamp = referenceTimestamp + convertedTimestamp;

        // Convert timestamp to hour:minute
        return getHour(convertedTimestamp);
    }

    public int getDecimalDigits() {
        return 0;
    }

    private String getHour(long timestamp){
        try{
            mDate.setTime(timestamp*1000);
            return mDataFormat.format(mDate);
        }
        catch(Exception ex){
            return "xx";
        }
    }
}

class MyYAxisTemperatureFormatter implements IAxisValueFormatter {

    private DecimalFormat mFormat;

    public MyYAxisTemperatureFormatter () {
        mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // write your logic here
        // access the YAxis object to get more information
        return mFormat.format(value) + " °C"; // e.g. append a dollar-sign
    }
}

class MyYAxisHumidityFormatter implements IAxisValueFormatter {

    private DecimalFormat mFormat;

    public MyYAxisHumidityFormatter () {
        mFormat = new DecimalFormat("###,###,##0"); // use no decimal
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // write your logic here
        // access the YAxis object to get more information
        return mFormat.format(value) + " %"; // e.g. append a dollar-sign
    }
}

/**
 * The following class for the MarkerView must be edited
 * The conversion of the referenceTimestamp must be deleted for my solution
 * See MyXAxisTimeFormatter
 *
 * https://github.com/PhilJay/MPAndroidChart/issues/789#issuecomment-241507904
 *
 */

/*
public class MyMarkerView extends MarkerView {

    private TextView tvContent;
    private long referenceTimestamp;  // minimum timestamp in your data set
    private DateFormat mDataFormat;
    private Date mDate;

    public MyMarkerView (Context context, int layoutResource, long referenceTimestamp) {
        super(context, layoutResource);
        // this markerview only displays a textview
        tvContent = (TextView) findViewById(R.id.tvContent);
        this.referenceTimestamp = referenceTimestamp;
        this.mDataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
        this.mDate = new Date();
    }

    // callbacks everytime the MarkerView is redrawn, can be used to update the
    // content (user-interface)
    @Override
    public void refreshContent(Entry e, Highlight highlight) {
        long currentTimestamp = (int)e.getX() + referenceTimestamp;

        tvContent.setText(e.getY() + "% at " + getTimedate(currentTimestamp)); // set the entry-value as the display text
    }

    @Override
    public int getXOffset(float xpos) {
        // this will center the marker-view horizontally
        return -(getWidth() / 2);
    }

    @Override
    public int getYOffset(float ypos) {
        // this will cause the marker-view to be above the selected value
        return -getHeight();
    }

    private String getTimedate(long timestamp){

        try{
            mDate.setTime(timestamp*1000);
            return mDataFormat.format(mDate);
        }
        catch(Exception ex){
            return "xx";
        }
    }
}
*/


text:
<?php
namespace SergioCarlos\IBMWatson\WatsonLanguageTranslator\Translator\Tests;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Psr7\Response;
use SergioCarlos\IBMWatson\WatsonLanguageTranslator\Api\Transport;

class TransportTest extends \PHPUnit_Framework_TestCase
{
    public function testCanInstantiateTransportWithoutSpecifyingHTTPClient()
    {
        $this->assertInstanceOf(
            Transport::class,
            new Transport('username', 'password')
        );
    }

    /**
     * @dataProvider provideSendSynchronousApiRequestKicksOffHTTPClientTestData
     * @param string $requestBody
     * @param bool $isRequestBodyJsonFlag
     */
    public function testSendSynchronousApiRequestKicksOffExpectedRequestOnHTTPClient(
        $requestBody,
        $isRequestBodyJsonFlag
    ) {
        $httpMethod = 'GET';
        $apiUri = 'whatever';
        $username = 'username';
        $password = 'password';
        $httpClient = $this->getMock(
            HttpClient::class,
            [
                'request'
            ]
        );
        $expectedHeaderContentType = ($isRequestBodyJsonFlag)
            ? 'application/json'
            : 'text/plain';
        $expectedHeadersArray = [
            'auth' => [$username, $password],
            'body' => $requestBody,
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => $expectedHeaderContentType
            ],
        ];
        $httpClient->expects($this->once())
            ->method('request')
            ->with($httpMethod, $apiUri, $expectedHeadersArray)
            ->will($this->returnValue(new Response()));
        $transport = new Transport($username, $password, $httpClient);
        $transport->sendSynchronousApiRequest($httpMethod, $apiUri, $requestBody, $expectedHeaderContentType);
    }

    /**
     * @return array
     */
    public function provideSendSynchronousApiRequestKicksOffHTTPClientTestData()
    {
        return [
            'JSON request' => [json_encode(new \stdClass()), true],
            'Plain text request' => [':)', false]
        ];
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>streams</artifactId>
        <groupId>com.hortonworks.streamline</groupId>
        <version>0.1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>streamline-authorizer</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.hortonworks.streamline</groupId>
            <artifactId>streamline-sdk</artifactId>
        </dependency>
        <dependency>
            <groupId>com.hortonworks.streamline</groupId>
            <artifactId>storage-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.hortonworks.streamline</groupId>
            <artifactId>streamline-catalog</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jmockit</groupId>
            <artifactId>jmockit</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
    </dependencies>
</project>