text:
typedef struct {
    int pointerIndex;
    int storageIndex;
    const char **pointers;
    char *storage;
} DFArrayBuilder;

DFArrayBuilder DFArrayBuilderEmpty = { 0, 0, NULL, NULL };

static void DFArrayBuilderBegin(DFArrayBuilder *builder)
{
    builder->pointerIndex = 0;
    builder->storageIndex = 0;
}

static void DFArrayBuilderAdd(DFArrayBuilder *builder, const char *str, size_t start, size_t end)
{
    assert(start <= end);
    size_t toklen = end - start;
    if ((builder->pointers != NULL) && (builder->storage != NULL)) {
        builder->pointers[builder->pointerIndex] = &builder->storage[builder->storageIndex];
        memcpy(&builder->storage[builder->storageIndex],&str[start],toklen);
        builder->storage[builder->storageIndex+toklen] = '\0';
    }

    builder->pointerIndex += 1;
    builder->storageIndex += (int)(toklen + 1);
}

static void DFArrayBuilderAllocate(DFArrayBuilder *builder)
{
    int pointerBytes = (builder->pointerIndex + 1)*sizeof(char *);
    void *mem = xmalloc(pointerBytes + builder->storageIndex);
    builder->pointers = mem;
    builder->storage = (char *)mem + pointerBytes;
}

static void DFArrayBuilderFinish(DFArrayBuilder *builder)
{
    builder->pointers[builder->pointerIndex] = NULL;
}

#define isstart1(c) (((c) & 0x80) == 0x00) // 0xxxxxxx
#define isstart2(c) (((c) & 0xE0) == 0xC0) // 110xxxxx
#define isstart3(c) (((c) & 0xF0) == 0xE0) // 1110xxxx
#define isstart4(c) (((c) & 0xF8) == 0xF0) // 11110xxx
#define iscont(c)   (((c) & 0xC0) == 0x80) // 10xxxxxx

uint32_t DFNextChar(const char *str, size_t *offsetp)
{
    size_t pos = *offsetp;
    const uint8_t *input = (const uint8_t *)str;

    // If we're part-way through a multi-byte character, skip to the beginning of the next one
    while ((input[pos] != 0) && iscont(input[pos]))
        pos++;

    // End of string
    if (input[pos] == 0) {
        *offsetp = pos;
        return 0;
    }

    if (isstart1(input[pos])) {
        // 1-byte character: 0xxxxxxx
        uint32_t a = input[pos];
        *offsetp = pos+1;
        return a;
    }
    else if (isstart2(input[pos]) && iscont(input[pos+1])) {
        // 2-byte character: 110xxxxx 10xxxxxx
        uint32_t a = input[pos+1] & 0x3F; // a = bits 0-5
        uint32_t b = input[pos+0] & 0x1F; // b = bits 6-10
        *offsetp = pos+2;
        return (a << 0) | (b << 6);
    }
    else if (isstart3(input[pos]) && iscont(input[pos+1]) && iscont(input[pos+2])) {
        // 3-byte character: 1110xxxx 10xxxxxx 10xxxxxx
        uint32_t a = input[pos+2] & 0x3F; // a = bits 0-5
        uint32_t b = input[pos+1] & 0x3F; // b = bits 6-11
        uint32_t c = input[pos+0] & 0x0F; // c = bits 12-15
        *offsetp = pos+3;
        return (a << 0) | (b << 6) | (c << 12);
    }
    else if (isstart4(input[pos]) && iscont(input[pos+1]) && iscont(input[pos+2]) && iscont(input[pos+3])) {
        // 4-byte character: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
        uint32_t a = input[pos+3] & 0x3F; // a = bits 0-5
        uint32_t b = input[pos+2] & 0x3F; // b = bits 6-11
        uint32_t c = input[pos+1] & 0x3F; // c = bits 12-17
        uint32_t d = input[pos+0] & 0x07; // d = bits 18-20
        *offsetp = pos+4;
        return (a << 0) | (b << 6) | (c << 12) | (d << 18);
    }
    else {
        // Invalid UTF8 byte sequence
        *offsetp = pos;
        return 0;
    }
}

uint32_t DFPrevChar(const char *string, size_t *offsetp)
{
    size_t pos = *offsetp;
    const uint8_t *input = (const uint8_t *)string;

    if (pos == 0)
        return 0;

    // Move to the first byte of the previous character
    do {
        pos--;
    } while ((pos > 0) && iscont(input[pos]));

    *offsetp = pos;
    size_t ignore = pos;
    return DFNextChar(string,&ignore);
}

int DFStringCompare(const char *a, const char *b)
{
    if ((a == NULL) && (b == NULL))
        return 0;
    else if ((a == NULL) && (b != NULL))
        return -1;
    else if ((a != NULL) && (b == NULL))
        return 1;
    else
        return strcmp(a,b);
}

int DFStringCompareCI(const char *a, const char *b)
{
    if ((a == NULL) && (b == NULL))
        return 0;
    else if ((a == NULL) && (b != NULL))
        return -1;
    else if ((a != NULL) && (b == NULL))
        return 1;
    else
        return strcasecmp(a,b);
}

int DFStringEquals(const char *a, const char *b)
{
    return (DFStringCompare(a,b) == 0);
}

int DFStringEqualsCI(const char *a, const char *b)
{
    return (DFStringCompareCI(a,b) == 0);
}

int DFStringHasPrefix(const char *str, const char *prefix)
{
    if ((str == NULL) || (prefix == NULL))
        return 0;
    if (strlen(str) < strlen(prefix))
        return 0;
    if (!strncmp(str,prefix,strlen(prefix)))
        return 1;
    return 0;
}

int DFStringHasSuffix(const char *str, const char *suffix)
{
    if ((str == NULL) || (suffix == NULL)) {
        return 0;
    }

    size_t slen = strlen(str);
    size_t suffixlen = strlen(suffix);
    if (slen < suffixlen)
        return 0;
    return !memcmp(&str[slen-suffixlen],suffix,suffixlen);
}

int DFStringIsWhitespace(const char *str)
{
    size_t pos = 0;
    uint32_t ch;
    while ((ch = DFNextChar(str,&pos)) != 0) {
        if (!DFCharIsWhitespaceOrNewline(ch))
            return 0;
    }
    return 1;
}

int DFStringContainsWhitespace(const char *str)
{
    size_t pos = 0;
    uint32_t ch;
    while ((ch = DFNextChar(str,&pos)) != 0) {
        if (DFCharIsWhitespaceOrNewline(ch))
            return 1;
    }
    return 0;
}

char *DFStringTrimWhitespace(const char *str)
{
    size_t startpos = 0;
    size_t pos = 0;
    uint32_t ch;
    do {
        startpos = pos;
        ch = DFNextChar(str,&pos);
    } while ((ch != 0) && DFCharIsWhitespaceOrNewline(ch));

    size_t endpos = strlen(str);

    pos = strlen(str);
    do {
        endpos = pos;
        ch = DFPrevChar(str,&pos);
    } while ((ch != 0) && DFCharIsWhitespaceOrNewline(ch));

    return DFSubstring(str,startpos,endpos);
}

char *DFStringTrimLeadingWhitespace(const char *str)
{
    size_t startpos = 0;
    size_t pos = 0;
    uint32_t ch;
    do {
        startpos = pos;
        ch = DFNextChar(str,&pos);
    } while ((ch != 0) && DFCharIsWhitespaceOrNewline(ch));

    return xstrdup(&str[startpos]);
}

char *DFStringNormalizeWhitespace(const char *input)
{
    if (input == NULL) {
        return NULL;
    }

    size_t inputLen = strlen(input);
    size_t outputLen = 0;

    char *output = (char *)xmalloc(inputLen+1);

    size_t start = 0;
    while ((start < inputLen) && isspace(input[start]))
        start++;
    size_t end = inputLen;
    while ((end > start) && isspace(input[end-1]))
        end--;
    int haveSpace = 0;
    for (size_t pos = start; pos < end; pos++) {
        if (isspace(input[pos])) {
            if (!haveSpace) {
                output[outputLen++] = ' ';
                haveSpace = 1;
            }
        }
        else {
            output[outputLen++] = input[pos];
            haveSpace = 0;
        }
    }

    assert(outputLen <= inputLen);

    output[outputLen] = '\0';

    return output;
}

char *DFSubstring(const char *str, size_t start, size_t end)
{
    if (str == NULL)
        return NULL;

    for (size_t pos = 0; (pos < start) && (pos < end); pos++) {
        if (str[pos] == 0) {
            start = pos;
            end = pos;
            break;
        }
    }

    if (end < start)
        end = start;

    char *substring = (char *)xmalloc(end-start+1);
    memcpy(substring,&str[start],end-start);
    substring[end-start] = '\0';
    return substring;
}

char *DFStrDup(const char *str)
{
    if (str != NULL)
        return xstrdup(str);
    else
        return NULL;
}

char *DFUpperCase(const char *input)
{
    if (input == NULL) {
        return NULL;
    }

    size_t len = strlen(input);
    char *result = xstrdup(input);
    for (size_t i = 0; i < len; i++) {
        // Avoid calling toupper with chars from UTF-8 multibyte sequences
        if ((result[i] >= 'a') && result[i] <= 'z')
            result[i] = toupper(result[i]);
    }
    return result;
}

char *DFLowerCase(const char *input)
{
    if (input == NULL) {
        return NULL;
    }

    size_t len = strlen(input);
    char *result = xstrdup(input);
    for (size_t i = 0; i < len; i++) {
        // Avoid calling tolower with chars from UTF-8 multibyte sequences
        if ((result[i] >= 'A') && result[i] <= 'Z')
            result[i] = tolower(result[i]);
    }
    return result;
}

char *DFVFormatString(const char *format, va_list ap)
{
    va_list ap2;
    va_copy(ap2,ap);
    size_t nchars = vsnprintf(NULL,0,format,ap2);
    va_end(ap2);

    char *result = (char *)xmalloc(nchars+1);

    va_copy(ap2,ap);
    vsnprintf(result,nchars+1,format,ap2);
    va_end(ap2);

    return result;
}

char *DFFormatString(const char *format, ...)
{
    va_list ap;
    va_start(ap,format);
    char *result = DFVFormatString(format,ap);
    va_end(ap);
    return result;
}

static void DFStringTokenizeInternal(const char *str, int (*isseparator)(int c), DFArrayBuilder *builder)
{
    size_t len = strlen(str);
    size_t start = 0;
    size_t pos = 0;

    DFArrayBuilderBegin(builder);

    for (; pos <= len; pos++) {
        if ((pos == len) || isseparator(str[pos])) {
            if (pos > start)
                DFArrayBuilderAdd(builder,str,start,pos);
            start = pos+1;
        }
    }
}

