text:
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "avfilter.h"
#include "formats.h"
#include "internal.h"
#include "video.h"

typedef struct VibranceContext {
    const AVClass *class;

    float intensity;
    float balance[3];
    float lcoeffs[3];
    int alternate;

    int depth;

    int (*do_slice)(AVFilterContext *s, void *arg,
                    int jobnr, int nb_jobs);
} VibranceContext;

static inline float lerpf(float v0, float v1, float f)
{
    return v0 + (v1 - v0) * f;
}

static int vibrance_slice8(AVFilterContext *avctx, void *arg, int jobnr, int nb_jobs)
{
    VibranceContext *s = avctx->priv;
    AVFrame *frame = arg;
    const int width = frame->width;
    const int height = frame->height;
    const float scale = 1.f / 255.f;
    const float gc = s->lcoeffs[0];
    const float bc = s->lcoeffs[1];
    const float rc = s->lcoeffs[2];
    const float intensity = s->intensity;
    const float alternate = s->alternate ? 1.f : -1.f;
    const float gintensity = intensity * s->balance[0];
    const float bintensity = intensity * s->balance[1];
    const float rintensity = intensity * s->balance[2];
    const float sgintensity = alternate * FFSIGN(gintensity);
    const float sbintensity = alternate * FFSIGN(bintensity);
    const float srintensity = alternate * FFSIGN(rintensity);
    const int slice_start = (height * jobnr) / nb_jobs;
    const int slice_end = (height * (jobnr + 1)) / nb_jobs;
    const int glinesize = frame->linesize[0];
    const int blinesize = frame->linesize[1];
    const int rlinesize = frame->linesize[2];
    uint8_t *gptr = frame->data[0] + slice_start * glinesize;
    uint8_t *bptr = frame->data[1] + slice_start * blinesize;
    uint8_t *rptr = frame->data[2] + slice_start * rlinesize;

    for (int y = slice_start; y < slice_end; y++) {
        for (int x = 0; x < width; x++) {
            float g = gptr[x] * scale;
            float b = bptr[x] * scale;
            float r = rptr[x] * scale;
            float max_color = FFMAX3(r, g, b);
            float min_color = FFMIN3(r, g, b);
            float color_saturation = max_color - min_color;
            float luma = g * gc + r * rc + b * bc;
            const float cg = 1.f + gintensity * (1.f - sgintensity * color_saturation);
            const float cb = 1.f + bintensity * (1.f - sbintensity * color_saturation);
            const float cr = 1.f + rintensity * (1.f - srintensity * color_saturation);

            g = lerpf(luma, g, cg);
            b = lerpf(luma, b, cb);
            r = lerpf(luma, r, cr);

            gptr[x] = av_clip_uint8(g * 255.f);
            bptr[x] = av_clip_uint8(b * 255.f);
            rptr[x] = av_clip_uint8(r * 255.f);
        }

        gptr += glinesize;
        bptr += blinesize;
        rptr += rlinesize;
    }

    return 0;
}

static int vibrance_slice16(AVFilterContext *avctx, void *arg, int jobnr, int nb_jobs)
{
    VibranceContext *s = avctx->priv;
    AVFrame *frame = arg;
    const int depth = s->depth;
    const float max = (1 << depth) - 1;
    const float scale = 1.f / max;
    const float gc = s->lcoeffs[0];
    const float bc = s->lcoeffs[1];
    const float rc = s->lcoeffs[2];
    const int width = frame->width;
    const int height = frame->height;
    const float intensity = s->intensity;
    const float alternate = s->alternate ? 1.f : -1.f;
    const float gintensity = intensity * s->balance[0];
    const float bintensity = intensity * s->balance[1];
    const float rintensity = intensity * s->balance[2];
    const float sgintensity = alternate * FFSIGN(gintensity);
    const float sbintensity = alternate * FFSIGN(bintensity);
    const float srintensity = alternate * FFSIGN(rintensity);
    const int slice_start = (height * jobnr) / nb_jobs;
    const int slice_end = (height * (jobnr + 1)) / nb_jobs;
    const int glinesize = frame->linesize[0] / 2;
    const int blinesize = frame->linesize[1] / 2;
    const int rlinesize = frame->linesize[2] / 2;
    uint16_t *gptr = (uint16_t *)frame->data[0] + slice_start * glinesize;
    uint16_t *bptr = (uint16_t *)frame->data[1] + slice_start * blinesize;
    uint16_t *rptr = (uint16_t *)frame->data[2] + slice_start * rlinesize;

    for (int y = slice_start; y < slice_end; y++) {
        for (int x = 0; x < width; x++) {
            float g = gptr[x] * scale;
            float b = bptr[x] * scale;
            float r = rptr[x] * scale;
            float max_color = FFMAX3(r, g, b);
            float min_color = FFMIN3(r, g, b);
            float color_saturation = max_color - min_color;
            float luma = g * gc + r * rc + b * bc;
            const float cg = 1.f + gintensity * (1.f - sgintensity * color_saturation);
            const float cb = 1.f + bintensity * (1.f - sbintensity * color_saturation);
            const float cr = 1.f + rintensity * (1.f - srintensity * color_saturation);

            g = lerpf(luma, g, cg);
            b = lerpf(luma, b, cb);
            r = lerpf(luma, r, cr);

            gptr[x] = av_clip_uintp2_c(g * max, depth);
            bptr[x] = av_clip_uintp2_c(b * max, depth);
            rptr[x] = av_clip_uintp2_c(r * max, depth);
        }

        gptr += glinesize;
        bptr += blinesize;
        rptr += rlinesize;
    }

    return 0;
}

static int filter_frame(AVFilterLink *link, AVFrame *frame)
{
    AVFilterContext *avctx = link->dst;
    VibranceContext *s = avctx->priv;
    int res;

    if (res = avctx->internal->execute(avctx, s->do_slice, frame, NULL,
                                       FFMIN(frame->height, ff_filter_get_nb_threads(avctx))))
        return res;

    return ff_filter_frame(avctx->outputs[0], frame);
}

static av_cold int query_formats(AVFilterContext *avctx)
{
    static const enum AVPixelFormat pixel_fmts[] = {
        AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP,
        AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12,
        AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
        AV_PIX_FMT_GBRAP10, AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRAP16,
        AV_PIX_FMT_NONE
    };

    AVFilterFormats *formats = NULL;

    formats = ff_make_format_list(pixel_fmts);
    if (!formats)
        return AVERROR(ENOMEM);

    return ff_set_common_formats(avctx, formats);
}

static av_cold int config_input(AVFilterLink *inlink)
{
    AVFilterContext *avctx = inlink->dst;
    VibranceContext *s = avctx->priv;
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);

    s->depth = desc->comp[0].depth;
    s->do_slice = s->depth <= 8 ? vibrance_slice8 : vibrance_slice16;

    return 0;
}

static const AVFilterPad vibrance_inputs[] = {
    {
        .name           = "default",
        .type           = AVMEDIA_TYPE_VIDEO,
        .needs_writable = 1,
        .filter_frame   = filter_frame,
        .config_props   = config_input,
    },
    { NULL }
};

static const AVFilterPad vibrance_outputs[] = {
    {
        .name = "default",
        .type = AVMEDIA_TYPE_VIDEO,
    },
    { NULL }
};

#define OFFSET(x) offsetof(VibranceContext, x)
#define VF AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_RUNTIME_PARAM

static const AVOption vibrance_options[] = {
    { "intensity", "set the intensity value",   OFFSET(intensity),  AV_OPT_TYPE_FLOAT, {.dbl=0},       -2,  2, VF },
    { "rbal", "set the red balance value",      OFFSET(balance[2]), AV_OPT_TYPE_FLOAT, {.dbl=1},      -10, 10, VF },
    { "gbal", "set the green balance value",    OFFSET(balance[0]), AV_OPT_TYPE_FLOAT, {.dbl=1},      -10, 10, VF },
    { "bbal", "set the blue balance value",     OFFSET(balance[1]), AV_OPT_TYPE_FLOAT, {.dbl=1},      -10, 10, VF },
    { "rlum", "set the red luma coefficient",   OFFSET(lcoeffs[2]), AV_OPT_TYPE_FLOAT, {.dbl=0.072186}, 0,  1, VF },
    { "glum", "set the green luma coefficient", OFFSET(lcoeffs[0]), AV_OPT_TYPE_FLOAT, {.dbl=0.715158}, 0,  1, VF },
    { "blum", "set the blue luma coefficient",  OFFSET(lcoeffs[1]), AV_OPT_TYPE_FLOAT, {.dbl=0.212656}, 0,  1, VF },
    { "alternate", "use alternate colors",      OFFSET(alternate),  AV_OPT_TYPE_BOOL,  {.i64=0},        0,  1, VF },
    { NULL }
};

AVFILTER_DEFINE_CLASS(vibrance);

AVFilter ff_vf_vibrance = {
    .name          = "vibrance",
    .description   = NULL_IF_CONFIG_SMALL("Boost or alter saturation."),
    .priv_size     = sizeof(VibranceContext),
    .priv_class    = &vibrance_class,
    .query_formats = query_formats,
    .inputs        = vibrance_inputs,
    .outputs       = vibrance_outputs,
    .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
    .process_command = ff_filter_process_command,
};


text:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import os
import sys
import collections

## Get user inputs and check if they are entered correctly
parser = argparse.ArgumentParser()
parser.add_argument("--MBHx", default="MBHxAggFeatures.npy")
parser.add_argument("--MBHy", default="MBHyAggFeatures.npy")
parser.add_argument("--labelFile", default="labels.npy")
parser.add_argument("--clusterFile", default="clusters.npy")
parser.add_argument("--environ", default="test")
args = parser.parse_args()

x_data = np.load(args.MBHx)
y_data = np.load(args.MBHy)
bach = 3

def f(x, num, den):
	return x * 1.0 * num / den

f = np.vectorize(f)

def loadData(x_data, y_data):
	'''
	Load the data and delete the last and first element.
	These elements are always 0 and cause errors in clustering.
	Label these clusters as -1.
	'''
	x = x_data
	y = y_data
	x_data = np.delete(x_data,0,0)
	x_data = np.delete(x_data,len(x_data)-1,0)
	y_data = np.delete(y_data,0,0)
	y_data = np.delete(y_data,len(y_data)-1,0)
	X = np.asarray([x_data.tolist(), y_data.tolist()])
	X = np.swapaxes(X,0,1)
	return X, x, y

def kMeans(X, i):
	'''
	Perform k-means clustering on the features (MBHx/MBHy)
	Return the labels and cluster centres.
	'''
	kmeans = KMeans(n_clusters=3, random_state=0).fit(X)
	labels = list(kmeans.labels_)
	clusters = list(kmeans.cluster_centers_)
	labels.insert(0, -1)
	labels.append(-1)
	X = np.vstack((np.asarray([0,0]),X))
	X = np.vstack((X,np.asarray([0,0])))
	print labels
	print len(labels)
	return clusters, labels, X

def plot_kMeans(X,labels):
	'''
	Plot the clusters for visual inspection.
	'''
	for (idx,i) in enumerate(X):
		if labels[idx] == 0:
			# print str(idx) + " :0 Here"
			plt.scatter(i[0],i[1],c='r',marker='o')
		elif labels[idx] == 1:
			# print str(idx) + " :1 Here"
			plt.scatter(i[0],i[1],c='b',marker='o')
		elif labels[idx] == 2:
			# print str(idx) + " :2 Here"
			plt.scatter(i[0],i[1],c='g',marker='o')
	# plt.show()

def smoothen(elem, idx, arr, rng):
	'''
	Smoothen the ranges which have turns.
	'''
	start = idx - rng
	if start < 0:
		start = 0
	end = idx + rng
	arr1 = arr[start:end]
	return sum(arr1)*1.0/len(arr1)