const char **DFStringTokenize(const char *str, int (*isseparator)(int c))
{
    if (isseparator == NULL) {
        isseparator = isspace;
    }

    DFArrayBuilder builder = DFArrayBuilderEmpty;

    // Determine how many strings there are, and how many bytes we need to allocate for the strings
    DFStringTokenizeInternal(str,isseparator,&builder);

    // Allocate a single block of memory to hold both the strings and the pointers to them ,thus
    // necessitating only a single call to free after the caller has finished with the result
    DFArrayBuilderAllocate(&builder);

    // Build the arrays of strings and pointers
    DFStringTokenizeInternal(str,isseparator,&builder);
    DFArrayBuilderFinish(&builder);

    return builder.pointers;
}

static void DFStringSplitInternal(const char *str, const char *separator, int lastEmpty, DFArrayBuilder *builder)
{
    size_t len = strlen(str);
    size_t start = 0;
    size_t pos = 0;
    size_t separatorLen = strlen(separator);

    DFArrayBuilderBegin(builder);

    while (pos <= len) {
        if ((pos == len) || !strncmp(&str[pos],separator,separatorLen)) {
            if ((pos < len) || lastEmpty || (pos > start))
                DFArrayBuilderAdd(builder,str,start,pos);
            pos += separatorLen;
            start = pos;
        }
        else {
            pos++;
        }
    }
}

const char **DFStringSplit(const char *str, const char *separator, int lastEmpty)
{
    DFArrayBuilder builder = DFArrayBuilderEmpty;
    DFStringSplitInternal(str,separator,lastEmpty,&builder);
    DFArrayBuilderAllocate(&builder);
    DFStringSplitInternal(str,separator,lastEmpty,&builder);
    DFArrayBuilderFinish(&builder);
    return builder.pointers;
}

void DFStringArrayFlattenInternal(DFArray *array, DFArrayBuilder *builder)
{
    DFArrayBuilderBegin(builder);

    size_t count = DFArrayCount(array);
    for (size_t i = 0; i < count; i++) {
        const char *item = (const char *)DFArrayItemAt(array,i);
        DFArrayBuilderAdd(builder,item,0,strlen(item));
    }
}

const char **DFStringArrayFlatten(DFArray *array)
{
    DFArrayBuilder builder = DFArrayBuilderEmpty;
    DFStringArrayFlattenInternal(array,&builder);
    DFArrayBuilderAllocate(&builder);
    DFStringArrayFlattenInternal(array,&builder);
    DFArrayBuilderFinish(&builder);
    return builder.pointers;
}

size_t DFStringArrayCount(const char **array)
{
    size_t count = 0;
    while (array[count] != NULL)
        count++;
    return count;
}

char *DFAppendPathComponent(const char *path1, const char *path2)
{
    char *unnormalized;
    if (strlen(path1) == 0)
        unnormalized = xstrdup(path2);
    else if (path1[strlen(path1)-1] == '/')
        unnormalized = DFFormatString("%s%s",path1,path2);
    else
        unnormalized = DFFormatString("%s/%s",path1,path2);
    char *normalized = DFPathNormalize(unnormalized);
    free(unnormalized);

    size_t len = strlen(normalized);
    while ((len > 0) && (normalized[len-1] == '/')) {
        normalized[len-1] = '\0';
        len--;
    }

    return normalized;
}

char *DFStringReplace(const char *input, const char *match, const char *replacement)
{
    size_t inputLen = strlen(input);
    size_t matchLen = strlen(match);

    if (matchLen == 0)
        return xstrdup(input); // protect against infinite loop

    struct DFBuffer *output = DFBufferNew();

    size_t i = 0;
    while (i < inputLen) {
        if (!strncmp(&input[i],match,matchLen)) {
            DFBufferFormat(output,"%s",replacement);
            i += matchLen;
        }
        else {
            DFBufferFormat(output,"%c",input[i]);
            i++;
        }
    }

    char *result = xstrdup(output->data);
    DFBufferRelease(output);
    return result;
}

char *DFQuote(const char *in)
{
    if (in == NULL) {
        return NULL;
    }

    // The maximum length of the quoted string is 2n + 2, where n is the number of characters in
    // the original string. This is because each character could potentially need a two-character
    // escape, and because we add a quote at the beginning and end of the string. We also need 1
    // extra byte for the NULL terminator, i.e. 2n + 3 bytes in total.

    // UTF-8 characters pass through untouched.

    size_t inlen = strlen(in);
    char *out = (char*)xmalloc(2*inlen+3);
    size_t outlen = 0;
    out[outlen++] = '"';
    for (size_t i = 0; i < inlen; i++) {
        char c = in[i];
        switch (c) {
            case '"':
                out[outlen++] = '\\';
                out[outlen++] = '"';
                break;
            case '\\':
                out[outlen++] = '\\';
                out[outlen++] = '\\';
                break;
            case '\b':
                out[outlen++] = '\\';
                out[outlen++] = 'b';
                break;
            case '\f':
                out[outlen++] = '\\';
                out[outlen++] = 'f';
                break;
            case '\n':
                out[outlen++] = '\\';
                out[outlen++] = 'n';
                break;
            case '\r':
                out[outlen++] = '\\';
                out[outlen++] = 'r';
                break;
            case '\t':
                out[outlen++] = '\\';
                out[outlen++] = 't';
                break;
            default:
                out[outlen++] = c;
                break;
        }
    }
    out[outlen++] = '"';
    out[outlen++] = '\0';
    assert(outlen <= 2*inlen+3);
    return out;
}

char *DFUnquote(const char *in)
{
    if (in == NULL)
        return NULL;

    if ((in[0] != '"') && (in[0] != '\''))
        return xstrdup(in);
    char quote = in[0];

    size_t inlen = strlen(in);
    char *out = (char *)xmalloc(inlen+1);
    size_t outlen = 0;
    size_t i = 1;
    for (; i < inlen; i++) {
        char c = in[i];
        if ((i+1 == inlen) && (c == quote))
            continue;
        if ((c == '\\') && (i+1 < inlen)) {
            i++;
            c = in[i];
            switch (c) {
                case 'b':
                    out[outlen++] = '\b';
                    break;
                case 'f':
                    out[outlen++] = '\f';
                    break;
                case 'n':
                    out[outlen++] = '\n';
                    break;
                case 'r':
                    out[outlen++] = '\r';
                    break;
                case 't':
                    out[outlen++] = '\t';
                    break;
                default:
                    out[outlen++] = c;
                    break;
            }
        }
        else {
            out[outlen++] = c;
        }
    }
    out[outlen++] = '\0';

    assert(outlen <= inlen);
    return out;
}

char *DFSpacesToUnderscores(const char *input)
{
    size_t len = strlen(input);
    char *output = xstrdup(input);
    for (size_t i = 0; i < len; i++) {
        if (output[i] == ' ')
            output[i] = '_';
    }
    return output;
}

char *DFUnderscoresToSpaces(const char *input)
{
    size_t len = strlen(input);
    char *output = xstrdup(input);
    for (size_t i = 0; i < len; i++) {
        if (output[i] == '_')
            output[i] = ' ';
    }
    return output;
}

const char *DFFormatDouble(char *str, size_t size, double value)
{
    snprintf(str,size,"%f",value);
    size_t len = strlen(str);
    while ((len > 0) && str[len-1] == '0') {
        len--;
    }
    if ((len > 0) && str[len-1] == '.')
        len--;
    str[len] = '\0';
    return str;
}

const char *DFFormatDoublePct(char *str, size_t size, double value)
{
    DFFormatDouble(str,size,value);
    size_t len = strlen(str);
    if (len+1 < size)
        str[len++] = '%';
    str[len] = '\0';
    return str;
}

const char *DFFormatDoublePt(char *str, size_t size, double value)
{
    DFFormatDouble(str,size,value);
    size_t len = strlen(str);
    if (len+1 < size)
        str[len++] = 'p';
    if (len+1 < size)
        str[len++] = 't';
    str[len] = '\0';
    return str;
}

static int cscompare(const void *val1, const void *val2)
{
    const char *str1 = *(const char **)val1;
    const char *str2 = *(const char **)val2;
    return strcmp(str1,str2);
}

static int cicompare(const void *val1, const void *val2)
{
    const char *str1 = *(const char **)val1;
    const char *str2 = *(const char **)val2;
    return strcasecmp(str1,str2);
}

static int countStrings(const char **strings)
{
    int i = 0;
    while (strings[i])
        i++;
    return i;
}

void DFSortStringsCaseSensitive(const char **strings)
{
    int count = countStrings(strings);
    qsort((void *)strings,count,sizeof(const char *),cscompare);
}

void DFSortStringsCaseInsensitive(const char **strings)
{
    int count = countStrings(strings);
    qsort((void *)strings,count,sizeof(const char *),cicompare);
}

char *DFStringReadFromFile(const char *filename, DFError **error)
{
    DFBuffer *buffer = DFBufferReadFromFile(filename,error);
    if (buffer == NULL)
        return NULL;
    char *result = xstrdup(buffer->data);
    DFBufferRelease(buffer);
    return result;
}

int DFStringWriteToFile(const char *str, const char *filename, DFError **error)
{
    size_t len = strlen(str);
    return DFWriteDataToFile(str,len,filename,error);
}

size_t DFUTF32Length(const uint32_t *str)
{
    if (str == NULL) {
        return 0;
    }

    size_t size = 0;
    while (str[size] != 0)
        size++;
    return size;
}

uint32_t *DFUTF8To32(const char *input)
{
    if (input == NULL) {
        return NULL;
    }

    size_t inpos = 0;
    size_t outlen = 0;
    while (DFNextChar(input,&inpos) != 0)
        outlen++;

    uint32_t *output = (uint32_t *)xmalloc((outlen+1)*sizeof(uint32_t));
    inpos = 0;
    for (size_t outpos = 0; outpos < outlen; outpos++)
        output[outpos] = DFNextChar(input,&inpos);
    output[outlen] = '\0';

    return output;
}

static size_t DFUTF32to8n(const uint32_t *input, char *soutput)
{
    unsigned char *output = (unsigned char *)soutput;

    size_t inlen = DFUTF32Length(input);
    size_t outlen = 0;

    for (size_t pos = 0; pos < inlen; pos++) {
        uint32_t value = input[pos];
        if (value <= 0x7F) { // Up to 7 bits
            // 7 bits encoded as 1 byte
            // 0aaaaaaa

            if (output != NULL) {
                output[outlen+0] = value & 0x7F; // a = bits 0-7
            }

            outlen += 1;
        }
        else if (value <= 0x7FF) {
            // 11 bits encoded as 2 bytes
            // 110bbbbb 10aaaaaa

            if (output != NULL) {
                output[outlen+0] = 0xC0 | ((value >> 6) & 0x1F); // b = bits 6-10
                output[outlen+1] = 0x80 | ((value >> 0) & 0x3F); // a = bits 0-5
            }

            outlen += 2;
        }
        else if (value <= 0xFFFF) { // Up to 16 bits
            // 16 bits encoded as 3 bytes
            // 1110cccc 10bbbbbb 10aaaaaa

            if (output != NULL) {
                output[outlen+0] = 0xE0 | ((value >> 12) & 0x0F); // c = bits 12-15
                output[outlen+1] = 0x80 | ((value >> 6) & 0x3F);  // b = bits 6-11
                output[outlen+2] = 0x80 | ((value >> 0) & 0x3F);  // a = bits 0-5
            }

            outlen += 3;
        }
        else if (value <= 0x10FFFF) {
            // 21 bits encoded as 4 bytes
            // 11110ddd 10cccccc 10bbbbbb 10aaaaaa

            if (output != NULL) {
                output[outlen+0] = 0xF0 | ((value >> 18) & 0x07); // d = bits 18-20
                output[outlen+1] = 0x80 | ((value >> 12) & 0x3F); // c = bits 12-17
                output[outlen+2] = 0x80 | ((value >> 6) & 0x3F);  // b = bits 6-11
                output[outlen+3] = 0x80 | ((value >> 0) & 0x3F);  // a = bits 0-5
            }

            outlen += 4;
        }

        // If above 0x10FFFF, skip
    }

    return outlen;
}

char *DFUTF32to8(const uint32_t *input)
{
    if (input == NULL) {
        return NULL;
    }

    size_t outlen = DFUTF32to8n(input,NULL);
    char *output = (char *)xmalloc(outlen+1);
    DFUTF32to8n(input,output);
    output[outlen] = '\0';

    return output;
}

// UTF-8 spec: http://tools.ietf.org/html/rfc3629


text:
var Delegator = require("delegator");
var modal = require("./modal.ejs");

    var container;

    function hide() {
        container.removeClass('in');
        container.find('.modal-backdrop').removeClass('in');
        setTimeout(function () {
            container.remove();
            container = undefined;
        }, 300);
    }

    function Dialog (param) {
        if (container) {
            container.remove();
            container = undefined;
        }
        container = $(modal({it :param}))
            .appendTo(document.body)
            .show();

        var key,
            action,
            delegator,
            on = param.on || {};

        delegator = (new Delegator(container))
            .on('click', 'close', hide);

        for (key in on) {
            action = key.split('/');
            delegator.on(action[0], action[1], on[key]);
        }

        setTimeout(function () {
            container.addClass('in');
            container.find('.modal-backdrop').addClass('in');
        }, 0);
    }

    Dialog.hide = hide;

module.exports =  Dialog;

redpajama_set_name: RedPajamaGithub


text:
import unittest
import sys
import os
import shlex
import glob
import numpy as np
import netCDF4 as nc
import subprocess as sp

sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../'))
import data_cache.data_cache as dc

class TestMOMScripts(unittest.TestCase):

    def test_mom_monthly_mean(self):
        """
        Test mom_monthly_mean.py and compare output to NCO results.
        """

        file_id_prefix = 'cm-tools-data/analyse/tests/inputs/'
        input_files = ['temp_000.nc', 'temp_001.nc',
                        'temp_002.nc', 'temp_003.nc']
        for f in input_files:
            dc.get_url(file_id_prefix + f)
        input_dir = os.path.dirname(dc.get_url(file_id_prefix + input_files[0]))

        test_dir = os.path.dirname(os.path.realpath(__file__))

        output_dir = os.path.join(test_dir, 'outputs')
        # Montly mean.
        mm_file = os.path.join(output_dir, 'temp_py_mm.nc')
        # Overall mean.
        om_file = os.path.join(output_dir, 'temp_py_om.nc')
        exe = os.path.join(os.path.join(test_dir, '../'), 'mom_monthly_mean.py')

        cmd = """{exe} {input_dir}/temp_000.nc \
                 {input_dir}/temp_001.nc {input_dir}/temp_002.nc \
                 {input_dir}/temp_003.nc {output} --vars temp \
                 --overall_mean_file {overall_mean}
              """.format(exe=exe, input_dir=input_dir,
                         output=mm_file, overall_mean=om_file)

        # Delete output file before regenerating.
        if os.path.exists(mm_file):
            os.remove(mm_file)
        if os.path.exists(om_file):
            os.remove(om_file)

        ret = sp.call(shlex.split(cmd))
        assert(ret == 0)

        # Check that script output and NCO output is the same.
        # Check monthly mean.
        with nc.Dataset(os.path.join(input_dir,'temp_nco_mm.nc')) as nco_out:
            with nc.Dataset(mm_file) as py_out:
                np.testing.assert_array_equal(py_out.variables['temp'][:],
                                              nco_out.variables['temp'][:])

        # Check overall mean.
        with nc.Dataset(os.path.join(input_dir,'temp_nco_om.nc')) as nco_out:
            with nc.Dataset(om_file) as py_out:
                np.testing.assert_array_equal(py_out.variables['temp'][:],
                                              nco_out.variables['temp'][:])

    def test_cice_monthly_mean(self):
        """
        Test cice_monthly_mean.py and compare output to NCO results.
        """

        test_dir = os.path.dirname(os.path.realpath(__file__))
        input_dir = os.path.join(test_dir, 'inputs')
        # Montly mean.
        mm_file = os.path.join(test_dir, 'outputs', 'iceh_hi_py_mm.nc')
        exe = os.path.join(os.path.join(test_dir, '../'), 'cice_monthly_mean.py')

        input_files = glob.glob('{}/iceh_hi.*.nc'.format(input_dir))
        cmd = '{} {} {} --vars hi'
        cmd = cmd.format(exe, ' '.join(input_files), mm_file)

        # Delete output file before regenerating.
        if os.path.exists(mm_file):
            os.remove(mm_file)

        ret = sp.call(shlex.split(cmd))
        assert(ret == 0)

        # Check that script output and NCO output is the same.
        # Check monthly mean.
        with nc.Dataset(os.path.join(input_dir,'iceh_nco_mm.nc')) as nco_out:
            with nc.Dataset(mm_file) as py_out:
                np.testing.assert_array_equal(py_out.variables['hi'][:],
                                              nco_out.variables['hi'][:])

    def test_calc_overall_mean(self):

        test_dir = os.path.dirname(os.path.realpath(__file__))
        input_dir = os.path.join(test_dir, 'inputs')
        output_file = os.path.join(test_dir, 'outputs', 'overall_mean.nc')
        exe = os.path.join(os.path.join(test_dir, '../'), 'overall_mean.py')

        input_files = glob.glob('{}/temp_00*.nc'.format(input_dir))
        cmd = '{} {} {} --vars temp'
        cmd = cmd.format(exe, ' '.join(input_files), output_file)

        if os.path.exists(output_file):
            os.remove(output_file)

        print('Executing: {}'.format(cmd))
        ret = sp.call(shlex.split(cmd))
        assert(ret == 0)

        with nc.Dataset(os.path.join(input_dir,'temp_nco_another_om.nc')) as nco_out:
            with nc.Dataset(output_file) as py_out:
                np.testing.assert_array_equal(py_out.variables['temp'][:],
                                              nco_out.variables['temp'][:])

if __name__ == '__main__':
    unittest.main()


text:
spring-data-jpa-sample
======================

This project is a sample project showing the usage of spring-data framework with jpa

Maven & Spring-data & Hibernate & Mysql

- Lombok should be installed
- MySQL should be installed & test_spring_data_jpa schema should be created
- MySQL user with name "test" and password "test" needs to be created and grant all rights for the schema test_spring_data_jpa
- Run mvn clean install to see it in action

Lombok : www.projectlombok.org

If you don't want to use lombok:
- Remove lombok annotations from domain classes
- Generate getter/setter methods for domain classes


text:
/**
 * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface
 */
static public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
{
    self::$dispatcher = $eventDispatcher;
}


text:
package com.github.ambry.clustermap;

import com.github.ambry.clustermap.HelixClusterManager.HelixClusterChangeHandler;
import java.io.Closeable;
import java.util.List;
import org.apache.helix.HelixManager;

/**
 * Class that stores the information associated with the helix aggregated cluster.
 */
public class HelixAggregatedViewClusterInfo implements Closeable {

  final HelixManager helixManager;
  private final List<DataNodeConfigSource> dataNodeConfigSources;
  // Handler that handles resource state changes in the entire cluster.
  final HelixClusterChangeHandler clusterChangeHandler;

  /**
   * Construct a HelixAggregatedViewClusterInfo object with the given parameters.
   * @param helixManager the associated {@link HelixManager} for this cluster.
   * @param clusterChangeHandler the associated {@link HelixClusterChangeHandler}
   *                            for this datacenter.
   * @param dataNodeConfigSources the list of {@link DataNodeConfigSource}s for data centers in this cluster.
   */
  HelixAggregatedViewClusterInfo(HelixManager helixManager, HelixClusterChangeHandler clusterChangeHandler,
      List<DataNodeConfigSource> dataNodeConfigSources) {
    this.helixManager = helixManager;
    this.dataNodeConfigSources = dataNodeConfigSources;
    this.clusterChangeHandler = clusterChangeHandler;
  }

  @Override
  public void close() {
    try {
      if (helixManager.isConnected()) {
        helixManager.disconnect();
      }
    } finally {
      dataNodeConfigSources.forEach(DataNodeConfigSource::close);
    }
  }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
MetricsSystemMXBean (Apache Hadoop Main 2.2.0 API)
</TITLE>

<META NAME="date" CONTENT="2013-10-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.hadoop.metrics2

Interface MetricsSystemMXBean

All Known Implementing Classes:
MetricsSystem

@InterfaceAudience.Public
@InterfaceStability.Evolving
public interface MetricsSystemMXBean

The JMX interface to the metrics system

Method Summary

 String
currentConfig()

 void
start()

          Start the metrics system

 void
startMetricsMBeans()

          Start metrics MBeans

 void
stop()

          Stop the metrics system

 void
stopMetricsMBeans()