def smoothenPlot(x, y, labels):
	'''
	Smoothen the plot based on the classes that the points are labelled as.
	Classes:
	1. Bump/Disturbance
	2. Minor Disturbance
	3. Turn/Disturbance
	'''
	x_data = []
	y_data = []
	for (idx,i) in enumerate(labels):
		if i == 1:
			x_data.append(smoothen(x[idx],idx,x,3))
			y_data.append(smoothen(y[idx],idx,y,3))
		elif i == 2:
			x_data.append(smoothen(x[idx],idx,x,2))
			y_data.append(smoothen(y[idx],idx,y,2))
		else:
			x_data.append(x[idx])
			y_data.append(y[idx])
	return x_data, y_data

def plot_Bumpiness(x,y):
	'''
	Plit the values of MBHx and MBHy for visual inspection.
	'''
	plt.clf()
	x = np.asarray(x)
	y = np.asarray(y)
	x_axis = range(len(x))
	plt.plot(x_axis,x)
	plt.plot(x_axis,y)
	plt.axis([0, 60, 0, 10])
	# plt.show()

if args.environ == "dep":
	'''
	Reiterate the smoothening and clustering process to get a better estimate of bumpiness during turns.
	'''
	for i in range(bach):
		X, MBHx, MBHy = loadData(x_data,y_data)
		print ("kMeans", i)
		clusters, labels, X = kMeans(X,i)
		# This saves the labels and cluster centres for the initial iteration.
		# The non-smoothed labels are used to display and catergorise situations in the demo Video.
		if i == 0:
			np.save(args.labelFile, labels)
			np.save(args.clusterFile, clusters)
			print ("cluster centres", clusters)
		plot_kMeans(X,labels)
		print("smoothen", i)
		x, y = smoothenPlot(MBHx.tolist(), MBHy.tolist(), labels)
		x_data = np.asarray(x)
		y_data = np.asarray(y)
		plot_Bumpiness(x,y)

redpajama_set_name: RedPajamaGithub


text:
package pl.softech.smpp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by ssledz on 10.12.15.
 */
@RestController
@RequestMapping(value = "/ctl")
public class SmppServerRestController {

    @Autowired
    private SmppServerSimulator serverSimulator;

    @RequestMapping(value = "/submit-sm", method = RequestMethod.POST, consumes = "application/json;charset=utf-8")
    public void submitSm(@RequestBody ShortMessage message) throws Exception {
        serverSimulator.sendMessage(message);
    }

}


text:
package com.dream.android.sample.lib.model;

import com.dream.android.sample.lib.base.BaseConstants;

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

public class Page<T> {

    private int pageSize;

    private int currentPage;

    private int totalPage;

    private int totalCount;

    private List<T> data;

    public Page() {
        currentPage = BaseConstants.INIT_PAGE;
        data = new ArrayList<>();
    }

    public Page(List<T> datas) {
        if(datas != null) {
            this.pageSize = datas.size();
            this.currentPage = 0;
            this.totalPage = 1;
            this.totalCount = datas.size();
            this.data = datas;
        }
    }

    public Page(int pageSize, int currentPage, int totalPage, int totalCount) {
        this.pageSize = pageSize;
        this.currentPage = currentPage;
        this.totalPage = totalPage;
        this.totalCount = totalCount;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public List<T> getData() {
        if(data == null) {
            return new ArrayList<>();
        } else {
            return data;
        }
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    /**
     * add page data
     * @param page data by page
     */
    public void addPage(Page<T> page) {
        this.pageSize = page.pageSize;
        this.currentPage = page.currentPage;
        this.totalPage = page.totalPage;
        this.totalCount = page.totalCount;
        if(page.getData() != null) {
            data.addAll(page.getData());
        }
    }

    public void removeData(int index) {
        if(index > 0 && index < data.size() - 1) {
            data.remove(index);
        }
    }

    public void removeData(T t) {
        data.remove(t);
    }

    /**
     * clear all datas
     */
    public void clear() {
        this.pageSize = 0;
        this.currentPage = BaseConstants.INIT_PAGE;
        this.totalPage = 0;
        this.totalCount = 0;
        data.clear();
    }

    /**
     * @return whether load more action is available or not
     */
    public boolean canLoadMore() {
        return currentPage < totalPage - 1;
    }

}


text:
@interface UIPResultViewController ()

@end

@implementation UIPResultViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated{
    self.originalImageView.image = self.originalImage;
    self.editedImageView.image = self.editedImage;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)goBack:(id)sender{
    [self.navigationController popToRootViewControllerAnimated:TRUE];
}

@end


text:
using System;
namespace CodeDocs
{

    // https://stackoverflow.com/questions/1030090/how-do-you-pass-multiple-enum-values-in-c
    // http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/22/c-fundamentals-combining-enum-values-with-bit-flags.aspx

    // https://en.wikipedia.org/wiki/List_of_software_architecture_styles_and_patterns

    // https://en.wikipedia.org/wiki/SOLID
    // https://en.wikipedia.org/wiki/Category:Programming_principles
    [Flags]
    public enum General
    {

        NotSet = 0,

        DontRepeatYourself = 1,
        LeastKnowledge = 2,

        OccamsRazor = 4,

        SeparationOfConcerns = 8,

        YouArentGonnaNeedIt = 16,
        MinimumViableProduct = 32,

        NoSideEffects = 64
    }
}


text:
.class public final Lo/Hp;
.super Lo/De;
.source ""

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "<E:Ljava/lang/Object;>Lo/De<TE;>;"
    }
.end annotation

.annotation build Lo/Ai;
    ˊ = true
    ˋ = true
.end annotation

# static fields
.field private static final ˊ:J = 0x0L
    .annotation build Lo/Aj;
        ˊ = "not needed in emulated source"
    .end annotation
.end field

# direct methods
.method private constructor <init>()V
    .locals 1

    .line 83
    new-instance v0, Ljava/util/LinkedHashMap;

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

    invoke-direct {p0, v0}, Lo/De;-><init>(Ljava/util/Map;)V

    .line 84
    return-void
.end method

.method private constructor <init>(I)V
    .locals 2

    .line 88
    new-instance v0, Ljava/util/LinkedHashMap;

    invoke-static {p1}, Lo/In;->ˋ(I)I

    move-result v1

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

    invoke-direct {p0, v0}, Lo/De;-><init>(Ljava/util/Map;)V

    .line 89
    return-void
.end method

.method private readObject(Ljava/io/ObjectInputStream;)V
    .locals 3
    .annotation build Lo/Aj;
        ˊ = "java.io.ObjectInputStream"
    .end annotation

    .line 104
    invoke-virtual {p1}, Ljava/io/ObjectInputStream;->defaultReadObject()V

    .line 105
    invoke-static {p1}, Lo/Ke;->ˊ(Ljava/io/ObjectInputStream;)I

    move-result v2

    .line 106
    new-instance v0, Ljava/util/LinkedHashMap;

    invoke-static {v2}, Lo/In;->ˋ(I)I

    move-result v1

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

    invoke-virtual {p0, v0}, Lo/Hp;->ˊ(Ljava/util/Map;)V

    .line 108
    invoke-static {p0, p1, v2}, Lo/Ke;->ˊ(Lo/Jf;Ljava/io/ObjectInputStream;I)V

    .line 109
    return-void
.end method

.method private writeObject(Ljava/io/ObjectOutputStream;)V
    .locals 0
    .annotation build Lo/Aj;
        ˊ = "java.io.ObjectOutputStream"
    .end annotation

    .line 97
    invoke-virtual {p1}, Ljava/io/ObjectOutputStream;->defaultWriteObject()V

    .line 98
    invoke-static {p0, p1}, Lo/Ke;->ˊ(Lo/Jf;Ljava/io/ObjectOutputStream;)V

    .line 99
    return-void
.end method

.method public static '()Lo/Hp;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:Ljava/lang/Object;>()Lo/Hp<TE;>;"
        }
    .end annotation

    .line 52
    new-instance v0, Lo/Hp;

    invoke-direct {v0}, Lo/Hp;-><init>()V

    return-object v0
.end method

.method public static ˊ(I)Lo/Hp;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:Ljava/lang/Object;>(I)Lo/Hp<TE;>;"
        }
    .end annotation

    .line 63
    new-instance v0, Lo/Hp;

    invoke-direct {v0, p0}, Lo/Hp;-><init>(I)V

    return-object v0
.end method

.method public static ˊ(Ljava/lang/Iterable;)Lo/Hp;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:Ljava/lang/Object;>(Ljava/lang/Iterable<+TE;>;)Lo/Hp<TE;>;"
        }
    .end annotation

    .line 76
    invoke-static {p0}, Lo/Jg;->ˊ(Ljava/lang/Iterable;)I

    move-result v0

    invoke-static {v0}, Lo/Hp;->ˊ(I)Lo/Hp;

    move-result-object v1

    .line 78
    invoke-static {v1, p0}, Lo/GE;->ˊ(Ljava/util/Collection;Ljava/lang/Iterable;)Z

    .line 79
    return-object v1
.end method