          Stop metrics MBeans.

Method Detail

start

void start()

Start the metrics system

Throws:

MetricsException

stop

void stop()

Stop the metrics system

Throws:

MetricsException

startMetricsMBeans

void startMetricsMBeans()

Start metrics MBeans

Throws:

MetricsException

stopMetricsMBeans

void stopMetricsMBeans()

Stop metrics MBeans.
 Note, it doesn't stop the metrics system control MBean,
 i.e this interface.

Throws:

MetricsException

currentConfig

String currentConfig()

Returns:
the current config
 Avoided getConfig, as it'll turn into a "Config" attribute,
 which doesn't support multiple line values in jconsole.

Throws:

MetricsException

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2013 Apache Software Foundation. All Rights Reserved.


text:
kaspay-php
==========

Kaspay API client for PHP

# Installation
Just copy the content of `dist` to your project directory and include `kaspay_api.combined.php` file.

# Getting merchant keys
Login to [Kaspay](https://www.kaspay.com) with your merchant account and directly go to [Profile Setting Page](https://www.kaspay.com/profile-setting) to acquire both **encryption key** and **MAC key**. There should be _API Keys_ section in that page.

>Trouble getting merchant keys? _API Keys_ section does not exist?
Please [contact us](http://localhost/kaspay-dev/contact).

# Usage
List of available services:

1. Payment API

### Payment API
#### Creating payment
```PHP
///Constructing the client
$client = new Kaspay_payment_api_client(
	<your uaccount>, <your enc key>, <your MAC key>
);
$attempt = new stdClass();
$attempt->merchant_uaccount = <your uaccount>;
$attempt->approve_url = <your site approve URL>;
$attempt->reject_url = <your site reject URL>;
$product_1 = new Product();
$product_1->id = "product-1";
$product_1->name = "product-1";
$product_1->price = 100;
$product_1->quantity = 1;
$attempt->transaction_no = <your generated transaction ID>;
$attempt->timestamp = time();
$attempt->products = array(
	$product_1,
	clone $product_1,
	clone $product_1,
);
$attempt->total = 10000;

///Calling the API
///You can comment the next line in production mode, for sandbox only
$client->set_as_development();
$client->create($attempt);

///Getting the response
$response = json_encode($client->get_response());
print_r($response);
```
#### Executing payment
```PHP
///Constructing the client
$client = new Kaspay_payment_api_client(
	<your uaccount>, <your enc key>, <your MAC key>
);

///Calling the API.
///You can comment the next line in production mode, for sandbox only
$client->set_as_development();
$client->execute($id);

///Getting the response
$response = json_encode($client->get_response());
print_r($response);
```
#### Refunding payment
_Applicable only for executed payments_
```PHP
///Constructing the client
$client = new Kaspay_payment_api_client(
	<your uaccount>, <your enc key>, <your MAC key>
);

///Calling the API.
///You can comment the next line in production mode, for sandbox only
$client->set_as_development();
///$reference_no is acquired from execute() call response
$client->refund($reference_no);

///Getting the response
$response = json_encode($client->get_response());
print_r($response);
```


text:
<?php

namespace Rougin\Transcribe\Source;

/**
 * Database Source
 *
 * Returns an array of words using the PHP Database Object (PDO).
 *
 * @package Transcribe
 * @author  Rougin Gutib <rougingutib@gmail.com>
 */
class DatabaseSource implements SourceInterface
{
    /**
     * @var \PDO
     */
    protected $pdo;

    /**
     * @var array
     */
    protected $table;

    /**
     * @var array
     */
    protected $words = array();

    /**
     * Initializes the source instance.
     *
     * @param \PDO  $pdo
     * @param array $table
     */
    public function __construct(\PDO $pdo, array $table)
    {
        $this->pdo = $pdo;

        $this->table = $table;
    }

    /**
     * Returns an array of words.
     * NOTE: To be removed in v1.0.0. Use "words" instead.
     *
     * @return array
     */
    public function getWords()
    {
        return $this->words();
    }

    /**
     * Returns an array of words.
     *
     * @return array
     */
    public function words()
    {
        $query = 'SELECT * FROM ' . $this->table['name'];

        $table = $this->pdo->prepare($query);

        $table->execute();

        foreach ($table->fetchAll(\PDO::FETCH_ASSOC) as $row) {
            $group = $row[$this->table['language']];

            isset($this->words[$group]) || $this->words[$group] = array();

            $text = (string) $row[$this->table['text']];

            $translation = $row[$this->table['translation']];

            $this->words[$group][$text] = $translation;
        }

        return $this->words;
    }
}


text:
package com.google.cloud.spanner.spi.v1;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.base.Ticker;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall;
import io.grpc.ForwardingClientCallListener;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;

/**
 * A gRPC interceptor that monitors activity on outstanding RPCs. If an RPC sees no activity for a
 * configurable period of time, the watchdog will cancel that RPC and cause it to return an {@code
 * UNAVAILABLE} error so that higher level code will retry the operation. This class exists to work
 * around any edge case that may cause an RPC to hang indefinitely.
 */
class WatchdogInterceptor implements ClientInterceptor {
  private static final String PROPERTY_TIMEOUT_SECONDS =
      "com.google.cloud.spanner.watchdogTimeoutSeconds";
  private static final String PROPERTY_PERIOD_SECONDS =
      "com.google.cloud.spanner.watchdogPeriodSeconds";
  private static final int DEFAULT_TIMEOUT_SECONDS = 30 * 60;
  private static final int DEFAULT_PERIOD_SECONDS = 10;

  private static final Logger logger = Logger.getLogger(WatchdogInterceptor.class.getName());

  private final long activityTimeoutNanos;
  private final TimeUnit activityTimeoutUnits;
  private final Ticker ticker;
  private final ConcurrentHashMap<MonitoredCall<?, ?>, MonitoredCall<?, ?>> monitoredCalls;

  WatchdogInterceptor(long activityTimeout, TimeUnit activityTimeoutUnits) {
    this(activityTimeout, activityTimeoutUnits, Ticker.systemTicker());
  }

  WatchdogInterceptor(long activityTimeout, TimeUnit activityTimeoutUnits, Ticker ticker) {
    checkArgument(activityTimeout > 0, "activityTimeout must be positive");
    this.activityTimeoutNanos = activityTimeoutUnits.toNanos(activityTimeout);
    this.activityTimeoutUnits = checkNotNull(activityTimeoutUnits);
    this.ticker = checkNotNull(ticker);
    // Expect up to ~100 RPCs/channel for initial capacity. Default concurrency level of 16 is
    // likely about right for most applications.
    this.monitoredCalls = new ConcurrentHashMap<>(128 /* initialCapacity */);
  }

  private static int systemProperty(String name, int defaultValue) {
    String stringValue = System.getProperty(name, "");
    return stringValue.isEmpty() ? defaultValue : Integer.parseInt(stringValue);
  }

  /**
   * Creates a default instance based on the system property {@code
   * com.google.cloud.spanner.watchdogTimeoutSeconds}, or a no-op interceptor if none configured.
   */
  @Nullable
  static ClientInterceptor newDefaultWatchdogInterceptor() {
    int timeoutSeconds = systemProperty(PROPERTY_TIMEOUT_SECONDS, DEFAULT_TIMEOUT_SECONDS);
    if (timeoutSeconds <= 0) {
      return new ClientInterceptor() {
        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
            MethodDescriptor<ReqT, RespT> methodDescriptor,
            CallOptions callOptions,
            Channel channel) {
          return channel.newCall(methodDescriptor, callOptions);
        }
      };
    }
    int periodSeconds = systemProperty(PROPERTY_PERIOD_SECONDS, DEFAULT_PERIOD_SECONDS);
    final WatchdogInterceptor interceptor =
        new WatchdogInterceptor(timeoutSeconds, TimeUnit.SECONDS);
    ScheduledExecutorService executor =
        Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder()
                .setDaemon(true)
                .setNameFormat("Cloud-Spanner-WatchdogInterceptor-%d")
                .build());
    executor.scheduleWithFixedDelay(
        new Runnable() {
          @Override
          public void run() {
            interceptor.tick();
          }
        },
        periodSeconds,
        periodSeconds,
        TimeUnit.SECONDS);
    logger.log(
        Level.FINE,
        "Created watchdog interceptor with activity timeout of {0}s and period {1}s",
        new Object[] {timeoutSeconds, periodSeconds});
    return interceptor;
  }

  /**
   * Scans over RPCs currently known to the interceptor, cancelling any that have not seen activity
   * within the timeout.
   */
  void tick() {
    for (MonitoredCall<?, ?> call : monitoredCalls.keySet()) {
      call.checkActivity();
    }
  }

  @Override
  public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions, Channel channel) {
    return new MonitoredCall<>(channel.newCall(methodDescriptor, callOptions));
  }

  private void registerCall(MonitoredCall<?, ?> call) {
    // Cannot put a null value into the map, so use "call".
    monitoredCalls.put(call, call);
  }

  private void unregisterCall(MonitoredCall<?, ?> call) {
    monitoredCalls.remove(call);
  }

  private class MonitoredCall<ReqT, RespT>
      extends ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT> {
    private volatile long lastActivityNanos;
    private volatile boolean stoppedByWatchdog;
    private final AtomicBoolean cancelled = new AtomicBoolean(false);

    MonitoredCall(ClientCall<ReqT, RespT> delegate) {
      super(delegate);
    }

    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      recordActivity();
      registerCall(this);

      ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT> listener =
          new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(
              responseListener) {
            @Override
            public void onHeaders(Metadata headers) {
              recordActivity();
              super.onHeaders(headers);
            }

            @Override
            public void onMessage(RespT message) {
              recordActivity();
              super.onMessage(message);
            }

            @Override
            public void onReady() {
              recordActivity();
              super.onReady();
            }

            @Override
            public void onClose(Status status, Metadata trailers) {
              unregisterCall(MonitoredCall.this);
              super.onClose(handleStatus(status), trailers);
            }
          };

      super.start(listener, headers);
    }

    void recordActivity() {
      lastActivityNanos = ticker.read();
    }

    void checkActivity() {
      if (ticker.read() - lastActivityNanos > activityTimeoutNanos
          && cancelled.compareAndSet(false, true)) {
        stoppedByWatchdog = true;
        delegate().cancel("Cancelled by activity watchdog", null);
        logger.log(
            Level.WARNING,
            "Cancelled due to exceeding inactivity timeout of {0} {1}",
            new Object[] {
              activityTimeoutUnits.convert(activityTimeoutNanos, TimeUnit.NANOSECONDS),
              activityTimeoutUnits
            });
      }
    }

    Status handleStatus(Status status) {
      if (stoppedByWatchdog && status.getCode() == Status.Code.CANCELLED) {
        return Status.UNAVAILABLE.withDescription(
            "Aborted by RPC activity watchdog [timeout="
                + activityTimeoutUnits.convert(activityTimeoutNanos, TimeUnit.NANOSECONDS)
                + " "
                + activityTimeoutUnits
                + "]");
      }
      return status;
    }

    @Override
    public void cancel(@Nullable String message, @Nullable Throwable cause) {
      if (cancelled.compareAndSet(false, true)) {
        super.cancel(message, cause);
      }
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.apache.sling</groupId>
    <artifactId>sling</artifactId>
    <version>26</version>
    <relativePath/>
  </parent>

  <groupId>org.apache.sling.samples</groupId>
  <artifactId>org.apache.sling.samples.fling</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>bundle</packaging>

  <name>Apache Sling Fling Sample</name>
  <description>sample using Sling Models, Query and Thymeleaf</description>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <sling.java.version>8</sling.java.version>
  </properties>

  <dependencies>
    <!-- javax -->
    <dependency>
      <groupId>javax.inject</groupId>
      <artifactId>javax.inject</artifactId>
      <version>1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.jcr</groupId>
      <artifactId>jcr</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- OSGi -->
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>osgi.core</artifactId>
      <version>6.0.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>osgi.annotation</artifactId>
      <version>6.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.service.component.annotations</artifactId>
      <version>1.3.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.service.metatype.annotations</artifactId>
      <version>1.3.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- Apache Commons -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- Apache Sling -->
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.api</artifactId>
      <version>2.11.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.commons.messaging</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.models.api</artifactId>
      <version>1.2.2</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.query</artifactId>
      <version>3.0.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.jcr.base</artifactId>
      <version>2.3.2</version>
      <scope>provided</scope>
    </dependency>
    <!-- Apache Jackrabbit -->
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>jackrabbit-api</artifactId>
      <version>2.12.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- SubEtha SMTP -->
    <dependency>
      <groupId>org.subethamail</groupId>
      <artifactId>subethasmtp</artifactId>
      <version>3.1.7</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.sling</groupId>
          <artifactId>maven-sling-plugin</artifactId>
          <version>2.1.8</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Bundle-Activator>org.apache.sling.samples.fling.internal.Activator</Bundle-Activator>
            <Embed-Dependency>*;scope=compile;inline=true</Embed-Dependency>
            <Sling-Bundle-Resources>
              /fling/assets;path:=/assets
            </Sling-Bundle-Resources>
            <Sling-Initial-Content>
              apps/fling;path:=/apps/fling;overwrite:=true;uninstall:=true,
              content;path:=/content;overwrite:=true;uninstall:=true,
              i18n;path:=/etc/i18n/org.apache.sling.samples.fling;overwrite:=true;uninstall:=true
            </Sling-Initial-Content>
            <Sling-Model-Packages>
              org.apache.sling.samples.fling
            </Sling-Model-Packages>
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>launchpad@localhost</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.sling</groupId>
            <artifactId>maven-sling-plugin</artifactId>
            <executions>
              <execution>
                <phase>install</phase>
                <goals>
                  <goal>install</goal>
                </goals>
                <configuration>
                  <slingUrl>http://localhost:8080/system/console/install</slingUrl>
                  <user>admin</user>
                  <password>admin</password>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
    <profile>
      <id>karaf@localhost</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.sling</groupId>
            <artifactId>maven-sling-plugin</artifactId>
            <executions>
              <execution>
                <phase>install</phase>
                <goals>
                  <goal>install</goal>
                </goals>
                <configuration>
                  <slingUrl>http://localhost:8181/system/console/install</slingUrl>
                  <user>karaf</user>
                  <password>karaf</password>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
file(REMOVE_RECURSE
  "X86GenRegisterInfo.inc.tmp"
  "X86GenRegisterInfo.inc"
  "X86GenDisassemblerTables.inc.tmp"
  "X86GenDisassemblerTables.inc"
  "X86GenInstrInfo.inc.tmp"
  "X86GenInstrInfo.inc"
  "X86GenAsmWriter.inc.tmp"
  "X86GenAsmWriter.inc"
  "X86GenAsmWriter1.inc.tmp"
  "X86GenAsmWriter1.inc"
  "X86GenAsmMatcher.inc.tmp"
  "X86GenAsmMatcher.inc"
  "X86GenDAGISel.inc.tmp"
  "X86GenDAGISel.inc"
  "X86GenFastISel.inc.tmp"
  "X86GenFastISel.inc"
  "X86GenCallingConv.inc.tmp"
  "X86GenCallingConv.inc"
  "X86GenSubtargetInfo.inc.tmp"
  "X86GenSubtargetInfo.inc"
  "CMakeFiles/LLVMX86CodeGen.dir/X86AsmPrinter.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86CallFrameOptimization.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86FastISel.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86FloatingPoint.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86FrameLowering.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86ISelDAGToDAG.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86ISelLowering.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86InstrInfo.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86MCInstLower.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86MachineFunctionInfo.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86NaClRewritePass.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86PadShortFunction.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86RegisterInfo.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86SelectionDAGInfo.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86Subtarget.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86TargetMachine.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86TargetObjectFile.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86TargetTransformInfo.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86VZeroUpper.cpp.o"
  "CMakeFiles/LLVMX86CodeGen.dir/X86FixupLEAs.cpp.o"
  "../../libLLVMX86CodeGen.pdb"
  "../../libLLVMX86CodeGen.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/LLVMX86CodeGen.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Builder SDK GitHub:
// https://github.com/Microsoft/BotBuilder
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using Microsoft.Bot.Builder.Calling.ObjectModel.Misc;
using Newtonsoft.Json;

namespace Microsoft.Bot.Builder.Calling.ObjectModel.Contracts
{
    /// <summary>
    /// This is the outcome of the "record" action. This is conveyed to the customer as POST to the customer CallBack Url.
    /// </summary>
    [JsonObject(MemberSerialization.OptOut)]
    public class RecordOutcome : OperationOutcomeBase
    {
        /// <summary>
        /// Completion reason
        /// </summary>
        [JsonProperty(Required = Required.Always)]
        public RecordingCompletionReason CompletionReason { get; set; }

        /// <summary>
        /// If recording was successful, this indicates length of recorded audio
        /// </summary>
        [JsonProperty(Required = Required.Always)]
        public double LengthOfRecordingInSecs { get; set; }

        /// <summary>
        /// Media encoding format of the recording.
        /// </summary>
        [JsonProperty(Required = Required.Default)]
        public RecordingFormat Format { get; set; }

        public RecordOutcome()
        {
            this.Type = ValidOutcomes.RecordOutcome;
        }

        public override void Validate()
        {
            base.Validate();
            if (this.Outcome == Outcome.Success)
            {
                Utils.AssertArgument(this.LengthOfRecordingInSecs > 0,
                    "Recording Length must be specified for successful recording");
            }
            else
            {
                Utils.AssertArgument(this.LengthOfRecordingInSecs <= 0,
                    "Recording Length must not be specified for failed recording");
            }
        }
    }
}


text:
package com.haoxitech.canzhaopin.ui.activity;

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haoxitech.HaoConnect.HaoResult;
import com.haoxitech.HaoConnect.HaoResultHttpResponseHandler;
import com.haoxitech.HaoConnect.connects.UserConnect;
import com.haoxitech.HaoConnect.library.HaoQiNiu;
import com.haoxitech.HaoConnect.results.UserResult;
import com.haoxitech.canzhaopin.R;
import com.haoxitech.canzhaopin.app.AppContext;
import com.haoxitech.canzhaopin.base.BaseTitleActivity;
import com.haoxitech.canzhaopin.common.RequestCommon;
import com.haoxitech.canzhaopin.utils.mutiphotochooser.PhotoPreviewActivity;
import com.haoxitech.canzhaopin.view.CircleImageView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cz.msebera.android.httpclient.Header;

/**
 * Created by wangtao on 16/3/18.
 */
public class UserInfoActivity extends BaseTitleActivity {

    @InjectView(R.id.image_head)
    CircleImageView imageHead;
    @InjectView(R.id.arrow_right)
    ImageView arrowRight;
    @InjectView(R.id.text_name)
    TextView textName;
    @InjectView(R.id.text_birthday)
    TextView textBirthday;
    @InjectView(R.id.text_telephone)
    TextView textTelephone;
    @InjectView(R.id.text_num)
    TextView textNum;
    @InjectView(R.id.text_expect_job)
    TextView textExpectJob;
    @InjectView(R.id.text_expect_salary)
    TextView textExpectSalary;
    @InjectView(R.id.text_sex)
    TextView textSex;

    private int mYear;
    private int mMonth;
    private int mDay;

    private int yearStart;
    private int monthStart;
    private int dayStart;
    private boolean isShow = false;

    private PopupWindow popupWindow;
    @Override
    public int getContentViewID() {
        return R.layout.activity_user_info;
    }

    @Override
    public void initView() {
        super.initView();
        setTitle("个人信息");

        imageHead.setIsCircle(true);

        findViewById(R.id.layout_user_head).setOnClickListener(this);
        findViewById(R.id.layout_user_name).setOnClickListener(this);
        findViewById(R.id.layout_birthday).setOnClickListener(this);
        findViewById(R.id.layout_telephone).setOnClickListener(this);
        findViewById(R.id.layout_num).setOnClickListener(this);
        findViewById(R.id.layout_positin).setOnClickListener(this);
        findViewById(R.id.layout_salary).setOnClickListener(this);
        findViewById(R.id.layout_sex).setOnClickListener(this);

        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        Date mydate = new Date(); // 获取当前日期Date对象
        calendar.setTime(mydate);// //为Calendar对象设置时间为当前日期

        yearStart = calendar.get(Calendar.YEAR); // 获取Calendar对象中的年
        monthStart = calendar.get(Calendar.MONTH);// 获取Calendar对象中的月
        dayStart = calendar.get(Calendar.DAY_OF_MONTH);// 获取这个月的第几天

        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);

        loadData();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.layout_user_head: {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                1);
                        return;
                    }
                }

                Intent intent = new Intent(this, PhotoPreviewActivity.class);
                startActivityForResult(intent, RequestCommon.REQUEST_REGISTER_PHOTO_ID);
            }
            break;
            case R.id.layout_user_name: {
                Intent intent = new Intent(this, InfoEditActivity.class);
                intent.putExtra("hint", "请填写您的昵称(10字以内)");
                intent.putExtra("title", "昵称");
                intent.putExtra("ori", textName.getText());
                intent.putExtra("max", 10);
                startActivityForResult(intent, RequestCommon.REQUEST_EDIT_NICKNAME_ID);
            }
            break;
            case R.id.layout_sex: {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }

                View popView = LayoutInflater.from(this).inflate(R.layout.pop_sex_layout, null);