# virtual methods
.method public bridge synthetic add(Ljava/lang/Object;)Z
    .locals 1

    .line 43
    invoke-super {p0, p1}, Lo/De;->add(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic addAll(Ljava/util/Collection;)Z
    .locals 1

    .line 43
    invoke-super {p0, p1}, Lo/De;->addAll(Ljava/util/Collection;)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic clear()V
    .locals 0

    .line 43
    invoke-super {p0}, Lo/De;->clear()V

    return-void
.end method

.method public bridge synthetic contains(Ljava/lang/Object;)Z
    .locals 1

    .line 43
    invoke-super {p0, p1}, Lo/De;->contains(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic equals(Ljava/lang/Object;)Z
    .locals 1

    .line 43
    invoke-super {p0, p1}, Lo/De;->equals(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic hashCode()I
    .locals 1

    .line 43
    invoke-super {p0}, Lo/De;->hashCode()I

    move-result v0

    return v0
.end method

.method public bridge synthetic isEmpty()Z
    .locals 1

    .line 43
    invoke-super {p0}, Lo/De;->isEmpty()Z

    move-result v0

    return v0
.end method

.method public bridge synthetic iterator()Ljava/util/Iterator;
    .locals 1

    .line 43
    invoke-super {p0}, Lo/De;->iterator()Ljava/util/Iterator;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic remove(Ljava/lang/Object;)Z
    .locals 1

    .line 43
    invoke-super {p0, p1}, Lo/De;->remove(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic removeAll(Ljava/util/Collection;)Z
    .locals 1

    .line 43
    invoke-super {p0, p1}, Lo/De;->removeAll(Ljava/util/Collection;)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic retainAll(Ljava/util/Collection;)Z
    .locals 1

    .line 43
    invoke-super {p0, p1}, Lo/De;->retainAll(Ljava/util/Collection;)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic size()I
    .locals 1

    .line 43
    invoke-super {p0}, Lo/De;->size()I

    move-result v0

    return v0
.end method

.method public bridge synthetic toString()Ljava/lang/String;
    .locals 1

    .line 43
    invoke-super {p0}, Lo/De;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic ˊ(Ljava/lang/Object;)I
    .locals 1

    .line 43
    invoke-super {p0, p1}, Lo/De;->ˊ(Ljava/lang/Object;)I

    move-result v0

    return v0
.end method

.method public bridge synthetic ˊ(Ljava/lang/Object;I)I
    .locals 1

    .line 43
    invoke-super {p0, p1, p2}, Lo/De;->ˊ(Ljava/lang/Object;I)I

    move-result v0

    return v0
.end method

.method public bridge synthetic ˊ()Ljava/util/Set;
    .locals 1

    .line 43
    invoke-super {p0}, Lo/De;->ˊ()Ljava/util/Set;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic ˊ(Ljava/lang/Object;II)Z
    .locals 1

    .line 43
    invoke-super {p0, p1, p2, p3}, Lo/De;->ˊ(Ljava/lang/Object;II)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic ˋ(Ljava/lang/Object;I)I
    .locals 1

    .line 43
    invoke-super {p0, p1, p2}, Lo/De;->ˋ(Ljava/lang/Object;I)I

    move-result v0

    return v0
.end method

.method public bridge synthetic ˎ(Ljava/lang/Object;I)I
    .locals 1

    .line 43
    invoke-super {p0, p1, p2}, Lo/De;->ˎ(Ljava/lang/Object;I)I

    move-result v0

    return v0
.end method

.method public bridge synthetic ˏ()Ljava/util/Set;
    .locals 1

    .line 43
    invoke-super {p0}, Lo/De;->ˏ()Ljava/util/Set;

    move-result-object v0

    return-object v0
.end method


text:
<?php

namespace Sociedad\ReservasBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * MesasReservadasRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class MesasReservadasRepository extends EntityRepository
{
}


text:
<!DOCTYPE html>

    <title>xeogl Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">

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

creating an Mesh, then finding it by ID and modifying it


text:
namespace content {
struct NativeWebKeyboardEvent;
}

namespace extensions {

struct DraggableRegion;

// This is an interface to a native implementation of a app window, used for
// new-style packaged apps. App windows contain a web contents, but no tabs
// or URL bar.
class NativeAppWindow : public ui::BaseWindow,
                        public web_modal::WebContentsModalDialogHost {
 public:
  // Sets whether the window is fullscreen and the type of fullscreen.
  // |fullscreen_types| is a bit field of AppWindow::FullscreenType.
  virtual void SetFullscreen(int fullscreen_types) = 0;

  // Returns whether the window is fullscreen or about to enter fullscreen.
  virtual bool IsFullscreenOrPending() const = 0;

  // Called when the icon of the window changes.
  virtual void UpdateWindowIcon() = 0;

  // Called when the title of the window changes.
  virtual void UpdateWindowTitle() = 0;

  // Called when the draggable regions are changed.
  virtual void UpdateDraggableRegions(
      const std::vector<DraggableRegion>& regions) = 0;

  // Returns the region used by frameless windows for dragging. May return NULL.
  virtual SkRegion* GetDraggableRegion() = 0;

  // Called when the window shape is changed. If |region| is NULL then the
  // window is restored to the default shape.
  virtual void UpdateShape(scoped_ptr<SkRegion> region) = 0;

  // Set whether the window should receive all keyboard events including task
  // switching keys.
  virtual void SetInterceptAllKeys(bool want_all_keys) = 0;

  // Allows the window to handle unhandled keyboard messages coming back from
  // the renderer.
  virtual void HandleKeyboardEvent(
      const content::NativeWebKeyboardEvent& event) = 0;

  // Returns true if the window has no frame, as for a window opened by
  // chrome.app.window.create with the option 'frame' set to 'none'.
  virtual bool IsFrameless() const = 0;

  // Returns information about the window's frame.
  virtual bool HasFrameColor() const = 0;
  virtual SkColor ActiveFrameColor() const = 0;
  virtual SkColor InactiveFrameColor() const = 0;

  // Returns the difference between the window bounds (including titlebar and
  // borders) and the content bounds, if any.
  virtual gfx::Insets GetFrameInsets() const = 0;

  // Hide or show this window as part of hiding or showing the app.
  // This may have different logic to Hide, Show, and ShowInactive as those are
  // called via the AppWindow javascript API.
  virtual void ShowWithApp() = 0;
  virtual void HideWithApp() = 0;

  // Returns the minimum size constraints of the content.
  virtual gfx::Size GetContentMinimumSize() const = 0;

  // Returns the maximum size constraints of the content.
  virtual gfx::Size GetContentMaximumSize() const = 0;

  // Updates the minimum and maximum size constraints of the content.
  virtual void SetContentSizeConstraints(const gfx::Size& min_size,
                                         const gfx::Size& max_size) = 0;

  // Sets whether the window should be visible on all workspaces.
  virtual void SetVisibleOnAllWorkspaces(bool always_visible) = 0;

  // Returns false if the underlying native window ignores alpha transparency
  // when compositing.
  virtual bool CanHaveAlphaEnabled() const = 0;

  ~NativeAppWindow() override {}
};

}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_APP_WINDOW_NATIVE_APP_WINDOW_H_


text:
package org.onosproject.routing.impl;

import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Maps;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.packet.EthType;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onlab.packet.VlanId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.incubator.net.intf.Interface;
import org.onosproject.incubator.net.intf.InterfaceService;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Host;
import org.onosproject.net.PortNumber;
import org.onosproject.net.config.NetworkConfigEvent;
import org.onosproject.net.config.NetworkConfigListener;
import org.onosproject.net.config.NetworkConfigService;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flowobjective.DefaultForwardingObjective;
import org.onosproject.net.flowobjective.DefaultNextObjective;
import org.onosproject.net.flowobjective.FlowObjectiveService;
import org.onosproject.net.flowobjective.ForwardingObjective;
import org.onosproject.net.flowobjective.NextObjective;
import org.onosproject.net.host.HostEvent;
import org.onosproject.net.host.HostListener;
import org.onosproject.net.host.HostService;
import org.onosproject.net.host.InterfaceIpAddress;
import org.onosproject.routing.RoutingService;
import org.onosproject.routing.config.RouterConfig;
import org.slf4j.Logger;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static org.slf4j.LoggerFactory.getLogger;
import static com.google.common.base.Preconditions.checkState;

/**
 * Manages connectivity between peers redirecting control traffic to a routing
 * control plane available on the dataplane.
 */
@Component(immediate = true, enabled = false)
public class ControlPlaneRedirectManager {

    private final Logger log = getLogger(getClass());

    private static final int MIN_IP_PRIORITY = 10;
    private static final int ACL_PRIORITY = 40001;
    private static final int OSPF_IP_PROTO = 0x59;

    private static final String APP_NAME = "org.onosproject.cpredirect";
    private ApplicationId appId;

    private ConnectPoint controlPlaneConnectPoint;
    private boolean ospfEnabled = false;
    private List<String> interfaces = Collections.emptyList();
    private Map<Host, Set<Integer>> peerNextId = Maps.newConcurrentMap();

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected CoreService coreService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected DeviceService deviceService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected InterfaceService interfaceService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected FlowObjectiveService flowObjectiveService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected NetworkConfigService networkConfigService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected MastershipService mastershipService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    protected HostService hostService;

    private final InternalDeviceListener deviceListener = new InternalDeviceListener();
    private final InternalNetworkConfigListener networkConfigListener =
            new InternalNetworkConfigListener();
    private final InternalHostListener hostListener = new InternalHostListener();

    @Activate
    public void activate() {
        this.appId = coreService.registerApplication(APP_NAME);

        deviceService.addListener(deviceListener);
        networkConfigService.addListener(networkConfigListener);
        hostService.addListener(hostListener);

        updateConfig();
    }

    @Deactivate
    public void deactivate() {
        deviceService.removeListener(deviceListener);
        networkConfigService.removeListener(networkConfigListener);
        hostService.removeListener(hostListener);
    }

    private void updateConfig() {
        ApplicationId routingAppId =
                coreService.registerApplication(RoutingService.ROUTER_APP_ID);

        RouterConfig config = networkConfigService.getConfig(
                routingAppId, RoutingService.ROUTER_CONFIG_CLASS);

        if (config == null) {
            log.warn("Router config not available");
            return;
        }

        controlPlaneConnectPoint = config.getControlPlaneConnectPoint();
        ospfEnabled = config.getOspfEnabled();
        interfaces = config.getInterfaces();

        updateDevice();
    }

    private void updateDevice() {
        if (controlPlaneConnectPoint != null &&
                deviceService.isAvailable(controlPlaneConnectPoint.deviceId())) {
            DeviceId deviceId = controlPlaneConnectPoint.deviceId();

            interfaceService.getInterfaces().stream()
                    .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
                    .filter(intf -> interfaces.isEmpty() || interfaces.contains(intf.name()))
                    .forEach(this::provisionInterface);

            log.info("Set up interfaces on {}", controlPlaneConnectPoint.deviceId());
        }
    }

    private void provisionInterface(Interface intf) {
        addBasicInterfaceForwarding(intf);
        updateOspfForwarding(intf);
    }

    private void addBasicInterfaceForwarding(Interface intf) {
        log.debug("Adding interface objectives for {}", intf);

        DeviceId deviceId = controlPlaneConnectPoint.deviceId();
        PortNumber controlPlanePort = controlPlaneConnectPoint.port();

        for (InterfaceIpAddress ip : intf.ipAddresses()) {
            // create nextObjectives for forwarding to this interface and the
            // controlPlaneConnectPoint
            int cpNextId, intfNextId;
            if (intf.vlan() == VlanId.NONE) {
                cpNextId = createNextObjective(deviceId, controlPlanePort,
                               VlanId.vlanId(SingleSwitchFibInstaller.ASSIGNED_VLAN),
                               true);
                intfNextId = createNextObjective(deviceId, intf.connectPoint().port(),
                               VlanId.vlanId(SingleSwitchFibInstaller.ASSIGNED_VLAN),
                               true);
            } else {
                cpNextId = createNextObjective(deviceId, controlPlanePort,
                                               intf.vlan(), false);
                intfNextId = createNextObjective(deviceId, intf.connectPoint().port(),
                                                 intf.vlan(), false);
            }

            // IPv4 to router
            TrafficSelector toSelector = DefaultTrafficSelector.builder()
                    .matchInPort(intf.connectPoint().port())
                    .matchEthDst(intf.mac())
                    .matchEthType(EthType.EtherType.IPV4.ethType().toShort())
                    .matchVlanId(intf.vlan())
                    .matchIPDst(ip.ipAddress().toIpPrefix())
                    .build();

            flowObjectiveService.forward(deviceId,
                    buildForwardingObjective(toSelector, null, cpNextId, true));

            // IPv4 from router
            TrafficSelector fromSelector = DefaultTrafficSelector.builder()
                    .matchInPort(controlPlanePort)
                    .matchEthSrc(intf.mac())
                    .matchVlanId(intf.vlan())
                    .matchEthType(EthType.EtherType.IPV4.ethType().toShort())
                    .matchIPSrc(ip.ipAddress().toIpPrefix())
                    .build();

            flowObjectiveService.forward(deviceId,
                    buildForwardingObjective(fromSelector, null, intfNextId, true));

            // ARP to router
            toSelector = DefaultTrafficSelector.builder()
                    .matchInPort(intf.connectPoint().port())
                    .matchEthType(EthType.EtherType.ARP.ethType().toShort())
                    .matchVlanId(intf.vlan())
                    .build();

            TrafficTreatment puntTreatment = DefaultTrafficTreatment.builder()
                    .punt()
                    .build();

            flowObjectiveService.forward(deviceId,
                    buildForwardingObjective(toSelector, puntTreatment, cpNextId, true));

            // ARP from router
            fromSelector = DefaultTrafficSelector.builder()
                    .matchInPort(controlPlanePort)
                    .matchEthSrc(intf.mac())
                    .matchVlanId(intf.vlan())
                    .matchEthType(EthType.EtherType.ARP.ethType().toShort())
                    .matchArpSpa(ip.ipAddress().getIp4Address())
                    .build();

            flowObjectiveService.forward(deviceId,
            buildForwardingObjective(fromSelector, puntTreatment, intfNextId, true));
        }
    }

    private void updateOspfForwarding(Interface intf) {
        // OSPF to router
        TrafficSelector toSelector = DefaultTrafficSelector.builder()
                .matchInPort(intf.connectPoint().port())
                .matchEthType(EthType.EtherType.IPV4.ethType().toShort())
                .matchVlanId(intf.vlan())
                .matchIPProtocol((byte) OSPF_IP_PROTO)
                .build();

        // create nextObjectives for forwarding to the controlPlaneConnectPoint
        DeviceId deviceId = controlPlaneConnectPoint.deviceId();
        PortNumber controlPlanePort = controlPlaneConnectPoint.port();
        int cpNextId;
        if (intf.vlan() == VlanId.NONE) {
            cpNextId = createNextObjective(deviceId, controlPlanePort,
                           VlanId.vlanId(SingleSwitchFibInstaller.ASSIGNED_VLAN),
                           true);
        } else {
            cpNextId = createNextObjective(deviceId, controlPlanePort,
                                           intf.vlan(), false);
        }
        log.debug("ospf flows intf:{} nextid:{}", intf, cpNextId);
        flowObjectiveService.forward(controlPlaneConnectPoint.deviceId(),
                buildForwardingObjective(toSelector, null, cpNextId, ospfEnabled));
    }

    /**
     * Creates a next objective for forwarding to a port. Handles metadata for
     * some pipelines that require vlan information for egress port.
     *
     * @param deviceId the device on which the next objective is being created
     * @param portNumber the egress port
     * @param vlanId vlan information for egress port
     * @param popVlan if vlan tag should be popped or not
     * @return nextId of the next objective created
     */
    private int createNextObjective(DeviceId deviceId, PortNumber portNumber,
                                    VlanId vlanId, boolean popVlan) {
        int nextId = flowObjectiveService.allocateNextId();
        NextObjective.Builder nextObjBuilder = DefaultNextObjective
                .builder().withId(nextId)
                .withType(NextObjective.Type.SIMPLE)
                .fromApp(appId);

        TrafficTreatment.Builder ttBuilder = DefaultTrafficTreatment.builder();
        if (popVlan) {
            ttBuilder.popVlan();
        }
        ttBuilder.setOutput(portNumber);

        // setup metadata to pass to nextObjective - indicate the vlan on egress
        // if needed by the switch pipeline.
        TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
        metabuilder.matchVlanId(vlanId);

        nextObjBuilder.withMeta(metabuilder.build());
        nextObjBuilder.addTreatment(ttBuilder.build());
        log.debug("Submited next objective {} in device {} for port/vlan {}/{}",
                nextId, deviceId, portNumber, vlanId);
        flowObjectiveService.next(deviceId, nextObjBuilder.add());
        return nextId;
    }

    /**
     * Builds a forwarding objective from the given selector, treatment and nextId.
     *
     * @param selector selector
     * @param treatment treatment to apply to packet, can be null
     * @param nextId next objective to point to for forwarding packet
     * @param add true to create an add objective, false to create a remove
     *            objective
     * @return forwarding objective
     */
    private ForwardingObjective buildForwardingObjective(TrafficSelector selector,
                                                         TrafficTreatment treatment,
                                                         int nextId,
                                                         boolean add) {
        DefaultForwardingObjective.Builder fobBuilder = DefaultForwardingObjective.builder();
        fobBuilder.withSelector(selector);
        if (treatment != null) {
            fobBuilder.withTreatment(treatment);
        }
        if (nextId != -1) {
            fobBuilder.nextStep(nextId);
        }
        fobBuilder.fromApp(appId)
            .withPriority(ACL_PRIORITY)
            .withFlag(ForwardingObjective.Flag.VERSATILE);

        return add ? fobBuilder.add() : fobBuilder.remove();
    }

    /**
     * Listener for device events.
     */
    private class InternalDeviceListener implements DeviceListener {
        @Override
        public void event(DeviceEvent event) {
            if (controlPlaneConnectPoint != null &&
                    event.subject().id().equals(controlPlaneConnectPoint.deviceId())) {
                switch (event.type()) {
                case DEVICE_ADDED:
                case DEVICE_AVAILABILITY_CHANGED:
                    if (deviceService.isAvailable(event.subject().id())) {
                        log.info("Device connected {}", event.subject().id());
                        updateDevice();
                    }

                    break;
                case DEVICE_UPDATED:
                case DEVICE_REMOVED:
                case DEVICE_SUSPENDED:
                case PORT_ADDED:
                case PORT_UPDATED:
                case PORT_REMOVED:
                default:
                    break;
                }
            }
        }
    }

    /**
     * Listener for network config events.
     */
    private class InternalNetworkConfigListener implements NetworkConfigListener {
        @Override
        public void event(NetworkConfigEvent event) {
            if (event.configClass().equals(RoutingService.ROUTER_CONFIG_CLASS)) {
                switch (event.type()) {
                case CONFIG_ADDED:
                case CONFIG_UPDATED:
                    updateConfig();
                    break;
                case CONFIG_REGISTERED:
                case CONFIG_UNREGISTERED:
                case CONFIG_REMOVED:
                default:
                    break;
                }
            }
        }
    }

    /**
     * Listener for host events.
     */
    private class InternalHostListener implements HostListener {
        private void peerAdded(HostEvent event) {
            Host peer = event.subject();
            Optional<Interface> peerIntf =
                    interfaceService.getInterfacesByPort(peer.location()).stream()
                    .filter(intf -> interfaces.isEmpty() || interfaces.contains(intf.name()))
                    .filter(intf -> peer.vlan().equals(intf.vlan()))
                    .findFirst();
            if (!peerIntf.isPresent()) {
                log.debug("Adding peer {}/{} on {} but the interface is not configured",
                        peer.mac(), peer.vlan(), peer.location());
                return;
            }

            // Generate L3 Unicast groups and store it in the map
            int toRouterL3Unicast = createPeerGroup(peer.mac(), peerIntf.get().mac(),
                    peer.vlan(), peer.location().deviceId(), controlPlaneConnectPoint.port());
            int toPeerL3Unicast = createPeerGroup(peerIntf.get().mac(), peer.mac(),
                    peer.vlan(), peer.location().deviceId(), peer.location().port());
            peerNextId.put(peer, ImmutableSortedSet.of(toRouterL3Unicast, toPeerL3Unicast));

            // From peer to router
            peerIntf.get().ipAddresses().forEach(routerIp -> {
                flowObjectiveService.forward(peer.location().deviceId(),
                        createPeerObjBuilder(toRouterL3Unicast, routerIp.ipAddress().toIpPrefix()).add());
            });

            // From router to peer
            peer.ipAddresses().forEach(peerIp -> {
                flowObjectiveService.forward(peer.location().deviceId(),
                        createPeerObjBuilder(toPeerL3Unicast, peerIp.toIpPrefix()).add());
            });
        }

        private void peerRemoved(HostEvent event) {
            Host peer = event.subject();
            Optional<Interface> peerIntf =
                    interfaceService.getInterfacesByPort(peer.location()).stream()
                            .filter(intf -> interfaces.isEmpty() || interfaces.contains(intf.name()))
                            .filter(intf -> peer.vlan().equals(intf.vlan()))
                            .findFirst();
            if (!peerIntf.isPresent()) {
                log.debug("Removing peer {}/{} on {} but the interface is not configured",
                        peer.mac(), peer.vlan(), peer.location());
                return;
            }

            Set<Integer> nextIds = peerNextId.get(peer);
            checkState(peerNextId.get(peer) != null,
                    "Peer nextId should not be null");
            checkState(peerNextId.get(peer).size() == 2,
                    "Wrong nextId associated with the peer");
            Iterator<Integer> iter = peerNextId.get(peer).iterator();
            int toRouterL3Unicast = iter.next();
            int toPeerL3Unicast = iter.next();

            // From peer to router
            peerIntf.get().ipAddresses().forEach(routerIp -> {
                flowObjectiveService.forward(peer.location().deviceId(),
                        createPeerObjBuilder(toRouterL3Unicast, routerIp.ipAddress().toIpPrefix()).remove());
            });

            // From router to peer
            peer.ipAddresses().forEach(peerIp -> {
                flowObjectiveService.forward(peer.location().deviceId(),
                        createPeerObjBuilder(toPeerL3Unicast, peerIp.toIpPrefix()).remove());
            });
        }

        private ForwardingObjective.Builder createPeerObjBuilder(
                int nextId, IpPrefix ipAddresses) {
            TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
            sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
            sbuilder.matchIPDst(ipAddresses);
            DefaultForwardingObjective.Builder builder =
                    DefaultForwardingObjective.builder()
                    .withSelector(sbuilder.build())
                    .fromApp(appId)
                    .withPriority(getPriorityFromPrefix(ipAddresses))
                    .withFlag(ForwardingObjective.Flag.SPECIFIC);
            if (nextId != -1) {
                builder.nextStep(nextId);
            }
            return builder;
        }

        private int createPeerGroup(MacAddress srcMac, MacAddress dstMac,
                VlanId vlanId, DeviceId deviceId, PortNumber port) {
            int nextId = flowObjectiveService.allocateNextId();
            NextObjective.Builder nextObjBuilder = DefaultNextObjective.builder()
                    .withId(nextId)
                    .withType(NextObjective.Type.SIMPLE)
                    .fromApp(appId);

            TrafficTreatment.Builder ttBuilder = DefaultTrafficTreatment.builder();
            ttBuilder.setEthSrc(srcMac);
            ttBuilder.setEthDst(dstMac);
            ttBuilder.setOutput(port);
            nextObjBuilder.addTreatment(ttBuilder.build());

            TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder();
            VlanId matchVlanId = (vlanId.equals(VlanId.NONE)) ?
                    VlanId.vlanId(SingleSwitchFibInstaller.ASSIGNED_VLAN) :
                    vlanId;
            metabuilder.matchVlanId(matchVlanId);
            nextObjBuilder.withMeta(metabuilder.build());

            flowObjectiveService.next(deviceId, nextObjBuilder.add());
            return nextId;
        }

        @Override
        public void event(HostEvent event) {
            DeviceId deviceId = event.subject().location().deviceId();
            if (!mastershipService.isLocalMaster(deviceId)) {
                return;
            }
            switch (event.type()) {
                case HOST_ADDED:
                    peerAdded(event);
                    break;
                case HOST_MOVED:
                    //TODO We assume BGP peer does not move for now
                    break;
                case HOST_REMOVED:
                    peerRemoved(event);
                    break;
                case HOST_UPDATED:
                    //TODO We assume BGP peer does not change IP for now
                    break;
                default:
                    break;
            }
        }
    }

    private int getPriorityFromPrefix(IpPrefix prefix) {
        return (prefix.isIp4()) ?
                2000 * prefix.prefixLength() + MIN_IP_PRIORITY :
                500 * prefix.prefixLength() + MIN_IP_PRIORITY;
    }
}


text:
{-# LANGUAGE BangPatterns #-}
module Kafka.Consumer.Callbacks
( rebalanceCallback
, offsetCommitCallback
, module X
)
where

import Control.Arrow          ((&&&))
import Control.Monad          (forM_, void)
import Foreign.ForeignPtr     (newForeignPtr_)
import Foreign.Ptr            (nullPtr)
import Kafka.Callbacks        as X
import Kafka.Consumer.Convert (fromNativeTopicPartitionList', fromNativeTopicPartitionList'')
import Kafka.Consumer.Types   (KafkaConsumer (..), RebalanceEvent (..), TopicPartition (..))
import Kafka.Internal.RdKafka
import Kafka.Internal.Setup   (HasKafka (..), HasKafkaConf (..), Kafka (..), KafkaConf (..), getRdMsgQueue, Callback (..))
import Kafka.Types            (KafkaError (..), PartitionId (..), TopicName (..))

import qualified Data.Text as Text

-- | Sets a callback that is called when rebalance is needed.
rebalanceCallback :: (KafkaConsumer -> RebalanceEvent -> IO ()) -> Callback
rebalanceCallback callback =
  Callback $ \kc@(KafkaConf con _ _) -> rdKafkaConfSetRebalanceCb con (realCb kc)
  where
    realCb kc k err pl = do
      k' <- newForeignPtr_ k
      pls <- newForeignPtr_ pl
      setRebalanceCallback callback (KafkaConsumer (Kafka k') kc) (KafkaResponseError err) pls

-- | Sets a callback that is called when rebalance is needed.
--
-- The results of automatic or manual offset commits will be scheduled
-- for this callback and is served by 'Kafka.Consumer.pollMessage'.
--
-- If no partitions had valid offsets to commit this callback will be called
-- with 'KafkaResponseError' 'RdKafkaRespErrNoOffset' which is not to be considered
-- an error.
offsetCommitCallback :: (KafkaConsumer -> KafkaError -> [TopicPartition] -> IO ()) -> Callback
offsetCommitCallback callback =
  Callback $ \kc@(KafkaConf conf _ _) -> rdKafkaConfSetOffsetCommitCb conf (realCb kc)
  where
    realCb kc k err pl = do
      k' <- newForeignPtr_ k
      pls <- fromNativeTopicPartitionList' pl
      callback (KafkaConsumer (Kafka k') kc) (KafkaResponseError err) pls

-------------------------------------------------------------------------------
redirectPartitionQueue :: Kafka -> TopicName -> PartitionId -> RdKafkaQueueTPtr -> IO ()
redirectPartitionQueue (Kafka k) (TopicName t) (PartitionId p) q = do
  mpq <- rdKafkaQueueGetPartition k (Text.unpack t) p
  case mpq of
    Nothing -> return ()
    Just pq -> rdKafkaQueueForward pq q

setRebalanceCallback :: (KafkaConsumer -> RebalanceEvent -> IO ())
                          -> KafkaConsumer
                          -> KafkaError
                          -> RdKafkaTopicPartitionListTPtr -> IO ()
setRebalanceCallback f k e pls = do
  ps <- fromNativeTopicPartitionList'' pls
  let assignment = (tpTopicName &&& tpPartition) <$> ps
  let (Kafka kptr) = getKafka k

  case e of
    KafkaResponseError RdKafkaRespErrAssignPartitions -> do
        f k (RebalanceBeforeAssign assignment)
        void $ rdKafkaAssign kptr pls

        mbq <- getRdMsgQueue $ getKafkaConf k
        case mbq of
          Nothing -> pure ()
          Just mq -> do
            {- Magnus Edenhill:
                If you redirect after assign() it means some messages may be forwarded to the single consumer queue,
                so either do it before assign() or do: assign(); pause(); redirect; resume()
            -}
            void $ rdKafkaPausePartitions kptr pls
            forM_ ps (\tp -> redirectPartitionQueue (getKafka k) (tpTopicName tp) (tpPartition tp) mq)
            void $ rdKafkaResumePartitions kptr pls

        f k (RebalanceAssign assignment)

    KafkaResponseError RdKafkaRespErrRevokePartitions -> do
        f k (RebalanceBeforeRevoke assignment)
        void $ newForeignPtr_ nullPtr >>= rdKafkaAssign kptr
        f k (RebalanceRevoke assignment)
    x -> error $ "Rebalance: UNKNOWN response: " <> show x


text:
package gc

import (
	"os"
	"runtime"
	"runtime/pprof"
)

// Line returns n's position as a string. If n has been inlined,
// it uses the outermost position where n has been inlined.
func (n *Node) Line() string {
	return linestr(n.Pos)
}

var atExitFuncs []func()

func atExit(f func()) {
	atExitFuncs = append(atExitFuncs, f)
}

func Exit(code int) {
	for i := len(atExitFuncs) - 1; i >= 0; i-- {
		f := atExitFuncs[i]
		atExitFuncs = atExitFuncs[:i]
		f()
	}
	os.Exit(code)
}

var (
	cpuprofile     string
	memprofile     string
	memprofilerate int64
	traceprofile   string
	traceHandler   func(string)
)

func startProfile() {
	if cpuprofile != "" {
		f, err := os.Create(cpuprofile)
		if err != nil {
			Fatalf("%v", err)
		}
		if err := pprof.StartCPUProfile(f); err != nil {
			Fatalf("%v", err)
		}
		atExit(pprof.StopCPUProfile)
	}
	if memprofile != "" {
		if memprofilerate != 0 {
			runtime.MemProfileRate = int(memprofilerate)
		}
		f, err := os.Create(memprofile)
		if err != nil {
			Fatalf("%v", err)
		}
		atExit(func() {
			// Profile all outstanding allocations.
			runtime.GC()
			// compilebench parses the memory profile to extract memstats,
			// which are only written in the legacy pprof format.
			// See golang.org/issue/18641 and runtime/pprof/pprof.go:writeHeap.
			const writeLegacyFormat = 1
			if err := pprof.Lookup("heap").WriteTo(f, writeLegacyFormat); err != nil {
				Fatalf("%v", err)
			}
		})
	} else {
		// Not doing memory profiling; disable it entirely.
		runtime.MemProfileRate = 0
	}
	if traceprofile != "" && traceHandler != nil {
		traceHandler(traceprofile)
	}
}


text:
package models

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"time"
)

// Stopwatch represents a stopwatch for time tracking.
type Stopwatch struct {
	ID          int64     `xorm:"pk autoincr"`
	IssueID     int64     `xorm:"INDEX"`
	UserID      int64     `xorm:"INDEX"`
	Created     time.Time `xorm:"-"`
	CreatedUnix int64
}

// AfterSet is invoked from XORM after setting the value of a field of this object.
func (s *Stopwatch) AfterSet(colName string, _ xorm.Cell) {

	switch colName {

	case "created_unix":
		s.Created = time.Unix(s.CreatedUnix, 0).Local()
	}
}

// GetStopwatchByID returns the stopwatch by given ID.
func GetStopwatchByID(id int64) (*Stopwatch, error) {
	c := new(Stopwatch)
	has, err := x.Id(id).Get(c)
	if err != nil {
		return nil, err
	} else if !has {
		return nil, ErrStopwatchNotExist{id}
	}
	return c, nil
}

func getStopwatch(e Engine, userID, issueID int64) (sw *Stopwatch, exists bool, err error) {
	sw = new(Stopwatch)
	exists, err = e.
		Where("user_id = ?", userID).
		And("issue_id = ?", issueID).
		Get(sw)
	return
}

// StopwatchExists returns true if the stopwatch exists
func StopwatchExists(userID int64, issueID int64) bool {
	_, exists, _ := getStopwatch(x, userID, issueID)
	return exists
}

// CreateOrStopIssueStopwatch will create or remove a stopwatch and will log it into issue's timeline.
func CreateOrStopIssueStopwatch(userID int64, issueID int64) error {
	sw, exists, err := getStopwatch(x, userID, issueID)
	if err != nil {
		return err
	}

	if exists {
		// Create tracked time out of the time difference between start date and actual date
		timediff := time.Now().Unix() - sw.CreatedUnix

		// Create TrackedTime
		tt := &TrackedTime{
			Created: time.Now(),
			IssueID: issueID,
			UserID:  userID,
			Time:    timediff,
		}

		if _, err := x.Insert(tt); err != nil {
			return err
		}
		// Add comment referencing to the tracked time
		comment := &Comment{
			IssueID:  issueID,
			PosterID: userID,
			Type:     CommentTypeStopTracking,
			Content:  secToTime(timediff),
		}

		if _, err := x.Insert(comment); err != nil {
			return err
		}

		if _, err := x.Delete(sw); err != nil {
			return err
		}
	} else {
		// Create stopwatch
		sw = &Stopwatch{
			UserID:  userID,
			IssueID: issueID,
			Created: time.Now(),
		}

		if _, err := x.Insert(sw); err != nil {
			return err
		}

		// Add comment referencing to the stopwatch
		comment := &Comment{
			IssueID:  issueID,
			PosterID: userID,
			Type:     CommentTypeStartTracking,
		}

		if _, err := x.Insert(comment); err != nil {
			return err
		}
	}
	return nil
}

// CancelStopwatch removes the given stopwatch and logs it into issue's timeline.
func CancelStopwatch(userID int64, issueID int64) error {
	sw, exists, err := getStopwatch(x, userID, issueID)
	if err != nil {
		return err
	}

	if exists {
		if _, err := x.Delete(sw); err != nil {
			return err
		}
		comment := &Comment{
			PosterID: userID,
			IssueID:  issueID,
			Type:     CommentTypeCancelTracking,
		}

		if _, err := x.Insert(comment); err != nil {
			return err
		}
	}
	return nil
}

func secToTime(duration int64) string {
	seconds := duration % 60
	minutes := (duration / (60)) % 60
	hours := duration / (60 * 60)

	var hrs string

	if hours > 0 {
		hrs = fmt.Sprintf("%dh", hours)
	}
	if minutes > 0 {
		if hours == 0 {
			hrs = fmt.Sprintf("%dmin", minutes)
		} else {
			hrs = fmt.Sprintf("%s %dmin", hrs, minutes)
		}
	}
	if seconds > 0 {
		if hours == 0 && minutes == 0 {
			hrs = fmt.Sprintf("%ds", seconds)
		} else {
			hrs = fmt.Sprintf("%s %ds", hrs, seconds)
		}
	}

	return hrs
}

// BeforeInsert will be invoked by XORM before inserting a record
// representing this object.
func (s *Stopwatch) BeforeInsert() {
	s.CreatedUnix = time.Now().Unix()
}


text:
body
{
  font-family: 'Arial';
  margin: 0px;
  padding: 0px;
}

article
{
  margin-left: auto;
  margin-right: auto;
  width: 640px;
}

header
{
  text-align: center;
  padding-left: 20px;
  padding-right: 20px;
}

small
{
  font-weight: normal;
}

#playground
{
  width: 640px;
  height: 480px;
}

#playgroundTop
{
  height: 54px;
  font-weight: bold;
}

#borderTop
{
  width: 580px;
  height: 54px;
  padding-top: 25px;
  padding-left: 30px;
  padding-right: 30px;
  color: white;
  font-size: 18px;
  text-align: center;
  line-height: 5px;
  background-image: url('ui/images/frame-top.png');
  background-size: contain;
}

#playgroundMiddle
{
  height: 406px;
}

#borderLeft
{
  float: left;
  width: 20px;
  height: 406px;
  background-image: url('ui/images/frame-left.png');
  background-size: contain;
}

#screen
{
  float: left;
  background-color: black;
}

#borderRight
{
  float: left;
  width: 20px;
  height: 406px;
  background-image: url('ui/images/frame-right.png');
  background-size: contain;
}

#playgroundBottom
{
  height: 20px;
  clear: both;
}

#borderBottom
{
  width: 640px;
  height: 20px;
  background-image: url('ui/images/frame-bottom.png');
  background-size: contain;
}

footer
{
  padding-top: 20px;
  padding-bottom: 20px;
}


text:
from hashlib import md5
from urllib.parse import urlparse
from . import util
import re

DEFAULT_PORT_MAP = {'http': 80, 'https': 443, 'ws': 80, 'wss': 443}
NON_IP_COMPONENT = re.compile ("[^.0-9]")

def sort_args (data):
	args = {}
	for arg in data.split ("&"):
		try: k, v = arg.split ("=")
		except: continue
		if v:
			args [k] = v
	args = list(args.items ())
	args.sort ()
	argslist = []
	for k, v in args:
		argslist.append ("%s=%s" % (k, v))
	argslist.sort ()
	return "&".join (argslist)

def parse_address (scheme, address):
	try:
		host, port = address.split (":", 1)
		port = int (port)
	except ValueError:
		host = address
		if scheme in ("http", "ws"):
			port = 80
		else:
			port = 443
	return host, port

def uuid (uri, method = "get", data = "", include_data = True):
	# url id
	if uri.find ("://") == -1:
		return None
	method = method.lower ()
	scheme, address, script, params, qs, fragment = urlparse (uri)

	if not script:
		script = "/"
	host, port = parse_address (scheme, address)
	sig = [
		method,
		host.startswith ("www.") and host [4:] or host,
		str (port),
		script
	]
	if include_data:
		sig.append (params)
	if qs:
		sig.append (sort_args (qs))
	if data:
		sig.append (sort_args (data))
	return md5 (":".join (sig).encode ("utf8")).hexdigest ()

def usid (uri, method = "get"):
	# script id
	return make_uuid (uri, method, "", False)

def uinf (url):
	return UrlInfo (url)

class UrlInfo:
	def __init__ (self, url):
		self.url = url
		self._parse ()

	def _parse (self):
		url = self.url
		self.scheme, self.netloc, self.script, self.params, self.querystring, self.fragment = urlparse (url)

		if not self.script:
			self.script = '/'
		if self.querystring:
			try: self.querystring = util.strencode (self.querystring)
			except: pass

		uri = self.script #real request uri
		if self.params:
			uri += ';' + self.params
		if self.querystring:
			uri += '?' + self.querystring
		self.uri = uri

		position = self.netloc.find('@')
		if position > -1:
			self.auth, self.netloc = self.netloc.split ("@", 1)
			try:
				self.username, self.password = self.auth.split (':', 1)
			except ValueError:
				pass
			else:
				self.auth = (self.username, self.password)

		try:
			self.netloc, self.port = self.netloc.split (':', 1)
		except ValueError:
			try:
				self.netloc, self.port = self.netloc, DEFAULT_PORT_MAP [self.scheme]
			except KeyError:
				self.netloc, self.port = self.netloc, 80

		self.netloc = self.netloc.lower ()
		try: self.port = int (self.port)
		except: self.port = 80

		if DEFAULT_PORT_MAP [self.scheme] == self.port:
			self.rfc = '%s://%s%s' % (self.scheme, self.netloc, self.uri)
		else:
			self.rfc = '%s://%s:%d%s' % (self.scheme, self.netloc, self.port, self.uri)

		self.host = None
		self.domain = None
		self.subdomain = None
		self.topdomain = None

		if NON_IP_COMPONENT.search (self.netloc):
			netloc = self.netloc
			netloc2 = netloc.split (".")
			self.topdomain = netloc2 [-1]

			if len (netloc2) == 1:
				self.host = ""
				self.domain = netloc
				self.subdomain = netloc
			elif len (netloc2) == 2:
				self.host = ""
				self.domain = netloc
				self.subdomain = netloc2 [0]
			elif len (netloc2 [-1]) >= 3:
				self.domain = ".".join (netloc2 [-2:])
				self.host = ".".join (netloc2 [:-2])
				self.subdomain = netloc2 [-2]
				if not self.host:
					self.host = "www"
			elif len (netloc2 [-1]) == 2:
				if len (netloc2) == 2:
					self.domain = ".".join (netloc2)
					self.subdomain = netloc2 [0]
					self.host = "www"
				elif len (netloc2) == 3:
					if netloc2 [0] == "www":
						self.domain = ".".join (netloc2 [-2:])
						self.subdomain = netloc2 [-2]
					else:
						self.domain = ".".join (netloc2)
						self.subdomain = netloc2 [0]
					self.host = "www"
				else:
					self.domain = ".".join (netloc2 [-3:])
					self.host = ".".join (netloc2 [:-3])
					self.subdomain = netloc2 [-3]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RPM.ApiResults
{
    class ProcResult
    {
        public string Process { get; set; }
        public int ProcessID { get; set; }
        public bool Enabled { get; set; }
        public DateTime Added { get; set; }
        public DateTime Modified { get; set; }
        public int Forms { get; set; }
        public int Archived { get; set; }
        public int Fields { get; set; }
    }
}


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

import com.facebook.presto.Session;
import com.facebook.presto.execution.QueryInfo;
import com.facebook.presto.execution.TaskInfo;
import com.facebook.presto.operator.DriverStats;
import com.facebook.presto.server.testing.TestingPrestoServer;
import com.facebook.presto.testing.QueryRunner;
import com.facebook.presto.tests.DistributedQueryRunner;
import com.facebook.presto.tpch.TpchPlugin;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import static com.facebook.presto.execution.QueryState.FINISHED;
import static com.facebook.presto.execution.StageInfo.getAllStages;
import static com.facebook.presto.memory.LocalMemoryManager.GENERAL_POOL;
import static com.facebook.presto.memory.LocalMemoryManager.RESERVED_POOL;
import static com.facebook.presto.memory.LocalMemoryManager.SYSTEM_POOL;
import static com.facebook.presto.operator.BlockedReason.WAITING_FOR_MEMORY;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

@Test(singleThreaded = true)
public class TestMemoryManager
{
    private static final Session SESSION = testSessionBuilder()
            .setCatalog("tpch")
            // Use sf1000 to make sure this takes at least one second, so that the memory manager will fail the query
            .setSchema("sf1000")
            .build();

    private static final Session TINY_SESSION = testSessionBuilder()
            .setCatalog("tpch")
            .setSchema("tiny")
            .build();

    private final ExecutorService executor = newCachedThreadPool();

    @Test(timeOut = 240_000)
    public void testClusterPools()
            throws Exception
    {
        Map<String, String> properties = ImmutableMap.<String, String>builder()
                .put("task.verbose-stats", "true")
                .put("task.operator-pre-allocated-memory", "0B")
                .build();

        try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) {
            // Reserve all the memory
            for (TestingPrestoServer server : queryRunner.getServers()) {
                for (MemoryPool pool : server.getLocalMemoryManager().getPools()) {
                    assertTrue(pool.tryReserve(pool.getMaxBytes()));
                }
            }

            List<Future<?>> queryFutures = new ArrayList<>();
            for (int i = 0; i < 2; i++) {
                queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk")));
            }

            ClusterMemoryManager memoryManager = queryRunner.getCoordinator().getClusterMemoryManager();
            ClusterMemoryPool reservedPool;
            while ((reservedPool = memoryManager.getPools().get(RESERVED_POOL)) == null) {
                MILLISECONDS.sleep(10);
            }

            ClusterMemoryPool generalPool = memoryManager.getPools().get(GENERAL_POOL);
            assertNotNull(generalPool);

            // Wait for the queries to start running and get assigned to the expected pools
            while (generalPool.getQueries() != 1 || reservedPool.getQueries() != 1 || generalPool.getBlockedNodes() != 2 || reservedPool.getBlockedNodes() != 2) {
                MILLISECONDS.sleep(10);
            }

            // Make sure the queries are blocked
            List<QueryInfo> currentQueryInfos = queryRunner.getCoordinator().getQueryManager().getAllQueryInfo();
            for (QueryInfo info : currentQueryInfos) {
                assertFalse(info.getState().isDone());
            }
            assertEquals(currentQueryInfos.size(), 2);
            // Check that the pool information propagated to the query objects
            assertNotEquals(currentQueryInfos.get(0).getMemoryPool(), currentQueryInfos.get(1).getMemoryPool());

            while (!allQueriesBlocked(currentQueryInfos)) {
                MILLISECONDS.sleep(10);
                currentQueryInfos = queryRunner.getCoordinator().getQueryManager().getAllQueryInfo();
                for (QueryInfo info : currentQueryInfos) {
                    assertFalse(info.getState().isDone());
                }
            }

            // Release the memory in the reserved pool and the system pool
            for (TestingPrestoServer server : queryRunner.getServers()) {
                MemoryPool reserved = server.getLocalMemoryManager().getPool(RESERVED_POOL);
                // Free up the entire pool
                reserved.free(reserved.getMaxBytes());
                assertTrue(reserved.getFreeBytes() > 0);

                MemoryPool system = server.getLocalMemoryManager().getPool(SYSTEM_POOL);
                // Free up the entire pool
                system.free(system.getMaxBytes());
                assertTrue(system.getFreeBytes() > 0);
            }

            // Make sure both queries finish now that there's memory free in the reserved pool.
            // This also checks that the query in the general pool is successfully moved to the reserved pool.
            for (Future<?> query : queryFutures) {
                query.get();
            }

            List<QueryInfo> queryInfos = queryRunner.getCoordinator().getQueryManager().getAllQueryInfo();
            for (QueryInfo info : queryInfos) {
                assertEquals(info.getState(), FINISHED);
            }

            // Make sure we didn't leak any memory on the workers
            for (TestingPrestoServer worker : queryRunner.getServers()) {
                MemoryPool reserved = worker.getLocalMemoryManager().getPool(RESERVED_POOL);
                assertEquals(reserved.getMaxBytes(), reserved.getFreeBytes());
                MemoryPool general = worker.getLocalMemoryManager().getPool(GENERAL_POOL);
                // Free up the memory we reserved earlier
                general.free(general.getMaxBytes());
                assertEquals(general.getMaxBytes(), general.getFreeBytes());
                MemoryPool system = worker.getLocalMemoryManager().getPool(SYSTEM_POOL);
                assertEquals(system.getMaxBytes(), system.getFreeBytes());
            }
        }
    }

    private static boolean allQueriesBlocked(List<QueryInfo> current)
    {
        boolean allDriversBlocked = current.stream()
                .flatMap(query -> getAllStages(query.getOutputStage()).stream())
                .flatMap(stage -> stage.getTasks().stream())
                .flatMap(task -> task.getStats().getPipelines().stream())
                .flatMap(pipeline -> pipeline.getDrivers().stream())
                .allMatch(DriverStats::isFullyBlocked);
        boolean waitingForMemory = current.stream().allMatch(TestMemoryManager::atLeastOneOperatorWaitingForMemory);

        return allDriversBlocked && waitingForMemory;
    }

    private static boolean atLeastOneOperatorWaitingForMemory(QueryInfo query)
    {
        return getAllStages(query.getOutputStage()).stream()
                .flatMap(stage -> stage.getTasks().stream())
                .map(TaskInfo::getStats)
                .anyMatch(task -> task.getBlockedReasons().contains(WAITING_FOR_MEMORY));
    }

    @Test(timeOut = 240_000, expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".*Query exceeded max memory size of 1kB.*")
    public void testQueryMemoryLimit()
            throws Exception
    {
        Map<String, String> properties = ImmutableMap.<String, String>builder()
                .put("query.max-memory", "1kB")
                .put("task.operator-pre-allocated-memory", "0B")
                .build();
        try (QueryRunner queryRunner = createQueryRunner(SESSION, properties)) {
            queryRunner.execute(SESSION, "SELECT COUNT(*), clerk FROM orders GROUP BY clerk");
        }
    }

    @Test(timeOut = 240_000, expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ".*Query exceeded local memory limit of 1kB.*")
    public void testQueryMemoryPerNodeLimit()
            throws Exception
    {
        Map<String, String> properties = ImmutableMap.<String, String>builder()
                .put("query.max-memory-per-node", "1kB")
                .put("task.operator-pre-allocated-memory", "0B")
                .build();
        try (QueryRunner queryRunner = createQueryRunner(SESSION, properties)) {
            queryRunner.execute(SESSION, "SELECT COUNT(*), clerk FROM orders GROUP BY clerk");
        }
    }

    @AfterClass(alwaysRun = true)
    public void shutdown()
    {
        executor.shutdownNow();
    }

    private static DistributedQueryRunner createQueryRunner(Session session, Map<String, String> properties)
            throws Exception
    {
        DistributedQueryRunner queryRunner = new DistributedQueryRunner(session, 2, properties);

        try {
            queryRunner.installPlugin(new TpchPlugin());
            queryRunner.createCatalog("tpch", "tpch");
            return queryRunner;
        }
        catch (Exception e) {
            queryRunner.close();
            throw e;
        }
    }
}


text: pip install -t lib -r requirements.txt


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.healthcare.v1beta1.model;

/**
 * Specifies additional options to apply to the base profile.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Healthcare API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Options extends com.google.api.client.json.GenericJson {

  /**
   * Set Clean Descriptors Option.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private CleanDescriptorsOption cleanDescriptors;

  /**
   * Apply `Action.clean_image` to
   * [`PixelData`](http://dicom.nema.org/medical/dicom/2018e/output/chtml/part06/chapter_6.html) as
   * configured.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ImageConfig cleanImage;

  /**
   * Set `Action` for [`StudyInstanceUID`, `SeriesInstanceUID`, `SOPInstanceUID`, and `MediaStorageS
   * OPInstanceUID`](http://dicom.nema.org/medical/dicom/2018e/output/chtml/part06/chapter_6.html).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String primaryIds;

  /**
   * Set Clean Descriptors Option.
   * @return value or {@code null} for none
   */
  public CleanDescriptorsOption getCleanDescriptors() {
    return cleanDescriptors;
  }

  /**
   * Set Clean Descriptors Option.
   * @param cleanDescriptors cleanDescriptors or {@code null} for none
   */
  public Options setCleanDescriptors(CleanDescriptorsOption cleanDescriptors) {
    this.cleanDescriptors = cleanDescriptors;
    return this;
  }

  /**
   * Apply `Action.clean_image` to
   * [`PixelData`](http://dicom.nema.org/medical/dicom/2018e/output/chtml/part06/chapter_6.html) as
   * configured.
   * @return value or {@code null} for none
   */
  public ImageConfig getCleanImage() {
    return cleanImage;
  }

  /**
   * Apply `Action.clean_image` to
   * [`PixelData`](http://dicom.nema.org/medical/dicom/2018e/output/chtml/part06/chapter_6.html) as
   * configured.
   * @param cleanImage cleanImage or {@code null} for none
   */
  public Options setCleanImage(ImageConfig cleanImage) {
    this.cleanImage = cleanImage;
    return this;
  }

  /**
   * Set `Action` for [`StudyInstanceUID`, `SeriesInstanceUID`, `SOPInstanceUID`, and `MediaStorageS
   * OPInstanceUID`](http://dicom.nema.org/medical/dicom/2018e/output/chtml/part06/chapter_6.html).
   * @return value or {@code null} for none
   */
  public java.lang.String getPrimaryIds() {
    return primaryIds;
  }

  /**
   * Set `Action` for [`StudyInstanceUID`, `SeriesInstanceUID`, `SOPInstanceUID`, and `MediaStorageS
   * OPInstanceUID`](http://dicom.nema.org/medical/dicom/2018e/output/chtml/part06/chapter_6.html).
   * @param primaryIds primaryIds or {@code null} for none
   */
  public Options setPrimaryIds(java.lang.String primaryIds) {
    this.primaryIds = primaryIds;
    return this;
  }

  @Override
  public Options set(String fieldName, Object value) {
    return (Options) super.set(fieldName, value);
  }

  @Override
  public Options clone() {
    return (Options) super.clone();
  }

}


text:
<?php
namespace Pstkweb\BoutiqueBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;
use Pstkweb\BoutiqueBundle\Entity\Personne;

class PersonneToArrayTransformer implements DataTransformerInterface
{
    private $om;

    public function __construct(ObjectManager $om)
    {
        $this->om = $om;
    }

    public function transform($data)
    {
        if (!$data) {
            return null;
        }

        $personne = new Personne;
        $personne->setGenre($data['genre']);
        $personne->setNom($data['nom']);
        $personne->setPrenom($data['prenom']);
        $personne->setEmail($data['email']);
        $personne->setTelephone($data['tel']);
        $personne->setDateNaissance($data['dateNaissance']);
        $personne->setDateEvenement($data['dateEvenement']);

        return $personne;
    }

    public function reverseTransform($personne)
    {
        if ($personne === null) {
            return array();
        }

        $data = array();

        $data['genre'] = $personne->getGenre();
        $data['nom'] = $personne->getNom();
        $data['prenom'] = $personne->getPrenom();
        $data['email'] = $personne->getEmail();
        $data['tel'] = $personne->getTelephone();
        $data['dateNaissance'] = $personne->getDateNaissance();
        $data['dateEvenement'] = $personne->getDateEvenement();

        return $data;
    }
}


text:
package io.atomix.core.set;

import java.util.NavigableSet;

/**
 * Distributed navigable set.
 */
public interface DistributedNavigableSet<E extends Comparable<E>> extends DistributedSortedSet<E>, NavigableSet<E> {
  @Override
  AsyncDistributedNavigableSet<E> async();
}


text:
#ifndef MIO_MANAGED_ALLOCATOR_H_
#define MIO_MANAGED_ALLOCATOR_H_

#include "base.h"

namespace mio {

class ManagedAllocator {
public:
    ManagedAllocator() = default;
    virtual ~ManagedAllocator() = default;

    /**
     * Initialize allocator
     */
    virtual bool Init() = 0;

    /**
     * Cleanup allocator
     */
    virtual void Finialize() = 0;

    /**
     * Allocate memory from managed area
     */
    virtual void *Allocate(int size) = 0;

    /**
     * Free memory to managed area
     */
    virtual void Free(const void *p) = 0;

    DISALLOW_IMPLICIT_CONSTRUCTORS(ManagedAllocator)
}; // class ManagedAllocator

} // namespace mio

#endif // MIO_MANAGED_ALLOCATOR_H_


text:
package me.learn.personal.month2;

/**
 *
 * Title 243 : Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = "coding", word2 = "practice"
Output: 3

Input: word1 = "makes", word2 = "coding"
Output: 1

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

 *
 * @author bramanarayan
 * @date May 26, 2020
 */
public class ShortestWordDistance1 {

	public static void main(String[] args) {

	}

	public int shortestDistance(String[] words, String word1, String word2) {
		int i1 = -1, i2 = -1;
		int minDistance = words.length;
		for (int i = 0; i < words.length; i++) {
			if (words[i].equals(word1)) {
				i1 = i;
			} else if (words[i].equals(word2)) {
				i2 = i;
			}

			if (i1 != -1 && i2 != -1) {
				minDistance = Math.min(minDistance, Math.abs(i1 - i2));
			}
		}
		return minDistance;
	}

}


text:
#ifndef SNMP_H
#define SNMP_H

#include "TCPIP Stack/TCPIP.h"
/****************************************************************************
  Section:
	Macros and Definitions
  ***************************************************************************/

#define DATA_TYPE_TABLE_SIZE    (sizeof(dataTypeTable)/sizeof(dataTypeTable[0]))

//This is the file that contains SNMP bib file.
//File name must contain all upper case letter and must match
//with what was included in MPFS2 image.

#define SNMP_BIB_FILE_NAME		"snmp.bib"

// Section:  SNMP Tx pdu offset settings
#define _SNMPSetTxOffset(o)     (SNMPTxOffset = o)
#define _SNMPGetTxOffset()      SNMPTxOffset

//This macro will be used to avoid SNMP OID memory buffer corruption
#define SNMP_MAX_OID_LEN_MEM_USE   (18)

//Change this to match your OID string length.
#define OID_MAX_LEN             (SNMP_MAX_OID_LEN_MEM_USE+1)

#define SNMP_START_OF_VAR       (0)
#define SNMP_END_OF_VAR         (0xff)
#define SNMP_INDEX_INVALID      (0xff)

//Trap information.
//This table maintains list of intereseted receivers
//who should receive notifications when some interesting
//event occurs.

//This macro will be used to avoid SNMP OID memory buffer corruption
#define SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE   (8)

#define TRAP_TABLE_SIZE         (2)
#define TRAP_COMMUNITY_MAX_LEN       (SNMP_TRAP_COMMUNITY_MAX_LEN_MEM_USE+1)

// Section:  SNMP specific data validation
#define IS_STRUCTURE(a)         (a==STRUCTURE)
#define IS_ASN_INT(a)           (a==ASN_INT)
#define IS_OCTET_STRING(a)      (a==OCTET_STRING)
#define IS_OID(a)               (a==ASN_OID)
#define IS_ASN_NULL(a)          (a==ASN_NULL)
#define IS_GET_REQUEST(a)       (a==GET_REQUEST)
#define IS_GET_NEXT_REQUEST(a)  (a==GET_NEXT_REQUEST)
#define IS_GET_RESPONSE(a)      (a==GET_RESPONSE)
#define IS_SET_REQUEST(a)       (a==SET_REQUEST)
#define IS_TRAP(a)              (a==TRAP)
#define IS_AGENT_PDU(a)         (a==GET_REQUEST || \
                                 a==GET_NEXT_REQUEST || \
                                 a==SET_REQUEST || \
                                 a==SNMP_V2C_GET_BULK)
#define IS_SNMPV3_AUTH_STRUCTURE(a) (a==SNMPV3_ENCRYPTION)

// Section:  SNMP specific variables
#define STRUCTURE               (0x30u)
#define ASN_INT                 (0x02u)
#define OCTET_STRING            (0x04u)
#define ASN_NULL                (0x05u)
#define ASN_OID                 (0x06u)

#define SNMP_IP_ADDR            (0x40)
#define SNMP_COUNTER32          (0x41)
#define SNMP_GAUGE32            (0x42)
#define SNMP_TIME_TICKS         (0x43)
#define SNMP_OPAQUE             (0x44)
#define SNMP_NSAP_ADDR          (0x45)

//This is the SNMP OID variable id.
//This id is assigned via MIB file.  Only dynamic and AgentID
//variables can contian ID.  MIB2BIB utility enforces this
//rules when BIB was generated.
typedef int SNMP_ID;
typedef BYTE SNMP_INDEX;

/*SNMP MIN and MAX message 484 bytes in size */
/*As per RFC 3411 snmpEngineMaxMessageSize and
RFC 1157 ( section 4- protocol specification )
and implementation  supports more than 484 whenever
feasible.*/
#define SNMP_MAX_MSG_SIZE  484

// Section:  SNMP agent version types
#define SNMP_V1                 (0)
#define SNMP_V2C				(1)
#define SNMP_V3					(3)

// Section:  SNMP v1 and v2c pdu types
#define GET_REQUEST             (0xa0)
#define GET_NEXT_REQUEST        (0xa1)
#define GET_RESPONSE            (0xa2)
#define SET_REQUEST             (0xa3)
#define TRAP                    (0xa4)
#define GET_BULK_REQUEST        (0xa5)
#define REPORT_RESPONSE			(0xa8)

// Section:  SNMP Udp ports
#define SNMP_AGENT_PORT     (161)
#define SNMP_NMS_PORT       (162)
#define AGENT_NOTIFY_PORT   (0xfffe)

/****************************************************************************
  Section:
	Data Structures and Enumerations
  ***************************************************************************/
// Section:  SNMP specific data tyes
typedef enum
{
	INT8_VAL		= 0x00, 	//8 bit integer value
	INT16_VAL		= 0x01, 	//16 bit integer value
	INT32_VAL		= 0x02, 	//32 bit integer value
	BYTE_ARRAY		= 0x03, 	//Aray of bytes
	ASCII_STRING	= 0x04, 	//Ascii string type
	IP_ADDRESS		= 0x05, 	//IP address variable
	COUNTER32		= 0x06, 	//32 bit counter variable
	TIME_TICKS_VAL	= 0x07, 	//Timer vakue counter variable
	GAUGE32 		= 0x08, 	//32 bit guage variable
	OID_VAL 		= 0x09, 	//Object id value var
	DATA_TYPE_UNKNOWN			//Unknown data type
} DATA_TYPE;

// Section:  SNMP specific mib file access information
typedef union
{
	struct
	{
		unsigned int bIsFileOpen : 1;  //MIB file access int flag
	} Flags;
	BYTE Val;						   //MIB file access byte flag
} SNMP_STATUS;

// Section:  SNMP OID index information
typedef union
{
	struct
	{
		unsigned int bIsOID:1;	//value is OID/index int flag
	} Flags;
	BYTE Val;					//value is OID/index byte flag
} INDEX_INFO;

// Section:  SNMP object information
typedef union
{
	struct
	{
		unsigned int bIsDistantSibling : 1; //Object have distant sibling node
		unsigned int bIsConstant : 1;		//Object is constant
		unsigned int bIsSequence : 1;		//Object is sequence
		unsigned int bIsSibling : 1;		//Sibling node flag

		unsigned int bIsParent : 1; 		//Node is parent flag
		unsigned int bIsEditable : 1;		//Node is editable flag
		unsigned int bIsAgentID : 1;		//Node have agent id flag
		unsigned int bIsIDPresent : 1;		//Id present flag
	} Flags;
	BYTE Val;								//MIB Obj info as byte value
} MIB_INFO;

// Section:  SNMP reuested variable list error status information.
//Max variable in a request supported 15
typedef struct
{
WORD noSuchObjectErr;		//Var list no such obj errors flags
WORD noSuchNameErr; 		//Var list no such name error
WORD noSuchInstanceErr; 	//Var list no such instance error
WORD endOfMibViewErr;		//Var list end of mib view error
}reqVarErrStatus;

// Section:  ASN data type info
typedef struct
{
	BYTE asnType;	//ASN data type
	BYTE asnLen;	//ASN data length
} DATA_TYPE_INFO;

// Section:  SNMP trap notification information for agent
typedef struct
{
	char community[NOTIFY_COMMUNITY_LEN];	//Community name array
	BYTE communityLen;						//Community name length
	SNMP_ID agentIDVar; 					//Agent id for trap identification
	BYTE notificationCode;					//Trap notification code
	UDP_SOCKET socket;						//Udp socket number
	DWORD_VAL timestamp;					//Time stamp for trap
#if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3) && !defined(SNMP_TRAP_DISABLED)
	SNMP_ID trapIDVar;						// SNMPV2 specific trap
#endif
} SNMP_NOTIFY_INFO;

// Section:  SNMP MIB variable object information
typedef struct
{
	DWORD			hNode;		//Node location in the mib
	BYTE			oid;		//Object Id
	MIB_INFO		nodeInfo;	//Node info
	DATA_TYPE		dataType;	//Data type
	SNMP_ID 		id; 		//Snmp Id
	WORD_VAL		dataLen;	//Data length
	DWORD			hData;		//Data
	DWORD			hSibling;	//Sibling info
	DWORD			hChild; 	//Child info
	BYTE			index;		//Index of object
	BYTE			indexLen;	//Index length
} OID_INFO;

// Section:  SNMP pdu information database
typedef struct
{
	DWORD_VAL		requestID;		//Snmp request id
	BYTE			nonRepeators;	//# non repeaters in the request
	BYTE			maxRepetitions; //# max repeaters in the request
	BYTE			pduType;		//Snmp pdu type
	BYTE			errorStatus;	//Pdu error status
	BYTE			erroIndex;		//Pdu error Index
	BYTE			snmpVersion;	//Snmp version
	WORD			pduLength;		//Pdu length
} PDU_INFO;

// Section:  SNMP specific errors
typedef enum
{
    SNMP_NO_ERR = 0,			//Snmp no error
    SNMP_TOO_BIG,				//Value too big error
    SNMP_NO_SUCH_NAME,			//No such name in MIB error
    SNMP_BAD_VALUE,				//Not assignable value for the var error
    SNMP_READ_ONLY,				//Read only variable, write not allowed err
    SNMP_GEN_ERR,				//Snmp gen error
    SNMP_NO_ACCESS,				//Access to modify or read not granted err
    SNMP_WRONG_TYPE,			//Variable data type wrong error
    SNMP_WRONG_LENGTH,			//Wrong data length error
    SNMP_WRONG_ENCODING,		//Wrong encoding error
    SNMP_WRONG_VALUE,			//Wrong value for the var type
    SNMP_NO_CREATION,			//No creationg error
    SNMP_INCONSISTENT_VAL,		//Inconsistent value error
    SNMP_RESOURCE_UNAVAILABE,	//Resource unavailbe error
    SNMP_COMMIT_FAILED,			//Modification update failed error
    SNMP_UNDO_FAILED,			//Modification undo failed
    SNMP_AUTH_ERROR,			//Authorization failed error
    SNMP_NOT_WRITABLE,			//Variable read only
    SNMP_INCONSISTENT_NAME,		//Inconsistent name
    SNMP_NO_SUCH_OBJ=128,		//No such object error
    SNMP_NO_SUCH_INSTANCE=129,	//No such instance error
    SNMP_END_OF_MIB_VIEW=130	//Reached to end of mib error
} SNMP_ERR_STATUS;

typedef struct
{
   BYTE Size;
   struct
   {
       BYTE communityLen;					//Community name length
       char community[TRAP_COMMUNITY_MAX_LEN];	//Community name array
       IP_ADDR IPAddress;					//IP address to which trap to be sent
       struct
       {
           unsigned int bEnabled : 1;		//Trap enabled flag
       } Flags;
   } table[TRAP_TABLE_SIZE];
} TRAP_INFO;

typedef union
{
    DWORD dword;				//double word value
    WORD  word;					//word value
    BYTE  byte;					//byte value
    BYTE  v[sizeof(DWORD)];		//byte array
} SNMP_VAL;

typedef enum
{
	READ_COMMUNITY=1,		//Read only community
	WRITE_COMMUNITY=2,		//Read write community
	INVALID_COMMUNITY=3			//Community invalid
}COMMUNITY_TYPE;

/********************************************************************
  This is the list of SNMP action a remote NMS can perform. This
  inforamtion is passed to application via callback
  SNMPValidateCommunity(). Application should validate the action for
  given community string.
  ********************************************************************/
typedef enum
{
    SNMP_GET            = 0xa0,	//Snmp GET identifier
    SNMP_GET_NEXT       = 0xa1, //Snmp GET_NEXT identifier
    SNMP_GET_RESPONSE   = 0xa2,	//Snmp GET_RESPONSE identifier
    SNMP_SET            = 0xa3,	//Snmp SET identifier
    SNMP_TRAP           = 0xa4,	//Snmp TRAP identifier
    SNMP_V2C_GET_BULK	= 0xa5,	//Snmp GET_BULK identifier
    SNMP_V2_TRAP		= 0xa7, //Snmp v2 Trap Identifier
    SNMPV3_ENCRYPTION	= 0x04,
    SNMP_ACTION_UNKNOWN = 0		//Snmp requested action unknown
} SNMP_ACTION;

typedef enum
{
	COLD_START 			=0x0,
	WARM_START			=0x1,
	LINK_DOWN			=0x2,
	LINK_UP				=0x3,
	AUTH_FAILURE		=0x4,
	EGP_NEBOR_LOSS		=0x5,
	ENTERPRISE_SPECIFIC	=0x6

} GENERIC_TRAP_NOTIFICATION_TYPE;

typedef enum
{
	VENDOR_TRAP_DEFAULT 	=0x0,
	BUTTON_PUSH_EVENT		=0x1,
	POT_READING_MORE_512	=0x2
} VENDOR_SPECIFIC_TRAP_NOTIFICATION_TYPE;

typedef enum
{
	SNMP_RESPONSE_PDU=0x01,
	SNMP_REQUEST_PDU=0x02

}INOUT_SNMP_PDU;

// SNMPv3
typedef struct
{
	UINT8 *head;
	WORD length;
	WORD maxlength;
	WORD msgAuthParamOffset;
}SNMPV3MSGDATA;

typedef struct
{
	UINT8 oidstr[16];
	UINT8 version;
}SNMPNONMIBRECDINFO;

extern UINT16 gSNMPv3ScopedPduDataPos;
extern SNMPV3MSGDATA gSNMPv3ScopedPduRequestBuf;
extern SNMPV3MSGDATA gSNMPv3ScopedPduResponseBuf;
//extern SNMPV3_REQUEST_WHOLEMSG gSnmpV3InPduWholeMsgBuf;

/****************************************************************************
  Section:
	Global Variables
  ***************************************************************************/
#if !defined(SNMP_TRAP_DISABLED)
extern BYTE gSendTrapFlag;//Global flag to send Trap
extern BYTE gGenericTrapNotification;//Global flag for Generic trap notification
extern BYTE gSpecificTrapNotification;//Global flag for vendor specific trap notification
#endif
extern BYTE gOIDCorrespondingSnmpMibID;//Gloabal var to store SNMP ID of var for OID received in SNMP request.
extern BYTE	gSetTrapSendFlag;
extern BYTE appendZeroToOID;//global flag to modify OID by appending zero
extern BOOL getZeroInstance;

// SNMPNotifyInfo is not required if TRAP is disabled
#if !defined(SNMP_TRAP_DISABLED)
extern SNMP_NOTIFY_INFO SNMPNotifyInfo; //notify info for trap
#endif
extern MPFS_HANDLE hMPFS;	//MPFS file handler
extern SNMPNONMIBRECDINFO gSnmpNonMibRecInfo[];

BYTE IsValidLength(WORD *len);
void SNMPInit(void);
BOOL SNMPTask(void);
void SNMPSendTrap(void);
BYTE SNMPValidateCommunity(BYTE * community);
BOOL SNMPNotify(SNMP_ID var, SNMP_VAL val, SNMP_INDEX index);
BOOL SNMPSetVar(SNMP_ID var, SNMP_INDEX index,BYTE ref, SNMP_VAL val);
BOOL SNMPGetVar(SNMP_ID var, SNMP_INDEX index,BYTE* ref, SNMP_VAL* val);
BOOL SNMPIsNotifyReady(IP_ADDR* remoteHost);
void SNMPNotifyPrepare(IP_ADDR* remoteHost, char* community, BYTE communityLen, SNMP_ID agentIDVar, BYTE notificationCode, DWORD timestamp);
BOOL SNMPGetNextIndex(SNMP_ID var, SNMP_INDEX* index);
BOOL SNMPGetExactIndex(SNMP_ID var, SNMP_INDEX index);
BOOL SNMPIsValidSetLen(SNMP_ID var, BYTE len,BYTE index);

BYTE ProcessGetVar(OID_INFO* rec, BOOL bAsOID, PDU_INFO* pduDbPtr);
BYTE ProcessGetNextVar(OID_INFO* rec, PDU_INFO* pduDbPtr);
BYTE ProcessSetVar(PDU_INFO* pduDbPtr,OID_INFO* rec, SNMP_ERR_STATUS* errorStatus);
BYTE ProcessGetBulkVar(OID_INFO* rec, BYTE* oidValuePtr, BYTE* oidLenPtr,BYTE* successor,PDU_INFO* pduDbPtr);
BYTE IsValidStructure(WORD* dataLen);

BOOL GetOIDStringByID(SNMP_ID id, OID_INFO* info, BYTE* oidString, BYTE* len);

extern BOOL IsValidInt(DWORD* val);
extern BYTE _SNMPGet(void);
extern void _SNMPPut(BYTE v);

extern 	void SetErrorStatus(WORD errorStatusOffset,WORD errorIndexOffset, SNMP_ERR_STATUS errorStatus,BYTE errorIndex);
extern BYTE OIDLookup(PDU_INFO* pduDbPtr,BYTE* oid, BYTE oidLen, OID_INFO* rec);
extern 	BOOL GetNextLeaf(OID_INFO* rec);

extern BOOL SNMPIdRecrdValidation(PDU_INFO * pduPtr,OID_INFO *var,BYTE * oidValuePtr,BYTE oidLen);
BOOL GetOIDStringByAddr(OID_INFO* rec, BYTE* oidString, BYTE* len);

extern SNMP_ERR_STATUS Snmpv3MsgProcessingModelProcessPDU(BYTE inOutPdu);
extern SNMP_ERR_STATUS Snmpv3UserSecurityModelProcessPDU(BYTE inOutPdu);
extern SNMP_ERR_STATUS Snmpv3ScopedPduProcessing(BYTE inOutPdu);

extern UINT8 Snmpv3TrapScopedpdu(SNMP_ID var, SNMP_VAL val, SNMP_INDEX index,UINT8 targetIndex);

extern void _SNMPDuplexInit(UDP_SOCKET socket);
extern void Snmpv3GetAuthEngineTime(void);
extern void Snmpv3UsmAesEncryptDecryptInitVector(BYTE inOutPdu);
extern void Snmpv3UsmOutMsgAuthenticationParam(UINT8 hashType);

extern BYTE Snmpv3AESDecryptRxedScopedPdu(void);
extern BYTE *getSnmpV2GenTrapOid(BYTE generic_trap_code,BYTE *len);
extern BYTE Snmpv3GetBufferData(SNMPV3MSGDATA getbuf,UINT16 pos);
extern void Snmpv3FormulateEngineID(UINT8 fifthOctectIdentifier );

extern BOOL Snmpv3ValidateSecNameAndSecLvl(void);
extern BOOL Snmpv3ValidateSecurityName(void);
extern BOOL Snmpv3ValidateEngineId(void);
extern BOOL GetDataTypeInfo(DATA_TYPE dataType, DATA_TYPE_INFO *info );
extern BOOL Snmpv3Notify(SNMP_ID var, SNMP_VAL val, SNMP_INDEX index,UINT8 targetIndex);
extern BOOL ProcessSnmpv3MsgData(PDU_INFO* pduDbPtr);
extern BOOL Snmpv3BufferPut(BYTE val ,SNMPV3MSGDATA *putbuf);
extern void Snmpv3InitializeUserDataBase(void);

#endif