                popView.findViewById(R.id.sex_man_btn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                            popupWindow = null;
                            updateInfo("sex", "1");
                            textSex.setText("男");
                        }
                    }
                });
                popView.findViewById(R.id.sex_woman_btn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                            popupWindow = null;
                            updateInfo("sex", "2");
                            textSex.setText("女");
                        }
                    }
                });

                popView.findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                            popupWindow = null;
                        }
                    }
                });
                popupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT, true);
                popupWindow.setFocusable(true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());

                popupWindow.showAtLocation(findViewById(R.id.user_info_layout), Gravity.BOTTOM, 0, 0);
            }
                break;
            case R.id.layout_birthday: {
                isShow = false;
                onCreateDialog().show();
            }
            break;
            case R.id.layout_telephone: {
//                Intent intent = new Intent(this, InfoEditActivity.class);
//                intent.putExtra("hint", "请填写您的联系方式");
//                intent.putExtra("title", "联系方式");
//                intent.putExtra("ori", textTelephone.getText());
//                intent.putExtra("max", 10);
//                startActivityForResult(intent, RequestCommon.REQUEST_EDIT_NICKNAME_ID);
            }
            break;
            case R.id.layout_num: {

            }
            break;
            case R.id.layout_positin: {

            }
            break;
            case R.id.layout_salary: {

            }
            break;

        }
    }

    private void loadData() {
        UserConnect.requestGetMyDetail(null, new HaoResultHttpResponseHandler() {
            @Override
            public void onSuccess(HaoResult result) {
                if (result.isResultsOK()) {
                    UserResult userResult = (UserResult) result;
                    ImageLoader.getInstance().displayImage(userResult.findAvatar().toString(), imageHead);
                    textName.setText(userResult.findNickname().toString());
                    textTelephone.setText(userResult.findTelephone().toString());
                    textBirthday.setText(userResult.findBirthday().toString());

                    if (userResult.findAsInt("sex") == 1) {
                        textSex.setText("男");
                    } else if (userResult.findAsInt("sex") == 2) {
                        textSex.setText("女");
                    } else {
                        textSex.setText("未知");
                    }
                    textBirthday.setText(userResult.findAsString("birthday"));
                    String birthday = userResult.findAsString("birthday");
                    if (birthday.length() == 10) {
                        mYear = Integer.parseInt(birthday.substring(0, 4));
                        mMonth = Integer.parseInt(birthday.substring(5, 7)) - 1;
                        mDay = Integer.parseInt(birthday.substring(8, 10));
                    }
                }
            }

            @Override
            public void onFail(HaoResult result) {
                super.onFail(result);
                showToast(result.errorStr);
            }
        }, this);
    }

    private void updateInfo(String key, String infoValue) {

        progressDialog.startProgressDialog();
        params.clear();
        params.put(key, infoValue);
        params.put("id", AppContext.getInstance().getUserId());
        UserConnect.requestUpdate(params, new HaoResultHttpResponseHandler() {
            @Override
            public void onSuccess(HaoResult result) {
                if (result.isResultsOK()) {
                    showToast("更新完成");
                }
                progressDialog.stopProgressDialog();
            }

            @Override
            public void onFail(HaoResult result) {
                super.onFail(result);
                showToast(result.errorStr);
                progressDialog.stopProgressDialog();
            }
        }, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCommon.REQUEST_REGISTER_PHOTO_ID: {
                    ImageLoader.getInstance().displayImage("file://" + data.getStringExtra("imagePath"), imageHead);
                    HaoQiNiu.requestUploadToQiNiuWithFile(new File(data.getStringExtra("imagePath")), new JsonHttpResponseHandler() {
                        @Override
                        public void onStart() {
                            super.onStart();
                        }

                        @Override
                        public void onProgress(long bytesWritten, long totalSize) {
                            super.onProgress(bytesWritten, totalSize);
                        }

                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            super.onSuccess(statusCode, headers, response);
                            try {
                                String photo = response.get("urlPreview").toString();
                                if (photo != null) {
                                    updateInfo("avatar", photo);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                            super.onFailure(statusCode, headers, responseString, throwable);
                        }

                    }, this);
                }
                break;
                case RequestCommon.REQUEST_EDIT_NICKNAME_ID: {
                    textName.setText(data.getStringExtra("results"));
                    if (textName.length() > 0) {
                        updateInfo("nickname", textName.getText().toString());
                    }
                }
                break;

            }
        }
    }

    private Dialog onCreateDialog() {

        Dialog dialog = null;

        dialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {
                        if (!isShow) {
                            isShow = true;
                            if (year > yearStart) {
                                showToast("您的生日不能大于当前时间");
                                return;
                            } else if (year == yearStart
                                    && monthOfYear > monthStart) {
                                showToast("您的生日不能大于当前时间");
                                return;
                            } else if (year == yearStart
                                    && monthOfYear == monthStart
                                    && dayOfMonth > dayStart) {
                                showToast("您的生日不能大于当前时间");
                                return;
                            } else {
                                if (mYear != year || mMonth != monthOfYear || mDay != dayOfMonth) {
                                    mYear = year;
                                    mMonth = monthOfYear;
                                    mDay = dayOfMonth;
                                    // 更新日期
                                    updateDateDisplay();
                                }
                            }
                        }
                    }
                }, mYear, mMonth, mDay);
        dialog.setTitle("选择生日");

        return dialog;
    }

    /**
     *
     * 更新日期显示
     */
    private void updateDateDisplay() {
        StringBuilder buffer = new StringBuilder().append(mYear).append("-")
                .append((mMonth + 1) < 10 ? "0" + (mMonth + 1) : (mMonth + 1))
                .append("-").append((mDay < 10) ? "0" + mDay : mDay);
        textBirthday.setText(buffer.toString());
        updateInfo("birthday", "" + buffer);
    }
}


text:
#include <linux/slab.h>
#include <linux/firmware.h>
#include <linux/etherdevice.h>
#include <linux/module.h>

#include <net/mac80211.h>

#include "p54.h"
#include "lmac.h"

static bool modparam_nohwcrypt;
module_param_named(nohwcrypt, modparam_nohwcrypt, bool, S_IRUGO);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
MODULE_AUTHOR("Michael Wu <flamingice@sourmilk.net>");
MODULE_DESCRIPTION("Softmac Prism54 common code");
MODULE_LICENSE("GPL");
MODULE_ALIAS("prism54common");

static int p54_sta_add_remove(struct ieee80211_hw *hw,
			      struct ieee80211_vif *vif,
			      struct ieee80211_sta *sta)
{
	struct p54_common *priv = hw->priv;

	/*
	 * Notify the firmware that we don't want or we don't
	 * need to buffer frames for this station anymore.
	 */

	p54_sta_unlock(priv, sta->addr);

	return 0;
}

static void p54_sta_notify(struct ieee80211_hw *dev, struct ieee80211_vif *vif,
			      enum sta_notify_cmd notify_cmd,
			      struct ieee80211_sta *sta)
{
	struct p54_common *priv = dev->priv;

	switch (notify_cmd) {
	case STA_NOTIFY_AWAKE:
		/* update the firmware's filter table */
		p54_sta_unlock(priv, sta->addr);
		break;
	default:
		break;
	}
}

static int p54_set_tim(struct ieee80211_hw *dev, struct ieee80211_sta *sta,
			bool set)
{
	struct p54_common *priv = dev->priv;

	return p54_update_beacon_tim(priv, sta->aid, set);
}

u8 *p54_find_ie(struct sk_buff *skb, u8 ie)
{
	struct ieee80211_mgmt *mgmt = (void *)skb->data;
	u8 *pos, *end;

	if (skb->len <= sizeof(mgmt))
		return NULL;

	pos = (u8 *)mgmt->u.beacon.variable;
	end = skb->data + skb->len;
	while (pos < end) {
		if (pos + 2 + pos[1] > end)
			return NULL;

		if (pos[0] == ie)
			return pos;

		pos += 2 + pos[1];
	}
	return NULL;
}

static int p54_beacon_format_ie_tim(struct sk_buff *skb)
{
	/*
	 * the good excuse for this mess is ... the firmware.
	 * The dummy TIM MUST be at the end of the beacon frame,
	 * because it'll be overwritten!
	 */
	u8 *tim;
	u8 dtim_len;
	u8 dtim_period;
	u8 *next;

	tim = p54_find_ie(skb, WLAN_EID_TIM);
	if (!tim)
		return 0;

	dtim_len = tim[1];
	dtim_period = tim[3];
	next = tim + 2 + dtim_len;

	if (dtim_len < 3)
		return -EINVAL;

	memmove(tim, next, skb_tail_pointer(skb) - next);
	tim = skb_tail_pointer(skb) - (dtim_len + 2);

	/* add the dummy at the end */
	tim[0] = WLAN_EID_TIM;
	tim[1] = 3;
	tim[2] = 0;
	tim[3] = dtim_period;
	tim[4] = 0;

	if (dtim_len > 3)
		skb_trim(skb, skb->len - (dtim_len - 3));

	return 0;
}

static int p54_beacon_update(struct p54_common *priv,
			struct ieee80211_vif *vif)
{
	struct ieee80211_tx_control control = { };
	struct sk_buff *beacon;
	int ret;

	beacon = ieee80211_beacon_get(priv->hw, vif);
	if (!beacon)
		return -ENOMEM;
	ret = p54_beacon_format_ie_tim(beacon);
	if (ret)
		return ret;

	/*
	 * During operation, the firmware takes care of beaconing.
	 * The driver only needs to upload a new beacon template, once
	 * the template was changed by the stack or userspace.
	 *
	 * LMAC API 3.2.2 also specifies that the driver does not need
	 * to cancel the old beacon template by hand, instead the firmware
	 * will release the previous one through the feedback mechanism.
	 */
	p54_tx_80211(priv->hw, &control, beacon);
	priv->tsf_high32 = 0;
	priv->tsf_low32 = 0;

	return 0;
}

static int p54_start(struct ieee80211_hw *dev)
{
	struct p54_common *priv = dev->priv;
	int err;

	mutex_lock(&priv->conf_mutex);
	err = priv->open(dev);
	if (err)
		goto out;
	P54_SET_QUEUE(priv->qos_params[0], 0x0002, 0x0003, 0x0007, 47);
	P54_SET_QUEUE(priv->qos_params[1], 0x0002, 0x0007, 0x000f, 94);
	P54_SET_QUEUE(priv->qos_params[2], 0x0003, 0x000f, 0x03ff, 0);
	P54_SET_QUEUE(priv->qos_params[3], 0x0007, 0x000f, 0x03ff, 0);
	err = p54_set_edcf(priv);
	if (err)
		goto out;

	eth_broadcast_addr(priv->bssid);
	priv->mode = NL80211_IFTYPE_MONITOR;
	err = p54_setup_mac(priv);
	if (err) {
		priv->mode = NL80211_IFTYPE_UNSPECIFIED;
		goto out;
	}

	ieee80211_queue_delayed_work(dev, &priv->work, 0);

	priv->softled_state = 0;
	err = p54_set_leds(priv);

out:
	mutex_unlock(&priv->conf_mutex);
	return err;
}

static void p54_stop(struct ieee80211_hw *dev)
{
	struct p54_common *priv = dev->priv;
	int i;

	priv->mode = NL80211_IFTYPE_UNSPECIFIED;
	priv->softled_state = 0;
	cancel_delayed_work_sync(&priv->work);
	mutex_lock(&priv->conf_mutex);
	p54_set_leds(priv);
	priv->stop(dev);
	skb_queue_purge(&priv->tx_pending);
	skb_queue_purge(&priv->tx_queue);
	for (i = 0; i < P54_QUEUE_NUM; i++) {
		priv->tx_stats[i].count = 0;
		priv->tx_stats[i].len = 0;
	}

	priv->beacon_req_id = cpu_to_le32(0);
	priv->tsf_high32 = priv->tsf_low32 = 0;
	mutex_unlock(&priv->conf_mutex);
}

static int p54_add_interface(struct ieee80211_hw *dev,
			     struct ieee80211_vif *vif)
{
	struct p54_common *priv = dev->priv;
	int err;

	vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER;

	mutex_lock(&priv->conf_mutex);
	if (priv->mode != NL80211_IFTYPE_MONITOR) {
		mutex_unlock(&priv->conf_mutex);
		return -EOPNOTSUPP;
	}

	priv->vif = vif;

	switch (vif->type) {
	case NL80211_IFTYPE_STATION:
	case NL80211_IFTYPE_ADHOC:
	case NL80211_IFTYPE_AP:
	case NL80211_IFTYPE_MESH_POINT:
		priv->mode = vif->type;
		break;
	default:
		mutex_unlock(&priv->conf_mutex);
		return -EOPNOTSUPP;
	}

	memcpy(priv->mac_addr, vif->addr, ETH_ALEN);
	err = p54_setup_mac(priv);
	mutex_unlock(&priv->conf_mutex);
	return err;
}

static void p54_remove_interface(struct ieee80211_hw *dev,
				 struct ieee80211_vif *vif)
{
	struct p54_common *priv = dev->priv;

	mutex_lock(&priv->conf_mutex);
	priv->vif = NULL;

	/*
	 * LMAC API 3.2.2 states that any active beacon template must be
	 * canceled by the driver before attempting a mode transition.
	 */
	if (le32_to_cpu(priv->beacon_req_id) != 0) {
		p54_tx_cancel(priv, priv->beacon_req_id);
		wait_for_completion_interruptible_timeout(&priv->beacon_comp, HZ);
	}
	priv->mode = NL80211_IFTYPE_MONITOR;
	eth_zero_addr(priv->mac_addr);
	eth_zero_addr(priv->bssid);
	p54_setup_mac(priv);
	mutex_unlock(&priv->conf_mutex);
}

static int p54_wait_for_stats(struct ieee80211_hw *dev)
{
	struct p54_common *priv = dev->priv;
	int ret;

	priv->update_stats = true;
	ret = p54_fetch_statistics(priv);
	if (ret)
		return ret;

	ret = wait_for_completion_interruptible_timeout(&priv->stat_comp, HZ);
	if (ret == 0)
		return -ETIMEDOUT;

	return 0;
}

static void p54_reset_stats(struct p54_common *priv)
{
	struct ieee80211_channel *chan = priv->curchan;

	if (chan) {
		struct survey_info *info = &priv->survey[chan->hw_value];

		/* only reset channel statistics, don't touch .filled, etc. */
		info->time = 0;
		info->time_busy = 0;
		info->time_tx = 0;
	}

	priv->update_stats = true;
	priv->survey_raw.active = 0;
	priv->survey_raw.cca = 0;
	priv->survey_raw.tx = 0;
}

static int p54_config(struct ieee80211_hw *dev, u32 changed)
{
	int ret = 0;
	struct p54_common *priv = dev->priv;
	struct ieee80211_conf *conf = &dev->conf;

	mutex_lock(&priv->conf_mutex);
	if (changed & IEEE80211_CONF_CHANGE_POWER)
		priv->output_power = conf->power_level << 2;
	if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
		struct ieee80211_channel *oldchan;
		WARN_ON(p54_wait_for_stats(dev));
		oldchan = priv->curchan;
		priv->curchan = NULL;
		ret = p54_scan(priv, P54_SCAN_EXIT, 0);
		if (ret) {
			priv->curchan = oldchan;
			goto out;
		}
		/*
		 * TODO: Use the LM_SCAN_TRAP to determine the current
		 * operating channel.
		 */
		priv->curchan = priv->hw->conf.chandef.chan;
		p54_reset_stats(priv);
		WARN_ON(p54_fetch_statistics(priv));
	}
	if (changed & IEEE80211_CONF_CHANGE_PS) {
		WARN_ON(p54_wait_for_stats(dev));
		ret = p54_set_ps(priv);
		if (ret)
			goto out;
		WARN_ON(p54_wait_for_stats(dev));
	}
	if (changed & IEEE80211_CONF_CHANGE_IDLE) {
		WARN_ON(p54_wait_for_stats(dev));
		ret = p54_setup_mac(priv);
		if (ret)
			goto out;
		WARN_ON(p54_wait_for_stats(dev));
	}

out:
	mutex_unlock(&priv->conf_mutex);
	return ret;
}

static u64 p54_prepare_multicast(struct ieee80211_hw *dev,
				 struct netdev_hw_addr_list *mc_list)
{
	struct p54_common *priv = dev->priv;
	struct netdev_hw_addr *ha;
	int i;

	BUILD_BUG_ON(ARRAY_SIZE(priv->mc_maclist) !=
		ARRAY_SIZE(((struct p54_group_address_table *)NULL)->mac_list));
	/*
	 * The first entry is reserved for the global broadcast MAC.
	 * Otherwise the firmware will drop it and ARP will no longer work.
	 */
	i = 1;
	priv->mc_maclist_num = netdev_hw_addr_list_count(mc_list) + i;
	netdev_hw_addr_list_for_each(ha, mc_list) {
		memcpy(&priv->mc_maclist[i], ha->addr, ETH_ALEN);
		i++;
		if (i >= ARRAY_SIZE(priv->mc_maclist))
			break;
	}

	return 1; /* update */
}

static void p54_configure_filter(struct ieee80211_hw *dev,
				 unsigned int changed_flags,
				 unsigned int *total_flags,
				 u64 multicast)
{
	struct p54_common *priv = dev->priv;

	*total_flags &= FIF_ALLMULTI | FIF_OTHER_BSS;

	priv->filter_flags = *total_flags;

	if (changed_flags & FIF_OTHER_BSS)
		p54_setup_mac(priv);

	if (changed_flags & FIF_ALLMULTI || multicast)
		p54_set_groupfilter(priv);
}

static int p54_conf_tx(struct ieee80211_hw *dev,
		       struct ieee80211_vif *vif, u16 queue,
		       const struct ieee80211_tx_queue_params *params)
{
	struct p54_common *priv = dev->priv;
	int ret;

	mutex_lock(&priv->conf_mutex);
	if (queue < dev->queues) {
		P54_SET_QUEUE(priv->qos_params[queue], params->aifs,
			params->cw_min, params->cw_max, params->txop);
		ret = p54_set_edcf(priv);
	} else
		ret = -EINVAL;
	mutex_unlock(&priv->conf_mutex);
	return ret;
}

static void p54_work(struct work_struct *work)
{
	struct p54_common *priv = container_of(work, struct p54_common,
					       work.work);

	if (unlikely(priv->mode == NL80211_IFTYPE_UNSPECIFIED))
		return ;

	/*
	 * TODO: walk through tx_queue and do the following tasks
	 * 	1. initiate bursts.
	 *      2. cancel stuck frames / reset the device if necessary.
	 */

	mutex_lock(&priv->conf_mutex);
	WARN_ON_ONCE(p54_fetch_statistics(priv));
	mutex_unlock(&priv->conf_mutex);
}

static int p54_get_stats(struct ieee80211_hw *dev,
			 struct ieee80211_low_level_stats *stats)
{
	struct p54_common *priv = dev->priv;

	memcpy(stats, &priv->stats, sizeof(*stats));
	return 0;
}

static void p54_bss_info_changed(struct ieee80211_hw *dev,
				 struct ieee80211_vif *vif,
				 struct ieee80211_bss_conf *info,
				 u32 changed)
{
	struct p54_common *priv = dev->priv;

	mutex_lock(&priv->conf_mutex);
	if (changed & BSS_CHANGED_BSSID) {
		memcpy(priv->bssid, info->bssid, ETH_ALEN);
		p54_setup_mac(priv);
	}

	if (changed & BSS_CHANGED_BEACON) {
		p54_scan(priv, P54_SCAN_EXIT, 0);
		p54_setup_mac(priv);
		p54_beacon_update(priv, vif);
		p54_set_edcf(priv);
	}

	if (changed & (BSS_CHANGED_ERP_SLOT | BSS_CHANGED_BEACON)) {
		priv->use_short_slot = info->use_short_slot;
		p54_set_edcf(priv);
	}
	if (changed & BSS_CHANGED_BASIC_RATES) {
		if (dev->conf.chandef.chan->band == NL80211_BAND_5GHZ)
			priv->basic_rate_mask = (info->basic_rates << 4);
		else
			priv->basic_rate_mask = info->basic_rates;
		p54_setup_mac(priv);
		if (priv->fw_var >= 0x500)
			p54_scan(priv, P54_SCAN_EXIT, 0);
	}
	if (changed & BSS_CHANGED_ASSOC) {
		if (info->assoc) {
			priv->aid = info->aid;
			priv->wakeup_timer = info->beacon_int *
					     info->dtim_period * 5;
			p54_setup_mac(priv);
		} else {
			priv->wakeup_timer = 500;
			priv->aid = 0;
		}
	}

	mutex_unlock(&priv->conf_mutex);
}

static int p54_set_key(struct ieee80211_hw *dev, enum set_key_cmd cmd,
		       struct ieee80211_vif *vif, struct ieee80211_sta *sta,
		       struct ieee80211_key_conf *key)
{
	struct p54_common *priv = dev->priv;
	int slot, ret = 0;
	u8 algo = 0;
	u8 *addr = NULL;

	if (modparam_nohwcrypt)
		return -EOPNOTSUPP;

	if (key->flags & IEEE80211_KEY_FLAG_RX_MGMT) {
		/*
		 * Unfortunately most/all firmwares are trying to decrypt
		 * incoming management frames if a suitable key can be found.
		 * However, in doing so the data in these frames gets
		 * corrupted. So, we can't have firmware supported crypto
		 * offload in this case.
		 */
		return -EOPNOTSUPP;
	}

	mutex_lock(&priv->conf_mutex);
	if (cmd == SET_KEY) {
		switch (key->cipher) {
		case WLAN_CIPHER_SUITE_TKIP:
			if (!(priv->privacy_caps & (BR_DESC_PRIV_CAP_MICHAEL |
			      BR_DESC_PRIV_CAP_TKIP))) {
				ret = -EOPNOTSUPP;
				goto out_unlock;
			}
			key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
			algo = P54_CRYPTO_TKIPMICHAEL;
			break;
		case WLAN_CIPHER_SUITE_WEP40:
		case WLAN_CIPHER_SUITE_WEP104:
			if (!(priv->privacy_caps & BR_DESC_PRIV_CAP_WEP)) {
				ret = -EOPNOTSUPP;
				goto out_unlock;
			}
			key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
			algo = P54_CRYPTO_WEP;
			break;
		case WLAN_CIPHER_SUITE_CCMP:
			if (!(priv->privacy_caps & BR_DESC_PRIV_CAP_AESCCMP)) {
				ret = -EOPNOTSUPP;
				goto out_unlock;
			}
			key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
			algo = P54_CRYPTO_AESCCMP;
			break;
		default:
			ret = -EOPNOTSUPP;
			goto out_unlock;
		}
		slot = bitmap_find_free_region(priv->used_rxkeys,
					       priv->rx_keycache_size, 0);

		if (slot < 0) {
			/*
			 * The device supports the chosen algorithm, but the
			 * firmware does not provide enough key slots to store
			 * all of them.
			 * But encryption offload for outgoing frames is always
			 * possible, so we just pretend that the upload was
			 * successful and do the decryption in software.
			 */

			/* mark the key as invalid. */
			key->hw_key_idx = 0xff;
			goto out_unlock;
		}

		key->flags |= IEEE80211_KEY_FLAG_RESERVE_TAILROOM;
	} else {
		slot = key->hw_key_idx;

		if (slot == 0xff) {
			/* This key was not uploaded into the rx key cache. */

			goto out_unlock;
		}

		bitmap_release_region(priv->used_rxkeys, slot, 0);
		algo = 0;
	}

	if (sta)
		addr = sta->addr;

	ret = p54_upload_key(priv, algo, slot, key->keyidx,
			     key->keylen, addr, key->key);
	if (ret) {
		bitmap_release_region(priv->used_rxkeys, slot, 0);
		ret = -EOPNOTSUPP;
		goto out_unlock;
	}

	key->hw_key_idx = slot;

out_unlock:
	mutex_unlock(&priv->conf_mutex);
	return ret;
}

static int p54_get_survey(struct ieee80211_hw *dev, int idx,
				struct survey_info *survey)
{
	struct p54_common *priv = dev->priv;
	struct ieee80211_channel *chan;
	int err, tries;
	bool in_use = false;

	if (idx >= priv->chan_num)
		return -ENOENT;

#define MAX_TRIES 1
	for (tries = 0; tries < MAX_TRIES; tries++) {
		chan = priv->curchan;
		if (chan && chan->hw_value == idx) {
			mutex_lock(&priv->conf_mutex);
			err = p54_wait_for_stats(dev);
			mutex_unlock(&priv->conf_mutex);
			if (err)
				return err;

			in_use = true;
		}

		memcpy(survey, &priv->survey[idx], sizeof(*survey));

		if (in_use) {
			/* test if the reported statistics are valid. */
			if  (survey->time != 0) {
				survey->filled |= SURVEY_INFO_IN_USE;
			} else {
				/*
				 * hw/fw has not accumulated enough sample sets.
				 * Wait for 100ms, this ought to be enough to
				 * to get at least one non-null set of channel
				 * usage statistics.
				 */
				msleep(100);
				continue;
			}
		}
		return 0;
	}
	return -ETIMEDOUT;
#undef MAX_TRIES
}

static unsigned int p54_flush_count(struct p54_common *priv)
{
	unsigned int total = 0, i;

	BUILD_BUG_ON(P54_QUEUE_NUM > ARRAY_SIZE(priv->tx_stats));

	/*
	 * Because the firmware has the sole control over any frames
	 * in the P54_QUEUE_BEACON or P54_QUEUE_SCAN queues, they
	 * don't really count as pending or active.
	 */
	for (i = P54_QUEUE_MGMT; i < P54_QUEUE_NUM; i++)
		total += priv->tx_stats[i].len;
	return total;
}

static void p54_flush(struct ieee80211_hw *dev, struct ieee80211_vif *vif,
		      u32 queues, bool drop)
{
	struct p54_common *priv = dev->priv;
	unsigned int total, i;

	/*
	 * Currently, it wouldn't really matter if we wait for one second
	 * or 15 minutes. But once someone gets around and completes the
	 * TODOs [ancel stuck frames / reset device] in p54_work, it will
	 * suddenly make sense to wait that long.
	 */
	i = P54_STATISTICS_UPDATE * 2 / 20;

	/*
	 * In this case no locking is required because as we speak the
	 * queues have already been stopped and no new frames can sneak
	 * up from behind.
	 */
	while ((total = p54_flush_count(priv) && i--)) {
		/* waste time */
		msleep(20);
	}

	WARN(total, "tx flush timeout, unresponsive firmware");
}

static void p54_set_coverage_class(struct ieee80211_hw *dev,
				   s16 coverage_class)
{
	struct p54_common *priv = dev->priv;

	mutex_lock(&priv->conf_mutex);
	/* support all coverage class values as in 802.11-2007 Table 7-27 */
	priv->coverage_class = clamp_t(u8, coverage_class, 0, 31);
	p54_set_edcf(priv);
	mutex_unlock(&priv->conf_mutex);
}

static const struct ieee80211_ops p54_ops = {
	.tx			= p54_tx_80211,
	.start			= p54_start,
	.stop			= p54_stop,
	.add_interface		= p54_add_interface,
	.remove_interface	= p54_remove_interface,
	.set_tim		= p54_set_tim,
	.sta_notify		= p54_sta_notify,
	.sta_add		= p54_sta_add_remove,
	.sta_remove		= p54_sta_add_remove,
	.set_key		= p54_set_key,
	.config			= p54_config,
	.flush			= p54_flush,
	.bss_info_changed	= p54_bss_info_changed,
	.prepare_multicast	= p54_prepare_multicast,
	.configure_filter	= p54_configure_filter,
	.conf_tx		= p54_conf_tx,
	.get_stats		= p54_get_stats,
	.get_survey		= p54_get_survey,
	.set_coverage_class	= p54_set_coverage_class,
};

struct ieee80211_hw *p54_init_common(size_t priv_data_len)
{
	struct ieee80211_hw *dev;
	struct p54_common *priv;

	dev = ieee80211_alloc_hw(priv_data_len, &p54_ops);
	if (!dev)
		return NULL;

	priv = dev->priv;
	priv->hw = dev;
	priv->mode = NL80211_IFTYPE_UNSPECIFIED;
	priv->basic_rate_mask = 0x15f;
	spin_lock_init(&priv->tx_stats_lock);
	skb_queue_head_init(&priv->tx_queue);
	skb_queue_head_init(&priv->tx_pending);
	ieee80211_hw_set(dev, REPORTS_TX_ACK_STATUS);
	ieee80211_hw_set(dev, MFP_CAPABLE);
	ieee80211_hw_set(dev, PS_NULLFUNC_STACK);
	ieee80211_hw_set(dev, SUPPORTS_PS);
	ieee80211_hw_set(dev, RX_INCLUDES_FCS);
	ieee80211_hw_set(dev, SIGNAL_DBM);

	dev->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
				      BIT(NL80211_IFTYPE_ADHOC) |
				      BIT(NL80211_IFTYPE_AP) |
				      BIT(NL80211_IFTYPE_MESH_POINT);

	priv->beacon_req_id = cpu_to_le32(0);
	priv->tx_stats[P54_QUEUE_BEACON].limit = 1;
	priv->tx_stats[P54_QUEUE_FWSCAN].limit = 1;
	priv->tx_stats[P54_QUEUE_MGMT].limit = 3;
	priv->tx_stats[P54_QUEUE_CAB].limit = 3;
	priv->tx_stats[P54_QUEUE_DATA].limit = 5;
	dev->queues = 1;
	priv->noise = -94;
	/*
	 * We support at most 8 tries no matter which rate they're at,
	 * we cannot support max_rates * max_rate_tries as we set it
	 * here, but setting it correctly to 4/2 or so would limit us
	 * artificially if the RC algorithm wants just two rates, so
	 * let's say 4/7, we'll redistribute it at TX time, see the
	 * comments there.
	 */
	dev->max_rates = 4;
	dev->max_rate_tries = 7;
	dev->extra_tx_headroom = sizeof(struct p54_hdr) + 4 +
				 sizeof(struct p54_tx_data);

	/*
	 * For now, disable PS by default because it affects
	 * link stability significantly.
	 */
	dev->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;

	mutex_init(&priv->conf_mutex);
	mutex_init(&priv->eeprom_mutex);
	init_completion(&priv->stat_comp);
	init_completion(&priv->eeprom_comp);
	init_completion(&priv->beacon_comp);
	INIT_DELAYED_WORK(&priv->work, p54_work);

	eth_broadcast_addr(priv->mc_maclist[0]);
	priv->curchan = NULL;
	p54_reset_stats(priv);
	return dev;
}
EXPORT_SYMBOL_GPL(p54_init_common);

int p54_register_common(struct ieee80211_hw *dev, struct device *pdev)
{
	struct p54_common __maybe_unused *priv = dev->priv;
	int err;

	err = ieee80211_register_hw(dev);
	if (err) {
		dev_err(pdev, "Cannot register device (%d).\n", err);
		return err;
	}
	priv->registered = true;

#ifdef CONFIG_P54_LEDS
	err = p54_init_leds(priv);
	if (err) {
		p54_unregister_common(dev);
		return err;
	}
#endif /* CONFIG_P54_LEDS */

	dev_info(pdev, "is registered as '%s'\n", wiphy_name(dev->wiphy));
	return 0;
}
EXPORT_SYMBOL_GPL(p54_register_common);

void p54_free_common(struct ieee80211_hw *dev)
{
	struct p54_common *priv = dev->priv;
	unsigned int i;

	for (i = 0; i < NUM_NL80211_BANDS; i++)
		kfree(priv->band_table[i]);

	kfree(priv->iq_autocal);
	kfree(priv->output_limit);
	kfree(priv->curve_data);
	kfree(priv->rssi_db);
	kfree(priv->used_rxkeys);
	kfree(priv->survey);
	priv->iq_autocal = NULL;
	priv->output_limit = NULL;
	priv->curve_data = NULL;
	priv->rssi_db = NULL;
	priv->used_rxkeys = NULL;
	priv->survey = NULL;
	ieee80211_free_hw(dev);
}
EXPORT_SYMBOL_GPL(p54_free_common);

void p54_unregister_common(struct ieee80211_hw *dev)
{
	struct p54_common *priv = dev->priv;

#ifdef CONFIG_P54_LEDS
	p54_unregister_leds(priv);
#endif /* CONFIG_P54_LEDS */

	if (priv->registered) {
		priv->registered = false;
		ieee80211_unregister_hw(dev);
	}

	mutex_destroy(&priv->conf_mutex);
	mutex_destroy(&priv->eeprom_mutex);
}
EXPORT_SYMBOL_GPL(p54_unregister_common);